code:
import urllib
import urllib2
import urlparse
from bs4 import BeautifulSoup

def main(url):
    html = urllib2.urlopen(url)
    soup = BeautifulSoup(html.read())

    parsed = list(urlparse.urlparse(url))

    for image in soup.find_all(id="page_image"):
        if image["src"].lower().startswith("http"):
            urllib.urlretrieve(image["src"], "image.png")
        else:
            new = (parsed[0], parsed[1], image["src"], "", "", "")
            urllib.urlretrieve(urlparse.urlunparse(new), "image.png")

if __name__ == '__main__':
    main("http://bookre.org/reader?file=1077091&pg=1")

rawDescription: Scraping a page for images but files are returned as empty


code:
import nltk.data
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
for paragraph in document:
    paragraph_sentence_list = tokenizer.tokenize(paragraph)
    for line in xrange(0,len(paragraph_sentence_list)):
        if 'could' in paragraph_sentence_list[line]:

            print(paragraph_sentence_list[line])

            try:
                print(paragraph_sentence_list[line-1])
            except IndexError as e:
                print('Edge of paragraph. Beginning.')
                pass

            try:
                print(paragraph_sentence_list[line+1])
            except IndexError as e:
                print('Edge of paragraph. End.')
                pass

rawDescription: Extract a Sentence Containing a Word Using Python... As well as the sentences around it?


code:
def flat_list(array, temp_list=None):
    if not temp_list:
         temp_list = []

    for item in array:
        if str(item).isdigit():
            temp_list.append(item)
        else:
            temp_list = flat_list(item, temp_list)

    return temp_list

rawDescription: Local object value is being saved between function calls (maybe scopes misunderstanding)


rawDescription: Perform mathematical operation on a matching columns from 2 data frames: Python Pandas


code:
import numpy as np
a = np.array([1,4,1,np.nan,2,np.nan])
a*0 + np.nan_to_num(a).cumsum()

rawDescription: Numpy cumsum considering NaNs

description: Numpy cumsum considering NaNs


rawDescription: Dynamically expanding a scipy array

description: Dynamically expanding a scipy array


code:
A_dict = {0: 'r', 1: 's', 2: 's', 3: 'r', 4: 'm', 5: 'm', 6: 'a', 7: 'k'}
base_dict = {0: 'k', 1: 'm', 2: 'm', 3: 's', 4: 'a', 5: 's', 6: 'r', 7: 'r'}
d = sorted(base_dict)
used = set()
for key, value in sorted(A_dict.items()):
    key2 = next((k for k in d if base_dict[k] == value and k not in used))
    used.add(key2)
    print('{} -> {}'.format(key, key2))

rawDescription: Reassigning keys in dictionary w.r.t another in python


code:
key = myobj.put()

# if you are using ndb you can get the key with
myobj.key

# if db use
myobj.key()

rawDescription: Getting Key from datastore (GAE)

description: Getting Key from datastore (GAE)


code:
import logging

from mailinglogger.SummarisingLogger import SummarisingLogger

handler = SummarisingLogger('from@example.com',
                            ('to@example.com',),
                            subject='[LOGS] %s (hostname)s',
                            mailhost='smtp.example.com')

logging.basicConfig(format='%(asctime)s %(message)s',
                    datefmt='%m/%d/%Y %I:%M:%S %p',
                    level=logging.INFO)
logger = logging.getLogger()
logger.addHandler(handler)

logging.info('Sent by email.')

rawDescription: What is the best way to send python console output as email from within the script?


code:
# get tables
m_table = ItemMySQL.__table__
pg_table = ItemPG.__table__

# SQL Expression that gets a range of rows quickly
pg_q = select([pg_table]).where(
    and_(
        pg_table.c.id >= id_start,
        pg_table.c.id <= id_end,

))

# get PG DB rows
eng_pg = DBSessionPG.get_bind()
conn_pg = eng_pg.connect()
result = conn_pg.execute(pg_q)
rows_pg = result.fetchall()

for row_pg in rows_pg:
    # convert PG row object into dict
    value_d = dict(row_pg)
    # insert into MySQL
    m_table.insert().values(**value_d)

# close row proxy object and connection, else suffer leaks
result.close()
conn_pg.close()

rawDescription: Automating data dump and restore between Postgres and MySQL


code:
'''"No, thanks, Mom," I said, "I don't know how long it will take."'''
print('''"No, thanks, Mom," I said, "I don't know how long it will take."''')

rawDescription: Pyschool: Topic 1

description: Pyschool: Topic 1


code:
import hashlib
[(fname, hashlib.md5(open(fname, 'rb').read()).digest()) for fname in fnamelst]

rawDescription: How to create a checksum of a file in python

description: Create a checksum of a file in python


code: pd.concat([x1, x2]).groupby(["city", "school"], as_index=False)["count"].sum()

rawDescription: how to merge two pandas DataFrames and aggregate one specific column

description: Merge two pandas DataFrames and aggregate one specific column


code: track_data = [track[prop][0] for prop in ('title', 'artist', 'album')]

rawDescription: Python - Best method to create list made of variables


code:
def _patch_eventlet():
    import eventlet
    import eventlet.debug

    eventlet.monkey_patch()
    blockdetect = float(os.environ.get('EVENTLET_NOBLOCK', 0))
    if blockdetect:
        eventlet.debug.hub_blocking_detection(blockdetect, blockdetect)

rawDescription: Does Celery Automatically Monkey Patch when running eventlet pool?


code: sort_by_score(identity_scoring, foo)

rawDescription: In Python, partial function application (currying) versus explicit function definition


code:
sums = session.query(func.sum(Irterm.n).label('a1')).group_by(Irterm.item_id)
average = session.query(func.avg(sums.subquery().columns.a1)).scalar()

rawDescription: SQLAlchemy subquery - average of sums

description: SQLAlchemy subquery - average of sums


code:
for image in Image.objects.all():
        image_data = serialize_image(image)
        myfile.write(image_data)
        all_tags = image.tag_set.all()
        tag_data = serialize_tag(all_tags)
        myfile.write(tag_data)

rawDescription: Django queryset getting all tags of a certain image along with image


code:
for col in ['parks', 'playgrounds', 'sports', 'roading']:
    public[col] = public[col].astype('category')

rawDescription: Python Pandas - Changing some column types to categories


code:
def rowExtractor(logfile):
    #output holds all of the rows
    ouput = []
    for row in logfile:
        if row[32] == 'No':
            a = []
            a.append(row[44])
            a.append(row[58])
            a.append(row[83])
            a.append(row[32])
            output.append(a)
    #notice that the return statement is outside of the for-loop
    return output
outLog.writerows(rowExtractor(newlogfile))

rawDescription: Trying to write python CSV extractor

description: Trying to write python CSV extractor


code:
import pandas as pd
import seaborn as sns
import numpy as np

df = pd.Series(np.random.randn(72), index=pd.date_range('1/1/2000', periods=72, freq='M'))

grouped = df.groupby(df.index.map(lambda x: x.month))
mnthmax, mnthmin = grouped.transform(max), grouped.transform(min)
df2 = pd.concat([df, mnthmax, mnthmin], axis=1)
df2.columns = ['data', 'max', 'min']

df2['2001'].plot()

rawDescription: Python Pandas groupby and returning result to original Pandas Data Frame


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

#changes here
server_names=['s1','s2','s3','s4']
exception_count = {
                  '2012':[40,30,20,10],
                  '2013':[10,40,40,15],
                  '2014':[20,70,10,30]
                 }

#fixed part
year= sorted(exception_count.keys())
sN = len(server_names)
yN = len(year)

colors = { y:(rd.rand(),rd.rand(),rd.rand()) for y in year}

ind=np.arange(sN)
width=0.8/float(yN)

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

rects = [ ax.bar(ind + i*width, exception_count[y], width, color=colors[y]) for (i,y) in enumerate(year)]

ax.set_xticks(ind + yN*width/2.0)
ax.set_xticklabels(server_names)

ax.legend(rects,year)

plt.show()

rawDescription: Dynamic statement in python to plot graph when one entity is varying


code:
class MainWidget(QtGui.QWidget):
    def __init__(self):
        super(MainWidget, self).__init__()
        # Create a combo and set the second item to be selected
        self.combo = QtGui.QComboBox()
        self.combo.addItems(['foo', 'bar', 'baz'])
        self.combo.setCurrentIndex(1)
        # Connect the combo currentIndexChanged signal
        self.combo.activated.connect(self.on_combo_change)
        # Setup layout
        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.combo)
        self.setLayout(self.layout)

    def on_combo_change(self, index):
        # Whatever the user do, just ignore it and revert to
        # the old value.
        self.combo.setCurrentIndex(1)

app = QtGui.QApplication(sys.argv)
mw = MainWidget()
mw.show()
app.exec_()

rawDescription: How can I create a read-only combobox in Pyqt?

description: Create a read-only combobox in Pyqt


code:
xr_arr = xr * ones(len(x))
yr_arr = yr * ones(len(y))
angle_arr = angle * ones(len(x))
x_new = xr_arr + (x - xr_arr)*cos(angle_arr) - (y - yr_arr)*sin(angle_arr)

rawDescription: How do I rotate a shape in python by +/- x degrees using numpy arrays?

description: Rotate a shape in python by +/- x degrees using numpy arrays


code:
{
'type': 'ir.actions.client',
'tag': 'action_warn',
'name': 'Warning',
'params': {
   'title': 'Warning!',
   'text': 'Entered Quantity is greater than quantity on source.',
   'sticky': True
}
}

rawDescription: Odoo - raise javascript warning

description: Odoo - raise javascript warning


code:
for group_name, grp in df.groupby('upperLevel'):
    plot_table = grp.pivot(index='time', columns='lowerLevel', values='data')
    plot_table.plot()

rawDescription: Python Pandas Subplot with Stacked data

description: Python Pandas Subplot with Stacked data


rawDescription: How to get the name of the module, calling a specific function, in Python.

description: Get the name of the module, calling a specific function, in Python.


code:
def f(x):
    return x['identity'] == 'creosote'

rawDescription: python ascribing another name to lambda function

description: Python ascribing another name to lambda function


code:
import re
def f_breaks(match):
    return match.group().replace('\n', ',')
msg = 'YOUR STRING DATA'
re.sub(r'(?si)(?<=message:\t).*?(?=\ncreated_time:)', f_breaks, msg)

rawDescription: regex matching and replacing with the pattern

description: Regex matching and replacing with the pattern


rawDescription: Using an integer as an SQL Alchemy selectable


code:
import json
from collections import OrderedDict

a = {'c':3, 'a':1, 'b':2}
print(json.dumps(a)) # Random order: a,c,b for example
a = OrderedDict([('c', 3), ('a', 1), ('b', 2)])
print(json.dumps(a))  # Desired order: c,a,b

rawDescription: python json keep object order on output

description: Python json keep object order on output


code:
l = [{'abc':1},{'abcd':2},{'ab':1}]
l.sort(key=lambda x: len(next(iter(x))), reverse=True)
print(l)

rawDescription: Python :sort list of dictionaries based on key


code:
import pygtk, gtk
win = gtk.Window(gtk.WINDOW_TOPLEVEL)
win.connect('destroy', lambda w: gtk.main_quit())

def _add_spinner():
    adj = gtk.Adjustment(0.0, -100.0, 100.0, 1.0, 2.0, 0.0)
    spin = gtk.SpinButton(adj, 0, 1)
    spin.set_wrap(True)
    hbox.pack_start(spin, True, True, 10)
    return spin

vbox = gtk.VBox(True, 10)
hbox = gtk.HBox(True, 10)
vbox.pack_start(hbox, True, True, 10)
spin1 = _add_spinner()
spin2 = _add_spinner()
win.add(vbox)

def set_spin(src, dst):
    # ensure that calling `set_value` does not fire events
    hid = handlers.get(dst)
    dst.handler_block(hid)
    dst.set_value(src.get_value() + 1.5)
    dst.handler_unblock(hid)

