code:
from multiprocessing import Pool
import contextlib

num_threads = 10

with contextlib.closing( Pool(num_threads) ) as pool:
    results = pool.map(Function, lst)

rawDescription: Multiprocessing on a set number of cores


code:
defined_in_class = (len(frames) > 2 and
                    frames[2][4][0].strip().startswith('class '))

rawDescription: Python: can a decorator determine if a function is being defined inside a class?


rawDescription: Remove matched tags in html files?

description: Remove matched tags in html files


code:
is_line_ok("this line contains bad text2.")
is_line_ok("this line's ok.")

rawDescription: What's the fastest way to remove duplicate lines in a txt file(and also some lines which contain specific strings) using python?


code:
def flat_list_keeping_track(l, track=None):
    track = track or ()
    for i, node in enumerate(l):
        new_track = track + (i,)
        if isinstance(node, list):
            for result in flat_list_keeping_track(node, track=new_track):
                yield result
        else:
            yield node, new_track

rawDescription: How can I find the index for a list of nested lists which I am recursing over?

description: Find the index for a list of nested lists which I am recursing over


code: a = combine_dicts(base1, base2, {'some non-identifier key': 42}, r=3)

rawDescription: Defined dict entries Python

description: Defined dict entries Python


code: my_rows = [row for row in reader]

rawDescription: Aparrent looping issue: Why am I appending the same thing to my list over and over again?


rawDescription: PyQt/Pyside - Create & Connect Dynamically - capturing function and arguments in lambda


code: stops = [(3*i,x) for i,x in enumerate(by3) if x in ["TAG","TGA","TAA"]]

rawDescription: Getting Python to read a text file in chunks of 3 (codons) and give me an output


code: s1,_,s2 = raw_input('Enter a range: ').partition(',')

rawDescription: input 2 variables separated by a comma in a single line

description: Input 2 variables separated by a comma in a single line


rawDescription: Creating a table out of data in python

description: Creating a table out of data in python


rawDescription: Change ALL html tags to symbol using python


code:
import myapplication

class MockApplication(myapplication.Application):
    class Mailer(myapplication.Application.Mailer):
        def send(self, message, recipients):
            self.owner.log('Mail send called (not actually sent)')
            return True

rawDescription: Organizing a large Python project that must share an internal state?


rawDescription: Populating a list with elements from different lists in Python


rawDescription: How can I build a regular expression which has options part

description: Build a regular expression which has options part


code:
from functools import reduce  # For Python 3.x
from pyspark.sql import DataFrame

def unionAll(*dfs):
    return reduce(DataFrame.unionAll, dfs)

df1 = sqlContext.createDataFrame([(1, "foo1"), (2, "bar1")], ("k", "v"))
df2 = sqlContext.createDataFrame([(3, "foo2"), (4, "bar2")], ("k", "v"))
df3 = sqlContext.createDataFrame([(5, "foo3"), (6, "bar3")], ("k", "v"))

unionAll(df1, df2, df3).show()

## +---+----+
## |  k|   v|
## +---+----+
## |  1|foo1|
## |  2|bar1|
## |  3|foo2|
## |  4|bar2|
## |  5|foo3|
## |  6|bar3|
## +---+----+

rawDescription: Spark union of multiple RDDs

description: Spark union of multiple RDDs


rawDescription: Aligning bins to xticks in plt.hist

description: Aligning bins to xticks in plt.hist


code:
sql = "insert into sensor values (%s, %s, tstzrange(%s, NULL));"
curs.execute(sql, (hostname, ip, ts))

sql = "update sensor set period = tstzrange(lower(period), %s) where hostname = %s and upper_inf(period);"

rawDescription: python insert and update tstzranges with psycopg2

description: Python insert and update tstzranges with psycopg2


code:
def zerolistmaker(n):
    listofzeros = [0] * n
    return listofzeros

rawDescription: List of zeros in python

description: List of zeros in python


code: shutil.copytree(src, dst)

rawDescription: Python: recursively copy batch of directories


code:
import itertools as it

l = ['Bill', 'Patrick', 'Aaron', 'Ann',
     'Jane', 'Rachel', 'Beatrix',
     'John', 'Basil', 'Alice', ]
l = iter(l)

print(
    list(
        it.chain(
            it.dropwhile(lambda _: True, iter(lambda: next(l), 'Ann')),
            iter(lambda: next(l), 'John')
        )
    )
)

rawDescription: Pythonic way to return interval from a list


code: middle if middle != "Missing" else ""

rawDescription: Using a for loop to concatenate columns in Pandas


code: df['EventCount'] = df['Event'].str.count("/") + 1

rawDescription: How to get the length of a cell value in pandas dataframe?

description: Get the length of a cell value in pandas dataframe


code:
rackset = frozenset(rack)
scored =  [(score_word(word), word) for word in words if word[0] in rackset \
           and spellable(word, rack)]

rawDescription: How can this Python Scrabble word finder be made faster?


rawDescription: how to get the neighboring elements in a numpy array with taking boundaries into account?

description: Get the neighboring elements in a numpy array with taking boundaries into account


code: re.sub(r'^(\t*)', r'\1 Added String here. ', inputtext)

rawDescription: Add string between tabs and text

description: Add string between tabs and text


code:
def exp_func(x):
    return np.dot(np.arange(len(x)), np.power(x, 10))/(np.sum(np.power(x, 10)))

weighted_sum = np.apply_along_axis(exp_func,0, clipped_background)

rawDescription: How can I extract this obvious event from this image?

description: Extract this obvious event from this image


code:
class new_integer(int):
  to_decorate = ( '__add__', '__sub__', ...)
  for k in to_decorate:
    locals()[k] = magic_decorator(getattr(int, k))

  del to_decorate, k

rawDescription: Argument parsing with python decorators

description: Argument parsing with python decorators


rawDescription: Numpy Detection of region borders

description: Numpy Detection of region borders


rawDescription: How do I change the widget type of the DELETE field in a django formset

description: Change the widget type of the DELETE field in a django formset


code:
serializers.py
from .models import Speaker
from rest_framework import serializers
from django.contrib.auth.models import User

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')
        lookup_field = 'username'

class SpeakerSerializer(serializers.HyperlinkedModelSerializer):
    user = serializers.HyperlinkedRelatedField(
        view_name='user-detail',
        read_only=True,
        lookup_field='username'
    )
    class Meta:
        model = Speaker
        fields = ('url', 'user')
        lookup_field = 'user__username'

rawDescription: django rest framework lookup_field through OneToOneField

description: Django rest framework lookup_field through OneToOneField


code: from matplotlib import pyplot as PLT

rawDescription: How do I set a matplotlib colorbar extents?

description: Set a matplotlib colorbar extents


code:
list1 =[[1, 11], [2, 22], [3, 33], [4, 44]]
list2 = list()

# Iterate over list1 two by two, first round: sublist = ([1,11], [2,22])
for sublist in zip(list1[0::2], list1[1::2]):

    inner_result = list()

    # Second loop equivalent to for tup in zip(sublist[0], sublist[1])
    for tup in zip(*sublist):  # First round, tup will be (1,2) then (11, 22)

        # Make dictionary from tuple, for first tuple this is
        # equivalent to: dict([(1,2)]) == {1: 2}
        new_dict = dict([tup])
        inner_result.append(new_dict)

    list2.append(inner_result)

rawDescription: how to convert two-dimensional list to another list with dict as elements

description: Convert two-dimensional list to another list with dict as elements


rawDescription: Does Python optimize function calls from loops?


code:
A
A_new = np.zeros(new_shape,dtype = A.dtype)
A_new[0:A.shape[0],0:A.shape[1]] = A
A_new

rawDescription: python - increase array size and initialize new elements to zero

description: Python - increase array size and initialize new elements to zero


code:
STOCK_ABOUT
STOCK_ADD
STOCK_APPLY
STOCK_BOLD
STOCK_CANCEL
STOCK_CAPS_LOCK_WARNING
STOCK_CDROM
STOCK_CLEAR
STOCK_CLOSE
STOCK_COLOR_PICKER
STOCK_CONNECT
STOCK_CONVERT
STOCK_COPY
STOCK_CUT
STOCK_DELETE
STOCK_DIALOG_AUTHENTICATION
STOCK_DIALOG_ERROR
STOCK_DIALOG_INFO
STOCK_DIALOG_QUESTION
STOCK_DIALOG_WARNING
STOCK_DIRECTORY
STOCK_DISCARD
STOCK_DISCONNECT
STOCK_DND
STOCK_DND_MULTIPLE
STOCK_EDIT
STOCK_EXECUTE
STOCK_FILE
STOCK_FIND
STOCK_FIND_AND_REPLACE
STOCK_FLOPPY
STOCK_FULLSCREEN
STOCK_GOTO_BOTTOM
STOCK_GOTO_FIRST
STOCK_GOTO_LAST
STOCK_GOTO_TOP
STOCK_GO_BACK
STOCK_GO_DOWN
STOCK_GO_FORWARD
STOCK_GO_UP
STOCK_HARDDISK
STOCK_HELP
STOCK_HOME
STOCK_INDENT
STOCK_INDEX
STOCK_INFO
STOCK_ITALIC
STOCK_JUMP_TO
STOCK_JUSTIFY_CENTER
STOCK_JUSTIFY_FILL
STOCK_JUSTIFY_LEFT
STOCK_JUSTIFY_RIGHT
STOCK_LEAVE_FULLSCREEN
STOCK_MEDIA_FORWARD
STOCK_MEDIA_NEXT
STOCK_MEDIA_PAUSE
STOCK_MEDIA_PLAY
STOCK_MEDIA_PREVIOUS
STOCK_MEDIA_RECORD
STOCK_MEDIA_REWIND
STOCK_MEDIA_STOP
STOCK_MISSING_IMAGE
STOCK_NETWORK
STOCK_NEW
STOCK_NO
STOCK_OK
STOCK_OPEN
STOCK_ORIENTATION_LANDSCAPE
STOCK_ORIENTATION_PORTRAIT
STOCK_ORIENTATION_REVERSE_LANDSCAPE
STOCK_ORIENTATION_REVERSE_PORTRAIT
STOCK_PAGE_SETUP
STOCK_PASTE
STOCK_PREFERENCES
STOCK_PRINT
STOCK_PRINT_ERROR
STOCK_PRINT_PAUSED
STOCK_PRINT_PREVIEW
STOCK_PRINT_REPORT
STOCK_PRINT_WARNING
STOCK_PROPERTIES
STOCK_QUIT
STOCK_REDO
STOCK_REFRESH
STOCK_REMOVE
STOCK_REVERT_TO_SAVED
STOCK_SAVE
STOCK_SAVE_AS
STOCK_SELECT_ALL
STOCK_SELECT_COLOR
STOCK_SELECT_FONT
STOCK_SORT_ASCENDING
STOCK_SORT_DESCENDING
STOCK_SPELL_CHECK
STOCK_STOP
STOCK_STRIKETHROUGH
STOCK_UNDELETE
STOCK_UNDERLINE
STOCK_UNDO
STOCK_UNINDENT
STOCK_YES
STOCK_ZOOM_100
STOCK_ZOOM_FIT
STOCK_ZOOM_IN
STOCK_ZOOM_OUT

rawDescription: What icons are available to use when displaying a notification with libnotify?


code: list(filter(None, ilist))

rawDescription: filter lists of lists by taking out items less than a certain length - more pythonic way?

description: Filter lists of lists by taking out items less than a certain length - more pythonic way


code:
from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "It is now %s." % now
    return HttpResponse(html)

rawDescription: django generic templates

description: Django generic templates


code:
words = ["_weight.txt","color.txt","_height.txt"]

print(sorted(words, key=lambda x: x.lstrip("_")))
['color.txt', '_height.txt', '_weight.txt']

