code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.button import Button

Builder.load_string("""
<Terminator>:
    id: masta
    orientation: 'vertical'

    MyButton:
        id: deleto

        button_id: deleto

        text: "Delete"
        on_release: masta.DelButton()

    MyButton
    MyButton
""")

class MyButton(Button):
    button_id = ObjectProperty(None)

class Terminator(BoxLayout):
    def DelButton(self):
        for child in self.children:
            print(child.button_id)

class TestApp(App):
    def build(self):
        return Terminator()

if __name__ == '__main__':
    TestApp().run()

rawDescription: kivy access child id

description: Kivy access child id


code: imshow(z)

rawDescription: Python - Plotting a raster image/contour plot with XY and Z points


rawDescription: plt.save saves a different image

description: Plt.save saves a different image


rawDescription: turn key="value" string into a dict

description: Turn key="value" string into a dict


code:
if geometry is not None:
    w.show()
    w.setGeometry(*geometry)
else:
    w.showNormal()

rawDescription: Pyforms - Form appears always maximized

description: Pyforms - Form appears always maximized


code:
a = float("nan")
b = float("nan")
d = {a: 1, b: 2, 'c': 3}
d

rawDescription: Filtering null values from keys of dictionary- Python


code:
from collections import defaultdict

to_ignore = defaultdict(set)
for path in ignored_paths:
    dirname, filename = os.path.split(path)
    to_ignore[dirname].add(filename)

def my_ignore(src, files):
    return to_ignore.get(src, set())

rawDescription: The Ignore callback for python shutil.copytree() does not accept full path


code:
grouped_rows = {}
for row in rows:
    second_column = row.split(" ")[1]
    if second_column in grouped_rows:
        grouped_rows[second_column].append(row)
    else:
        grouped_rows[second_column] = [row]

rawDescription: Categorize the data into three groups (positive,negative) (positive,positive) (negative,negative) based on $3 and $2


rawDescription: Convert all letters to uppercase except those following a backslash


code:
df
A

rawDescription: Create 2D array from Pandas dataframe

description: Create 2D array from Pandas dataframe


rawDescription: Sort Versions in Python

description: Sort Versions in Python


code:
class _PyGObject_Functions(ctypes.Structure):
    _fields_ = [
        ('register_class', ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int, ctypes.py_object, ctypes.py_object)),
        ('register_wrapper', ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.py_object)),
        ('lookup_class', ctypes.PYFUNCTYPE(ctypes.py_object, ctypes.c_int)),
        ('newgobj', ctypes.PYFUNCTYPE(ctypes.py_object, ctypes.c_void_p)),
    ]

class PyGObjectCPAI(object):
    def __init__(self):
        PyCObject_AsVoidPtr = ctypes.pythonapi.PyCObject_AsVoidPtr
        PyCObject_AsVoidPtr.restype = ctypes.c_void_p
        PyCObject_AsVoidPtr.argtypes = [ctypes.py_object]
        addr = PyCObject_AsVoidPtr(ctypes.py_object(gi._gobject._PyGObject_API))
        self._api = _PyGObject_Functions.from_address(addr)

    def pygobject_new(self, addr):
        return self._api.newgobj(addr)

def cToPython(ptr, capi = PyGObjectCPAI()):
    return capi.pygobject_new(ptr)

def pythonToC(obj):
    return hash(obj)

rawDescription: Can't find DOMEventTarget.add_event_listener in Python


code:
channel_routing = {
     "websocket.receive": "news_providers.consumers.ws_message",
}

rawDescription: How to use Channel instead of Group when using django channels?

description: Use Channel instead of Group when using django channels


rawDescription: Sorting string into identical words

description: Sorting string into identical words


code:
for i in range(c):
    b = randrange(1, 200)
    if b in my:
        print('Duplicate random value generated')
    my.add(b)

rawDescription: comparing values in a set

description: Comparing values in a set


code:
comparison('A') < comparison('AB')
comparison('B') < comparison('AB')
comparison('Z') < comparison('AB')
comparison('AA') < comparison('AB')
comparison('AC') < comparison('AB')

rawDescription: Comparing string in python

description: Comparing string in python


code:
self.ListA=[] if ListA is None else ListA[:]
self.ListB=[] if ListB is None else ListB[:]

rawDescription: Python-2.7 class method causing objects to be


rawDescription: Animate quadratic grid changes (matshow)


code:
with open(filename, 'r') as f:
    next(f) # discard the first line
    l = [int(line) for line in f]   # save numbers to a list

rawDescription: Save data from a text file into an array in Python


code:
s="bla bla bla \\uf604 bla bla bla"
print(s)
s.replace('\uf604','X')

rawDescription: Replacing a unicode character in a string in Python 3


code:
def f1(arg1, arg2, arg3):
    f2(arg1=arg1, arg2=arg2, arg3=arg3)

rawDescription: Python: put all function arguments into **kwargs automatically


code:
def get_absolute_url(self):
   return resolve('home_page')

rawDescription: Navigating from admin site to one of my apps in same project


code:
class Student(object):
    def __init__ (self, name, age, gender):
        self.name   = name
        self.age    = age
        self.gender = gender

rawDescription: Create Python objects from strings

description: Create Python objects from strings


code:
lst = [6, 7, 8, 9]
[lst[i:j] for j in range(len(lst)+1) for i in range(j)]

rawDescription: python connected combinations of list items

description: Python connected combinations of list items


code:
somestring = u"äüÊÂ"
somestring
import unicodedata
unicodedata.normalize('NFKD', somestring).encode('ascii', 'ignore')

rawDescription: Possible to do a string replace with a dictionary?


code:
def taggify(soup):
     for tag in soup:
         if isinstance(tag, bs4.Tag):
             yield '<{}>{}</{}>'.format(tag.name,''.join(taggify(tag)),tag.name)

rawDescription: Get a structure of HTML code

description: Get a structure of HTML code


rawDescription: Resize the height of the header in QTableWidget in PyQt


code:
[{i for i, t in enumerate(zip(*pair), 1) if t[0]!=t[1]} for pair in
    [(tuple1, tuple2), (tuple1, tuple3), (tuple2, tuple3)]]

rawDescription: Element by element comparison in tuple to return set of sets - python


code:
x = 10
ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("./scriptB.py " + str(x))

rawDescription: Ssh variable found in one python script to another python script and then execute the second script


code:
b.T
b.swapaxes(0,-1)

rawDescription: Generalizing matrix transpose in numpy

description: Generalizing matrix transpose in numpy


code:
def get_value(mydict, keys):
    if not keys:
        return mydict
    if keys[0] not in mydict:
        return 0
    return get_value(mydict[keys[0]], keys[1:])

rawDescription: Reaching into a nested dictionary several levels deep (that might not exist)


rawDescription: Email multiple contacts in Python

description: Email multiple contacts in Python


code:
def getAvg(student, total, numScore):
    average = total / numScore
    print ("The average for student number", student, "is:", average)
    return average

def main():
    student = 0
    more = 'y'

    while more == 'y':
        student += 1
        total = 0

        numScore = int(input('How many test scores per student: '))

        for test_number in range(numScore):
            print ("The score for test", test_number+1)
            score = int(input(': '))
            total += score

        print ("Student number", student)
        print ('-----------------------------------------')

        avg = getAvg(student, total, numScore)

        if avg > 90:
            print ("You're doing excellent work")
        elif avg > 85:
            print("You are doing pretty good work")
        elif avg > 70:
            print ("You better get busy")
        else:
            print ("You need to get some help")

        print()
        print('Do you want to enter another student test score and get the average score of the student?')
        more = input('Enter y for yes, and n for no: ').lower()

main()

rawDescription: Python; calculate the average of three grades for each of a number of students


code:
dic = dict.fromkeys(lis, [])
[id(x) for x in dic.values()]
dic = {x: [] for x in lis}
[id(x) for x in dic.values()]

rawDescription: Most Pythonic Way to Build Dictionary From Single List


code:
od = OrderedDict()
od[1] = 'a'
od[3] = 'b'
od[2] = 'c'
od[4] = 'd'
od
od.keys()[:2]
OrderedDict([(k, od[k]) for k in od.keys()[:2]])

rawDescription: create a dictionary for a certain range in Python

description: Create a dictionary for a certain range in Python


rawDescription: MySQL string replace using SQLAlchemy

description: MySQL string replace using SQLAlchemy


rawDescription: Split strings every two places and add it to a list


code:
from collections import defaultdict
def parse_datafile(fname,output=None):
    if output is None:
       output = defaultdict(Supplier)
    with open(fname,r) as f:
       project = f.readline().split(':')[1].strip()
       suppliers = map(str.strip,f.readline().split(',')[:-2])
       bids = map(str.strip,f.readline().split(','))
       winner = bids[-1]
       win_amt = bids[-2]

       for s,b in zip(suppliers,bids):
           output[s].bids.append(int(b),int(win_amt))
       output[winner].projects.append(project)
    return output

rawDescription: search large number of text files python

description: Search large number of text files python


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

def main():
    app     = QApplication (sys.argv)
    tree    = QTreeWidget ()
    headerItem  = QTreeWidgetItem()
    item    = QTreeWidgetItem()

    for i in xrange(3):
        parent = QTreeWidgetItem(tree)
        parent.setText(0, "Parent {}".format(i))
        parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
        for x in xrange(5):
            child = QTreeWidgetItem(parent)
            child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
            child.setText(0, "Child {}".format(x))
            child.setCheckState(0, Qt.Unchecked)
    tree.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: PyQt Tree Widget, adding check boxes for dynamic removal


code:
from hashlib import sha256 as _sha256
from hmac import HMAC as _HMAC
from math import ldexp as _ldexp
from os import urandom as _urandom
from sys import byteorder as _byteorder

class PRF():

    def __init__(self):
        digestmod = _sha256
        self._h = _HMAC(_urandom(digestmod().block_size), digestmod=digestmod)

    def __getitem__(self, key):
        h = self._h.copy()
        h.update(repr(key).encode())
        b = h.digest()
        return _ldexp(int.from_bytes(b, _byteorder), (len(b) * (- 8)))

rawDescription: Many independent pseudorandom graphs each with same arbitrary y for any input x


rawDescription: Find lists which together contain all values from 0-23 in list of lists python


code:
print(y)
print(y1)
print(y2)

rawDescription: Filling in the space between lines with matplotlib


code:
import pandas
import numpy as np

