code: presents = any(x in string_control for x in item_list)

rawDescription: Python oneline foreach verification in string


code:
@mock.patch('os.path.exists')
def test_vm_exists(self, mock_exists):
    mock_exists.return_value = True
    fake_path = 'fake/path'

    response = self._VixConnection.vm_exists(fake_path)

    mock_exists.assert_called_with(fake_path)
    self.assertEqual(response, True)

rawDescription: Nosetests failing when no file is specified


code:
import random
df
ids = df.ID.unique()
random.shuffle(ids)
n = len(ids)
ids1, ids2 = ids[:n/2], ids[n/2:]
ids1
ids2
df1 = df[df.ID.isin(ids1)]
df2 = df[df.ID.isin(ids2)]
df1
df2

rawDescription: Python how to split a data frame into two equal sized groups based on unique customer IDs?


code:
a = 'November 19th 2015, 12:48:34.402'
time.mktime(datetime.datetime.strptime(a, "%B %d{} %Y, %H:%M:%S.%f".format(a.split()[1][-2:])).timetuple())
a = 'November 23rd 2015, 12:48:34.402'
time.mktime(datetime.datetime.strptime(a, "%B %d{} %Y, %H:%M:%S.%f".format(a.split()[1][-2:])).timetuple())

rawDescription: Time format in python

description: Time format in python


code:
fmt = time_fmt_long if " " in input_string else time_fmt_short
dt = datetime.strptime(input_string, fmt)

rawDescription: Python: parse string as time given two possible formats


code:
contents = []

with open('file') as f:
     for line in f:
         if line.startswith('<start>'):
            pass
         contents.append(line)

contents = "".join(contents)
sections = contents.split("<stop>")

rawDescription: How to iterate over a file in python in a particular way as described below.

description: Iterate over a file in python in a particular way as described below.


code:
cons = ('s', 'x', 'ch', 'sh')
vowels = ('a', 'e', 'i', 'o', 'u')
if not s.endswith(cons + vowels):
    s += 's'
return s

rawDescription: If a string ends in a vowel of the following characters?


code:
from heapq import nlargest

five_largest = nlargest(5, yourdict, key=yourdict.get)

rawDescription: Is there a cleaner way to find the highest 5 values in a dictionary?


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

x = np.arange(6)
y = np.arange(6)

X, Y = np.meshgrid(x, y)

Z = np.random.rand(5, 5)

ax = plt.subplot(111, aspect='equal') # To make the cells square
ax.pcolor(X, Y, Z,
          edgecolor='white',          # Color of "padding" between cells
          linewidth=2)                # Width of "padding" between cells

plt.show()

rawDescription: How to pad adjacency matrix cells in D3.js style?

description: Pad adjacency matrix cells in D3.js style


code:
listofobjs = []
for x in data:
    d = {
      'a_data': x.a,
      'b_data':model_obj.address,
      'c_data':x.c,
      'd_data':x.d,
    }
    listofobjs.append(d)

rawDescription: How to create a dictionary in a for loop in python?

description: Create a dictionary in a for loop in python


rawDescription: Python Regex match so long as there's no character


code:
from PyQt4 import QtCore, QtGui

class FileDialog(QtGui.QFileDialog):
    def __init__(self, *args, **kwargs):
        super(FileDialog, self).__init__(*args, **kwargs)
        self.setOption(QtGui.QFileDialog.DontUseNativeDialog, True)
        self.setFileMode(QtGui.QFileDialog.ExistingFiles)

    def accept(self):
        QtGui.QDialog.accept(self)

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('Test', self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)

    def handleButton(self):
        dialog = FileDialog()
        if dialog.exec_() == QtGui.QDialog.Accepted:
            print(dialog.selectedFiles())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: Multiple files and folder selection in QFileDialog (Revisited)


code:
my_urls = [
    url(r'^$', self.my_view),
]

rawDescription: django admin redirecting to custom view

description: Django admin redirecting to custom view


code:
from_file.readline() # and discard
to_file.write(replacement_line)
shutil.copyfileobj(from_file, to_file)

rawDescription: change first line of a file in python

description: Change first line of a file in python


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

fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')

# Set up the grid in polar
theta = np.linspace(0,2*np.pi,90)
r = np.linspace(0,3,50)
T, R = np.meshgrid(theta, r)

# Then calculate X, Y, and Z
X = R * np.cos(T)
Y = R * np.sin(T)
Z = np.sqrt(X**2 + Y**2) - 1

# Set the Z values outside your range to NaNs so they aren't plotted
Z[Z < 0] = np.nan
Z[Z > 2.1] = np.nan
ax.plot_wireframe(X, Y, Z)

ax.set_zlim(0,2)

plt.show()

rawDescription: Disconnected surfaces when plotting cones


code:
import re
re.search('(AB|CD|EF)(12|34)', 'zzAB34zz').group()

rawDescription: Regex for multi character strings embedded in rest of match?


code: df.rename(columns = {'\xef\xbb\xbfId':'ID'}, inplace=True)

rawDescription: Executing multiple python pandas dataframe methods on one csv


code:
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.orm import mapper, sessionmaker

engine = create_engine('sqlite:///:memory:', echo=True,)
metadata = MetaData()

mytable = Table('mytable', metadata,
    Column('id', Integer, primary_key=True),
    Column('title', String(50)),
    Column('description', String(50)),
)

class MyObject(object):
    # 1. define keywork based constructor (or do this in the part 2.)
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

mapper(MyObject, mytable)
metadata.create_all(engine)

session = sessionmaker(bind=engine, autoflush=False)()

input = ([('title', 'A title'), ('description', 'A description'),
('title', 'Another title'), ('description', 'Another description'),
('title', 'One more title'), ('description', 'One more description')])

# 2. add data to the session, then commit
while input:
    values = dict((input.pop(0), input.pop(0)))
    obj = MyObject(**values)
    session.add(obj)
session.commit()

rawDescription: Inserting data from multipledict into multiple rows using sqlalchemy


code:
import numpy as np
import matplotlib.pylab as pl
import matplotlib.gridspec as gridspec

# Create 2x2 sub plots
gs = gridspec.GridSpec(2, 2)

pl.figure()
ax = pl.subplot(gs[0, 0]) # row 0, col 0
pl.plot([0,1])

ax = pl.subplot(gs[0, 1]) # row 0, col 1
pl.plot([0,1])

ax = pl.subplot(gs[1, :]) # row 1, span all columns
pl.plot([0,1])

rawDescription: Python - Organisation of 3 subplots with matplotlib


code:
def koch_invoke():
    koch(int(pointSize_max.get()), int(pointSize.get()))
drawButton = tk.Button(frame, text = "Draw a fractal", command=koch_invoke)

rawDescription: Why is the function called before pressing a button?


code:
mappings = {
    "doc": {
        "properties": {
            "geo": {
                 "properties": {
                     "location": {
                         "type": "geo_point"
                     }
                 }
             }
        }
    }
}
es.indices.create(index='geodata', body=mappings)

# ...
es_entries['geo'] = { 'location': str(data['_longitude_'])+","+str(data['_latitude_'])}
# ...
es.index(index="geodata", doc_type="doc", body=es_entries)

rawDescription: Elasticsearch Python client to add geo_point


code:
import mysql.connector

cnx = mysql.connector.connect(database='test', user='root',
                              charset='gbk', use_unicode=False)
cur = cnx.cursor()

cur.execute("DROP TABLE IF EXISTS gbktest")
table = (
    "CREATE TABLE gbktest ("
    "id INT AUTO_INCREMENT KEY, "
    "c1 VARCHAR(40)"
    ") CHARACTER SET 'gbk'"
)
cur.execute(table)

def gbk_to_hexstr(value):
    """Convert value to Hexadecimal Literal for MySQL
    """
    return "0x{0}".format(''.join(
        ["{0:x}".format(ord(c)) for c in value.encode('gbk')]))

# Convert your Unicode data using gbk_to_hexstr
data = {
    'c1' : gbk_to_hexstr(u'赵孟頫'),
}

# Use MySQLCursor.execute() _not_ passing data as second argument
cur.execute("INSERT INTO gbktest (c1) VALUES ({c1})".format(**data))
cur.execute("SELECT c1 FROM gbktest")

# Print the inserted data as Unicode
for row in cur:
    print(row[0].decode('gbk').encode('utf8'))

rawDescription: mysql-connector-python cannot work with GBK string "赵孟頫"

description: Mysql-connector-python cannot work with GBK string "赵孟頫"


code:
import os
import json

def check_in_file(my_file,my_string):
    with open(my_file) as f:
        try:
            return my_string in f.read()
        except:
            return False

def path_to_dict(path, my_string=None):
    d = {'name': os.path.basename(path)}
    if os.path.isdir(path):
        d['type'] = "directory"
        d['children'] = []
        paths = [os.path.join(path,x) for x in os.listdir(path)]
        #Just the children that contains at least a valid file
        for p in paths:
            c = path_to_dict(p, my_string)
            if c is not None:
                d['children'].append(c)
        if not d['children']:
            return None
    else:
        if my_string is not None and not check_in_file(path,my_string):
            return None
        d['type'] = "file"
    return d

print(json.dumps(path_to_dict('.',), indent=2))
print(json.dumps(path_to_dict('.','kkkkk'), indent=2))

rawDescription: Getting JSON tree of folders and files (but only with files containing given string)


code:
class Colormapper:
    """
    Create a colormap to map tuples onto RGBA values produced by matplolib's
    cmap function.

    Arguments are the maximum value of each place in the tuple. Dimension of
    the tuple is inferred from the length of the args array.
    """
    def __init__(self,*args):
        from itertools import product
        import matplotlib.pyplot as plt

        self.occs = sorted(list(product(*[xrange(arg+1) for arg in args])),key=sum)
        self.n = float(len(self.occs))
        self.hotmap = plt.get_cmap('hot')
        return

    def __call__(self,occ):
        ind255 = int(255*self.occs.index(occ)/self.n)
        return self.hotmap(ind255)

rawDescription: Map a tuple of arbitrary length to an RGB value


code:
THRESHOLD = 100

waiting_for_high_value = True  # False means: waiting for low value

while True:  # Infinite loop (or "while on", if "on" is a changing variable)
    if waiting_for_high_value:
        if value_ind >= THRESHOLD:
            open_time = time()
            waiting_for_high_value = False
    else:  # Waiting for a low value:
        if value < THRESHOLD:
            close_time = time()
            calculate_time_open(open_time, close_time)
            waiting_for_high_value = True

rawDescription: Is there a variation of the while loop that will only run the clause once until a change occurs?


code:
class FixProgress:
    def __init__(self):
        self.saw_progress = False

    def write(self, s):
        if 'Progress:' in s:
            self.saw_progress = True
        if s == '\n' and self.saw_progress:
            sys.stdout.write('\r')
            self.saw_progress = False
        else:
            sys.stdout.write(s)

    def flush(self):
        sys.stdout.flush()

def some_task():
    with settings(user = 'root'):
        run('./task_with_progress_bar.out', stdout = FixProgress())

rawDescription: Handling of carriage return (\r) character in Python's Fabric


code:
import cgi
import webapp2

from google.appengine.api import users

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.out.write("""

              <form action="/sign">

<textarea name="content" rows="3" cols="60"></textarea>

<input type="submit" value="Sign Guestbook">

              </form>

          """)