rawDescription: How to sort files starting with _ in python

description: Sort files starting with _ in python


rawDescription: Python - group files by modified date [hour]


rawDescription: Django 1.5 url redirect with regex?

description: Django 1.5 url redirect with regex


code:
from numpy.random import random

bland_altman_plot(random(10), random(10))
plt.title('Bland-Altman Plot')
plt.show()

rawDescription: Bland-Altman plot in Python

description: Bland-Altman plot in Python


code:
first = True
for data in data_list:
    if first:
        first = False
    else:
        between_items()

    item()

rawDescription: What is the pythonic way to detect the last element in a python 'for' loop?


code:
data = ['5', '4', '9']

sum(int(i) for i in data)
18

rawDescription: Summing elements in a list

description: Summing elements in a list


code:
import re
fnames = ["abc1234", "abcdef", "1024"]
matches = [m.groups() for m in (re.match('(\w+?)(\d+)', f) for f in fnames) if m]
matches

rawDescription: Is there a `let` or `as` keyword for Python generators?


code:
res = df
for col in df.columns:
    if len(df[col].unique()) == 1:
        res = res.drop(col,axis=1)

rawDescription: quickly drop dataframe columns with only one distinct value

description: Quickly drop dataframe columns with only one distinct value


code: f = np.random.rand(5,6)

rawDescription: Parallel array manipulations in numpy

description: Parallel array manipulations in numpy


rawDescription: Using JSON in Python to send query to MongoDB


code: numStreak = ([a[0] == n for n in a]+[False]).index(False)

rawDescription: Find number of consecutive elements that are the same before they change


rawDescription: Using df.apply() with a Pandas MuliIndex / carrying out operations on hierarchical index rows?


code:
par = configparser.ConfigParser(comment_prefixes="=#;")
par.read("foo.ini")

print(list((par["SESSIONS_id"]).items()))

[('session_a', '{F34B3238-EEE5-4006-B19C-AB8CC233D8F0}'), ('session_b', '{AF2D869B-0FB1-4287-A10E-82B0884E1CFC}'), ('session_c', '{F5A7FA65-2107-4B9B-A7C2-8C89C354D4FF}')]

rawDescription: Reading configfiles with no key but value entries using python configparser


code:
class FakeArray(object):
    def __getitem__(self, idx):
        return "You can't change the original FakeArray through me"
    def __setitem__(self, idx, val):
        print("We could set elements %r to %r here" % (idx, val))

rawDescription: Numpy Indexing - Questions on Odd Behavior/Inconsistencies


code:
a = numpy.random.rand(30000000)
cProfile.run('sumeveryxrows(a, 3)')

rawDescription: Python numpy: sum every 3 rows (converting monthly to quarterly)


rawDescription: Finding gradient of a Caffe conv-filter with regards to input


code:
from nanomsg import Socket, PAIR
sock = Socket(PAIR)
sock.bind('inproc://bob')
response1 = sock.recv()
response2 = sock.recv()
response3 = sock.recv()

rawDescription: Python sending mutliple strings using socket.send() / socket.recv()


code:
stream_cycle = itertools.cycle(streams_list)
for item in db_list:
    stream = stream_cycle.next()

rawDescription: Python loop through 2 lists

description: Python loop through 2 lists


code:
import copy

#Define object for the tree nodes
class Node(object):
  def __init__(self, depth, state, field=None):
    self.depth = depth
    self.state = state
    self.field = field
    self.subnodes = []
    if self.depth > 0:
      self.SpawnSubnodes()
  def SpawnSubnodes(self):
    for field in self.state:
      depth_new = self.depth -1
      state_new = copy.copy(self.state)
      state_new[field] += 1
      self.subnodes.append(Node(depth_new, state_new, field))

rawDescription: large number of changing dictionaries for tree nodes in python

description: Large number of changing dictionaries for tree nodes in python


rawDescription: Instantiate two 2D numpy arrays from a list of strings


code: images, paths = read_images(TRAINING_DIR, (90, 90))

rawDescription: Face Recognition - How to return the correct image?


code:
import os
import win32com.client
from pandas import ExcelWriter

if os.path.exists("C:\Full Location\To\excelsheet.xlsm"):
  xlApp=win32com.client.Dispatch("Excel.Application")
  wb = xlApp.Workbooks.Open(Filename="C:\Full Location\To\excelsheet.xlsm")

  # MACRO TO CLEAR SHEET 5 CONTENT
  xlApp.Run("ClearExistingContent")
  wb.Save()
  xlApp.Quit()
  del xl

  # WRITE IN DATA FRAME TO SHEET 5
  writer = ExcelWriter('C:\Full Location\To\excelsheet.xlsm')
  yourdf.to_excel(writer,'Sheet5')
  writer.save()

rawDescription: Pandas Dataframe to excel sheet

description: Pandas Dataframe to excel sheet


code: first_point = self.__points[0]

rawDescription: Classes in python, get attribute

description: Classes in python, get attribute


code:
ks_refs.user_name_cf = ks_refs.cf_connect('UserName')
ks_refs.user_tweet_cf = ks_refs.cf_connect('UserTweet')

rawDescription: python static class with static method that uses self?

description: Python static class with static method that uses self


rawDescription: Efficiently re-indexing one level with "forward-fill" in a multi-index dataframe


code: a // 10 ** int(math.log10(a)/2)   # Use a single / with Python 2

rawDescription: how to divide integer and take some part

description: Divide integer and take some part


rawDescription: How to write a function that copies all of the elements of a list except the largest value into another list? Python 3.2

description: Write a function that copies all of the elements of a list except the largest value into another list? Python 3.2


code:
import collections

class MySuperSpecialSet(dict, collections.MutableSet):
    def __init__(self, it=[]):
        for v in it:
            self.add(v)

    def add(self, v):
        super(MySuperSpecialSet, self).__setitem__(v, v)

    def discard(self, v):
        try:
            super(MySuperSpecialSet, self).__delitem__(v)
        except Exception:
            pass

    # make sure some `dict` methods are hard to call by accident
    __setitem__ = None
    keys = iterkeys = viewkeys = None
    items = iteritems = viewitems = None
    values = itervalues = viewvalues = None
    copy = None
    fromkeys = None
    popitem = None

    # some MutableSet methods that should override dict methods
    pop = collections.MutableSet.pop
    update = collections.MutableSet.__ior__

s = MySuperSpecialSet([Resource("test", 10), Resource("test2", 20)])

test2 = Resource("test2", 2)
test2_orig = s[test2]

test2.rest == test2_orig.rest  # False

rawDescription: Get/Search reference of element in set

description: Get/Search reference of element in set


rawDescription: Python, reading RDF files, scraping Gutenberg books


code:
df['date'] = df['datetime'].apply(lambda x: x.strftime('%d%m%Y'))
df['time'] = df['datetime'].apply(lambda x: x.strftime('%H%M%S'))

rawDescription: How to specify date format when using pandas.to_csv?

description: Specify date format when using pandas.to_csv


code: "cat test.txt | grep %s"%variable

rawDescription: Variable in subprocess

description: Variable in subprocess


code:
def goAhead(x, y,n=1):
    step = -n if xCurrent > xDesired else n
    for x in range(xCurrent, xDesired, step):
        y = int(slope * (x - xCurrent) + yCurrent)
        SetCursorPos((int(x), y))
        sleep(0.002)

rawDescription: Construct a list of integers from bigger to smaller in python


code:
{_id: ObjectId("50fe0f437f774e8013000001"),
    prereq: ["English", "Literature", "Language"]},
{_id: ObjectId("50fe0f437f774e8013000002"),
    prereq: ["Chemistry"]},
{_id: ObjectId("50fe0f437f774e8013000003"),
    prereq: ["Methods","Specialist Maths"]},
...

rawDescription: How to do advanced list modelling and matching in MongoDB

description: Do advanced list modelling and matching in MongoDB


code:
outval = clr.Reference[int]()
Test.Test1(outval)
outval
outval.Value

rawDescription: (Iron)Python - defining a variable of specific type


code:
def convert_to_decimal(degrees, argminutes, arcseconds):
    return 42

rawDescription: python code for "minute of arc" calculation, completing a latitude and longitude conversion function

description: Python code for "minute of arc" calculation, completing a latitude and longitude conversion function


code:
import scapy.all as scapy
import sys
scapy.sr(scapy.IP(dst=sys.argv[1])/scapy.ICMP())
[...]

rawDescription: Scapy In A Script

description: Scapy In A Script


code:
import requests
proxies = {
    "http": "http://user:pass@10.10.1.10:3128/",
}
#ready for `req = requests.get(url, proxies=proxies)`

rawDescription: Login, Navigate and Retrieve data behind a proxy with Python


code: app = Flask(__name__)

rawDescription: How to share the global app object in flask?

description: Share the global app object in flask


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

commands = {}
#csv
import csvsys
commands["--getCSV"] = csvsys.getCSV
#commands["--getCSVSplitted"] = csvsys.getCSVSplitted

# update & insert
import database
commands["--insertProductSpecification"] = database.insertProductSpecification

# download
import download
commands["--downloadProductSites"] = download.downloadProductSites
commands["--downloadImages"] = download.downloadImages

# parse
import parse
commands["--parseProductSites"] = parse.parseProductSites

rawDescription: How are Python command line arguments related to methods?


code:
class MySerializer(serializers.ModelSerializer):
    json_data = JSONSerializerField()

rawDescription: Django Rest Framework and JSONField

description: Django Rest Framework and JSONField


code:
from PyQt4 import QtGui, QtCore

def show_splash(path):
    image = QtGui.QPixmap(path)
    splash = QtGui.QSplashScreen(image)
    splash.setAttribute(QtCore.Qt.WA_DeleteOnClose)
    splash.setMask(image.mask())
    font = QtGui.QFont(splash.font())
    font.setPointSize(font.pointSize() + 5)
    splash.setFont(font)
    splash.show()
    QtGui.QApplication.processEvents()
    for count in range(1, 6):
        splash.showMessage(splash.tr('Processing %1...').arg(count),
                           QtCore.Qt.AlignBottom | QtCore.Qt.AlignLeft,
                           QtCore.Qt.white)
        QtGui.QApplication.processEvents()
        QtCore.QThread.msleep(1000)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    show_splash(sys.argv[1])
    app.quit()

rawDescription: White border on a transparent QSplashScreen image in PyQt


code:
import imageloader
aTile = imageloader.tile_table[1]

rawDescription: calling class/static method from class variable in python

description: Calling class/static method from class variable in python


code:
user_scores = {}
for line in scores:
    name, score = line.rstrip('\n').split(' - ')
    score = int(score)
    if name not in user_scores:
        user_scores[name] = []       # Initialize score list
    user_scores[name].append(score)  # Add the most recent score
    if len(user_scores[name]) > 3:
        user_scores[name].pop(0)     # If we've stored more than 3, get rid of the oldest

rawDescription: Displaying only the highest of a person's 3 most recent scores, saved in a .txt file


rawDescription: Using split to populate a column in Pandas dataframe


code:
def func(foo, bar=None, **kwargs):
    pass

rawDescription: Parameter vs Arguments ? finally,what are they?


code: cursor = db[collects[1]].find()

rawDescription: How to extract collections in Mongo using Python?

description: Extract collections in Mongo using Python


code:
from xml.dom.minidom import parseString

xml = """
    <root>
        <parent>
            <child1>X</child1>
            <child2>Y</child2>
        </parent>
    </root>
"""

dom = parseString(xml)
children = [c.localName for p in dom.getElementsByTagName("parent")
            for c in p.childNodes if c.nodeType == c.ELEMENT_NODE]

rawDescription: python sax xml names of the children tags

description: Python sax xml names of the children tags


rawDescription: how to write unreadable ^A into output file in Python?