def tocontainer(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return Container(result)
    return wrapper

class Container(object):
   def __init__(self, df):
       self.contained = df
   def __getitem__(self, item):
       result = self.contained[item]
       if isinstance(result, type(self.contained)):
           result = Container(result)
       return result
   def __getattr__(self, item):
       result = getattr(self.contained, item)
       if callable(result):
           result = tocontainer(result)
       return result
   def __repr__(self):
       return repr(self.contained)

rawDescription: How to redirect all methods of a contained class in Python?

description: Redirect all methods of a contained class in Python


code:
def group_by_start(inputlist, n):
    for k, g in groupby(inputlist, key=itemgetter(slice(n))):
        res = list(g)
        yield res[0] if len(res) == 1 else res

rawDescription: Python. How to make list from another list by mark?


code:
def __cmp__(self, a):
    return cmp(self.weight, a.weight)

rawDescription: Huffman encoding issue

description: Huffman encoding issue


code: # pylint: disable-msg=C0103

rawDescription: How do I tell PyLint "it's a variable, not a constant" to stop message C0103?

description: Tell PyLint "it's a variable, not a constant" to stop message C0103


rawDescription: parsing a url in python with changing part in it

description: Parsing a url in python with changing part in it


code:
from celeryconfig import app # config file you must have build earlier where app = Celery(), object of Celery class

def worker():
    # Arguments you give on command line
    argv = [
        'worker','-A','<module>.tasks',
        '-P','gevent',     # Would probably need this argument if running with other Greenlets
        '--loglevel=info']
    app.worker_main(argv)

rawDescription: Run celery worker and celery beat as thread


code:
l=range(2,200)
r=[]
for y in l:
  if all(y%p for p in q):
     r.append(y)
r

rawDescription: To test a condition on all values in a list before proceeding to the next line


rawDescription: Avoid updating nested lists in for loop

description: Avoid updating nested lists in for loop


code:
@locked_cached_property
def jinja_loader(self):
    """The Jinja loader for this package bound object.

    .. versionadded:: 0.5
    """
    if self.template_folder is not None:
        return FileSystemLoader(os.path.join(self.root_path,
                                             self.template_folder))

rawDescription: How to load from more then one template_folder for Flask blueprint?

description: Load from more then one template_folder for Flask blueprint


code: map(str, range(10))

rawDescription: python random.sample("abc",3) . how to use regular expressions in place of "abc"

description: Python random.sample("abc",3) . how to use regular expressions in place of "abc"


code:
import random
import time
from Levenshtein import distance
from bktree import BKtree

with open("/usr/share/dict/words") as inf:
    word_list = [l[:-1] for l in inf]

def remove_duplicates(lst, threshold):
    tr = BKtree(iter(lst), distance, threshold)
    return tr.nodes.keys()

def time_remove_duplicates(n, threshold):
    """Test using n words"""
    nwords = random.sample(word_list, n)
    t = time.time()
    newlst = remove_duplicates(nwords, threshold)
    return len(newlst), time.time() - t

ns = range(1000, 16000, 2000)
results = [time_remove_duplicates(n, 3) for n in ns]
lengths, timings = zip(*results)

from matplotlib import pyplot as plt

plt.plot(ns, timings)
plt.xlabel("Number of strings")
plt.ylabel("Time (s)")
plt.savefig("number_vs_time.pdf")

rawDescription: Generating a list of distinct (distant, by edit distance) words by filtering


code:
container = [
    ('Field', 'Integer', 'Hex'),
    ('Machine;', 332, '0x14c'),
    ('NumberOfSections;', 9, '0x9'),
    ('Time Date Stamp;', 4, '0x4'),
    ('PointerToSymbolTable;', 126976, '0x1f000')
]
lengths = [
    max(len(str(row[i])) for row in container) for i in range(len(container[0]))
] # => [21, 7, 7]
# OR  lengths = [max(map(len, map(str, x))) for x in zip(*container)]
fmt = ' '.join('{:<%d}' % l for l in lengths)
# => '{:<21} {:<7} {:<7}'    # < for left-align

print(fmt.format(*container[0]))  # header
print('-' * (sum(lengths) + len(lengths) - 1))  # separator
for row in container[1:]:
    print(fmt.format(*row))  # <------- unpacking argument list
    # similar to   print(fmt.format(row[0], row[1], row[2])

rawDescription: Python format print with a list

description: Python format print with a list


rawDescription: Trouble making a table with HTML.py in python


code:
from itertools import product
names = [('Bob', 'Tom'), ('GreenWood', 'Pearson')]
for item in product(*names):
    print(item)

rawDescription: How to make unique combinations of the following list of tuples

description: Make unique combinations of the following list of tuples


code:
cur = db.cursor()
cur.execute("SELECT ingredientID FROM Ingredients WHERE ingredientName = %s", "onions")
print(cur.fetchone()) # Fetch one row

rawDescription: Python (pymysql) Select...Where query returning boolean, not desired value


rawDescription: Evaluation order of positional and keyword arguments


code:
viewer = Viewer()    # pops up a window
import lxml.etree as etree
from lxml.builder import E as svg

rectangle = svg.rect(x="10", y="10", width="80", height="80", style="fill: yellow; stroke: black; stroke-width: 2;")
circle = svg.circle(cx="70", cy="70", r="30", style="fill: red; fill-opacity: 0.5; stroke: black; stroke-width: 2;")

document = svg.svg(rectangle, circle, width="100", height="100")

viewer.renderSVG(etree.tostring(document))   # draws the image in the window

rawDescription: How to use python to generate a magazine cover?

description: Use python to generate a magazine cover


code:
perm = Permission.objects.get(pk=1) # pk #1 for brevity.
group = Group.objects.get(pk=1)     # Again, for brevity.
group_perms = GroupPermission.objects.filter(permission=perm, group=group)
objects = [x.content_object for x in group_perms]

rawDescription: Django generic relations practice

description: Django generic relations practice


code: x = array.array('i', range(N))

rawDescription: Python Typed Array of a Certain Size

description: Python Typed Array of a Certain Size


code: #pylint: skip-file

rawDescription: Pylint disable all warnings for a file

description: Pylint disable all warnings for a file


code:
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer

def fn_tdm_df(docs, xColNames = None, **kwargs):
    ''' create a term document matrix as pandas DataFrame
    with **kwargs you can pass arguments of CountVectorizer
    if xColNames is given the dataframe gets columns Names'''

    #initialize the  vectorizer
    vectorizer = CountVectorizer(**kwargs)
    x1 = vectorizer.fit_transform(docs)
    #create dataFrame
    df = pd.DataFrame(x1.toarray().transpose(), index = vectorizer.get_feature_names())
    if xColNames is not None:
        df.columns = xColNames

    return df

rawDescription: efficient Term Document Matrix with NLTK

description: Efficient Term Document Matrix with NLTK


code:
from operator import itemgetter
sorted((x for x in chain(A, B, C) if x[0] in common), key=itemgetter(0))

rawDescription: Efficiently find overlap of a lists of tuples


code:
ms = fb.MyStruct

# This will fail (throws a Python exception)
# ret =  fb.MYSTRUCT_Func1(ms, 123)

rawDescription: SWIG interfacing C library to Python (SWIG generated classes are cumbersome to use)


code:
def __repr__(self):
    innerRepr = '['+'\n'.join(str(list_val) for list_val in self.list_) + ']' if self.list_ else ''
    return '\n'.join(['this','should','all','be','on','separate','lines']) + innerRepr

rawDescription: Python - nested __repr__ reverts newline to "\\n"


code: array([0, 2, 1], dtype=int64)

rawDescription: I have need the N minimum (index) values in a numpy array


code:
M
ngroups, narticles = M.shape

rawDescription: Transforming a mapping matrix

description: Transforming a mapping matrix


code:
connSqlServer = pyodbc.connect(driver='{SQL Server Native Client 10.0}',
                               server='192.106.0.102\instance1',
                               database='master',
                               uid='sql2008',pwd='password123')

rawDescription: python pyodbc : how to connect to a specific instance

description: Python pyodbc : how to connect to a specific instance


code: tuple(b'ciphertext')

rawDescription: Break bytes object into n equally sized blocks based on index


code:
a, b, c, d,o, p, q, r
e, f, g, h,s, t, u, v
i, j, k, l,w, x, y, z

rawDescription: How to merge .csv files to do a matrix

description: Merge .csv files to do a matrix


code:
fig = plt.figure()
ax0 = plt.subplot(nplots,1,1)
plt.plot(np.linspace(0,1,100), a * np.linspace(0,1,100)**2)
for i, alpha in enumerate(val):
    plt.subplot(nplots,1,i+2,sharex=ax0)
    plt.plot(np.linspace(0,1,100), a * np.linspace(0,1,100)**2)
plt.show()

rawDescription: How to share x axes into a loop?

description: Share x axes into a loop


code:
def merge(a, b):
    l1 = [(t, value, 1) for (t, value) in a]
    l2 = [(t, value, 2) for (t, value) in b]
    events = l1 + l2
    events.sort()
    last_time = -1
    result = []
    c1 = 0
    c2 = 0
    for t, value, index in events:
        if index == 1:
            c1 = value
        if index == 2:
            c2 = value
        if t == last_time:
            result.pop()
        result.append((t, c1 + c2))
        last_time = t
    return result

rawDescription: Merge two lists of tuples with timestamps and queue lengths


code: map(None, *result)

rawDescription: How do I convert apply(map, args) to map(function, iterable) in this case?

description: Convert apply(map, args) to map(function, iterable) in this case


rawDescription: Elegant way to add functionallity to previously defined functions


code:
class MyTypeSubclass(type):
    pass

class MyClass(object):
    __metaclass__ = MyTypeSubclass

rawDescription: Python builtin functions aren't really functions, right?


code:
def my_grouper(n, iterable):
  "my_grouper(3, 'ABCDEFG') --> ABC DEF G"
  args = [iter(iterable)] * n
  return tuple(tuple(n for n in t if n)
       for t in itertools.izip_longest(*args))

rawDescription: Python : Get many list from a list

description: Python : Get many list from a list


code:
for k,v in d.iteritems():
   print('{} {} {};'.format(v[0], v[1], k))

rawDescription: Python: How to create new variable in each iteration of a for loop?


code:
# hack to get window supported
subq = subq.filter(text("TRUE WINDOW w AS (PARTITION BY id "
                        "ORDER BY time_stamp ASC "
                        "RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)"))

rawDescription: Using SQLAlchemy, how do to PGSQL ranged window subquery?


code:
from lxml import etree
import re

tree = etree.parse('htmlfile')
root = tree.getroot()

for elem in root.iter('*'):
    if elem.tail is not None and elem.tail.strip() and re.search('\$\d+', elem.tail):
        e = etree.Element('div')
        e.text = elem.tail
        elem.tail = ''
        elem.addnext(e)

print(etree.tostring(root))

rawDescription: Parsing and Modyfying the html with BeautifulSoup or lxml. Surround a text with some html tag which is directly under the <body> tag


code:
import pandas as pd
df = pd.DataFrame(
    {'player':['A', 'B', 'C', 'D', 'A', 'C', 'B'],
     'game':['gameA', 'gameB', 'gameC', 'gameC', 'gameB', 'gameD', 'gameA']})

game_table = pd.merge(df, df, how='left', on=['player'])
freq = pd.crosstab(game_table['game_x'], game_table['game_y'])
result = freq.stack()
result.name = 'overlap'
result = result.reset_index()
mask = (result['game_x'] != result['game_y'])
result = result.loc[mask]
print(result)

rawDescription: Pandas: calculate overlapping with pivot_table or crosstab


code:
if dtobject.year < 100:
    dtobject = dtobject.replace(year=dtobject.year + 2900)

rawDescription: getting date fields from oracle in correct format using Python and cx-oracle

description: Getting date fields from oracle in correct format using Python and cx-oracle


code:
from django.conf.urls import include, url
from django.conf.urls.static import static  # Added this line
from django.contrib import admin

from tastypie.api import Api

from blog.api import UserResource

blog = Api(api_name='v1')
blog.register(UserResource())

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^blog/', include(blog.urls))
]  + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)  # And this

rawDescription: Using django ImageField with Tastypie

description: Using django ImageField with Tastypie


code:
import numpy as np

x = np.array([[12,7,3],
              [4 ,5,6],
              [7 ,8,9]])

y = x.shape[0] - np.argsort(np.argsort(x, axis = 0), axis = 0)

rawDescription: Rank each number by position in a list of arrays - Python


code:
from lxml import html
import lxml.etree as le

input = "
abcdefgb1b2b3
"
tree = html.fromstring(input)
node = tree.xpath("//pre")[0]

rawDescription: Xpath extract current node content including all child node


code:
def is_perfect_cube(n):
    c = int(n**(1/3.))
    return (c**3 == n) or ((c+1)**3 == n)

rawDescription: Is cube root integer?

description: Is cube root integer


code:
if guess in word_list: # If the guess is correct
    for n, i in enumerate(word_list):
        if i == guess: # Find the indexes where the letter 'guess' is present
            blank_word_list[n]= i # Replace the underscode with the correct letter
            print (blank_word_list)
            letters.remove(guess)
            print (letters)
            if ('_') not in blank_word_list:
                game_on = False
                print ("You Win!")
            else: # If the game is not finished:
                guess = input("Guess a letter ") # Ask for a new letter
                guess = str(guess)