class Guestbook(webapp2.RequestHandler):
    def get(self):
        self.response.out.write('You wrote:
')
        self.response.out.write(cgi.escape(self.request.get('content')))
        self.response.out.write('
')

app = webapp2.WSGIApplication([('/', MainPage),
                              ('/sign', Guestbook)],
                              debug=True)

rawDescription: App Engine: map form data to url

description: App Engine: map form data to url


code: course_name = line[16:45].strip()

rawDescription: python re module - What regular expression to use to extract pieces of text

description: Python re module - What regular expression to use to extract pieces of text


code:
s="SKU 9780136058281, (ASIN B00A2KNZ2S, (binding Merchant: 'paperback' / 'hardcover'))"
import re
re.search(r'SKU (\d+)',s).group(1)

rawDescription: Python regex match middle of string

description: Python regex match middle of string


code:
msg.as_string()
str(msg)
repr(msg)

rawDescription: Python imaplib fetch body emails gmail

description: Python imaplib fetch body emails gmail


code:
from django.views.generic.base import RedirectView, TemplateView, View
from django.http import Http404, HttpResponse
from django.conf import settings
from django.conf.urls import patterns, url, include
from django.contrib import messages
from django.core.urlresolvers import reverse_lazy, reverse
from guardian.mixins import LoginRequiredMixin
from simple_salesforce import Salesforce
import logging, requests, json

from campaigns.views import CampaignOwnerPermission
from . import api, utils, settings
from .models import OauthToken

class SalesforceOauthRedirectView(
    LoginRequiredMixin,
    RedirectView
):
# permanent = False
# query_string = False

    def get_redirect_url(self):
        logger = logging.getLogger(__name__)

        try:
            payload = {
                'grant_type': 'authorization_code',
                'client_id': settings.CONSUMER_KEY,
                'client_secret': settings.CONSUMER_SECRET,
                'code': self.request.GET.get('code'), # get code param from response URL
                # TODO: redirect_uri should NOT be hardcoded
                'redirect_uri': 'https://127.0.0.1:8000/oauth/salesforce/'
                }

            try:
                # Post payload to Salesforce Oauth server and get user
                # token in response.
                r = requests.post(
                    "https://login.salesforce.com/services/oauth2/token",
                    headers={
                        "Content-Type":"application/x-www-form-urlencoded"
                    },
                    data=payload
                )

                try:
                    # Decode the JSON response from Salesforce Oauth server
                    decoded = json.loads(r.content)
                    # Store tokens & Salesforce user info to database
                    creds = OauthToken.objects.get(user=self.request.user)
                    # TODO: Store salesforce_user_id, Thumbnail, etc.
                    creds.access_token = decoded['access_token']
                    # creds.salesforce_organization_id = decoded['refresh_token']
                    # creds.refresh_token = creds['refresh_token']
                    # creds.id_token = creds['id_token']
                    # creds.instance_url = decoded['instance_url']
                    creds.active = True
                    creds.save()

                    messages.add_message(
                        self.request,
                        messages.SUCCESS,
                        _(
                            'Successfully updated Salesforce  \
                            authentication with user credentials: "%s"'
                            %
                            creds.salesforce_user_id
                        )
                    )

                except:
                    logger.error("%s: %s" % (e.__class__, e.args))
                    messages.add_message(
                    self.request,
                    messages.WARNING,
                        ('Error connecting with Salesforce.  \
                        Contact explorro support. [Error 003]')
                        )

                    return reverse_lazy('providers:provider_list')

            except BaseException as e:
                #raise e # Print error to the console
                # or, to print to the error logs
                logger.error("%s: %s" % (e.__class__, e.args))
                messages.add_message(
                    self.request,
                    messages.WARNING,
                    ('Could not get Oauth_token from Salesforce API.\n\n \
                    Salesforce may be experiencing an outage.  Try again \
                    in a few minutes and contact explorro support if the \
                    problem persists. [Error 002]'
                    )
                )
                return reverse_lazy('providers:provider_list')

        except BaseException as e:
            raise e # Print error to console
            logger.error("%s: %s" % (e.__class__, e.args))
            messages.add_message(
                self.request,
                messages.WARNING,
                ('There was a problem authenticating with \
                 Salesforce.  Be sure to enter your Salesforce \
                 username and password before attempting to authorize your\
                 account.  Contact our support team if you need some help. \
                 [Error 003]'
                )
            )
            return reverse_lazy('providers:provider_list')

rawDescription: Salesforce Oauth with Django

description: Salesforce Oauth with Django


code:
nan_mask = np.isnan(matrix)
matrix[nan_mask] = np.random.randint(0, 2, size=np.count_nonzero(nan_mask))

rawDescription: Replacing missing values with random in a numpy array


code:
alist = ['username1,username2', 'username3','username4,username5']
','.join(alist).split(',')

rawDescription: Converting a list

description: Converting a list


code:
try:
    from local_settings import *
except ImportError:
    pass

rawDescription: overwrite settings and package defaults

description: Overwrite settings and package defaults


rawDescription: For every integer in a string I want to add an integer on - Python


code:
for thread in threadList:
    thread.start()
while any(thread.is_alive() for thread in threadList):
    print('running...')
    time.sleep(1)

rawDescription: Python threading - do something while join()


code:
self.table.setColumnCount(8)
self.table.setHorizontalHeaderLabels(title)
for i,row in enumerate(cur):
    self.table.insertRows(self.table.rowCount())
    for j,val in enumerate(row):
        self.table.setItem(i, j, QtGui.QTableWidgetItem(str(val)))

rawDescription: How can rowcount update itself when data is added?


code:
from collections import defaultdict

d = defaultdict(set)

with open('data.csv','r') as r:
    for line in r:
        splitted = line.strip().split(',')
        name = splitted[3].strip()
        value = splitted[4].strip()
        d[name].add(value)

rawDescription: read file into a dictionary so that columns become keys and values, Python

description: Read file into a dictionary so that columns become keys and values, Python


code: ('\\' + 'a').decode('string-escape')

rawDescription: Map character to its escaped version

description: Map character to its escaped version


code:
app = Celery()
app.config_from_object('conf.config')

response = app.control.enable_events(reply=True)
# print response here

rawDescription: How to know if event group {task} is enabled or disabled in Celery

description: Know if event group {task} is enabled or disabled in Celery


code:
import numpy as np
coeffs = [1, 2, 3, 4]
N = len(coeffs)
a = np.tile(coeffs, (N, 1))
a
for i in xrange(1, N):
    a[i] = np.roll(a[i], i)

a

rawDescription: How to set up equations in python

description: Set up equations in python


code:
def construct_blueprint(database):

    myblueprint = Blueprint('myblueprint', __name__)

    @myblueprint.route('/route', methods=['GET'])
    def route():
        database = database

    return(myblueprint)

rawDescription: How to pass arbitrary arguments to a flask blueprint?

description: Pass arbitrary arguments to a flask blueprint


code:
def mimeTypes(self):
    return QtCore.QStringList([
        'text/uri-list',
        'application/x-qabstractitemmodeldatalist',
        ])

rawDescription: Dropping an external file into a QTreeWidget


code:
#!/usr/bin/env python
import sys
from zipfile import ZipFile
from PIL import Image # $ pip install pillow

filename = sys.argv[1]
with ZipFile(filename) as archive:
    for entry in archive.infolist():
        with archive.open(entry) as file:
            img = Image.open(file)
            print(img.size, img.mode, len(img.getdata()))

rawDescription: How to read an image inside a zip file with PIL/Pillow

description: Read an image inside a zip file with PIL/Pillow


code:
import sublime, sublime_plugin

class SaveAllExistingFilesCommand(sublime_plugin.ApplicationCommand):
    def run(self):
        for w in sublime.windows():
            self._save_files_in_window(w)

    def _save_files_in_window(self, w):
        for v in w.views():
            self._save_exiting_file_in_view(v)

    def _save_exiting_file_in_view(self, v):
        if v.file_name():
            if v.is_dirty():
                v.run_command("save")

rawDescription: sublime - save all open/loaded files that have names?

description: Sublime - save all open/loaded files that have names


code:
import zipfile,fnmatch,os

rootPath = r"C:\Project"
pattern = '*.zip'
for root, dirs, files in os.walk(rootPath):
    for filename in fnmatch.filter(files, pattern):
        print(os.path.join(root, filename))
        zipfile.ZipFile(os.path.join(root, filename)).extractall(os.path.join(root, os.path.splitext(filename)[0]))

rawDescription: Unzip zip files in folders and subfolders with python


code:
with open("input.csv") as inputFile, open("output.csv", 'w') as outputFile:
    outCsv = csv.writer(outputFile, delimiter=',')
    inCsv = csv.reader(inputFile, delimiter=',')

    header = next(inCsv)
    outCsv.writerow(header)

    for line in inCsv:
        newLine = line[0:3]
        for value in line[3:]:
            value = value.strip()
            code = {
                'A': line[1],
                'B': line[2],
                '0': value
            }
            newLine.append(code[value])

        outCsv.writerow(newLine)

rawDescription: Convert letter based on given information?


rawDescription: Creating a masked array in Python with multiple given values


code:
from urllib import request

# Retrieve the webpage as a string
response = request.urlopen("http://ichart.finance.yahoo.com/table.csv?s=AAPL&d=1&e=1&f=2014&g=d&a=8&b=7&c=1984&ignore=.csv")
csv = response.read()

# Save the string to a file
csvstr = str(csv).strip("b'")

lines = csvstr.split("\\n")
f = open("historical.csv", "w")
for line in lines:
   f.write(line + "\n")
f.close()

rawDescription: Download a .csv file with Python

description: Download a .csv file with Python


code:
f_writ = open('one_4.csv', 'wb')
csvReader = csv.reader(iInputFile)
writer = csv.writer(f_writ, delimiter=',',
                lineterminator='\r\n',
                quotechar = "'"
                )

for row in csvReader:

    writer.writerow(['31-7-2014',row[0],'\"text\"'])

f_writ.close()

rawDescription: write csv file with double quotes for particular column not working

description: Write csv file with double quotes for particular column not working


code:
def fib(n, r):
    if n < 2:
        r[0] = n
    else:
        r1 = [None]
        r2 = [None]
        # Start fib() threads that use r1 and r2 for results.
        ...

        # Sum the results of the threads.
        r[0] = r1[0] + r2[0]

def FibonacciThreads(n):
    r = [None]
    fib(n, r)
    return r[0]

rawDescription: Recursive thread creation in python

description: Recursive thread creation in python


code:
class Survey(models.Model):
    name = CharField(max_length=255)

    def __str__(self):     # or def __unicode__(self) in Python 2
        return self.name

rawDescription: DRF form render object property (name) instead of Object


code:
from difflib import Differ
from pprint import pprint

d = Differ()
result = list(d.compare(open('1.sql', 'r').readlines(), open('2.sql', 'r').readlines()))
pprint(result)

rawDescription: How to compare two .sql files in python?

description: Compare two .sql files in python


code: l2 = [item.strip('\t') for item in l1]

rawDescription: Python:how to change string or list elements


code: new_list = [elem for elem in your_list if elem.endswith('.txt')]

rawDescription: Creating a new List from results of If Statement


code:
import sys
# insert at 0 instead of appending to end to take precedence
# over system-installed suds (if there is one).
sys.path.insert(0, "suds-0.4-py2.6.egg")
import suds

rawDescription: Including a Python Library (suds) in a portable way


code:
items = ['foo', 'bar', 'item', 'item2', 'item3']
for elm in items:
    getattr(self.ui, elm).setEnabled(False)

rawDescription: Python code refactoring question. Applying functions to multiple elements


code:
training_data_without_sports, test_data_without_sports, feature_cols_all = (
    divide_data('../data/feature_without_sports.csv', training_ratio))

rawDescription: How to break this line properly to match PEP 8 style guide?

description: Break this line properly to match PEP 8 style guide


code:
def transform_dictionary(dictionary, callback, qc=lambda x: True):
    return {k: callback(v) if qc(v) else v for k, v in dictionary.items()}

rawDescription: using dict comprehension if/else logic to determine using a function or not

description: Using dict comprehension if/else logic to determine using a function or not


code:
VariantDir('buildA', '.', duplicate=0)
VariantDir('buildB', '.', duplicate=0)

env.Library('libraryA', 'buildA/source.c', CCFLAGS=['-DCONFIG_X'])
env.Library('libraryB', 'buildB/source.c', CCFLAGS=['-DCONFIG_Y'])

rawDescription: SCons: modify intermediate builder calls


rawDescription: Django Foreign key query

description: Django Foreign key query


code: zip(list_of_strings, result[0])

rawDescription: convert an array to list in python

description: Convert an array to list in python


code:
from docutils import nodes, utils
from docutils.parsers.rst import roles
from sphinx.roles import _amp_re

def patched_menusel_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    text = utils.unescape(text)
    if typ == 'menuselection':
        text = text.replace('-->', u'\N{RIGHTWARDS ARROW}')  # Here is the patch
    spans = _amp_re.split(text)

    node = nodes.emphasis(rawtext=rawtext)
    for i, span in enumerate(spans):
        span = span.replace('&&', '&')
        if i == 0:
            if len(span) > 0:
                textnode = nodes.Text(span)
                node += textnode
            continue
        accel_node = nodes.inline()
        letter_node = nodes.Text(span[0])
        accel_node += letter_node
        accel_node['classes'].append('accelerator')
        node += accel_node
        textnode = nodes.Text(span[1:])
        node += textnode

    node['classes'].append(typ)
    return [node], []

# Use 'patched_menusel_role' function for processing the 'menuselection' role
roles.register_local_role("menuselection", patched_menusel_role)

rawDescription: How can I configure the separator character used for :menuselection:?

description: Configure the separator character used for :menuselection:


code:
...
item['title'] = site.select('a/text()').extract()
item['link'] = site.select('a/@href').extract()
item['desc'] = site.select('text()').extract()
items.append(item)
with open('log.txt', 'a') as f:
  f.write('name: {0}, link: {1}\n'.format(item['title'], item['link']))

rawDescription: How can i write data in text file in python Scrapy

description: Write data in text file in python Scrapy


rawDescription: Tkinter Spinbox Widget

description: Tkinter Spinbox Widget


code:
PLUS = 0
MINUS = 1
OPERATIONS = [PLUS, MINUS]

class Generator:
    operations = {}

    def __init__(self, state):
        self._state = state

    @classmethod
    def init_operations(cls):
        cls.operations = {
            PLUS:  cls.plus,
            MINUS:  cls.minus
        }

    def plus(self, a, b):
        # Depends on state
        return a + b

    def minus(self, a, b):
        return a - b if self._state else b - a

    def generate(self):
        a, b = 5, 10
        for op in self.operations:
            print( self.operations[op](self, a, b) )

gen = Generator(1)
gen.init_operations()
gen.generate()

rawDescription: Reference methods from static member

description: Reference methods from static member


rawDescription: How to unpack a list of indefinite length

description: Unpack a list of indefinite length


code: random.sample(query_objects, 3)

rawDescription: Django. Returning a random small list from a larger Query


code:
def mpmine(word, dictionary):
  '''Takes a tuple of length 2 with it's arguments.

  At least dictionary needs to be sorted by word length. If not, whacky results ensue.
  '''
  results = dict()
  pw = word
  pwlen = len(pw)
  pwres = list()
  for word in dictionary:
    if len(word) > pwlen:
      break
    if word in pw:
      pwres.append(word)
  if len(pwres) > 0:
    results[pw] = pwres
  return results

rawDescription: passing list of strings to map_async()

description: Passing list of strings to map_async()


code:
p = re.compile("name (.*) is valid")
p.search(s)    # The result of this is referenced by variable name '_'
_.group(1)     # group(1) will return the 1st capture.

rawDescription: Python extract pattern matches

description: Python extract pattern matches


code:
df = pd.DataFrame(np.random.randn(4,2), index=pd.MultiIndex.from_arrays([['a', 'a', 'b', 'b'],[1,1,2,2]]))
df
df.drop([('a', 1)])

rawDescription: Remove certain rows from dataframe based on index


code: raise HTTP(503, 'Down for maintenance')

rawDescription: Can't disable example app on Web2Py

description: Can't disable example app on Web2Py


code:
def quicksort(alist):
    if len(alist) < 2:
        return alist # primitive case: a list of size one is ordered

    pivotelement = alist.pop()
    # compute the 2 lists for the next recursive call
    left  = [element for element in alist if element < pivotelement]#left = smaller than pivotelemet
    right = [element for element in alist if element >= pivotelement]#left = greater than pivotelemet

    # call function recursively
    return quicksort(left) + [pivotelement] + quicksort(right)

rawDescription: Halt a recursively called function

description: Halt a recursively called function


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

x = 0.1
# preallocate xn
xn = np.zeros([1001, 200])
# linspace is better for a non-integer step
zz = np.linspace(2.8, 3.9, 1001)

# use enumerate instead of counting iterations
for j,z in enumerate(zz):
    print(j)
    for n in range(200):
        # use tuple unpacking so old values of x are unneeded
        xn[j,n], x = x, z*x*(1 - x)

plt.plot(zz, xn[:, 100:], 'r.')
plt.show()

rawDescription: Python plotting data generated from for loop inside for loop


code:
from sqlalchemy import desc

stmt = select([users_table]).order_by(desc(users_table.c.name))

rawDescription: SQLAlchemy Core: order by desc

description: SQLAlchemy Core: order by desc


code:
import sys
if sys.version_info[0] == 2 and sys.version_info[1] < 7:
    sys.exit('Sorry, Python < 2.7 is not supported')

rawDescription: Enforcing python version in setup.py

description: Enforcing python version in setup.py


code: result = re.findall("(?:^|\s)(#[a-zA-Z]+)", text, re.MULTILINE)

rawDescription: Trying to match '#' in a text

description: Trying to match '#' in a text


code:
matches = re.findall(r'(.+)(?=.*\1)',yourstring)
largest = '' if not matches else max(matches,key=lambda m:len(m))

rawDescription: Regular expression to find longest substring which occurs twice (and is disjoint from its twin)


code:
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        pygame.quit()
        quit()

rawDescription: Pygame wait for key down

description: Pygame wait for key down


code:
type(u'abc')
r'ab\c'

rawDescription: What does 'u' mean in a list?

description: What does 'u' mean in a list


code:
pivot_product['subtotals'] = pivot_product[('sum', 'counter')].groupby(level=0).transform(np.sum)
pivot_product

rawDescription: pivot table subtotals

description: Pivot table subtotals


code:
def get_url(self, obj, view_name, request, format):
    """
    Given an object, return the URL that hyperlinks to the object.
    May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
    attributes are not configured to correctly match the URL conf.
    """
    # Unsaved objects will not yet have a valid URL.
    if hasattr(obj, 'pk') and obj.pk in (None, ''):
        return None

    lookup_value = getattr(obj, self.lookup_field)
    kwargs = {self.lookup_url_kwarg: lookup_value}
    return self.reverse(view_name, kwargs=kwargs, request=request, format=format)

rawDescription: Django Rest Framework Tests HyperlinkedRelatedField


code:
d={}
key=''
file2 = open("ref.txt",'r')
for line in file2.readlines():
    if line.startswith('>'):
        key=line.strip()
        d[key]=[]
        continue
    d[key].append(line.strip())
file.close()

rawDescription: creating a dictionary in python

description: Creating a dictionary in python


code:
import pandas as pd
df = pd.read_csv("somefile.csv", sep=";")
df
df["foo"]
df["bar"]
df["foo"] * df["bar"]
list(df["foo"] * df["bar"])

rawDescription: Pythonic way to copy a column from a CSV file


code:
listeners = [component1, component2, component3]
eventqueue.add(InitEvent())
while True:
    event = eventqueue.pop()
    for listener in listeners:
        listener.handle_event(event)

rawDescription: Basic Event Loop in Python

description: Basic Event Loop in Python


rawDescription: Pymssql: Calling Stored Procedure with parameters


code:
if FormSet.IsEmpty(CurrentForm, "ADD_COMP1_ADDRESS") and \
   FormSet.IsEmpty(CurrentForm, "ADD_COMP2_ADDRESS") and \
   FormSet.IsEmpty(CurrentForm, "ADD_COMP3_ADDRESS") and \
   FormSet.IsEmpty(CurrentForm, "ADD_COMP4_ADDRESS") and \
   FormSet.IsEmpty(CurrentForm, "ADD_COMP5_ADDRESS") and \
   FormSet.IsEmpty(CurrentForm, "ADD_COMP6_ADDRESS"):
    Rule.Violated = True
else:
    Rule.Violated = False

rawDescription: python multiple formset.isempty in one if statement - need syntax info

description: Python multiple formset.isempty in one if statement - need syntax info


code:
def stretch(xs, coef, centre):
    """Scale a list by a coefficient around a point in the list.

    Parameters
    ----------
    xs : list
        Input values.
    coef : float
        Coefficient to scale by.
    centre : int
        Position in the list to use as a centre point.

    Returns
    -------
    list

    """
    grain = 100
    stretched_array = np.repeat(xs, grain * coef)

    if coef < 1:
        # pad start and end
        total_pad_len = grain * len(xs) - len(stretched_array)
        centre_pos = float(centre) / len(xs)
        start_pad_len = centre_pos * total_pad_len
        end_pad_len = (1 - centre_pos) * total_pad_len
        start_pad = [stretched_array[0]] * int(start_pad_len)
        end_pad = [stretched_array[-1]] * int(end_pad_len)
        stretched_array = np.array(start_pad + list(stretched_array) + end_pad)
    else:
        pivot_point = (len(xs) - centre) * grain * coef
        first = int(pivot_point - (len(xs) * grain)/2)
        last = first + len(xs) * grain
        stretched_array = stretched_array[first:last]

    return [round(chunk.mean(), 2) for chunk in chunks(stretched_array, grain)]

def chunks(iterable, n):
    """
    Yield successive n-sized chunks from iterable.
    Source: http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python#answer-312464

    """
    for i in xrange(0, len(iterable), n):
        yield iterable[i:i + n]

rawDescription: How do I stretch a list of floats in Python?

description: Stretch a list of floats in Python


code:
from io import BytesIO
import mock

class MemorisingBytesIO(BytesIO):
    """Like a BytesIO, but it remembers what its value was when it was closed."""
    contents = {}
    def __init__(self, filepath, *args, **kwargs):
        self.filepath = filepath
        super(MemorisingBytesIO, self).__init__()
    def close(self):
        self.contents[self.filepath] = self.getvalue()
        super(MemorisingBytesIO, self).close()

def write_to_the_file():
    with open('a/b.txt', 'wb') as f:
        f.write('the data')
    with open('a/c.txt', 'wb') as f:
        f.write('another data')

#MemorisingBytesIO.contents.clear()
open_mock = mock.Mock(side_effect=MemorisingBytesIO)
with mock.patch('__builtin__.open', open_mock):
    write_to_the_file()  # the function under test

open_mock.assert_called_once_with('a/b.txt', 'wb')
open_mock.assert_called_once_with('a/c.txt', 'wb')
assert MemorisingBytesIO.contents['a/b.txt'] == b'the data'
assert MemorisingBytesIO.contents['a/c.txt'] == b'another data'

rawDescription: Python's 'mock' - responding to an argument


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

# generate random data
data = npr.randn(300)

# calculate hist
heights,edges = np.histogram(data,50)

# center edges
edges = edges[:-1]+(edges[1]-edges[0])

# plot histogram
fig, ax = plt.subplots()
ax.plot(edges,heights)
ax.set(title='Click Twice', xlabel='X', ylabel='Y')

# get input from 2 clicks on figure
point1, point2 = fig.ginput(2)

# paint selected area in red
ax.axvspan(point1[0], point2[0], color='red', alpha=0.5)

# calculate which values are selected and display mean and std
mask = (edges>point1[0]) & (edges<point2[0])
fig.text(0.2,0.83,'Mean: ' + str(np.mean(heights[mask])))
fig.text(0.2,0.8,'Std: ' + str(np.std(heights[mask])))

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

rawDescription: Interactive histogram using matplotlib?

description: Interactive histogram using matplotlib


code:
INST_HT = [1.545000,
           1.335000]
lines = open('tmp.txt')
out = open('tmp2.txt', 'w')
i = -1
while True:
    try:
        line = lines.next()
    except StopIteration:
        break
    if 'slope' in line.lower():
        i += 1
        out.write(line)
        while True:
            line = lines.next()
            if 'end slope' in line.lower():
                out.write(line)
                break
            else:
                out.write('    ' + line.strip()[:-1] + ', ' + str(INST_HT[i]) + ';\n')
    else:
        out.write(line)
out.close()

rawDescription: read specific number from different lines in a txt file and add it to the end of each line block in txt

description: Read specific number from different lines in a txt file and add it to the end of each line block in txt


code:
from pylab import *

t = arange(0.0, 2.0, 0.01)
s = sin(2*pi*t)
p1, = plot(t, s, linewidth=1.0, label="Graph1")
grid(True)
s = sin(4*pi*t)
p2, = plot(t, s, color='r',linewidth=1.0, label="Graph2")

l1 = legend([p1], ["Graph1"], loc=1)
l2 = legend([p2], ["Graph2"], loc=4)
gca().add_artist(l1)

show()

rawDescription: Splitting the legend in matploblib

description: Splitting the legend in matploblib


code:
def writeline(line):
    file.write(line + "\n")

file = open(filename, "w")
ftp.retrlines("retr " + filename, writeline)

rawDescription: Downloading text files with Python and ftplib.FTP from z/os


code:
import os
s = os.stat("test.html")
os.utime("test.pdf", (s.st_atime, s.st_mtime))

rawDescription: python pdfkit preserve datetimestamp

description: Python pdfkit preserve datetimestamp


code:
cars = [...] # A list of Car objects.

models = {car.model for car in cars}

rawDescription: How to get unique values from a python list of objects

description: Get unique values from a python list of objects


code:
...
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write(repr(self.request))
...

rawDescription: How do I get the client IP of a Tornado request?

description: Get the client IP of a Tornado request


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

t = np.linspace(0, 4*np.pi, 100)
x = np.cos(3 * t)
y = np.sin(t)

gridx = np.linspace(-1, 1, 5)
gridy = np.linspace(-1, 1, 5)

grid, _, _ = np.histogram2d(x, y, bins=[gridx, gridy])

plt.figure()
plt.plot(x, y, 'ro')
plt.grid(True)

plt.figure()
plt.pcolormesh(gridx, gridy, grid)
plt.plot(x, y, 'ro')
plt.colorbar()

plt.show()

rawDescription: Countig points in boxes of a grid

description: Countig points in boxes of a grid


code:
import sys
sys.stdin.isatty()

rawDescription: How to check if raw_input() came from keyboard in Python

description: Check if raw_input() came from keyboard in Python


code:
import gc

class Foo: pass

f1 = Foo()

[o for o in gc.get_objects() if isinstance(o, Foo)]

f2 = Foo()

[o for o in gc.get_objects() if isinstance(o, Foo)]

rawDescription: How do I list all instantiated objects in Python?

description: List all instantiated objects in Python


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

data = np.loadtxt('data.txt')
plt.imshow(data, cmap=cm.Blues)
plt.show()

rawDescription: Convert Numpy array to image

description: Convert Numpy array to image


rawDescription: Find xml-tag with given value

description: Find xml-tag with given value


code:
# our merged items and store locations
merged_items = items.merge(store_loc, on='itemCat')
for i in stores:
    # take a copy
    temp_df = merged_items.copy()
    # set the store id
    temp_df['storeID'] = i
    # now just concat
    item_merged = pd.concat([iterm_merged, temp_df], ignore_index=True)

# rest of code is same

rawDescription: Append Py Pandas Dataframes into a single .csv, iterating by separate list


code:
def non_Destructive_pixel_addition(original, segmentated):

    to_be_added = np.matrix(np.where(segmentated)).transpose()

    n, m = np.shape(to_be_added)

    for k in range(n):
        i = to_be_added[k, 0]
        j = to_be_added[k, 1]
        if (original[i,j] == 0):
            original[i,j] = segmentated[i,j]

rawDescription: Add matrices in a boolean way

description: Add matrices in a boolean way


code:
G=nx.Graph()

#extract and add AGE_GROUP nodes in graph
f1 = csv.reader(open("user_agegroup.txt","rb"))
for row in f1:
    G.add_nodes_from(row, color = 'blue')

#extract and add COUNTRY nodes in graph
f2 = csv.reader(open('user_country.txt','rb'))
for row in f2:
    G.add_nodes_from(row, color = 'red')

#extract and add USER_ID nodes in graph
f3 = csv.reader(open('user_id.txt','rb'))
for row in f3:
    G.add_nodes_from(row, color = 'yellow')

f4 = csv.reader(open('id,agegroup.txt','rb'))
for row in f4:
    if len(row) == 2 : # add an edge only if both values are provided
        G.add_edge(row[0],row[1])

f5 = csv.reader(open('id,country.txt','rb'))

for row in f5:
    if len(row) == 2 : # add an edge only if both values are provided
        G.add_edge(row[0],row[1])
# Remove empty nodes
for n in G.nodes():
    if n == '':
        G.remove_node(n)
# color nodes according to their color attribute
color_map = []
for n in G.nodes():
    color_map.append(G.node[n]['color'])
nx.draw_networkx(G, node_color = color_map, with_labels = True, node_size = 500)

plt.savefig("path.png")

plt.show()

rawDescription: Networkx : How to create graph edges from a csv file?


code:
input_file = open('some_tab_separated_file.txt', 'r')
output_file = open('some_tab_separated_file.csv', 'w')
input_file.readline() # skip first line
for line in input_file:
    (a, date, time, lon, lat, country) = line.strip().split('\t')
    output_file.write(','.join([lon, lat, country, date, time]) + '\n')
input_file.close()
output_file.close()

rawDescription: converting a space delimited file to a CSV

description: Converting a space delimited file to a CSV


code:
d = {}
with open('text.txt') as f:
    for line in f:
        key, value = line.strip().split(':')
        d[key] = int(value)

rawDescription: Python- how to convert lines in a .txt file to dictionary elements?


code:
import matplotlib.pyplot as plt

# Some sample lists
l1 = [0.7,0.8,0.8,0.9,0.8,0.7,0.6,0.9,1.0,0.9]
l2 = [0.2,0.3,0.1,0.0,0.2,0.1,0.3,0.1,0.2,0.1]
l3 = [0.4,0.6,0.4,0.5,0.4,0.5,0.6,0.4,0.5,0.4]

l4 = [78,87,77,65,89,98,74,94,85,73]
l5 = [16,44,14,55,34,36,76,54,43,32]

# Make a figure
fig = plt.figure()

# Make room for legend at bottom
fig.subplots_adjust(bottom=0.2)

# The axes for your lists 1-3
ax1 = fig.add_subplot(211)
# A twin axis for list 4. This shares the x axis, but has a separate y axis
ax2 = ax1.twinx()

# Plot lines 1-3
line1 = ax1.plot(l1,'bo-',label='list 1')
line2 = ax1.plot(l2,'go-',label='list 2')
line3 = ax1.plot(l3,'ro-',label='list 3')

# Plot line 4
line4 = ax2.plot(l4,'yo-',label='list 4')

# Some sensible y limits
ax1.set_ylim(0,1)
ax2.set_ylim(0,100)

# Your second subplot, for lists 4&5
ax3 = fig.add_subplot(212)

# Plot lines 4&5
ax3.plot(l4,'yo-',label='list 4')
line5 = ax3.plot(l5,'mo-',label='list 5')

# To get lines 1-5 on the same legend, we need to
# gather all the lines together before calling legend
lines = line1+line2+line3+line4+line5
labels = [l.get_label() for l in lines]

# giving loc a tuple in axes-coords. ncol=5 for 5 columns
ax3.legend(lines, labels, loc=(0,-0.4), ncol=5)

ax3.set_xlabel('events')

# Display the figure
plt.show()

rawDescription: Matplotlib: how to plot data from lists, adding two y-axes?


code:
class A:
    def __new__(cls):
        return object.__new__(cls)

A()

rawDescription: Python __new__ without calling another class's version of __new__?


code:
def recur_to_gen(step_fu, current, sentinel=None):
    while current != sentinel:
        yield current
        current = step_fu(current)

matches = itertools.takewhile(predicate, recur_to_gen(step_fu, start))

rawDescription: Does Python have an iterative recursion generator function for first-order recurrence relations?


code:
items = ["First", "Second", "# First", "Third", "# Second"]
for e in items:
    if e.startswith('#'):
            items.remove(e)
            break

items

rawDescription: Remove first occurrence that matches criteria from a list


code:
yv = 0
xv = 1
while True:
    yv += .5 # .5 is the acceleration
    x+=xv
    y+=yv
    if y > 170: # check that didn't move past the floor
        y=170        # reset to the floor
        yv = -yv*.9  # reverse velocity and lose some energy from the bounce
    time.sleep(0.05)
    canvas.coords(oval_id,x,y,x+10,y+10) # use absolute coordinates
    canvas.update()

rawDescription: Python: stopping gravity

description: Python: stopping gravity


code:
no_class_at_all = soup.find_all("li", class_=False)
hidden_class = soup.find_all("li", class_="hidden")

rawDescription: Beautiful Soup: Trying to select tags on conflicting multiple criteria


code:
...
img = ImageTk.PhotoImage(Image.open("test.gif"))
panel = Label(root, image = img)
panel.pack(side="top", fill = "both", expand = "yes")

app = Frame(root)
app.pack(side='bottom')
button1 = Button(app, text = "This is a button")
button1.pack()
...

rawDescription: Python 2.7.8 Tkinter Gui with image, button and text


code: my_dict.pop("key", None)

rawDescription: How to remove a key from a dictionary?

description: Remove a key from a dictionary


code:
if timeElapsed == FPS * secondsBetweenSpawns:
    generateEnemy()

rawDescription: Delaying Enemy Character Onset in Pygame


code:
class Singleton(object):

    def __new__(cls):

        try:
            return cls._instance
        except AttributeError:
            cls._instance = object.__new__(cls)
            return cls._instance

rawDescription: How do I implement subclassable singletons?

description: Implement subclassable singletons


code:
# avoid closures and use default args which copy on function definition
for i in xrange(3):
    def func(x, i=i):
        return x*i
    flist.append(func)

# or introduce an extra scope to close the value you want to keep around:
for i in xrange(3):
    def makefunc(i):
        def func(x):
            return x*i
        return func
    flist.append(makefunc(i))

# the second can be simplified to use a single makefunc():
def makefunc(i):
    def func(x):
        return x*i
    return func
for i in xrange(3):
    flist.append(makefunc(i))

# if your inner function is simple enough, lambda works as well for either option:
for i in xrange(3):
    flist.append(lambda x, i=i: x*i)

def makefunc(i):
    return lambda x: x*i
for i in xrange(3):
    flist.append(makefunc(i))

rawDescription: About python closure

description: About python closure


code:
from pprint import pprint

# Build the tree somehow

with open('output.txt', 'wt') as out:
    pprint(myTree, stream=out)

rawDescription: Prettyprint to a file?

description: Prettyprint to a file


code:
from PyQt4 import QtGui, QtCore
import qrcode

class Image(qrcode.image.base.BaseImage):
    def __init__(self, border, width, box_size):
        self.border = border
        self.width = width
        self.box_size = box_size
        size = (width + border * 2) * box_size
        self._image = QtGui.QImage(
            size, size, QtGui.QImage.Format_RGB16)
        self._image.fill(QtCore.Qt.white)

    def pixmap(self):
        return QtGui.QPixmap.fromImage(self._image)

    def drawrect(self, row, col):
        painter = QtGui.QPainter(self._image)
        painter.fillRect(
            (col + self.border) * self.box_size,
            (row + self.border) * self.box_size,
            self.box_size, self.box_size,
            QtCore.Qt.black)

    def save(self, stream, kind=None):
        pass

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.label = QtGui.QLabel(self)
        self.edit = QtGui.QLineEdit(self)
        self.edit.returnPressed.connect(self.handleTextEntered)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.label)
        layout.addWidget(self.edit)

    def handleTextEntered(self):
        text = unicode(self.edit.text())
        self.label.setPixmap(
            qrcode.make(text, image_factory=Image).pixmap())

if __name__ == '__main__':

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

rawDescription: Create QR-code in Python (PyQt)

description: Create QR-code in Python (PyQt)


code:
def get_resolution(filename):
    with open(filename, "rb") as f:
        data = f.read()
    if data[0:2] != b"\xff\xd8":
        raise ValueError("Not JPEG.")
    if data[2:4] != b"\xff\xe0":
        return None
    else:
        if data[13] == b"\x00":
            unit = "no unit"
        elif data[13] == b"\x01":
            unit = "dpi"
        elif data[13] == b"\x02":
            unit = "dpcm"
        else:
            raise ValueError("Bad JFIF")
        x = 256 * ord(data[14]) + ord(data[15])
        y = 256 * ord(data[16]) + ord(data[17])
    return {"unit":unit, "resolution":(x, y)}

rawDescription: How to extract image file details in Python (Windows)?

description: Extract image file details in Python (Windows)


code:
class Example(model.Model):
    #...
    def clean(self):
        if self.parent.id == self.id:
            raise ValidationError("no self referential models")

rawDescription: How to get field with ForeignKey('self') without the possibilty to link to same entry?

description: Get field with ForeignKey('self') without the possibilty to link to same entry


code:
for d in inputlist:
    words = d['stim'].split(',')
    d['stim'] = words[0]
    d.update(('stim{}'.format(i), word) for i, word in enumerate(words[1:], 1))

rawDescription: Python: Conditionally create new keys in list of dictionaries


code:
types=[str,int,int,int,float,float]
[f(x) for (f,x) in zip(types,line.split(', '))]

rawDescription: Cast list of string to different data type in python


code:
cmd = [
    './configure',
    'CXXFLAGS=-O2 -march=i586 -mtune=i686',
]
subprocess.Popen(cmd)

rawDescription: how to "export CFLAGS='my -flags -here' from python script


rawDescription: How to write the tuple into CSV file?

description: Write the tuple into CSV file


code:
word = 'lake1!'
new_word = ''
for char in word:
    if char.isalpha():
        new_word += char

rawDescription: Remove nonalphabet characters from a string


code:
import audiotools

f = audiotools.open(filename)
try:
    result = f.verify()
except audiotools.InvalidFile:
    # Invalid file.
    print("Invalid File")
else:
    # Valid file.
    print("Valid File")

rawDescription: Django/Python: How to read a file and validate that it is an audio file?


rawDescription: numpy: replicating each 1-d array element n times

description: Numpy: replicating each 1-d array element n times


code:
class MyRegressor():
    '''uses different regressors internally'''
    def __init__(self):
        self.randomForest = initializeRandomForest()
        self.kNN = initializekNN()

    def fit(self, X, y):
        '''calls the appropriate regressors'''
        X1 = X[X[:,0] == 1]
        y1 = y[X[:,0] == 1]
        X2 = X[X[:,0] != 1]
        y2 = y[X[:,0] != 1]
        self.randomForest.fit(X1, y1)
        self.kNN.fit(X2, y2)

    def predict(self, X):
        '''predicts values using regressors internally'''
        results = np.zeros(X.shape[0])
        results[X[:,0]==1] = self.randomForest.predict(X[X[:,0] == 1])
        results[X[:,0]!=1] = self.kNN.predict(X[X[:,0] != 1])

        return results

rawDescription: Use a different estimator based on value


code:
import random

# get the first line if this is the one with the words words
lines = open("../WordsForGames.txt").readlines()
line = lines[0]

words = line.split()
myword = random.choice(words)

rawDescription: Pulling a random word/string from a line in a text file in python


code:
def read_data(filename, fieldnames, n):
    data = numpy.fromfile(filename, count=n * len(fieldnames))
    assert len(data) == n * len(fieldnames)
    return dict((key, data[idx::len(fieldnames)]) for idx, key in enumerate(fieldnames))

rawDescription: matlab to python fread with eof

description: Matlab to python fread with eof


code:
def information(sentence):
    '''Splits the sentence on space and returns it as tuple'''
    split_up = tuple(sentence.split(' '))
    return split_up

def print_as_string():
    '''Prints tuple as string'''
    sentence = "welcome to SO dear friend"
    print(" ".join(information(sentence)))

if __name__ == "__main__":
    print_as_string()

rawDescription: How to print a returned tuple in another method

description: Print a returned tuple in another method


code:
class A(object):
    myVar=0
    def __init__(self):
        pass
    def doit(self):  # <--- Missing 'self' here
        print("A.doit(): {}".format(self.myVar))

class B(object):
    def __init__(self, other):

        #A.doit()       # This will not work.  It's not a class function now that we've added 'self'
        print("B.__init__: {}".format(A.myVar))
        other.doit()    # other is the passed in object

def main():
    a1=A()
    a1.myVar=1
    b1=B(a1)
    print("main: {}".format(A.myVar))

if __name__ == "__main__":
    main()

# Out
# B.__init__: 0
# A.doit(): 1
# main: 0

rawDescription: python - reference method of object defined in main

description: Python - reference method of object defined in main


code:
import dateutil.parser
dateutil.parser.parse('Feb 02, 1976')
dateutil.parser.parse('02-08-2001')

rawDescription: convert string of various format into datetime object

description: Convert string of various format into datetime object


code:
import rpy2
import pandas as pd
import pandas.rpy.common as com
rpy2.__version__
pd.__version__
datframe = pd.DataFrame({'a' : [1, 2, 3], 'b' : [3, 4, 5]})
r_df = com.convert_to_r_dataframe(datframe)
r_df

rawDescription: convert_to_r_dataframe module object has no attribute

description: Convert_to_r_dataframe module object has no attribute


code: pandas.concat([X[X.columns - Y.columns], Y], axis=1)

rawDescription: Update Pandas DataFrame with extra columns?


rawDescription: how to combine two data frames in python pandas

description: Combine two data frames in python pandas


code:
content = list(f)
f.write('905771\n')

rawDescription: How to check a python list whether it contains the element I have just inserted

description: Check a python list whether it contains the element I have just inserted


code:
writer = csv.writer(stringIO)
headers = ['HEADING1', 'HEADING2']
writer.writerow(headers)

writer = csv.writer(stringIO, quotechar='"', quoting=csv.QUOTE_ALL)
values=['value1', 'value2']
writer.writerow(values)

rawDescription: Only delimit values with quotes and not the headers


code: line = soup.find('img', attrs={'data-a-dynamic-image': True})

rawDescription: How to use Beautiful Soup's find() instead of find_all() for better runtime

description: Use Beautiful Soup's find() instead of find_all() for better runtime


code:
keypoints = detector.detect(frame) #list of blobs keypoints
x = keypoints[i].pt[0] #i is the index of the blob you want to get the position
y = keypoints[i].pt[1]

rawDescription: OpenCV return keypoints coordinates and area from blob detection, Python


rawDescription: Multiplying Multi Index Pandas Series and DataFrame


code:
from collections import Counter

def read_words(file_name):
    with open(file_name) as f:
        words = f.read().lower().split()
    return words

def top_n_words(counter, n):
    top_n = counter.most_common(n)
    print("Top %d words are:" % n)
    print("-" * 20)
    for w, c in top_n:
        # print("%10s: %-10s" % (w, c))
        print("{word:>10s}: {counts:<10d}".format(word=w, counts=c))

def word_appears(counter, w):
    print("The word '{word:s}' appears {time:d} times.".format(word=w,
        time=counter[w]))

if __name__ == '__main__':

    def main(file_name):
        words = read_words(file_name)
        counter = Counter(words)
        top_n_words(counter, 12)
        print("-" * 20)
        print("Total words: %d" % len(words))
        word_appears(counter, "history")

    main('words.txt')

rawDescription: How to reference a global variable in more than one function?

description: Reference a global variable in more than one function


code:
import waveapi.events
import waveapi.robot

def OnBlipSubmitted(properties, context):
    # Get the blip that was just submitted.
    blip = context.GetBlipById(properties['blipId'])
    # Respond to the blip (i.e. create a child blip)
    blip.CreateChild().GetDocument().SetText('That\'s so funny!')

def OnRobotAdded(properties, context):
    # Add a message to the end of the wavelet.
    wavelet = context.GetRootWavelet()
    wavelet.CreateBlip().GetDocument().SetText('Heeeeey everybody!')

if __name__ == '__main__':
    # Register the robot.
    bot = waveapi.robot.Robot(
        'The Annoying Bot',
        image_url='http://example.com/annoying-image.gif',
        version='1.0',
        profile_url='http://example.com/')
    bot.RegisterHandler(waveapi.events.BLIP_SUBMITTED, OnBlipSubmitted)
    bot.RegisterHandler(waveapi.events.WAVELET_SELF_ADDED, OnRobotAdded)
    bot.Run()

rawDescription: Google Wave Sandbox

description: Google Wave Sandbox


code:
to = []
p3 = email.split(',')
p4 = rname.split(',')
for i,em in enumerate(p3):
    recipient = {'email': em, 'name': None, 'type': to}
    if len(p4) > i:
        recipient = p4[i]
    to.append(recipient)

rawDescription: Convert Javascript function to python

description: Convert Javascript function to python


rawDescription: Split string by position not character

description: Split string by position not character


code:
class DescriptionsInline(admin.TabularInline):
    model = Descriptions
    exclude = ['modified']
    extra = 0
    def formfield_for_dbfield(self, field, **kwargs):
        if field.name == 'descriptiontype':
            parent_business = self.get_object(kwargs['request'], Business)
            if parent_business == None:
                related_descriptiontype = DescriptionType.objects.all()
            else:
                related_descriptiontype = DescriptionType.objects.filter(category=parent_business.category_id)
            return forms.ModelChoiceField(queryset=related_descriptiontype)
        return super(DescriptionsInline, self).formfield_for_dbfield(field, **kwargs)

    def get_object(self, request, model):
        object_id = request.META['PATH_INFO'].strip('/').split('/')[-1]
        try:
            object_id = int(object_id)
        except ValueError:
            return None
        return model.objects.get(pk=object_id)

rawDescription: Django admin inline conditional values

description: Django admin inline conditional values


code:
Z = {(1,1): 0, (2,2):1, (3,3):3}
hash(Z)
frozenset(Z.items())
hash(frozenset(Z.items()))

rawDescription: Dictionary be a Key in a Dictionary Python


code: s = your_lst[0]

rawDescription: How to make a list of one item just that item

description: Make a list of one item just that item


code:
sentence = s.lower()
counts = { letter: sentence.count(letter) for letter in alpha }
print(counts)

rawDescription: counting the frequency of a letter in a string

description: Counting the frequency of a letter in a string


code:
class Transplant:
    def __init__(self, method, host, method_name=None):
        self.host = host
        self.method = method
        self.method_name = method_name or method.__name__
        setattr(host, method_name or method.__name__, self)

    def __call__(self, *args, **kwargs):
        nargs = [self.host, self.method_name]
        nargs.extend(args)
        return apply(self.method, nargs, kwargs)

rawDescription: How to get name of called method (added dynamically) in Python?

description: Get name of called method (added dynamically) in Python


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

N = 150
highlightc = np.zeros([N, N])

M = 1000
hl = np.random.randint(N, size=(M, 2))
highlightc[zip(*hl)] = 1

colour = 0.21
fig, ax = plt.subplots()
h = ax.imshow(
    (highlightc * colour), interpolation='nearest', cmap=plt.cm.spectral_r,
    vmin=0, vmax=1)
plt.show()

rawDescription: colour a binary matrix matplotlib

description: Colour a binary matrix matplotlib


code:
class UpdateModelMixin(object):
    """
    Update a model instance.
    """
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        return Response(serializer.data)

    def perform_update(self, serializer):
        serializer.save()

    def partial_update(self, request, *args, **kwargs):
        kwargs['partial'] = True
        return self.update(request, *args, **kwargs)

rawDescription: Some actions with object in UpdateAPIView when update


code:
import urllib2
import csv
import requests
from django.core.management import setup_environ
from django.db import models
from yoursite import settings

setup_environ(settings)

from gmbl.models import Match

master_data_file = urllib2.urlopen("http://www.football-data.co.uk/mmz4281/1213/E0.csv", "GET")
data = list(tuple(rec) for rec in csv.reader(master_data_file, delimiter=','))

# ... your code ...

rawDescription: Importing CSV to Django and settings not recognised


code:
results = [0] * len(b)
for p_a in a:
    dists = [euclid(p_a, p_b) for p_b in b]
    min_index = dists.index(min(dists))
    results[min_index] += 1

rawDescription: Optimize counting in an array

description: Optimize counting in an array


rawDescription: Empty values in a Python list

description: Empty values in a Python list


rawDescription: How to check if my table has a specific letter

description: Check if my table has a specific letter


code: np.einsum('ijk,ki->ij', A, B)

rawDescription: dot product of subarrays without for loop

description: Dot product of subarrays without for loop


code: self.config = Config(self)

rawDescription: Tkinter; Toplevel in a new class

description: Tkinter; Toplevel in a new class


code:
# we are checking if we can make s2 from s1 just with inserts
def check(s1, s2):

    # indices for iterating through s1 and s2
    i1 = 0
    i2 = 0

    # dictionary to keep track of where to insert what
    inserts = dict()
    buffer = ""
    pos = 0

    while i1 < len(s1) and i2 < len(s2):
        if s1[i1] == s2[i2]:
            i1 += 1
            i2 += 1
            if buffer != "":
                inserts[pos] = buffer
                buffer = ""
            pos += 1
        else:
            buffer += s2[i2]
            i2 += 1

    # if possible return the what and where to insert, otherwise return false
    if i1 == len(s1):
        return inserts
    else:
        return False

rawDescription: converting a string to another only by insert in python

description: Converting a string to another only by insert in python


rawDescription: In python 2.x should I call object.__del__?


code:
class TaskDetailView(DetailView):
    model = Task
    template_name = 'todo/task_detail.html'

    def get_context_data(self, **kwargs):
        context = super(TaskDetailView, self).get_context_data(**kwargs)
        context['form'] = TaskForm()
        return context

rawDescription: Form inside page in Django

description: Form inside page in Django


code:
Dictionary = {}
with open('clues.txt') as f:
    for l in f:
        Dictionary[l[0]] = l[1]

rawDescription: How to import a text file into a dictionary

description: Import a text file into a dictionary


code: #!/home/explore/bin/python

rawDescription: Python not working in Linux shared hosting server


code: from Tkinter import *

rawDescription: Using tkMessageBox without importing Tkinter


rawDescription: How should I Arrange my data?

description: How should I Arrange my data


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

col = ['c', 'm', 'g', 'y', 'k']
c_dash = [[0,[8, 4]], [0,[8, 4, 2, 4]], 'solid', [0,[8, 4, 2, 4, 2, 4]], 'solid']

for i in range(5):
    x, y = range(10), np.random.uniform(0., 10., 10)
    plt.plot(x, y, color=col[i], linestyle=c_dash[i])

rawDescription: Plot continuous line using 'dashes' argument in matplotlib's plot()


code:
from numba import autojit

def autojit_except_when_unit_testing(func):
    if UNIT_TESTING:
        return func
    return autojit(func)

rawDescription: Can I compile numba in the setup phase of a unit test?

description: Compile numba in the setup phase of a unit test


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

class Exercises(models.Model):
    lesson = models.ForeignKey(Lessons)
    name = models.CharField()
    text = models.CharField()

rawDescription: How to make model, django

description: Make model, django


code: (n, bins, p) = plt.hist(numbers1, bins = 25, range = (25,75), normed=True)

rawDescription: asymmetry in matplotlib histograms

description: Asymmetry in matplotlib histograms


code:
f = open('junk', 'ab+')
f
f.write('hello\n')
f.seek(0, os.SEEK_SET)
f.readline()
f.write('there\n')
f.seek(0, os.SEEK_SET)
f.readline()
f.readline()

rawDescription: File mode for creating+reading+appending+binary


code:
def findNextZero(x, y, board):
    if board[x][y] == 0:
        return (x, y)
    else:
        if y == (SIZE-1):
            # if its at the edge of the "board", the 2d matrix
            return findNextZero(x+1, 0, board)
        else:
            return findNextZero(x, y+1, board)

rawDescription: Python recursive function returning Nonetype


code:
def nested_sum(q):
    sum = 0
    for v in q:
        if type(v) == int or type(v) == float:
            sum += v
        elif type(v) == list:
            sum += nested_sum(v)
    return sum

rawDescription: how would i write a recursive function to add all numbers in a deeply nested list of numbers and words

description: How would i write a recursive function to add all numbers in a deeply nested list of numbers and words


code:
import datetime
from System import DateTime
datetime.datetime(DateTime.Now)

rawDescription: How do I convert from a .NET DateTime to an IronPython datetime?

description: Convert from a .NET DateTime to an IronPython datetime


code:
import ttk
import Tkinter
root = Tkinter.Tk()

root.option_add("*TCombobox*Listbox*Background", 'green')

combo = ttk.Combobox().pack()
root.mainloop()

rawDescription: How to change background color in ttk.Combobox's listview?

description: Change background color in ttk.Combobox's listview


code:
def parse_line(line):
    """parse a score line, returning its data

    A score line is of the form: <username>,<level>,<level_score>

    The level and score are integers.
    """
    parts = line.split(',')
    if len(parts) != 3:
        return None # or raise an exception
    name = parts[0]
    level = int(parts[1])
    level_score = int(parts[2])
    return name, level, level_score

# read the lines
with open('scores.txt', 'r') as t:
    lines = t.readlines()

# parse the lines, ignoring empty lines
scores = [parse_line(line) for line in lines if line != ""]

# get the person's name
name = input("Enter a username: ") # Say 'buzzysin'

# filter that person's scores
persons_scores = [score for score in scores if score[0] == name]

# now print your table...

rawDescription: How do I read data sandwiched between a certain character (Python 3.3)

description: Read data sandwiched between a certain character (Python 3.3)


code:
from nltk.internals import find_jars_within_path
from nltk.parse.stanford import StanfordNeuralDependencyParser
parser = StanfordNeuralDependencyParser(model_path="edu/stanford/nlp/models/parser/nndep/english_UD.gz")
stanford_dir = parser._classpath[0].rpartition('/')[0]
slf4j_jar = stanford_dir + '/slf4j-api.jar'
parser._classpath = list(parser._classpath) + [slf4j_jar]
parser.java_options = '-mx5000m'
sent = "John sees Bill"
[parse.tree() for parse in parser.raw_parse(sent)]

rawDescription: Why Stanford parser with nltk is not correctly parsing a sentence?


code:
from os import getpid
from collections import defaultdict
from glob import glob
from multiprocessing import Pool
from time import time
from functools import partial

path = '/data/personal'
print("Running with PID: %d" % getpid())

def process_file(psl, filename):
    print(filename)
    f = open(filename, 'r')
    for n, line in enumerate(f):
        line = line[:-1]
        ip,reversed_domain_1= line.split('|')
        reversed_domain_2 = reversed_domain_1.split('.')
        reversed_domain_3 = list(reversed(reversed_domain_2))
        domain = ('.'.join(reversed_domain_3))
        domain = psl.get_public_suffix(domain)
        return ip, domain

if __name__ == "__main__":
    psl = PublicSuffixList()
    d = defaultdict(set)
    start = time()
    files_list = glob(path)
    pp = Pool(processes=cores)
    func = partial(process_file, psl)
    results = pp.imap_unordered(func, files_list)
    for ip, domain in results:
       d[ip].add(domain)
    p.close()
    p.join()

    for ip, domains in d.iteritems():
        for domain in domains:
            print(ip,domain)

rawDescription: How to define an input for python multiprocessing function to take all the files in a directory?

description: Define an input for python multiprocessing function to take all the files in a directory


code:
timeStamp="2013-09-19T21:37:04Z"
timeStamp_dt = datetime.datetime.strptime(timeStamp, '%Y-%m-%dT%H:%M:%SZ')
now = datetime.datetime.now()
age = now - timeStamp_dt
if age < datetime.timedelta(minutes=30):
    doStuff()

rawDescription: Time since a isodate timestamp in python


code:
sns.set(font_scale=1.4)
cmap = sns.diverging_palette(h_neg=210, h_pos=350, s=90, l=30, as_cmap=True)
sns.clustermap(data=corr, annot=True, fmt='d', cmap="Blues", annot_kws={"size": 16})

rawDescription: Change xticklabels fontsize of seaborn heatmap


code:
current_ids = set(soldier.id for soldier in user.soldiers)
for soldier_class in soldierlist:
    if soldier_class.id not in current_ids:
         user.soldiers.append( soldier_class() )

rawDescription: Fastest way in python for finding object with certain attribute value from list?


code:
class YearReviews(YearArchiveView):

    def get_context_data(self, **kwargs):
        context = super(YearReviews, self).get_context_data(**kwargs)
        context['years_available'] = self.queryset.dates(self.date_field, 'year')
        return context

rawDescription: Can a Django YearArchiveView return a list of all possible years?


rawDescription: Regex a: b c d a:b

description: Regex a: b c d a:b


code:
x = range(1,10)
y = range(8,20)
xs = set(x)
xs.intersection(y)

rawDescription: How to find range overlap in python?

description: Find range overlap in python


rawDescription: Formatting time from Google Calendar API with Python


code:
import struct
struct.pack('f', 3.141592654)
struct.unpack('f', b'\xdb\x0fI@')
struct.pack('4f', 1.0, 2.0, 3.0, 4.0)

rawDescription: Convert Bytes to Floating Point Numbers in Python


code:
def __unicode__(self):
    return unicode(self.cliente)

rawDescription: How to use Unicode for a ForeignKeyField, Django

description: Use Unicode for a ForeignKeyField, Django


code: "didn't".replace("'", "")

rawDescription: Replace the single quote (') character from a string


code:
# creates 201 values evenly spaced from 0 to 2e6, inclusive
f = np.linspace(0, 2e6, 201)
w = 2 * np.pi * f
# now calculate the magnitude for all 201 values at once
magnitude = (w * L - 1 / (w * C)) / np.sqrt(R**2 + (w * L - 1 / (w * C))**2)
# now you can plot magnitude vs. frequency
plt.plot(f / 1e6, magnitude, '-k')

rawDescription: algebraic expressions in python

description: Algebraic expressions in python


code:
def save_df(df, chunk_size=100000):
    for i, start in enumerate(range(0, df_size, chunk_size)):
        df[start:start+chunk_size].to_csv('df_name_{}.csv'.format(i))

rawDescription: Splitting a Pandas Data Frame into Rows by Count


code: plt.plot(x, y, linestyle='-', color='r')

rawDescription: Plotting line color and style in matplotlib time-series


rawDescription: Optimizing pairwise calculation of distances an array for a given shift


rawDescription: How to replace part of str using `re.sub()`?

description: Replace part of str using `re.sub()`


code:
rcvd_msg = None
lock = thread.Condition()

# executed in the main thread
with lock:
    while rcvd_msg == None:
        lock.wait()
    # read rcvd_msg
    rcvd_msg = None
    lock.notifyAll()

class Listener(ConnectionListener):

    def on_message(self, headers, message):
        # executed in the receiver thread
        global rcvd_msg, lock
        with lock:
            while rcvd_msg != None:
                lock.wait()
            rcvd_msg = message
            lock.notifyAll()

rawDescription: Stomp.py return message from listener

description: Stomp.py return message from listener


code:
@mock.path('mymodule.utils.another_file.get_remote_value')
class MyTest(TestCase):
    def first_test(self, mock_get_remote_value):
        mock_get_remote_value.return_value = True
        self.assertEqual(check_remote_value(), True)

    def second_test(self, mock_get_remote_value):
        mock_get_remote_value.return_value = False
        self.assertEqual(check_remote_value(), False)

rawDescription: Python mock: mock object not updated when running multiple tests


code:
MAJOR               = 1
MINOR               = 8
MICRO               = 0

VERSION             = '%d.%d.%d' % (MAJOR, MINOR, MICRO)

rawDescription: How to check the current version of numpy in the source code?

description: Check the current version of numpy in the source code


rawDescription: How to match elements of two arrays and return a value

description: Match elements of two arrays and return a value


code:
GBasMB = int(1000000000) # Allows for accurate Bytes to GB conversion

global RAMSTRROUNDED
RAMTOTAL = int(SYSINFO.TotalPhysicalMemory) / (GBasMB) # Outputs GB by dividing by previous MB variable
RAMROUNDED = math.ceil(RAMTOTAL / 2.) * 2 # Rounds up to nearest even whole number
RAMSTRROUNDED = int(RAMROUNDED) # final converted variable

HDDTOTAL = int(HDDINFO.size) / (GBasMB) # Similar process as before for HardDrive
HDDROUNDED = math.ceil(HDDTOTAL / 2.) * 2 # round up to nearest even whole number

def ROUNDHDDTBORGB(): # function for determining TB or GB sized HDD
    global HDDTBORGBOUTPUT
    global HDDPRNT
    if HDDROUNDED >= 1000: # if equal to or greater than 1000GB, list as 1TB
        HDDTBORGB = HDDROUNDED * .001
        HDDTBORGBOUTPUT = str(HDDTBORGB) + "TB"
        HDDPRNT = "HDD: " + str(HDDTBORGBOUTPUT)
        print(HDDPRNT)
    elif HDDROUNDED < 1000: # if less than 1000GB list as GB
        HDDTBORGBOUTPUT = str(str(HDDROUNDED) + "GB")
        HDDPRNT = "HDD: " + str(HDDTBORGBOUTPUT)

rawDescription: Round system RAM and HDD bytes, UP to nearest even gigabyte. Python


code:
import file1
import file2
reload(file1)
reload(file2)

func1, func2 = file1.func1, file1.func2
func3 = file2.func3

rawDescription: Reloading python module with flattened namespace


code:
@app.after_request
def add_header(response):
    """
    Add headers to both force latest IE rendering engine or Chrome Frame,
    and also to cache the rendered page for 10 minutes.
    """
    response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
    response.headers['Cache-Control'] = 'public, max-age=0'
    return response

rawDescription: Browser caching issues in flask

description: Browser caching issues in flask


code:
a[start:end] # items start through end-1
a[start:]    # items start through the rest of the array
a[:end]      # items from the beginning through end-1
a[:]         # a copy of the whole array

rawDescription: Why does printing a[0][:0:] give me a different answer than printing a[0][0] ? (Python multi-Dimensional array)


code:
from selenium import webdriver
from concurrent.futures import ThreadPoolExecutor

URL ="https://pypi.python.org/pypi/{}"

li =["pywp/1.3","augploy/0.3.5"]

def get_content(url):
    driver = webdriver.Firefox()
    driver.get(url)
    tag = driver.find_element_by_tag_name("a")
    # do your work here and return the result
    return tag.get_attribute("href")

li = list(map(lambda link: URL.format(link), li ))

futures = []
with ThreadPoolExecutor(max_workers=2) as ex:
    for link in li:

        futures.append(ex.submit(get_content,link))

for future in futures:
    print(future.result())

rawDescription: How to use several instance of selenium [python]

description: Use several instance of selenium [python]


code:
class mylist (list):

    def __getitem__(self, n):
        if n < 0:
            raise IndexError("...")
        return list.__getitem__(self, n)

keyboard = mylist() # instead of []

rawDescription: How to make Python refuse negative index values?

description: Make Python refuse negative index values


code:
def _spawn(self, data, overrides={}):
    """
    Creates a new audio segment using the metadata from the current one
    and the data passed in. Should be used whenever an AudioSegment is
    being returned by an operation that would alters the current one,
    since AudioSegment objects are immutable.
    """
    # accept lists of data chunks
    if isinstance(data, list):
        data = b''.join(data)

    # accept file-like objects
    if hasattr(data, 'read'):
        if hasattr(data, 'seek'):
            data.seek(0)
        data = data.read()

    metadata = {
        'sample_width': self.sample_width,
        'frame_rate': self.frame_rate,
        'frame_width': self.frame_width,
        'channels': self.channels
    }
    metadata.update(overrides)
    return self.__class__(data=data, metadata=metadata)

rawDescription: How to force to a class?

description: Force to a class


code:
crypted_password = db.StringProperty()
salt = db.StringProperty()

def __encrypt(self, plaintext, salt=''):
    """returns the SHA1 hexdigest of a plaintext and salt"""

    phrase = hashlib.sha1()
    phrase.update('%s--%s' % (plaintext, salt))
    return phrase.hexdigest()

def set_password(self, new_password):
    """sets the user's crypted_password"""

    import datetime
    if not self.salt:
        self.salt = self.__encrypt(str(datetime.datetime.now()))
    self.crypted_password = self.__encrypt(new_password, self.salt)

rawDescription: Storing the result of an SHA hash as a db.StringProperty() property


code:
df = (pd.concat([df1, df2])
      .groupby(['ID','X','Y'])
      .agg({'value':'max', 'value_sum':'sum'}))

rawDescription: Compare rows of 2 pandas data frames by column and keep bigger and sum


code:
success, num = fixture.GetNumDataPoints(num)
success, voltages = fixture.GetDataPoints(num, voltages)

rawDescription: How do I get a reference to an array back from VB when using IronPython?

description: Get a reference to an array back from VB when using IronPython


code:
def get_infobox(site=None, name=None, templates=None):
    if site is not None and name is not None and templates is None:
        get_infobox_from_site_and_name(site, name)
    elif templates is not None and site is None and name is None:
        get_infobox_from_list(templates)
    else:
        raise Exception # or some particular type of exception

rawDescription: Resolve overloading in Python

description: Resolve overloading in Python


code:
from win32com.shell import shell, shellcon
import win32api

folder = win32api.GetTempPath()
folder_pidl=shell.SHILCreateFromPath(folder,0)[0]
desktop = shell.SHGetDesktopFolder()
shell_folder = desktop.BindToObject(folder_pidl, None, shell.IID_IShellFolder)
items = [item for item in shell_folder][:5]
## print (items)
shell.SHOpenFolderAndSelectItems(folder_pidl, items, 0)

rawDescription: How to open folder with specified items selected on Windows

description: Open folder with specified items selected on Windows


rawDescription: Do Django models have a data dict containing all the current values?


code:
class RssFooFeedGenerator(Rss201rev2Feed):
    def add_root_elements(self, handler):
        super(RssFooFeedGenerator, self).add_root_elements(handler)
        handler.addQuickElement(u"image", '',
            {
                 'url': u"http://www.example.com/images/logo.jpg",
                 'title': u"Some title",
                 'link': u"http://www.example.com/",
             })

class RssFooFeed(Feed):
    feed_type = RssFooFeedGenerator
    title = u"Foo items"
    link = u"http://www.example.com/"
    description = u"Some description"

rawDescription: Django-way of specifying channel image in rss feed


code:
import datetime
from time import sleep

SECONDS_PER_DAY = 3600 * 24
DAILY_START_TIME = datetime.time(8,15)   # 8:15 am

def seconds(t):
    return 3600*t.hour + 60*t.minute + t.second

def now():
    t = datetime.datetime.now()
    return t.weekday(), seconds(t)

def load_run_days():
    # get data from registry
    return [1,1,1,1,1,0,0]

def days_until_next_run(today, run_days=None):
    if run_days is None:
        run_days = load_run_days()
    # rotate
    run_days = run_days[today+1:] + run_days[:today+1]
    # find next On day
    for days,_on in enumerate(run_days, 1):
        if _on:
            return days
    # no run day found?
    raise ValueError("No 'On' days found")

def sleep_until_next_run():
    today, elapsed = now()
    days_to_wait = days_until_next_run(today)
    sleep(-elapsed + days_to_wait*SECONDS_PER_DAY + seconds(DAILY_START_TIME))

def main():
    while True:
        try:
            sleep_until_next_run()
        except ValueError:
            break

        do_my_stuff()

if __name__=="__main__":
    main()

rawDescription: Custom Timer to get the seconds to the next start time/date


code:
initial = "aSuffixbSuffixcSuffix"

final = initial.replace("Suffix", "Suffix ")
print(final)

rawDescription: Separating a string in Python

description: Separating a string in Python


rawDescription: Stripping start/end characters on regular expression


code:
base_url = "http://www.example.com/dir1/dir2"
next = "/index.html"

rawDescription: How to get the full url from a link

description: Get the full url from a link


code:
import csv
with open('some.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)

rawDescription: How to write a python code which copies a unique column from an output file to a .csv file

description: Write a python code which copies a unique column from an output file to a .csv file


code:
strs=b'\x0f\x00\x00\x00NR09G05164\x00'
import binascii
binascii.hexlify(strs)

rawDescription: Python : convert a hex string

description: Python : convert a hex string


code:
class_dict= defaultdict(lambda: defaultdict(lambda: defaultdict(str)))
for (section, stu, sub) in zip(sections, students, subjects):
    l = len(class_dict[section][stu])
    class_dict[section][stu][l+1] = sub

rawDescription: How To Merge 3 lists into one dictionary(with unique elements)


code:
from datetime import datetime
dt = datetime.fromtimestamp(1449798068)
print(dt)

rawDescription: UTS to DateTime in Python from Last.fm API


rawDescription: create a file in the script using python

description: Create a file in the script using python


rawDescription: How to write JSON requests using django

description: Write JSON requests using django


code:
class AboutFrame(wx.Frame):

    title = "About this program"

    def __init__(self):
        wx.Frame.__init__(self, wx.GetApp().TopWindow, title=self.title)

rawDescription: Creating child frames of main frame in wxPython


code:
import sys
import requests
from BeautifulSoup import BeautifulSoup

def scrape_google(keyword):

    # dynamically build the URL that we'll be making a request to
    url = "http://www.google.com/search?q={term}".format(
        term=keyword.strip().replace(" ", "+"),
    )

    # spoof some headers so the request appears to be coming from a browser, not a bot
    headers = {
        "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)",
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
        "accept-encoding": "gzip,deflate,sdch",
        "accept-language": "en-US,en;q=0.8",
    }

    # make the request to the search url, passing in the the spoofed headers.
    r = requests.get(url, headers=headers)  # assign the response to a variable r

    # check the status code of the response to make sure the request went well
    if r.status_code != 200:
        print("request denied")
        return
    else:
        print("scraping " + url)

    # convert the plaintext HTML markup into a DOM-like structure that we can search
    soup = BeautifulSoup(r.text)

    # each result is an <li> element with class="g" this is our wrapper
    results = soup.findAll("li", "g")

    # iterate over each of the result wrapper elements
    for result in results:

        # the main link is an <h3> element with class="r"
        result_anchor = result.find("h3", "r").find("a")

        # print out each link in the results
        print(result_anchor.contents)

if __name__ == "__main__":

    # you can pass in a keyword to search for when you run the script
    # be default, we'll search for the "web scraping" keyword
    try:
        keyword = sys.argv[1]
    except IndexError:
        keyword = "web scraping"

    scrape_google(keyword)

rawDescription: web scraping tutorial using python 3?

description: Web scraping tutorial using python 3


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

# Need to do this so we don't have to worry about how many lines we have -
# matplotlib doesn't like one x and multiple ys, so just repeat the x
lines = []
for y in ys:
    lines.append(x)
    lines.append(y)

ax.plot(*lines)

fig.savefig("filename.png")

rawDescription: Python Matplotlib to smtplib

description: Python Matplotlib to smtplib


code:
for path,dirs,files in os.walk('data/'):
    for f in files:
        fname = os.path.join(path,f)
        assert(os.path.exists(fname))

rawDescription: Correct usage of os.path and os.join

description: Correct usage of os.path and os.join


code:
dis.dis(compile('a==2==b', '', 'eval'))
dis.dis(compile('a==2 and b==2', '', 'eval'))

rawDescription: What's faster, a==2==b, or a==2 and b==2


code:
sentinel = None
while True:
  item = queue.get()
  if item == sentinel:
    break
  # do stuff
  queue.task_done()

rawDescription: How does this loop works: for item in iter(queue.get, None)?


code:
curs = conn.cursor()
curs.execute('select * from bigtable')

rawDescription: Using Python/PyGreSQL, how can I efficiently handle a large result set?


code: seven_up = __import__("7update")

rawDescription: python: importing a file that is not a valid identifier?

description: Python: importing a file that is not a valid identifier


code:
import itertools
x = 2
[''.join(i) for i in itertools.product('10', repeat=x)]

rawDescription: Generate values of N digits among 2 values


code:
my_list = [1, 2, 3, 4, 5]
query = db.session.query(Sensor).filter(Sensor.experiment_id == pandas_id)

for obj, new_value in itertools.izip(query, my_list):
    obj.value = new_value
    db.session.add(obj)  # I think this line can be removed

db.session.commit()

rawDescription: Flask-SQL Alchemy iterate over query and update values


code:
lp = [0] * 10000
for index in l:
    lp[index - 1] = 1

rawDescription: convert a numbered list into an order list

description: Convert a numbered list into an order list


code:
#!/usr/bin/env python
import os
import sys
import platform
from subprocess import Popen, PIPE

# set system/version dependent "start_new_session" analogs
kwargs = {}
if platform.system() == 'Windows':
    # from msdn [1]
    CREATE_NEW_PROCESS_GROUP = 0x00000200  # note: could get it from subprocess
    DETACHED_PROCESS = 0x00000008          # 0x8 | 0x200 == 0x208
    kwargs.update(creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
elif sys.version_info < (3, 2):  # assume posix
    kwargs.update(preexec_fn=os.setsid)
else:  # Python 3.2+ and Unix
    kwargs.update(start_new_session=True)

p = Popen(["C"], stdin=PIPE, stdout=PIPE, stderr=PIPE, **kwargs)
assert not p.poll()

rawDescription: Popen waiting for child process even when the immediate child has terminated


code:
class SillyExampleFriendsList(object):
    """Just manipulates a couple lists"""
    def __init__(self):
       self._lock = threading.RLock()
       self._friends = []
       self._enemies = []

    def unfriend(self, x):
       # we lock here to ensure that we're never in a state where
       # someone might think 'x' is both our friend and our enemy.
       self._lock.acquire()
       self._friends.remove(x)
       self._enemies.append(x)
       self._lock.release()

rawDescription: Twisted threading howto avoid deepcopy

description: Twisted threading howto avoid deepcopy


code:
ord('a')
hex(ord('a'))
bin(ord('a'))

rawDescription: printing bit representation of numbers in python

description: Printing bit representation of numbers in python


code:
import sympy as sp
x, y, z = sp.symbols('x, y, z')
rho, sigma, beta = sp.symbols('rho, sigma, beta')
f1 = sigma * (y - x)
f2 = x * (rho - z) - y
f3 = x * y - beta * z
sp.solvers.solve((f1, f2, f3), (x, y, z))

rawDescription: Solving system of nonlinear equations with python


code:
import asyncio
import aiohttp

urls = [
    'http://www.whitehouse.gov/cea/',
    'http://www.whitehouse.gov/omb',
    'http://www.google.com']

def test_async():
    connector = aiohttp.TCPConnector(verify_ssl=False)
    for url in urls:
        try:
            r = yield from aiohttp.request('get', url, connector=connector)
        except aiohttp.errors.ClientOSError as e:
            print('bad eternal link %s: %s' % (url, e))
        else:
            print(r.status)

if __name__ == '__main__':
    print('async')
    asyncio.get_event_loop().run_until_complete(test_async())

rawDescription: asynchronous aiohttp requests fails, but synchronous requests succeed

description: Asynchronous aiohttp requests fails, but synchronous requests succeed


code:
df.sort(['id', 'Time'], inplace=True)
df['Transition'] = df.Category != df.Category.shift(1)
df.loc[df.id != df.id.shift(1), 'Transition'] = np.nan

rawDescription: Column operations on pandas groupby object


code:
import os
os.system('lpr <here you need to find out about the arguments>')

rawDescription: How to physically print something out with python?

description: Physically print something out with python


code:
import numpy as np
import pylab as plt
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection

fig, ax = plt.subplots(figsize=(10,10))
rands = np.random.random_sample((N,))

patches = []
colors  = []

for x in range(N):
    C = Circle((x/float(N), rands[x]), .01)
    colors.append([rands[x],rands[x],rands[x]])
    patches.append(C)

plt.axis('equal')
ax.set_xlim(0,1)
ax.set_ylim(0,1)

collection = PatchCollection(patches)
collection.set_facecolor(colors)
ax.add_collection(collection)
plt.show()

rawDescription: Can I pass a list of colors for points to matplotlib's 'Axes.plot()'?

description: Pass a list of colors for points to matplotlib's 'Axes.plot()'


code:
from Tkinter import *
import tkFont

master = Tk()

canvas = Canvas(master, width=600, height=150)
canvas.grid(row=0, column=0, columnspan=2, sticky=W+N+E+S)

list = Listbox(master)
for f in sorted(tkFont.families()):
    list.insert(END, f)

list.grid(row=1, column=0)

font_size= IntVar()
ruler = Scale(master, orient=HORIZONTAL, from_=1, to=200, variable=font_size)
ruler.grid(row=1, column=1, sticky=W+E)

def font_changed(*args):
    sel = list.curselection()
    font_name = list.get(sel[0]) if len(sel) > 0 else "Times"
    canvas.itemconfig(text_item, font=(font_name,font_size.get()))
    #force redrawing of the whole Canvas
    # dirty rectangle of text items has bug with "superscript" character
    canvas.event_generate("<Configure>")

def draw():
    supernumber_exception={1:u'\u00b9', 2:u'\u00b2', 3:u'\u00b3'}
    mytext =""
    for i in range(10):
        mytext += u'U'+ (supernumber_exception[i] if i in supernumber_exception else unichr(8304+i))+" "
    return canvas.create_text(50, 50,text = mytext, anchor=NW)

text_item = draw()

list.bind("<<ListboxSelect>>", font_changed)

font_size.trace("w", font_changed)
font_size.set(30)

master.grid_columnconfigure(0, weight=0)
master.grid_columnconfigure(1, weight=1)
master.grid_rowconfigure(0, weight=1)
master.grid_rowconfigure(1, weight=0)

master.mainloop()

rawDescription: Problems with superscript using Python tkinter canvas


rawDescription: Append the same value multiple times to a list


code:
import wx
import wx.wizard

class WizardPage(wx.wizard.PyWizardPage):
    def __init__(self, parent, title):
        wx.wizard.PyWizardPage.__init__(self, parent)
        self.next = None
        self.prev = None
        self.initializeUI(title)

    def initializeUI(self, title):
        # create grid layout manager
        self.sizer = wx.GridBagSizer()
        self.SetSizerAndFit(self.sizer)

    def addWidget(self, widget, pos, span):
        self.sizer.Add(widget, pos, span, wx.EXPAND)

    # getters and setters
    def SetPrev(self, prev):
        self.prev = prev

    def SetNext(self, next):
        self.next = next

    def GetPrev(self):
        return self.prev

    def GetNext(self):
        return self.next

########################################################################
class MyWizard(wx.wizard.Wizard):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.wizard.Wizard.__init__(self, None, -1, "Some Title")
        self.SetPageSize((500, 350))

        mypage1 = self.create_page1()

        forward_btn = self.FindWindowById(wx.ID_FORWARD)
        forward_btn.Disable()

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

        self.RunWizard(mypage1)

    #----------------------------------------------------------------------
    def create_page1(self):
        page1 = WizardPage(self, "Page 1")
        d = wx.StaticText(page1, label="test")
        page1.addWidget(d, (2, 1), (1,5))

        self.text1 = wx.TextCtrl(page1)
        page1.addWidget(self.text1, (3,1), (1,5))

        self.text2 = wx.TextCtrl(page1)
        page1.addWidget(self.text2, (4,1), (1,5))

        page2 = WizardPage(self, "Page 2")
        page3 = WizardPage(self, "Page 3")

        # Set links
        page2.SetPrev(page1)
        page1.SetNext(page2)
        page3.SetPrev(page2)
        page2.SetNext(page3)

        return page1

    #----------------------------------------------------------------------
    def onUpdate(self, event):
        """
        Enables the Next button if both text controls have values
        """
        value_one = self.text1.GetValue()
        value_two = self.text2.GetValue()
        if value_one and value_two:
            forward_btn = self.FindWindowById(wx.ID_FORWARD)
            forward_btn.Enable()
            self.timer.Stop()

#----------------------------------------------------------------------
def main():
    """"""
    wizard = MyWizard()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    main()
    app.MainLoop()

rawDescription: How do I disable the "Next" button of wxPython wizard page?

description: Disable the "Next" button of wxPython wizard page


rawDescription: Best way to trigger a Node-RED flow from python script

description: Trigger a Node-RED flow from python script


code:
class test:
    def __nonzero__(self):
        return False

rawDescription: overriding bool() for custom class

description: Overriding bool() for custom class


code:
# Step #1
img = cv2.imread('contour.png', 0)
img_bw = img <= 128
img_bw = 255*img_bw.astype('uint8')

# Step #2
contours, _ = cv2.findContours(img_bw,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

# Step #3
out = img.copy()

# Step #4
ref = np.zeros_like(img_bw)
cv2.drawContours(ref, contours, 0, 255, 1)

# Step #5
M = cv2.moments(contours[0])
centroid_x = int(M['m10']/M['m00'])
centroid_y = int(M['m01']/M['m00'])

# Get dimensions of the image
width = img.shape[1]
height = img.shape[0]

# Define total number of angles we want
N = 20

# Step #6
for i in range(N):
  # Step #6a
  tmp = np.zeros_like(img_bw)

  # Step #6b
  theta = i*(360/N)
  theta *= np.pi/180.0

  # Step #6c
  cv2.line(tmp, (centroid_x, centroid_y),
           (int(centroid_x+np.cos(theta)*width),
            int(centroid_y-np.sin(theta)*height)), 255, 5)

  # Step #6d
  (row,col) = np.nonzero(np.logical_and(tmp, ref))

  # Step #6e
  cv2.line(out, (centroid_x, centroid_y), (col[0],row[0]), 0, 1)

# Show the image
# Step #7
cv2.imshow('Output', out)
cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: OpenCV: Lines passing through centroid of contour at given angles