description: Write unreadable ^A into output file in Python


rawDescription: Python Pandas Pivot Table - Adding calculated column to multi-index column


code:
for line in file:
    lst += [line.split()]

rawDescription: Read specific column from .dat-file in Python


rawDescription: python argparse strore_true and store optional option in one argument

description: Python argparse strore_true and store optional option in one argument


code: worker = {'admin': ('unknown', 1), 'worker1': ('Paul', 1), 'worker2': ('Francis', 1) }

rawDescription: check if item is part of dict keys

description: Check if item is part of dict keys


code: sys.stdout = sys.__stdout__

rawDescription: Redirect print to string list?

description: Redirect print to string list


rawDescription: selecting rows in numpy ndarray based on the value of two columns

description: Selecting rows in numpy ndarray based on the value of two columns


code:
import logging.handlers
import smtplib
from threading import Thread

def smtp_at_your_own_leasure(mailhost, port, username, password, fromaddr, toaddrs, msg):
    smtp = smtplib.SMTP(mailhost, port)
    if username:
        smtp.ehlo() # for tls add this line
        smtp.starttls() # for tls add this line
        smtp.ehlo() # for tls add this line
        smtp.login(username, password)
    smtp.sendmail(fromaddr, toaddrs, msg)
    smtp.quit()

class ThreadedTlsSMTPHandler(logging.handlers.SMTPHandler):
    def emit(self, record):
        try:
            import string # for tls add this line
            try:
                from email.utils import formatdate
            except ImportError:
                formatdate = self.date_time
            port = self.mailport
            if not port:
                port = smtplib.SMTP_PORT
            msg = self.format(record)
            msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
                            self.fromaddr,
                            string.join(self.toaddrs, ","),
                            self.getSubject(record),
                            formatdate(), msg)
            thread = Thread(target=smtp_at_your_own_leasure, args=(self.mailhost, port, self.username, self.password, self.fromaddr, self.toaddrs, msg))
            thread.start()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

rawDescription: How to make SMTPHandler not block

description: Make SMTPHandler not block


code:
len
str

rawDescription: Difference between methods and functions


code:
from string import punctuation,whitespace
strs = "(251) 342-7344"
strs.translate(None, punctuation+whitespace)

rawDescription: Is there a more efficient way to convert this phone number to plain text?


code: mylist[:] = mylist[:-2]

rawDescription: How is the iadd operator ( += ) different than simple addition?


code: output, _ = tf.listdiff(test, c)

rawDescription: Check if values are contained within a Tensor


code: not not {}  # This is basically what you are doing.

rawDescription: Difference between not dict and not dict=={}


code:
Table
-Column [Type] [Relation] [Notes]

rawDescription: How to organize MySQL table for multi player game Win/Loss reports

description: Organize MySQL table for multi player game Win/Loss reports


code:
class Subcategory(db.Model):
       name = CharField()
       category = ForeignKeyField(Category, related_name = 'subcategories')

rawDescription: How to Reverse Foreign key in python Flask-peewee


rawDescription: python.exe crushed while creating numpy array

description: Python.exe crushed while creating numpy array


rawDescription: getting GtkTressStore parent from child in python

description: Getting GtkTressStore parent from child in python


code:
board = ChessBoard()
move = board.make_move
give_up = board.give_up
# call methods

rawDescription: Currying using python with-statement?

description: Currying using python with-statement


rawDescription: Get dictionaries in a list where the key:value pairs are in another list of dictionaries


code:
import re
text = "\nSubject: Good morning - How are you?\n"
m = re.search(r'\nSubject:.+\n', text)
if m:
    line = m.group()

rawDescription: How to find a part of string in another string?

description: Find a part of string in another string


code: df.apply( lambda x: abs(x * 10) % 10 )

rawDescription: How to get the first digit of the fractional part of a decimal number?

description: Get the first digit of the fractional part of a decimal number


code:
@asyncio.coroutine
def start_connection(self, some_arg):
    pass

rawDescription: TypeError: A Future or coroutine is required


code: from posix import *

rawDescription: Where is os.stat() defined in CPython?

description: Where is os.stat() defined in CPython


rawDescription: Parallelise web tasks with asyncio in Python


code:
def get_user(userQuestion):
    name1 = input(userQuestion).lower()
    while name1 == "" or not name1.replace(' ','').isalpha():
        name1 = input(userQuestion).lower()
    return name1

userQuestions = (
    "Give me name 1?\n",
    "Give me name 2?\n",
    "Give me name 3?\n",
    )
users = []

for i in userQuestions:
    users.append(get_user(i))

print(users)

rawDescription: Turning this code into a python function


code:
np.array([0,6],ndmin=2)
_.shape

rawDescription: Python/numpy issue with array/vector with empty second dimension


code:
def match_line(ID, f):
    with open(f) as file:
        for line in file:
            if str(ID) in line:
                for line2 in file:
                    if 'Sale' in line2:
                        return line2

rawDescription: Searching a txt file for a character, and returning a character from a line below it


code:
class Association(Base):
    __tablename__ = 'association'
    left_id = Column(Integer, ForeignKey('left.id'), primary_key=True)
    right_id = Column(Integer, ForeignKey('right.id'), primary_key=True)
    extra_data = Column(String(50))
    child = relationship("Child")

class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship("Association")

class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)

rawDescription: How can I create a many to many relationship using SQLAlchemy?

description: Create a many to many relationship using SQLAlchemy


code:
from ...file1 import func1
# "." means current dir, ".." means one level above, and "..." is 2 levels above

func1('test_value')

rawDescription: python invoke script with arguments two folders above

description: Python invoke script with arguments two folders above


code:
from pprint import  pprint as pp

pp(out)
[{'Access': 'RW',
  'Cache': 'RWTD',
  'Consist': 'No',
  'DG/VD': '0/0',
  'Name': 'one',
  'Size': '1.818 TB',
  'State': 'Optl',
  'TYPE': 'RAID1',
  'sCC': '-'},
 {'Access': 'RW',
  'Cache': 'RWTD',
  'Consist': 'No',
  'DG/VD': '1/1',
  'Name': 'two',
  'Size': '1.818 TB',
  'State': 'Optl',
  'TYPE': 'RAID1',
  'sCC': '-'},
 {'Access': 'RW',
  'Cache': 'RWTD',
  'Consist': 'No',
  'DG/VD': '2/2',
  'Name': 'three',
  'Size': '1.818 TB',
  'State': 'Optl',
  'TYPE': 'RAID1',
  'sCC': '-'},
 {'Access': 'RW',
  'Cache': 'RWTD',
  'Consist': 'No',
  'DG/VD': '3/3',
  'Name': 'four',
  'Size': '1.818 TB',
  'State': 'Optl',
  'TYPE': 'RAID1',
  'sCC': '-'}]

rawDescription: Python convert table to dictionary

description: Python convert table to dictionary


code:
L = [0, 0, 0, 0]
things_to_add = ({'idx':1, 'amount': 1}, {'idx': 2, 'amount': 1})
for item in things_to_add:
    L[item['idx']] += item['amount']

L

rawDescription: Add to integers in a list

description: Add to integers in a list


code: tmp = window; del tmp, window

rawDescription: QWidget not deleted with parent window

description: QWidget not deleted with parent window


code:
def callback(self,i): # This is the callback factory. Calling it returns a function.
    def _callback():
        print(i) # i tells you which button has been pressed.
    return _callback

def __init__(self):
    names=('One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten')
    self.button=[]
    for i,name in enumerate(names):
        self.button.append(Button(frame, text=name, command=self.callback(i+1)))
        row,col=divmod(i,5)
        self.button[i].grid(sticky=W+E+N+S, row=row, column=col, padx=1, pady=1)

rawDescription: How can I add a lot of Buttons to the tkinter Frame efficiently?

description: Add a lot of Buttons to the tkinter Frame efficiently


code:
class MyClass(object):
    def __init__(self, member):
        self._member = member

    @property
    def member(self):
        return 'Hello {}!'.format(self._member)

    @member.setter
    def member(self, value):
        # Remove "Hello " and "!" from the start and end of any value being set.
        if value.startswith('Hello '):
            value = value.split(None, 1)[1]
        self._member = value.rstrip('!')

rawDescription: Python class members confusion

description: Python class members confusion


rawDescription: How to set value of current Numbers cell using Py-Appscript

description: Set value of current Numbers cell using Py-Appscript


code:
from scrapy import Spider, Item, Field

class Post(Item):
    title = Field()

class BlogSpider(Spider):
    name, start_urls = 'blogspider', ['http://blog.scrapinghub.com']

    def parse(self, response):
        return [Post(title=e.extract()) for e in response.css("h2 a::text")]

rawDescription: How scrapy write in log while running spider?


rawDescription: Limit of digit-by-digit calculation of square roots


rawDescription: Compute the similarity between two lists


code:
from collections import OrderedDict
dd = OrderedDict(a=1, b=2)
print(dd[next(reversed(dd))])     # 2

rawDescription: Get last value of an OrderedDict in Python3


code:
def FN_OpenWindow2(self):
    self.win2 = Window2()
    #Display it
    self.win2.show()

rawDescription: Python3 PyQt4 Calling function from QPushButton


code: map(int, tokens)

rawDescription: convert a list of strings to a list of numbers?

description: Convert a list of strings to a list of numbers


code:
{'position': 'parent', 'title': 'dave root'}
{'position': 'child', 'created': '2013-11-20', 'obj': 'obj', 'title': 'dave'}
{'position': 'parent', 'title': 'james root'}
{'position': 'child', 'created': '2013-11-19', 'obj': 'obj', 'title': 'james'}
{'position': 'child', 'created': '2013-11-18', 'obj': 'obj', 'title': 'james'}
{'position': 'parent', 'title': 'ian root'}
{'position': 'child', 'created': '2013-11-17', 'obj': 'obj', 'title': 'ian'}
{'position': 'parent', 'title': 'dave root'}
{'position': 'child', 'created': '2013-11-16', 'obj': 'obj', 'title': 'dave'}
{'position': 'child', 'created': '2013-11-15', 'obj': 'obj', 'title': 'dave'}
{'position': 'child', 'created': '2013-11-14', 'obj': 'obj', 'title': 'dave'}

rawDescription: Grouping lists in Python but keeping them in order


code:
def words(stringIterable):
    #upcast the argument to an iterator, if it's an iterator already, it stays the same
    lineStream = iter(stringIterable)
    for line in lineStream: #enumerate the lines
        for word in line.split(): #further break them down
            yield word

rawDescription: How to split a text file to its words in python?

description: Split a text file to its words in python


code:
class GameLogic():
    def __init__(self):
        self.Player = Player(self)
        self.Business = Business(self)
    ...

class Player(...):
    def __init__(self, controller):
        self.controller = controller

rawDescription: Calling a method of a class within a class (non-inherited separate classes)


code: some_func(verify_state('TAG1') == 100)

rawDescription: How to get atributes and operator from function

description: Get atributes and operator from function


code:
def make_instance(instance, values):
    '''
    Copied from eviscape.com

    generates an instance for dict data coming from an sp

    expects:
        instance - empty instance of the model to generate
        values -   dictionary from a stored procedure with keys that are named like the
                   model's attributes
    use like:
        evis = InstanceGenerator(Evis(), evis_dict_from_SP)

    >>> make_instance(Evis(), {'evi_id': '007', 'evi_subject': 'J. Bond, Architect'})
    <Evis: J. Bond, Architect>

    '''
    attributes = filter(lambda x: not x.startswith('_'), instance.__dict__.keys())

    for a in attributes:
        try:
            # field names from oracle sp are UPPER CASE
            # we want to put PIC_ID in pic_id etc.
            setattr(instance, a, values[a.upper()])
            del values[a.upper()]
        except:
            pass

    #add any values that are not in the model as well
    for v in values.keys():
        setattr(instance, v, values[v])
        #print 'setting %s to %s' % (v, values[v])

    return instance