rawDescription: Python- Replacing a item in a list only replaces the first instance, rather than all instances


code:
class AuthSenderHandler(webapp.RequestHandler):
  def post(self):
    # get whatever data is in the form to send an email.
    # let's say that user_id is a field we extracted either from a cookie or from
    # the POST parameters themselves.
    link = "http://your.server.com/authHandler?user_id=%s" % user_id
    message = mail.EmailMessage()
    message.body = """some stuff %s""" % link
    # fill in other message fields, then send it.

    # now we'll create a channel token using the user_id and return
    # it to the client.
    token = channel.create_channel(user_id)
    self.response.out.write(token)

rawDescription: How can I send data to Chrome extension?

description: Send data to Chrome extension


code:
import wikimarkup
import pandas as pd
from pyquery import PyQuery

def get_tables(wiki):
    html = PyQuery(wikimarkup.parse(wiki))
    frames = []
    for table in html('table'):
        data = [[x.text.strip() for x in row]
                for row in table.getchildren()]
        df = pd.DataFrame(data[1:], columns=data[0])
        frames.append(df)
    return frames

rawDescription: How to convert Wikipedia wikitable to Python Pandas DataFrame?

description: Convert Wikipedia wikitable to Python Pandas DataFrame


code: mylist = [f.attribute for f in files]

rawDescription: Python iterating over a list to add items to another list?


code:
with  open("clues.txt", 'r') as f, open("words.txt", 'r') as f2:
    # keys are ord of character to replace,
    # values are character to replace with
    d = {ord(k): v for v, k in (list(line.rstrip()) for line in f)}
    for line in f2:
        print(line.translate(d).rstrip())

rawDescription: Replace character(s) in list a with character from list b


code:
class DstTzInfo(BaseTzInfo):
    '''A timezone that has a variable offset from UTC

    The offset might change if daylight savings time comes into effect,
    or at a point in history when the region decides to change their
    timezone definition.
    '''
    # Overridden in subclass
    _utc_transition_times = None # Sorted list of DST transition times in UTC
    _transition_info = None # [(utcoffset, dstoffset, tzname)] corresponding
                            # to _utc_transition_times entries

rawDescription: How to determine when DST starts or ends in a specific location in Python?

description: Determine when DST starts or ends in a specific location in Python


code:
def C(i, coins, cdict = None):
    if cdict == None:
        cdict = {}
    if i <= 0:
        cdict[i] = 0
        return cdict[i]
    elif i in cdict:
        return cdict[i]
    elif i in coins:
        cdict[i] = 1
        return cdict[i]
    else:
        min = 0
        for cj in coins:
            result = C(i - cj, coins)
            if result != 0:
                if min == 0 or (result + 1) < min:
                    min = 1 + result
        cdict[i] = min
        return cdict[i]

rawDescription: recursively implementing 'minimum number of coins' in python

description: Recursively implementing 'minimum number of coins' in python


rawDescription: What's the cleanest way to add a decorator from a derived class to its base class?


code:
from __future__ import (absolute_import, division, print_function,)
#                        unicode_literals)

import collections
import sys

if sys.version_info.major == 2:
    import Queue as queue
    import itertools
    map = itertools.imap

else:  # >= 3
    import queue

import ib.opt
import ib.ext.Contract

class IbManager(object):
    def __init__(self, timeout=20, **kwargs):
        self.q = queue.Queue()
        self.timeout = 20

        self.con = ib.opt.ibConnection(**kwargs)
        self.con.registerAll(self.watcher)

        self.msgs = {
            ib.opt.message.error: self.errors,
            ib.opt.message.updatePortfolio: self.acct_update,
            ib.opt.message.accountDownloadEnd: self.acct_update,
        }

        # Skip the registered ones plus noisy ones from acctUpdate
        self.skipmsgs = tuple(self.msgs.keys()) + (
            ib.opt.message.updateAccountValue,
            ib.opt.message.updateAccountTime)

        for msgtype, handler in self.msgs.items():
            self.con.register(handler, msgtype)

        self.con.connect()

    def watcher(self, msg):
        if isinstance(msg, ib.opt.message.error):
            if msg.errorCode > 2000:  # informative message
                print('-' * 10, msg)

        elif not isinstance(msg, self.skipmsgs):
            print('-' * 10, msg)

    def errors(self, msg):
        if msg.id is None:  # something is very wrong in the connection to tws
            self.q.put((True, -1, 'Lost Connection to TWS'))
        elif msg.errorCode < 1000:
            self.q.put((True, msg.errorCode, msg.errorMsg))

    def acct_update(self, msg):
        self.q.put((False, -1, msg))

    def get_account_update(self):
        self.con.reqAccountUpdates(True, 'D999999')

        portfolio = list()
        while True:
            try:
                err, mid, msg = self.q.get(block=True, timeout=self.timeout)
            except queue.Empty:
                err, mid, msg = True, -1, "Timeout receiving information"
                break

            if isinstance(msg, ib.opt.message.accountDownloadEnd):
                break

            if isinstance(msg, ib.opt.message.updatePortfolio):
                c = msg.contract
                ticker = '%s-%s-%s' % (c.m_symbol, c.m_secType, c.m_exchange)

                entry = collections.OrderedDict(msg.items())

                # Don't do this if contract object needs to be referenced later
                entry['contract'] = ticker  # replace object with the ticker

                portfolio.append(entry)

        # return list of contract details, followed by:
        #   last return code (False means no error / True Error)
        #   last error code or None if no error
        #   last error message or None if no error
        # last error message

        return portfolio, err, mid, msg

ibm = IbManager(clientId=5001)

portfolio, err, errid, errmsg = ibm.get_account_update()

if portfolio:
    print(','.join(portfolio[0].keys()))

for p in portfolio:
    print(','.join(map(str, p.values())))

sys.exit(0)  # Ensure ib thread is terminated

rawDescription: ibpy Getting portfolio information: Interactive Broker, Python

description: Ibpy Getting portfolio information: Interactive Broker, Python


code: lines = f.readlines()

rawDescription: getting data out of a txt file

description: Getting data out of a txt file


code:
Results = Label(window, text = data)
Results.grid(row = 1, column = 1)

rawDescription: How to print results from text file to window using Python

description: Print results from text file to window using Python


code:
user_score = 0
for multiplier, user_set in enumerate(user_sets, 1):
    user_score += len(input_set & user_set) * multiplier

rawDescription: Finding the intersection between sets and awarding points


code:
class UserSerializer(serializers.ModelSerializer):

    bio = serializers.CharField(source='profile.bio')
    gender = serializers.CharField(source='profile.gender')
    #same for the others

    class Meta:
        model = User
        fields = ('url', 'username', 'password', 'email', 'groups', 'bio', 'gender')

rawDescription: Django rest framework extended user profile


code:
pivoted.columns = [''.join((lvl1, str(lvl2))) for lvl1,lvl2 in pivoted.columns]
pivoted

rawDescription: Adding DataFrame groups as data columns

description: Adding DataFrame groups as data columns


rawDescription: python - Extend 2-d array and interpolate the missing values

description: Python - Extend 2-d array and interpolate the missing values


code:
fig = plt.gcf()
mapper.set_array(indexList)
fig.colorbar(mapper)

rawDescription: Adding Colorbar legend to Basemap plot containing multiple shapefiles


code:
from collections import Mapping

def treeZip(t1,t2):
    if isinstance(t1,Mapping) and isinstance(t2,Mapping):
        assert set(t1)==set(t2)
        for k,v1 in t1.items():
            v2 = t2[k]
            for tuple in treeZip(v1,v2):
                yield tuple
    else:
        yield (t1,t2)

rawDescription: How do you iterate over two dictionaries and grab the values at the same path?

description: Iterate over two dictionaries and grab the values at the same path


code:
class UserConverter(BaseConverter):
    """Converts Users for flask URLs."""

    def to_python(self, value):
        """Called to convert a `value` to its python equivalent.

        Here, we convert `value` to a User.
        """
        # Anytime an invalid value is provided, raise ValidationError.  Flask
        # will catch this, and continue searching the other routes.  First,
        # check that value is an integer, if not there is no way it could be
        # a user.
        if not value.isdigit():
            raise ValidationError()
        user_id = int(value)

        # Look up the user in the database.
        if user_id not in _database:
            raise ValidationError()

        # Otherwise, return the user.
        return _database[user_id]

    def to_url(self, value):
        """Called to convert a `value` to its `url` equivalent.

        Here we convert `value`, the User object to an integer - the user id.
        """
        return str(value.id)

rawDescription: Flask multiple URL handlers process URLs partially


code:
import argparse
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = "Print a range.")

    parser.add_argument("start", type = int, help = "Specify start.", )
    parser.add_argument("stop", type = int, help = "Specify stop.", )
    parser.add_argument("step", type = int, help = "Specify step.", )

    args=parser.parse_args()
    print(args)

rawDescription: How to modify the metavar for a positional argument in pythons argparse?

description: Modify the metavar for a positional argument in pythons argparse


code:
thirteen
fourteen
fifteen

rawDescription: how to extract specific lines from a data file

description: Extract specific lines from a data file


code:
import nltk

groucho_grammar = nltk.CFG.fromstring("""
S -> NP VP
PP -> P NP
NP -> Det N | Det N PP | 'I' | NUM N
VP -> V NP | VP PP
Det -> 'an' | 'my'
N -> 'elephant' | 'pajamas' | 'elephants'
V -> 'shot'
P -> 'in'
NUM -> '#NUM#'
""")

sent = 'I shot 333 elephants'.split()
sent = ['#NUM#' if i.isdigit() else i for i in sent]

parser = nltk.ChartParser(groucho_grammar)
for tree in parser.parse(sent):
    print(tree)

rawDescription: How to match integers in NLTK CFG?

description: Match integers in NLTK CFG


rawDescription: Complex Data Manipulation in Python

description: Complex Data Manipulation in Python


rawDescription: Concatenate or print list elements with a trailing comma in Python


code:
s=  "['a','b','c','d']"
from ast import literal_eval
list1=literal_eval(s)
list1

rawDescription: Python List comprehension: Single string to list


rawDescription: It is possible to round up integers using format?


code:
from math import *
def angle_trunc(a):
    while a < 0.0:
        a += pi * 2
    return a

def getAngleBetweenPoints(x_orig, y_orig, x_landmark, y_landmark):
    deltaY = y_landmark - y_orig
    deltaX = x_landmark - x_orig
    return angle_trunc(atan2(deltaY, deltaX))

angle = getAngleBetweenPoints(5, 2, 1,4)
assert angle >= 0, "angle must be >= 0"
angle = getAngleBetweenPoints(1, 1, 2, 1)
assert angle == 0, "expecting angle to be 0"
angle = getAngleBetweenPoints(2, 1, 1, 1)
assert abs(pi - angle) <= 0.01, "expecting angle to be pi, it is: " + str(angle)
angle = getAngleBetweenPoints(2, 1, 2, 3)
assert abs(angle - pi/2) <= 0.01, "expecting angle to be pi/2, it is: " + str(angle)
angle = getAngleBetweenPoints(2, 1, 2, 0)
assert abs(angle - (pi+pi/2)) <= 0.01, "expecting angle to be pi+pi/2, it is: " + str(angle)
angle = getAngleBetweenPoints(1, 1, 2, 2)
assert abs(angle - (pi/4)) <= 0.01, "expecting angle to be pi/4, it is: " + str(angle)
angle = getAngleBetweenPoints(-1, -1, -2, -2)
assert abs(angle - (pi+pi/4)) <= 0.01, "expecting angle to be pi+pi/4, it is: " + str(angle)
angle = getAngleBetweenPoints(-1, -1, -1, 2)
assert abs(angle - (pi/2)) <= 0.01, "expecting angle to be pi/2, it is: " + str(angle)

