code:
from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length = 200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length = 200)
    votes = models.IntegerField(default = 0)
    def __str__(self):
        return self.choice_text

rawDescription: Model value won't change in admin area in Django


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from Tkinter import *
import Tkinter as tk
from tkFileDialog import askopenfilename
import time
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

#out
out = open("n_grams_outfile.txt", "w")
out.write("search string" + "\t" + "pub year" + "\t" + "frequency" + "\n")

#create a function that will return the filepath for a file provided by the user
user_defined_filepath = {}
def selectfile():
    user_defined_filepath['filename'] = askopenfilename(filetypes=[("Text","*.txt")]) # user_defined_filepath['filename'] may now be accessed in the global scope.

#create function we'll call when start button is pressed
def query_n_grams(event = "<Button>"):

    #create binary switch we'll use to only start new browser in first pass. Set default to true
    first_pass = 1

    #identify the input file
    inputfile = user_defined_filepath['filename']
    readinputfile = open(inputfile).read()
    stringinputfile = str(readinputfile)

    #assume input file = tsv. Left hand column = string of len <= 6; right hand column = pub year of text
    split_by_row = stringinputfile.split("\n")
    for row in split_by_row:

        #because the program will yelp if it reaches the end of the input file and then tries to split an empty line on "\t", wrap call in try/except
        try:
            search_terms = row.split("\t")[0]
            actual_pub_year = row.split("\t")[1]
        except IndexError:
            pass

        pub_year_minus_five = int(actual_pub_year) - 5
        pub_year_plus_five = int(actual_pub_year) + 5

        #you now have terms and pub yaer. Fire up webdriver and ride, cowboy
        if first_pass == 1:

            binary = FirefoxBinary('C:\Text\Professional\Digital Humanities\Programming Languages\Python\Query Literature Online\LION 3.0\Firefox Versions\Firefox23\FirefoxPortable.exe')
            driver = webdriver.Firefox(firefox_binary=binary)

            first_pass = 0

        #otherwise, use extant driver
        driver.implicitly_wait(10)
        driver.get("https://books.google.com/ngrams")
        driver.refresh()
        driver.implicitly_wait(10)

        #send keys
        driver.implicitly_wait(10)
        keyword = driver.find_element_by_class_name("query")
        driver.implicitly_wait(10)
        keyword.clear()
        driver.implicitly_wait(10)
        keyword.send_keys(str(search_terms))
        driver.implicitly_wait(10)

        #find start year
        driver.implicitly_wait(10)
        start_year = driver.find_element_by_name("year_start")
        driver.implicitly_wait(10)
        start_year.clear()
        driver.implicitly_wait(10)
        start_year.send_keys(str(pub_year_minus_five))
        driver.implicitly_wait(10)

        #find end year
        driver.implicitly_wait(10)
        end_year = driver.find_element_by_name("year_end")
        driver.implicitly_wait(10)
        end_year.clear()
        driver.implicitly_wait(10)
        end_year.send_keys(pub_year_plus_five)
        driver.implicitly_wait(10)

        #click enter
        driver.implicitly_wait(10)
        submit_button = driver.find_element_by_class_name("kd_submit")
        driver.implicitly_wait(10)
        submit_button.click()
        driver.implicitly_wait(10)

        #grab html
        driver.implicitly_wait(10)
        html = driver.page_source
        driver.implicitly_wait(10)

        #if you run a search that yields no hits, can't split the html, so use try/except
        try:

            #we want the list object that comes right after timeseries and before the comma
            desired_percent_figures = html.split('"timeseries": [')[1].split("]")[0]

            #now desired_percent_figures contains comma-separated list of percents (which we still need to convert out of mathematical notation). Convert out of mathematical notation (with e)
            percents_as_list = desired_percent_figures.split(",")

            #convert to ints
            percent_list_as_ints = [float(i) for i in percents_as_list]

            #take your list and find mean
            mean_percent = sum(percent_list_as_ints) / float(len(percent_list_as_ints))

            out.write(str(search_terms) + "\t" + str(actual_pub_year) + "\t" + str(mean_percent) + "\n")

        #you'll get IndexError if you run a query like "Hello Garrett" for which there are no entries in the database at all. (Other queries, like 'animal oeconomy' for year 1700, yields result 0, but because search string is in database elsewhere, won't throw IndexError)
        except IndexError:

            mean_percent = "0.0"

            #because we got an index error, we know that the search yielded no results. so let's type 0.0 as percent
            out.write(str(search_terms) + "\t" + str(actual_pub_year) + "\t" + str(mean_percent) + "\n")

#create TK frame
root = tk.Tk()
canvas = tk.Canvas(root, width=157, height=100)
canvas.pack()

#create label for tk
ngram_label = tk.Button(root, text = "Google N-Gram API", command = "", anchor = 'w', width = 14, activebackground = "#33B5E5")
ngram_label_canvas = canvas.create_window(20, 20, anchor='nw', width = 119, window=ngram_label)

#create a button that allows users to find a file for analysis
file_label = tk.Button(root, text = "Input file", command = selectfile, anchor = 'w', width = 7, activebackground = "#33B5E5")
file_label_canvas = canvas.create_window(20, 60, anchor='nw', window=file_label)

#create a start button that allows users to submit selected parameters and run the "startviewing" processes
start_label = tk.Button(root, text = "Go!", command = query_n_grams, anchor = 'w', width = 3, activebackground = "#33B5E5")
start_label_canvas = canvas.create_window(107, 60, anchor='nw', window=start_label)

root.mainloop()

rawDescription: Selenium Webdriver halting with [Errno 10054]


code:
with open('poem.txt') as poem_file:
    with open('poem-numbered.txt', 'w') as numbered_file:
        for index, line in enumerate(poem_file, 1):
            numbered_file.write('{}: {}'.format(index, line))

rawDescription: How to take a text file and create a copy but with numbered lines

description: Take a text file and create a copy but with numbered lines


code:
class UpperBase(Base):
    def __init__(self, name):
        if not name_valid(name):
            raise ValueError()
        super(UpperBase, self).__init__(name)

rawDescription: In python, super() is always called first in a method. Are there situations where it should be called later?


rawDescription: Paramiko hang when use ssh-keygen command


rawDescription: Randomly choose a number in a specific range with a specific multiple in python


code:
df = pd.DataFrame([[1,1],[1,-1],[2,1],[2,2]], columns=list('ab'))
print(df)
#    a  b
# 0  1  1
# 1  1 -1
# 2  2  1
# 3  2  2

data = df.groupby(['a'])
def replace(group):
    mask = group<0
    # Select those values where it is < 0, and replace
    # them with the mean of the values which are not < 0.
    group[mask] = group[~mask].mean()
    return group
print(data.transform(replace))
#    b
# 0  1
# 1  1
# 2  1
# 3  2

rawDescription: Replacing values with groupby means

description: Replacing values with groupby means


code:
greetings = open("x.txt", "r").readlines()
names = open("c.txt", "r").readlines()

with open("b.txt", "w") as output_file:
    for greeting, name in zip(greetings, names):
        greeting = greeting.split(" ")[0]
        output = "{0} {1}\n".format(greeting, name)
        output_file.write(output)

rawDescription: Python linking 2 strings

description: Python linking 2 strings


code:
final = pd.DataFrame()
final['team values'] = pdf['Year'].astype('str') + '_' + pdf['Wteam'].astype('str') + '_' + pdf['lteam'].astype('str')
final['predicted_value'] = 1

rawDescription: A complex transformation of a data set in pandas


code:
import pandas as pd
from collections import Counter
from itertools import product

df = pd.DataFrame({
    'Customer_ID': ['Alpha', 'Alpha', 'Alpha', 'Beta', 'Beta'],
    'Location_ID': ['A', 'B', 'C', 'A', 'B'],
    })

ctrs = {location: Counter(gp.Customer_ID) for location, gp in df.groupby('Location_ID')}

# In [7]: q.ctrs
# Out[7]:
# {'A': Counter({'Alpha': 1, 'Beta': 1}),
#  'B': Counter({'Alpha': 1, 'Beta': 1}),
#  'C': Counter({'Alpha': 1})}

ctrs = list(ctrs.items())
overlaps = [(loc1, loc2, sum(min(ctr1[k], ctr2[k]) for k in ctr1))
    for i, (loc1, ctr1) in enumerate(ctrs, start=1)
    for (loc2, ctr2) in ctrs[i:] if loc1 != loc2]
overlaps += [(l2, l1, c) for l1, l2, c in overlaps]

df2 = pd.DataFrame(overlaps, columns=['Loc1', 'Loc2', 'Count'])
df2 = df2.set_index(['Loc1', 'Loc2'])
df2 = df2.unstack().fillna(0).astype(int)

#      Count
# Loc2     A  B  C
# Loc1
# A        0  2  1
# B        2  0  1
# C        1  1  0

rawDescription: Creating a matrix from Pandas dataframe to display connectedness


rawDescription: How to silence statsmodels.fit() in python

description: Silence statsmodels.fit() in python


code:
import pprint, sys
from PyQt4 import QtCore, QtNetwork

app = QtCore.QCoreApplication(sys.argv)
request = QtNetwork.QNetworkRequest(QtCore.QUrl("http://stackoverflow.com"))
manager = QtNetwork.QNetworkAccessManager()
reply = manager.get(request)
while not reply.isFinished():
    app.processEvents()

try:
    # for Qt 4.7 and higher:
    pprint.pprint(reply.rawHeaderPairs())
except AttributeError:
    # for Qt < 4.7:
    for header in reply.rawHeaderList():
        pprint.pprint((header, reply.rawHeader(header)))

rawDescription: PyQt4: extract values from rawHeaderList


code:
comment_str = "None" if row["comment"] is None else "'{}'".format(row["comment"])
file.write("INSERT INTO SAMPLE_TABLE (int_value, string_value, comment)\n"
           "VALUES (%d, '%s', %s)\n\n"
           % (row["int_value"], row["string_value"], comment_str))

rawDescription: How to write a string that could be None to '%s' to a file (python)

description: Write a string that could be None to '%s' to a file (python)


code:
#add these lines to app.py
def prerender_jinja(text):
    prerendered_body = render_template_string(Markup(text))
    return pygmented_markdown(prerendered_body)

app.config['FLATPAGES_HTML_RENDERER'] = prerender_jinja

rawDescription: Mix images with Markdown in a Flask app

description: Mix images with Markdown in a Flask app


code:
address = Address(email='foo@bar.com', person_id=current_user.id)
db.session.add(address)
db.session.commit()

rawDescription: Do I need to create/update both models to insert a one-to-many in Flask?


code:
def get_list(prompt, halt):
    lst = []
    while True:
        item = raw_input(prompt)
        if item == halt:
            return lst
        else:
            lst.append(item)

def check_list(lst, item):
    if item in lst:
        print('Yay there is {} here'.format(item))
        return True
    else:
        print('No you have not added {}'.format(item))
        return False

def get_yesno(prompt):
    while True:
        yesno = raw_input(prompt).lower()
        if yesno in {'y', 'yes'}:
            return True
        elif yesno in {'n', 'no'}:
            return False

def main():
    mylist = get_list('Add to list:', 'q')

    check = raw_input('Look for item:')
    if not check_list(mylist, check):
        if get_yesno('Would you like to add it?'):
            mylist.append(check)

    print(mylist)

if __name__=="__main__":
    main()

rawDescription: Python Nested If

description: Python Nested If


code:
import enchant
import nltk

spell_dict = enchant.Dict('en_US')  # or whatever language supported

def get_distance_limit(w):
    '''
    The word is considered good
    if it's no further from a known word than this limit.
    '''
    return len(w)/5 + 2  # just for example, allowing around 1 typo per 5 chars.