rawDescription: What is the best way to access stored procedures in Django's ORM


code:
names = 'van der Hilst, Rob, Chen, Min, Huang, Hui, Niu, Fenglin, Yao, Huajian' + \
        'Malanotte-Rizzoli, Paola, Eltahir, Elfatih, Wei, Jun, Xue, Pengfei' + \
        'Bowring, Samuel, Hoke, Gregory, Schmitz, Mark'

rawDescription: Python: extract unique id from file name


code:
class Ui_Wizard(object):
    def addSpins(self):
        list_x = []
        ...

    ...
    self.wizardPage2.initializePage = self.addSpins

rawDescription: How to get a value from QSpinBox, how to disable NextButton in QWizard

description: Get a value from QSpinBox, how to disable NextButton in QWizard


code:
def customerind(customer):
  #Iterate through each name, and see if there is a match.
  for i in range(len(customers)):
    if customer == customers[i]:
      return i #If we found the name, instantly return the index.
  #Outside of the for loop, will get called once above finishes iterating through all names.
  return -1 #Return -1 if no match, since the index can be any value 0 -> Infinity

rawDescription: how do you break code in a if loop?

description: Break code in a if loop


rawDescription: sorting by common item

description: Sorting by common item


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

class ChangingPlot(object):
    def __init__(self):
        self.inc = 0.5

        self.fig, self.ax = plt.subplots()
        self.sliderax = self.fig.add_axes([0.2, 0.02, 0.6, 0.03],
                                          axisbg='yellow')

        self.slider = DiscreteSlider(self.sliderax, 'Value', 0, 10,
                                     increment=self.inc, valinit=self.inc)
        self.slider.on_changed(self.update)

        x = np.arange(0, 10.5, self.inc)
        self.ax.plot(x, x, 'ro')
        self.dot, = self.ax.plot(self.inc, self.inc, 'bo', markersize=18)

    def update(self, value):
        self.dot.set_data([[value],[value]])

    def show(self):
        plt.show()

class DiscreteSlider(Slider):
    """A matplotlib slider widget with discrete steps."""
    def __init__(self, *args, **kwargs):
        """Identical to Slider.__init__, except for the "increment" kwarg.
        "increment" specifies the step size that the slider will be discritized
        to."""
        self.inc = kwargs.pop('increment', 0.5)
        Slider.__init__(self, *args, **kwargs)

    def set_val(self, val):
        discrete_val = int(val / self.inc) * self.inc
        # We can't just call Slider.set_val(self, discrete_val), because this
        # will prevent the slider from updating properly (it will get stuck at
        # the first step and not "slide"). Instead, we'll keep track of the
        # the continuous value as self.val and pass in the discrete value to
        # everything else.
        xy = self.poly.xy
        xy[2] = discrete_val, 1
        xy[3] = discrete_val, 0
        self.poly.xy = xy
        self.valtext.set_text(self.valfmt % discrete_val)
        if self.drawon:
            self.ax.figure.canvas.draw()
        self.val = val
        if not self.eventson:
            return
        for cid, func in self.observers.iteritems():
            func(discrete_val)

p = ChangingPlot()
p.show()

rawDescription: Can I make matplotlib sliders more discrete?

description: Make matplotlib sliders more discrete


code:
df = DataFrame({'A' : np.random.randn(9)},index=pd.MultiIndex.from_product([range(3),list('abc')],names=['first','second']))
df
store = pd.HDFStore('test.h5',mode='w')
store.append('df',df)
store

rawDescription: Pandas multiindex and pytables... separate indexes or one concatenated index?


code:
import myviridisfile as vs
plt.register_cmap(name='viridis', cmap=vs.viridis)

rawDescription: Convert given value of contourf color to rgb code


code:
class RootServer:

    def __init__(self):
        cherrypy.engine.subscribe('start', self.start)
        cherrypy.engine.subscribe('stop', self.stop)

    def start(self):
        self.running = True

    def stop(self):
        self.running = False

    @cherrypy.expose
    def index(self, **keywords):
        for i in range(0,1000):
            lengthyprocess(i)
            if not self.running:
                return

rawDescription: How to detect if cherrypy is shutting down

description: Detect if cherrypy is shutting down


code:
st = {s[0] for s in myList}
l = []
for ind, sub in enumerate(myListOfList):
    k = sub[0][-1]
    if st.issubset(ch[0] for ch in sub) and all((ch[-1] == k for ch in sub)):
        l.append(ind)
print(l)
[1, 6, 7]

rawDescription: Compare lists of strings regarding the suffixes of their respective elements


rawDescription: Count the same list's occur frequency in a multi-dimensional list?


code:
class TypeInfo(Base):
    __tablename__ = 'typeinfo'
    id = Column(Integer, primary_key=True)
    sort_order = Column(Integer)

# assiming the database contains values like:
tis = [ TypeInfo(id=1, sort_order=50),
        TypeInfo(id=2, sort_order=20),
        TypeInfo(id=3, sort_order=30),
        TypeInfo(id=4, sort_order=10),
        TypeInfo(id=5, sort_order=40),
        ]

# your query might look like below:
q = session.query(SomeTable)
q = q.join(TypeInfo, SomeTable.type == TypeInfo.id).order_by(TypeInfo.sort_order)

rawDescription: SQLALchemy custom integer sort order

description: SQLALchemy custom integer sort order


rawDescription: Python Numpy 2D Array Number of Rows For Empty Matrix is Still 1


code:
import numpy as np
x = np.arange(9).reshape(3,3)
x
mask = np.array([[False, False, True],
                     [True, False, False],
                     [True, False, False]])
x[mask]

rawDescription: Iterating through a numpy array and then indexing a value in another array


code:
class Door():
    def __init__(self, attributes):
        self.attributes = attributes

rawDescription: How do I set a value of a dictionary to a reference to a value of another dictionary?

description: Set a value of a dictionary to a reference to a value of another dictionary


rawDescription: Merging lists in a row wise manner to generate a 2D array


rawDescription: Using array indexing to apply 2D array function on 3D array


code:
jenkins_url = "https://jenkins.example.com"
username = "johndoe@example.com"
api_token = "my-api-token"

rawDescription: Fetching a URL from a basic-auth protected Jenkins server with urllib2


code:
def __new__(cls):
    self = object.__new__(cls)
    return self

rawDescription: Translating perl to python - What does this line do (class variable confusion)


code:
def func(t):
    hours = set(t['Hour_of_call'].values)
    calls = iter(t['call_Frequency'].values)
    return pd.Series([0 if x not in hours else next(calls)
            for x in range(1, 25)])

rawDescription: Ho to convert a pd data frame to matrix structure in python


code:
name;surname
Jan;Vlcinsky
Pieter;Pan
Jane;Fonda

rawDescription: Parsing CSV data based on header fields using Pyparsing


code:
misspelled_word_list = []
for word in sentence_list:
    if (not word in misspelled_word_list) and (not word in words):
        misspelled_word_list.append(word)

rawDescription: How to check if my list has an item from another list(dictionary)?

description: Check if my list has an item from another list(dictionary)


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

# 100 values from a normal distribution with a std of 3 and a mean of 0.5
data = 3.0 * np.random.randn(100) + 0.5

counts, start, dx, _ = scipy.stats.cumfreq(data, numbins=20)
x = np.arange(counts.size) * dx + start

plt.plot(x, counts, 'ro')
plt.xlabel('Value')
plt.ylabel('Cumulative Frequency')

plt.show()

rawDescription: Python: Matplotlib - probability plot for several data set


code:
def convert_fields(iterable, **conversions):
    for item in iterable:
        for key in item.viewkeys() & conversions:
            item[key] = conversions[key](item[key])
        yield item

rawDescription: Is it possible to have csv.DictReader format certain columns as something other than string?


rawDescription: How to do sorting inside a python dictionary from a predefined list

description: Do sorting inside a python dictionary from a predefined list


code:
from bs4 import BeautifulSoup as bs
import re

markup = '''001.00 SPL
    543.00 SPL
    056.00 SPL
    228.00 SPL'''

soup = bs(markup)
tags = soup.find_all('span', id=re.compile(r'[dataView]\d+'))
for t in tags:
    print(t.text)

rawDescription: Extracting a specific string out an HTML document


rawDescription: parse html body fragment in lxml

description: Parse html body fragment in lxml


code: pd.merge(df1, df2, how='outer', on='id').merge(df3, how='outer', on='id')

rawDescription: Python Pandas: Join on unique column values and concatenate


code:
def getStats(self):
    return "width:      %s\nheight:      %s\narea:      %s\nperimeter: %s" % (self.width, self.height, self.area(), self.perimeter())

rawDescription: Object Oriented Python - rectangle using classes and functions


code:
for change in self.changes:
    change()

rawDescription: Pythonic way of applying changes on closing a dialog window


code:
def predicate(line):
    if 'something' in line:
        return False # ignore it
    return True

rawDescription: Ignoring lines while comparing files using Python