rawDescription: How to calculate the angle between a line and the horizontal axis?

description: Calculate the angle between a line and the horizontal axis


code: u'foo\nb'

rawDescription: creating stream to iterate over from string in Python

description: Creating stream to iterate over from string in Python


code:
from protorpc import messages

class Alpha(messages.Enum):
    A = 0
    B = 1
    C = 2
    D = 3

rawDescription: Pass enum to ndb.Model field in python

description: Pass enum to ndb.Model field in python


rawDescription: Execute regex located in an external file in python


code:
host='192.168.0.11'
port=8080

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
conn, addr = s.accept()

string = bytes('','UTF-8')

while True:

    d = conn.recv(640*480)

    if not d:
        print ("break")
        break

    else:

        string += d

    pil_image = Image.fromstring("RGB",(352,288),string)
    #(352,288) is the return of cam.get_size()

rawDescription: Sending Webcam feed via socket

description: Sending Webcam feed via socket


code:
order = df.sum(axis=1).sort(inplace=False)
result = df.loc[order.index]

rawDescription: custom sorting pandas dataframe

description: Custom sorting pandas dataframe


code:
query = "select date, sum(a) from table group by date"
cursor.execute (query, queryParameters)
result = dict(cursor.fetchall())

rawDescription: Python MySQLdb: How to get the result of a sql select having a group by into a dict?


code: ip = settings['IP']

rawDescription: Reading Tags in text File Python

description: Reading Tags in text File Python


code:
def custom_run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
    """Set the test indices"""
    settings.CATEGORY_CLASSIFIER_DATA = settings.TEST_CLASSIFIER_DATA
    return run_tests(test_labels, verbosity, interactive, extra_tests)

rawDescription: How to make django test framework read from live database?

description: Make django test framework read from live database


code:
def f():
  pass

rawDescription: What's a standard way to do a no-op in python?


code: any(x) and not all(x)

rawDescription: How do Python's any and all functions work?


code:
from weakref import WeakSet
class foo:
    _instances = WeakSet()
    def __init__(self, value):
        self.value = value
        foo._instances.add(self)
    def getvalues(self):
        return sum(instance.value for instance in foo._instances)

Joe = foo(5)
Bob = foo(4)
Jon = foo(3)
Jon.getvalues()
del Joe
Jon.getvalues()

rawDescription: Python: reference to other instances of class objects


code:
m = MyHashTable(5)

m.insert(13) # 13 % 5 = 3
m.insert(73) # 83 % 5 = 3
m.insert(93) # 93 & 5 = 3
print(m.search(13)) # 3
print(m.search(73)) # 4
print(m.search(93)) # 0
print(m.search(2)) # -1

rawDescription: Python MyHashTable class: search method with linear probing


code:
mylog = MyFile('test.log', 'w')
mylog.write('...')
mylog.close()

rawDescription: Write a file to disk only when first content is written into it


code:
def coroutine(func):
    # http://www.dabeaz.com/coroutines/index.html
    def start(*args,**kwargs):
        cr = func(*args,**kwargs)
        cr.next()
        return cr
    return start

def initialize():
    print('initialize')

def do_the_thing(*args, **kwargs):
    print('doing things', args, kwargs)
    return ('result', args)

@coroutine
def _function():
    args, kwargs = (yield)
    initialize()
    while True:
        args, kwargs = (yield do_the_thing(*args, **kwargs))
_function = _function().send
def function(*args, **kwargs):
    # This is purely to overcome the limitation that send can only accept 1 argument
    return _function((args,kwargs))

rawDescription: Changing a function implementation in Python


code: sorted_list = sorted(list_not_sorted, key=lambda x:x[1], reverse=True)

rawDescription: Using the python sorted function?

description: Using the python sorted function


code:
s = 'this is a sentences that has is and is and is (4)'
word = 'is'
counter = len([x for x in s.split() if x == word])
counter

rawDescription: Python - Find words in string

description: Python - Find words in string


code:
import os
import pickle
import functools

PICKLE = False
PICKLE_PATH = '/tmp'

def checkpoint(f):

    if not PICKLE:
        return f

    save_path = os.path.join(PICKLE_PATH, '%s.pickle' % f.__name__)

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        if os.path.exists(save_path):
            with open(save_path, 'rb') as f:
                return pickle.load(f)

        rv = f(*args, **kwargs)
        with open(save_path, 'wb') as f:
            pickle.dump(rv, f)

        return rv

    return wrapper

rawDescription: Formatting if try except else code blocks


code: from google.appengine.api import datastore

rawDescription: Django (nonrel), App engine and asynchronous database calls


code:
list_a = []
set_b = set()
for e in a_list:
    list_a.append(e['a'])
    set_b.add(e['b'])

rawDescription: Python: How should I reformat this short code block?


code:
print(test_idx.size)
# 439

rawDescription: Cross-validation: finding row indices for a test set that aren't part of a training set


code: from PyQt4.QtGui import QApplication

rawDescription: pyqt4 python QLabel show when push button clicked

description: Pyqt4 python QLabel show when push button clicked


code:
count = 0
prime = []          # this is obviously meant to collect all primes
candidate = []      # what is this supposed to do then though?
x = 2
y = 1               # never used
while count < 1000: # you start at `count = 0` but never increase the count
                    # later on, so would loop forever
    x = x+1
    if x > 1: # x is always bigger than 1 because you started at 2
              # and only increase it; also, you skipped 2 itself
        if x%2 != 0:                      # here, all you do is check if the
            if x%3 != 0:                  # number is dividable by any prime you
                if x%5 != 0:              # know of
                    if x%7 != 0:          # you can easily make this check work
                        if x%11 != 0:     # for any set (or list) of primes
                            if x%13 != 0: #
                                candidate.append(x) # why a candidate? If it’s
                                                    # not dividable by all primes
                                                    # it’s a prime itself

rawDescription: Trouble finding the 1000th prime using python


code:
from __future__ import unicode_literals
from distutils import dir_util
from pytest import fixture
import os

@fixture
def datadir(tmpdir, request):
    '''
    Fixture responsible for searching a folder with the same name of test
    module and, if available, moving all contents to a temporary directory so
    tests can use them freely.
    '''
    filename = request.module.__file__
    test_dir, _ = os.path.splitext(filename)

    if os.path.isdir(test_dir):
        dir_util.copy_tree(test_dir, bytes(tmpdir))

    return tmpdir

rawDescription: Pytest where to store expected data

description: Pytest where to store expected data


code:
import sys
sys.stdin.encoding

rawDescription: Python Unicode strings and the Python interactive interpreter


code:
class ParentForm(forms.Form):
     media = forms.ModelChoiceField(Media.objects.none(), widget=forms.Select())
     def __init__(self, *args, **kwargs):
         parent = kwargs.pop('parent')
         super(ParentForm, self).__init__(*args, **kwargs)
         self.fields['media'].queryset = parent.media.all()

def my_view(request):
    parent = Parent.objects.filter(name=request.session['current_parent'])
    form = ParentForm(parent=parent)
    return render_to_response('tab.html', {'media_form': form})

rawDescription: Django show ManyToMany field of model using ModelChoiceField


code:
class Parent:
    def __init__(self):
        self._construct_parser()
        # parse the argument
        self.parser.parse_args()

    def _construct_parser(self):
        self.parser = argparse.ArgumentParser()
        self.parser.add_argument("user")

class Child(Parent):
    def _construct_parser(self):
        super()._construct_parser()
        # add on to self.parser

rawDescription: How to decorate (wrap) child's method with parent's method

description: Decorate (wrap) child's method with parent's method


code:
import gc
n = 1000000
list_bar = [ None ] * n
for i in xrange(n):
    list_bar[i] = foo()
    if i % 10000 == 0:
        gc.collect()

rawDescription: Python list of Objects taking up too much memory


code:
if __name__ == '__main__':
    lib_app = app.App()
    res = player.getScreenResolution()
    lib_app.run(MainDiv(), app_fullscreen='True', app_resolution=''+str(res.x)+'x'+str(res.y))

rawDescription: How can I run an app in fullscreen?

description: Run an app in fullscreen


rawDescription: How to find number of instances of an item in a python list

description: Find number of instances of an item in a python list


code:
def store_var(self, name, value):
    setattr(self.data, name, value)

rawDescription: PyQt, Python 3: Lambda slot assigning signal argument to a variable?


code: zip(*(islice(accumulate(col), 1, None) for col in cols))

rawDescription: Cumulative addition whilst looping over a list


code: Symbol('{myvar-42}') + 1

rawDescription: Using SymPy to generically parse and solve equations


code:
@app.route('/getmethod/<jsdata>')
def get_javascript_data(jsdata):
    return jsdata

rawDescription: How do I send data from JS to Python with Flask?

description: Send data from JS to Python with Flask


code:
# Get west, north, east & south elements for [1:-1,1:-1] region of input array
W = A[1:-1,:-2]
N  = A[:-2,1:-1]
E = A[1:-1,2:]
S  = A[2:,1:-1]

# Check if all four arrays have 100 for that same element in that region
mask = (W == 100) & (N == 100) & (E == 100) & (S == 100)

# Use the mask to set corresponding elements in a copy version as 100s
out = A.copy()
out[1:-1,1:-1][mask] = 100

rawDescription: Replace values in an 2d array according to neighboring values


code: from mpl_toolkits.basemap import Basemap, _cylproj, _pseudocyl

rawDescription: How do I add a method to a class from a third-party Python module without editing the original module

description: Add a method to a class from a third-party Python module without editing the original module


code:
from datetime import date
def next_pi_date():
    today = date.today()
    pi_date = date(today.year, 3, 14)
    if pi_date < today:
        pi_date = pi_date.replace(year=pi_date.year + 1)
    return pi_date

next_pi_date()

rawDescription: Dates ( pi-Day )

description: Dates ( pi-Day )


code: pd.concat([df1,df2,df3], axis=1)

rawDescription: After Pandas Dataframe pd.concat I get NaNs


code: [float(i.replace(',', '.')) + 1 for s in invoer for i in s.split()]

rawDescription: How to convert a string to a float in python?

description: Convert a string to a float in python


code: vertices = sorted(vertices, key = lambda x: x.co.y, reverse = True)

rawDescription: Multisort Python

description: Multisort Python


code:
mycoord = { 'pink'  :[(5258,5422), (5479,5864)],
            'green' :[(5425,5450)],
            'orange':[(5266,5770)],
            'red'   :[(5258,5864)] }

# Sort the endpoints. Remember their color and whether they open or close.
points = []
for color, spans in mycoord.items():
  for open, close in spans:
    points.append((open, 'open', color))
    points.append((close, 'close', color))
points.sort()

# Iterate over the endpoints. Keep track of open spans. Mark intersections.
active_spans = {}
intersections = []
for point, kind, color in points:
  if len(intersections) != 0 and intersections[-1][0] == point:
    intersections[-1][1].add(color)
  else:
    color_set = set([color] + list(active_spans.keys()))
    intersections.append((point, color_set))
  if kind == 'close':
    active_spans[color] -= 1
    if active_spans[color] == 0:
      del active_spans[color]
  else:
    active_spans[color] = active_spans.setdefault(color, 0) + 1

# Iterate over consecutive pairs of unique intersections. Intersect the color sets.
tab_width = sum(map(len, mycoord)) + len(mycoord)
count = 0
for i in range(1, len(intersections)):
  a, b = intersections[i - 1], intersections[i]
  colors = sorted(a[1] & b[1])
  if len(colors) > 0:
    count += 1
    print('sect{0}/{1:<{2}}: {3},{4}'.format(count, '-'.join(colors), tab_width,
        a[0], b[0]))

rawDescription: Python program to detect intersection of one-dimensional line segments


code:
orange
lemon

rawDescription: How to separate a single list into multiple list in python

description: Separate a single list into multiple list in python


code: {k:v for k, v in d.items() if v != ''}