def check_word(word):
    if spell_dict.check(word):
        return True  # a known dictionary word

    # try similar words
    max_dist = get_distance_limit(word)
    for suggestion in spell_dict.suggest(word):
        if nltk.edit_distance(suggestion, word) < max_dist:
            return True

    return False

rawDescription: identifying strings which cant be spelt in a list item

description: Identifying strings which cant be spelt in a list item


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

import psycopg2
import csv
#Connect to database
conn = psycopg2.connect(database="db_name",
    user="user", password="password", host="127.0.0.1", port="5432")
cur = conn.cursor()
#Get all cities ids and names with specific state
cur.execute("SELECT id, name from res_country_state_city WHERE state_id = 53")
rows = cur.fetchall()
rows_dict = {}
#Generate dict from data provided
for row in rows:
    rows_dict[row[1]] = row[0]
#Check which name from cities-names.csv match with name in database
#(match returns that cities id
with open('cities-names.csv') as csvfile:
    with open('cities-ids.csv', 'wb') as csvfile2:
        reader = csv.reader(csvfile)
        writer = csv.writer(csvfile2)
        #create ids csv file and write ids that were matched
        for row in reader:
            if rows_dict.get(row[0]):
                writer.writerow([rows_dict.get(row[0])])

conn.close()

rawDescription: Mapping rows ids with external csv file?

description: Mapping rows ids with external csv file


code:
s="(static string) name (different static string ) message (last static string)"
_,_,s=s.partition("(static string)")
name,_,s=s.partition("(different static string )")
message,_,s=s.partition("(last static string)")
name
message

rawDescription: Python name grabber

description: Python name grabber


code:
import psutil
somepid = 1023
p = psutil.Process(somepid)
p.suspend()
p.resume()

rawDescription: Pausing a process?

description: Pausing a process


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.widgets import Slider

vals = np.linspace(-np.pi,np.pi,100)
xgrid, ygrid = np.meshgrid(vals,vals)

def f(x, y, b):
    return np.sin(x * b)
b = 5

ax = plt.subplot(111)
plt.subplots_adjust(left=0.15, bottom=0.25)
fig = plt.imshow(f(xgrid, ygrid, b), cm.gray)
plt.axis('off')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)

axb = plt.axes([0.15, 0.1, 0.65, 0.03])
sb = Slider(axb, 'b', 0.1, 10.0, valinit=b)
def update(val):
    fig.set_data(f(xgrid, ygrid, val))
sb.on_changed(update)

plt.show()

rawDescription: How can I incorporate a slider into my plot to manipulate a variable?

description: Incorporate a slider into my plot to manipulate a variable


code:
(lambda x: x and 0 or 1)(True)
(lambda x: 0 if x else 1)(True)

rawDescription: Python Ternary Operator Comparison: `a if test else b` v.s. `test and a or b`


code:
with open(pickle_file) as f:
    unpickled = []
    while True:
        try:
            unpickled.append(pickle.load(f))
        except EOFError:
            break

rawDescription: How to get all pickled data

description: Get all pickled data


code:
DEFAULT_PADDR = '/dev/ttyUSB0'
# ...
paddr = DEFAULT_PADDR

rawDescription: python 'constants' and changing them

description: Python 'constants' and changing them


code:
hello = "Hello"
world = 'World'

hello_world = hello + " " + world

print(hello_world)

rawDescription: Contatenation and white space

description: Contatenation and white space


code:
import re
s = "look[+3],panel button layout[+3],feature[+2]it 's very sleek looking with a very good front panel button layout , and it has a great feature set . "
re.findall(r"(?:^|,)(.*?)\[\+?(\-?\d+)\]", s)
s = "darn diopter adjustment dial[-1]"
re.findall(r"(?:^|,)(.*?)\[\+?(\-?\d+)\]", s)

rawDescription: How to write regular expression to find multiple strings in Python

description: Write regular expression to find multiple strings in Python


code: a = dict.fromkeys(a, 0)

rawDescription: Simultaneously replacing all values of a dictionary to zero python


rawDescription: ctypes.windll.user32.GetCursorInfo() - how can I manage this to work? [Python]

description: Ctypes.windll.user32.GetCursorInfo() - how can I manage this to work? [Python]


code:
#!/usr/bin/env python
import copy, sys
from pyPdf import PdfFileWriter, PdfFileReader
input = PdfFileReader(sys.stdin)
output = PdfFileWriter()
for i in range(input.getNumPages()):
    p = input.getPage(i)
    q = copy.copy(p)

    bl = p.mediaBox.lowerLeft
    ur = p.mediaBox.upperRight

    print >> sys.stderr, 'splitting page',i
    print >> sys.stderr, '\tlowerLeft:',p.mediaBox.lowerLeft
    print >> sys.stderr, '\tupperRight:',p.mediaBox.upperRight

    p.mediaBox.upperRight = (ur[0], (bl[1]+ur[1])/2)
    p.mediaBox.lowerLeft = bl

    q.mediaBox.upperRight = ur
    q.mediaBox.lowerLeft = (bl[0], (bl[1]+ur[1])/2)
    if i%2==0:
        output.addPage(q)
        output.addPage(p)
    else:
        output.addPage(p)
        output.addPage(q)

output.write(sys.stdout)

rawDescription: Why my code not correctly split every page in a scanned pdf?


code:
import random
random.shuffle(array)

rawDescription: Shuffle an array with python, randomize array item order with python


code:
import re
re.findall(r"[\w']+|[.,!?;]", "Hello, I'm a string!")

rawDescription: Splitting a string into words and punctuation


code:
def module_exists(module_name):
    try:
        __import__(module_name)
    except ImportError:
        return False
    else:
        return True

rawDescription: How to check if python module exists and can be imported

description: Check if python module exists and can be imported


code:
argstr = ", ".join(arglist)
fakefunc = "def func(%s):\n    return real_func(%s)\n" % (argstr, argstr)
fakefunc_code = compile(fakefunc, "fakesource", "exec")
fakeglobals = {}
eval(fakefunc_code, {"real_func": f}, fakeglobals)
f_with_good_sig = fakeglobals["func"]

help(f)               # f(*args, **kwargs)
help(f_with_good_sig) # func(foo, bar, baz)

rawDescription: Set function signature in Python

description: Set function signature in Python


code: list_items = [ListItem(item=thing) for thing in list_of_things]

rawDescription: Making SQLAlchemy records from a list

description: Making SQLAlchemy records from a list


code: tree.write(filename, pretty_print=True)

rawDescription: inserting newlines in xml file generated via xml.etree.ElementTree in python

description: Inserting newlines in xml file generated via xml.etree.ElementTree in python


code:
class MyModel(db.Model):
  @classmethod
  def new(cls, **kwargs):
    return cls(key_name=str(uuid.uuid4()), **kwargs)

rawDescription: Automatic GUID key_name in model

description: Automatic GUID key_name in model


code:
if any(ext in url_string for ext in extensionsToCheck):
    print(url_string)

rawDescription: How to check if a string contains an element from a list in Python

description: Check if a string contains an element from a list in Python


code: foo = (x**2 for x in count())

rawDescription: Lazy map function in Python

description: Lazy map function in Python


code:
class Nationality:
        Poland='PL'
        Germany='DE'
        France='FR'

        def convertToCodeFromName(name):
                return getattr( Nationality, name )

        def convertToNameFromCode(code):
                lookFor = None

                for member in dir( Nationality ):
                        if ( getattr( Nationality, member ) == code ):
                                lookFor = member
                return lookFor

print( Nationality.convertToCodeFromName( "Poland" ) )
print( Nationality.convertToNameFromCode( "PL" ) )

rawDescription: Enum converter in python

description: Enum converter in python


rawDescription: Seaborn / Matplotlib: How to repress scientific notation in factorplot y-axis


code:
import urlparse
url = '/url?q=http://www.amazon.com/Quantitative-Trading-Build-Algorithmic-Business/dp/0470284889&sa=U&ei=P2ycT6OoNuasiAL2ncV5&ved=0CBIQFjAA&usg=AFQjCNEo_ujANAKnjheWDRlBKnJ1BGe'
data = urlparse.parse_qs(
    urlparse.urlparse(url).query
)
data
data['q'][0]

rawDescription: beautiful soup extract a href from google search

description: Beautiful soup extract a href from google search


rawDescription: Set axis marks in matplotlib

description: Set axis marks in matplotlib


rawDescription: sqlalchemy: distinct only on one column

description: Sqlalchemy: distinct only on one column


rawDescription: How to get all the values from a list that are smaller or equivalent to another list in python

description: Get all the values from a list that are smaller or equivalent to another list in python


code:
blueprint = Blueprint(
    self.blueprint_map[str(self.ui.blueprint_combo.currentText())],
    runs=self.ui.runs_spin.text(),
    me=self.ui.me_spin.text(),
    pe=self.ui.pe_skill_combo.currentIndex(),
)

rawDescription: How to break the following line of python

description: Break the following line of python


code:
import datetime
import pymongo
conn = pymongo.MongoClient()
db = conn.test #test is my database
col = db.bar #bar is my collection
col.find_one({"created_at": {"$gt" : datetime.datetime(2014, 9, 1), "$lt": datetime.datetime(2014, 12, 9)}})

rawDescription: Pymongo How to I extract the data

description: Pymongo How to I extract the data


code:
zip = 10010
zipcode = ZipCode.objects.get(number=zip)
Store.objects.filter(coordinates__in=zipcode)

rawDescription: geodjango - search by city, state or zip code

description: Geodjango - search by city, state or zip code


code:
quantile = 0.75  # 0.25, 0.5, 0.75, etc.
df[df.gt(df.quantile(q=quantile, axis=1), axis=0)].sum(axis=1)

rawDescription: sum of values larger than median of each row in pandas dataframes

description: Sum of values larger than median of each row in pandas dataframes


code:
from PIL import Image
import PIL.ImageOps
import glob

files = glob.glob('path/*.jpg') # Use *.* if you're sure all are images

for f in files:
  image = Image.open(f)
  inverted_image = PIL.ImageOps.invert(image)
  out = f[:f.rfind('.')]
  inverted_image.save('%s-n.png'%out)

rawDescription: Copy and process images in python

description: Copy and process images in python


code:
def __str__(self):
    return str(self.x)

rawDescription: Classes Python and developing Stack

description: Classes Python and developing Stack


rawDescription: Access to models with a foreign key in the template


code:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# ...

button.click()

wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#id-of-the-added-element")))

# now the page is "re-parsed"
print(driver.page_source)

rawDescription: Reparse Page Selenium Web Driver - Python


code:
df = pd.DataFrame({"A": [1,2,np.nan]}, index=[10,20,np.nan])
df
df.query("index == index or index != index")

rawDescription: query expressions that return the full dataframe

description: Query expressions that return the full dataframe


code:
fileName = QtGui.QFileDialog.getSaveFileName(None, 'Save File',
                                             '/path/to/your/file.ext')

rawDescription: Automatically provide save file name?

description: Automatically provide save file name


code:
import numpy as np
OLD = np.array([1,4,7,2,5,8,3,6,9])
OLD.reshape((3, 3), order='F')

rawDescription: rearrange the array elements using numpy in python

description: Rearrange the array elements using numpy in python


code: result = number[index - 1: index + 3]

rawDescription: Convert string to modified digit

description: Convert string to modified digit


rawDescription: Compare unicode to non-unicode strings (spanish)


code:
test = 'qwertyuiopasdfghjklzxcvbnm'

def changestring(string):
    for x in 'aeiou':
        string = string.replace(x, '*')
    return string

changestring(test)
'qw*rty***p*sdfghjklzxcvbnm'

rawDescription: Why can't I return the modified str_func function back to the main function?