# when 'spinN' is changed, call 'set_spin'
hid1 = spin1.connect('value-changed', set_spin, spin2)
hid2 = spin2.connect('value-changed', set_spin, spin1)
handlers = {spin1: hid1, spin2: hid2}
win.show_all()
gtk.main()

rawDescription: Mutually dependent PyGtk SpinButtons

description: Mutually dependent PyGtk SpinButtons


code:
from datetime import datetime, timedelta
delta24h = timedelta(hours=13)
(datetime.min + delta24h).strftime('%I:%M:%S %p')

rawDescription: Represeting timedelta object in 12'o Clock time format


code:
filename = files.blobstore.create(mime_type='text/csv')
csvfile = request.FILES.get('csvfile')

with files.open(filename, 'a') as output_file:
    writer = csv.writer(output_file, quoting=csv.QUOTE_NONE)
    for row in csv.reader(csvfile.read().splitlines()):
         writer.writerow(row)

files.finalize(filename)

rawDescription: How to store a CSV file uploaded via Django into a blobstore on Google App Engine?

description: Store a CSV file uploaded via Django into a blobstore on Google App Engine


code:
def read_file_to_list(filename):
    temp = open(filename, 'r')
    string = temp.read()
    numbers = [int(x) for x in string.split(' ')]
    return numbers

sort1 = read_file_to_list('sortfile1.txt')
sort2 = read_file_to_list('sortfile2.txt')

total = sort1 + sort2

rawDescription: python 3.4.2 joining strings into lists

description: Python 3.4.2 joining strings into lists


code:
records = []

with open('data.txt', 'r') as lines:
    for line in lines:
        if line.startswith ('\t'):
            record ['notes'].append (line [1:])
            continue
        record = {'title': line, 'notes': [] }
        records.append (record)

for record in records:
    print ('Record is', record ['title'] )
    print ('Notes are', record ['notes'] )
    print ()

rawDescription: Parsing Text Structured with Indents in Python


code:
from django.db.models import signals

class Post(models.Model):
    title = models.CharField(max_length=240)
    last_comment_date = models.DateField(null=True, blank=True)

def post_last_comment_date(sender, instance=None, **kwargs):
    try:
        last_comment_date = self.comment_set.order_by('-date')[0].date
    except Comment.DoesNotExist:
        return

    if last_comment_date != comment.post.last_comment_date:
        comment.post.last_comment_date = last_comment_date
        comment.post.save()

signals.post_save.connect(post_last_comment_date, sender=Comment)

rawDescription: Django order_by ForeignKey set models

description: Django order_by ForeignKey set models


code:
from tkinter import *
import functools

class practice:
    def __init__(self,root):
        self.button_list = []
        self.entry_list = []
        for w in range(5):
            button = Button(root,text="submit",command=functools.partial(self.enabling, idx=w))
            button.grid(row=w,column=0)
            self.button_list.append(button)
            entry1=Entry(root, state="disabled")
            entry1.grid(row=w,column=1)
            self.entry_list.append(entry1)

    def enabling(self,idx):
            self.entry_list[idx].config(state="normal")

root = Tk()
a = practice(root)

root.mainloop()

rawDescription: How do I link python tkinter widgets created in a for loop?

description: Link python tkinter widgets created in a for loop


code:
s = struct.unpack('IL3f3f3f512s3f')
name = s[11].decode('utf-16')
camera_pos_x,camera_pos_y,camera_pos_z = s[12:15]

rawDescription: Accessing a memory-mapped file using Python


code:
cursor.execute(
    "SELECT tbl_name FROM sqlite_master WHERE type='table'")

table_names = cursor.fetchall()

rawDescription: How do you create an index on the tables themselves in a database?

description: Create an index on the tables themselves in a database


rawDescription: striping string in python

description: Striping string in python


code:
img = gimp.image_list()[0]
img.layers[0].name
folder = "/tmp/"
for layer in img.layers:
  name = folder + layer.name + ".png"
  pdb.gimp_file_save(img, layer, name, name)

rawDescription: Gimp save all layers to files with the layers size


rawDescription: Django: Getting data associated with logged in user.


code:
file_list = os.listdir('.')
for each in file_list:
    if each[-4:] != '.exe':
        file_list.pop(file_list.index(each))

for each in file_list:
    name = each.split('_')[0]
    name += '.exe'
    os.rename(each, name)

rawDescription: I want to rename a file that has a random part (in its filename) to a specific one


rawDescription: Sort Python list of objects by date

description: Sort Python list of objects by date


code:
df
df.drop(df.index[[1,3]])

rawDescription: How to drop a list of rows from Pandas dataframe?

description: Drop a list of rows from Pandas dataframe


code:
class BaseA():
    a_attr = 'I handle Table'
    # _children = [] # & There was the problem...

    def entery_point(self):
         print('Computing Value from %s' % self.a_attr)
         for child in self._children:  #This is where i think need help
             child().entery_point_b()

    def __init__(self):
        self._children=[] #the right way
        for x in self.__class__.__subclasses__():
            if x not in self._children:
                self._children.append(x)
class BaseB(A):
    b_attr = 'I handle Fields'
    def entery_point_b(self):
         print('Computing Value from %s and %s' % (self.a_attr,self.b_attr) )

#Now the concrete classes
class A(BaseA):
    a_attr = 'table_name'

class B(BaseB,A):
    b_attr = 'field_name_1'

class BB(BaseB, A):
    b_attr = 'field_name_2'

#another set of concrete classes to handle another table
class A2(BaseA):
    a_attr = 'another_table_name'

class B2(BaseB,A2):
    b_attr = 'another_field_name_1'

class BB2(BaseB, A2):
    b_attr = 'another_field_name_2'

if certain_condition:
    a = A()
    a.entery_point()
else:
    a2 = A2()
    a2.entery_point()

rawDescription: How to make a child class call a function in All of its children

description: Make a child class call a function in All of its children


code:
offset = 10
for i in range(offset, 100 + offset):
    print(i)

rawDescription: How to do a python range with offset

description: Do a python range with offset


code:
from Tkinter import *
from ttk import *
import time

root = Tk()
root.geometry('1000x900')
root.title("Astronomical Observing Recording Program")
frame1 = Frame(root, name='frame1')
frame1.pack(fill=BOTH)

welcome_message = "Hi" #shortened

root.protocol("WM_DELETE_WINDOW", frame1.quit)
nb = Notebook(frame1, name='nb')
nb.pack(fill=BOTH, padx=2, pady=3)

welcome_screen = Frame(nb, name='welcome_screen')
Label(welcome_screen, text=welcome_message).pack(side=LEFT)
nb.add(welcome_screen, text='Welcome')

time_screen = Frame(frame1, name='time_screen')
lb_current_time = Label(time_screen)
lb_current_time.pack(side=TOP)
lb_gmt_time = Label(time_screen)
lb_gmt_time.pack(side=TOP)
nb.add(time_screen, text='Time Bar')

def update_time():
    localtime = time.asctime(time.localtime(time.time()))
    gmttime = time.asctime(time.gmtime(time.time()))
    current_time = "The current time is: " + localtime
    gmt_time = "The current GMT time is: " + gmttime
    lb_current_time['text'] = current_time
    lb_gmt_time['text'] = gmt_time
    root.after(1000, update_time)
update_time()

frame1.mainloop()

rawDescription: Updating a clock on a notepad tab

description: Updating a clock on a notepad tab


code:
class StatusCode(object):
    codes  = {
            0: { 'flag': "QEX_OK",      'message': "job successful"                           },
            1: { 'flag': "QEX_CMDLINE", 'message': "general cmd line syntax or semantic error"},
            }

    @classmethod
    def get_code(cls, code):
        return cls.codes[code]

rawDescription: Refering to class variables without creating an instance in Python


code:
from apiclient.http import BatchHttpRequest
import httplib2

def call_back(request_id, response, exception):
  """Do something with the response of each call"""
  pass

def get_request(service, profile_id, days, dimensions, segment):
   """Note I removed the execute() from the end of this method."""
   return service.data().ga().get(
     ids='ga:' + profile_id,
     start_date=days,
     end_date='today',
     metrics='ga:sessions',
     dimensions=dimensions,
     sort='-ga:sessions',
     segment=segment,
     max_results=10)

# Create a batch Http Request object
batch = BatchHttpRequest(callback=self.call_back)

# Construct your queries.
# get top 10 desktop browsers
print("Getting top 10 desktop browsers...")
request_1a = get_request(service, profile_id, '30daysAgo', 'ga:browser', 'sessions::condition::ga:deviceCategory==desktop')
request_1b = get_request(service, profile_id, '60daysAgo', 'ga:browser', 'sessions::condition::ga:deviceCategory==desktop')
request_1c = get_request(service, profile_id, '90daysAgo', 'ga:browser', 'sessions::condition::ga:deviceCategory==desktop')

for request in [request_1a, request_1b, request_1c]:
    batch.add(request)

batch.execute(http=httplib2.Http())

rawDescription: How can I combine/speed up multiple API calls to improve performance?

description: Combine/speed up multiple API calls to improve performance


code:
data = [
    (a1, b1, c1),
    (a2, b2, c2),
    (a3, b3, c3)
]

results = [func(*args) for args in data]   # becomes [result1, result2, result3]

rawDescription: Calculating a function and storing them as different variables


code:
class Foo(object):
    _instances = []

    def __new__(cls, *args, **kw):
        instance = object.__new__(cls)
        cls._instances.append(instance)
        return instance

    @classmethod
    def get_instances(cls):
        return self._instances

rawDescription: How do I get a reference to all classes implementing descriptor object in python

description: Get a reference to all classes implementing descriptor object in python


code:
class Win(QMainWindow):
    ...

    def deleteObject(self):
        ...
        if len(self.list_1) > 1:
            self.delete = Delete(self) # set self as the parent

class Delete(self):
    def _init__(self, parent):
        super(Delete, self).__init__(parent)
        ...

    def deleteObjectCreated(self):
        widget_erased = self.parent().splitter.widget(index)
        ...

rawDescription: Create a class object from another class in python


code:
class NewsBodyResource(ModelResource):
    class Meta:
        queryset = ArticleBody.objects.all()
        resource_name = 'article_body'

class NewsResource(ModelResource):
    newsbodies = fields.ToManyField('yourapp.api.resources.NewsBodyResource', 'articlebody_set', full=True)

    class Meta:
        queryset = Article.objects.filter(status='PU', date_published__lt=datetime.datetime.now).order_by('-date_published')
        resource_name = 'news'

rawDescription: How do I return data from a related model in Django Tastypie?

description: Return data from a related model in Django Tastypie


code:
def get_success_url(self, request, user):
    return ('registration_complete', (), {})

rawDescription: Django-registration class-based views with different templates and parameters


code:
import requests
from urllib import quote_plus as rawurlencode
import time
import string
import random
import operator
from hashlib import sha1
from hmac import new as hmac

def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

# personal Info - taken from https://www.mkmapi.eu/ws/documentation/API:Auth_Overview
mkmAppToken = 'bfaD9xOU0SXBhtBP'
mkmAppSecret = 'pChvrpp6AEOEwxBIIUBOvWcRG3X9xL4Y'
mkmAccessToken = 'lBY1xptUJ7ZJSK01x4fNwzw8kAe5b10Q'
mkmAccessSecret = 'hc1wJAOX02pGGJK2uAv1ZOiwS7I9Tpoe'

# Url to access on mkm
# note that this deviates from the example in the header documentation (https://www.mkmapi.eu/ws/documentation/API:Auth_OAuthHeader) which uses
#accessUrl = 'https://www.mkmapi.eu/ws/v1.1/account'
accessUrl = 'https://www.mkmapi.eu/ws/v1.1/output.json/account'

#Method for access

MyMethod = "GET"

baseString = MyMethod + "&" + rawurlencode(accessUrl) + "&"

# create a random string
# the documentation in https://www.mkmapi.eu/ws/documentation/API:Auth_OAuthHeader uses
#nonce = 53eb1f44909d6
nonce = id_generator(8)