rawDescription: remove the keys which has blank values

description: Remove the keys which has blank values


code:
class AnotherScreen(Screen):
    def on_pre_enter(self, *args):
        t=[]
        a = App.get_running_app()
        self.ids.container.add_widget(Button(text='Assignatura',background_color=[0,1,1,1]))
        self.ids.container.add_widget(Button(background_color=[0,1,1,1],text='Escriu Grup'))
        for k,v in a.big_dict.iteritems():
            if v:
                self.ids.container.add_widget(Label(text=k))
                self.k=TextInput(multiline=False)
                t.append(self.k.text)
                self.ids.container.add_widget(self.k)
        b1=Button(text='Exit',background_color=[0,1,0,1])
        self.ids.container.add_widget(b1)
        b2=Button(text='Run',background_color=[0,1,0,1])
        self.ids.container.add_widget(b2)
        b1.bind(on_press=exit)

rawDescription: How to create a dynamic kivy app with checkboxes?

description: Create a dynamic kivy app with checkboxes


code:
import numpy as np

a = np.random.choice(10**7, size=10**6, replace=False)
a.sort()
b = np.random.choice(10**7, size=10**5, replace=False)
b.sort()

def using_searchsorted(a, b):
    return (np.where(np.searchsorted(b, a, side='right')
                     != np.searchsorted(b, a, side='left')))[0]

def using_in1d(a, b):
    return np.where(np.in1d(a, b))[0]

def using_searchsorted_divakar(a, b):
    idx1 = np.searchsorted(a,b,'left')
    idx2 = np.searchsorted(a,b,'right')
    out = idx1[idx1 != idx2]
    return out

def using_jaime_mask(haystack, needle):
    idx = np.searchsorted(haystack, needle)
    mask = idx < haystack.size
    mask[mask] = haystack[idx[mask]] == needle[mask]
    idx = idx[mask]
    return idx

expected = using_searchsorted(a, b)
for func in (using_in1d, using_searchsorted_divakar, using_jaime_mask):
    result = func(a, b)
    assert np.allclose(expected, result)

rawDescription: Find indices of large array if it contains values in smaller array


code:
df = DataFrame(randint(6, size=(10, 3)))
df
df.where(df, nan)

rawDescription: python pandas .map double variable lambda

description: Python pandas .map double variable lambda


code:
class B(A):

     def __init__(self, x, y):
          super().__init__(x)
          self.y = y

rawDescription: What is the purpose of calling __init__ directly?


rawDescription: Numpy array comparison using nditer

description: Numpy array comparison using nditer


code: "The sum of 1 + 2 is {0}".format(1+2)

rawDescription: insert variable values into a string in python

description: Insert variable values into a string in python


code:
import re
text = "[Admin] has [logged out] on [admin page] at [Monday 20 May, 11:00]"
re.findall(r'\[([^\]]*)\]', text)

rawDescription: Match many results in the same String

description: Match many results in the same String


code:
def drawTree(self, tree, f):
    id = 0
    nodes = [(None, self)]  # queue with nodes to process

    while nodes:
        parent, node = nodes.pop(0)
        tree.add_node(id, label=node.data, color='goldenrod2', style='filled')
        if parent is not None:
            tree.add_edge(parent, id, color='sienna', style='filled')

        if node.left is not None:
            nodes.append((id, node.left))
        else:
            none_id = '{}_left_none'.format(id)
            tree.add_node(none_id, label='', color='goldenrod1', shape='box', style='filled')
            tree.add_edge(id, none_id, color='sienna', style='filled')

        if node.right is not None:
            nodes.append((id, node.right))
        else:
            none_id = '{}_right_none'.format(id)
            tree.add_node(none_id, label='', color='goldenrod1', shape='box', style='filled')
            tree.add_edge(id, none_id, color='sienna', style='filled')

        id += 1

    tree.write(f)
    img = pgv.AGraph(f)
    img.layout(program='dot')
    img.draw(f.split('.')[0] + '.pdf')
    img.close()

rawDescription: How to create duplicate nodes in PyGraphviz?

description: Create duplicate nodes in PyGraphviz


code:
def doY():
    print("in y") # line 2

rawDescription: Remember breakpoints when debugging using ipython


code: comment_form = CommentForm()

rawDescription: Flask WTF-forms adding select and textarea


code:
def unique_preserve_order(seq, key=None):
    if key is None:
        key = lambda elem: elem
    seen = set()
    seen_add = seen.add
    augmented = ((key(x), x) for x in seq)
    return [x for k, x in augmented if not (k in seen or seen_add(k))]

rawDescription: delete duplicates from list of tuples

description: Delete duplicates from list of tuples


rawDescription: Select rows from a list of tuples in pandas


code:
with open("in.txt") as f, open('test_output.txt', "w") as out:
    wr = csv.writer(out, delimiter=",")
    for line in f:
        wr.writerow(filter(lambda x: x not in  {",",""},line.rstrip().split("|")))

rawDescription: (Python) Breaking an output text file into tokens


code:
memDC.Blit(0, 0, size.width, size.height, dcSource, 0,0,  useMask=True)

canvas_dc.DrawBitmap(testImage,0, 0, useMask=True)

rawDescription: Is there a max image size (pixel width and height) within wx where png images lose there transparency?


code:
from bisect import bisect_left

class discrete_cdf:
    def __init__(data):
        self._data = data # must be sorted
        self._data_len = float(len(data))

    def __call__(point):
        return (len(self._data[:bisect_left(self._data, point)]) /
                self._data_len)

rawDescription: Python: How to plot a cdf function given an array of numbers


code:
try:
    stats = [re.search('[A-Z]?[a-z]?[A-Z][a-z]{1,} [A-Z][a-z]{1,}',player).group()]
except:
    stats = [re.search('[A-Z]\.?[A-Z]?\.? [A-Z][a-z]{1,}',player).group()]

rawDescription: Problems Parsing NBA Boxscore Data with BeautifulSoup


code:
results = portal_catalog.searchResults(query)
results = sorted(results, key=lambda b: (b.item_publication_year, b.item_publication_month))

rawDescription: Sorting the catalog results by multiple fields


code:
s1 = 'I program'
s2 = ' like to'
s1[:1] + s2 + s1[1:]
Out[5]: 'I like to program'

rawDescription: python add to string after nth characters

description: Python add to string after nth characters


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

# Data
states = ["AK", "TX", "CA", "MT", "NM", "AZ", "NV", "CO", "OR", "WY", "MI",
          "MN", "UT", "ID", "KS", "NE", "SD", "WA", "ND", "OK"]
staff = np.array([20, 30, 40, 10, 15, 35, 18, 25, 22, 7, 12, 22, 3, 4, 5, 8,
                  14, 28, 24, 32])
sales = staff * (20 + 10 * np.random.random(staff.size))

# Sort by number of sales staff
idx = staff.argsort()
states, staff, sales = [np.take(x, idx) for x in [states, staff, sales]]

y = np.arange(sales.size)

fig, axes = plt.subplots(ncols=2, sharey=True)
axes[0].barh(y, staff, align='center', color='gray', zorder=10)
axes[0].set(title='Number of sales staff')
axes[1].barh(y, sales, align='center', color='gray', zorder=10)
axes[1].set(title='Sales (x $1000)')

axes[0].invert_xaxis()
axes[0].set(yticks=y, yticklabels=states)
axes[0].yaxis.tick_right()

for ax in axes.flat:
    ax.margins(0.03)
    ax.grid(True)

fig.tight_layout()
fig.subplots_adjust(wspace=0.09)
plt.show()

rawDescription: Using Python libraries to plot two horizontal bar charts sharing same y axis


code:
from operator import add
from pyspark.sql.functions import col, lit

n = lit(len(df.columns) - 1.0)
rowMean  = (reduce(add, (col(x) for x in df.columns[1:])) / n).alias("mean")

df.select(rowMean)

rawDescription: Spark DataFrame: Computing row-wise mean (or any aggregate operation)


code:
def cond_with(*phrases):
  """for each 2-tuple, invokes first item.  the first pair where
  the first item returns logical true, result is passed to second
  function in pair.  Like an if-elif-elif.. chain"""
  for (cond_lambda, then_lambda) in phrases:
    c = cond_lambda()
    if c:
      return then_lambda(c)
  return None

cond_with(
  ((lambda: re.match('foo (\w+) bar (\d+)', line)),
      (lambda m:
          ... # do stuff with m.group(1) and m.group(2)
          )),
  ((lambda: re.match('baz whoo_(\d+)', line)),
      (lambda m:
          ... # do stuff with m.group(1)
          )),
  ...)

rawDescription: Python's re module - saving state?

description: Python's re module - saving state


code:
import base64
def b64encode(s):
    return base64.b64encode(s)

jinja2_environment.filters['b64encode'] = b64encode

rawDescription: Jinja2: Converting hex to Base64

description: Jinja2: Converting hex to Base64


rawDescription: nan in interp1d scipy

description: Nan in interp1d scipy


code:
with contextlib.ExitStack as stack:
    lenmap = {i: stack.enter_context(open('file{}'.format(i), 'w'))
             for i in range(10)}
    for entry in List1:
        f = lenmap.get(len(entry))
        if f:
            f.write(entry)

rawDescription: Extract elements from a list and sorting them by length


code:
a_copy=a.copy()
for hor_shift,vert_shift in neighbors:
    if not np.any(a.mask): break
    a_shifted=np.roll(a_copy,shift=hor_shift,axis=1)
    a_shifted=np.roll(a_shifted,shift=vert_shift,axis=0)
    idx=~a_shifted.mask*a.mask
    a[idx]=a_shifted[idx]

rawDescription: Fill in missing values with nearest neighbour in Python numpy masked arrays?


code: randomList

rawDescription: creating list of random numbers in python

description: Creating list of random numbers in python


code:
def calculator(user_input):
    global ans
    if any(c not in config.valid_cal_chars for c in user_input):
        print("- Invalid Equation | Bad characters")
        return
    sys.stdout.write("calculating " + "-".join(gfx.load_sequence))
    time.sleep(0.1)
    print (" | 100%")
    try:
        ans = eval(user_input, {'ans':ans,'sqrt':sqrt},{})
    except (SyntaxError, ZeroDivisionError, NameError, TypeError, ValueError):
        print ("- Invalid Equation | Error")
        return
    config.ans = ans
    print (ans)

rawDescription: Using user defined variables/functions in eval [Python 3.4.2]?


rawDescription: Replace every second element in list with every third in other list.


code:
Holiday("Good Friday", type='moveable',
    base='gregorian_easter', delta_days=-2)
Holiday("Easter Monday", etc, delta_days=1)
# Some states in Australia used to have Easter Tuesday (no kidding)
Holiday("Easter Tuesday", etc, delta_days=2)

rawDescription: Detecting a US Holiday

description: Detecting a US Holiday


code:
class SplitableList:
    def __init__(self,ar): self.ary = ar
    def split(self,sep): return separate(self.ary,sep)
    # delegate other method calls to self.ary here, for example
    def __len__(self): return len(self.ary)

a = SplitableList([1,3,4,6,8,5,3,4,5,8,4,3])
b = a.split([3,4]) # returns desired result

rawDescription: Python use split with arrays

description: Python use split with arrays


code:
u'٤'.isdigit()
u'٢'.isdigit()

rawDescription: How to Force Django's urls.py regex to restrict to ASCII digits only?


code:
from wand.api import library
import ctypes

class ChannelStatistics(ctypes.Structure):
    _fields_ = [('depth', ctypes.c_size_t),
                ('minima', ctypes.c_double),
                ('maxima', ctypes.c_double),
                ('sum', ctypes.c_double),
                ('sum_squared', ctypes.c_double),
                ('sum_cubed', ctypes.c_double),
                ('sum_fourth_power', ctypes.c_double),
                ('mean', ctypes.c_double),
                ('variance', ctypes.c_double),
                ('standard_deviation', ctypes.c_double),
                ('kurtosis', ctypes.c_double),
                ('skewness', ctypes.c_double)]