code:
import wx
class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, title="test", size=(800,600))

        self.splitter = wx.SplitterWindow(self, wx.ID_ANY)
        self.panelOne = wx.Panel(self.splitter,1)
        self.panelTwo = wx.Panel(self.splitter,1)
        self.panelOne.SetBackgroundColour('sky blue')
        self.panelTwo.SetBackgroundColour('pink')
        self.splitter.SplitHorizontally(self.panelOne, self.panelTwo)
        self.splitter.SetMinimumPaneSize(20)

        self.buttonpanel = wx.Panel(self, 1)
        self.buttonpanel.SetBackgroundColour('white')
        self.mybutton = wx.Button(self.buttonpanel,label = "Hide")
        self.Bind(wx.EVT_BUTTON, self.show_hide, self.mybutton)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.splitter, 2, wx.EXPAND)
        self.sizer.Add(self.buttonpanel, 0, wx.EXPAND)
        self.SetSizer(self.sizer)

    def show_hide(self, event):
        label = self.mybutton.GetLabel()
        if label == "Hide":
            ### How to Hide panelOne ??
            self.mybutton.SetLabel("Show")
            self.splitter.Unsplit(self.panelOne)
        if label == "Show":
            ### How to Show panelOne ??
            self.splitter.SplitHorizontally(self.panelOne, self.panelTwo)
            self.mybutton.SetLabel("Hide")

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

rawDescription: wxpython: Hide one of splitterWindow panels

description: Wxpython: Hide one of splitterWindow panels


code:
from PIL import Image, ImageDraw, ImageFont

#open your original image, get it's width
img_src = Image.open('my_img.jpg')
xsize, ysize = img_src.size()

#create a new image that's just a little bit taller than the src image
img_text = Image.new("RGB",(xsize,yszize+30))

#paste the old image into the new one, flush at the top
img_text.paste(img_src,(0,0))

#Load font, draw to the bottom of the new image
#note that you must have the font file in your project
font = ImageFont.truetype("Arial.ttf", 16)
draw = ImageDraw.Draw(img_text)
draw.text((0, xsize),"Put your text here",(255,255,255),font=font)

img_text.save("appended_image.jpg")

rawDescription: How to add custom bottom to every image in Django

description: Add custom bottom to every image in Django


code:
class YourModelAdmin(admin.ModelAdmin):
    raw_id_fields=('professor', )

admin.site.register(YourModel, YourModelAdmin)

rawDescription: How to change a default widget in the Django admin?

description: Change a default widget in the Django admin


code:
ind = ~np.isnan(np.asarray(data.astype(float)))
plt.plot(np.asarray(x)[ind], np.asarray(data)[ind], 'ro--')

rawDescription: matplotlib not continuing lines after NaN's

description: Matplotlib not continuing lines after NaN's


code:
def function():
    for value in iter(lambda: input('would you like to restart?:'), '0'):
        pass # do your stuff here
    return None # or some meaningful result here

rawDescription: exit function if 0 is entered at any time for any variable

description: Exit function if 0 is entered at any time for any variable


code:
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'EMAIL ADDRESSES'
mail.Subject = 'Subject'
mail.HTMLbody = (r"""Hello All -

     Please find the following files in the shared drive:

     \\servername1\apps\folder

     The file names are:

     FILENAMES""")
mail.send

rawDescription: Python win32com Outlook HTMLbody formatting directory incorrectly


code:
x ={'1': [['a','b'],['ac','d']], '2' : [['p','qa'],['r','s']]}
for key in x:
    for n, item in enumerate(x[key]):
            x[key][n] = list(filter(lambda l: 'a' not in l, x[key][n]))
x

rawDescription: Change element of dictionary with values as list of lists


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

queryset.annotate(sum=Sum(Func(F('my_date'), function='UNIX_TIMESTAMP')))

rawDescription: How to write Django QuerySet to get UNIX_TIMESTAMP of a DateTimeField?

description: Write Django QuerySet to get UNIX_TIMESTAMP of a DateTimeField


code:
nrows, ncols = img.shape
sigma = (14 * nrows / 100.0, 14 * ncols / 100.0)
img = ndimage.gaussian_filter(img, sigma=sigma)

rawDescription: apply gaussian blur to an image ussing python

description: Apply gaussian blur to an image ussing python


code:
import time
time.mktime(time.strptime('02-12-2012', '%d-%m-%Y'))

rawDescription: Convert date to floating number since epoch


rawDescription: Python: Split a string, respect and preserve quotes


code:
message = """
          Hello, %(foo)s
          Sincerely, %(bar)s
          """ % {'foo': 'John', 'bar': "Doe"}

rawDescription: Python: format multitline strings with variables


code:
from django.core.exceptions import ValidationError

forbidden = {'login', 'logout'}

def not_forbidden(value):
    if value in forbidden:
        raise ValidationError(u'%s is not permitted as a username' % value)

username = models.CharField(max_length=14, blank=False, unique=True, validators=[
        validators.RegexValidator(r'^[^:;\'\"<>!@#$%|\^&\*\(\)~`,.?/=\-\+\\\{\}]? [\w]+$'),
        not_forbidden,
    ])

rawDescription: How to match a 'word' using regex in django/python

description: Match a 'word' using regex in django/python


code:
class ArtistRelationship(models.Model):
    from_artist = models.ForeignKey('Artist')
    to_artist = models.ForeignKey('Artist')

    def __unicode__(self):
        return u"%s - %s" % (self.from_artist.name, self.to_artist.name)

class Artist(models.Model):
    name = models.CharField(max_length=200)
    # ... more fields ...
    related_to = models.ManyToManyField("self", null=True, blank=True,
                                        through=ArtistRelationship)

rawDescription: Django : how to display actual objects in admin


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.send_keys("selenium")
elem.send_keys(Keys.RETURN)
assert "Google" in driver.title
driver.close()

rawDescription: How to simulate a AJAX call (XHR) with python and mechanize

description: Simulate a AJAX call (XHR) with python and mechanize


code:
import wx

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        super(MyFrame, self).__init__(*args, **kwargs)
        self.Bind(wx.EVT_ACTIVATE, self.on_focus)

    def on_focus(self, evt):
        self.Lower()

if __name__ == '__main__':
    app = wx.App(False)
    main_window = MyFrame(None)
    main_window.Show()
    app.MainLoop()

rawDescription: Keep window always on bottom

description: Keep window always on bottom


code:
import clr
clr.AddReference('System.Speech')
from System.Speech.Synthesis import SpeechSynthesizer

spk = SpeechSynthesizer()
spk.Speak('Hello world!')

rawDescription: C# scripting (python)

description: C# scripting (python)


code:
from django.db.models import Q
from itertools import combinations
# this -- the unicorn to be matched with
attr = ['horn_length', 'skin_color', 'average_speed', 'magical', 'affinity']
q = None
for c in combinations(attrs, 3):
    q_ = Q(**{c[0]: getattr(this, c[0])}) & Q(**{c[1]: getattr(this, c[1])}) & Q(**{c[2]: getattr(this, c[2])})
    if q is None:
        q = q_
    else:
        q = q | q_
Unicorn.objects.get(q)

rawDescription: Matching 3 out 5 fields - Django

description: Matching 3 out 5 fields - Django


code:
def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here":
    print("Annotations:", f.__annotations__)
    print("Arguments:", ham, eggs)
f('wonderful')

rawDescription: What do the colons in the following Python code do?


code:
from Project.items import SomeItem
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.selector import Selector
from selenium import webdriver
import time

class RandomSpider(CrawlSpider):

    name = 'RandomSpider'
    allowed_domains = ['random.com']
    start_urls = [
        'http://www.random.com'
    ]

    rules = (
        Rule(SgmlLinkExtractor(allow=('some_regex_here')), callback='parse_item', follow=True),
    )

    def __init__(self):
        CrawlSpider.__init__(self)
        # use any browser you wish
        self.browser = webdriver.Firefox()

    def __del__(self):
        self.browser.close()

    def parse_item(self, response):
        item = SomeItem()
        self.browser.get(response.url)
        # let JavaScript Load
        time.sleep(3)

        # scrape dynamically generated HTML
        hxs = Selector(text=self.browser.page_source)
        item['some_field'] = hxs.select('some_xpath')
        return item

rawDescription: Python Scrapy Dynamic Web Sites

description: Python Scrapy Dynamic Web Sites


code:
results_dict = {}
azimuthRoadsIDX = roadsLayer.fieldNameIndex('azimuth')
azimuthPathsIDX = pathsLayer.fieldNameIndex('azimuth')
for i, feat in enumerate(roadsLayer.getFeatures()):
    roadsAzimuth = feat.attributes()[azimuthRoadsIDX]
    results_dict[i] = ([], [])
    for feature in pathsLayer.getFeatures():
        pathsAzimuth = feature.attributes()[azimuthPathsIDX]
        difference = roadsAzimuth - pathsAzimuth
        if (-100 < difference < -80):
            results_dict[i][0].append(feature.id())
        if (260 < difference < 280):
            results_dict[i][0].append(feature.id())
        if (80 < difference < 100):
            results_dict[i][1].append(feature.id())
        if (-280 < difference < -260):
            results_dict[i][1].append(feature.id())

rawDescription: Python 2.7 for QGIS 2.6 : append to list if in range


code:
l = ['29382 this is something', '2938535 hello there', '392835 dont care for this', '22024811 yup']
[i.split(' ', 1)[0] for i in l]

rawDescription: Erasing everything from every element in a list except the first few numbers in those elements


code:
import pandas as pd
d_one = from_csv('data.csv',sep=',',engine='python',header=0)
d_two = from_csv('data2.csv',sep=',',engine='python',header=0)
d_three = pd.merge(d_one, d_two, left_on='timestamp',right_on='timestamp')
d_three.to_csv('output.csv',sep=',')

rawDescription: Merge csv Files with TimeStamps

description: Merge csv Files with TimeStamps


code:
from functools import wraps
def check_key(f):
    @wraps(f)
    def wrapper(self, request):
        try:
            key = request.META['HTTP_X_KEY']
        except KeyError:
            key = None
        if key and key == os.environ.get('KEY'):
            #Process the request
            f(self, request)
            return None
        #Redirect to Home Page
        return HttpResponsePermanentRedirect('http://google.com', status=301)
    return wrapper

class Checker(object):
   @check_key
   def process_request(self, request):
      ...

rawDescription: how do I write a middleware for tornado?

description: Write a middleware for tornado


code:
def distance(a, b):
    """
    Returns distance between `a` and `b`.
    `a` and `b` should have `x` and `y` attributes.
    """

    return math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2)

rawDescription: Pythonic way to add several methods to several classes?


code:
import threading
dummy_event = threading.Event()
dummy_event.wait()

rawDescription: Non blocking wait in python

description: Non blocking wait in python


rawDescription: run program in Python shell

description: Run program in Python shell


code: b = [set() for i in range(3)]

rawDescription: Initialize a python list with unique sets


code:
for sel in response.xpath('//div[@class="lower-col-right"]'):
    item = CouncilExtractorItem()
    item['title'] = sel.xpath('.//header[@class="intro user-content font-set clearfix"]/h1/text()').extract()
    item['link'] = sel.xpath('.//div[@class="user-content"]/section[@class="listing-item"]/a/@href').extract()
    item['desc'] = sel.xpath('.//div[@class="user-content"]/section[@class="listing-item"]/a/h2/text()').extract()
    item['date'] = sel.xpath('.//div[@class="user-content"]/section[@class="listing-item"]/span/text()').extract()
    # ...

rawDescription: Taking data from multiple links while storing in one item in Scrapy


code:
import sys

count = 0
with open("file-1.dat", "r") as f:
    sys.stdout = open('%s2 (converted).txt' % f.name, 'a')
    for line in f:
        converted_line = line.split()[:-3] #split each line and remove last 3 column
        if not converted_line: # if list/line is empty
            count += 1 #increase count but DO NOT PRINT/ WRITE TO FILE
        else:
            converted_line.insert(2,str(count)) # insert between 2nd and 3rd column
            print ('\t'.join(converted_line)) # join them and print them with tab delimiter