# what time is it?
# the documentation in https://www.mkmapi.eu/ws/documentation/API:Auth_OAuthHeader uses
#now = 1407917892

now = str(int(time.time()))

MyOauthmethod = "HMAC-SHA1"
MyOauthver = "1.0"

# define Parameters and values, order doesn't matter
paramDict ={"oauth_consumer_key":mkmAppToken, "oauth_token" :mkmAccessToken, "oauth_nonce":nonce, "oauth_timestamp":now, "oauth_signature_method":MyOauthmethod, "oauth_version":MyOauthver}

# sorting of parameters is done here
sorted_paramDict = sorted(paramDict.items(), key=operator.itemgetter(0))

#collect the full parameters string
paramStr = ''

for kv in sorted_paramDict:
    paramStr = paramStr + kv[0] + "=" + kv[1] + "&"

# and get rid of the trailing ampersand
paramStr = paramStr[:-1]

#concatenate request and oauth parameters
baseString = baseString + rawurlencode(paramStr)

# concatenate both keys
signingKey = rawurlencode(mkmAppSecret) + "&" + rawurlencode(mkmAccessSecret)
# and create a hased signature with the key and the baseString
Signature = hmac(signingKey, baseString, sha1).digest().encode('base64')[:-1]

# construct the header from the parameters and the URL and the signature
MyHeader = 'OAuth ' + 'realm="' + accessUrl + '", '

for kv in sorted_paramDict:
    MyHeader += kv[0] + '="' + kv[1] + '",'

MyHeader += 'oauth_signature="' + Signature +'"'

headers = {'Authorization': MyHeader}

# and now requests can do its magic (pun intended)

r = requests.get(accessUrl, headers=headers)

outjson = r.json()

rawDescription: Oauth1.0 API issue with Python

description: Oauth1.0 API issue with Python


code:
# On the top of the file:
from django.db.models import Q

# Game instance method:
def get_all_players(self):
    return Player.objects.filter(Q(games1__pk=self.pk) | Q(games2__pk=self.pk))

rawDescription: merge querysets in django

description: Merge querysets in django


code:
from selenium import webdriver
from selenium.webdriver.support.ui import Select

URL          = 'http://www.arnoldporter.com/news.cfm'
CSS_SELECTOR = 'select[name=search_practice_id][class=medium]'
OPTION_TEXT  = 'FDA and Healthcare'

browser = webdriver.Chrome()
browser.get(URL)
select_el = browser.find_element_by_css_selector(CSS_SELECTOR)
select = Select(select_el)
select.select_by_visible_text(OPTION_TEXT)

rawDescription: Selenium Hidden Elements: Hidden <option> Elements Within <select>


code:
[build_ext]
compiler=icc

rawDescription: Set C/C++ compiler for Python extensions


code:
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 izip_longest(fillvalue=fillvalue, *args)

rawDescription: Python - prevent "for i in range:" cutting off end of sequence


code: devdir = subprocess.check_output(["ssh", connectstring, "sh -l -c 'echo $DEVDIR'"])

rawDescription: How can I retrieve environment variables from remote system in Python?

description: Retrieve environment variables from remote system in Python


code:
import random
for d1 in range(21):
    if table1[d1]: #1 evaluates to true in python
       table2[d1] = random.expovariate(x)
    else:
       table2[d1] = random.expovariate(y)

rawDescription: Relating list to each

description: Relating list to each


rawDescription: Modulus in django query

description: Modulus in django query


code:
first_list = ['foo','bar','baz']
second_list = [x+y for x,y in zip(first_list,'dsy')]

rawDescription: appending to the strings within a list of strings in python

description: Appending to the strings within a list of strings in python


code:
SEGMENTS = (SEGMENT_1, SEGMENT_2) = range(2)

class NeuronRegion(object):
    def __init__(self):
        self.connection = [None, None]
        self.chosen = 0
    def choose(self, segment):
        assert segment in SEGMENTS
        self.chosen = segment
    def connect(other_neuron_region):
       # remember to reset those to None when they're not needed anymore,
       # to avoid cycles that prevent the garbage collector from doing his job:
       self.connection[self.chosen] = other_neuron_region
       other_neuron_region.connection[other_neuron_region.chosen] = self

class Child1(NeuronRegion):
   ''' other stuff '''

class Child2(NeuronRegion):
   ''' other stuff '''

rawDescription: Call an arbitrary child attribute from a parent class?


code:
def remove_indices(numbers, indices):
    result = []
    i=0
    for j in sorted(indices):
        result += numbers[i:j]
        i = j+1
    result += numbers[i:]
    return result

rawDescription: What is the most efficient way to remove a group of indices from a list of numbers in Python 2.7?


code:
import urlparse
import re

def check_and_add_http(url):
    # checks if 'http://' is present at the start of the URL and adds it if not.
    http_regex = re.compile(r'^http[s]?://')
    if http_regex.match(url):
        # 'http://' or 'https://' is present
        return url
    else:
        # add 'http://' for urlparse to work.
        return 'http://' + url

for url in url_list:
    url = check_and_add_http(url)
    print(urlparse.urlsplit(url)[1])

rawDescription: How do i truncate url using python

description: Truncate url using python


code:
val = raw_input()    #val accepts a string

val = int(raw_input())   #val takes integer input

rawDescription: Input from keyboard in python

description: Input from keyboard in python


code:
import tkinter as tk
from tkinter import font as tkFont

def resizer(event=None):
    print("Resize")
    widget = event.widget
    menu = widget['menu']

    req_width = widget.winfo_width()-10
    menu_width = menu.winfo_reqwidth()

    cur_label = menu.entrycget(0, "label")
    cur_label = cur_label.rstrip() # strip off existing whitespace

    font = tkFont.Font() # set font size/family here
    resized = False
    while not resized:
        difsize = req_width - menu_width # check how much we need to add in pixels
        tempsize = 0
        tempstr = ""
        while  tempsize < difsize:
            tempstr += " " # add spaces into a string one by one
            tempsize = font.measure(tempstr) #measure until big enough
        menu.entryconfigure(0, label=cur_label + tempstr) # reconfigure label
        widget.update_idletasks() # we have to update to get the new size
        menu_width = menu.winfo_reqwidth() # check if big enough
        cur_label = menu.entrycget(0, "label") # get the current label for if loop needs to repeat
        if menu_width >= req_width: # exit loop if big enough
            resized = True

root = tk.Tk()

var = tk.StringVar()
var.set('First')

option = tk.OptionMenu(root, var, 'First', 'Second', 'Third')
option.bind("<Configure>", resizer) # every time the button is resized then resize the menu
option.configure(indicatoron = False)

option.pack(expand = True, fill = tk.X)

root.mainloop()

rawDescription: OptionMenu modify drop down list width to match OptionMenu width


rawDescription: Converting pandas data frame to dictionary in python


code:
import subprocess
out, err = subprocess.Popen(["pdftotext", "-", "-"], stdout=subprocess.PIPE).communicate(pdf_data)

rawDescription: Running a command line from python and piping arguments from memory


code:
import Cocoa
Cocoa.NSBeep()

rawDescription: Why isn't print(\a) working in IDLE

description: Why isn't print(\a) working in IDLE


code:
def team(request):
    team = None
    if request.user.is_authenticated():
        try:
            # fetch the team managed by the logged in user
            team = Team.objects.get(manager=request.user)
        except (Team.DoesNotExist, Team.MultipleObjectsReturned):
            pass
    return {'team': team}

rawDescription: how to have some contexts all over a project?

description: Have some contexts all over a project


code:
demjson.decode("""{
 firstName:"John",
 lastName:"Doe",
 age:50,
 eyeColor:"blue",
 dimensions:[
     {
      height: "2",
      width: "1"
     }
]
}""")

rawDescription: JavaScript Object to JSON using python

description: JavaScript Object to JSON using python


code:
from pylab import *

sample_rate = .001
f0, f1 = 10, 20
t_change = 2

times = arange(0, 4, sample_rate)

ramp = 1./(1+exp(-6.*(times-t_change)))
freq = f0*(1-ramp)+f1*ramp
phase_correction = add.accumulate(times*concatenate((zeros(1), 2*pi*(freq[:-1]-freq[1:]))))

figure()
subplot(311)
plot(times, freq)
subplot(312)
plot(times, sin(2*pi*freq*times))
subplot(313)
plot(times, sin(2*pi*freq*times+phase_correction))

show()

rawDescription: sine wave glissando from one pitch to another in Numpy

description: Sine wave glissando from one pitch to another in Numpy


code:
import os, pickle, struct

myfile = open('/path/to/my/file', 'w+b')
myfile.write(struct.pack('L', 0)) # write a long of zeroes
index = []
for o in objects:
    index.append(myfile.tell())
    pickle.dump(o, myfile)
index_loc = myfile.tell()
pickle.dump(index, myfile)
myfile.seek(0, 0,  os.SEEK_SET)
myfile.write(struct.pack('L', index_loc))

rawDescription: Seek into a file full of pickled objects


code:
soup = BeautifulSoup(doc)
tags = soup.fetch('td')
for tag in tags:
    if tag.contents[0] and tag.contents[0].strip() == 'Preferred Name':
        return tag

rawDescription: Iterating HTML with BeautifulSoup

description: Iterating HTML with BeautifulSoup


rawDescription: Creating lambda inside a loop

description: Creating lambda inside a loop


code:
def calculate(N, scores1, scores2):
    ranked1 = sorted(enumerate(scores1),key=lambda x: x[1], reverse=True)
    ranked2 = sorted(enumerate(scores2),key=lambda x: x[1], reverse=True)
    ...

rawDescription: Python efficiency for list comparison on numbers >= 10,000


code:
run = hdr_cells[0].paragraphs[0].add_run('Date Filmed:')
run.bold = True
run.underline = True

rawDescription: How can I make table header cells both bold and underline in python?

description: Make table header cells both bold and underline in python


code:
import itertools
a = ['A','B','C','D']
b = ['a','b','c','d']  # [x.lower() for x in a]
[list(x) for x in itertools.product(*zip(a, b))]

rawDescription: Combine two lists in a pythonic way

description: Combine two lists in a pythonic way


code:
ser = Serial('/dev/ttyUSB0', 115200, timeout=1) # NB! One second timeout here!
ser.flushInput() # Might be a good idea?
ser.flushOutput()
ser.write(' cat /sdcard/dump.xml \r\n')
sleep(5) # I really don't think you need to sleep here.

rx_buf = [ser.read(1024)] # Try reading a large chunk. It will read up to 1024 bytes, or timeout and continue.
while True: # Loop to read remaining data, to the end of the rx buffer.
    pending = ser.inWaiting()
    if pending:
        rx_buf.append(ser.read(pending)) # Read pending data, appending to the list.
        # You'll read pending number of bytes, or until the timeout.
    else:
        break

rx_data = ''.join(rx_buf) # Make a string of your buffered chunks.

rawDescription: pySerial cuts off text in file

description: PySerial cuts off text in file


code:
threshold = vtk.Threshold()
threshold.SetInputConnection(extractSlice.GetOutputPort())
threshold.ThresholdRange = [37.35310363769531, 276.8288269042969]

rawDescription: Getting region inside contour in VTK

description: Getting region inside contour in VTK


code:
with open("file.to.create", "w") as file:
    file.truncate(10 ** 10)

rawDescription: How to create a very large file cheaply using Python in Windows 7?

description: Create a very large file cheaply using Python in Windows 7


code:
q = session.query(Parent).\
    join(Parent.children).\
    options(contains_eager(Parent.children)).\
    filter(Child.foo == 1)

rawDescription: How do I filter both parents and children in a O(1) queries?

description: Filter both parents and children in a O(1) queries


code:
from unittest.mock import patch
from unittest import TestCase

def get_input(text):
    return input(text)

def answer():
    ans = get_input('enter yes or no')
    if ans == 'yes':
        return 'you entered yes'
    if ans == 'no':
        return 'you entered no'