code:
scores = [93, 89, 87, 83, 79, 77, 73, 69, 67, 60, 0]
grades = ['A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'F']
grade_scores = zip(scores, grades)
def gradeFor(s):
    for score, grade in grade_scores:
       if s >= score:
           return grade
gradeFor(87)
gradeFor(89)
gradeFor(88)
gradeFor(67)
gradeFor(72)
gradeFor(40)

rawDescription: Python: How do I add a “Final Grade” converter in my Grading System Calculator


rawDescription: Python: value that occurs the most in a list


code:
import re
from datetime import timedelta

rawDescription: Python Regex: Mixed format string duration to seconds


code:
soup = BeautifulSoup(respText, "html.parser")
for item in soup.find_all("td", {"class" : "titleColumn"}):
    print(item.find("a").text)

rawDescription: Need to extract data from a website and store in list using regex


code:
from django.core.files.storage import FileSystemStorage

class ThumbnailStorage(FileSystemStorage):
    def __init__(self, **kwargs):
        super(ThumbnailStorage, self).__init__(
            location='/fs02', base_url='/fs02')

description: SuspiciousOperation using sorl-thumbnail


code:
#!/usr/bin/env python
# coding: utf8
from __future__ import absolute_import, division, print_function

class Node(object):

    def __init__(self, word, children):
        self.word = word
        self.children = children
        self.is_marked = False

    def __iter__(self):
        yield self
        for child in self.children:
            for result in child:
                yield result

    @property
    def is_leaf(self):
        return not self.children

    def mark_nodes(self, words):
        self.is_marked = True
        word2node = dict((n.word, n) for n in self)
        for word in words:
            word2node[word].is_marked = True

    def iter_marked_paths(self, path=list()):
        if self.is_marked:
            if self.is_leaf:
                yield path
            else:
                for child in self.children:
                    for result in child.iter_marked_paths(path + [child.word]):
                        yield result

    def as_dot(self, standalone=True):
        result = ['digraph G {'] if standalone else []
        result.append(
            'n{0} [label="{1.word}"{2}];'.format(
                id(self),
                self,
                ' style=bold color=blue' if self.is_marked else ''
            )
        )
        if not self.is_leaf:
            result.extend(c.as_dot(False) for c in self.children)
            result.extend(
                'n{0} -> n{1} [{2}];'.format(
                    id(self),
                    id(child),
                    ' color=blue' if self.is_marked and child.is_marked else ''
                )
                for child in self.children
            )
        if standalone:
            result.append('}')
        return '\n'.join(result)

    @classmethod
    def from_dict(cls, data, word=''):
        return cls(word, [cls.from_dict(c, w) for w, c in data.items()])

def main():
    data = {
        'i': {'love': {'skiing': {}}, 'know': {'math': {}}},
        'he': {'hates': {'bathing': {}, 'disco': {}}},
    }
    tree = Node.from_dict(data)
    tree.mark_nodes(['he', 'i', 'love', 'hates', 'skiing', 'disco', 'bathing'])
    print(list(tree.iter_marked_paths()))
    #print(tree.as_dot())

if __name__ == '__main__':
    main()

rawDescription: mixed string breaking down in order and per keyword from groups

description: Mixed string breaking down in order and per keyword from groups


code:
if number is None:     # No numbers were found
    end_line = current_line
else:
    current_line = lines[first_number]
    number = find_number(current_line)

rawDescription: Numbers in string

description: Numbers in string


code:
def doMarket():
    # do market related stuff

    # User can go anywhere from the market
    return raw_input("Where to next?")

def doMansion():
    # do mansion related stuff

    # User must always go to the market after the mansion
    return "market"

location = "start"
while location != "exit":
    if location == "market":
        location = doMarket()
    elif location == "mansion":
        location = doMansion()

rawDescription: Python: Can One Piece of Script Skip into another?


code:
import traceh
traceh.install()

import inspect

traceh.jump_to(10, inspect.currentframe())
print(1)
print(2)
print(3)
print(4)
print(5)
print(6)

rawDescription: Python: resuming program at line number in the context before an exception using a custom sys.excepthook


code:
my_64_array = my_64_array[:32] + read_device(my_64_array[31:31+16]) + my_64_array[31+16:]
# equivalently, but around 33% faster for even small arrays (length 10), 3 times faster for (length 50)...
my_64_array[31:31+16] = read_device(my_64_array[31:31+16])

rawDescription: Passing subset reference of array/list as an argument in Python


code:
def broadcast(self, line):
    for sessions in self.sessions:
        sessions.push(sessions.sock.getpeername() + ': ' + line + '\r\n')

rawDescription: socket server - getting a connected user's ip

description: Socket server - getting a connected user's ip


code:
from itertools import islice

def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

def check_ranges(lst):
    return any(a[1] < b[1] for a, b in window(sorted(lst)))

rawDescription: Checking if ranges cross paths

description: Checking if ranges cross paths


code:
def __init__(self,s):
    super(Crazyperson,self).__init__(s)
    self.dance = s.get('dance')

rawDescription: Overriding decorated subclass methods

description: Overriding decorated subclass methods


code:
import wave
import numpy as np

wr = wave.open('input.wav', 'r')
sz = 44100 # Read and process 1 second at a time.
da = np.fromstring(wr.readframes(sz), dtype=np.int16)
left, right = da[0::2], da[1::2]

rawDescription: Python amplitude spectrum plot

description: Python amplitude spectrum plot


rawDescription: Pandas convert minute number index (0 to 1440) to datetime


rawDescription: Python Assign Value to New Column If Contains() Is True


rawDescription: simple/efficient way to expand a pandas dataframe

description: Simple/efficient way to expand a pandas dataframe


code:
import collections

word_dict = collections.defaultdict(set)
for word in word_list:
    word_dict[word[0]].add(set0)

rawDescription: Assigning lower case alphabet as keys in a dictionary?


rawDescription: Python add leading zeroes using str.format


code: driver.find_element_by_css_selector("table#MainContent_Table1 > tbody > tr > td:nth-of-type(2)").text

rawDescription: Sending and Receive data from a web page - Selenium


code:
import numpy as np
import Image

def normalize(arr):
    for i in range(3):
        minval = arr[..., i].min()
        maxval = arr[..., i].max()

        if minval != maxval:
            arr[..., i] -= minval
            arr[..., i] *= (255.0 / (maxval - minval))
    return arr

img = Image.open('orig.jpg').convert('RGBA')
a = np.array(img)
b = normalize(a)

im = Image.fromarray(b)
im.save('output.jpg')

rawDescription: Convert Image (png) to Matrix,normalizing it, vise versa


code:
def qwer(num):
    d = {}
    tmp_inte = 0
    while tmp_inte <= num:
        d[str(tmp_inte)] = tmp_inte
        tmp_inte += 1
    return d

dictname = qwer(10)

rawDescription: What is the name of this dictionary?

description: What is the name of this dictionary


rawDescription: python pandas: get fiscal quarter from fiscal year and month (for UK)

description: Python pandas: get fiscal quarter from fiscal year and month (for UK)


code:
import numpy as np

def get_neighbours(p, exclude_p=True, shape=None):

    ndim = len(p)

    # generate an (m, ndims) array containing all combinations of 0, 1, 2
    offset_idx = np.indices((3,) * ndim).reshape(ndim, -1).T

    # use these to index into np.array([-1, 0, 1]) to get offsets
    offsets = np.r_[-1, 0, 1].take(offset_idx)

    # optional: exclude offsets of 0, 0, ..., 0 (i.e. p itself)
    if exclude_p:
        offsets = offsets[np.any(offsets, 1)]

    neighbours = p + offsets    # apply offsets to p

    # optional: exclude out-of-bounds indices
    if shape is not None:
        valid = np.all((neighbours < np.array(shape)) & (neighbours >= 0), axis=1)
        neighbours = neighbours[valid]

    return neighbours

rawDescription: How to Find the Neighbors of a Cell in an ndarray?


code:
with open('test.cpp', 'a') as out:
    print(test_str.encode('unicode_escape').decode('utf-8'), file=out)

rawDescription: Python handling newline and tab characters when writing to file


code:
wordslist = []
f = open('Sample.csv')
for word in f.read().split():
    wordslist.append(word)

rawDescription: Counter in python not showing all words

description: Counter in python not showing all words


code:
class SomeModel(models.Model):
    class Meta(object):
        app_label = 'yourapplabel'
        db_table = 'yourapplabel_somemodel'

rawDescription: Can i divide the models in different files in django

description: Divide the models in different files in django


code:
df
pd.options.display.max_colwidth

rawDescription: Formatting issue in IPython/pandas

description: Formatting issue in IPython/pandas


code:
it.SessionId = 'blahablhabalh'
it

rawDescription: SUDS: Pass Array Parameter in Client.service Method : GAE Python


code:
if event is not None:
    if event.type == pygame.KEYDOWN:
        if event.key in [pygame.K_UP, pygame.K_SPACE]:
            jump_pressed = True
    elif event.type == pygame.KEYUP:
        if event.key in [pygame.K_UP, pygame.K_SPACE]:
            jump_pressed = False

if jump_pressed and self.vspeed == 0:
    self.vspeed = -(self.speed)*2
    print("jump is pressed")

rawDescription: Pygame sprite jump with pressed key

description: Pygame sprite jump with pressed key


code:
def rmNegatives(L):
    subscript = 0
    for num in list(L):
        if num < 0:
            L = L[:subscript] + L[subscript+1:]
        else:
            subscript += 1
    return L

rawDescription: Removing Negative Elements in a List - Python


code:
b[indices]
b[indices].shape

rawDescription: Python/Scipy: Find "bounded" min/max of a matrix


code:
# program2.py
import program1
program1.main()

rawDescription: Importing classes in python

description: Importing classes in python


rawDescription: Inverse of Python's unicodedata.name?

description: Inverse of Python's unicodedata.name


code:
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError

from utils import date

def validate_future_date(value):
    if value <= date.today():
        raise ValidationError(_('Date should be in the future.'))

rawDescription: Django unit testing with date/time-based objects


rawDescription: options for applying conditions to numpy arrays

description: Options for applying conditions to numpy arrays


code:
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=5) as executor:
    for work in work_list:
        executor.submit(work_function, work)

rawDescription: Using Python threads to make thousands of calls to a slow API with a rate limit


code:
import numpy as np
from scipy.interpolate import griddata
import pylab as plt
# i guess the pd.read_csv is something pandas (heard of it, but never used it before, but since the only thing you do is read_csv i guess that wont cause problems)

rawDescription: converting map coordinates to lat/long

description: Converting map coordinates to lat/long


code:
class A2(A):
    ...

rawDescription: Test subclass behaviour?

description: Test subclass behaviour


code:
import wx
app=wx.App()
dc=wx.ScreenDC()
panel = wx.Panel(self)
dc.DrawLine(100,100,500,500)
dc.Clear()

# and then
dc.Refresh()

app.MainLoop()

rawDescription: How to clear drawing on screen in wxpython?

description: Clear drawing on screen in wxpython


rawDescription: Global event handlers in wxPython (Pheonix)


rawDescription: Building Django Q() objects from other Q() objects, but with relation crossing context


code:
from urllib import urlencode
form_inputs = [
    {'someparam': 'aaa'},
    {'someparam': 'bbb'},
    {'someparam': 'ccc'},
]
'&'.join([urlencode(d) for d in form_inputs])

rawDescription: How to simulate POST arguments in python

description: Simulate POST arguments in python


code:
import timeit
cmd1 = """\
"".join(this.d[c] if c in this.d else c for c in this.s)
"""
cmd2 = """\
"".join(c in this.d and this.d[c] or c for c in this.s)
"""
cmd3 = """\
"".join(this.d.get(c, c) for c in this.s)
"""
cmd4 = """\
_get=this.d.get;"".join(_get(c, c) for c in this.s)
"""
t1 = timeit.Timer(cmd1, "import this")
t2 = timeit.Timer(cmd2, "import this")
t3 = timeit.Timer(cmd3, "import this")
t4 = timeit.Timer(cmd4, "import this")

rawDescription: Returning a dict value for a key, or the key if the dict does not contain that key


code:
yours: A20352DB4214FD
mine : DB4214FD

rawDescription: CARP hash in Python

description: CARP hash in Python


code:
hasher1.update(buf1)
a = hasher1.hexdigest()

rawDescription: Compare md5 hashes of two files in python


code:
df = pd.DataFrame({'Class': ['Gammaproteobacteria', 'Bacteroidetes', 'Negativicutes'], 'Number': [3, 5, 6]})
df
df = df.set_index('Class')
df.loc[['Bacteroidetes', 'Negativicutes', 'Gammaproteobacteria']]

rawDescription: Sorting a pandas DataFrame by the order of a list


code:
from functools import partial
def my_function(a, b, c, d, e, f):
    print(a, b, c, d, e, f)

new_func = partial(my_function, 1, 2, 3)
new_func('d', 'e', 'f')

rawDescription: Passing default arguments to functions in Python


code:
# we're going to name the file by the date it was downloaded (e.g. 2012-3-18.csv)
fname = now.strftime("%Y-%m-%d")+".csv";

rawDescription: How to download and rewrite a file in Python?

description: Download and rewrite a file in Python