rawDescription: How to edit the *.txt or *.dat file information in Python?

description: Edit the *.txt or *.dat file information in Python


code:
import unittest
from flaskapp import app
from flask import session

class FlaskTestCase(unittest.TestCase):
    def testNumberIncrease(self):
        with app.test_client() as client:
            with client.session_transaction() as sess:
                # Modify the session in this context block.
                sess["last_num"] = "8"
            # Test the request in this context block.
            res = client.get("/increasenum")
            self.assertTrue(res is not None)

if __name__ == '__main__':
    unittest.main()

rawDescription: Can't Get Session Variables Set Up In Flask Unit Test


code:
import os

def append_data(filename, month, total, critical, high):
    vals = month, total, critical, high
    tmp_filename = filename + '.tmp'
    if os.path.exists(tmp_filename):
        os.remove(tmp_filename)
    with open(filename) as fin, open(tmp_filename, 'w') as fout:
         for val in vals:
             col = ',{}\n'.format(val)
             fout.write(next(fin)[:-1] + col)
    os.remove(filename)
    os.rename(tmp_filename, filename)

# test

with open('deleteme', 'w') as fp:
    fp.write("""Month,Jan,Feb
Total,70,80
Critical,20,30
High,50,50
""")

append_data('deleteme', 'Mar', 50, 20, 30)

print(open('deleteme').read())

rawDescription: Appending .csv's in Python

description: Appending .csv's in Python