class Test(TestCase):

    # get_input will return 'yes' during this test
    @patch('yourmodule.get_input', return_value='yes')
    def test_answer_yes(self, input):
        self.assertEqual(answer(), 'you entered yes')

    @patch('yourmodule.get_input', return_value='no')
    def test_answer_no(self, input):
        self.assertEqual(answer(), 'you entered no')

rawDescription: python mocking raw input in unittests

description: Python mocking raw input in unittests


code:
from subprocess import Popen
process = Popen(['slow', 'running', 'program'])
while process.poll():
    if raw_input() == 'Kill':
        if process.poll(): process.kill()

rawDescription: Process closing

description: Process closing


code:
import matplotlib.pyplot as plt
import math
x = [1,2,3,4,5]
y = [1000, 1002, 1001, 1003, 1005]
low = min(y)
high = max(y)
plt.ylim([math.ceil(low-0.5*(high-low)), math.ceil(high+0.5*(high-low))])
plt.bar(x,y)
plt.show()

rawDescription: Automatically setting y-axis limits for bar graph using matplotlib


code: cls = db.class_for_kind(db_key.kind())

rawDescription: Derive db.Model subclass from db.Key

description: Derive db.Model subclass from db.Key


code:
import datetime
results.sort(key=lambda r: r.person.birthdate
    if (r and r.person and r.person.birthdate)
    else datetime.datetime.now())

rawDescription: Sort Python list of objects by date (when some are None)


code:
fig, ax = plt.subplots(1, 1, figsize=(9, 5))
ax.hist([data.ix[low:high, 'values'] for low, high in [(0, 70), (70, 85), (85, 90)]],
         bins=15,
         stacked=True,
         rwidth=1.0,
         label=['first70', 'next15', 'last5'])
ax.legend()

rawDescription: Histogram with stacked components

description: Histogram with stacked components


code:
# This is for Py2k.  For Py3k, use http.client and urllib.parse instead, and
# use // instead of / for the division
import httplib
import urlparse

def unshorten_url(url):
    parsed = urlparse.urlparse(url)
    h = httplib.HTTPConnection(parsed.netloc)
    resource = parsed.path
    if parsed.query != "":
        resource += "?" + parsed.query
    h.request('HEAD', resource )
    response = h.getresponse()
    if response.status/100 == 3 and response.getheader('Location'):
        return unshorten_url(response.getheader('Location')) # changed to process chains of short urls
    else:
        return url

rawDescription: How can I un-shorten a URL using python?

description: Un-shorten a URL using python


code:
@patch('mbgmodule.MBG120Simulator._send_reply', autospec=True)
@patch('mbgmodule.MBG120Simulator._reset_watchdog', autospec=True)
@patch('mbgmodule.MBG120Simulator._handle_set_watchdog', autospec=True)
def test_handle_command_too_short(self,mock_handle_set_watchdog,
                                          mock_reset_watchdog,
                                          mock_send_reply):
    simulator = MBG120Simulator()
    simulator._handle_command('XA99')
    # You can use ANY instead simulator if you don't know it
    mock_send_reply.assert_called_once_with(simulator, 'X?')
    self.assertFalse(mock_reset_watchdog.called)
    self.assertFalse(mock_handle_set_watchdog_mock.called)
    simulator.stop()

rawDescription: Preferred way of patching multiple methods in Python unit test


code:
list1 = [1,2,3,4]
list2 = [3,4,5,6]
result = set(list1).intersection(list2)

rawDescription: Python list intersection efficiency: generator or filter()?


code:
import networkx as nx
import matplotlib.pyplot as plt
import random

N = 20 # number of nodes
K = 3 # number of "long" edges

G = nx.cycle_graph(N)

for node in G.nodes():
    while len(G.neighbors(node)) < K+2:
        # Add K neighbors to each node
        # (each node already has two neighbors from the cycle)
        valid_target_found = False
        while not valid_target_found:
            # CAUTION
            # This loop will not terminate
            # if K is too high relative to N
            target = random.randint(0,N-1)
            # pick a random node
            if (not target in G.neighbors(node)
                and len(G.neighbors(target)) < K+2):
                # Accept the target if (a) it is not already
                # connected to source and (b) target itself
                # has less than K long edges
                valid_target_found = True
        G.add_edge(node, target)

nx.draw_circular(G)
plt.show()

rawDescription: Networkx creating a graph with node attributes to determine which edges are connected


code:
for blob in blobs:
    a=blob.meanColor()
    mc=(int(a[0]), int(a[1]), int(a[2]))
    rect=blob.boundingBox()
    img.drawRectangle(rect[0], rect[1], rect[2], rect[3], mc, 3)
img.show()

rawDescription: Vehicle detection, count and classification in Python


code:
@mock.patch('path.my_file.randint', return_value=0)
def test_place_value(m_randint):
    obj = math_q.Questions()
    obj.place_value("value of {0} in {1}", [1,2,3,4])

    m_randint.assert_called_once_with(0, 3)
    assert obj.questions["question1"] == ...

rawDescription: nosetest a function with random elements

description: Nosetest a function with random elements


rawDescription: Pandas: Eliminating for loops

description: Pandas: Eliminating for loops


code:
def setcolor(self,bname):
    if bname == "RED": #or 1, can't tell how you've written it
        self.text_in.config(foreground = RED) #I think that's how colors work in tkinter
    elif bname == "BLUE":
        self.text_in.config(foreground = BLUE)
    #etc etc

rawDescription: Tkinter Lamda Button

description: Tkinter Lamda Button


code:
def computation(A):
    for i in range(A.shape[0]):
        idx_begin = A.indptr[i]
        idx_end = A.indptr[i+1]
        row_nnz = idx_end - idx_begin
        diag_elems = A.data[idx_begin:idx_end]
        diag_indices = A.indices[idx_begin:idx_end]
        ith_diag = sparse.csc_matrix((diag_elems, (diag_indices, diag_indices)),shape=(A.shape[1], A.shape[1]))
        ith_diag.eliminate_zeros()

rawDescription: Create a sparse diagonal matrix from row of a sparse matrix


rawDescription: Find Element Next to Element With Specified Text


code:
processing = zip(booleans, functions)

for i, action in enumerate([p for (b,p) in processing if b]):
    action([a[i] for a in myList])

rawDescription: What is the pythonic way to get the next unprocessed list column?


code:
serversocket.setblocking(False)

readable, writable, err = select.select([serversocket.fileno()], [], [], 1)
if readable:
    clientsocket, address = serversocket.accept()

rawDescription: Detect when a clientsocket attempts to connect to a serversocket


code:
import csv

with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

rawDescription: How do I write a csv file from a dictionary with multiple values per key?

description: Write a csv file from a dictionary with multiple values per key


code:
response = urllib2.urlopen(url_to_get_x_accel_mapping_header)
download_url = response.headers['X-Accel-Mapping']
download_contents = urllib2.urlopen(download_url).read()

rawDescription: Download image from URL that automaticaly creates download - python


code:
s = '34 ch33se 34e8 3.4'
map(int, filter(None, ''.join(map(lambda c: (c.isdigit() and c or ' '), s)).split(' ')))

rawDescription: Separating integers from a string properly (no regex)


code:
size_dict = \
[
    {
         "sizeOptionName":"XS",
         "sizeOptionId":"1528",
         "sortOrderNumber":"7017"
    },
    {
        "sizeOptionName":"S",
        "sizeOptionId":"1529",
        "sortOrderNumber":"7047"
    },
    {
        "sizeOptionName":"M",
        "sizeOptionId":"1530",
        "sortOrderNumber":"7095"
    }
]

size_id_map = {size["sizeOptionId"] : size for size in size_dict}

production_dict = \
[
    {
        "catalogItemId":"7627712",
        "catalogItemTypeId":"3",
        "regularPrice":"0.0",
        "sizeDimension1Id":"1528",
        "sizeDimension2Id":"0",
    }
]

def make_variant(idict):
    odict =  idict.copy()
    size_id = odict.pop("sizeDimension1Id")
    odict.pop("sizeDimension2Id")
    odict["sizeName"] = size_id_map[size_id]["sizeOptionName"]
    odict["sizeId"]   = size_id
    return odict

result_dict = \
{
    "variant" : [make_variant(product) for product in production_dict]
}

print(result_dict)

rawDescription: Logic for building converter using python dictionary values


rawDescription: How can I efficiently move from a Pandas dataframe to JSON

description: Efficiently move from a Pandas dataframe to JSON


code:
class F(Form):
    a = StringField('a', validators = [validators.DataRequired()])

    def __init__(self, *args, **kwargs):
        hide_a = kwargs.pop('hide_a')
        super(F, self).__init__(*args, **kwargs)
        if hide_a:
            self.a.widget = widgets.HiddenInput()

@app.route('/f', methods = ['GET', 'POST'])
def f():
    if foo():
        form = F(request.form, hide_a=True)
    else:
        form = F(request.form)
    if request.method == 'GET':
        return render_template('f.html', form = form)

rawDescription: Flask, WTForms: Is there a way to make a StringField in the form _temporarily_ hidden?


code:
import os
parent_folder_path = 'somepath/parent_folder'
for eachFile in os.listdir(parent_folder_path):
    if eachFile.endswith('.xml'):
       newfilePath = parent_folder_path+'/'+eachFile
       file = open(newfilePath, 'r')
       xml = file.read()
       file.close()
       xml = xml.replace('thing to replace', 'with content')
       file = open(newfilePath, 'w')
       file.write(str(xml))
       file.close()

rawDescription: multiple search and replace in python

description: Multiple search and replace in python


code: np.maximum(x, 0)

rawDescription: How to compute the maximum between an array and a number element by element?

description: Compute the maximum between an array and a number element by element


code:
#! /usr/bin/env python

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

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
z = np.random.rand(N)

# point's to join
p1 = 10
p2 = 20

fig = plt.figure()

# a background axis to draw lines on
ax0 = plt.axes([0.,0.,1.,1.])
ax0.set_xlim(0,1)
ax0.set_ylim(0,1)

# use these to know how to transform the screen coords
dpi = ax0.figure.get_dpi()
height = ax0.figure.get_figheight() * dpi
width = ax0.figure.get_figwidth() * dpi

# first scatter plot
ax1 = plt.axes([0.05,0.05,0.9,0.425], projection='3d')
ax1.scatter(x, y, z)

# one point of interest
ax1.scatter(x[p1], y[p1], z[p1], s=100.)
x1, y1, _ = proj3d.proj_transform(x[p1], y[p1], z[p1], ax1.get_proj())
[x1,y1] = ax1.transData.transform((x1, y1))  # convert 2d space to screen space
# put them in screen space relative to ax0
x1 = x1/width
y1 = y1/height

# second scatter plot (same data)
ax2 = plt.axes([0.05,0.475,0.9,0.425], projection='3d')
ax2.scatter(x, y, z)

# another point of interest
ax2.scatter(x[p2], y[p2], z[p2], s=100.)
x2, y2, _ = proj3d.proj_transform(x[p2], y[p2], z[p2], ax2.get_proj())
[x2,y2] = ax2.transData.transform((x2, y2))  # convert 2d space to screen space
x2 = x2/width
y2 = y2/height

# set all these guys to invisible (needed?, smartest way?)
for item in [fig, ax1, ax2]:
    item.patch.set_visible(False)

# draw a line between the transformed points
# again, needed? I know it works...

transFigure = fig.transFigure.inverted()

coord1 = transFigure.transform(ax0.transData.transform([x1,y1]))
coord2 = transFigure.transform(ax0.transData.transform([x2,y2]))

line = matplotlib.lines.Line2D((coord1[0],coord2[0]),(coord1[1],coord2[1]),
                               transform=fig.transFigure)
fig.lines = line,

plt.show()

rawDescription: matplotlib ConnectionPatch for 3D subplots

description: Matplotlib ConnectionPatch for 3D subplots