code:
def escape_html(s):
    s = s.replace('&', "&")
    s = s.replace(">", ">")
    s = s.replace("<", "<")
    s = s.replace('"', """)
    return s

escape_html('<script>alert("Oops & bummer!")</script>')
import cgi
cgi.escape('<script>alert("Oops & bummer!")</script>', True)

rawDescription: Escape characters and raw string

description: Escape characters and raw string


code: {k: v for k, v in tupled_dict.iteritems() if 'a' in k}

rawDescription: Return and delete all key-value pairs whose tuple keys contain a given element


code:
self.layout().removeWidget(self.label)
self.text = 'new text'
self.label = QtGui.QLabel(self.text)
self.layout().addWidget(self.label, 0, 0)

rawDescription: PyQt: Recreating widgets

description: PyQt: Recreating widgets


code:
i = input("Please enter the direction: ")
j = input("Please enter the steps: ")
k = int(j) #convert steps input into integer
x = 0 #x-axis position
y = 0 #y-axis position
xpos = ""
ypos = ""

option = 1

if (option == 1):
    if (i == "UP"):
        y += k
        if (y > 0):
            steps = str(y)
            print ("I am now " + steps + " steps above")
        elif (y < 0):
            steps = str(y)
            print ("I am now " + steps + " steps below")
        option = input("1 to continue moving, 0 to terminate: ")
        if(option=="1"):
           return 1
        else:
           return 0
    elif (i == "DOWN"):
        y -= k
        if (y < 0):
            steps = str(y)
            print ("I am now " + steps + " steps below")
        elif (y > 0):
            steps = str(y)
            print ("I am now " + steps + " steps above")
        option = input("1 to continue moving, 0 to terminate: ")
        if(option=="1"):
           return 1
        else:
           return 0
    elif (i == "LEFT"):
        x -= k
        if (x < 0):
            steps = str(x)
            print ("I am now " + steps + " steps behind")
        elif (x > 0):
            steps = str(x)
            print ("I am now " + steps + " steps infront")
        option = input("1 to continue moving, 0 to terminate: ")
        if(option=="1"):
           return 1
        else:
           return 0
    elif (i == "RIGHT"):
        x += k
        if (x < 0):
            steps = str(x)
            print ("I am now " + steps + " steps behind")
        elif (x > 0):
            steps = str(x)
            print ("I am now " + steps + " steps infront")
        option = input("1 to continue moving, 0 to terminate: ")
        if(option=="1"):
           return 1
        else:
           return 0

flag=1
while flag:
   flag=robot()

rawDescription: Python "Option" to determine IF ELSE decision is not working


code:
values = [v.strip() for v in line.split("|")[1:-1]]
num_fields = len(values)
num_empty_fields = values.count("")

rawDescription: constructing regexp expression to check for particular text-database format

description: Constructing regexp expression to check for particular text-database format


code:
text = 'Ex-NFL QB's sad condition'
import HTMLParser
parser = HTMLParser.HTMLParser()
parser.unescape(text)

rawDescription: Change &#39 into normal character

description: Change &#39 into normal character


code:
myPorterStemmer = nltk.stem.porter.PorterStemmer()
...
myPorterStemmer.step1ab()

rawDescription: How to use NLTK stem

description: Use NLTK stem


code:
import json

elements = dict(
    mac = self.lineEdit_mac.text,
    broadcast = self.lineEdit_broadcast.text,
    destination = self.lineEdit_destination.text,
    port = self.lineEdit_port.text,
    destinationCheckBox = self.checkBox_destination.checkState,
    portCheckBox = self.checkBox_port.checkState
)

with open(fileName, 'w') as f:
    # if you need the root key
    data = {'wol': dict((name, str(fn())) for name, fn in elements.iteritems())}
    json.dump(data, f, indent=4)

    # or, just the key/values
    #json.dump(elements, f, indent=4, default=lambda o: str(o()))

rawDescription: How to save qlineedit fields into an XML file using Python for loops?

description: Save qlineedit fields into an XML file using Python for loops


code:
#!/usr/bin/python
from flask import Flask, Blueprint
from my_routes import *

app = Flask(__name__)
app.register_blueprint(api_v1_0)
app.run()

rawDescription: How can Blueprint Flask routes in different files access shared objects


code: [[] for _ in range(n)]

rawDescription: A sequence of empty lists of length n in Python?


code:
def div(*tup):
    return [[x/10] for x in tup]
div(100,50,30)

rawDescription: Multiple iterations over different arguments in a tuple (python)


code:
for row_index, cell_values in enumerate(csv_input):
    # Determine what style to use for the whole row
    if row_index == 0:
        common_style = headerStyle
    elif row_index == 3:
        common_style = subheadStyle
    elif "Assets" in cell_values:
        # perhaps elif any("Assets" in cell_value for cell_value in cell_values):
        # perhaps elif cell_values and cell_values[0] == "Assets":
        # perhaps elif cell_values and "Assets" in cell_values[0]:
        common_style = highlightStyle
    else:
        common_style = rowStyle
    # Iterate over the columns
    for col_index, cell_value in enumerate(cell_values):
        if common_style == rowStyle and is_number(cell_value):
            cell_value = float(cell_value)
        sheet.write(row_index, col_index, cell_value, common_style)

rawDescription: How do I apply a style to the whole row using XLWT Python Excel?

description: Apply a style to the whole row using XLWT Python Excel


code:
import urllib2
import bs4 as bs
import re
import urlparse

url = 'http://www.tesco.com/groceries/SpecialOffers/SpecialOfferDetail/Default.aspx?promoId=A31033985'

response = urllib2.urlopen(url)
content = response.read()
# with open('/tmp/test.html', 'w') as f:
#     f.write(content)
# Useful for debugging off-line:
# with open('/tmp/test.html', 'r') as f:
#     content = f.read()
soup = bs.BeautifulSoup(content)
barcodes = set()
for tag in soup.find_all('img', {'src': re.compile(r'/pi/')}):
    href = tag['src']
    scheme, netloc, path, query, fragment = urlparse.urlsplit(href)
    barcodes.add(path.split('\\')[1])

print(barcodes)

rawDescription: Parsing xml in python - don't understand the DOM


code:
from lxml import etree
doc = etree.XML("""<projects>
  <project>
    <id>1</id>
    <name>
      <![CDATA[First Project]]>
    </name>
    <overview>
      <![CDATA[
This is overview of the first project
]]>
    </overview>
    <status>
      <![CDATA[active]]>
    </status>
    <type>...</type>
    <permalink>...</permalink>
    <leader_id>...</leader_id>
    <company_id>...</company_id>
    <group_id>...</group_id>
  </project>
</projects>""")
data = {}
for a in doc.xpath('/projects/project/*'):
  data[a.tag] = str(a.text).strip()
data

rawDescription: Assigning variables from XML returned from an API call


code: allp = open("allp.txt","r").readlines()

rawDescription: More nested for loops in python

description: More nested for loops in python


code: from Math import *

rawDescription: How to include external Python code to use in other files?

description: Include external Python code to use in other files


code:
def add(x,y):
    return x + y

def multiply(a,b):
    product = 0
    for i in range(b):
        product = add(product, a)   # Note I am calling the add function
    return product

rawDescription: using functions: print vs return

description: Using functions: print vs return


rawDescription: How can I partially sort a Python list?

description: Partially sort a Python list


code:
# For generating a list of odd numbers from 1 to 10
[n for n in range(1, 10) if n % 2 == 1]

# Generator version preventing evaluation of the whole list at once.
(n for n in range(1, 10) if n % 2 == 1)

rawDescription: For loops and else statements in Python

description: For loops and else statements in Python


code:
for key, val in PIX0.items():
    NUM = input("Which standard has a resolution of {!r}?".format(val))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))

rawDescription: Python3 Dictionary iterate through values?


code:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
word = 'java'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
splits
replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b]
replaces

rawDescription: The Alphabet and Recursion

description: The Alphabet and Recursion


code:
import re
parensnumber = re.compile(r'\s*\((\d+)\)')
parensnumber.sub(r'-\1', 'itemA (3)')
parensnumber.sub(r'-\1',  'itemB (test) abcd (2)')
line = 'itemB (test) abcd (2)'
count = int(parensnumber.search(line).group(1))
for i in range(count):
    print(parensnumber.sub('-{0}'.format(i + 1), line))

rawDescription: How to parse a number from line

description: Parse a number from line


code:
def max_sim(d1, d2):
    # assume that's the same for both dicts
    length = sum(d1.values())
    matches = 0
    for letter in set(d1.keys() + d2.keys()):
        matches += min(d1.get(letter, 0), d2.get(letter, 0))
    return matches / float(length)

rawDescription: Max similarity of two character dictionaries?


rawDescription: Creating a multindex'd column DataFrame (expanded explanation)


code:
tmp.recursive_bubble_ands_up(('not', ('p', ('and', 'a', 'b'), 'x')))
tmp.repeat_bubble_until_finished(('not', ('p', ('and', 'a', 'b'), 'x')))

rawDescription: replacing values in a nested tuple with the whole tuple

description: Replacing values in a nested tuple with the whole tuple


rawDescription: Django/Python: How can i monitor mysql database and trigger email when timestamp = NOW()?


code:
show_list = ["ABC\\AAA.txt", "DEF\\abc.txt", "ABC\\readme.txt"]
items = self.tree_widget_list(show_list)
self.cfg_src_tree.insertTopLevelItems(0, items)

rawDescription: Duplicates in QTreeWidget

description: Duplicates in QTreeWidget


code:
import dis
def f():
    for x in range(100):
        y = 1 + 1

dis.dis(f)

rawDescription: Is this calculation executed in Python?

description: Is this calculation executed in Python


rawDescription: Port MATLAB bounding ellipsoid code to Python


code:
for i in range(0, len(some_list), line_length):
    print( "  ".join( "{0:.2f}".format(x) for x in some_list[i:i+line_length] ) )

rawDescription: Idiomatic way to print arbitrary number of items from a list on each line


code:
for obj in all_objects:
    if isinstance(obj, Planet):
        obj.gravity()

rawDescription: Call the same method in all objects in Python?


code:
newpath = name + ".txt"
newfile = open(newpath, "r")

rawDescription: reading from a text document in python using a variable

description: Reading from a text document in python using a variable


code:
class ControlWindow(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.capture = None

        self.start_button = QtGui.QPushButton('Start')
        self.start_button.clicked.connect(self.startCapture)
        self.quit_button = QtGui.QPushButton('End')
        self.quit_button.clicked.connect(self.endCapture)
        self.end_button = QtGui.QPushButton('Stop')

        vbox = QtGui.QVBoxLayout(self)
        vbox.addWidget(self.start_button)
        vbox.addWidget(self.end_button)
        vbox.addWidget(self.quit_button)
        self.setLayout(vbox)
        self.setWindowTitle('Control Panel')
        self.setGeometry(100,100,200,200)
        self.show()

    def startCapture(self):
        if not self.capture:
            self.capture = QtCapture(0)
            self.end_button.clicked.connect(self.capture.stop)
            # self.capture.setFPS(1)
            self.capture.setParent(self)
            self.capture.setWindowFlags(QtCore.Qt.Tool)
        self.capture.start()
        self.capture.show()

    def endCapture(self):
        self.capture.deleteLater()
        self.capture = None

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = ControlWindow()
    sys.exit(app.exec_())

rawDescription: Display OpenCv window on top of PyQt's main window


code: df = df.groupby('ID').resample('W', how='sum').reset_index('ID')

rawDescription: Report with Pivot Tables like in Excel using Python


code:
class LI(list):
    def append(self, *args):
        self.extend(args)

rawDescription: Overriding list method

description: Overriding list method


code:
import example
class PyC(example.A, example.B):
    def __init__(self):
        example.A.__init__(self)
        example.B.__init__(self)

c = PyC()
example.print_a(c)
example.print_b(c)
c.x = 42
example.print_a(c)
example.print_b(c)
class PyC(example.C):
    pass

c = PyC()
example.print_a(c)
example.print_b(c)
c.x = 42
example.print_a(c)
example.print_b(c)

rawDescription: Virtual inheritance C++ and boost python


code: ['something', 'else', 'things']

rawDescription: Turning an existing array into a multidimensional


code:
fixture = StraightredFixture.objects.get(fixtureid=some_fixture_id)
fixture.home_team  # Returns the associated StraightredTeam instance.

team = StraightredTeam.objects.get(team_id=some_team_id)
team.home_fixtures.all()  # Return all at home fixtures for that team.

rawDescription: Django - How to link tables

description: Django - How to link tables


code:
r = [(19, 5), (5, 11), (5, 19)]
from itertools import groupby
m = map(set, r)
m
sorted(m, key=lambda x: sum(x))
[tuple(k) for k, v in groupby(sorted(m, key = lambda x: sum(x)))]

rawDescription: Generating random vertices that don't repeat


rawDescription: semantics of generating symmetric matrices in numpy

description: Semantics of generating symmetric matrices in numpy


code: warnings.warn('Could not find matplotlibrc; using defaults')

rawDescription: .matplotlibrc and default options

description: .matplotlibrc and default options


rawDescription: Python append lists into lists

description: Python append lists into lists


code:
def loadrun(runs, varnames = None):
    for fle in runs:
        _varnames = None if varnames is None else varnames[:]
        yield sio.loadmat(fle, variable_names = _varnames)

rawDescription: Why is scipy.io.loadmat failing to filter out variables on all but the first iteration of this generator function?


code: ['!', ' This is an example.', 'A particular case.', 'Made up of more than once sentence?', 'Yes, it is.', 'But no blank !', '!', '!', "That's a problem ?", '?', '?', '?', 'Yes.', 'I think so!', ' :)']

rawDescription: Non-consuming regular expression split in Python


code:
import example
class Derived(example.Base):
    def perform(self):
        return "abc"

derived = Derived()
assert("ABC" == example.make_upper(derived))

rawDescription: Exposing virtual member functions from C++ to Python using boost::python


rawDescription: pandas: grabbing value of column based on value of other variable

description: Pandas: grabbing value of column based on value of other variable


code:
import csv

def load_data(filename):
    with open(filename) as f:
        data = [(line[0], line[1:]) for line in csv.reader(f)]
    return data

rawDescription: How can i split a single tuple into multiple using python?

description: Split a single tuple into multiple using python


rawDescription: find submit button in selenium without id

description: Find submit button in selenium without id


code:
d1 = Counter({'key4': 50, 'key3': 4})
d.update(d1)
d

rawDescription: Sum values in a Python dict?

description: Sum values in a Python dict


code: df2 = pd.DataFrame(df.unique()).T          # T = transpose()

rawDescription: Sorting through list and storing distinct values


code:
class RhiModelForm(forms.ModelForm):
    class Meta:
        model = Rhi
        exclude = ['slug']

class ActivityModelForm(forms.ModelForm):
    class Meta:
        model = Activity
        exclude = ['createdBy','lastModifiedBy']

rawDescription: Django ModelForm - Multiple Forms in Template with Different Action Views and Redirects


rawDescription: Matplotlib colorbar ticks on left/opposite side


code: L[a:b] = M

rawDescription: Replace the contents of a list rather than appending to it


rawDescription: transpose multiple columns Pandas dataframe

description: Transpose multiple columns Pandas dataframe


code: globals()["TestXYZ"]()

rawDescription: Getting an object by name

description: Getting an object by name


code: a = D.get('a') or print('hah')

rawDescription: why does D.get(k,v) seem to always execute v if v is returned from a function?

description: Why does D.get(k,v) seem to always execute v if v is returned from a function


code: data.apply(lambda x: sorted(x, 3))

rawDescription: Get top biggest values from each column of the pandas.DataFrame


code:
import curses

w = curses.initscr()

while True:
    w.addstr("Enter data: ")
    value = w.getstr()

    if value == 'quit':
        break

    w.addstr('data: %s\n' % value)

    w.addstr('Press any key to continue')
    w.getch()
    w.clear()
    w.refresh()

curses.endwin()

rawDescription: "Refreshing" Command Line in Windows

description: "Refreshing" Command Line in Windows


code:
import model
model.Bar()

rawDescription: How can I split a module into multiple files, without breaking a backwards compatibly?

description: Split a module into multiple files, without breaking a backwards compatibly


code:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import orm
import sqlalchemy as db
Base = declarative_base()

favorite_series = db.Table('favorite_series', Base.metadata,
    db.Column('user_id', db.Integer, db.ForeignKey('User.id')),
    db.Column('series_id', db.Integer, db.ForeignKey('Series.id'))
)
class Episode(Base):
    __tablename__ = 'Episode'
    id = db.Column(db.Integer, primary_key=True)
    season = db.Column(db.Integer)
    episode_num = db.Column(db.Integer)
    series_id = db.Column(db.Integer, db.ForeignKey('Series.id'))

    def __init__(self, season, episode_num, series_id):
        self.season = season
        self.episode_num = episode_num
        self.series_id = series_id

    def __repr__(self):
        return self.series.title + \
               ' S' + str(self.season) + \
               'E' + str(self.episode_num)

class Series(Base):
    __tablename__ = 'Series'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String)
    episodes = orm.relationship('Episode', backref='series')

    def __init__(self, title):
        self.title = title

    def __repr__(self):
        return self.title

class User(Base):
    __tablename__ = 'User'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    favorite_series = orm.relationship('Series',
        secondary=favorite_series, backref='users')

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return self.name

rawDescription: SQLAlchemy: retrieve all episodes from favorite_series of specific user


code: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,  width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, None);

rawDescription: OpenGL Framebuffer with more than one texture


code:
from __future__ import division
import csv

gene = 3
valor_B = 4

data = []
with open('data.csv', 'r') as readfile:
    reader = csv.reader(readfile)
    for row in reader:
        data.append(row)

values_to_add = []
with open('B_Media.txt','wb') as writefile:
    writer = csv.writer(writefile)

    for i in range(len(data)):
        values_to_add.append(int(data[i][valor_B]))
        # if last row or row is different from previous, write it
        if i == len(data)-1 or data[i][gene] != data[i+1][gene]:
            data[i][valor_B] = sum(values_to_add)/len(values_to_add)
            writer.writerow(data[i])
            values_to_add = []

rawDescription: Verify if previous line have same string than current line and sum value of another column


rawDescription: How to start a file that has a period in front of it?

description: Start a file that has a period in front of it


rawDescription: how to insert two lists as values to a dictionary to the same key

description: Insert two lists as values to a dictionary to the same key


code:
...
self.a_list = self.a_list[:]
self.a_list += ['child1_item']

rawDescription: How do I extend a list from a parent class?

description: Extend a list from a parent class


code:
# wsgi.py
import collections, logging, time, greenlet

logging.basicConfig()
log = logging.getLogger(__name__)
log.level = logging.DEBUG

# used to store per-request data
# keys are greenlets, values are dicts
storage = collections.defaultdict(dict)

# return a dict for this request
# TODO: remove the per-request dict at the end of the request
def get_per_greenlet_dict():
    return storage[greenlet.getcurrent()]

def application(env, start_response):

    # extract query vars
    query_vars = env['QUERY_STRING'].split("&")
    a = query_vars[0].split("=")[1]
    b = query_vars[1].split("=")[1]

    # store 'a' in our per-request dict
    get_per_greenlet_dict()['a'] = a

    log_a_and_b("Before sleep", b)
    time.sleep(1)
    log_a_and_b("After sleep", b)

    start_response('200 OK', [('Content-Type', 'text/html')])
    return [b"OK: "]

def log_a_and_b(prefix, b):
    # log both a and b,
    # where a is sourced from our per-request dict
    # and b is passed as a parameter as a means of verifying a
    a = get_per_greenlet_dict()['a']
    log.debug(prefix + "; a:%s b:%s", a, b)

rawDescription: Gunicorn with gevent: maintaining per request global data


rawDescription: Parsing code with python

description: Parsing code with python


code:
from rest_framework.renderers import JSONRenderer

class MyRenderer(JSONRenderer):
    media_type = 'application/vdn.name.v1+json'

rawDescription: Django doesn't parse a custom http accept header


code:
class UserView(RetrieveAPIView):
    model = User
    serializer_class = UserSerializer

    def retrieve(self, request, pk=None):
        """
        If provided 'pk' is "me" then return the current user.
        """
        if request.user and pk == 'me':
            return Response(UserSerializer(request.user).data)
        return super(UserView, self).retrieve(request, pk)

rawDescription: Get Authenticated user from token in Django Rest Framework


code:
def fib(n):
    old = 0
    cur = 1
    i = 1
    yield cur
    while (i < n):
        cur, old, i = cur+old, cur, i+1
        yield cur

for f in fib(10):
    print(f)

rawDescription: How do I print a fibonacci sequence to the nth number in Python?

description: Print a fibonacci sequence to the nth number in Python


rawDescription: How can I generate a list like this with python

description: Generate a list like this with python


code:
import datetime
datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')

rawDescription: Convert Date String to Day of Week

description: Convert Date String to Day of Week


code:
class Broadcaster(object):

    consumers = []

    def __init__(self, gen):
        self.gen = gen

    def __iter__(self):
        return self

    def __call__(self, *args, **kwargs):
        self.gen = self.gen(*args, **kwargs)

    def next(self):
        yielded = next(self.gen)

        for consumer in self.consumers:
            consumer.send(yielded)

        return yielded

@Broadcaster
def adder(producer1, producer2):
        while True:
            x = next(producer1)
            y = next(producer2)
            yield x + y
#  result is the same as in previous solution

rawDescription: How to unify sender- and receiver-based coroutines?

description: Unify sender- and receiver-based coroutines


code:
import argparse
from num2words import num2words

def play():
    parser = argparse.ArgumentParser()
    parser.add_argument("--b", default=100,type=int,help="b")
    args = parser.parse_args()
    for file in reversed(range(file)):
        print(num2words(iteration) + " there are")
        print(num2words(iteration) + " there are")

if __name__ == '__main__':
    play()

rawDescription: Use argparse module with argument for a function


code:
import itertools

def make_sequences(num_a, num_b):
    b_locations = range(num_a+1)
    for b_comb in itertools.combinations_with_replacement(b_locations, num_b):
        result = []
        result_a = 0
        for b_position in b_comb:
            while b_position > result_a:
                result.append('A')
                result_a += 1
            result.append('B')
        while result_a < num_a:
            result.append('A')
            result_a += 1
        yield ''.join(result)

rawDescription: Finding all sequences of A, B such that have a specified number of each element


code:
def startgame():
    def getName(): # define this inside startgame, so we don't need to pass widgets
        global name # tell the program that we're referring to the global variable 'name'
        name = nameEntry.get() # assign the contents of nameEntry to 'name'
        backtotitle() # do something

    canvas.delete(ALL)
    welcome = canvas.create_text(400,100,font=("Times New Roman", 50),
    text="WELCOME!")
    welcome2 = canvas.create_text(400,150,font=("Times New Roman", 30),
    text="PLEASE ENTER YOUR NAME")

    nameEntry = Entry(canvas)
    enterName = Button(canvas, text="Enter", width=10,
    command=getName) # does not pass widget

    canvas.create_window(350, 200, window = nameEntry)
    canvas.create_window(490, 200, window = enterName)

    nameEntry.delete(0,END)
    nameEntry.insert(0, "Enter Player Name")

    print(name) # for testing, to see the current name

rawDescription: How to use other variables from other definitions using buttons?

description: Use other variables from other definitions using buttons


code: tot = arr.sum(0).sum(0) # first sums all the rows, second sums all the columns

rawDescription: Sum of colorvalues of an image

description: Sum of colorvalues of an image


rawDescription: What is the fastest (to access) struct-like object in Python?


code:
client.py
@asyncio.coroutine
def test_connection(host, port):
    # Get the streams for the socket
    print('Starting client connection')
    reader, writer = yield from asyncio.open_connection(host, port)

    message = 'Test Message'.encode('ascii')

    # Start communication
    print('Sending message to {}:{} - {}'.format(host, port, message))
    writer.write(message)
    writer.write_eof()

    print('Waiting 3 sec for response...')
    response = yield from asyncio.wait_for(reader.read(), timeout=5.0)
    print('Got response: {}'.format(response.decode('ascii')))

    writer.close()

rawDescription: Why is this Python 3 asyncio client sending the bytes only after the Python process is interrupted?


rawDescription: python script does not work but individual shell command does

description: Python script does not work but individual shell command does


code: del mylist[:]  #This will implicitly call the `__delslice__` or `__delitem__` method.

rawDescription: Delete all objects in a list

description: Delete all objects in a list


code:
MEDIA_URL = '/pictures/'

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploaded_pictures')

rawDescription: Django Rest app not using media root correctly to serve images


code:
import pandas as pd

df = pd.read_csv("test.txt")
print(df)
def match(x):
    m = r.search(x)
    if m:
        return  m.group()
    return  ""

rawDescription: Extract first date from string in a data frame


code:
iplay = QtGui.QIcon("path/play_icon.png")
ipause = QtGui.QIcon("path/pause_icon.png")
btn = QtGui.QPushButton(ipause, "", None)

def toggle_play():
    if btn.icon() == ipause:
        btn.setIcon(iplay)
        # Do Pause Action
    else:
        btn.setIcon(ipause)
        # Do Play Action
btn.clicked.connect(toggle_play)
btn.show()

rawDescription: How to add a second pixmap to an abstract button when pushed in PySide/PyQt

description: Add a second pixmap to an abstract button when pushed in PySide/PyQt


code: dict([ln.split('\t') for ln in records[0].splitlines()][2:])

rawDescription: Python 3.5 Regular expressions cannot read text file


code: corpus = dict(((term, index) for index, term in enumerate(sorted(all_words))))

rawDescription: Python: implementing feature vectors efficiently


rawDescription: How to vectorize multiple levels of recursion?

description: Vectorize multiple levels of recursion


rawDescription: Rendering vectors in a sphere, with better perception


code:
example = [(5, 1), (4, 2), (3, 3), (2, 4), (1, 5)]
min(example)
min(example, key=lambda element: element[1])

rawDescription: generate min combining multiple lists, return lowest uncombined list?

description: Generate min combining multiple lists, return lowest uncombined list


code:
def many(f):
    def wrapper(*args,**kwds):
        return f(*args,**kwds)
    return wrapper

decos = here = many

class Foo(object):
    @register(many,decos,here)
    def bar(self):
        pass

foo=Foo()

rawDescription: Introspection to get decorator names on a method?


code:
import argparse
import itertools as IT

VERSION = 0.1

version = "%(prog)s " + str(VERSION)
operation = {
    'intersection': set.intersection,
    'union': set.union,
    'uniques': set.difference}

parser = argparse.ArgumentParser()
parser.add_argument('--version', action='version', version=version)
parser.add_argument('-i', '--featurefiles', nargs='+', help='Gene list',
                    metavar='FILE')
parser.add_argument('-o', '--outfile', help="output file (type determined by extension)",
                    metavar='FILE')
parser.add_argument('--op', dest="operation",
                    help="Intersection, Union & Uniques (default Intersection)",
                    default='intersection',
                    # can't use type=operation.get. See http://bugs.python.org/issue16516
                    type=lambda x: operation[x])

args = parser.parse_args()
print(args)

if args.outfile:
    with open(args.outfile, 'w') as f:
        for group_size in (len(args.featurefiles), 2):
            for group in IT.combinations(args.featurefiles, group_size):
                result = ''.join(sorted(reduce(
                    args.operation,
                    (set(open(filename))
                     for filename in group))))
                f.write('{g}:\n{r}\n'.format(g=str(group), r=result))

rawDescription: How to fit parser in my python script

description: Fit parser in my python script


code: dict( zip( argsa[-2:], a[ argsa[-2:] ] ) )

rawDescription: Dictionaries containing the biggest values


code:
import matplotlib.path as mpath
import matplotlib.patches as patches

verts = [(0,0),
         (1,0),
         (1,1),
         (0,1),
         (0,0)]

codes = [mpath.Path.MOVETO] + (len(x)-1)*[mpath.Path.LINETO]
square_verts = mpath.Path(verts, codes)

fig, ax = plt.subplots(subplot_kw={'aspect': 1.0, 'xlim': [-0.2,1.2], 'ylim': [-0.2,1.2]})

square = patches.PathPatch(square_verts, facecolor='orange', lw=2)
ax.add_patch(square)

rawDescription: matplotlib - radius in polygon edges - is it possible?

description: Matplotlib - radius in polygon edges - is it possible


rawDescription: Query regarding the "width" option for format specifiers in python?


code:
import operator
conds = (request.GET.get(f) for f in ('category', 'something', 'from_price', 'to_price'))
if any(conds):
    d = Data.objects.filter(
            reduce(operator.or_,
                (Q(**{a:b}) for a,b in zip(('category', 'something', 'price__gt', 'price__lt'), filter(lambda x: x, conds)))))

rawDescription: How to filter data If I filled (for example) only to_price?

description: Filter data If I filled (for example) only to_price


code:
# aggregate the pressed keys
pressed = []
for i, k in enumerate(keypresses_raw):
    o = ord(k)
    if o:
        #print i, o # this line print code for any pressed key
        for byte,key in key_mapping.get(i, {}).iteritems():
            if byte & o:
                if isinstance(key, tuple): key = key[shift or caps_lock_state]
                pressed.append(key)

rawDescription: how to determine byte and value of keyboard key in Python

description: Determine byte and value of keyboard key in Python


code: aapl = aapl.asfreq('D', method='ffill')

rawDescription: How can I approximate the periodicity of a panda time Series

description: Approximate the periodicity of a panda time Series


code:
def mymethod(self,*args,**kwargs):
    super(thisclass,self).method(*args,**kwargs)
    ...

rawDescription: Call all __init__ but once in Python

description: Call all __init__ but once in Python


code:
from itertools import groupby
with open("in.txt") as f:
    d = {}
    groups = groupby(f, lambda x: x.startswith("Id:"))
    for k, v in groups:
        if k: # if we have a line with "Id:.."
            # use the line as the key
            k = next(v).rstrip()
            # call next on the grouper object extracting
            # the second item which is our section of lines
            d[k] = list(map(str.rstrip, next(groups)[1]))

rawDescription: Group strings in file into dictionary

description: Group strings in file into dictionary


code:
X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([X.ravel(), Y.ravel()])

rawDescription: Numpy meshgrid points

description: Numpy meshgrid points


code:
cur.execute('''select * from warehouse''')
itemlist = cur.fetchall()

rawDescription: pySQLite integration to pyGtk treeview

description: PySQLite integration to pyGtk treeview


code:
def sub_combinations(segment, size=0):
    if segment == ():
        yield ()
        return
    stop = min(size or len(segment), len(segment))
    for i in range(1, stop + 1):
        for j in sub_combinations(segment[i:], size):
            yield (segment[:i],) + j

rawDescription: subtuples for a tuple

description: Subtuples for a tuple


code:
# Adding Helper column that shows when direction have been changed
df['dir_change'] = (df.direction.shift(1) != df.direction).astype(int)
# Identify the DF "blocks" for every direction change
df['block'] = df.dir_change.cumsum()
# Split the DF based on those bolcks
grouped = df.groupby('block')
# Add Function that will cumsum() for a block, and call it
def f1(group):
     return DataFrame({'rolling_count' : group.cumsum()})

df['rolling_count'] = grouped.change.apply(f1)

rawDescription: Python and Pandas - column that "count direction" and show "avarage until now"


code:
windows = [{
    'script': "yourapp.py",
    'uac_info': "requireAdministrator",
},]

rawDescription: How to hide PhantomJS console when running a GUI app in Py2Exe?

description: Hide PhantomJS console when running a GUI app in Py2Exe


code: True if 1 in l else False

rawDescription: Test if value exists in several lists

description: Test if value exists in several lists


code:
d = {}
for i in (line.split() for line in log):
    d.setdefault(i[1], {}).update({i[2]:i[-1]})

#as pointed by @gnibbler, you can also use "defaultdict"
#instead of dict with "setdefault"

rawDescription: Python query: iterating through log file


code:
import xlwt

def write(workbookDict, colMap, filename):
    '''
       workbookDict should be a map of sheet names to a list of dictionaries.
       Each member of the list should be a mapping of column names to contents,
       missing keys are handled with the nullEntry field. colMap should be a
       dictionary whose keys are identical tto the sheet names in the workbookDict.
       Each value is a list of column names that are assumed to be in order.
       If a key exists in the workbookDict that does not exist in the colDict, the
       entry in workbookDict will not be written.
    '''

    workbook = xlwt.Workbook()

    for sheet in workbookDict.keys():
        worksheet = workbook.add_sheet(sheet)
        cols = colMap[sheet]
        i = 0
        writeCols = True
        while i <= len(workbookDict[sheet]):
            if writeCols:
                for j in range(len(cols)):
                    if writeCols:  # write col headings
                        worksheet.write(i, j, cols[j])
                writeCols = False
            else:
                for j in range(len(cols)):
                    worksheet.write(i, j, workbookDict[sheet][(i-1)][cols[j]])
            i += 1

    workbook.save(filename)

rawDescription: Python script to manipulate excel sheets by auto-filling spaces in columns


rawDescription: Python Pandas Dataframe: portfolio backtesting investing cashflows on different dates


code: prime == True

rawDescription: Failing to change bool var state in loop


code:
import re
stringy = "If y0u can 66.6 r34d 25 this, you're 29 t00 close."
integers = re.compile(r'(?<!\S)\d+(?!\S)')
integers.findall(stringy)

rawDescription: Python 2.7: Faster/better way to extract all integer values from a string?


code:
from itertools import islice,chain
with open("sample.txt") as f:
   r = csv.reader(f)
   arr =np.fromiter(chain.from_iterable(map(itemgetter(0, 4, 10),
                                            islice(r,  4, 10))), dtype=float).reshape(6, -1)

rawDescription: load a certain number of rows from csv with numpy

description: Load a certain number of rows from csv with numpy


code:
Example
from shapes import triangle
triangle(3)

rawDescription: Triangle of "T" in Python

description: Triangle of "T" in Python


code:
a = A()
a.put()

b = B();
b.a_reference = a.key()

b.put()

orginial_key = b.a_reference.get_value_for_datastore()

rawDescription: Need help understanding ReferenceProperty


code:
class Son3(object):

    __metaclass__ = HasSonMeta

    def __son_func__():

        pass

rawDescription: Python, how to keep a non-class method as non-class method?


code:
import re

wait = WebDriverWait(driver, 60)
pattern = re.compile(r"\d+/\d+")
pingdom_performance_result = wait.until(wait_for_text_to_match((By.XPATH, "//div[@id='rt_sumright']/dl[@class='last']/dd[1]"), pattern))

print(pingdom_performance_result.text)

rawDescription: How can I get Selenium WebDriver to wait until <dd> element contains data before proceeding?

description: Get Selenium WebDriver to wait until <dd> element contains data before proceeding


code:
#You might want to split based on specific delimiters, but I am using the default
split_line = last.split() #T:  55% 27.50   12% 90% N

rawDescription: Python specific item from last line

description: Python specific item from last line


rawDescription: Python Reshape 3d array into 2d

description: Python Reshape 3d array into 2d


code:
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.core import paginator
from django.db import connection
from django.db.models import Q
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.utils.translation import ugettext as _

rawDescription: django/python imports perfomance

description: Django/python imports perfomance


rawDescription: Extract the Name and Span of Regex Matched Groups


code: [(set(i),sum(j)) for i,j in a]

rawDescription: Reorganise list in list python

description: Reorganise list in list python


rawDescription: Accessing to PK in Function Based View in a Template Context Processor


code: template.format(**{"Title": "SampleTitle", "Note": "SampleNote"})

rawDescription: Replacing "tokens" in Python string with alternate values


code:
sd_selector = CSSSelector('span,div')
elements = sd_selector(page_html)

rawDescription: lxml findall div and span tags

description: Lxml findall div and span tags


code: [i for i in set(b) for _ in range(min(b.count(i), a.count(i)))]

rawDescription: How do I target a particular element in two lists separately? How do I pick an arbitrary number of an element occurring many times in a list?

description: Target a particular element in two lists separately? How do I pick an arbitrary number of an element occurring many times in a list