code:
proc = subprocess.Popen(['python', testRunner.tsPyFile, test], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdoutValue = proc.communicate()[0]

rawDescription: Calling main() of another python script and getting STDOUT result


rawDescription: Python Regular Expressions - removing all characters passed a certain character


code:
def status(conn):
    status_map = {}
    response = conn.describe_db_instances()
    instances = response['DescribeDBInstancesResponse']['DescribeDBInstancesResult']['DBInstances']
    for instance in instances:
        status_map[instance['DBInstanceIdentifier']] = instance['Engine']
    return status_map

rawDescription: Not able to retrieve information about db instances from the describe_instance method using boto.rds2


code:
import sys

if len(sys.argv) == 2:
  print(sys.argv[1])
elif len(sys.argv) == 3:
  print(str(sys.argv[1]) + str(sys.argv[2]))
elif len(sys.argv) > 3:
  print("too many")

rawDescription: Python if-elif argv return

description: Python if-elif argv return


code:
import Image

img = Image.open('image.png').convert('RGBA')

r, g, b, a = img.split()

def invert(image):
    return image.point(lambda p: 255 - p)

r, g, b = map(invert, (r, g, b))

img2 = Image.merge(img.mode, (r, g, b, a))

img2.save('image2.png')

rawDescription: Python: invert image with transparent background (PIL, Gimp,...)


code:
z = sorted(zip(x,y))
x=[i[0] for i in z]
y=[i[1] for i in z]

rawDescription: pyplot, plotting from left to right

description: Pyplot, plotting from left to right


code:
def clear_cache(filename):
        if filename in pyglet.resource._default_loader._cached_images:
            del pyglet.resource._default_loader._cached_images[filename]

rawDescription: Clear pyglet resource cache

description: Clear pyglet resource cache


code:
from __future__ import print_function

import errno
import os

try:
    from itertools import zip_longest  # Python 3
except ImportError:  # Python 2
    from itertools import izip_longest as zip_longest  # Python 2

from PIL import Image

DEFAULT_IMAGE_EXTS = ('.jpg',)

# From the recipes section of the itertools documentation:
# https://docs.python.org/3/library/itertools.html#itertools-recipes
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

def makedirs(d):
    try:
        os.makedirs(d)
    except OSError as e:
        # If the file already exists, and is a directory
        if e.errno == errno.EEXIST and os.path.isdir(d):
            created = False
        # It's some other error, or the existing file is not a directory
        else:
            raise
    else:
        created = True

    return created

def get_valid_filenames(directory, extensions):
    for filename in os.listdir(directory):
        if filename.lower().endswith(extensions):
            yield filename

def get_corrupt_image_filenames(directory, extensions=DEFAULT_IMAGE_EXTS):
    for filename in get_valid_filenames(directory, extensions):
        image_path = os.path.join(directory, filename)
        try:
            with open(image_path, 'rb') as filehandle:
                Image.open(filehandle)
                # img = Image.open(filehandle)
                # img.load()  # I don't think this is needed, unless
                #               the corruption is not in the header.
        except IOError:
            yield filename

def confirm_it(directory, extensions, images_per_dir=5000):
    # Confirm selection and move files to new sub-directory
    if directory:
        for corrupt_file_name in get_corrupt_image_filenames(directory):
            os.remove(os.path.join(directory, corrupt_file_name))

        valid_images = get_valid_filenames(directory, extensions)
        grouped_image_file_names = grouper(valid_images, images_per_dir)
        for subdir, image_filenames in enumerate(grouped_image_file_names):
            for filename in image_filenames:
                from_path = os.path.join(directory, filename)
                to_dir = os.path.join(directory, str(subdir))
                to_path = os.path.join(to_dir, filename)

                makedirs(to_dir)

                os.rename(from_path, to_path)

def confirm_it_wrapper():
    confirm_it(directory=folderPath.get(), extensions=extensions)

rawDescription: Python deletion of files - "Currently being used by another process"


code:
class PossibleAnswerSerializer(serializers.ModelSerializer):
    companyId = serializers.Field(source='pollId.companyId')
    class Meta:
        model = PossibleAnswer
        fields = ('answerString', 'token', 'pollId', 'companyId')

rawDescription: django rest serialize level 2 field

description: Django rest serialize level 2 field


code:
variable_names = ('S1', 'S2', 'foo', 'bar')
values = {}

for name in variable_names:
    values[name] = input('Enter value for {}: '.format(name))

rawDescription: How can I display a Python input statement's variable name?

description: Display a Python input statement's variable name


code:
import kivy
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.spinner import Spinner
from bs4 import BeautifulSoup
from urllib import request
import sys, traceback
from functools import partial
import re
from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.image import Image
from kivy.properties import ObjectProperty

kv = '''
<IncidentScreen>:
    station: stationSpinner
    results: resultsLabel
    Image:
        source:'DSFRSLogo.png'
        allow_stretch:True
        pos_hint: {'center_x':0.5, 'y': .25}

    Spinner:
        id: stationSpinner
        text:'Select a Station'
        values: ('Appledore','Axminster','Bampton','Barnstaple','Bere Alston','Bideford','Bovey Tracey','Braunton','Bridgwater','Brixham','Buckfastleigh','Budleigh Salterton','Burnham on sea','Camels Head','Castle Cary','Chagford','Chard','Cheddar','Chulmleigh','Colyton','Combe Martin','Crediton','Crewkerne','Crownhill','Cullompton','Dartmouth','Dawlish','Exeter Danes Castle','Exeter Middlemoor','Exmouth','Frome','Glastonbury','Greenbank','Hartland','Hatherleigh','Holsworthy','Honiton','Ilfracombe','Ilminster','Ivybridge','Kingsbridge','Kingston','Lundy Island','Lynton','Martock','Minehead','Modbury','Moretonhampstead','Nether Stowey','Newton Abbot','North Tawton','Okehampton','Ottery St Mary','Paignton','Plympton','Plymstock','Porlock','Princetown','Salcombe','Seaton','Shepton Mallet','Sidmouth','Somerton','South Molton','Street','Taunton','Tavistock','Teignmouth','Tiverton','Topsham','Torquay','Torrington','Totnes','USAR','Wellington','Wells','Williton','Wincanton','Witheridge','Wiveliscombe','Woolacombe','Yelverton','Yeovil')
        size_hint: None, None
        size: (150, 44)
        pos_hint: {'center_x':0.5, 'y': 0.35}
        on_text: app.show_selected_value()

    Label:
        id: resultsLabel
        text:"Results will display here"
        color: [0,0,0,1]
        size_hint:(None, None)
        pos_hint:{'center_x':0.5, 'y': 0.25}
        size: (150, 44)

'''
class IncidentScreen(FloatLayout):
    station = ObjectProperty(None)
    results = ObjectProperty(None)

class DSFRSapp(App):

    def build(self):
        Builder.load_string(kv)
        fl = IncidentScreen()
        return fl

    def show_selected_value(self):
        incident = self.FindIncident(self.root.station.text)
        if incident:
            self.root.results.text = incident
        else:
            self.root.results.text = 'Try again later'

    def FindIncident(self, sStation, *args ):
        webpage = request.urlopen("http://www.dsfire.gov.uk/News/Newsdesk/IncidentsPast7days.cfm?siteCategoryId=3&T1ID=26&T2ID=35")#main page
        soup = BeautifulSoup(webpage)
        incidents = soup.find(id="CollapsiblePanel1") #gets todays incidents panel
        #create list call Links

        #get all hyperlinks: loads links into Links list while making them full links
        Links = [''.join(["http://www.dsfire.gov.uk/News/Newsdesk/",line.get('href')]) for line in incidents.find_all('a')]

        #loop through links to find station
        incident = ''
        for link in Links:
            print('Trying {}'.format(link))
            webpage = request.urlopen(link) #opens link in list)
            soup = BeautifulSoup(webpage) #loads webpage

            #check if returned value is found
            incident = soup.find_all('p', text=re.compile(r'{}'.format(sStation)))
            print(incident)
            break

        return incident

if __name__ =="__main__":
    DSFRSapp().run()

rawDescription: output text to a label from procedure

description: Output text to a label from procedure


code:
class AttributeReference:
    def __init__(self, obj, attr):
        self.obj = obj
        self.attr = attr

    def set(self, value):
        setattr(self.obj, self.attr, value)

    # add get() and del() and other methods to your heart's content

class ElementReference:
    def __init__(self, obj, key):
        self.obj = obj
        self.key = key

    def set(self, value):
        self.obj[self.key] = value

    # add get() and del() and other methods to your heart's content

rawDescription: Python: updating reference values

description: Python: updating reference values


code:
sentence = 'Python is a programming language'

[c for c in sentence if not c.isspace()]

rawDescription: How to turn a sentence into a list containing its letters?

description: Turn a sentence into a list containing its letters


code:
inner_qs = table2.objects.all()
results = table1.objects.exclude(field1__in=inner_qs)

rawDescription: Select values which not in another table with Django


code:
with open(yourfile) as f:
    rows = [l.split() for l in f]

names, firstnums, secondnums = zip(*rows)

rawDescription: Python 3: Extracting Data from a .txt File?


rawDescription: How can I display text AND variables in a tkinter text widget

description: Display text AND variables in a tkinter text widget


rawDescription: Access an item in ListProperty

description: Access an item in ListProperty


rawDescription: Failed to read netcdf file attribute, since the attribute name contains parentheses


code:
from openpyxl import Workbook

newRwa = Workbook()
ws1 = newRwa.active
for i in range(2,101):
    a = preqAS['A'+str(i)].value
    b = preqAS['B'+str(i)].value
    ws1.append([a, b])

newRa.save(filename='/Users/Ians/Desktop/newRwa.xlsx')

rawDescription: python : TypeError: 'str' object is not callable

description: Python : TypeError: 'str' object is not callable


code:
import subprocess

p = subprocess.Popen(["/bin/cat", "hello.txt"], stdout=subprocess.PIPE)

for line in p.stdout:
    print("PIPE OUT [%s]" % line)

rawDescription: Setting output of a program to pipe in Python 2.6.6


code:
def b1down(event):
    entry = Entry(root,bd=0,font=("Purisa",15)) #No Border and added font:)
    entry.place(x= event.x, y= event.y)
    entry.focus_force()

root = Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
drawing_area = Canvas(root)
drawing_area.grid(sticky=N+E+S+W)
drawing_area.bind("<ButtonPress-1>", b1down)
root.mainloop()

rawDescription: Create a textbox like in MS Paint in Python


code: elevation[elevation > 0] = numpy.NAN

rawDescription: Fast in-place replacement of some values in a numpy array


code:
from selenium import webdriver
wd = webdriver.Firefox()
wd.get("http://localhost/foo/bar")
wd.execute_script("return 5")
wd.execute_script("return true")
wd.execute_script("return {foo: 'bar'}")
wd.execute_script("return foobar()")

rawDescription: Getting the return value of Javascript code in Selenium


code:
def update_object_wrapper(request, object_id, *args, **kwargs):
    redirect_to = reverse('your object edit url name', object_id)
    return update_object(request, object_id, post_save_redirect=redirect_to, *args, **kwargs)

rawDescription: how to pass id from url to post_save_redirect in urls.py

description: Pass id from url to post_save_redirect in urls.py


code:
arglist = current_arg.split('+')
# This will create a list of Keyboard objects
keys = [KeyBoard(globals()["VK_%s" % key.upper()]) for key in  arglist]
# *keys splits the list of Keyboard objects so that SendInput receives
# one entry in it's argument list for each Keyboard object in keys
SendInput(*keys)

rawDescription: Is there a way to create/modify function on the fly in python


code:
def mealrating(score, review):
    mp = 0
    mg = 0
    me = 0

    for x in range(0,len(score)):
        if score[x] >= 1 and score[x] <= 3:
            review.append("poor")
            mp = mp + 1

        if score[x] >= 4 and score[x] <= 6:
            review.append("good")
            mg = mg + 1

        if score[x] >= 7 and score[x] <= 10:
            review.append("excellent")
            me = me + 1

    print("The customer rated tonight's meal as:")
    print('Poor:' + str(mp))
    print('Good:' + str(mg))
    print('Excellent:' + str(me))
    print("\n")

rawDescription: Counter doesn t seem to add properly

description: Counter doesn t seem to add properly


code: filename = url.rstrip().split('/')[-1]

rawDescription: Python urlretrieve saving files with ' \r\n ' after the file extension


code:
confirmation_message = _(
    'ORDER_CREATED: %(PROPERTY_1)s - '
    '%(PROPERTY_2)s - %(PROPERTY_3)s - %(PROPERTY_4)s') % {
        'PROPERTY_1': order.lorem,
        'PROPERTY_2': order.ipsum,
        'PROPERTY_3': order.ipsum,
        'PROPERTY_4': order.dolor,
        'PROPERTY_5': order.sit
    }

rawDescription: How to correctly break a long line in Python?

description: Correctly break a long line in Python


code:
from IPython.display import display
display(salaries.head())
display(teams.head())

rawDescription: IPython Notebook cell multiple outputs

description: IPython Notebook cell multiple outputs


code:
import json

def load_scores():
    with open("scores.json") as infile:
        return json.load(infile)

def save_scores(scores):
    with open("scores.json", "w") as outfile:
        json.dump(scores, outfile)

rawDescription: How can I save past high scores?

description: Save past high scores


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

df = pd.read_csv('t.txt', delim_whitespace=True, header=None, parse_dates={'Dates': [1, 2]})

plt.figure()
l_h = []
for identifier in df[0].unique():
    h, = plt.plot(df[df[0]==identifier]['Dates'], df[df[0]==identifier][3], label=identifier)
    l_h.append(h)
plt.legend(handles=l_h)
plt.show()

rawDescription: How can i plot line chart in python?

description: Plot line chart in python


code:
def findNode(start, name):
    return findNodeBy(start, lambda n: n.name == name)

rawDescription: Merge functions with 2 non-overlapping sets of parameters in a pythonic way


rawDescription: How do I make Matplotlib graph more spaced out?

description: Make Matplotlib graph more spaced out


code:
from django.core.management import call_command

call_command('es_sync_index')

rawDescription: How to do a manage.py command from within a file

description: Do a manage.py command from within a file


code:
class Event(models.Model):
        name = models.CharField(max_length=26)
        description = models.CharField(max_length=200)
        date = models.DateField()
        user = models.ManyToMany(User, related_name="events")
        image = models.ImageField(
            upload_to='images/',
            default='images/default.png'
        )

rawDescription: Count values in ManyToManyField - Django


code:
from scipy.sparse import csr_matrix
ll = [[0, 0, 1.0], [1, 2, 2.0], [4, 5, 3.0], [5, 5, 4.0], [5, 6, 5.0]]
rows, cols, vals = zip(*ll)
a = csr_matrix((vals, (rows, cols)))
a.A

rawDescription: Convert list of lists (with indexes) to csr matrix


code:
try:
    # Python 3.3 or later
    import unittest.mock as mock
except ImportError:
    # Make sure you install it first
    import mock

class TestFoo(unittest.TestCase):
    def setUp(self):
        self.f = Foo()

    def test_bar(self):
        with mock.patch.object(self.f, '_is_positive_number') as is_pos:
            self.f.bar(3)
            self.assertTrue(is_pos.called)

rawDescription: What is the canonical way to check if a function has been called in Python unittest without use of a mock?


code:
class Foo(object):
   a = 1
Foo.a

rawDescription: Python class instance __dict__ doesn't contain all instance variables. Why?


code: os.open(file, os.O_NONBLOCK | os.O_RDONLY)

rawDescription: If I open and read the file which is periodically written, can I/O deadlock occour?


code:
df1 = df.resample(rule='5Min',how='last',closed='left').reset_index().fillna(method='ffill')
df2 = df.resample(rule='5Min',how='first',closed='left').reset_index().fillna(method='ffill')

dt = df1.datetime - df2.datetime
px_fld = df1.price + ...

rawDescription: Pandas data frame: resample with linear interpolation


code:
def GetWithFile(self, client, servicename, modelthings):
    func = client.get_suds_func('Retrieve' + servicename)
    clientclass = func.clientclass({})
    SoapClient = clientclass(func.client, func.method)
    binding = func.method.binding.input
    soap_xml = binding.get_message(func.method, [modelthings], {})

    soap_xml.children[0].children[1].children[0].attributes.append(u'attachmentInfo="true"')
    soap_xml.children[0].children[1].children[0].attributes.append(u'attachmentData="true"')
    soap_xml.children[0].children[1].children[0].attributes.append(u'ignoreEmptyElements="true"')

    SoapClient.last_sent(soap_xml)
    plugins = PluginContainer(SoapClient.options.plugins)
    plugins.message.marshalled(envelope=soap_xml.root())
    if SoapClient.options.prettyxml:
        soap_xml = soap_xml.str()
    else:
        soap_xml = soap_xml.plain()
    soap_xml = soap_xml.encode('utf-8')
    plugins.message.sending(envelope=soap_xml)
    request = Request(SoapClient.location(), soap_xml)
    request.headers = SoapClient.headers()
    reply = SoapClient.options.transport.send(request)
    print(reply)

    Files = []
    boundary = self.find_substring(reply.headers['content-type'], 'boundary="', '"')
    if boundary is not "":
        list_of_data = reply.message.split(boundary)
        list_of_data.pop(0)
        list_of_data.pop(len(list_of_data) - 1)
        soap_body = '<SOAP-ENV:Envelope' + self.find_substring(list_of_data[0], '<SOAP-ENV:Envelope', '</SOAP-ENV:Envelope>') + '</SOAP-ENV:Envelope>'

        for line in list_of_data[1:]:
            File = SMFile()
            Files.append(File)
            File.filename = self.find_substring(line, 'Content-Location: ', '\r\n')
            File.key = self.find_substring(line, 'Content-ID: ', '\r\n')

            idx = line.index( 'Content-ID:' )
            start_idx = line.index( '\r\n\r\n' , idx ) + len('\r\n\r\n')
            fin_idx = line.rindex( '\r\n--', start_idx )
            File.body = line[start_idx: fin_idx]
            File.size = fin_idx - start_idx
    else:
        soap_body = '<SOAP-ENV:Envelope' + self.find_substring(reply.message, '<SOAP-ENV:Envelope', '</SOAP-ENV:Envelope>') + '</SOAP-ENV:Envelope>'

    ctx = plugins.message.received(reply=soap_body)
    soap_body = ctx.reply
    if SoapClient.options.retxml:
        answer = soap_body
    else:
        answer = SoapClient.succeeded(binding, soap_body)

    dict = {}
    self.FieldsToDict(answer.model.instance, dict)

    return {u'body': answer, u'Files': Files}

rawDescription: Get SOAP attachment

description: Get SOAP attachment


code:
self.buttons = {}
for i, operation in enumerate(['/','*','-','+']):
    self.buttons[operation] = tk.Button(self, text = operation,
                                        width = 4, command = lambda: self.process(operation))
    self.buttons[operation].grid(row = i+2, column = 3)

rawDescription: Making the creation of multiple widgets less repetitive


code:
equal_or_none = lambda x, y: x is None or x == y
if (
        equal_or_none(instanceType, instance_type)
        and equal_or_none(operatingSystem, operating_system)
        and equal_or_none(tenancy, tenancy_db)):
    sku_list.append(key)

rawDescription: How to handle if statement along with and operator in python?

description: Handle if statement along with and operator in python


code:
from flask import send_from_directory

@app.route('/pdf/myfile')
def pdf():
    return send_from_directory('/dir/of/pdf', 'my.pdf')

rawDescription: python - send pdf as bytes in web services

description: Python - send pdf as bytes in web services


code:
import json
instr = '{"id":13021,"buys":{"quantity":3494,"unit_price":257},"sells":{"quantity":3187,"unit_price":433}}'

injs = json.loads(instr)

injs["buys"]
Out[62]: {'quantity': 3494, 'unit_price': 257}

rawDescription: Extract pre-formatted data from a String


code:
import collections, operator
words = collections.Counter(map(operator.itemgetter(1), data))
populars = [p for p in data if words[p[1]] >= 3]

rawDescription: Count frequency of words in lists and remove unpopular words


code:
import serial
ser = serial.Serial('/dev/cu.usbmodem1421', 9600); # timeout after a second

while ser.isOpen():
    try:
        ser.write(b'5');
        while not ser.inWaiting():  # wait till something's received
            pass
        print(str(ser.read(), encoding='ascii'))  #decode and print
    except KeyboardInterrupt:  # close the port with ctrl+c
        ser.close()

rawDescription: Arduino Serial programming issue

description: Arduino Serial programming issue


code:
from collections import OrderedDict

annotations = [OrderedDict([('ID', i + 1),     # need to initialize with a list of tuples
                            ('NAME', 'Tag Name'),   # to preserve the order of the items
                            ('CONTENT', 'Note Content: This space will have a lot of text'),
                            ('URL', 'ref address'),
                            ('URL Info', 'url info')])
               for i in range(10)]

for i, dct in enumerate(annotations):
    print("Annotation #{}".format(i+1))
    for key, value in dct.items():
        print("{}: {}".format(key, value))
    print()

rawDescription: reaching values in dictionary inside dictionary python 2.7

description: Reaching values in dictionary inside dictionary python 2.7


code:
class CustomFormatter(argparse.HelpFormatter):
    def _format_action_invocation(self, action):
        if not action.option_strings:
            metavar, = self._metavar_formatter(action, action.dest)(1)
            return metavar
        else:
            parts = []
            # if the Optional doesn't take a value, format is:
            #    -s, --long
            if action.nargs == 0:
                parts.extend(action.option_strings)

            # if the Optional takes a value, format is:
            #    -s ARGS, --long ARGS
            # change to
            #    -s, --long ARGS
            else:
                default = action.dest.upper()
                args_string = self._format_args(action, default)
                for option_string in action.option_strings:
                    #parts.append('%s %s' % (option_string, args_string))
                    parts.append('%s' % option_string)
                parts[-1] += ' %s'%args_string
            return ', '.join(parts)

rawDescription: python argparse help message, disable metavar for short options?

description: Python argparse help message, disable metavar for short options


code:
self.ematrix = [ [ Entry(self.top) for j in range(6)]  # columns
                                   for i in range(30)] # rows

for i,row in enumerate(self.ematrix):
    for j,elt in enumerate(row):
        elt.grid(row=i,column=j)

rawDescription: Iterating variables to change its features in Python


code:
myvar="ID,Name\n1001,Tania\n1002,Geraldina"
with open("myvar.csv", "w") as w:
    w.write(str(myvar))

rawDescription: CSV'ify a variable

description: CSV'ify a variable


code:
from string import Template
s = Template('$who likes $what')
s.substitute(who='tim', what='kung pao')

rawDescription: How do I parse a file and substitute the environment variables with values in Python

description: Parse a file and substitute the environment variables with values in Python


code:
# -*- coding: utf-8 -*-

from distutils.core import setup
import py2exe, sys, os
import easygui

manifest = '''
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
       <asmv3:trustInfo xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
         <asmv3:security>
           <asmv3:requestedPrivileges>
             <asmv3:requestedExecutionLevel
               level="requireAdministrator"
               uiAccess="false" />
           </asmv3:requestedPrivileges>
         </asmv3:security>
       </asmv3:trustInfo>
     </assembly>
'''

file = easygui.fileopenbox("Script")

sys.argv.append('py2exe')
setup(
    options = {'py2exe': {'includes': "sip, PyQt5.QtNetwork, PyQt5.QtWebKit, PyQt5.QtPrintSupport", 'compressed': True}},
    windows = [{'script': file,
                "icon_resources": [(1, "[Icon]")],
                'other_resources':[(24, 1, manifest)]}],
    data_files = [('platforms', [
        'C:/Python34/Lib/site-packages/PyQt5/plugins/platforms/qwindows.dll'
        ])],
)

rawDescription: win32com opens 2 processes

description: Win32com opens 2 processes


code:
import xmlrpclib
from django.db.models.signals import post_save
from app.models import MyModel

def ping_handler(sender, instance=None, **kwargs):
    if instance is None:
        return
    rpc = xmlrpclib.Server('http://ping.feedburner.google.com/')
    rpc.weblogUpdates.ping(instance.title, instance.get_absolute_url())

post_save.connect(ping_handler, sender=MyModel)

rawDescription: Ping FeedBurner in Django App

description: Ping FeedBurner in Django App


code:
sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()

rawDescription: Write over line in console in python

description: Write over line in console in python


code:
lst = [['gene_id', 'EFNB2'], ['Gene_type', 'cDNA_supported'], ['transcript_id', 'EFNB2.aAug10'], ['product_id', 'EFNB2.aAug10']]
dict(lst)

rawDescription: List of List to Key-Value Pairs

description: List of List to Key-Value Pairs


code: map(dict(bar).get, foo)

rawDescription: Map value from list of tuples to another list


code:
for qid in qids:
    date = db[collection].find_one({ "querySummary.qid": qid }, {"querySummary.date":1})["querySummary"]["date"].isoformat()
    cursor = db[collection].find({ "querySummary.qid": qid })
    cols = ["resultNum", "col2", "col3", "col4"] # list of columns labels
    rows = [] # will be populated below

    for result in cursor:
        rows.append([result["resultNum"], result["col2"], result["col3"], result["col4"]])
    df = pd.DataFrame(rows, columns=cols);
    scatter_matrix(df, alpha=0.3, figsize=(16,16), diagonal='kde', marker='o')

    plt.suptitle(date)

rawDescription: How to put a title on each scatter_matrix in jupyter + pandas

description: Put a title on each scatter_matrix in jupyter + pandas


code:
def get_or_increase_tag(tag_name):
    tag = session.query(Tag).filter_by(tag=tag_name).first()
    if not tag:
       tag = Tag(tag_name)
    else:
       tag.cnt += 1
    return tag

rawDescription: SQLAlchemy update if unique key exists

description: SQLAlchemy update if unique key exists


code:
from struct import pack,unpack
fs = pack('f',1.0)               # pack float ('f') into binary string
fs
bval = list( unpack('BBBB', fs)) # use list() so mutable list
bval
bval[1]=12                # mutate it (byte in middle of mantissa bits)
fs = pack('BBBB', *bval)  # back to a binary string after mutation
fs
fnew=unpack('f',fs)  # and let's look at that slightly altered float value
fnew                 # NB it is a tuple of values, just one in this case

rawDescription: Python: flip a bit in a float

description: Python: flip a bit in a float


code:
import sys
sys.getsizeof(s)

# getsizeof(object, default) -> int
# Return the size of object in bytes.

rawDescription: How many bytes does a string have

description: How many bytes does a string have


code:
columns = [[1,2,3],[1,4,5],[6,4,2]]
colors = ['green', 'pink', 'blue']
labels = ['foo', 'bar', 'baz']

fig, ax = plt.subplots(1, 1)
for i, column in enumerate(columns):
    ax.plot(column, color=colors[i], label=labels[i])
ax.legend(loc='lower center', bbox_to_anchor=(0.82, 1),
          fancybox=True, shadow=True, ncol=3)

rawDescription: How to change the line colour for different lines in a subplot

description: Change the line colour for different lines in a subplot


rawDescription: Accessing list element without for loop

description: Accessing list element without for loop


code:
import random

with open('testfile.txt') as f:
    lines = f.readlines()
    print(random.choice(lines))  # prints a random line from testfile.txt

rawDescription: Homework help: Reading specific random lines of a text file


code:
from pyspark.sql.types import BooleanType
from pyspark.sql.functions import udf

point_inside_polygon_ = udf(point_inside_polygon, BooleanType())
df1 = df.where(point_inside_polygon(latitide,longitude,polygonArr))

rawDescription: UDF in pyspark SQL Context sending data as columns


rawDescription: Webbrowser module in cgi python

description: Webbrowser module in cgi python


code:
import itertools

names = "mains_voltage mains_time CT_voltage CT_time".split()
answer = {name:L for name,L in itertools.izip(names, lists)}

rawDescription: How can I convert a list of lists into a dictionary of lists in Python?

description: Convert a list of lists into a dictionary of lists in Python


code:
if not link.find_one({"domain": "example.co.uk", "good.link": "/url-1"}):
    link.update_one({"domain": "example.co.uk"},
                    {"$push": {"good": {"crawled": False, 'link':"/url-1"}}})

rawDescription: Update document if value there is no match


code:
df[['age', 'name', 'interest']].groupby(['age' , 'name']).size()
df[['age', 'name', 'interest']].groupby(['age' , 'name']).size().reset_index(name='count')

rawDescription: Pandas data frame sum of column and collecting the results


rawDescription: Match first instance of digit by Regex in python


rawDescription: Printing multiple blank lines in python

description: Printing multiple blank lines in python


rawDescription: Define a Function to Lookup IDs from a List in a Dictionary and Sum the Values


code:
import turtle
t = turtle.Pen()
t.left(90)
for x in range(180):
    t.forward(1)
    t.right(1)
t.right(90)
t.forward(118)

rawDescription: How to draw a semi circle in python turtle only

description: Draw a semi circle in python turtle only


code:
for i in range(0, len(self.info)):
    tempdic = dict()

rawDescription: How to append dict to a list in a loop

description: Append dict to a list in a loop


code:
from random import randint

def rn():
    return randint(1,49)

with open('Output.txt', 'w') as f:
    f.write("Random numbers are: \n")
    for _ in xrange(10):
        s = sorted(rn() for _ in xrange(6))
        f.write("{},{},{},{},{},{}\n".format(*s))

rawDescription: sorted function takes 4 arguments?

description: Sorted function takes 4 arguments


code:
def get_params(packagename):
    module = __import__('alpha.%s' % packagename)
    return module.__dict__['REQUIRED_PARAMS']

rawDescription: Getting attributes of a Python package that I don't have the name of, until runtime


rawDescription: Pandas Convert 'NA' to NaN

description: Pandas Convert 'NA' to NaN


code: arr.shape += (1,) * (4 - arr.ndim)

rawDescription: How to return an array of at least 4D: efficient method to simulate numpy.atleast_4d

description: Return an array of at least 4D: efficient method to simulate numpy.atleast_4d


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

time, x, p, q, r = np.random.random((5, 50))

fig, axes = plt.subplots(ncols=3)
for ax, y in zip(axes.flat, [p, q, r]):
    # "s=150" indicates a markersize of 15 points (blame matlab)
    scat = ax.scatter(x, y, c=time, s=150, cmap='jet')
fig.colorbar(scat)

plt.show()

rawDescription: Adding a colorbar to python subplots where color of datapoint depends on a third variable not plotted


code:
def readDataPts(filename):
    listPts = []
    with open(filename, 'r') as f:
        for line in f:
            numbers = line.split()
            if len(numbers) == 2:
                listPts.append(map(int, numbers))
    return listPts

rawDescription: writing a file to a list of tuples

description: Writing a file to a list of tuples


code:
mystops = HashSet(Arrays.asList(['a','b','c']))
result = StopFilter(True, result, mystops)

rawDescription: Custom stopwords for PyLucene

description: Custom stopwords for PyLucene


code:
maxlen = len(max(l, key=len))
maxlist = [s for s in l if len(s) == maxlen]

rawDescription: Find all the strings with max length using max() function


code:
import Image
import ImageDraw
import numpy

def transformblit(src_tri, dst_tri, src_img, dst_img):
    ((x11,x12), (x21,x22), (x31,x32)) = src_tri
    ((y11,y12), (y21,y22), (y31,y32)) = dst_tri

    M = numpy.array([
                     [y11, y12, 1, 0, 0, 0],
                     [y21, y22, 1, 0, 0, 0],
                     [y31, y32, 1, 0, 0, 0],
                     [0, 0, 0, y11, y12, 1],
                     [0, 0, 0, y21, y22, 1],
                     [0, 0, 0, y31, y32, 1]
                ])

    y = numpy.array([x11, x21, x31, x12, x22, x32])

    A = numpy.linalg.solve(M, y)

    src_copy = src_img.copy()
    srcdraw = ImageDraw.Draw(src_copy)
    srcdraw.polygon(src_tri)
    src_copy.show()
    transformed = src_img.transform(dst_img.size, Image.AFFINE, A)

    mask = Image.new('1', dst_img.size)
    maskdraw = ImageDraw.Draw(mask)
    maskdraw.polygon(dst_tri, fill=255)

    dstdraw = ImageDraw.Draw(dst_img)
    dstdraw.polygon(dst_tri, fill=(255,255,255))
    dst_img.show()
    dst_img.paste(transformed, mask=mask)
    dst_img.show()

im100 = Image.open('test100.jpg')
im250 = Image.open('test250.jpg')

tri1 = [(10,10), (20,20), (10,20)]
tri2 = [(35,30), (75,19), (50,90)]

transformblit(tri1, tri2, im100, im250)

rawDescription: Copying triangular image region with PIL


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

#---------
# IMPORT
#---------
from PyQt4 import QtGui, QtCore

#---------
# MAIN
#---------
class MyWindow(QtGui.QWidget):
    valueChanged  = QtCore.pyqtSignal(int)

    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.value = 0

        self.pushButtonAdd = QtGui.QPushButton(self)
        self.pushButtonAdd.setText("Add!")
        self.pushButtonAdd.clicked.connect(self.on_pushButtonAdd_clicked)

        self.pushButtonSubtract = QtGui.QPushButton(self)
        self.pushButtonSubtract.setText("Subtract!")
        self.pushButtonSubtract.clicked.connect(self.on_pushButtonSubtract_clicked)

        self.lineEditValue = QtGui.QLineEdit(self)
        self.lineEditValue.setText(str(self.value))

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.pushButtonAdd)
        self.layoutVertical.addWidget(self.pushButtonSubtract)
        self.layoutVertical.addWidget(self.lineEditValue)

    @QtCore.pyqtSlot()
    def on_pushButtonAdd_clicked(self):
        self.valueChanged.emit(1)

    @QtCore.pyqtSlot()
    def on_pushButtonSubtract_clicked(self):
        self.valueChanged.emit(-1)

    def setValue(self, value):
        self.value += value
        self.lineEditValue.setText(str(self.value))

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.resize(333, 111)
    main.valueChanged.connect(main.setValue)
    main.show()

    sys.exit(app.exec_())