code:
s = 'x\t1\ny\t2\nz\t3'
dd = dict(ss.split('\t') for ss in s.split('\n'))
dd

rawDescription: Convert a string with 2-tier delimiters into a dictionary - python


code:
def check(FF=FlowGraph, GG=FlowGraph):
    if FF.I != GG.I or FF.O !=  GG.O:
        return False
    for u in FF.I:
        reachF = { v for v in nx.dfs_preorder_nodes(FF,u) if v in FF.O }
        reachG = { v for v in nx.dfs_preorder_nodes(GG,u) if v in GG.O }
        if not reachF <= reachG:
            return False
    return True

rawDescription: Checking flow in graphs

description: Checking flow in graphs


code:
import config

def send_message(mailgunkey=None):
    """
    send an email
    """
    if mailgunkey is None:
        mailgunkey = config.MAILGUNKEY

rawDescription: Sphinx revealing my (mailgun) password

description: Sphinx revealing my (mailgun) password


code:
VSVersionInfo(
  ffi=FixedFileInfo(
    filevers=(6, 1, 7601, 17514),
    prodvers=(6, 1, 7601, 17514),
    mask=0x3f,
    flags=0x0,
    OS=0x40004,
    fileType=0x1,
    subtype=0x0,
    date=(0, 0)
    ),
  kids=[
    StringFileInfo(
      [
      StringTable(
        u'040904B0',
        [StringStruct(u'CompanyName', u'Microsoft Corporation'),
        StringStruct(u'FileDescription', u'Windows Command Processor'),
        StringStruct(u'FileVersion', u'6.1.7601.17514 (win7sp1_rtm.101119-1850)'),
        StringStruct(u'InternalName', u'cmd'),
        StringStruct(u'LegalCopyright', u'\xa9 Microsoft Corporation. All rights reserved.'),
        StringStruct(u'OriginalFilename', u'Cmd.Exe'),
        StringStruct(u'ProductName', u'Microsoft\xae Windows\xae Operating System'),
        StringStruct(u'ProductVersion', u'6.1.7601.17514')])
      ]),
    VarFileInfo([VarStruct(u'Translation', [1033, 1200])])
  ]
)

rawDescription: What does a "version file" look like?

description: What does a "version file" look like


code:
import win32clipboard as clipboard

def toClipboardForExcel(array):
    """
    Copies an array into a string format acceptable by Excel.
    Columns separated by \t, rows separated by \n
    """
    # Create string from array
    line_strings = []
    for line in array:
        line_strings.append("\t".join(line.astype(str)).replace("\n",""))
    array_string = "\r\n".join(line_strings)

    # Put string into clipboard (open, clear, set, close)
    clipboard.OpenClipboard()
    clipboard.EmptyClipboard()
    clipboard.SetClipboardText(array_string)
    clipboard.CloseClipboard()

rawDescription: How to paste a Numpy array to Excel

description: Paste a Numpy array to Excel


code:
from PIL import Image

def find_rows_with_color(pixels, width, height, color):
    rows_found=[]
    for y in xrange(height):
        for x in xrange(width):
            if pixels[x, y] != color:
                break
        else:
            rows_found.append(y)
    return rows_found

old_im = Image.open("path/to/old/image.png")
if old_im.mode != 'RGB':
    old_im = old_im.convert('RGB')
pixels = old_im.load()
width, height = old_im.size[0], old_im.size[1]
rows_to_remove = find_rows_with_color(pixels, width, height, (0, 0, 0)) #Remove black rows
new_im = Image.new('RGB', (width, height - len(rows_to_remove)))
pixels_new = new_im.load()
rows_removed = 0
for y in xrange(old_im.size[1]):
    if y not in rows_to_remove:
        for x in xrange(new_im.size[0]):
            pixels_new[x, y - rows_removed] = pixels[x, y]
    else:
        rows_removed += 1
new_im.save("path/to/new/image.png")

rawDescription: Using PIL or a Numpy array, how can I remove entire rows from an image?


code:
import random
import uuid
outfile = 'data.csv'
outsize = 1024 * 1024 * 1024 # 1GB
with open(outfile, 'ab') as csvfile:
    size = 0
    while size < outsize:
        txt = '%s,%.6f,%.6f,%i\n' % (uuid.uuid4(), random.random()*50, random.random()*50, random.randrange(1000))
        size += len(txt)
        csvfile.write(txt)

rawDescription: Fastest way to write large CSV with Python


code:
if 'Met' not in df:
    df['Met'] = df['freqC'] * df['coverage']

rawDescription: Pandas: Add column if does not exists

description: Pandas: Add column if does not exists


code:
f = StringIO('''\
<element name="a" xmlns="http://relaxng.org/ns/structure/1.0">
 <zeroOrMore>
    <element name="b">
      <text />
    </element>
 </zeroOrMore>
</element>
''')
relaxng_doc = etree.parse(f)
relaxng = etree.RelaxNG(relaxng_doc)
valid = StringIO('')
doc = etree.parse(valid)
relaxng.validate(doc)
invalid = StringIO('<c></c>')
doc2 = etree.parse(invalid)
relaxng.validate(doc2)

rawDescription: How do I validate XML document using RELAX NG schema in Python?

description: Validate XML document using RELAX NG schema in Python


rawDescription: Python - Get Yesterday's date as a string in YYYY-MM-DD format


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup(html_doc)
page_images = [image["src"] for image in soup.findAll("img")]

rawDescription: regex find <img src='url' /> in html

description: Regex find <img src='url' /> in html


code:
import csv
with open('EstonianExports2011.csv', 'rb')as f:
    archive = list(csv.reader(f, delimiter=','))[1:11] # get lines 1 to 10
    arch_dict = {row[2]: float(row[3].strip("$").replace(",","")) for row in archive}

arch_dict
{'Rubber Tires': 242977533.7, 'Cars': 371092090.84, 'Vehicle Parts': 241059109.78, 'Insulated Wire': 319352873.32, 'Scrap Iron': 331463406.48, 'Telephones': 2823450843.6, 'Sawn Wood': 238358904.17, 'Large Construction Vehicles': 239589588.65, 'Wood Carpentry': 237521163.59, 'Refined Petroleum': 2124413818.52}

In [2]: s = "$213,137,606.81"

In [3]: s.strip("$") # strips from the ends of a string
Out[3]: '213,137,606.81'

In [5]: s.strip("$").replace(",","") # combine with replace to remove the commas
Out[5]: '213137606.81'

rawDescription: CSV to dictionary

description: CSV to dictionary


code:
d = dict( A = np.array([1,2]), B = np.array([1,2,3,4]) )
DataFrame(dict([ (k,Series(v)) for k,v in d.iteritems() ]))

rawDescription: Creating dataframe from a dictionary where entries have different lengths


code:
import numpy as np
a = np.array([-2,4,3,-1,2])
positive_indicator = np.int64(a > 0)

rawDescription: Converting an array to positive indicator


code: name = models.CharField(max_length=200, verbose_name="Nom")

rawDescription: Change field name in django admin

description: Change field name in django admin


code:
if ans in ['yes', 'YES', 'y', 'Y']:
    print('ok')
else:
    print('no')

rawDescription: how to simplify if statement yes

description: Simplify if statement yes


code:
colours = {"black": "000",
           "red": "f00",
           "green": "0f0",
           "yellow": "ff0",
           "blue": "00f",
           "magenta": "f0f",
           "cyan": "0ff",
           "white": "fff"}

class MyString(str):
    pass

for name, code in colours.iteritems():
    def _in_colour(self, code=code):
        return '%s' % (code, self)
    setattr(MyString, "in_" + name, _in_colour)

rawDescription: Python's equivalent for Ruby's define_method?


code: sorted(map(lambda x: [x[0], int(x[1])], scoresave), key=lambda x: x[1])

rawDescription: How to convert nested list strings to integers then sort them in python 3?

description: Convert nested list strings to integers then sort them in python 3


code:
for i in range(2**8):
    with open("test" + str(i) + ".bin", "wb") as f:
        f.write(chr(i))

rawDescription: Using python to write hex to file

description: Using python to write hex to file


code:
import sys
from PyKDE4.kdecore import ki18n, KAboutData, KCmdLineArgs
from PyKDE4.kdecore import KLibLoader as ll
from PyKDE4.kdeui import KApplication
import PyKDE4.kparts as kp

appName     = "KApplication"
catalog     = ""
programName = ki18n ("KApplication")
version     = "1.0"
description = ki18n ("KApplication")
license     = KAboutData.License_GPL
copyright   = ki18n ("(c) 2007 John Doe")
text        = ki18n ("none")
homePage    = "www.johndoe.com"
bugEmail    = "johndoe@nowhere.com "

aboutData   = KAboutData(
    appName, catalog, programName, version, description,
    license, copyright, text, homePage, bugEmail
)

KCmdLineArgs.init( sys.argv, aboutData)

app = KApplication()
win= kp.KParts.MainWindow()
okupart= ll.self().factory( 'okularpart').create()
win.setCentralWidget( okupart.widget())
win.show()

app.exec_()

rawDescription: How to use KDE Okular's document view widget in a Python Qt app?

description: Use KDE Okular's document view widget in a Python Qt app


code:
import socket,os,threading,subprocess

class mysocket(socket.socket):

    def __init__(self,*arg, **kw):
        super(mysocket,self).__init__(*arg, **kw)
        self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    def read(self):
        return self.recv(2048)

    def write(self,data):
        self.send(data)

    def accept(self):
        conn,addr = super(mysocket,self).accept()
        return mysocket(_sock=conn),addr

socket.socket = mysocket

import SocketServer

class RequestHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        subprocess.call('script -q -f -c "bash -i" /dev/null',shell=True,env=os.environ,stdin=self.request,stdout=self.request,stderr=self.request)

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    pass

if __name__ == '__main__':
    address = ('0.0.0.0', 2000)
    server = ThreadedTCPServer(address, RequestHandler)
    server.serve_forever()

rawDescription: Main Python Process is stopped using subprocess calls in SocketServer


code:
while abs(testBal) > .001:
    month = 0
    testBal = balance
    ans = (high + low)/2
    while month < 12:
        ...

rawDescription: Infinite Loop with while function and I can't debug it


code:
def ClearText123(self, event):
    if self.Savings_TermYears.GetValue() == 'Years': # if the control isn't blank, clear it
        self.Savings_TermYears.Clear()
        self.Savings_TermYears.Unbind(wx.EVT_LEFT_DOWN)
    self.Savings_TermYears.SetFocus()

rawDescription: wxPython TextCtrl Not Focusing After using Remove() or Clear()

description: WxPython TextCtrl Not Focusing After using Remove() or Clear()


rawDescription: Getting a previous value Pandas

description: Getting a previous value Pandas


code:
from distutils.core import setup

setup(
    name='somemodule',
    scripts=['mymodule']
)

rawDescription: How to make a Python script runs as trivial linux command with Distutils?

description: Make a Python script runs as trivial linux command with Distutils


code:
@subscriber(NewRequest)
def mysubscriber(event):
    event.request.foo = 1
    # log an event based on the route and the user

rawDescription: Record last activity of a logged in user in Pyramid


code:
class B():
    def __init__(self):
        self.x = None
    def fun(self):
        print("Assigning value to attribute of object of class B.\n")
        self.x = "Value of B object's attribute"
class A():
    def __init__(self):
        self.value = B()
    def fun(self):
        print("Screw this, I'll do something else this time!\n")
        self.value.x = 13
    def override(self):
        # Edit: you can assign any identifier (that is not reserved) to
        # any type of object or method AND the "fun" ("really self.fun")
        # above is visible from here, since we passed "self" as an
        # argument
        self.value.fun = self.fun

myObj = B()
myOtherObj = A()
myOtherObj.override()

myObj.fun()
myOtherObj.value.fun()

rawDescription: How to override a method of a member object?

description: Override a method of a member object


code:
stringtosplit = 'hello57world'
letters = []
numbers = []
for k in stringtosplit:
    if k.isalpha() == True:
        letters.append(k)
    elif k.isdigit() == True:
        numbers.append(k)