library.MagickGetImageChannelStatistics.argtypes = [ctypes.c_void_p]
library.MagickGetImageChannelStatistics.restype = ctypes.POINTER(ChannelStatistics)

rawDescription: Python-wand: How can I read image properties/statistics


code:
from dateutil.relativedelta import relativedelta

A_MONTH = relativedelta(months=1)

month = ItemPrice.objects \
    .filter(date__gte = date - A_MONTH) \
    .filter(date__lt = date) \
    .aggregate(month_average = Avg('price'))

rawDescription: Django/python date aggregation by month and quarter


code:
my_string = 'foo_bar_one_two_three'
print(my_string.rsplit('_', 1)[0])

rawDescription: Remove Last instance of a character and rest of a string


code: [('#meta data 1', 'skadjflaskdjfasljdfalskdjfl\nsdkfjhasdlkgjhsdlkjghlaskdj\nasdhfk'), ('#meta data 2', 'jflaksdjflaksjdflkjasdlfjas\nldaksjflkdsajlkdfj'), ('#meta data 3', 'alsdkjflasdjkfglalaskdjf')]

rawDescription: How to read a file with variable multi-row data in Python

description: Read a file with variable multi-row data in Python


code:
huge_list = []

with open(huge_file, "r") as f:
    huge_list = f.read().split()

rawDescription: Reading words from a file and putting into list


rawDescription: How to take out the column index name in dataframe

description: Take out the column index name in dataframe


code:
def newcsv(data, csvheader, fieldnames):
    """
    Create a new csv file that represents generated data.
    """
    csvrow = []
    new_csvfile = StringIO.StringIO()
    wr = csv.writer(new_csvfile, quoting=csv.QUOTE_ALL)
    wr.writerow(csvheader)
    wr = csv.DictWriter(new_csvfile, fieldnames = fieldnames)

    for key in data.keys():
        wr.writerow(data[key])

    return new_csvfile

rawDescription: How to generate a file without saving it to disk in python?

description: Generate a file without saving it to disk in python


code:
...
soup = bs4.BeautifulSoup(html_content)
diff = d.compare(list(soup.stripped_strings), list_to_compare_to)
print('\n'.join(diff))
...

rawDescription: Comparing HTML with difflib

description: Comparing HTML with difflib


code:
try:
    # for Python2
    from Tkinter import *
except ImportError:
    # for Python3
    from tkinter import *

class GUI(Frame):

    # Create and return a packed frame.
    def frame(self, side):
        w = Frame(self)
        w.pack(side=side, expand=YES, fill=BOTH)
        return w

    # Create and return a button.
    def button(self, root, side, text, command=None):
        w = Button(root, text=text, command=command)
        w.pack(side=side, expand=YES, fill=BOTH)
        return w

    def hello(self):
        self.display.set('hello')

    def keyPressed(self,event):
        #test to see whether enetr is pressed
        if event.keysym == 'Return':
            self.hello()
    def __init__(self):
        Frame.__init__(self)
        self.option_add('*Font', 'Verdana 12 bold')
        self.pack(expand=YES, fill=BOTH)
        self.master.title('Simple GUI')

        # The StringVar() object holds the value of the Entry.
        self.display = StringVar()
        e = Entry(self, relief=SUNKEN, textvariable=self.display)
        e.pack(side=TOP, expand=YES, fill=BOTH)

        # Clear button.
        clearF = self.frame(BOTTOM)
        self.hello_button = self.button(clearF, LEFT, 'Hello', self.hello)
        #bind keypresses
        self.bind_all('<Key>', self.keyPressed)

if __name__ == '__main__':
 GUI().mainloop()

rawDescription: i cant use the equals or the enter key on my keyboard to get an answer for anything

description: I cant use the equals or the enter key on my keyboard to get an answer for anything


code: z = zipfile.ZipFile('myfile.zip')

rawDescription: How to add the contents of a directory to a zip file?

description: Add the contents of a directory to a zip file


code:
df['D'] = df.groupby('A')['B'].transform('max') + df['C']
df

rawDescription: Python pandas - apply function to grouped dataframe


code:
if test in 'abcd': # string
   do_something()

rawDescription: Is it possible to check if a value is equal to another in python quickly when referring it to a list?


code:
slower_gen_expr = ' - '.join('{}: {}'.format(key, value) for key, value in some_dict)
faster_list_comp = ' - '.join(['{}: {}'.format(key, value) for key, value in some_dict])

rawDescription: Concatenate elements of a list

description: Concatenate elements of a list


code:
class Pdb(OldPdb):
  """Modified Pdb class, does not load readline."""

  def __init__(self,color_scheme='NoColor',completekey=None,
               stdin=None, stdout=None, context=None):
      context=20

rawDescription: How can I make ipdb show more lines of context while debugging?

description: Make ipdb show more lines of context while debugging


code:
def load_url(self, url):
    self.view. load(QtCore.QUrl(url))

rawDescription: Python PyQt QWebView load site in clicked tab


code: new_data = numpy.zeros((1, 2), dtype=stereo_data.dtype)

rawDescription: constructing a wav file and writing it to disk using scipy

description: Constructing a wav file and writing it to disk using scipy


code: ["%s and %s" % (t1, t2) for i, t1 in enumerate(teams) for t2 in teams[i + 1:]]

rawDescription: Itertools product without repeating duplicates


code:
mapping = '''
{
    "mappings": {
        "test": {
            "properties": {
                "DocumentID": {
                    "type": "string"
                },
                "Tags": {
                    "type": "string",
                    "index": "not_analyzed"
                }
            }
        }
    }
}
'''

rawDescription: Elasticsearch : es.index() changes the Mapping when message is pushed


rawDescription: Need help reading data from input files and displaying it


rawDescription: Map arrays to integers in python

description: Map arrays to integers in python


code:
from string import punctuation as pnc
tokens = {':)', 'cool', 'happy', 'fun'}
tweets = ['this has been a fun day :)', 'i find python cool! it makes me happy']
for tweet in tweets:
    s = [(word in tokens or word.strip(pnc) in tokens) for word in tweet.split()]
    print(' '.join('1' if t else '0' for t in s))

rawDescription: Best way to change words into numbers using specific word list

description: Change words into numbers using specific word list


rawDescription: count distinct occurrences in pandas

description: Count distinct occurrences in pandas


code:
import __builtin__
__builtin__.myapp_debug = True
from app import app

rawDescription: Set a variable before importing module __init.py__


code:
from unidecode import unidecode
from django.template import defaultfilters
slug = defaultfilters.slugify(unidecode(input_text))

rawDescription: How to make Django slugify work properly with Unicode strings?

description: Make Django slugify work properly with Unicode strings


code:
x, y = max(a, c), min(b, d)
if x > y:  # no overlap
    x, y = None, None

rawDescription: Computing where the overlap is

description: Computing where the overlap is


code:
s = '12abcd405'
result = ''.join(i for i in s if not i.isdigit())
result

rawDescription: Removing numbers from string

description: Removing numbers from string


rawDescription: Python convention for variables that won't be used, but are reuturned from a function nonetheless


code:
accessories,James,John,Adam,Nick
Ties,6,3,1,4
Belts,0,1,0,0
Jeans,6,6,2,8
Shirts,10,5,3,4
Shoes,5,10,5,3

rawDescription: Parsing Dictionary Into Spreadsheet in Python


code:
df = pd.DataFrame(np.random.random(10), columns=['a'])
df = df.ix[(df.a > lower) & (df.a < upper)]

rawDescription: Apply upper and lower bounds to Pandas Dataframe


code:
def neu(self, sortByValue, secondValue):
    def child(node):
        if(node is None):
            return MyTree(sortByValue, secondValue)
        else:
            child.neu(sortByValue, secondValue)
            return node

    if(sortByValue.lower() < self.value[0].lower()):
        self.left = child(self.left)
    else:
        self.right = child(self.right)

rawDescription: Pointers in Python on variables with None value


code:
import re

search_string = ['Good', 'Bad', 'Ugly']
pattern = '({0})'.format('|'.join(map(re.escape, search_string)))
retained_texts = []
for text in full_text:
    if re.search(pattern, text):
        retained_texts.append(' '.join(text))

rawDescription: Capture any occurrence of word in a text; RegEx; Python


code:
result = (yourlist for yourlist in yourlists
          if any(node.startswith('4-') for node in yourlist))

rawDescription: Deleting a list that does not meet a specific criteria?


code:
frame = store.select(group_that_I_want)
# you can optionally specify:
# columns = a list of the columns IN THAT GROUP (if you wanted to
#     select only say 3 out of the 20 columns in this sub-table)
# and a where clause if you want a subset of the rows

# do calculations on this frame
new_frame = cool_function_on_frame(frame)

# to 'add columns', create a new group (you probably want to
# limit the columns in this new_group to be only NEW ones
# (e.g. so you don't overlap from the other tables)
# add this info to the group_map
store.append(new_group, new_frame.reindex(columns = new_columns_created, copy = False), data_columns = new_columns_created)

rawDescription: "Large data" work flows using pandas

description: "Large data" work flows using pandas


code:
from tkinter import ttk
from tkinter import *
import tkinter.font

class Main(Tk):
    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)

        self.fonts = list(tkinter.font.families())
        self.fonts.sort()

        self.list = Listbox(self, activestyle=NONE)
        for item in self.fonts:
            self.list.insert(END, item)
        self.list.pack(side=LEFT, expand=YES, fill=BOTH)
        self.list.bind("<<ListboxSelect>>", self.PrintSelected)

        self.scroll = ttk.Scrollbar(self)
        self.scroll.pack(side=RIGHT, fill=Y)

        self.scroll.configure(command=self.list.yview)
        self.list.configure(yscrollcommand=self.scroll.set)

    def PrintSelected(self, e):
        print(self.fonts[int(self.list.curselection()[0])])

root = Main()
root.mainloop()

rawDescription: Tkinter - How to assign variable to currently selected item in Listbox?


code:
re.sub(r'("[^"]*")|delhi', lambda m: m.group(1) if m.group(1) else "", a)
re.sub(r'("[^"]*")|delhi', lambda m: m.group(1) if m.group(1) else "", a).strip()

rawDescription: Replace a substring selectively inside a string


code: index_dict = dict( (item, i) for i, item in enumerate(index_list) )

rawDescription: Making a index array from an array in numpy


code:
regex = re.compile('|'.join(re.escape(x) for x in searchList))
found = regex.findall(cleanText)

rawDescription: Fastest way in python to search for multiple items in a body of text


code: new_dict = dict((key, template[key] % values_dict) for key, value in template.items())

rawDescription: Python dictonary with string placeholders and defaults


code: a = [i for i in a if i[-1] != 0] #list comprehension (1 line) method.

rawDescription: Removing items from a list in python

description: Removing items from a list in python


code: x

rawDescription: Substituting only unmasked values in a masked numpy array


code:
from tkinter import *

class myClass:
    def __init__(self, root):
        print("root background is %s" % root.cget("background"))

root = Tk()
newObj = myClass(root)

rawDescription: Tkinter: invoke event in main loop

description: Tkinter: invoke event in main loop


code: year = models.IntegerField(_('year'), max_length=4, choices=year_dropdown, default=datetime.datetime.now().year)

rawDescription: Creating year dropdown in Django template


code:
#python test.py
1
1
1

rawDescription: What is the exact way to send erlang module and erlang function to the mapreduce face in python-riak client l


code:
A=10*np.eye(10) + np.random.rand(100).reshape(10,10)
imshow(A)

rawDescription: Prevent anti-aliasing for imshow in matplotlib


code: list = City.objects.filter(Q(primary_doc__name='Smith') | Q(secondary_doc__name='Smith'))

rawDescription: Django join tables with two FK fields backwards