rawDescription: PyQt. How to translate function value to lineEdit? Please, help to find a better approach


code:
df = x.pivot_table(values = "price", index = "trade_date", columns = "ticker")
df
df.reindex_axis(["A", "AA", "AAPL", "IBM", "XOM"], axis=1)

rawDescription: Pandas pivot_table using a given list of indices and columns


code:
def format_for_user(self, user):
    body = self.body
    soup = BeautifulSoup(body)
    user_msg = False
    if not user is None:
        user_tags = soup.findAll('note', {"class": "%s" % user.nickname})
        for tag in user_tags:
            tag.name = 'span'
    all_tags = soup.findAll('note')
    for tag in all_tags:
        tag.decompose()
    soup = soup.prettify()
    return (soup, user_msg)

rawDescription: Modifying a group within Regular Expression Match


code:
from django.contrib import admin
from django.forms import ModelForm, Select
from .models import MyModel

CHOICES = (
    ("hello", "hello"),
    ("world", "world")
)

class MyModelForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget = Select(choices=CHOICES)
    class Meta:
        model = MyModel
        fields = ('myfield',)

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm

admin.site.register(MyModel, MyModelAdmin)

rawDescription: django admin formfield_for_dbfield raises multiple times

description: Django admin formfield_for_dbfield raises multiple times