letters
numbers
letters = ''.join(letters)
numbers = ''.join(numbers)
letters
numbers

rawDescription: Splitting a string into a two separate lists of numbers and letters -python


code:
for column in array.T:
   some_function(column)

rawDescription: Numpy how to iterate over columns of array?


rawDescription: How to join specific key in list in Python?

description: Join specific key in list in Python


code:
import sys

sys.stdout.write ('some stuff')

rawDescription: Python: Prevent fileinput from adding newline characters


code:
benchmark=[]
with open('test.csv','r') as inp:
    csvin=csv.reader(inp)
    for row in csvin:
        benchmark.append(row[:1] + [float(row[1])] + row[2:])

rawDescription: Looping Through Nested List - Convert from String to Float


rawDescription: Django: Is it possible to achieve the same thing as sql's exists?


code:
from __future__ import print_function
import time
import sys

print(".", end="\r")
sys.stdout.flush()
time.sleep(1)
print("..", end="\r")
sys.stdout.flush()
time.sleep(1)
print("...")
sys.stdout.flush()

rawDescription: Change text on same CLI line Python

description: Change text on same CLI line Python


code:
@view_config(route_name='main', renderer='main.mako')
def main_view(request):
    return {}

@view_config(route_name='login', renderer='login.mako')
def login_view(request):
    login = request.params.get('login')
    password = request.params.get('password')
    if request.method == 'POST':
        if login and USERS.get(login) == password:
            headers = remember(request, login)
            return HTTPFound('/', headers=headers)
    return {}

@view_config(route_name='logout')
def logout(request):
    headers = forget(request)
    return HTTPFound(location='/', headers=headers)

if __name__ == '__main__':
    # configuration settings
    settings = {}
    settings['mako.directories'] = os.path.join(here, 'templates')
    authn_policy = AuthTktAuthenticationPolicy('sosecret', hashalg='sha512')
    authz_policy = ACLAuthorizationPolicy()
    config = Configurator(settings=settings)
    config.include('pyramid_mako')
    config.add_static_view('static', os.path.join(here, 'static'))
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)
    config.add_route('main', '/')
    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.scan()
    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 8080, app)
    server.serve_forever()

rawDescription: How do I set up a simple login system in pyramid?

description: Set up a simple login system in pyramid


rawDescription: pandas 0.13 read_excel new format

description: Pandas 0.13 read_excel new format


code:
import glob
for file in glob.iglob("*.html"):
    with open(file) as f:
        a = f.read()

rawDescription: Python fastest way to read a large number of small files into memory?


caption: SublimeREPL

mnemonic: r

caption: Python

caption: IPython - Anaconda

mnemonic: p

type: subprocess

external_id: python

rawDescription: SublimeREPL and IPython

description: SublimeREPL and IPython


code:
name = input("what is your name?")
if name in ("Kamran", "Samaneh"):
    print("That is a nice name")
else:
    print("You have a boring name ;)")

rawDescription: What's the logical value of "string" in Python?


rawDescription: Python: subtract lists in a list while iteration


code:
for file_name in os.listdir('path/to/modules'):
    if file_name.startswith('.') or not file_name.ends_with('.py'):
        continue
    module_name = file_name[:-3]
    module = __import__(module_name)
    module.some_function()

rawDescription: How to call a function from every module in a directory in Python?

description: Call a function from every module in a directory in Python


code:
def print(*line, sep=' ', end='\n', file=None, default = 'full'):
    '''If file is None, defaults to sys.stdout.'''

    if file is None:
        file = sys.stdout

rawDescription: pydoc generated help-text with file handle parameters

description: Pydoc generated help-text with file handle parameters


code:
row = 'Apple Pear Orange Cracker Honey Cheese Grape Bread Tomato 5/11/13'.split()
assert row[6] == 'Grape'  # This is the 7th column in your sample
assert row[7] == 'Bread'  # This is the column you were getting

date = row[9]
assert date == '5/11/13'

parts = date.split('/')
assert parts == ['5', '11', '13']
MM = int(parts[0])
assert MM == 5

# Doesn't matter if there's more digits
assert int('27/11/13'.split('/')[0]) == 27

rawDescription: Filter only the month from date column before the slash


rawDescription: Python convert string in array

description: Python convert string in array


code:
from urllib import urlencode
import requests
params = {'search': '7420 Westlake Ter #1210 20817'}
search_url = 'http://www.trulia.com/submit_search/?'
url = search_url + urlencode(params)
r = requests.get(url)
# now you get your desired response.

rawDescription: use python requests library to post data to search box

description: Use python requests library to post data to search box


code:
from PyQt4 import QtCore, QtGui

class CheckableComboBox(QtGui.QComboBox):
    def __init__(self, parent=None):
        super(CheckableComboBox, self).__init__(parent)
        self.view().pressed.connect(self.handleItemPressed)
        self._changed = False

    def handleItemPressed(self, index):
        item = self.model().itemFromIndex(index)
        if item.checkState() == QtCore.Qt.Checked:
            item.setCheckState(QtCore.Qt.Unchecked)
        else:
            item.setCheckState(QtCore.Qt.Checked)
        self._changed = True

    def hidePopup(self):
        if not self._changed:
            super(CheckableComboBox, self).hidePopup()
        self._changed = False

    def itemChecked(self, index):
        item = self.model().item(index, self.modelColumn())
        return item.checkState() == QtCore.Qt.Checked

    def setItemChecked(self, index, checked=True):
        item = self.model().item(index, self.modelColumn())
        if checked:
            item.setCheckState(QtCore.Qt.Checked)
        else:
            item.setCheckState(QtCore.Qt.Unchecked)

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.combo = CheckableComboBox(self)
        for index in range(6):
            self.combo.addItem('Item %d' % index)
            self.combo.setItemChecked(index, False)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.combo)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 200, 100)
    window.show()
    sys.exit(app.exec_())

rawDescription: PyQt: How to keep ComboBox open while selecting items


code:
payload = {
   'username': 'your username',
   'password': 'your password'
   }
p = requests.post(myurl, data=payload)

rawDescription: Python urllib2 response 404 error but url can be opened


code:
import tkinter as tk
import sys

class App(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        menubar = tk.Menu(self)
        fileMenu = tk.Menu(menubar, tearoff=False)
        menubar.add_cascade(label="File", underline=0, menu=fileMenu)
        fileMenu.add_command(label="Exit", underline=1,
                             command=quit, accelerator="Ctrl+Q")
        self.config(menu=menubar)

        self.bind_all("<Control-q>", self.quit)

    def quit(self, event):
        print("quitting...")
        sys.exit(0)

if __name__ == "__main__":
    app = App()
    app.mainloop()

rawDescription: Tkinter dropdown Menu with keyboard shortcuts?


code:
def karatsuba(x, y):
    if x < 10 or y < 10:
        return x * y
    # get longest digits
    n = max(math.log10(x) + 1, math.log10(y) + 1)
    # catch where n is odd
    n -= n % 2
    bn = B ** (n // 2)
    x1, x2 = divmod(x, bn)
    y1, y2 = divmod(y, bn)
    ac = karatsuba(x1, y1)
    bd = karatsuba(x2, y2)
    # caluclate a+b and c + d subtracting already
    # calculated ac and bd leaving ad + bc
    adbc = karatsuba(x1 + x2, y1 + y2) - ac - bd
    # x . y = 10 ^ n ac + 10^n/2 (ad + bc) + bd
    return ((B ** n) * ac) + bn * adbc + bd

res = karatsuba(x, y)

print('%d * %d = %d' % (x, y, res))

rawDescription: Implementing Karatsubas Multiplication Algorithm in Python


code:
d = {'level':2, 'position':[2,3]}
import json
json.dumps(d) # or json.dump(d, save) in your code

rawDescription: retrieving string from file in python and changing tuples

description: Retrieving string from file in python and changing tuples


code:
start = r'C:\Users'
entries = []
for path, filenames, dirnames in os.walk(start):
    relative = os.path.relpath(path, start)
    depth = len(os.path.split(os.pathsep))
    entries.extend([('\t' * depth) + f for f in filenames])
with open("List.txt", "w") as output:
    output.write('\n'.join(entries))

rawDescription: Generating a list of files

description: Generating a list of files


code:
import csv

with open('myfile.csv', 'rb') as inf:
    incsv = csv.reader(inf)
    column = 1                # the second column (Python counts from 0, per @MRAB's comment)
    datatype = float          # or int, as appropriate (per MvG)
    data = (datatype(row[column]) for row in incsv)    # NB: a generator expression, not a list
    least_value = min(data)

rawDescription: Python code to find minimum column value with a 15000 line data set


code:
import operator
names = [...]
query = reduce(operator.or_, [Q(name__icontains=name) for name in names])
results = queryset.complex_filter(query)

rawDescription: Creating dynamic objects with | separator python


code:
def rect_to_polar_input(x, y):
    hypotenuse = math.hypot(x, y)
    angle = round(math.degrees(math.atan2(y, x)))
    if angle<0:
        angle += 360
    return hypotenuse, angle

rawDescription: Basic trig: math.atan() issue

description: Basic trig: math.atan() issue


code:
class AnonymousPostAuthentication(BasicAuthentication):
    """ No auth on post / for user creation """

    def is_authenticated(self, request, **kwargs):
        """ If POST, don't check auth, otherwise fall back to parent """

        if request.method == "POST":
            return True
        else:
            return super(AnonymousPostAuthentication, self).is_authenticated(request, **kwargs)

rawDescription: Tastypie : Authentication for GET and Anonymous for POST


code:
my_time = my_tedit.dateTime()
my_time = my_time.toPyDateTime()

rawDescription: pyqt how to get python timestamp from QDateTimeEdit

description: Pyqt how to get python timestamp from QDateTimeEdit


code:
# Allow the image to have its alpha value changed
image = pygame.image.load("Images/dead.jpg").convert()

# Set the transparency to full
image_alpha = 0

# Decide how many frames you want the image to fade in over
fade_frame_number = 60
# And the frames per second
FPS = 30
FPS_Clock = pygame.time.Clock()

while True:
    window.fill((255, 255, 255))               # Fill the window with a white bg
    if image_alpha < 255:
        image_alpha += 255 / fade_frame_number # Change the transparency variable
    image.set_alpha(image_alpha)               # Set the image's alpha value
    window.blit(image, (0, 0))                 # Display the image
    pygame.display.update()                    # Update the screen
    FPS_Clock.tick(FPS)                        # Wait for the next frame

rawDescription: How do you make an image transparent over a period of time?

description: Make an image transparent over a period of time


rawDescription: best way ( short hand) adding column and row to numpy array

description: Best way ( short hand) adding column and row to numpy array


code:
from Tkinter import *

class Interface():
        def __init__(self, window):
            frame = Frame(window)
            frame.pack()

            self.hopLabel = Label(frame, text="Hop:", anchor=E)
            self.hopLabel.grid(row=0, column=0, sticky=EW)

            hops = range(0,6)
            hops.append("Other")

            self.selectedHop = StringVar(frame)
            self.selectedHop.set(hops[0])
            self.hopOptions = OptionMenu(frame, self.selectedHop, *hops, command=self.optupdate)
            self.hopOptions.grid(row=0, column=2, sticky=EW)

            self.otherEntry = Entry(frame, state=DISABLED)
            self.otherEntry.grid(row=0, column=1, sticky=EW)

        def optupdate(self, value):
            if value == "Other":
                self.otherEntry.config(state=NORMAL)
            else:
                self.otherEntry.config(state=DISABLED)

if __name__ == "__main__":
    root = Tk()
    app = Interface(root)
    root.mainloop()

rawDescription: Check what tkinter OptionMenu item was selected


code:
x = arange(1,5,0.01)
yarr = vstack((x,))
y = sin(x)

imshow(yarr, extent=(min(x),max(x), min(y),max(y)), cmap=cm.hot)
plot(x, y, color='cornflowerblue',lw=4)

rawDescription: Shade the background of matplotlib based on array and colormap


rawDescription: Selenium locate submit button

description: Selenium locate submit button


code:
import numpy as np
import soundfile as sf

rms = [np.sqrt(np.mean(block**2)) for block in
sf.blocks('myfile.wav', blocksize=1024, overlap=512)]

rawDescription: How to read a wave file block by block in python (compatible with numpy array)?

description: Read a wave file block by block in python (compatible with numpy array)


code:
import matplotlib.pyplot as plt

x = range(-2,3)
xi = -1

plt.plot(x,x)
plt.annotate('as expected',
            xy=(1, 1), xycoords='data',
            xytext=(.5, .8), textcoords='axes fraction',
            arrowprops=dict(arrowstyle='-'))
plt.annotate('why am i here?',
            xy=(xi, 0.5), xycoords='data',
            xytext=(-.5, .8), textcoords='axes fraction',
            arrowprops=dict(arrowstyle='-'))

plt.show()

rawDescription: Why does the text leave the axes if the x coordinate is negative?


code:
def aProcedure(cursor, arg1, arg2):
    cursor.execute("CALL A_PROCEDURE(%s, %s)", (arg1, arg2))
    return cursor.fetchall()

d = dbpool.runInteraction(aProcedure, arg1, arg2)
...

rawDescription: Calling MySQL stored procedure with Twisted adbapi


code:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'tester',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': 'password',                  # Not used with sqlite3.
        'HOST': '127.0.0.1',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    }
}