code:
y = y_and_data[:,0]       # the first column is the y-values
data = y_and_data[:,1:]   # the remaining columns are the data

rawDescription: How to manipulate the data after numpy.loadtxt?

description: Manipulate the data after numpy.loadtxt


code:
from pyrise import *
Highrise.server('my-server')
Highrise.auth('api-key-goes-here')
p = Person()
p.first_name = 'Joe'
p.last_name = 'Schmoe'
p.save()

rawDescription: Access Highrise's API with Python?

description: Access Highrise's API with Python


code: m = max(dictionary, key=lambda v: dictionary[v].get(value, float('-inf')))

rawDescription: Find Maximum Value in Nested Dictionary and return Key


code:
import numpy as np
list_to_check_var = [2,2,2,2,2.00000000001]
np.var(list_to_check_var)

rawDescription: Python: numpy.var yields unknown number

description: Python: numpy.var yields unknown number


code:
def post(self):
    uploads = self.get_uploads()
    try:
        pass  # Put your application-specific code here.
        # As soon as you have stored a blob key in the database (using a transaction),
        # remove the corresponding upload from the uploads array.
    finally:
        keys = [upload.key() for upload in uploads]
        blobstore.delete_multi(keys)

rawDescription: GAE: how can I combine a BlobstoreUploadHandler and a RequestHandler in 1 webpage


code: x[:, None]

rawDescription: Shortest Syntax To Use numpy 1d-array As sklearn X


rawDescription: Python 3.4.3 - Sorting statistical list alphabetically


code:
import re

forbidden_patterns = ['Word1', 'Word2', 'Word3', '\d{4}']

string = "This is Word1 a list thatWord2 I'd like to 2016 be readableWord3"

for pattern in forbidden_patterns:
    string = ''.join(re.split(pattern, string))

print(string)

rawDescription: Removing any pattern (word or regex) defined in a list from a string


code:
urls = []

with open(urls_file) as f:
    while True:
        try:
            for i in range(5):
                urls.append(next(f).rstrip())
            print(urls)  # i.e. you have the list of urls, now use it/put it to work
            urls = []
        except StopIteration:
            print(urls)
            break

rawDescription: How to trigger something on the close of a loop?

description: Trigger something on the close of a loop


code:
root.config(menu_Bar = file_Menu)

# Tkinter GUI Menu

from tkinter import *

### Functions ###

# Do Nothing
def do_Nothing():
    print('I just did... nothing')

### Create tkinter window ###

# Create Window
root = Tk()

#### Creating the Menu(s) ###

# Create the Menu Bar
menu_Bar = Menu(master = root)

# Create File Menu
file_Menu = Menu(master = menu_Bar)

### Displaying the Menu(s) ###

# Display Menu Bar
root.config(menu = menu_Bar)

# Display File Menu
menu_Bar.add_cascade(label = 'File', menu = file_Menu)

### File Menu Properties ####

# New
file_Menu.add_command(label = 'New', command = do_Nothing)

# Open
file_Menu.add_command(label = 'Open', command = do_Nothing)

# Exit
file_Menu.add_command(label = 'Exit', command = root.quit)

### Display tkinter window ###
root.mainloop()

# Display Menu Bar
root.config(menu = menu_Bar)

rawDescription: Python quit unexpectedly

description: Python quit unexpectedly


code:
import xml.etree.ElementTree as ET

class PIParser(ET.XMLTreeBuilder):
    """
    http://effbot.org/zone/element-pi.htm
    """
    def __init__(self):
        ET.XMLTreeBuilder.__init__(self)
        # assumes ElementTree 1.2.X
        self._parser.CommentHandler = self.handle_comment
        self._parser.ProcessingInstructionHandler = self.handle_pi
        self._target.start("document", {})

    def close(self):
        self._target.end("document")
        return ET.XMLTreeBuilder.close(self)

    def handle_comment(self, data):
        self._target.start(ET.Comment, {})
        self._target.data(data)
        self._target.end(ET.Comment)

    def handle_pi(self, target, data):
        self._target.start(ET.PI, {})
        self._target.data(target + " " + data)
        self._target.end(ET.PI)

tree = ET.parse('data', PIParser())

rawDescription: updating XML attribute value in python

description: Updating XML attribute value in python


code:
rs = Request.select().where(Request.TIME_STAMP-datetime.datetime.now()
                            <(datetime.timedelta(seconds=10*60)))

rawDescription: Python peewee, filtering query based on ellapsed time


code:
def extract_nouns(i_location, o_location):
    import nltk

    with open(i_location, "r") as myfile:
      data = myfile.read().replace('\n', '')

    tokens = nltk.word_tokenize(data)
    tagged = nltk.pos_tag(tokens)
    length = len(tagged)
    a = []

    for i in range(0,length):
       print(i)
       log = (tagged[i][1][0] == 'N')
       if not log:
           a.append(tagged[i][0])
    with open(i_location, 'r') as fin, open(o_location, "w+")  as fout:
        for line in fin:
            for word in a:
               line = line.replace(word, "")
            fout.write(line)
            fout.seek(0) # go back to start of file
            data_out = fout.read().replace('\n' , '')
        return data_out

rawDescription: Why my function is returning empty string in python?


code:
class Contact(object):
    def __hash__(self):
        return self.name.__hash__

rawDescription: Compare attributes of objects inside a list?


rawDescription: Txt Parsing in Python

description: Txt Parsing in Python


code:
fmt = '\033[0;41;97m %(message)s \033[0m'
logging.basicConfig(level=logging.DEBUG, format=fmt)
logger = logging.getLogger(__file__)
logger.info('hello')

rawDescription: How to decorate console logger messages in Python?

description: Decorate console logger messages in Python


code:
lod = [ ] # "list of dicts"

def populate_lod(lod, csv_fp):
    rdr = csv.DictReader(csv_fp, ['Row', 'Name', 'Year', 'Priority'])
    lod.extend(rdr)

def query_lod(lod, filter=None, sort_keys=None):
    if filter is not None:
        lod = (r for r in lod if filter(r))
    if sort_keys is not None:
        lod = sorted(lod, key=lambda r:[r[k] for k in sort_keys])
    else:
        lod = list(lod)
    return lod

def lookup_lod(lod, **kw):
    for row in lod:
        for k,v in kw.iteritems():
            if row[k] != str(v): break
        else:
            return row
    return None

rawDescription: Python: Data Structure for Maintaing Tabular Data in Memory?


code:
while True:
   pygame.event.pump() #allow Pygame to handle internal actions
   joystick_count = pygame.joystick.get_count()

   for i in range(joystick_count):
        joystick = pygame.joystick.Joystick(i)
        joystick.init()

        name = joystick.get_name()
        axes = joystick.get_numaxes()
        hats = joystick.get_numhats()
        button = joystick.get_numbuttons()

        joy = joystick.get_axis(0)

        print(name, joy)

rawDescription: Pygame read axis value from BU0836X HID device


code:
from collections import defaultdict
d = defaultdict(list)
d
d[9].append(100)
d

rawDescription: Creating a dict of blank lists that are not the same list


code: b = list(map(obj.getDateTimeStat,data))

rawDescription: Python: Map calling a function not working


code:
from mock import patch

class Tests_urls(TestCase):
    @patch('my_app.views.treat_login')
    def test_signin(self, mock_treat_login):
        self.client.post(reverse("login"), {"username":"login", "password":"pwd"})
        self.assert_http_status(url, status, "after a standard login")
        self.assertTrue(mock_treat_login.called)

rawDescription: How to mock databases access while testing urls with Django

description: Mock databases access while testing urls with Django


code:
def myLog(x, b):
    if b > x:
            return 0
    elif x == b:
            return 1
    else:
            x /= b
            return 1 + myLog(x, b)

rawDescription: Computing logarithm

description: Computing logarithm


rawDescription: Convert pyBarcode output to PIL Image file


code:
a = ['Little Mary had a lamb', 'the horse is black', 'Mary had a cat']
b = ['The horse is white', 'Mary had a dog', 'The horse is hungry']
[sent for sent in a+b if 'Mary' in sent]

rawDescription: Extract some items from a list to build a new list


code:
class SomeMixin(object):

    def get_context_data(self, **kwargs):
        context = super(SomeMixin, self).get_context_data(**kwargs)
        something = something
        context['something'] = something
        return context

rawDescription: Django: How to provide context for a FormView?


code: args_on = [arg for arg in self.request.arguments() if self.request.get(arg) == 'on']

rawDescription: Getting the Parameter name of a Value in a URL request


rawDescription: Threading halts execution of Tkinter program


rawDescription: python pandas extract unique dates from time series

description: Python pandas extract unique dates from time series


code:
import unicodedata

def unitprefix(val):
    """Give the unit an appropriate SI prefix.

    :param val: Number and a unit, e.g. "0.000009 m²"
    """
    xstr, unit = val.split(None, 2)
    x = float(xstr)

    try:
        dimension = unicodedata.digit(unit[-1])
    except ValueError:
        dimension = 1

    return prefix(x, dimension) + unit

rawDescription: Pretty-printing physical quantities with automatic scaling of SI prefixes


code:
class CrossTab(object):

    def __init__(
        self,
        missing=0, # what to return for an empty cell.
                   # Alternatives: '', 0.0, None, 'NULL'
        ):
        self.missing = missing
        self.col_key_set = set()
        self.cell_dict = {}
        self.headings_OK = False

    def add_item(self, row_key, col_key, value):
        self.col_key_set.add(col_key)
        try:
            self.cell_dict[row_key][col_key] += value
        except KeyError:
            try:
                self.cell_dict[row_key][col_key] = value
            except KeyError:
                self.cell_dict[row_key] = {col_key: value}

    def _process_headings(self):
        if self.headings_OK:
            return
        self.row_headings = list(sorted(self.cell_dict.keys()))
        self.col_headings = list(sorted(self.col_key_set))
        self.headings_OK = True

    def get_col_headings(self):
        self._process_headings()
        return self.col_headings

    def generate_row_info(self):
        self._process_headings()
        for row_key in self.row_headings:
            row_dict = self.cell_dict[row_key]
            row_vals = [
                row_dict.get(col_key, self.missing)
                for col_key in self.col_headings
                ]
            yield row_key, row_vals

if __name__ == "__main__":

    data = [["apples", 2, "New York"],
      ["peaches", 6, "New York"],
      ["apples", 6, "New York"],
      ["peaches", 1, "Vermont"]]

    ctab = CrossTab(missing='uh-oh')
    for s in data:
        ctab.add_item(row_key=s[2], col_key=s[0], value=s[1])
    print()
    print('Column headings:', ctab.get_col_headings())
    for row_heading, row_values in ctab.generate_row_info():
        print(repr(row_heading), row_values)

rawDescription: How to pivot/cross-tab data in Python 3?

description: Pivot/cross-tab data in Python 3


code:
#!/usr/bin/env python
import os
from subprocess import call

bash_lines = ['#!/bin/bash\n', '#PBS -l nodes=1;ppn=1\n']
bash_name = 'myjob_%i.sh'
job_call = 'ifort -openmp ran_numbers.f90 %s ompscmf.f90 -o scmf.o &\n'
qsub_call = 'qsub myjob_%i.sh'

filenames = [os.path.join(root, f) for root, _, files in os.walk(directory)
                                   for f in files if f.endswith('.txt')]
for i, filename in enumerate(filenames):
    with open(bash_name%i, 'w') as bash_file:
        bash_file.writelines(bash_lines + [job_call%filename, 'wait\n'])
    call(qsub_call%i, shell=True)

rawDescription: Submitting jobs using python

description: Submitting jobs using python


rawDescription: Python: create fixed point decimal from two 32-bit ints (one for int portion, one for decimal)


code:
import math

area1 = 0.5 * self.sides[0] * self.sides[1] * math.sin(math.radians(self.angles[1]))
area2 = 0.5 * self.sides[2] * self.sides[3] * math.sin(math.radians(self.angles[3]))
area = area1 + area2