code:
class Node:
  def __init__(self):
    self.data = None
    self.next = None

class LinkedList:
  def __init__(self):
    self.head = None

  def addNode(self, data):
    curr = self.head
    if curr is None:
      n = Node()
      n.data = data
      self.head = n
      return

    if curr.data > data:
      n = Node()
      n.data = data
      n.next = curr
      self.head = n
      return

    while curr.next is not None:
      if curr.next.data > data:
        break
      curr = curr.next
    n = Node()
    n.data = data
    n.next = curr.next
    curr.next = n
    return

  def __str__(self):
    data = []
    curr = self.head
    while curr is not None:
      data.append(curr.data)
      curr = curr.next
    return "[%s]" %(', '.join(str(i) for i in data))

  def __repr__(self):
    return self.__str__()

def main():
  ll = LinkedList()
  num = int(input("Enter a number: "))
  while num != -1:
    ll.addNode(num)
    num = int(input("Enter a number: "))
  c = ll.head
  while c is not None:
    print(c.data)
    c = c.next

main()

rawDescription: Sorted Linked List in Python

description: Sorted Linked List in Python


code:
f = open("file.txt", "r")
lines = f.readlines()
f.close()

f = open("file.txt", "w")
num = 0
for line in lines:
    if num > 0:
        num = num - 1
    elif 'A_B' in line:
        number = line.split()[1]
        num = int(number)
    else:
        f.write(line)
f.close()

rawDescription: Find and remove lines in Python and output result


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

r1 = 1  #  AU Earth
r2 = 1.524  #  AU Mars
deltanu = 75 * np.pi / 180  #  angle in radians
mu = 38.86984154054163
c = np.sqrt(r1 ** 2 + r2 ** 2 - 2 * r1 * r2 * np.cos(deltanu))
s = (r1 + r2 + c) / 2
am = s / 2

def g(a, alphag, betag):
    return (np.sqrt(a ** 3 / mu)
            * (alphag - betag - (np.sin(alphag) - np.sin(betag))))

a = np.linspace(am, 2, 500000)

fig, ax = plt.subplots()

alphag = 2 * np.pi - 2 * np.arcsin(np.sqrt(s / (2 * a)))
betag = 2 * np.arcsin(np.sqrt((s - c) / (2 * a)))
ax.plot(a, g(a, alphag, betag), color = 'r')
alphag = 2 * np.arcsin(np.sqrt(s / (2 * a)))
ax.plot(a, g(a, alphag, betag), color = 'r')

plt.show()

rawDescription: Python: Filling in a gap between two plots


code:
import sys,os
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', newline='')
print("Whatever")

rawDescription: Windows/Py3 stdout with only LR, not CRLF


code:
import collections
dir(collections)

rawDescription: What is/are the Python equivalent(s) to the Java Collections Framework?


code:
from lxml import html
import requests
import xlsxwriter

Urllist = []
titlecontentlist =[]