rawDescription: MySQL for Python on Windows via Xampp

description: MySQL for Python on Windows via Xampp


code:
def primes(limit):
    a = [True] * limit
    a[0] = a[1] = False
    primes = []

    for (i, isprime) in enumerate(a):
        if isprime:
            primes.append(i)
            for n in range(i*i, limit, i):
                a[n] = False

    return primes

rawDescription: Python function returns generator instead of list


code:
from itertools import product
pd.DataFrame(list(product(l1, l2)), columns=['l1', 'l2'])

rawDescription: Get get all combinations of elements from two lists?


code:
def make_msg_dict(part):
    return {
        'error': ' Please insert a valid (%s) name' % part,
        'required': ' Please insert your (%s) name' % part,
    }
d1 = make_msg_dict('first')
d2 = make_msg_dict('last')
d1
d2

rawDescription: Format some strings which are inside a dictionary


code: re.search(r"\((?P<remixer>[^)]+) (Remix)\)", "Title (Blabla) (Menda Remix)")

rawDescription: Last matching symbol in Regex

description: Last matching symbol in Regex


code: any((ob is contained_ob or ob == contained_ob) for contained_ob in some_sequence)

rawDescription: What are the mechanics of the in operator for lists or hashes of classes in Python?


code:
from PyQt4 import QtCore, QtGui, QtNetwork

class Window(QtGui.QWidget):
    def __init__(self, address):
        QtGui.QWidget.__init__(self)
        self.address = address
        self.table = QtGui.QTableWidget(self)
        header = self.table.horizontalHeader()
        header.setStretchLastSection(True)
        header.hide()
        self.table.setColumnCount(2)
        self.button = QtGui.QPushButton('Add Upload', self)
        self.button.clicked.connect(self.handleAddUpload)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.table)
        layout.addWidget(self.button)
        self.netaccess = QtNetwork.QNetworkAccessManager(self)
        self._uploaders = {}

    def handleAddUpload(self):
        stream = QtCore.QFile('files/sample.tar.bz2')
        if stream.open(QtCore.QIODevice.ReadOnly):
            data = stream.readAll()
            stream.close()
            row = self.table.rowCount()
            button = QtGui.QPushButton('Abort', self.table)
            button.clicked.connect(lambda: self.handleAbort(row))
            progress = QtGui.QProgressBar(self.table)
            progress.setRange(0, len(data))
            self.table.setRowCount(row + 1)
            self.table.setCellWidget(row, 0, button)
            self.table.setCellWidget(row, 1, progress)
            uploader = self._uploaders[row] = Uploader(row, self.netaccess)
            uploader.uploadProgress.connect(self.handleUploadProgress)
            uploader.uploadFinished.connect(self.handleUploadFinished)
            uploader.upload(data, self.address)

    def handleUploadProgress(self, key, sent, total):
        print('upload(%d): %d [%d]' % (key, sent, total))
        progress = self.table.cellWidget(key, 1)
        progress.setValue(sent)

    def handleUploadFinished(self, key):
        print('upload(%d) finished' % key)
        button = self.table.cellWidget(key, 0)
        button.setDisabled(True)
        uploader = self._uploaders.pop(key)
        uploader.deleteLater()

    def handleAbort(self, key):
        try:
            self._uploaders[key].abort()
        except (KeyError, AttributeError):
            pass

class Uploader(QtCore.QObject):
    uploadProgress = QtCore.pyqtSignal(object, int, int)
    uploadFinished = QtCore.pyqtSignal(object)

    def __init__(self, key, parent):
        QtCore.QObject.__init__(self, parent)
        self._key = key
        self._reply = None

    def abort(self):
        if self._reply is not None:
            self._reply.abort()

    def upload(self, data, url):
        if self._reply is None:
            request = QtNetwork.QNetworkRequest(QtCore.QUrl(url))
            request.setHeader(
                QtNetwork.QNetworkRequest.ContentTypeHeader,
                'application/x-www-form-urlencoded')
            self._reply = self.parent().post(request, data)
            self._reply.uploadProgress.connect(self.handleUploadProgress)
            self._reply.finished.connect(self.handleFinished)

    def handleUploadProgress(self, sent, total):
        self.uploadProgress.emit(self._key, sent, total)
        if sent >= total:
            # prevent duplicated uploads
            self._reply.close()

    def handleFinished(self):
        self._reply.deleteLater()
        self._reply = None
        self.uploadFinished.emit(self._key)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window('http://localhost:54321/upload')
    window.setGeometry(500, 300, 500, 300)
    window.show()
    sys.exit(app.exec_())

rawDescription: How to get each Process ID when multiprocessing

description: Get each Process ID when multiprocessing


code:
import os
import threading
import tornado.options
import tornado.ioloop
import tornado.httpserver
import tornado.httpclient
import tornado.web
from tornado import gen
from tornado.web import asynchronous

tornado.options.define('port', type=int, default=9000, help='server port number (default: 9000)')
tornado.options.define('debug', type=bool, default=False, help='run in debug mode with autoreload (default: False)')

class Worker(threading.Thread):
   def __init__(self, callback=None, *args, **kwargs):
        super(Worker, self).__init__(*args, **kwargs)
        self.callback = callback

   def run(self):
        import time
        time.sleep(10)
        self.callback('DONE')

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", IndexHandler),
            (r"/thread", ThreadHandler),
        ]
        settings = dict(
            static_path = os.path.join(os.path.dirname(__file__), "static"),
            template_path = os.path.join(os.path.dirname(__file__), "templates"),
            debug = tornado.options.options.debug,
        )
        tornado.web.Application.__init__(self, handlers, **settings)

class IndexHandler(tornado.web.RequestHandler):
    client = tornado.httpclient.AsyncHTTPClient()

    @asynchronous
    @gen.engine
    def get(self):
        response = yield gen.Task(self.client.fetch, "http://google.com")

        self.finish("Google's homepage is %d bytes long" % len(response.body))

class ThreadHandler(tornado.web.RequestHandler):
    @asynchronous
    def get(self):
        Worker(self.worker_done).start()

    def worker_done(self, value):
        self.finish(value)

def main():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(tornado.options.options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()

rawDescription: Tornado blocking asynchronous requests

description: Tornado blocking asynchronous requests


code:
eventDict={}
for e in eventlist:
     eventdict[e.id]=e.flag if e.flag is not None else eventDict[e.id]
compressed = [Event(k, None, v) for k,v in eventdict.items()]

rawDescription: Compress list of objects by matching attribute in Python


code:
profile.set_preference('browser.helperApps.neverAsk.saveToDisk',
                   'image/jpeg,image/png,'
                   'application/octet-stream')

rawDescription: using Selenium, Firefox, Python to save download of EPS files to disk after automated clicking of download link

description: Using Selenium, Firefox, Python to save download of EPS files to disk after automated clicking of download link


code:
mongo_conn.Tags.insert({
    "key": 12345,
    "tags": ["foo","bar","foobar"]
})

rawDescription: adding a list field in mongo (python)

description: Adding a list field in mongo (python)


code: l.append({key:value for key, value in zip(['A', 'B'], t)})

rawDescription: Conditional dictionary explicit initialization


code:
#!/usr/bin/env python3
import gc
import socket
import unittest
import warnings

class Test(unittest.TestCase):
    def test_resource_warning(self):
        s = socket.socket()
        ####s.close() #XXX uncomment to pass the test

        # generate resource warning when s is deleted
        with warnings.catch_warnings(record=True) as w:
            warnings.resetwarnings() # clear all filters
            warnings.simplefilter('ignore') # ignore all
            warnings.simplefilter('always', ResourceWarning) # add filter
            del s        # remove reference
            gc.collect() # run garbage collection (for pypy3)
            self.assertFalse(w and str(w[-1])) # test fails if there
                                               # are warnings

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

rawDescription: Convert Python 3 ResourceWarnings into exception


code:
from django.conf.urls import patterns

urlpatterns = patterns('',
    (r'^$', 'cms.views.your_view')
)

urlpatterns += i18n_patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': {'cmspages': CMSSitemap}}),
    url(r'^', include('cms.urls')),
)

rawDescription: DjangoCMS multilingual site (i18n) and intro page


code:
daily_price_df = daily_price_df.fillna(method='pad', limit=8)
OR
daily_price_df.fillna(method='pad', limit=8, inplace=True)

rawDescription: Filling data using .fillNA(), data pulled from Quandl


rawDescription: How to convert a part of list string values to integer in python?

description: Convert a part of list string values to integer in python


code:
# factorial :: Int -> Int
def factorial(n):
    return product(down(n))

# product :: [Int] -> Int
def product(arr):
    if len(arr) == 0: return 1
    a, ar = arr[0], arr[1:]
    return a * product(ar)

# down :: Int -> [Int]
def down(n):
    if n == 0: return []
    return [n] + down(n - 1)

rawDescription: Haskell to Python: multiple-functions conversion issue


code:
def getshape(d):
    if isinstance(d, dict):
        return {k:getshape(d[k]) for k in d}
    else:
        # Replace all non-dict values with None.
        return None

def shape_equal(d1, d2):
    return getshape(d1) == getshape(d2)

rawDescription: Check that Python dicts have same shape and keys


code:
line_regex = re.compile('^\((\d+), (\d+), (.+)\)$', re.MULTILINE)
sents_with_positions = []
sents_words = []

for section in _input.split('\n\n'):
    words_with_positions = [
        (int(start), int(end), text)
        for start, end, text in line_regex.findall(section)
    ]
    words = tuple(t[2] for t in words_with_positions)
    sents_with_positions.append(words_with_positions)
    sents_words.append(words)

rawDescription: Unpacking tuple-like textfile

description: Unpacking tuple-like textfile


code:
processed = dict((n, "'%s'" % v if v is not None else 'NULL')
                 for n, v in locals().iteritems())

rawDescription: Python: automated change in variable contents


code:
x = 'http://amz.com/New-Balance-WT910-Trail-Running/dp/B0098FOFCW/ref=zg_bsms_shoes_2'
'/'.join(x.split('/')[:6])
y = 'http://amz.com/New-Balance-WT910-Trail-Running/dp/B0098FOFCW'
'/'.join(y.split('/')[:6])

rawDescription: Strip Some Part Of URL And Save File

description: Strip Some Part Of URL And Save File


code:
import csv
lines =[]
with open(inputFile,'rb') as f:
    for line in csv.reader(f):
        lines.append(line)