rawDescription: Calculate the area of a quadrilateral

description: Calculate the area of a quadrilateral


code:
import datetime as DT
time = [DT.datetime.fromtimestamp(t/1000) for t in time]
...
p1, = host.plot(time, temp)
p2, = par1.plot(time, hum)
p3, = par2.plot(time, light_lv)

rawDescription: Python Use data/time as x-axis?

description: Python Use data/time as x-axis


code:
for icon in icons:
    PostIcon(post=post, icon=icon).save()

rawDescription: Way to allow for duplicate many-to-many entries in Python/Django


rawDescription: Merging Two Outer Lists Based on Iterated Inner List Value


rawDescription: re.split on multiple characters (and maintaining the characters) produces a list containing also empty strings

description: Re.split on multiple characters (and maintaining the characters) produces a list containing also empty strings


code: ['Hello World!', 'Hello Dennis!']

rawDescription: Filter strings into list depending on position - Python


code:
import numpy as np
from multiprocessing import Pool

def I(index):
    return x[index]

def setup(value):
    global x
    x = value

if __name__ == "__main__":
    x = np.random.random(100)
    y = np.random.random(100)

    pool = Pool(initializer=setup, initargs=(x,))
    y[:] = pool.map(I, range(100))

    print(x == y) # [True, True, True, ...]

rawDescription: Assignment in map method of multiprocessing module (Python)


code:
example=[["hello i am adolf","hi my name is "],["this is a test","i like to play"]]
chars2=[]
for list in example:
    a = []
    chars2.append(a)
    for string in list:
        a.extend(string)
chars2

rawDescription: Get the characters from a list of lists

description: Get the characters from a list of lists


code:
post = Post.objects.get(id=1)
post.blog.title

rawDescription: How do I have two fields for a choice?

description: Have two fields for a choice


rawDescription: Storing an ascii lookup table in a file in Python


code:
def con(x):
    return np.linalg.norm(x) - 1

cons = {'type':'eq', 'fun': con}

rawDescription: I'm having difficulty understanding the syntax of scipy.optimize


rawDescription: Correct xpath syntax with pythons lxml library for parsing all the text from arbitrary nested html tags


code:
m = np.ones(len(a), dtype=bool)
m[i] = False
b = a[m]

rawDescription: delete the first element in subview of a matrix

description: Delete the first element in subview of a matrix


code:
import inspect
ismethod = inspect.getargspec(method).args[0] == 'self'

rawDescription: Decorator changing function status from method to function


code:
{(u'A', u'B'): [{'more_data': u'2',
                 'name': u'EXAMPLE ONE',
                 'some_data': u'1'},
                {'more_data': u'4',
                 'name': u'EXAMPLE TWO',
                 'some_data': u'3'}],
 (u'C', u'D'): [{'more_data': u'2', 'name': u'EXAMPLE', 'some_data': u'1'}]}

rawDescription: Extract and group elements/tags with BeautifulSoup


code:
import bisect
try:
    from math import isclose
except ImportError:
    def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
        # simplified backport, doesn't handle NaN or infinity.
        if a == b: return True
        return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

result = []
for value in a1:
    index = bisect.bisect(a, value)
    if index and isclose(a[index - 1], value):
        result.append(b[index - 1])
    elif index < len(a) and isclose(a[index], value):
        result.append(b[index])

rawDescription: How to compare list in Python?

description: Compare list in Python


rawDescription: Find dependency/execution order of several statements


code:
#    ListView:
#        adapter: root.beer_la

rawDescription: Kivy: Having trouble getting ListView to update when sorting ListAdapter data


code: pymongo_collection_object.remove({'$or': [{'sku': '100-00'}, {'sku': '200-00'}]}, safe=True)

rawDescription: Removing multiple MongoDB documents in Python


code: ts + pd.DateOffset(days=5)

rawDescription: Python Time Series

description: Python Time Series


code: db.update({"_id": acs_num}, {"$set": mydata}, upsert = True)

rawDescription: Pymongo find and modify

description: Pymongo find and modify


code:
othercode='y="led" "zeppelin"'
othercodeio = StringIO(othercode)
othertokens = list(gt(othercodeio.readline))
pp(othertokens)

rawDescription: python, x = """"""; lexed as triple quotes or 3 pairs of quotes

description: Python, x = """"""; lexed as triple quotes or 3 pairs of quotes


code:
import shutil
import os
import string

directory_path = r'C:\Users\myname\da\data\originals\Word_4_0'
for file_name in os.listdir(directory_path):
    new_file_name = ''.join(c for c in file_name if c in string.printable)
    shutil.move(os.path.join(directory_path,file_name),os.path.join(directory_path,new_file_name))

rawDescription: Registered Trademark: Why does strip remove ® but replace can't find it? How do I remove symbols from folder and file names?


code: path

rawDescription: Python class inheritance: dynamic attribute creation


code:
# Mechanize headless
import mechanize
import cookielib
import urllib
# Browser
br = mechanize.Browser()
# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
# Want debugging messages?
#br.set_debug_http(True)
#br.set_debug_redirects(True)
#br.set_debug_responses(True)

rawDescription: Python: Save page's dynamic image

description: Python: Save page's dynamic image


code:
# ------------------ #
# == process_text == #
# ------------------ #

def bundle_dialogue_items(lines):
    cur_speaker = None
    paragraphs = Counter()
    for line in lines:
        if re.match(p, line):
            cur_speaker, dialogue = line.split(':')
            paragraphs[cur_speaker] += 1
        else:
            dialogue = line

        res = cur_speaker, dialogue, paragraphs[cur_speaker]
        yield res

def filter_dialogue_items(lines):
    for name, dialogue, paragraph in lines:
        if dialogue:
            res = name, dialogue, paragraph
            yield res

def clean_dialogue_items(flines):
    for name, dialogue, paragraph in flines:
        s_dialogue = dialogue.strip().split()
        c_dialouge = [clean_word(w) for w in s_dialogue]
        res = name, c_dialouge, paragraph
        yield res

rawDescription: Python: How to sum up the word count for each person in a dialogue?


code:
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
    i = bisect(breakpoints, score)
    return grades[i]

rawDescription: How to change an integer value to a letter python

description: Change an integer value to a letter python


code:
result = None
with open("filename", 'r') as fh:
    result = [json.loads(line) for line in fh]

rawDescription: python: convert list of strings of json type to list of dictionaries

description: Python: convert list of strings of json type to list of dictionaries


code:
import datetime
datetime.datetime.now()

rawDescription: What's the best way to make a time from "Today" or "Yesterday" and a time in Python?


code:
for i, j in zip(*np.where(significant)):
     ax.plot(x[i], y[j], 'bo')

rawDescription: Plotting points on a contourf plot

description: Plotting points on a contourf plot


code: makedir (datetime.date.today().strftime("/myfolder/%d %B, %Y"))

rawDescription: Passing argument to python which is half "<direct string>" and half value of a variable


code: rdd = sc.parallelize([(1, 2)])

rawDescription: How do I order fields of my Row objects in Spark (Python)

description: Order fields of my Row objects in Spark (Python)


code:
for i in range(len(listA)):
    for inst_B in listB:
        if listA[i].id == inst_B.id:
            # almost the same as above, except here we're changing the value
            # of the i-th entry in listA
            listA[i] = inst_B

rawDescription: Python: Updating Class Instances in one List-Variable based on same Class Instances from Another List-Variable


rawDescription: More efficient method for this calculation?


rawDescription: Was asked to make a simple Windchill index table


rawDescription: Subtract a column from one pandas dataframe from another


code:
import numpy as np

fp = open("test.dat", "r")
line = fp.readline()
ndata = int(line.strip())
data = np.fromfile(fp, count=ndata, sep=" ", dtype=int)
fp.close()

rawDescription: Reading large formatted text file with NumPy


code: foo = repo.cfg.get(repo.id, 'foo')

rawDescription: Yum : How to retrieve option value from repositories configuration using python


rawDescription: regex to match or ignore a set of two digit numbers

description: Regex to match or ignore a set of two digit numbers


rawDescription: Sorting Multi-Index to full depth (Pandas)


rawDescription: Replace all occurrences of a string in a pandas dataframe (Python)


code:
import pandas as pd

file_name = r"/tmp/file.txt"

lines_no = int(30e6)

with open(file_name, 'w') as f:
    for i in range(lines_no):
        if i%int(1e5) == 0:
            print("Writing progress: {:0.1f}%"
                    .format(float(i) / float(lines_no)*100), end='\r')
        f.write(" ".join(["{:<10.8f}".format(random()*10) for v in range(6)])+"\n")

print("File created. Now read it using pd.read_fwf ...")

fwidths = [11,11,11,11,11,11]

df = pd.read_fwf(file_name, widths = fwidths,
               names = ['col0', 'col1', 'col2', 'col3', 'col4', 'col5'])

#print(df)

print(df.shape) #<30M

rawDescription: Pandas read_fwf not Loading Entire Content of File


code:
def weekend(day):
    return day in ('Saturday', 'Sunday')

rawDescription: Return a Boolean instead of a string containing True or False in Python


code:
import socket
items = sorted(ipCount.items(), key=lambda item: socket.inet_aton(item[0]))

rawDescription: How to sort IP addresses stored in dictionary in Python?

description: Sort IP addresses stored in dictionary in Python


code:
class MyModel(models.Model):
  field1 = models.CharField(max_length=50)
  field2 = models.CharField(max_length=50)

  class Meta:
    unique_together = ('field1', 'field2',)

rawDescription: How to define two fields "unique" as couple

description: Define two fields "unique" as couple


code:
class Bar(object): pass

b = Bar()
fn.__get__(b, Bar)

rawDescription: Python Method object creation

description: Python Method object creation


rawDescription: Python: more readable list comprehension


code:
def dates(data, dates1):
    r = re.compile("\d+/\d+/\d+")
    dict_days = Counter((dt for dt in r.findall(data) if dt in dates1))
    return dict_days.most_common(5)

rawDescription: Performance - searching a string in a text file - Python


rawDescription: pandas joining multiple dataframes on columns

description: Pandas joining multiple dataframes on columns


code:
...
class WebkitDownloader( object ):
    def process_request( self, request, spider ):
        if not isinstance(request, FormRequest):
            webview = webkit.WebView()
            ...

rawDescription: How to use webkit with scrapy

description: Use webkit with scrapy


code:
import socket

if __name__ == "__main__":
    sock = socket.socket()
    sock.connect(("localhost", 50839))

    with open("data.bin", "rb") as fd:
        buf = fd.read(1024)
        while (buf):
            sock.send(buf)
            buf = fd.read(1024)
    sock.close()

rawDescription: using python to send an image over TCP to c# server

description: Using python to send an image over TCP to c# server


code: func = df.groupby("y").apply(lambda d: "id_%d" % d.name)

rawDescription: pandas: apply a function to each unique element in a dataframe column and merge back the output

description: Pandas: apply a function to each unique element in a dataframe column and merge back the output


rawDescription: Getting Data of a boxplot - Pandas

description: Getting Data of a boxplot - Pandas


code:
class MenuScreen(Screen):
    text = StringProperty('')
    def change_text(self):
        self.text = "The text you want to set"
        self.manager.current = "SettingsScreen"

class SettingsScreen(Screen):
    label_text = StringProperty('')

rawDescription: Kivy - Screen Manager - Accessing attribute in other class


code:
def float_to_int_mod(array):
    mod_array, int_array = np.modf(array)
    if not np.equal(mod_array, 0).all():
        raise TypeError("Cannot safely convert float array to int dtype. "
                        "Array must only contain whole numbers.")
    return int_array.astype(int, casting='unsafe', copy=True)

rawDescription: Convert float64 to int64 using "safe"

description: Convert float64 to int64 using "safe"