workbook = xlsxwriter.Workbook('PIB.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write_row(0, 0, ["URL", "TITLE"])
row = 1

for pageno in range(123310, 123314):
    Url = "http://pib.nic.in/newsite/PrintRelease.aspx?relid={}".format(pageno)
    page = requests.get(Url)
    tree = html.fromstring(page.text)

    titlecontent = tree.xpath('//title/text()')
    heading = tree.xpath('//div[@id="condiv"]/text()')

    worksheet.write_row(row, 0, [Url, titlecontent[0].strip()])
    row += 1

workbook.close()

rawDescription: Create a dynamic list of URLs and titles and save it in an Excel file


rawDescription: best way to add logic around django version?

description: Add logic around django version


code:
def last_index(l, value):
    """
    Find the last occurance of value in the list
    """
    # http://stackoverflow.com/q/522372/693869#comment336488_522401
    return len(l) - 1 - l[::-1].index(value)

def move_item(l, old, new):
    """
    Move an item from an old index to a new index
    """
    l.insert(new, l.pop(old))

def relative_reorder(l, before, after):
    """
    reorder list so that all occurrences of before are of a lower
    index than all occurrences of after
    """
    while last_index(l, before) > l.index(after):
        move_item(l, last_index(l, before), l.index(after))

stack = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
relative_reorder(stack, 9, 7)
print(stack)
[1, 2, 3, 4, 5, 6, 9, 9, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8]

rawDescription: How to do stable in-place relative reordering of elements in a list

description: Do stable in-place relative reordering of elements in a list


code: processes = [ subprocess.Popen(['rsh', host, 'myscript']) for host in hosts ]

rawDescription: Python subprocess.Popen without joining

description: Python subprocess.Popen without joining


code:
compile("First = Myclass('firstvar','secondvar','thirdvar')", "sample", "single")
dis.dis(Out[12])

rawDescription: Python: Referring to any created object with __init__


code:
import datetime
datetime.datetime.strptime("01-Jan-1995", "%d-%b-%Y")

rawDescription: Parse a string with a date to a datetime object


code:
from urlparse import urlparse, urlunparse

@app.before_request
def redirect_nonwww():
    """Redirect non-www requests to www."""
    urlparts = urlparse(request.url)
    if urlparts.netloc == 'example.com':
        urlparts_list = list(urlparts)
        urlparts_list[1] = 'www.example.com'
        return redirect(urlunparse(urlparts_list), code=301)

rawDescription: How do I redirect to the www. version of my Flask site on Heroku?

description: Redirect to the www. version of my Flask site on Heroku


code:
setup(
    # other arguments here...
    entry_points = {
        'console_scripts': [
            'foo = my_package.some_module:main_func',
            'bar = other_module:some_func',
        ],
        'gui_scripts': [
            'baz = my_package_gui.start_func',
        ]
    }
)

rawDescription: Installable distutils packages: How do I import package modules from command line scripts which are also part of the same package?


code:
from dateutil.relativedelta import relativedelta
from datetime import datetime
(datetime.now() - relativedelta(months=2)).replace(day=1)
(datetime(2010, 4, 30) - relativedelta(months=2)).replace(day=1)
(datetime(2010, 2, 28) - relativedelta(months=2)).replace(day=1)

rawDescription: A more suitable way to rewrite this?

description: A more suitable way to rewrite this


code:
import gtk
import webkit

view = webkit.WebView()

sw = gtk.ScrolledWindow()
sw.add(view)

win = gtk.Window(gtk.WINDOW_TOPLEVEL)
win.add(sw)
win.show_all()

view.open("http://w3.org/")
gtk.main()

rawDescription: Need a simple "Hello World" example using the Webkit library in Python


code:
def escape(s):
    isIn = False
    ret = []
    for i in range(len(s)):
        if not isIn and s[i]=="'": ret += ["""]
        else: ret += s[i:i+1]

        if isIn and s[i:i+2]=="%}": isIn = False
        if not isIn and s[i:i+2]=="{%": isIn = True

    return "".join(ret)

rawDescription: Python regex - Replace all characters except those between braces


code:
class LedThread(Thread):
    def __init__(self, args):
        Thread.__init__(self)
        self.args = args
    def run(self):
        self.doLeds()
    def doLeds(self):
        onoff = 0
        while 1:
            onoff=not onoff
            for led in self.args:
                wpi.digitalWrite(led,onoff)
                time.sleep(0.025)

t = LedThread([17,22,10,9,11])
t.start()
time.sleep(10)
t.args = [10,9,11]
time.sleep(10)

rawDescription: Python Thread Update Arg

description: Python Thread Update Arg


code:
import string
string.punctuation
'!Hello.'.strip(string.punctuation)
' '.join(word.strip(string.punctuation) for word in "Hello, world. I'm a boy, you're a girl.".split())

rawDescription: strip punctuation with regex - python

description: Strip punctuation with regex - python


code:
class User(Base):
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False, unique=True)
    created_at = Colmn(DateTime, nullable=False, default=func.now())

class Post(Base):
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey(User.id), nullable=False)
    user = relationship(User, backref=backref('posts'))
    title = Column(String, nullable=False)
    body = Column(Text, nullable=False)
    created_at = Colmn(DateTime, nullable=False, default=func.now())

User.post_query = relationship(Post, lazy="dynamic")

rawDescription: How to use joinedload/contains_eager for query-enabled relationships (lazy='dynamic' option) in SQLAlchemy

description: Use joinedload/contains_eager for query-enabled relationships (lazy='dynamic' option) in SQLAlchemy


code:
from datetime import datetime
import pandas as pd
parse = lambda x: datetime.strptime(x, '%Y%m%d %H')
pd.read_csv("..\\file.csv",  parse_dates = [['YYYYMMDD', 'HH']],
            index_col = 0,
            date_parser=parse)

rawDescription: Parse dates when YYYYMMDD and HH are in separate columns using pandas in Python


code:
from django.utils.html import strip_tags

class Publication(models.Model):
    authors = models.CharField()
    authors_stripped = models.CharField(editable=False)

    def __save__(self,*args, **kwargs):
        if self.authors:
            self.authors_stripped = strip_tags(self.authors)
        super(Publication, self).save(*args, **kwargs)

rawDescription: order queryset by strip_tags(html string)

description: Order queryset by strip_tags(html string)


code:
def get_access_token(self):
    ...
    self.access_token = response_data["access_token"]
    self.refresh_token = response_data["refresh_token"]
    self.oauth_obj.access_token = self.access_token
    self.oauth_obj.refresh_token = self.refresh_token
    ...

rawDescription: How to change value in initial in Class() after some change

description: Change value in initial in Class() after some change


code:
import re
line = "abc def ghi"
new_line = re.sub("abc", "123", line)
new_line

rawDescription: Using Sed through subprocess.call in python to conduct in file replacements


code:
the_string = 'x1y1'
the_reference = self.ids[the_string]
the_reference.text = 'the_new_text'

rawDescription: Kivy Reference id by string

description: Kivy Reference id by string


code:
import matplotlib.pyplot as plt
from pandas import DataFrame
import numpy as np

# Fake up some data
test3 = DataFrame({
    'tau':np.logspace(-3,0,100),
    'E_tilde':np.linspace(100,0,100),
    'Max_error_red':np.logspace(-2,1,100),
    'time_snnls':np.linspace(5,0,100),
    'z_t_gandb':np.linspace(16,15,100)
    })

# Setting up plot with 3 'y' axis
fig, ax = plt.subplots()
ax2, ax3 = ax.twinx(), ax.twinx()
rspine = ax3.spines['right']
rspine.set_position(('axes', 1.25))
ax3.set_frame_on(True)
ax3.patch.set_visible(False)
fig.subplots_adjust(right=0.75)

# Setting the logscaling
ax.set_xscale('log') # Works
ax2.set_yscale('log')# Doesnt work

# Plotting the dataframe
test3.plot(x = 'tau', y = 'time_snnls', ax=ax, style='b-',legend=False)
test3.plot(x = 'tau', y = 'Max_error_red', ax=ax2, style='r-',legend=False)
test3.plot(x = 'tau', y = 'z_t_gandb', ax=ax, style='b-.',legend=False)
test3.plot(x = 'tau', y = 'E_tilde', ax=ax3, style='g-',legend=False)

# Setting the color and labels
ax.set_xlabel('tau(nounit)')
ax.set_ylabel('Time(s)', color = 'b')
ax2.set_ylabel('Max_error_red', color = 'r')
ax3.set_ylabel('E_tilde', color = 'g')

# Gather all the legend handles and labels to plot in one legend
l1 = ax.get_legend_handles_labels()
l2 = ax2.get_legend_handles_labels()
l3 = ax3.get_legend_handles_labels()

handles = l1[0]+l2[0]+l3[0]
labels = l1[1]+l2[1]+l3[1]

ax.legend(handles,labels,loc=5)

plt.show()

rawDescription: Pandas dataframe plotting: yscale log and xy label and legend issues


rawDescription: Django How to pass list of values one views function to other views function


code: File_Name = inspect.getfile(f)

rawDescription: How to determine the callee details in a pythondecorator function?

description: Determine the callee details in a pythondecorator function


code:
items = [{'category': m.category, 'message': m.message}
  for m in h.flash.pop_messages()]

rawDescription: Load list with content of object

description: Load list with content of object


code:
import shutil
import tkMessageBox
import ttk
import urllib2
from threading import Thread

IPOD_1_URL = (
    'http://downloads.sourceforge.net/project/whited00r/7.1/'
    'Whited00r71-iPodTouch1G.zip'
    '?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fwhited00r%2Ffiles%2F7.1%2F'
    '&ts=1405674672'
    '&use_mirror=softlayer-ams'
)

def download(url, filename):
    response = urllib2.urlopen(url)
    with open(filename, 'wb') as output_file:
        shutil.copyfileobj(response, output_file)

def check_download(thread, progress_bar):
    if thread.is_alive():
        progress_bar.after(500, check_download, thread, progress_bar)
    else:
        progress_bar.stop()
        tkMessageBox.showinfo(
            title='Done',
            message='Download complete. Please follow the installation'
                ' instructions provided in the .html file.'
        )

def start_download_for_ipod1():
    progress_bar = ttk.Progressbar(
        orient='horizontal', length=200, mode='indeterminate'
    )
    progress_bar.pack(side='top')
    progress_bar.start()
    thread = Thread(
        target=download, args=(IPOD_1_URL, 'Whited00r71-iPodTouch1G.zip')
    )
    thread.daemon = True
    thread.start()
    check_download(thread, progress_bar)

rawDescription: running urllib2 with progressbar calls crashes program

description: Running urllib2 with progressbar calls crashes program


code:
def generate_image(filepath, text='Hello World!', color='red', font=None):
    img = QtGui.QImage(720, 405, QtGui.QImage.Format_RGB32)
    img.fill(QtCore.Qt.gray)
    painter = QtGui.QPainter(img)
    painter.setPen(QtGui.QColor(color))
    if font is None:
        font = painter.font()
        font.setBold(True)
        font.setPointSize(24)
    painter.setFont(font)
    painter.drawText(img.rect(), QtCore.Qt.AlignCenter, text)
    painter.end()
    return img.save(filepath, 'JPG')

rawDescription: PyQt: How to Generate a Raster Image with a Custom Message


code:
import time

NUM_CYCLES = 10
start = time.time()
for impulse_count in range(NUM_CYCLES):
    GPIO.wait_for_edge(25, GPIO.FALLING)
duration = time.time() - start      #seconds to run for loop
frequency = NUM_CYCLES / duration   #in Hz

rawDescription: How to get the frequency of a square wave in a python script

description: Get the frequency of a square wave in a python script


code:
cnn = get_db_connection()
sqlqry = "select * from table"
nacols = ['Col_with_NAs']
indexcols = ['Col_with_NAs', 'othercol1', 'othercol2']
df = pandas.read_sql(sqlqry, cnn).dropna(subset=nacols).set_index(indexcols)

rawDescription: None in pandas dataframe index

description: None in pandas dataframe index


code:
def _recurse_for_children(self, node, only_active=False):
    children = []
    children.append(node)
    for child in node.child.active():
        if child != self:
            if (not only_active) or child.active_products().count() > 0:
                children_list = self._recurse_for_children(child, only_active=only_active)
                children.append(children_list)
    return children

rawDescription: Dynamic navigation in django

description: Dynamic navigation in django


rawDescription: Efficient way to transpose the bit of an integer in python?


code:
import numpy as np
points = np.random.rand(10,2)
translation = np.array([180,-90])
scaling = np.array([1024, -768]) / np.array([360,180])
transformed_points = (points + translation) * scaling

rawDescription: Calculating long expressions using Numpy (coordinate transform)?


code:
import re
s = 'abc>a'
r = re.compile(r'>[:alpha:]$')
print( r.search(s) )

rawDescription: python regular expression help

description: Python regular expression help


code:
my_list = [1, 2, 3, 4, 5]

if 3 in my_list:
    print('you found it')

rawDescription: How to Get a specific value from a list

description: Get a specific value from a list


code: data = [image.getpixel((x, y)) for x in range(image.width) for y in range(image.height)]

rawDescription: Converting PNG file to bitmap array in Python


rawDescription: Determine if python is being run in Ubuntu Linux


code:
emote_dict ={value.get('code'):emote_id for (emote_id, value) in r.json()['images'].iteritems()}
query_name = raw_input("Enter emote name:").strip()
if query_name in emote_dict:
    response = "http://static-cdn.jtvnw.net/emoticons/v1/" + emote_dict[query_name] + "/1.0"

rawDescription: Lookup value inside dictionary-of-dictionary


code:
#! /usr/bin/env python2

import collections

def translate(srcf, dstf):
    by_chem = collections.defaultdict(list)

    with open(srcf, 'rb') as f:
        for line in f:
            values = line.split()
            if not values:
                continue
            soln = values.pop(0)
            for chem in values:
                by_chem[chem].append(soln)
    with open(dstf, 'wb') as f:
        for chem, solns in sorted(by_chem.iteritems()):
            f.write('%s\t%s\n' % (chem, '\t'.join(solns)))

translate('ch_source.txt', 'ch_dst.txt')

rawDescription: Converting file formats

description: Converting file formats


code:
from itertools import permutations

foo = ['a', 'b', 'c']
print(list(permutations(foo, 2)))

# Out: [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

rawDescription: Every combination of list elements without replacement


code:
f = open('results.txt', 'a')
f.write(args + " " + str(len(i)) + "\n")
f.close()

rawDescription: storing results into a file after multiple runs python

description: Storing results into a file after multiple runs python


code:
order = input("Please enter the name of the product you wish to purchase\n")
with open("barcode.txt","r") as myfile:
    details=myfile.readlines() #reads the file and stores it as the variable 'details'
    for line in details:
        if order in line: #if the barcode is in the line it stores the line as 'productline'
            productline=line
            quantity=int(input("How much of the product do you wish to purchase?\n"))
            itemsplit=productline.split(' ') #seperates into different words
            price=float(itemsplit[1]) #the price is the second part of the line
            total=(price)*(quantity) #this works out the price
            print("Your total spent on this product is: " +'£'+str(total))

rawDescription: How do you get python to read a whole text file, not just one line?

description: Get python to read a whole text file, not just one line


code:
class SpotifyMiddlware(object):
    def __init__(self):
        config = spotify.SessionConfig()
        config.application_key_filename = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), 'spotify_appkey.key')

        self.session = spotify.Session(config=config)
        self.session.login('TehNanor', '*******')
        while not self.session.user:
            self.session.process_events()

    def process_request(self, request):
        request.spotify = self.session

rawDescription: pyspotify working locally but not production

description: Pyspotify working locally but not production


code:
class SSHClientAgent(boto.manage.cmdshell.SSHClient):

    def __init__(self, server,
                 host_key_file='~/.ssh/known_hosts',
                 uname='root', timeout=None, ssh_pwd=None):
        self.server = server
        self.host_key_file = host_key_file
        self.uname = uname
        self._timeout = timeout
        # replace the call to get the private key
        self._pkey = None
        self._ssh_client = paramiko.SSHClient()
        self._ssh_client.load_system_host_keys()
        self._ssh_client.load_host_keys(os.path.expanduser(host_key_file))
        self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.connect()

rawDescription: How to use boto.manage.cmdshell with ssh-agent?

description: Use boto.manage.cmdshell with ssh-agent


code:
import os
os.path.realpath(__file__)

rawDescription: Get filepath from shell working directory in Python?


code:
list_of_parent_keys = ndb.put_multi(list_of_entities)
child_keys = []
for parent_key in list_of_parent_keys:
  child_key = ndb.Key(Parent, parent_key, Child, child_key)
  child_keys.append(child_key)

rawDescription: google app engine Efficient way to put large data in datastore

description: Google app engine Efficient way to put large data in datastore


code:
[...]

data1 = band1.ReadAsArray (0, 0, cols, rows).astype(np.float)

[...]

# Normalize data range
max1 = np.nanmax(data1)
min1 = np.nanmax(data1)

data1 = ((data1 - min1)/(max1 - min1)) * 255

[...]

rgbArray[..., 0] = data1.astype(int)

rawDescription: Combine arrays to raster (jpeg)

description: Combine arrays to raster (jpeg)


rawDescription: Check modulo arithmetics conditions using regexp


code:
data = [('James','Germany'), ('Gail','US'), ('Merkel','Poland')]
with open('output', 'w') as f:
    for name,place in data:
        f.write("Name=%s\nLocation=%s\n\n" % (name, place))

rawDescription: write text file line by line python

description: Write text file line by line python


code:
set_b = set(list_b)
result = [x for x in list_a if (x[1], x[2]) in set_b]

rawDescription: I how to intersect a range of columns between two horizontal list?


code:
for i in range(10, 90, 10):
    mjrdno = math.ceil(i*0.7/2)
    mnrdno = i*0.7 - mjrdno
    arcpy.CreateRandomPoints_management(outFolder, "mjrd_network_"+str(i), inFolder+"\mjrd_sample.shp", "", mjrdno, 200)
    arcpy.CreateRandomPoints_management(outFolder, "mnrd_network_"+str(i), inFolder+"\mnrd_sample.shp", "", mnrdno, 200)

rawDescription: Python looping only returns the last results


code:
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))
ax1.set_xticks(np.pi/180. * np.linspace(180,  -180, 8, endpoint=False))

rawDescription: Setting theta-ticks in matplotlib polar plots


code: new  =  not bool(X.objects.filter(pk=self.pk).count())

rawDescription: Check if object with OneToOneField is new or already exists


rawDescription: How to join string with list with python?

description: Join string with list with python