def groupUp (lines):
    finalList = []
    for row in lines:
        for i,otherRow in enumerate(finalList):
            if row[0]==otherRow[0]:
                finalList[i] += row[1:]
                break
        else:
            finalList.append(row)
    return finalList

with open(newFile,'wb') as f:
    a = csv.writer(f)
    a.writerows(groupUp(lines))

rawDescription: Python: Transform a CSV with one value per line to multiple values per line with first value as key


rawDescription: Initialize many string variables

description: Initialize many string variables


code:
m = re.match("Duplicate entry '(?P<value>.*)' for key '(?P<key>.*)'", "Duplicate entry 'blah@gmail.com' for key 'email'")
m.group('value')
m.group('key')

rawDescription: Regex that matches anything between ' '

description: Regex that matches anything between ' '


code:
from Tkinter import *

class SplashScreen:

    # some code here

    def __init__(self, master):
        self.master = master
        self.master.title("SplashScreen")

    def destroyMe(self):
        self.master.destroy()

    def destroySplashScreen(self, timeToSleep=0):
        if timeToSleep > 0:
            self.master.after(timeToSleep*1000, self.destroyMe)

    # some other code here

if __name__ == '__main__':
    root = Toplevel()
    mySP = SplashScreen(root)
    #mySP.populateSplashScreen()
    mySP.destroySplashScreen(3)
    root.mainloop()

rawDescription: Invoking destroy() method on window after mainloop in tkinter


code:
# For updating the version!
version = "0.1"

# For game start!
from choice1 import choice1
# insert import functions from checkpoints choices here!

def gamemenu():
    print("Welcome to the RTG!")
    # Starts the game
    print("1. START!")
    # Goes to an earlier checkpoint
    print("2. CHECKPOINTS!")
    # Views the "about' page
    print("3. ABOUT")
    # Shows my website address!
    print("4. INFO ABOUT CREATOR")
    # Exits the game
    print("5. EXIT")

    # The user input!
    option = input("Make your choice, buddy! ") #you missed a closing parenthesis here :D

    if option == "1":
        choice1()
    # elif option == "2":
    # Not added yet
    elif option == "3":
       print("Random Text RPG, version %s" % version)
       print("This is just a random game made by me for fun")
       print("Please dont't take offence :(")
    elif option == "4":
       print("Made by Lightning Bolt.") # there was an extra paren here
    elif option == "5":
       pass #as @Padraic mentioned, there should be no break statement
    else:
       print("ERROR: invalid option")
       menu()

menu()

rawDescription: What is wrong with this piece of code [Python]?


code:
from pylab import *
from matplotlib.widgets import Slider, Button, RadioButtons

ax = subplot(111)
subplots_adjust(left=0.25, bottom=0.25)
t = arange(0.0, 1.0, 0.001)
a0 = 5
f0 = 3
s = a0*sin(2*pi*f0*t)
l, = plot(t,s, lw=2, color='red')
axis([0, 1, -10, 10])

axcolor = 'lightgoldenrodyellow'
axfreq = axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
axamp  = axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)

sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0)
samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)

def update(val):
    amp = samp.val
    freq = sfreq.val
    l.set_ydata(amp*sin(2*pi*freq*t))
    draw()
sfreq.on_changed(update)
samp.on_changed(update)

resetax = axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
def reset(event):
    sfreq.reset()
    samp.reset()
button.on_clicked(reset)

rax = axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor)
radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
def colorfunc(label):
    l.set_color(label)
    draw()
radio.on_clicked(colorfunc)

show()

rawDescription: Interactive matplotlib plot with two sliders


code:
def markOneRead(self, element):

    """Slot to mark an article read"""

    table = self.liste_tables_in_tabs[self.onglets.currentIndex()]
    new = table.model().index(element.row(), 12).data()

    if new == 0:
        return
    else:

        # Save the current line
        line = table.selectionModel().currentIndex().row()
        selected_id = table.selectionModel().selection().indexes()[0].data()

        # Change the data in the model
        table.model().setData(table.model().index(line, 12), 0)

        # Update the view after the model is updated
        self.updateView(selected_id)

def updateView(self, current_item_id=None):

    """Method to update the view after a model change.
    If an item was selected, the item is re-selected"""

    model = self.liste_models_in_tabs[self.onglets.currentIndex()]
    table = self.liste_tables_in_tabs[self.onglets.currentIndex()]
    proxy = self.liste_proxies_in_tabs[self.onglets.currentIndex()]

    if current_item_id is not None:
        selected_id = current_item_id
    else:
        try:
            selected_id = table.selectionModel().selection().indexes()[0].data()
        except IndexError:
            selected_id = None

    try:
        # Try to update the model
        model.setQuery(self.query)
        proxy.setSourceModel(model)
        table.setModel(proxy)
    except AttributeError:
        pass

    if selected_id is not None:
        for index in range(1, model.rowCount() + 1):
            table.selectRow(index)
            if table.selectionModel().selection().indexes()[0].data() == selected_id:
                # If the previously selected item is found, leave
                return
        # If we are still here, the old item wasn't found, so deselect all
        table.clearSelection()

rawDescription: QTableView: update model on the fly and select correct line


code:
import re
re.sub('\nThis.*?ok','',a, flags=re.DOTALL)

rawDescription: Replace all text between 2 strings python


rawDescription: assignment to multiple indirectly addressed variables

description: Assignment to multiple indirectly addressed variables


rawDescription: How do you get a random number from a non-consecutive set?

description: Get a random number from a non-consecutive set


code:
def do_something(event):
    box = event.GetEventObject()
    setting = box.GetValue()
    if setting:
            selectionSEM1.append('Time')
    event.Skip()

cb1.Bind(wx.EVT_CHECKBOX, do_something, cb1)

rawDescription: wxPython checkbox true or false

description: WxPython checkbox true or false


code:
import numpy as np
import matplotlib.pyplot as plt
soa =np.array( [ [0,0,3,2], [0,0,1,1],[0,0,9,9]])
X,Y,U,V = zip(*soa)
plt.figure()
ax = plt.gca()
ax.quiver(X,Y,U,V,angles='xy',scale_units='xy',scale=1)
ax.set_xlim([-1,10])
ax.set_ylim([-1,10])
plt.draw()
plt.show()

rawDescription: How to plot 2d math vectors with matplotlib?

description: Plot 2d math vectors with matplotlib


code:
def runifmain(mainname):
    def deco(clas):
        if mainname == '__main__':
            clas().run()
        return clas
    return deco

@runifmain(__name__)
class B(A):
    [...]

rawDescription: Avoid if __name__ == '__main__' in Python subclasses to be run using function from parent


code:
class categoria(models.Model):
    nomeCategoria = models.CharField(max_length=50)
    imagemCategoria = models.CharField(max_length=200)

    def __str__(self):
       return self.nomeCategoria

class post(models.Model):
    tituloPost = models.CharField(max_length=200,default='tituloPost')
    textoPost = models.TextField()
    textoTagPost = models.TextField()
    categoria = models.ForeignKey(categoria)
    enviadoNewsletter = models.BooleanField(default=False)

    def __str__(self):
       return 'Post: ' + self.tituloPost

rawDescription: Show python object name

description: Show python object name


code:
mapping = {'set': 1, 'test': 2}
df.replace({'set': mapping, 'tesst': mapping})

rawDescription: python pandas replacing strings in dataframe with numbers

description: Python pandas replacing strings in dataframe with numbers


code:
class KFold(_BaseKFold):
    """K-Folds cross validation iterator.
    Provides train/test indices to split data in train test sets. Split
    dataset into k consecutive folds (without shuffling).
    Each fold is then used a validation set once while the k - 1 remaining
    fold form the training set.
    Parameters
    ----------
    n : int
        Total number of elements.
    n_folds : int, default=3
        Number of folds. Must be at least 2.
    shuffle : boolean, optional
        Whether to shuffle the data before splitting into batches.
    random_state : None, int or RandomState
        Pseudo-random number generator state used for random
        sampling. If None, use default numpy RNG for shuffling
    Examples
    --------
    >>> from sklearn import cross_validation
    >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
    >>> y = np.array([1, 2, 3, 4])
    >>> kf = cross_validation.KFold(4, n_folds=2)
    >>> len(kf)
    2
    >>> print(kf)  # doctest: +NORMALIZE_WHITESPACE
    sklearn.cross_validation.KFold(n=4, n_folds=2, shuffle=False,
                                   random_state=None)
    >>> for train_index, test_index in kf:
    ...    print("TRAIN:", train_index, "TEST:", test_index)
    ...    X_train, X_test = X[train_index], X[test_index]
    ...    y_train, y_test = y[train_index], y[test_index]
    TRAIN: [2 3] TEST: [0 1]
    TRAIN: [0 1] TEST: [2 3]
    Notes
    -----
    The first n % n_folds folds have size n // n_folds + 1, other folds have
    size n // n_folds.
    See also
    --------
    StratifiedKFold: take label information into account to avoid building
    folds with imbalanced class distributions (for binary or multiclass
    classification tasks).
    """

    def __init__(self, n, n_folds=3, shuffle=False,
                 random_state=None):
        super(KFold, self).__init__(n, n_folds, shuffle, random_state)
        self.idxs = np.arange(n)
        if shuffle:
            rng = check_random_state(self.random_state)
            rng.shuffle(self.idxs)

    def _iter_test_indices(self):
        n = self.n
        n_folds = self.n_folds
        fold_sizes = (n // n_folds) * np.ones(n_folds, dtype=np.int)
        fold_sizes[:n % n_folds] += 1
        current = 0
        for fold_size in fold_sizes:
            start, stop = current, current + fold_size
            yield self.idxs[start:stop]
            current = stop

    def __repr__(self):
        return '%s.%s(n=%i, n_folds=%i, shuffle=%s, random_state=%s)' % (
            self.__class__.__module__,
            self.__class__.__name__,
            self.n,
            self.n_folds,
            self.shuffle,
            self.random_state,
        )

    def __len__(self):
        return self.n_folds

rawDescription: How to look at the source code of scikit learn ML classes?

description: Look at the source code of scikit learn ML classes


code:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('abdk3
The content we need
aaaaabbb
The content we need2
')
soup.h1
soup.h1.text
soup.h2
soup.h2.text

rawDescription: Python regular expression

description: Python regular expression


code:
from http.server import BaseHTTPRequestHandler, HTTPServer, CGIHTTPRequestHandler
from socketserver import ThreadingMixIn
import threading
import cgitb; cgitb.enable()  ## This line enables CGI error reporting
import webbrowser

class HTTPRequestHandler(CGIHTTPRequestHandler):
    """Handle requests in a separate thread."""
    def do_GET(self):
        if "shutdown" in self.path:
            self.send_head()
            print ("shutdown")
            server.stop()
        else:
            self.send_head()

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    allow_reuse_address = True
    daemon_threads = True

    def shutdown(self):
        self.socket.close()
        HTTPServer.shutdown(self)

class SimpleHttpServer():
    def __init__(self, ip, port):
        self.server = ThreadedHTTPServer((ip,port), HTTPRequestHandler)
        self.status = 1

    def start(self):
        self.server_thread = threading.Thread(target=self.server.serve_forever)
        self.server_thread.daemon = True
        self.server_thread.start()

    def waitForThread(self):
        self.server_thread.join()

    def stop(self):
        self.server.shutdown()
        self.waitForThread()

if __name__=='__main__':
    HTTPRequestHandler.cgi_directories = ["/", "/ircapp"]
    server = SimpleHttpServer('localhost', 8020)
    print ('HTTP Server Running...........')
    webbrowser.open_new_tab('http://localhost:8020/ircapp/search.py')
    server.start()
    server.waitForThread()

rawDescription: Python CGI simultaneous AJAX requests

description: Python CGI simultaneous AJAX requests


code:
lst = ['spam', 'eggs', 'ham']
d = {}   # empty dictionary
for name in lst:
    d[name] = rat.readColumn(ratDataset, name)

rawDescription: Python convert string to variable name

description: Python convert string to variable name