code:
import string

LOWERCASE = set(string.ascii_lowercase)

def plus_surrounds(s):
    """Return True if `+` surrounds a single ascii lowercase letter."""
    # initialize to 0 -- The first time through the loop is guaranteed not
    # to find anything, but it will initialize `idx1` and `idx2` for us.
    # We could actually make this more efficient by factoring out
    # the first 2 `find` operations (left as an exercise).
    idx2 = idx1 = 0

    # if the indices are negative, we hit the end of the string.
    while idx2 >= 0 and idx1 >= 0:
        # if they're 2 spaces apart, check the character between them
        # otherwise, keep going.
        if (idx2 - idx1 == 2) and (s[idx1+1] in LOWERCASE):
            return True
        idx1 = s.find('+', idx2)
        idx2 = s.find('+', max(idx1+1, 0))
    return False

assert plus_surrounds('s+s+s')
assert plus_surrounds('+s+')
assert not plus_surrounds('+aa+')

rawDescription: Navigating around a string in python

description: Navigating around a string in python


rawDescription: Python's namespace equivalent for dict.get()


code:
import datetime, pytz

@property
def isNew(self):
    return pytz.utc.localize(datetime.datetime.now())-self.user.date_joined < datetime.timedelta(days=40)

rawDescription: Subtract datetime in Django - no output

description: Subtract datetime in Django - no output


code:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(htmlString)

raw_data = soup.find(**{"class": "quick"}).contents
data = [x for x in raw_data if not hasattr(x, "name") or not x.name == "br"]

rawDescription: Extracting data between </br> tags using beautifulsoup


code:
def copyfileobj(fsrc, fdst, length=16*1024):
    """copy data from file-like object fsrc to file-like object fdst"""
    while 1:
        buf = fsrc.read(length)
        if not buf:
            break
        fdst.write(buf)

rawDescription: Copying files with python

description: Copying files with python


code:
import wx
import wx.grid

class MyGrid(wx.grid.Grid):
    def __init__(self, *args, **kwargs):
        wx.grid.Grid.__init__(self, *args, **kwargs)
        self.CreateGrid(8, 3)

        self.editor = wx.grid.GridCellChoiceEditor(["One", "Two", "Three"])
        self.SetCellEditor(1, 1, self.editor)
        self.SetCellValue(1, 0, "And here.")
        self.SetCellValue(1, 1, "Try here.")

        self.Bind(wx.EVT_KEY_DOWN, self.OnEnter)

    def OnEnter(self, e):
        if e.GetKeyCode() == wx.WXK_RETURN or e.GetKeyCode() == wx.WXK_NUMPAD_ENTER:
            self.EnableCellEditControl()
        else:
            e.Skip()

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.grid = MyGrid(self)
        self.Show()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: Enter key behavior in wx.grid

description: Enter key behavior in wx.grid


code:
myList = [1,2,3,4]

with open('path/to/output', 'w') as outfile:
  outfile.write('\n'.join(str(i) for i in myList))

rawDescription: writing a list to a txt file in python

description: Writing a list to a txt file in python


code:
current_func_ref = None
def func():
    global current_func_ref
    current_func_ref = func

rawDescription: how to get the pointer to the current function in python?

description: Get the pointer to the current function in python


code:
authorList = ['Shakes.','Scott']
already_seen = {} # dict to keep track of what has been seen

with open('/Users/Adam/Desktop/Poetrylist.txt','w') as output_file:
    with open('/Users/Adam/Desktop/2e.txt','r') as open_file:
            the_whole_file = open_file.read()
            for x in authorList:
                start_position = 0
                while True:
                   start_position = the_whole_file.find('<A>'+x+'</A>', start_position)
                   if start_position < 0:
                       break
                   end_position = the_whole_file.find('</W>', start_position)
                   author_data = the_whole_file[start_position:end_position+4]
                   if author_data not in already_seen:
                       output_file.write(author_data + "\n")
                       already_seen[author_data] = True
                   start_position = end_position + 4

rawDescription: Checking for matches in a txt file before writing in Python


rawDescription: How do I handle a multiple select form field in python + webapp2?

description: Handle a multiple select form field in python + webapp2


code:
my_list = ['abcdefg']
len(my_list)

rawDescription: Count number of entries in a list when the list has one entry


rawDescription: How do I combine two lists into a dictionary in Python?

description: Combine two lists into a dictionary in Python


code:
import matplotlib; matplotlib.use('TkAgg')

import matplotlib.pyplot as plt
import matplotlib.backends.backend_tkagg as tkagg

def main():
    fig, ax = plt.subplots()
    text = ax.text(0.5, 0.5, 'TEST', ha='center', va='center', size=25)
    fig.canvas.callbacks.connect('motion_notify_event', OnHover(text))
    plt.show()

class OnHover(object):
    def __init__(self, artist, cursor='hand1'):
        self.artist = artist
        self.cursor = cursor
        self.default_cursor = tkagg.cursord[1]
        self.fig = artist.axes.figure

    def __call__(self, event):
        inside, _ = self.artist.contains(event)
        if inside:
            tkagg.cursord[1] = self.cursor
        else:
            tkagg.cursord[1] = self.default_cursor
        self.fig.canvas.toolbar.set_cursor(1)

main()

rawDescription: Set hand cursor for picking matplotlib text


code:
from copy import deepcopy

abPositions = [[1, 'a.png', [9, 9, 9, 9]], [1, 'b.png', [9, 9, 9, 9]]]
abPositionsRotated = deepcopy(abPositions)

# Now any operation on abPositionsRotated will only apply to it

rawDescription: copying a nested list, then updating values in only the new list

description: Copying a nested list, then updating values in only the new list


code:
from pandas import Series, date_range
import numpy as np

# Generate some synthetic price data
ts = pd.Series(np.random.randn(1000), index=date_range('1/1/2000', periods=1000))
ts = ts.cumsum() + 100
ts.plot()

# Define a function to calculate percent change over an x-day period
rollingChange = lambda x: 100*(x[-1]-x[0])/x[0]

# Use rolling_apply to calculate 7 and 30 day rolling prcnt_change
week = pd.rolling_apply(ts, 7, rollingChange)
month = pd.rolling_apply(ts, 30, rollingChange)

rawDescription: Python dynamic datetime periods

description: Python dynamic datetime periods


rawDescription: Python Pandas Cleaning columns with multiple dates


code:
import os
with open('lines.txt') as f:
    lines = f.readlines()

lines.insert(lines.index('exactarch=1\n') + 1, 'obsoletes=1\n')
with open('dst.txt', 'w') as f:
    for l in lines:
        f.write(l)

rawDescription: Add lines to text file after occurence of certain text


code:
def parse(self, response):
   hxs = HtmlXPathSelector(response)
   for tb in hxs.xpath('//table'):

       heading = tb.xpath('.//thead/tr/th/a/text()').extract()[0]

       for td in tb.xpath('.//tbody/tr'):
          il = WebsiteLoader(response=response, selector=td)
          ...
          il.add_value('heading', heading)
          yield il.load_item()

rawDescription: Scrapy - Adding a table header (thead) value to Item Loader


code: df['count'] = df.apply(lambda x: 1 if x.category in x.category_pred else 0, axis = 1)

rawDescription: For every row in Pandas dataframe determine if a column value exists in another column


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

import MySQLdb
import feedparser

db = MySQLdb.connect(host="127.0.0.1",
                     user="root",
                      passwd="",
                      db="FeedStuff",
                     charset='UTF8')

urllistnzz =['international', 'wirtschaft', 'sport']
urllistbernerz =['kultur', 'wissen', 'leben']

cur = db.cursor()

for uri in urllistbernerz:
    urlbernerz = feedparser.parse('http://www.bernerzeitung.ch/{uri}/rss.html'.format(uri=uri))

    for entry in urlbernerz.entries:
        insert_sql = u"""INSERT INTO articles (title, description, date, category,
                        link, source) VALUES ("{e.title}", "{e.description}",
                        "{e.published}", "{e.category}", "{e.link}", "Berner Zeitung")
                        """.format(e=entry)

        cur.execute(insert_sql)

for uri in urllistnzz:
    urlnzz = feedparser.parse('http://www.nzz.ch/{uri}.rss'.format(uri=uri) )

    for entry in urlnzz.entries:
        insert_sql = u"""INSERT INTO articles (title, description, date, category,
                        link, source) VALUES ("{e.title}", "{e.description}",
                        "{e.published}", "{e.category}", "{e.link}", "NZZ")
                        """.format(e=entry)

        cur.execute(insert_sql)

db.commit()

cur.close()
db.close()

rawDescription: UnicodeEncodeError when trying to insert UTF-8 data into Mysql


code:
recent_media, next_ = api.user_recent_media()
photos = []
for media in recent_media:
    photos.append('<img src="%s"/>' % media.images['thumbnail'].url)

rawDescription: Get media with Instagram Python API

description: Get media with Instagram Python API


code:
def word_func(word, letter):
    return word.replace(letter, '')

word_func('bird', 'b')

rawDescription: Remove known character

description: Remove known character


code:
re.split(r'\s+', string)
['A', '(small,', 'simple)', 'example']

rawDescription: Implement a tokeniser in Python

description: Implement a tokeniser in Python


code:
import dateutil.relativedelta as rd
import datetime

last_monday = datetime.date.today() + rd.relativedelta(weekday=rd.MO(-1))

rawDescription: Python Date Utility Library

description: Python Date Utility Library


rawDescription: how to get the sum of a series of decimel numbers strings?

description: Get the sum of a series of decimel numbers strings


code:
single_lines = []
current = []

for i in lines:
    i = i.strip()
    if i:
        current.append(i)
    else:
        if not current:
            continue  # treat multiple blank lines as one
        single_lines.append(' '.join(current))
        current = []
else:
    if current:
        # collect the last line if the file doesn't end with a blank line
        single_lines.append(' '.join(current))

rawDescription: Concatenate lines together if they are not emty in a file


code:
import urllib2
from multiprocessing.dummy import Pool # use threads

def fetch(url):
    try:
        return url, urllib2.urlopen(url).read(), None
    except Exception as e:
        return url, None, str(e)

urls = ['http://example.com', ...]
pool = Pool(20) # use no more than 20 concurrent connections
for url, result, error in pool.imap_unordered(fetch, urls):
    if error is None:
       print(url + " done")
    else:
       print(url + " error: " + error)

rawDescription: Python - how can i make the client to be able to connect multiple times?


code:
self.buttonList= [self.answerBtn, self.wrong1Btn,
                  self.wrong2Btn, self.wrong3Btn]

rawDescription: Shuffling list of widgets? Tkinter

description: Shuffling list of widgets? Tkinter


code:
#!/usr/bin/env python

from string import printable
from curses import erasechar, wrapper

PRINTABLE = map(ord, printable)

def input(stdscr):
    ERASE = input.ERASE = getattr(input, "ERASE", ord(erasechar()))
    Y, X = stdscr.getyx()
    s = []

    while True:
        c = stdscr.getch()

        if c in (13, 10):
            break
        elif c == ERASE:
            y, x = stdscr.getyx()
            if x > X:
                del s[-1]
                stdscr.move(y, (x - 1))
                stdscr.clrtoeol()
                stdscr.refresh()
        elif c in PRINTABLE:
            s.append(chr(c))
            stdscr.addch(c)

    return "".join(s)

def prompt(stdscr, y, x, prompt=">>> "):
    stdscr.move(y, x)
    stdscr.clrtoeol()
    stdscr.addstr(y, x, prompt)
    return input(stdscr)

def main(stdscr):
    Y, X = stdscr.getmaxyx()

    lines = []
    max_lines = (Y - 3)

    stdscr.clear()

    while True:
        s = prompt(stdscr, (Y - 1), 0)  # noqa
        if s == ":q":
            break

        # scroll
        if len(lines) > max_lines:
            lines = lines[1:]
            stdscr.clear()
            for i, line in enumerate(lines):
                stdscr.addstr(i, 0, line)

        stdscr.addstr(len(lines), 0, s)
        lines.append(s)

        stdscr.refresh()

wrapper(main)

rawDescription: Keep stdin line at top or bottom of terminal screen


code:
i = PythonMagick.Image(img)
i.sample('!<width>x<height>')

rawDescription: resize image with PythonMagick

description: Resize image with PythonMagick


code:
selectList = [sktTCP,sys.stdin]
(read, write, exc) =  select.select(selectList, [], [], 0 )

rawDescription: Read from keyboard non blocking mode because of sockets working, python


rawDescription: Regular expression matches both numbers and units


code:
import imghdr
imghdr.what('', byteStream)

rawDescription: Determine image in memory

description: Determine image in memory


code:
rar = rarfile.RarFile(source_filename)
if rar.needs_password():
    rar.setpassword('') # whatever the password is

# Rest of code here

rawDescription: How get percentage of password protected rar file extraction in python?


code:
def define_styles(root):
    default = tkFont.Font(root=root, name="TkTextFont", exists=True)

    large = default.copy()
    large.config(size=36)

    style = Style(root)
    style.configure("Large.TLabel", font=large)
    root.myfont = large

rawDescription: Why can't I define (and save) Tkinter fonts inside a function?


code:
from PIL import Image
img=Image.open("file.png")
size=list(img.size)
size[0] /= 2
size[1] /= 2
downsized=img.resize(size, Image.NEAREST) # NEAREST drops the lines
downsized.save("file_small.png")

rawDescription: How do I deinterlace an image in Python?

description: Deinterlace an image in Python


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

from threading import Thread
from functools import wraps
from time import sleep

try:
    import queue as Queue
except ImportError:
    import Queue as Queue

def run_async(func):
    @wraps(func)
    def async_func(*args, **kwargs):
        queue = Queue.Queue()
        t = Thread(target=func, args=(queue,) + args, kwargs=kwargs)
        t.start()
        return queue, t

    return async_func

@run_async
def do_something_else(queue):
    while True:
        sleep(1)
        print("doing something else")
        # check if something in the queue and return if so
        try:
            queue.get(False)
        except Queue.Empty:
            pass
        else:
            print("Told to quit")
            return

@run_async
def print_somedata(queue):
    print('starting print_somedata')
    sleep(2)
    try:
        queue.get(False)
    except Queue.Empty:
        pass
    else:
        print("Told to quit")
        return

    print('print_somedata: 2 sec passed')
    sleep(2)
    try:
        queue.get(False)
    except Queue.Empty:
        pass
    else:
        print("Told to quit")
        return

    print('print_somedata: another 2 sec passed')
    sleep(2)
    try:
        queue.get(False)
    except Queue.Empty:
        pass
    else:
        print("Told to quit")
        return

    print('finished print_somedata')

def test():
    threads = list()

    # at this moment the thread is created and starts immediately
    threads.append(print_somedata())
    print('back in main')

    # at this moment the thread is created and starts immediately
    threads.append(print_somedata())
    print('back in main')

    # at this moment the hread is created and starts immediately
    threads.append(do_something_else())
    print('back in main')

    # at this moment the hread is created and starts immediately
    threads.append(do_something_else())
    print('back in main')

    print("Wait a bit in the main")
    sleep(1)  # uncomment the wait here to stop the threads very fast ;)

    # you don't have to wait explicitly, as the threads are already
    # running. This is just an example to show how to interact with
    # the threads
    for queue, t in threads:
        print("Tell thread to stop: %s", t)
        queue.put('stop')
        #t.join()

if __name__ == '__main__':
    test()

rawDescription: decorator for extra thread

description: Decorator for extra thread


code:
import os, shutil

dir1 = r'/path/to/dir/1'
dir2 = r'/path/to/dir/2'
copy_dest = r'/path/to/copy/dirs/to'

dir1_folders = [dir for dir in os.listdir(dir1) if os.path.isdir(os.path.join(dir1, dir))]
dir2_folders = [dir for dir in os.listdir(dir2) if os.path.isdir(os.path.join(dir2, dir))]

for dir in dir1_folders:
    if dir in dir2_folders:
        shutil.copytree(os.path.join(dir1, dir), os.path.join(copy_dest, dir))

rawDescription: find match folders then copy files and subfolders

description: Find match folders then copy files and subfolders


code:
from django.contrib.auth.models import User

User._meta.get_field('username')._unique = False

rawDescription: Django - Allow duplicate usernames

description: Django - Allow duplicate usernames


code:
3>> 'ﻴ ﻲ ﯾ'.translate({0xfbfe: 'a', 0xfef2: 'a', 0xfef4: 'a'})
'a a a'

rawDescription: Replacing a list of utf8 characters in Python


code:
class Hop(SQLObject):
    BITTERING = 0
    AROMA = 1
    BOTH = 2
    LEAF = 0
    PELLET = 1
    PLUG = 2
    hop_types = ['Bittering', 'Aroma', 'Both',]
    hop_forms = ['Leaf', 'Pellet', 'Plug',]

    hop_type = IntCol(default=BITTERING)
    hop_form = IntCol(default=LEAF)
    alpha = PercentCol(default=0.0)
    beta = PercentCol(default=0.0)
    stability = PercentCol(default=0.0)
    origin = UnicodeCol(default=None)
    name = UnicodeCol(length=64, default=None)
    description = UnicodeCol(default=None)
    substitutes = RelatedJoin('Hop',
                              joinColumn='master_hop',
                              otherColumn='substitute_hop',
                              addRemoveName="Substitute",
                              intermediateTable="substitute_hops",
                              createRelatedTable=True)
    versions = Versioning()

rawDescription: ManyToMany relationships on the same table in SQLObject


code:
from django.forms import ModelForm
from django import forms as forms

class Method1ClusteringForm(ModelForm):
    clustering_method_param = forms.forms.TypedChoiceField(
                    required=True,
                    initial = 'ward',
                    choices = (
                        ('complete', 'Complete linkage'),
                        ('average','Average linkage'),
                        ('ward','Ward'),)
                    )
    class Meta:
        model = Method1
        fields = ('inputfile_param', 'clustering_method_param',)

rawDescription: Django: CharField remove default ------— choice


code: current_locale = QtCore.QLocale()

rawDescription: How to find current QLocale in Qt/PyQt/PySide?

description: Find current QLocale in Qt/PyQt/PySide


code:
N = len(allspec)
numspec = [0] * N
for i in xrange(N):
    for x_rel in xrange(-1, +1):
        for y_rel in xrange(-1, +1):
            x_idx = (x + xrel) % N
            y_idx = (y + yrel) % N
            if x_idx != x or y_idx != y:
                numspec[hab[x_idx][y_idx]] += 1

rawDescription: How to wrap around to the start/end of a list in python?

description: Wrap around to the start/end of a list in python


code: string1.replace("val2", str(val2))

rawDescription: replace a substring with a non-string value in python

description: Replace a substring with a non-string value in python


code:
results = []

for home in homes:
    home_coords = [home.latitude, home.longtitude]

    distance = distance_miles(current_location_coordinates, home_coords)
    if distance <= distance_from:
        results.append((distance,home))

results.sort(key=lambda item:item[0])

rawDescription: Django / Python - return a sorted list from generated values each assigned to an object


code:
import urllib.request
from urllib.parse import quote

url='https://www.bing.com/search?q=%s&qs=n&form=QBLH&pq=%s&sc=2-0&sp=-1&sk=&cvid=8F0865226C'%(quote('你好'),quote('你好'))
urllib.request.urlopen(url)

rawDescription: When I use Chinese as URL parameter，it doesn't work with python


rawDescription: Python Dictionary Sorting Using Sorted

description: Python Dictionary Sorting Using Sorted


code:
class PythonTest(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Python!")
        #self.style = Style()
        #self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)
        self.canw = 300
        self.canh = 400

        self.paper = Canvas(self, width=self.canw, height=self.canh)
        self.paper.pack()

        self.rec1c = 'red'
        self.rec1o = 'red'
        self.rec1 = self.paper.create_rectangle(0, 0, 300, 300, fill=self.rec1c, outline=self.rec1o)

        self.translate = Button(self, text="Translate to Pig Latin", command=self.toB)
        self.translate.place(x=50, y=50)

    def toB(self):
        print(self.rec1c)
        self.rec1c = 'blue'
        print(self.rec1c)
        self.paper.itemconfig(self.rec1, fill=self.rec1c)

rawDescription: Python Tkinter Confusion

description: Python Tkinter Confusion


code:
class SubProcessWithoutThread(object):
    def __init__(self, arguments, currentWorkingDirectory):
        self.arguments = arguments
        self.currentWorkingDirectory = currentWorkingDirectory
        self.isTerminated = False

    def start(self):
        self.subProcess = subprocess.Popen(self.arguments, cwd=self.currentWorkingDirectory)

    def kill(self):
        while self.subProcess.poll() is None:
            try:
                self.subProcess.kill()
            except:
                time.sleep(0.1)

    __enter__ = start
    def __exit__(self, *x):
        self.kill()

rawDescription: Sub Process in its own Thread

description: Sub Process in its own Thread


code:
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write('
OK
')
    def log_message(self, format, *args):
        return

httpd = HTTPServer(('', 8001), MyHandler)
httpd.serve_forever()

rawDescription: How to silent/quiet HTTPServer and BasicHTTPRequestHandler's stderr output?

description: Silent/quiet HTTPServer and BasicHTTPRequestHandler's stderr output


code:
opening = open('filename.txt') # "w" is not necessary since you're opening it read-only
a = [b.split() for b in opening.readlines()] # create a list of each line and strip the newline "\n" character

print(a[0]) # print first line
print(a[1]) # print second line

rawDescription: How to assign a single variable to a specific line in python?

description: Assign a single variable to a specific line in python


code:
import locale
import threading

from datetime import datetime
from contextlib import contextmanager

LOCALE_LOCK = threading.Lock()

@contextmanager
def setlocale(name):
    with LOCALE_LOCK:
        saved = locale.setlocale(locale.LC_ALL)
        try:
            yield locale.setlocale(locale.LC_ALL, name)
        finally:
            locale.setlocale(locale.LC_ALL, saved)

# Let's set a non-US locale
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')

# Example to write a formatted English date
with setlocale('C'):
    print(datetime.now().strftime('%a, %b')) # e.g. => "Thu, Jun"

# Example to read a formatted English date
with setlocale('C'):
    mydate = datetime.strptime('Thu, Jun', '%a, %b')

rawDescription: How do I strftime a date object in a different locale?

description: Strftime a date object in a different locale


code:
db.eval(Code("function () {"
             "coll.find({}, {field1: 1, field2: 2})"
             ".forEach( function(doc) {"
             "    doc.field1 += doc.field2;"
             "    coll.save(doc);"
             "    });"
             "}"))

rawDescription: pymongo: updating a field using another field

description: Pymongo: updating a field using another field


code:
def filter_data_items(bundle):
    res = DataResource()
    new_bundle = Bundle(request=bundle.request)
    objs = res.obj_get_list(new_bundle)
    return objs.filter(parent_id=bundle.obj.pk)

rawDescription: Django Tastypie - Filtering ToManyField resource with URL parameter


code:
import subprocess

class mysubprocess():

    def execute(self, directory_list):
        procs = []
        for d in directory:
            print(d)
            procs.append(subprocess.Popen('ls', cwd=d))  # <---
        for proc in procs:
            proc.wait()

def main():
    myobject = mysubprocess()
    myobject.execute(['/home/suresh/Documents','/home/suresh/Downloads'])

if __name__ == '__main__':
    main()

rawDescription: Wait all subprocess to complete in python


code: a = [x for x in a if x != 43]

rawDescription: Removing every occurrence of some value from a Python list?


code:
for i, word in enumerate(z):
    if "-" not in word:
        if word in d.keys():
            z[i] = str(d[word])
        else:
            count = count + 1
            d[word] = count
            z[i] = str(count)

rawDescription: python : replace words in string

description: Python : replace words in string


code:
def isOnTrack(track,car):
    #one corner; a is alpha, the transparency
    #If a is 0 that means completely transparent
    if track.get_at(car.x,car.y).a==0:
        return false

    #do this for all four corners of car

    return true

rawDescription: Testing for image collision Pygame

description: Testing for image collision Pygame


code:
class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter):
    pass

parser = argparse.ArgumentParser(description='test\ntest\ntest.',
                                 epilog='test\ntest\ntest.',
                                 formatter_class=CustomFormatter)

rawDescription: ArgumentParser epilog and description formatting in conjunction with ArgumentDefaultsHelpFormatter


rawDescription: How to extract money value from "grossing" string in IMDbPY

description: Extract money value from "grossing" string in IMDbPY


code: "".join(code.get(k, k) for k in str)

rawDescription: How do I replace characters in a string in Python?

description: Replace characters in a string in Python


code:
with open('test.csv', 'rb') as csv_file:
    r = requests.post(url, data=csv_file, headers={'Content-Type': 'text/plain'}, auth=('user', 'password'))

rawDescription: Is Python's Requests module adding data to a file that it is posting?


rawDescription: Scraping hidden content from a javascript webpage with python


code:
import psutil
psutil.cpu_percent()

rawDescription: Python - how to check system load?

description: Python - how to check system load


code:
from user import User
from unittest.mock import patch

with patch('user.Account') as MockAccount:
    MockAccount.return_value.discount_id = 1
    u = User(1)
    print(u.has_discount)
    # True

with patch('user.Account') as MockAccount:
    MockAccount.return_value.discount_id = 0
    u = User(1)
    print(u.has_discount)
    # False

rawDescription: How to mock a property inside a class in Python

description: Mock a property inside a class in Python


code:
import subprocess
subprocess.call('dpkg -l', shell=True)

rawDescription: List all installed packages in Ubuntu using python


code:
if mask is True and mdtype == MaskType:
    mask = np.ones(_data.shape, dtype=mdtype)
elif mask is False and mdtype == MaskType:
    mask = np.zeros(_data.shape, dtype=mdtype)

rawDescription: Why is creating a masked numpy array so slow with mask=None or mask=0


code: ' %s ' % 'Need some help around here'

rawDescription: Opposite of trim in python

description: Opposite of trim in python


code:
for (j,i),label in np.ndenumerate(grid):
    ax1.text(i,j,label,ha='center',va='center')
    ax2.text(i,j,label,ha='center',va='center')

rawDescription: Matplotlib : display array values with imshow


code:
with self.connection as cursor:
    cursor.execute(open("schema.sql", "r").read())

rawDescription: Execute .sql schema in psycopg2 in Python


code:
# get uids of unseen messages
result, uids = conn.uid('search', None, '(UNSEEN)')

# convert these uids to a comma separated list
fetch_ids = ','.join(uids[0].split())

# first fetch the headers, this will mark them read (SEEN)
status, headers = conn.uid('fetch', fetch_ids, '(RFC822.HEADER)')

# now mark each message unread (UNSEEN)
status1, flags = conn.uid('store', fetch_ids,'-FLAGS','\\Seen')

rawDescription: imaplib/gmail how to download full message (all parts) while not marking read

description: Imaplib/gmail how to download full message (all parts) while not marking read


code:
import re

keyPat = re.compile(r'key (\w+) key')
valuePat = re.compile(r'value (\d+)')

result = {}
for line in open('data.txt'):
    if keyPat.search(line):
        match = keyPat.search(line).group(1)
        tempL = []
        result[match] = tempL
    elif valuePat.search(line):
        match = valuePat.search(line).group(1)
        tempL.append(int(match))
    else:
        print('Did not match:', line)

print(result)

rawDescription: python regex to construct a structured data structure

description: Python regex to construct a structured data structure


code:
import numpy as np

import mpl_toolkits.axisartist.floating_axes as floating_axes
from matplotlib.projections import PolarAxes
from mpl_toolkits.axisartist.grid_finder import FixedLocator, MaxNLocator, \
             DictFormatter
import matplotlib.pyplot as plt

tr = PolarAxes.PolarTransform()

degree_ticks = lambda d: (d*np.pi/180, "%d$^\\circ$"%(360-d))
angle_ticks = map(degree_ticks, np.linspace(180, 360, 5))
grid_locator1 = FixedLocator([v for v, s in angle_ticks])
tick_formatter1 = DictFormatter(dict(angle_ticks))
tick_formatter2 = DictFormatter(dict(zip(np.linspace(1000, 6000, 6),
                                         map(str, np.linspace(0, 5000, 6)))))

grid_locator2 = MaxNLocator(5)

gh = floating_axes.GridHelperCurveLinear(tr,
                                         extremes=(2*np.pi, np.pi, 1000, 6000),
                                         grid_locator1=grid_locator1,
                                         grid_locator2=grid_locator2,
                                         tick_formatter1=tick_formatter1,
                                         tick_formatter2=tick_formatter2)

fig = plt.figure()
ax = floating_axes.FloatingSubplot(fig, 111, grid_helper=gh)
fig.add_subplot(ax)

azimuths = np.radians(np.linspace(180, 360, 90)) # added 180 degrees
zeniths = np.arange(1050, 6050, 50) # added 1000

r, theta = np.meshgrid(zeniths, azimuths)
values = 90.0+5.0*np.random.random((len(azimuths), len(zeniths)))

aux_ax = ax.get_aux_axes(tr)
aux_ax.patch = ax.patch
ax.patch.zorder = 0.9

aux_ax.contourf(theta, r, values) # use aux_ax instead of ax

plt.show()

rawDescription: How to format a polar contour plot in matplotlib

description: Format a polar contour plot in matplotlib


code:
from itertools import chain
from genshi.core import DOCTYPE, Stream
from genshi.output import DocType
from genshi.builder import tag as t

# Build the page using `genshi.builder.tag`
page = t.html (t.head (t.title ("Hello world!")), t.body (t.div ("Body text")))

# Convert the page element into a stream
stream = page.generate ()

# Chain the page stream with a stream containing only an HTML4 doctype declaration
stream = Stream (chain ([(DOCTYPE, DocType.get ('html4'), None)], stream))

# Convert the stream to text using the "html" renderer (could also be xml, xhtml, text, etc)
text = stream.render ('html')

rawDescription: How do I use genshi.builder to programmatically build an HTML document?

description: Use genshi.builder to programmatically build an HTML document


code: from future_builtins import filter, map, zip

rawDescription: Python iterable map, range, etc

description: Python iterable map, range, etc


code:
x = None
lis = []
while x != '':
    x = input('Enter a number: ')
    if x != '':
        lis.append(int(x))
avg = sum(lis) / len(lis)
print(avg)

rawDescription: How to keep repeating a program until a specific input?

description: Keep repeating a program until a specific input


code: {k: (lst[0], float(v)/lst[0]) for k, v in lst[1].items()}

rawDescription: Multiply a dictionary value by other in a nested dictionary


code:
from django.contrib.auth.models import User

class Student(User):

     ...

class Mentor(User):

     ...

rawDescription: Django custom user models in 1.8

description: Django custom user models in 1.8


code: df = pd.read_sql('SELECT * FROM table_name', con=db_connection)

rawDescription: Importing data from a MySQL database into a Pandas data frame including column names


code: O(nlogn) + O(k)

rawDescription: How to find all ordered pairs of elements in array of integers whose sum lies in a given range of value

description: Find all ordered pairs of elements in array of integers whose sum lies in a given range of value


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

x = ['One', 'Two', 'Three', 'Four', 'Five']
y = [2, 3, -5, 4.5, 4]

sns.axes_style('white')
sns.set_style('white')

colors = ['pink' if _y >=0 else 'red' for _y in y]
ax = sns.barplot(x, y, palette=colors)

for n, (label, _y) in enumerate(zip(x, y)):
    ax.annotate(
        s='{:.1f}'.format(abs(_y)),
        xy=(n, _y),
        ha='center',va='center',
        xytext=(0,10),
        textcoords='offset points',
        color=color,
        weight='bold'
    )

    ax.annotate(
        s=label,
        xy=(n, 0),
        ha='center',va='center',
        xytext=(0,10),
        textcoords='offset points',
    )
# axes formatting
ax.set_yticks([])
ax.set_xticks([])
sns.despine(ax=ax, bottom=True, left=True)

rawDescription: Bar chart in seaborn

description: Bar chart in seaborn


code:
In: autoIt = win32com.client.Dispatch("AutoItX3.Control")
In: autoIt.AutoItSetOption("WinTitleMatchMode", 4)
In: mainWindowTitle = "Untitled"
In: mainWindowHandle = autoIt.WinGetHandle(mainWindowTitle)
In: mainWindowHandle
Out: u'000204AC'
In: testHandle = "[HANDLE:%s]" % mainWindowHandle
In: autoIt.WinGetTitle(testHandle)
Out: u'Untitled - Notepad'

rawDescription: Getting Python and AutoIT to work together using win32com: what's up with those window handles?


code:
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.add_patch(
    patches.Rectangle(
        (0.1, 0.1),   # (x,y)
        0.5,          # width
        0.5,          # height
    )
)
fig1.savefig('rect1.png', dpi=90, bbox_inches='tight')

rawDescription: creating a chart with high/low and percentile box plus other points

description: Creating a chart with high/low and percentile box plus other points


code:
from pyslibtesseract import TesseractConfig, PageSegMode
config_line = TesseractConfig(psm=PageSegMode.PSM_SINGLE_LINE)
config_line.add_variable('tessedit_char_whitelist', '0123456789.')

rawDescription: Numerical character recognition in Pytesser


code:
from datetime import datetime
import pytz
from tzlocal import get_localzone # $ pip install tzlocal

utc_dt = datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=pytz.utc)
print(utc_dt.astimezone(get_localzone())) # print local time
# -> 2009-07-10 14:44:59.193982-04:00

rawDescription: Python: simply print datetime.now() including correct timezone


code:
compile('o[x]', '<string>', 'exec', PyCF_ONLY_AST).body[0].value.slice
compile('o[x,y]', '<string>', 'exec', PyCF_ONLY_AST).body[0].value.slice
compile('o[x:y]', '<string>', 'exec', PyCF_ONLY_AST).body[0].value.slice
compile('o[x:y,z]', '<string>', 'exec', PyCF_ONLY_AST).body[0].value.slice

rawDescription: What syntax is represented by an ExtSlice node in Python's AST?


rawDescription: Log a string without ending newline

description: Log a string without ending newline


code: raw_input("Press Enter to terminate.")

rawDescription: how to pause a program until a button is pressed

description: Pause a program until a button is pressed


code:
def parse_tweet(in_t):
    t = {}
    t["_id"] = get_me_an_int32_id
    t["text"] = in_t["text"]
    t["shape"] = in_t["coordinates"]["coordinates"][0], in_t["coordinates"]["coordinates"][1]
    return t

rawDescription: How to set _id to be 32bit Integer?

description: Set _id to be 32bit Integer


rawDescription: Python greater than or less than

description: Python greater than or less than


code:
...
button = Button(end, text="Close", command=self.close)
...
def close(self):
    self._canvas.destroy()
    self._canvas2.destroy()

rawDescription: Closing a Game(object) from tkinter popup


rawDescription: progress bar within a table in pyqt4

description: Progress bar within a table in pyqt4


code:
import IPython

def some_complex_fn():
    x = 42
    IPython.embed()

some_complex_fn()

rawDescription: interactive use of python console inside function scope without debugging mode

description: Interactive use of python console inside function scope without debugging mode


code:
gc.collect()
oldcounts = gc.get_counts()
del last_reference_to_list
gc.collect()
newcounts = gc.get_counts()
print(oldcounts, newcounts)

rawDescription: Will python automatically garbage collect doubly-linked list?


code: int_field = forms.TypedChoiceField(choices=SOME_CHOICES, coerce=int)

rawDescription: Coerce in django forms

description: Coerce in django forms


code:
#!/usr/bin/env python
from PyPDF2 import PdfFileWriter, PdfFileReader
output = PdfFileWriter()
input1 = PdfFileReader(open('introduction.pdf', 'rb'))
output.addPage(input1.getPage(0))
input2 = PdfFileReader(open('hello.pdf', 'rb'))
output.addPage(input2.getPage(0))

parent = output.addBookmark('Introduction', 0) # add parent bookmark
output.addBookmark('Hello, World', 0, parent) # add child bookmark

rawDescription: Adding bookmarks using PyPDF2

description: Adding bookmarks using PyPDF2


code:
from Tkinter import *
root=Tk()
root.focus_force()
Label(root,text="foo").pack()
root.mainloop()

rawDescription: set focus to Tkinter window in Python (and OS X)

description: Set focus to Tkinter window in Python (and OS X)


code:
import datetime
today = datetime.date.today()
margin = datetime.timedelta(days = 3)
today - margin <= datetime.date(2011, 1, 15) <= today + margin

rawDescription: Checking date against date range in Python


code:
tree = etree.parse(open('./test.xml'))
reviews = tree.findall(".//Review")

rawDescription: Get all nodes of particular name in lxml?


code:
aws_access_key_id = XXXX
aws_secret_access_key = YYYY

rawDescription: How to change environment variables in mrjob for AWS accesskey and secretaccesskey

description: Change environment variables in mrjob for AWS accesskey and secretaccesskey


code:
activate_this = 'A/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))

rawDescription: Staying in the same Shell session with Python


code:
import Tkinter
import sys

class MenuBar(Tkinter.Menu):
    def __init__(self, parent):
        Tkinter.Menu.__init__(self, parent)

        fileMenu = Tkinter.Menu(self, tearoff=False)
        self.add_cascade(label="File",underline=0, menu=fileMenu)
        fileMenu.add_command(label="Exit", underline=1, command=self.quit)

    def quit(self):
        sys.exit(0)

class App(Tkinter.Tk):
    def __init__(self):
        Tkinter.Tk.__init__(self)
        menubar = MenuBar(self)
        self.config(menu=menubar)

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

rawDescription: Class menu in Tkinter Gui

description: Class menu in Tkinter Gui


rawDescription: Pandas Datetime: Calculate Number of Weeks Between Dates in Two Columns


code:
def foo(a=None):
    if a is None:
        a = 10
        # no value for a provided

rawDescription: Is there any way to know if the value of an argument is the default vs. user-specified?


code:
averages = {}    # Create a new empty dictionary to hold the averages
for key, values in scores.items():
  averages[key] = float(sum([int(i) for i in values])) / len(values)
  # Rather than store the averages in a local variable, store them in under the appropriate key in your new dictionary.

rawDescription: Storing averages of values in a dictionary in a separate dictionary - Python


code:
def __on_key_down(self, keyboard, keycode, text, modifiers):
    self.__set_status('Loading, please wait...')
    proxy = Loader.image('http://pl.python.org/forum/Smileys/default/cheesy.gif')
    proxy.bind(on_load=self.__image_loaded)

def __image_loaded(self, proxy):
    if proxy.image.texture:
        self.__img.texture = proxy.image.texture
        self.__set_status('Done')

rawDescription: How to immediately update widget in Kivy?

description: Immediately update widget in Kivy


code:
from paypal import PayPalInterface
paypal_api = PayPalInterface(API_USERNAME="xxx_xxx_apix.xxx.com",
                             API_PASSWORD="xxxxxxxxxx",
                             API_SIGNATURE="xxxxxxxxxxxxxxxxxxxxxxxx",
                             DEBUG_LEVEL=0,
                             HTTP_TIMEOUT=30)

transactions = paypal_api._call('TransactionSearch',
                                STARTDATE='2014-01-01T00:00:00Z',
                                STATUS="Success")

rawDescription: Retrieving all Payment info from PayPal App


code:
import Tkinter

class simpleapp_tk(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()

        self.entryVariable = Tkinter.StringVar()
        self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)
        self.entry.grid(column=0,row=0,sticky='EW')
        self.entry.bind("<Return>", self.OnPressEnter)
        self.entryVariable.set(u"Enter text here.")

        button = Tkinter.Button(self,text=u"Click me !",
                                command=self.OnButtonClick)
        button.grid(column=1,row=0)

        self.labelVariable = Tkinter.StringVar()
        label = Tkinter.Label(self,textvariable=self.labelVariable,
                              anchor="w",fg="white",bg="blue")
        label.grid(column=0,row=1,columnspan=2,sticky='EW')
        self.labelVariable.set(u"Hello !")

        self.grid_columnconfigure(0,weight=1)
        self.resizable(True,False)
        self.update()
        self.geometry(self.geometry())
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)

    def OnButtonClick(self):
        self.labelVariable.set( self.entryVariable.get()+" (You clicked the button)" )
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)

    def OnPressEnter(self,event):
        self.labelVariable.set( self.entryVariable.get()+" (You pressed ENTER)" )
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)

if __name__ == "__main__":
    app = simpleapp_tk(None)
    app.title('my application')
    app.mainloop()

rawDescription: How to create a UI in Python

description: Create a UI in Python


code:
class MockLoggingHandler(logging.Handler):
    """Mock logging handler to check for expected logs."""

    def __init__(self, *args, **kwargs):
        self.reset()
        logging.Handler.__init__(self, *args, **kwargs)

    def emit(self, record):
        self.messages[record.levelname.lower()].append(record.getMessage())

    def reset(self):
        self.messages = {
            'debug': [],
            'info': [],
            'warning': [],
            'error': [],
            'critical': [],
        }

rawDescription: How should I verify a log message when testing Python code under nose?


code:
list_of_pixels = list(im.getdata())
# Do something to the pixels...
im2 = Image.new(im.mode, im.size)
im2.putdata(list_of_pixels)

rawDescription: How do I create an image in PIL using a list of RGB tuples?

description: Create an image in PIL using a list of RGB tuples


code:
filter = ""
parameters = []
if ...:
    filter += " AND xxx = ?"
    parameters += [x]
if ...:
    filter += " AND yyy = ?"
    parameters += [y]

rawDescription: SQLite python how to add multiple filters in SELECT


code:
def generate_lattice(image_shape, lattice_vectors) :
    center_pix = numpy.array(image_shape) // 2
    # Get the lower limit on the cell size.
    dx_cell = max(abs(lattice_vectors[0][0]), abs(lattice_vectors[1][0]))
    dy_cell = max(abs(lattice_vectors[0][1]), abs(lattice_vectors[1][1]))
    # Get an over estimate of how many cells across and up.
    nx = image_shape[0]//dx_cell
    ny = image_shape[1]//dy_cell
    # Generate a square lattice, with too many points.
    # Here I generate a factor of 4 more points than I need, which ensures
    # coverage for highly sheared lattices.  If your lattice is not highly
    # sheared, than you can generate fewer points.
    x_sq = np.arange(-nx, nx, dtype=float)
    y_sq = np.arange(-ny, nx, dtype=float)
    x_sq.shape = x_sq.shape + (1,)
    y_sq.shape = (1,) + y_sq.shape
    # Now shear the whole thing using the lattice vectors
    x_lattice = lattice_vectors[0][0]*x_sq + lattice_vectors[1][0]*y_sq
    y_lattice = lattice_vectors[0][1]*x_sq + lattice_vectors[1][1]*y_sq
    # Trim to fit in box.
    mask = ((x_lattice < image_shape[0]/2.0)
             & (x_lattice > -image_shape[0]/2.0))
    mask = mask & ((y_lattice < image_shape[1]/2.0)
                    & (y_lattice > -image_shape[1]/2.0))
    x_lattice = x_lattice[mask]
    y_lattice = y_lattice[mask]
    # Translate to the centre pix.
    x_lattice += center_pix[0]
    y_lattice += center_pix[1]
    # Make output compatible with original version.
    out = np.empty((len(x_lattice), 2), dtype=float)
    out[:, 0] = y_lattice
    out[:, 1] = x_lattice
    return out

rawDescription: Efficiently generate a lattice of points in python


code:
class RestTestCase(unittest.TestCase):
    resource = Resource('http://example.com')

    def sometest(self):
        r = self.resource
        ...
        self.assertEqual(expectedresult, actualresult)

class SomeOtherRestTestCase(RestTestCase):
    resource = Resource('http://someother.example.com')

class YetAnotherRestTestCase(RestTestCase):
    resource = Resource('http://yetanother.example.com')

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

rawDescription: What's the right way to pass a var to a Python unittest TestCase and/or TestSuite?


code:
from collections import defaultdict
d = defaultdict(dict)
d1 = {1:2,3:4}
d['id1'].update(d1)
d

rawDescription: dictionary of dictionary - How to update or create a value if key does not exist yet?

description: Dictionary of dictionary - How to update or create a value if key does not exist yet


code:
from bs4 import BeautifulSoup
html = """

Same participants, different directions

                RHEA:16949
                myo-inositol + NAD(+) <?> scyllo-inosose + H(+) + NADH

                RHEA:16950
                myo-inositol + NAD(+) => scyllo-inosose + H(+) + NADH

                RHEA:16951
                scyllo-inosose + H(+) + NADH => myo-inositol + NAD(+)

"""
soup = BeautifulSoup(html, 'html.parser')
soup.find('span', class_='icon-arrow-right').find_previous_sibling().get_text()

rawDescription: Extracting specific information from fetched HTML code using python


code:
class StructReader(object):
    def __init__(self, input_file):
        self.input_file = input_file

    def get_float(self, n):
        fmt = ...
        return struct.unpack(fmt, self.input_file.read(struct.calcsize(fmt)))

    ...

rawDescription: A custom file class. Is this feasible?

description: A custom file class. Is this feasible


code:
def length(wordLengths, i, j):
    return sum(wordLengths[i- 1:j]) + j - i + 1

def breakLine(text, L):
    # wl = lengths of words
    wl = [len(word) for word in text.split()]

    # n = number of words in the text
    n = len(wl)

    # total badness of a text l1 ... li
    m = dict()
    # initialization
    m[0] = 0

    # auxiliary array
    s = dict()

    # the actual algorithm
    for i in range(1, n + 1):
        sums = dict()
        k = i
        while (length(wl, k, i) <= L and k > 0):
            sums[(L - length(wl, k, i))**3 + m[k - 1]] = k
            k -= 1
        m[i] = min(sums)
        s[i] = sums[min(sums)]

    # actually do the splitting by working backwords
    line = 1
    while n > 1:
        print("line " + str(line) + ": " + str(s[n]) + "->" + str(n))
        n = s[n] - 1
        line += 1

rawDescription: Implementing Text Justification with Dynamic Programming


code:
import unicodedata
import re

splitter = re.compile(r'[\s|\-|\)|\(|/]+')

def remove_accents(text):
    nkfd_form = unicodedata.normalize('NFKD', unicode(text))
    return u"".join([c for c in nkfd_form if not unicodedata.combining(c)])

def get_words(text):
    return [s.lower() for s in splitter.split(remove_accents(text)) if s!= '']

def get_unique_words(text):
    word_set = set(get_words(text))
    return word_set

def get_starts(text):
    word_set = get_unique_words(text)
    starts = set()
    for word in word_set:
        for i in range(len(word)):
            starts.add(word[:i+1])
    return sorted(starts)

rawDescription: GAE Simple Searching + Autocomplete

description: GAE Simple Searching + Autocomplete


rawDescription: sorting a list of dictionary values by date in python

description: Sorting a list of dictionary values by date in python


code:
import networkx as nx
import numpy as np
G = nx.Graph()
feature_vector=np.array([1,7,22])
G.add_node(1,v=feature_vector)
G.node[1]['v']

rawDescription: Generating a feature vector for nodes and edges in networkx


code:
import re

template = re.compile(r'^name_is_here_(\d+)_20131204.txt$')

testList = ['name_is_here_100_20131204.txt', #accepted
            'name_is_here_100_20131204.txt.NEW', #rejected!
            'name_is_here_aabs2352_20131204.txt', #rejected!
            'other_name.txt'] #rejected!

acceptList = [item for item in testList if template.match(item)]

rawDescription: Python test if string matches a template value


code:
import datetime
now = datetime.datetime.now()

if now.weekday() < 5 and now.hour == 9 and now.minute == 45:
    # it's 9:45 on a weekday, do stuff
    premkt(bot)

rawDescription: compare set time with current time python

description: Compare set time with current time python


code:
import requests
import codecs

OMDBPath = "http://www.omdbapi.com/"

with codecs.open("movies.txt", encoding='utf-8') as movieFile, \
     codecs.open("log_found.txt", 'w', encoding='utf-8') as foundLog, \
     codecs.open("log_not_found.txt", 'w', encoding='utf-8') as notFoundLog:
    for line in movieFile:
        name = line.split('(')[0]
        print(name)
        year = False
        if line.find('(') != -1:
            year = line[line.find('(')+1 : line.find(')')]
            OMDBQuery = {'t': name, 'y': year}
        else:
            OMDBQuery = {'t': name}

        req = requests.get(OMDBPath, params=OMDBQuery)
        if req.json()[u'Response'] == "False":
            if year:
                notFoundLog.write(u"Couldn't find {} ({})\n".format(name, year))
            else:
                notFoundLog.write(u"Couldn't find {}\n".format(name))
        #else:
            #print(req.json())
            #foundLog.write(u"{},".format(req.text))

rawDescription: python: getting UnicodeEncodeError when trying to parse a list

description: Python: getting UnicodeEncodeError when trying to parse a list


code:
hists = [generate_random_histogram() for x in xrange(3)]
for h in hists:
    bin_locations = h['loc']
    bin_counts = h['count']
    bin_edges = np.concatenate([[0], (bin_locations[1:] + bin_locations[:-1])/2, [100]])
    bin_widths = np.diff(bin_edges)
    bin_density = bin_counts.astype(float) / np.dot(bin_widths, bin_counts)
    h['density'] = bin_density

    data = np.repeat(bin_locations, bin_counts)
    h['kde'] = gaussian_kde(data)

    plt.step(bin_locations, bin_density, where='mid', label='normalized')
    plt.plot(np.linspace(0,100), h['kde'](np.linspace(0,100)), label='kde')

rawDescription: Making Probability Distribution Functions (PDFs) from histograms


code:
def tokenize(data, col_of_category):
    str_to_int, int_to_str = {}, {}
    for row in data:
        cat = row[col_of_category]
        if cat in str_to_int.keys(): token = str_to_int[cat]
        else:
            token = len(str_to_int.keys())
            str_to_int[cat] = token
            int_to_str[token] = cat
        row[col_of_category] = token # assuming your rows are mutable
    return str_to_int, int_to_str

rawDescription: How to use one hot encoder on categorical data in scikit?

description: Use one hot encoder on categorical data in scikit


code:
from tvtk.api import tvtk, write_data
import numpy as np

data = np.random.random((3,3,3))
data2 = np.random.random((3,3,3))

i = tvtk.ImageData(spacing=(1, 1, 1), origin=(0, 0, 0))
i.point_data.scalars = data.ravel()
i.point_data.scalars.name = 'scalars'
i.dimensions = data.shape
# add second point data field
i.point_data.add_array(data2.ravel())
i.point_data.get_array(1).name = 'field2'
i.point_data.update()

write_data(i, 'vtktest.vtk')

rawDescription: Save data to VTK using Python and tvtk with more than one vector field


code:
def sortkey(row):
    return (row[5], row)

def unwrap(key):
    sortkey, row = key
    return row

from itertools import imap
FILE_LIST = map(file, ['foo.csv', 'bar.csv'])
input_iters = imap(sortkey, map(csv.csvreader, FILE_LIST))
output_iter = imap(unwrap, heapq.merge(*input_iters))

rawDescription: Yielding from sorted iterators in sorted order in Python?


code:
from igraph import Graph, Plot
from cairo import Context

# Create two graphs
g = Graph.Ring(5)
g2 = Graph.Full(5)

# Create a figure containing the two graphs
fig = Plot("test.pdf", bbox=(800, 360), background="white")
fig.add(g, bbox=(20,20,340,340))
fig.add(g2, bbox=(460,20,780,340))

# Force the figure to be drawn
fig.redraw()

# Create a Cairo drawing context
ctx = Context(fig.surface)

# Draw an arrow
ctx.set_source_rgb(0,0,0)
ctx.move_to(360,180)
ctx.line_to(430,180)
ctx.stroke()
ctx.move_to(440,180)
ctx.line_to(430,170)
ctx.line_to(430,190)
ctx.line_to(440,180)
ctx.fill()

# Save the figure
fig.save()

rawDescription: How to draw an arrow edge with ArrowEdgeDrawer in python-graph?

description: Draw an arrow edge with ArrowEdgeDrawer in python-graph


code:
class A:
    "A class without __abs__ defined"
    def __init__(self, v):
        self.v = v

def A_abs(a):
    "An 'extension' method that will be added to `A`"
    return abs(a.v)

# Make abs() work with an instance of A
A.__abs__ = A_abs

rawDescription: Why built-in functions like abs works on numpy array?


code:
def dump_object(self, value):
    """Dumps an object into a string for redis.  By default it serializes
    integers as regular string and pickle dumps everything else.
    """
    t = type(value)
    if t in integer_types:
        return str(value).encode('ascii')
    return b'!' + pickle.dumps(value)

def load_object(self, value):
    """The reversal of :meth:`dump_object`.  This might be called with
    None.
    """
    if value is None:
        return None
    if value.startswith(b'!'):
        try:
            return pickle.loads(value[1:])
        except pickle.PickleError:
            return None
    try:
        return int(value)
    except ValueError:
        # before 0.8 we did not have serialization.  Still support that.
        return value

rawDescription: How do I work with cached values created by flask-cache

description: Work with cached values created by flask-cache


code:
def func(s, old, new):
    n = 1
    while old in s:
        s = s.replace(old, new + '_{}'.format(n), 1)
        n += 1

    return s

text = "bbsjsddh www.test.com shduh sudhuhd sjdjsdh wiowqiuedl www.test.com uasuisdhckjdfh www.test.com sudhdhdhfh"

print(func(text, 'www.test.com', 'website'))
# bbsjsddh website_1 shduh sudhuhd sjdjsdh wiowqiuedl website_2 uasuisdhckjdfh website_3 sudhdhdhfh

rawDescription: Increasing integer after having found occurrence


code:
your_dict = {u'605': [u'56', u'31'], u'602': [u'43', u'77']}

for precincts in map_data["features"]:

    placeVariable = precincts["properties"]
    prec = placeVariable["precNum"]

    if your_dict.get(prec): #checks if prec exists in your_dict
        placeVariable["cand1"] = your_dict['prec'][0]
        placevariable["cand2"] = your_dict['prec'][0]

rawDescription: Updating geoJSON file from python dict

description: Updating geoJSON file from python dict


code:
l = [('apple', ['gala','fuji', 'macintosh']),
('pear', ['seckel','anjou','bosc'])]

l2 = [(k, sorted(v)) for k, v in l]
# [('apple', ['fuji', 'gala', 'macintosh']), ('pear', ['anjou', 'bosc', 'seckel'])]

rawDescription: Iterate over a list of nested tuples

description: Iterate over a list of nested tuples


code:
for i in range(10000):
    chi1 = chisqg(y1,mod1,sd=0.1)
    chi.append(chi1)

rawDescription: python: execute a .py file multiple times?

description: Python: execute a .py file multiple times


rawDescription: regex for catching only upper-case matches

description: Regex for catching only upper-case matches


code:
from splinter import Browser
import time
from bs4 import BeautifulSoup
import codecs

browser = Browser()
url = 'http://play.spotify.com'
browser.visit(url)
time.sleep(2)
button = browser.find_by_id('has-account')
button.click()
time.sleep(1)
browser.fill('username', 'your_username')
browser.fill('password', 'your_password')
buttons = browser.find_by_css('button')
visible_buttons = [button for button in buttons if button.visible]
login_button = visible_buttons[-1]
login_button.click()
time.sleep(1)
browser.visit('https://play.spotify.com/artist/5YGY8feqx7naU7z4HrwZM6')
time.sleep(30)

CORRECT_FRAME_INDEX = 6
with browser.get_iframe(CORRECT_FRAME_INDEX) as iframe:
    html = iframe.html
    soup = BeautifulSoup(html)
    output = soup.prettify()
    with codecs.open('test.html', 'w', 'utf-8') as output_f:
        output_f.write(output)
browser.quit()

rawDescription: Scrape spotify web interface

description: Scrape spotify web interface


code:
from collections import defaultdict
import csv

# ... read values using a csv reader (assuming name csv_reader)

result = defaultdict(set)
for row in csv_reader:
    # create same key for `A, B` and `B, A`
    key = tuple(sorted([row[0], row[1]]))
    result[key].add(row[2])

# result should now contain all aggregated values

rawDescription: How do I find duplicates within two columns in a csv file, then combine them in Python?

description: Find duplicates within two columns in a csv file, then combine them in Python


code:
d = {}
with open("input") as f:
    for line in f:
        key, dummy, dummy, value, dummy = line.split()
        d[key] = float(value)

rawDescription: Text file to dictionary

description: Text file to dictionary


code:
class Property(object):
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

    def getter(self, fget):
        return type(self)(fget, self.fset, self.fdel, self.__doc__)

    def setter(self, fset):
        return type(self)(self.fget, fset, self.fdel, self.__doc__)

    def deleter(self, fdel):
        return type(self)(self.fget, self.fset, fdel, self.__doc__)

rawDescription: Subclassing Python's `property`

description: Subclassing Python's `property`


code:
@app.template_filter()
@evalcontextfilter
def mark2html(eval_ctx, value):
    result = value.replace('[s]',u'<strong>')
    result = result.replace('[/s]',u'</strong>')
    if eval_ctx.autoescape:
        result = Markup(result)
    return result

rawDescription: Jinja2 filter to convert custom markup to html


code:
def myComplicatedFunction(status):
    """Here I have a brief description

    :param status: explanation

    :returns: explanation

    >>> myComplicatedFunction('status value')
    {'foo': 2, 'bar': -400}

    """
    # Code

    return statistics

rawDescription: Include python source code in header function declaration part of sphinx


code:
from flask import Flask, request, send_from_directory

@app.route('/robots.txt')
@app.route('/sitemap.xml')
def static_from_root():
    return send_from_directory(app.static_folder, request.path[1:])

rawDescription: With Flask, how can I serve robots.txt and sitemap.xml as static files?


code:
for i,j in enumerate(list):
    if j==x:
        print(i)
        break
else:
    print(-1)

rawDescription: Find index of a given number in a list python3


code:
from django.db.models import Count

Link.objects.extra(select={'month': 'extract( month from pub_date )'}).values('month').annotate(dcount=Count('pub_date'))

rawDescription: Django annotate groupings by month

description: Django annotate groupings by month


code:
plt.plot(data0.x, data0.y)
for target in [data1, data2]:
    dx = np.mean(np.diff(data0.x.values))
    shift = (np.argmax(signal.correlate(data0.y, target.y)) - len(target.y)) * dx
    plt.plot(target.x + shift, target.y)

rawDescription: Use of pandas.shift() to align datasets based on scipy.signal.correlate


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

# set a custom user-agent
user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = user_agent

driver = webdriver.PhantomJS(desired_capabilities=dcap)
driver.get("http://www.seloger.com/list.htm?cp=40250&org=advanced_search&idtt=2&pxmin=50000&pxmax=200000&surfacemin=20&surfacemax=100&idtypebien=2&idtypebien=1&idtypebien=11")

# wait for arcitles to be present
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.TAG_NAME, "article")))

# get articles
for article in driver.find_elements_by_tag_name("article"):
    print(article.text)

rawDescription: Issue scraping javascript generated content with Selenium and python


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

def goto(driver, section, subsection):
    if subsection != "None":
        hover_over = driver.find_element_by_link_text(section)
        hover = selenium.webdriver.ActionChains(driver).move_to_element(hover_over)
        hover.perform()

        # IMPROVEMENT HERE
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, subsection))).click()
    else:
        driver.find_element_by_link_text(section).click()

rawDescription: Fragile Test in Selenium with Python

description: Fragile Test in Selenium with Python


code: Dtot = Dacceleration + Dconstant + Dbraking

rawDescription: Solving Quadratic Equation Equal to 0 in Python


code:
def modify_dict(my_dict):
    my_dict['b'] = 2
    print(my_dict)

rawDescription: Modifying dictionary inside a function

description: Modifying dictionary inside a function


code:
pq = []                         # list of entries arranged in a heap
entry_finder = {}               # mapping of tasks to entries
REMOVED = '<removed-task>'      # placeholder for a removed task
counter = itertools.count()     # unique sequence count

def add_task(task, priority=0):
    'Add a new task or update the priority of an existing task'
    if task in entry_finder:
        remove_task(task)
    count = next(counter)
    entry = [priority, count, task]
    entry_finder[task] = entry
    heappush(pq, entry)

def remove_task(task):
    'Mark an existing task as REMOVED.  Raise KeyError if not found.'
    entry = entry_finder.pop(task)
    entry[-1] = REMOVED

def pop_task():
    'Remove and return the lowest priority task. Raise KeyError if empty.'
    while pq:
        priority, count, task = heappop(pq)
        if task is not REMOVED:
            del entry_finder[task]
            return task
    raise KeyError('pop from an empty priority queue')

rawDescription: Removing an arbitrary item from the priority queue


code:
posts_with_multiple_readers = (
    Blog.objects.filter(reader__type__name='male')
    .annotate(reader_count=Count('reader'))
    .filter(reader_count__gte=2)
)

rawDescription: Django filter on related field using annotate


code:
from nameparser import HumanName
from nameparser.constants import TITLES
titles_c = TITLES | set("assistant professor".split())
hn = HumanName(titles_c=titles_c)
hn.full_name = "Assistant Professor Darwin Mittenchops"
hn

rawDescription: Custom constants in python humanname not working


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

# get a list of countries
website = "http://vbcity.com/cfs-filesystemfile.ashx/__key/CommunityServer.Components.PostAttachments/00.00.61.18.99/Country-List.txt"
response = urllib2.urlopen(website)
page = response.read()
many_countries = page.split('\r\n')

# pick out a subset of them
n = 25
ind = np.random.randint(0, len(many_countries), 25)
country_list = [many_countries[i] for i in ind]

# some random heights for each of the bars.
heights = np.random.randint(3, 12, len(country_list))

plt.figure(1)
h = plt.bar(xrange(len(country_list)), heights, label=country_list)
plt.subplots_adjust(bottom=0.3)

xticks_pos = [0.65*patch.get_width() + patch.get_xy()[0] for patch in h]

plt.xticks(xticks_pos, country_list,  ha='right', rotation=45)

rawDescription: Matplotlib Python Barplot: Position of xtick labels have irregular spaces between eachother


code:
import pylab as plt
import numpy as NP

plt.figure(figsize=(14,8), dpi=72)
plt.gcf().suptitle(r'Difference between TI and $\lambda$D', size=16)
# Subplot 1
ax1 = plt.subplot2grid((1,3),(0,0),colspan=2)
N = 100
LE_x = NP.random.rand(N)
LE_y = NP.random.rand(N)
MD_x = NP.random.rand(N)
MD_y = NP.random.rand(N)

# Plot scattered data in first subplot
s1 = plt.scatter(LE_x, LE_y, s=40, lw=0, color='gold', marker='o', label=r'$\lambda$D')
s2 = plt.scatter(MD_x, MD_y, s=40, lw=0, color='blue', marker='^', label=r'TI')

data = NP.random.randn(1000)
LE_hist, bins2 = NP.histogram(data, 50)

data = NP.random.randn(1000)
MD_hist, bins2 = NP.histogram(data, 50)
# Subplot 2
ax2 = plt.subplot2grid((1,3),(0,2))
vpos1 = NP.arange(0, len(LE_hist))
vpos2 = NP.arange(0, len(MD_hist)) + 0.5
h1 = plt.barh(vpos1, LE_hist, height=0.5, color='gold', label=r'$\lambda$D')
h2 = plt.barh(vpos2, MD_hist, height=0.5, color='blue', label=r'TI')

# Legend
#legend = plt.legend()
lgd = plt.legend((s1, s2, h1, h2), (r'$\lambda$D', r'TI', r'$\lambda$D', r'TI'), loc='upper center')
plt.show()

rawDescription: One legend for all subplots in pyplot

description: One legend for all subplots in pyplot


code:
import random
random.getrandbits(10)

rawDescription: How to generate a number of n-bit in length using python?

description: Generate a number of n-bit in length using python


code:
import pynotify
import sys
pynotify.init(sys.argv[0])
notification = pynotify.Notification("Title", "body", "dialog-info")
notification.set_urgency(pynotify.URGENCY_NORMAL)
notification.set_timeout(pynotify.EXPIRES_DEFAULT)
notification.show()

rawDescription: Flash Characters on Screen in Linux

description: Flash Characters on Screen in Linux


code:
import pyttsx
import random
data = pyttsx.init()
d = str(random.randrange(100, 1000, 2))
data.say(d)
data.runAndWait()

rawDescription: How to generate output as sound in python..?

description: Generate output as sound in python..


code:
if int(row["DISTANCE"]) <= 300:
    proceed_with_row(...)

rawDescription: Using a Comparison Operator on a Dictionary in Python


code: lines = r.splitlines()

rawDescription: about textarea \r\n or \n in python

description: About textarea \r\n or \n in python


code:
data = range(1,10);
fig = figure()
for i in range(6):
    ax = fig.add_subplot(2,3,i)

    ax.text(.5,.9,'centered title',
        horizontalalignment='center',
        transform=ax.transAxes)

    ax.plot(data)
show()

rawDescription: Matplotlib placement of text e.g. suptitle inside the frame


code:
import subprocess
subprocess.check_output(["python", "start.py"])

rawDescription: How to run a file from the body of a program?

description: Run a file from the body of a program


code:
# A list of module ids to install:
module_ids = (
    59, #account_accountant
    104, # account_asset
    7, # account_voucher
    47, # crm
    23, # crm_todo
    119, # hr
    115, # hr_timesheet_sheet
    14, # knowledge
    191, # purchase
    175, # stock
)

#send request to server
response = sock.execute(dbname, uid, pwd, 'ir.module.module', 'button_immediate_install', module_ids)

rawDescription: OpenERP: answering module configuration via XML-RPC


code:
import re
find_decimal = re.compile(r'decimal\((\d+,\d+)\)')
find_decimal.match('decimal(4,1)').group(1)

rawDescription: Regular expression with positive lookbehind at beginning fails to match whole string


code:
@pyqtSlot(QtGui.QTableWidgetItem)
def flag_cell_unsaved(self, item):
    if item.foreground() != Qt.red:
        item.setForeground(Qt.red)

rawDescription: Slot triggers its own signal

description: Slot triggers its own signal


code:
replaced = row[0].replace('word','changed word')  # I want to replace in first column=row[0] 'word' with 'changed word'
row[0] = replaced
writer.writerow(row)

rawDescription: How to replace a word in a csv file in specific column with python

description: Replace a word in a csv file in specific column with python


code:
class DictRow(list):
    """A row object that allow by-column-name access to data."""

    __slots__ = ('_index',)

    def __init__(self, cursor):
        self._index = cursor.index
        self[:] = [None] * len(cursor.description)

    def __getitem__(self, x):
        if not isinstance(x, (int, slice)):
            x = self._index[x]
        return list.__getitem__(self, x)

    def __setitem__(self, x, v):
        if not isinstance(x, (int, slice)):
            x = self._index[x]
        list.__setitem__(self, x, v)

    def items(self):
        return list(self.iteritems())

    def keys(self):
        return self._index.keys()

    def values(self):
        return tuple(self[:])

    def has_key(self, x):
        return x in self._index

    def get(self, x, default=None):
        try:
            return self[x]
        except:
            return default

    def iteritems(self):
        for n, v in self._index.iteritems():
            yield n, list.__getitem__(self, v)

    def iterkeys(self):
        return self._index.iterkeys()

    def itervalues(self):
        return list.__iter__(self)

    def copy(self):
        return dict(self.iteritems())

    def __contains__(self, x):
        return x in self._index

    def __getstate__(self):
        return self[:], self._index.copy()

    def __setstate__(self, data):
        self[:] = data[0]
        self._index = data[1]

    if _sys.version_info[0] > 2:
        items = iteritems; del iteritems
        keys = iterkeys; del iterkeys
        values = itervalues; del itervalues
        del has_key

rawDescription: Cursor when returning dictionary and print where are the keys


code:
def block(ch):
  '''
  Return the Unicode block name for ch, or None if ch has no block.

  >>> block(u'a')
  'Basic Latin'
  >>> block(unichr(0x0b80))
  'Tamil'
  >>> block(unichr(0xe0080))

  '''

  assert isinstance(ch, unicode) and len(ch) == 1, repr(ch)
  cp = ord(ch)
  for start, end, name in _blocks:
    if start <= cp <= end:
      return name

def _initBlocks(text):
  global _blocks
  _blocks = []
  import re
  pattern = re.compile(r'([0-9A-F]+)\.\.([0-9A-F]+);\ (\S.*\S)')
  for line in text.splitlines():
    m = pattern.match(line)
    if m:
      start, end, name = m.groups()
      _blocks.append((int(start, 16), int(end, 16), name))

# retrieved from http://unicode.org/Public/UNIDATA/Blocks.txt
_initBlocks('''
# Blocks-5.1.0.txt
# Date: 2008-03-20, 17:41:00 PDT [KW]
#
# Unicode Character Database
# Copyright (c) 1991-2008 Unicode, Inc.
# For terms of use, see http://www.unicode.org/terms_of_use.html
# For documentation, see UCD.html
#
# Note:   The casing of block names is not normative.
#         For example, "Basic Latin" and "BASIC LATIN" are equivalent.
#
# Format:
# Start Code..End Code; Block Name

# ================================================

# Note:   When comparing block names, casing, whitespace, hyphens,
#         and underbars are ignored.
#         For example, "Latin Extended-A" and "latin extended a" are equivalent.
#         For more information on the comparison of property values,
#            see UCD.html.
#
#  All code points not explicitly listed for Block
#  have the value No_Block.

# Property: Block
#
# @missing: 0000..10FFFF; No_Block

0000..007F; Basic Latin
0080..00FF; Latin-1 Supplement
0100..017F; Latin Extended-A
0180..024F; Latin Extended-B
0250..02AF; IPA Extensions
02B0..02FF; Spacing Modifier Letters
0300..036F; Combining Diacritical Marks
0370..03FF; Greek and Coptic
0400..04FF; Cyrillic
0500..052F; Cyrillic Supplement
0530..058F; Armenian
0590..05FF; Hebrew
0600..06FF; Arabic
0700..074F; Syriac
0750..077F; Arabic Supplement
0780..07BF; Thaana
07C0..07FF; NKo
0900..097F; Devanagari
0980..09FF; Bengali
0A00..0A7F; Gurmukhi
0A80..0AFF; Gujarati
0B00..0B7F; Oriya
0B80..0BFF; Tamil
0C00..0C7F; Telugu
0C80..0CFF; Kannada
0D00..0D7F; Malayalam
0D80..0DFF; Sinhala
0E00..0E7F; Thai
0E80..0EFF; Lao
0F00..0FFF; Tibetan
1000..109F; Myanmar
10A0..10FF; Georgian
1100..11FF; Hangul Jamo
1200..137F; Ethiopic
1380..139F; Ethiopic Supplement
13A0..13FF; Cherokee
1400..167F; Unified Canadian Aboriginal Syllabics
1680..169F; Ogham
16A0..16FF; Runic
1700..171F; Tagalog
1720..173F; Hanunoo
1740..175F; Buhid
1760..177F; Tagbanwa
1780..17FF; Khmer
1800..18AF; Mongolian
1900..194F; Limbu
1950..197F; Tai Le
1980..19DF; New Tai Lue
19E0..19FF; Khmer Symbols
1A00..1A1F; Buginese
1B00..1B7F; Balinese
1B80..1BBF; Sundanese
1C00..1C4F; Lepcha
1C50..1C7F; Ol Chiki
1D00..1D7F; Phonetic Extensions
1D80..1DBF; Phonetic Extensions Supplement
1DC0..1DFF; Combining Diacritical Marks Supplement
1E00..1EFF; Latin Extended Additional
1F00..1FFF; Greek Extended
2000..206F; General Punctuation
2070..209F; Superscripts and Subscripts
20A0..20CF; Currency Symbols
20D0..20FF; Combining Diacritical Marks for Symbols
2100..214F; Letterlike Symbols
2150..218F; Number Forms
2190..21FF; Arrows
2200..22FF; Mathematical Operators
2300..23FF; Miscellaneous Technical
2400..243F; Control Pictures
2440..245F; Optical Character Recognition
2460..24FF; Enclosed Alphanumerics
2500..257F; Box Drawing
2580..259F; Block Elements
25A0..25FF; Geometric Shapes
2600..26FF; Miscellaneous Symbols
2700..27BF; Dingbats
27C0..27EF; Miscellaneous Mathematical Symbols-A
27F0..27FF; Supplemental Arrows-A
2800..28FF; Braille Patterns
2900..297F; Supplemental Arrows-B
2980..29FF; Miscellaneous Mathematical Symbols-B
2A00..2AFF; Supplemental Mathematical Operators
2B00..2BFF; Miscellaneous Symbols and Arrows
2C00..2C5F; Glagolitic
2C60..2C7F; Latin Extended-C
2C80..2CFF; Coptic
2D00..2D2F; Georgian Supplement
2D30..2D7F; Tifinagh
2D80..2DDF; Ethiopic Extended
2DE0..2DFF; Cyrillic Extended-A
2E00..2E7F; Supplemental Punctuation
2E80..2EFF; CJK Radicals Supplement
2F00..2FDF; Kangxi Radicals
2FF0..2FFF; Ideographic Description Characters
3000..303F; CJK Symbols and Punctuation
3040..309F; Hiragana
30A0..30FF; Katakana
3100..312F; Bopomofo
3130..318F; Hangul Compatibility Jamo
3190..319F; Kanbun
31A0..31BF; Bopomofo Extended
31C0..31EF; CJK Strokes
31F0..31FF; Katakana Phonetic Extensions
3200..32FF; Enclosed CJK Letters and Months
3300..33FF; CJK Compatibility
3400..4DBF; CJK Unified Ideographs Extension A
4DC0..4DFF; Yijing Hexagram Symbols
4E00..9FFF; CJK Unified Ideographs
A000..A48F; Yi Syllables
A490..A4CF; Yi Radicals
A500..A63F; Vai
A640..A69F; Cyrillic Extended-B
A700..A71F; Modifier Tone Letters
A720..A7FF; Latin Extended-D
A800..A82F; Syloti Nagri
A840..A87F; Phags-pa
A880..A8DF; Saurashtra
A900..A92F; Kayah Li
A930..A95F; Rejang
AA00..AA5F; Cham
AC00..D7AF; Hangul Syllables
D800..DB7F; High Surrogates
DB80..DBFF; High Private Use Surrogates
DC00..DFFF; Low Surrogates
E000..F8FF; Private Use Area
F900..FAFF; CJK Compatibility Ideographs
FB00..FB4F; Alphabetic Presentation Forms
FB50..FDFF; Arabic Presentation Forms-A
FE00..FE0F; Variation Selectors
FE10..FE1F; Vertical Forms
FE20..FE2F; Combining Half Marks
FE30..FE4F; CJK Compatibility Forms
FE50..FE6F; Small Form Variants
FE70..FEFF; Arabic Presentation Forms-B
FF00..FFEF; Halfwidth and Fullwidth Forms
FFF0..FFFF; Specials
10000..1007F; Linear B Syllabary
10080..100FF; Linear B Ideograms
10100..1013F; Aegean Numbers
10140..1018F; Ancient Greek Numbers
10190..101CF; Ancient Symbols
101D0..101FF; Phaistos Disc
10280..1029F; Lycian
102A0..102DF; Carian
10300..1032F; Old Italic
10330..1034F; Gothic
10380..1039F; Ugaritic
103A0..103DF; Old Persian
10400..1044F; Deseret
10450..1047F; Shavian
10480..104AF; Osmanya
10800..1083F; Cypriot Syllabary
10900..1091F; Phoenician
10920..1093F; Lydian
10A00..10A5F; Kharoshthi
12000..123FF; Cuneiform
12400..1247F; Cuneiform Numbers and Punctuation
1D000..1D0FF; Byzantine Musical Symbols
1D100..1D1FF; Musical Symbols
1D200..1D24F; Ancient Greek Musical Notation
1D300..1D35F; Tai Xuan Jing Symbols
1D360..1D37F; Counting Rod Numerals
1D400..1D7FF; Mathematical Alphanumeric Symbols
1F000..1F02F; Mahjong Tiles
1F030..1F09F; Domino Tiles
20000..2A6DF; CJK Unified Ideographs Extension B
2F800..2FA1F; CJK Compatibility Ideographs Supplement
E0000..E007F; Tags
E0100..E01EF; Variation Selectors Supplement
F0000..FFFFF; Supplementary Private Use Area-A
100000..10FFFF; Supplementary Private Use Area-B

# EOF
''')

rawDescription: Unicode block of a character in python

description: Unicode block of a character in python


code:
#!/usr/bin/env python

from twisted.internet import reactor, protocol

class Responder(protocol.Protocol):
    def connectionMade(self):
        self.vcode = None

    def dataReceived(self, data):
        # check the voucher code, and return disabled if its out of time or not there. Otherwise return time left.
        if data.startswith("check="):
            param, vcode = data.split("=")
            if vcode in self.factory.activeVouchers:
                self.transport.write("in use")
                return
            self.factory.activeVouchers.add(vcode)
            self.vcode = vcode

            checkcode = SQLConnect("check", vcode, vcode)
            if checkcode == "disabled":
                self.transport.write("disabled")
            else:
                self.transport.write(str(checkcode))
        # Update time left.
        if data.startswith("update="):
            param, vcode, vtime = data.split("=")
            SQLConnect("update", vcode, vtime)

    def connectionLost(self, reason):
        if self.vcode is not None:
            self.factory.activeVouchers.remove(self.vcode)

def main():
    factory = protocol.ServerFactory()
    factory.activeVouchers = set()
    factory.protocol = Responder
    reactor.listenTCP(6500,factory)
    reactor.run()

if __name__ == '__main__':
    main()

rawDescription: Python twisted - Need to go through all connections and find a client


code:
from itertools import product
list(product(range(1, 4), repeat=3))

rawDescription: How to create N-tuples in Python?

description: Create N-tuples in Python


code:
class NavigationToolbar(NavigationToolbar2GTKAgg):
    # only display the buttons we need
    toolitems = [t for t in NavigationToolbar2GTKAgg.toolitems if
                 t[0] in ('Home', 'Pan', 'Zoom', 'Save')]

rawDescription: How to modify the navigation toolbar easily in a matplotlib figure window?

description: Modify the navigation toolbar easily in a matplotlib figure window


code:
def rotate(L, N): return L[N:] + L[:N]
L = [1, 2, 3, 4, 5]
rotate(L, 1)
rotate(L, -1)

rawDescription: Rotating list in Python without collection.deque


code:
import cookielib
import logging
import sys
import urllib
import urllib2

cookies = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))
urllib2.install_opener(opener)
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12',
    'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
    'Accept-Language': 'en-gb,en;q=0.5',
    'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
}

# Fetch the login page to set initial cookies
urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=00', None, headers))

# Login so we can access the Off Topic forum
login_headers = headers.copy()
login_headers.update({
    'Referer': 'http://www.rllmukforum.com/index.php?act=Login&CODE=00',
    'Content-Type': 'application/x-www-form-urlencoded',
})
html = urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=01',
                                       urllib.urlencode({
                                           'referer': 'http://www.rllmukforum.com/index.php?',
                                           'UserName': RLLMUK_USERNAME,
                                           'PassWord': RLLMUK_PASSWORD,
                                       }),
                                       login_headers)).read()
if 'The following errors were found' in html:
    logging.error('RLLMUK login failed')
    logging.info(html)
    sys.exit(1)

rawDescription: How would one log into a phpBB3 forum through a Python script using urllib, urllib2 and ClientCookie?


code:
from celery.signals import celeryd_init

@celeryd_init.connect(sender='worker12@example.com')
def configure_worker12(conf=None, **kwargs):
    ...

rawDescription: Django celery task run at once on startup of celery server


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

rawDescription: Charts with proper unicode support

description: Charts with proper unicode support


code: pd.read_csv('test.csv', sep='|', skiprows=range(1, 10))

rawDescription: Python Pandas read_csv skip rows but keep header


code:
import subprocess
proc = subprocess.Popen('cmd.exe', stdin = subprocess.PIPE, stdout = subprocess.PIPE)
stdout, stderr = proc.communicate('dir c:\\')
stdout

rawDescription: How to execute a command prompt command from python

description: Execute a command prompt command from python


code:
import maya.cmds as mc

Xsl = (mc.ls (sl=1, sn=1))[0]

def toastFUNC (arg=0):
    mc.animCurveEditor (curveEditor, e=1, lck=1)

mc.window(w=500)
mc.paneLayout( configuration='vertical2', swp=1, ps=[2, 70, 0] )
mc.frameLayout(w=150, h=100, lv=0)

mc.outlinerEditor(mlc='modelList', slc='modelList', showReferenceNodes=0, showReferenceMembers=0,    showAttributes=1, showSelected=0, highlightActive=1, showAnimCurvesOnly=0, autoExpand=1,
showConnected=1, showDagOnly=0, ignoreDagHierarchy=1, expandConnections=0, showCompounds=0,   showNumericAttrsOnly=0,
autoSelectNewObjects=0, doNotSelectNewObjects=1, transmitFilters=0, showSetMembers=1,    setFilter='defaultSetFilter', lck=1, sec=toastFUNC)

mc.setParent('..')

mc.frameLayout(w=1, h=100, lv=0)
curveEditor = mc.animCurveEditor(mlc='modelList', slc='modelList', dak=1, di=0, dat='off', lck=1)
mc.setParent('..')
mc.showWindow()

rawDescription: How can I keep an object selected in the outliner after physically deselecting it in the 3d view?

description: Keep an object selected in the outliner after physically deselecting it in the 3d view


code:
def get_upload_file_name(instance, filename):
    new_file_path_and_name = os.path.join(BASE_DIR, 'static', 'test.txt')
    return new_file_path_and_name

rawDescription: Image upload through admin in Django

description: Image upload through admin in Django


code:
class Basket(Base):
    ...
    items          = relationship("Item")

class Item(Base):
    ...
    basket_id = Column(Integer, ForeignKey(Basket.id))

rawDescription: SQLAlchemy, one to many list always drop to one object after a commit


code:
import PIL.Image
import sys

# python chop.py [chop-factor] [in-file] [out-file]

chop = int(sys.argv[1])
image = PIL.Image.open(sys.argv[2]).convert('1')
width, height = image.size
data = image.load()

# Iterate through the rows.
for y in range(height):
    for x in range(width):

        # Make sure we're on a dark pixel.
        if data[x, y] > 128:
            continue

        # Keep a total of non-white contiguous pixels.
        total = 0

        # Check a sequence ranging from x to image.width.
        for c in range(x, width):

            # If the pixel is dark, add it to the total.
            if data[c, y] < 128:
                total += 1

            # If the pixel is light, stop the sequence.
            else:
                break

        # If the total is less than the chop, replace everything with white.
        if total <= chop:
            for c in range(total):
                data[x + c, y] = 255

        # Skip this sequence we just altered.
        x += total

# Iterate through the columns.
for x in range(width):
    for y in range(height):

        # Make sure we're on a dark pixel.
        if data[x, y] > 128:
            continue

        # Keep a total of non-white contiguous pixels.
        total = 0

        # Check a sequence ranging from y to image.height.
        for c in range(y, height):

            # If the pixel is dark, add it to the total.
            if data[x, c] < 128:
                total += 1

            # If the pixel is light, stop the sequence.
            else:
                break

        # If the total is less than the chop, replace everything with white.
        if total <= chop:
            for c in range(total):
                data[x, y + c] = 255

        # Skip this sequence we just altered.
        y += total

image.save(sys.argv[3])

rawDescription: Removing the background noise of a captcha image by replicating the chopping filter of TesserCap


rawDescription: Frequency mapping with dictionary in Python


code:
part = image.MIMEImage( "image", "x-other", encoders.encode_noop )
part.set_payload( os.urandom(200) )
part.add_header( 'Content-Transfer-Encoding', 'binary' )
m.attach( part )

rawDescription: Encode MIME multipart with binary data in Python?


code: total = sum([d['quantity'] * d['price'] for d in base])

rawDescription: Summing the values in database

description: Summing the values in database


code:
class UserProfileadmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'hub':
            kwargs['queryset'] = Airports.objects.filter(hub=True)
        return super(UserProfileadmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

rawDescription: Django admin dropdowns based on a boolean


code:
from itertools import product

dice_outcomes = list(product(range(1, 7), repeat=2))
is_even = {el for el in dice_outcomes if sum(el) % 2 == 0}
product_is_even = {(fst, snd) for fst, snd in dice_outcomes if fst*snd % 2 == 0}
just_even = is_even - product_is_even
even_and_product = is_even & product_is_even

rawDescription: How to change a list of tuples to a set in Python?

description: Change a list of tuples to a set in Python


code:
## Product list
ta_prod = {} # dictionary instead of list

prod = open("products.txt", "r")
for line2 in prod:
    row2 = line2.split(",")
    prodordnavn = row2[4] # reading the referencing key
    ta_prod[prodordnavn] = row2[11] # the value you would like to use in the other loop

## Producs Ordered
supne = []
ta_prodord = []
prodord = open("products_ordered.txt", "r")
for line in prodord:
    row = line.split(",")
    prodordnavn = re.sub('"',"",row[1])
    ta_prodord.append(prodordnavn)
    if prodordnavn in ta_prod:
        value = ta_prod[prodordnavn] # reading the value from ta_prod dictionary by prodordnavn key
        supne.append([row[0],row[1],row[2],value])

rawDescription: How to append information from a list that is not in the current loop

description: Append information from a list that is not in the current loop


code:
def imerge(a, b):
    for i, j in itertools.izip(a,b):
        yield i
        yield j

rawDescription: How do I merge two python iterators?

description: Merge two python iterators


code:
x = input("What is wrong with your phone?")
keywords = ["doesn't turn on", "cracked", "dropped"]
if any(keyword in x for keyword in keywords):
    print("test")

rawDescription: How can I detect multiple words from a string? (python)

description: Detect multiple words from a string? (python)


code:
def send(self, obj):
    """Send a (picklable) object"""
    self._check_closed()
    self._check_writable()
    buf = io.BytesIO()
    ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(obj)
    self._send_bytes(buf.getbuffer())

def recv(self):
    """Receive a (picklable) object"""
    self._check_closed()
    self._check_readable()
    buf = self._recv_bytes()
    return pickle.loads(buf.getbuffer())

rawDescription: Does Python's multiprocessing.connection serialize?


code:
food = {}
for i in range(amount):
    coords = randint(100, 700), randint(100, 700)
    if coords not in food:
        food[coords] = [
            i,   #identifier
            100, # energy
        ]

rawDescription: Python - How to check values in a sublist


code: sorted(wordSimDic, key=lambda k: (wordSimDic.get(k), k), reverse=True)

rawDescription: sorted Dictionary to list

description: Sorted Dictionary to list


code:
import bisect
L = range(10, 100)
L.remove(15)
solve(L,15)
solve(L,17)
L.pop(20)
solve(L,31)

rawDescription: Finding the max number <= some other number


code:
rsync_out = subprocess.Popen(['sshpass', '-p', password, 'rsync', '--recursive', source], stdout=subprocess.PIPE)
output = subprocess.check_output(('grep', '\.'), stdin=rsync_out.stdout)

rawDescription: How to use the following piece of rsync command in subprocess call?

description: Use the following piece of rsync command in subprocess call


code: MyModel.all().filter('prop >=', prefix).filter('prop <', prefix + u'\ufffd')

rawDescription: Implementing "Starts with" and "Ends with" queries with Google App Engine


code:
class TwitterC:
    def __init__(self, database):
        self.database = database
    def logtodatabase(self, tweet, timestamp):
        # Will log to the database
        database = sqlite3.connect(self.database) # Create a database file
        #(...)

rawDescription: How to deal with configuration variables in Python?

description: Deal with configuration variables in Python


code: r = requests.get('https://example.com', verify='/path/to/cetificate.pem')

rawDescription: Python Requests: .pem -> .crt + key

description: Python Requests: .pem -> .crt + key


code:
def makeCounter(seq):
    if hasOnlyHashables(seq):
        return OptimizedCounter(seq)
    else:
        return MyCounter(seq)

rawDescription: Should a class constructor return a subclass?


code:
ignored = {"folder_one", "folder_two", "folder_three"}
folders = [x for x in os.listdir(path) if x not in ignored]

rawDescription: Ignore some folders in os.listdir(path) Python


code:
import random
import time

def generate_samples():
    while True:
        input('Press ENTER to simulate next sample...')
        yield random.random()

def period_elapsed(period_start, period_duration):
    return period_start + period_duration < time.time()

def collect_buffers(samples, buffer_period):
    buffer_time = time.time()
    buffer_samples = []
    for sample in samples:
        buffer_samples.append(sample)
        if period_elapsed(buffer_time, buffer_period):
            yield buffer_samples
            buffer_samples = []
            buffer_time = time.time()

def post_buffers(buffers, url):
    for b in buffers:
        requests.post(url, data=json.dumps(buffer))

post_buffers(collect_buffers(generate_samples(), 300), 'http://localhost:3000')

rawDescription: Scheduling periodic uploads, good practice?


code:
#!/usr/bin/python
import webbrowser,subprocess
from time import sleep
webbrowser.open("https://vimeo.com/95250540")
sleep(30) # You can adjust it according to you internet speed.
subprocess.call(["xdotool","mousemove","800","500","click","1"])

rawDescription: Python Script to play a Vimeo Video

description: Python Script to play a Vimeo Video


code:
files = QtGui.QFileDialog.getOpenFileNames(self.dlg, "Select one or more files to open", os.getenv("HOME"),'.sql (*.sql)')

if files:
    model = QStandardItemModel()
    for file in files:
        item = QStandardItem('%s' % file)
        item.setCheckable(True)
        model.appendRow(item)
    self.dlg.DatacheckerlistView2.setModel(model)
    self.dlg.DatacheckerlistView2.show()

rawDescription: How to display multiple filenames with checkboxes inside the listview using pyqt

description: Display multiple filenames with checkboxes inside the listview using pyqt


code:
def time_difference(datetime_time):
    delta = datetime.now() - datetime_time
    return int(delta.total_seconds())

rawDescription: How to convert datetime to timestamp Python

description: Convert datetime to timestamp Python


code:
sharedFilterQuery = '''WITH    RECURSIVE
        q AS
        (
        SELECT  h.*
        FROM    "Selection"."FilterFolder" h
        join "Selection"."Filter" f
        on f."filterFolderId" = h.id
        WHERE   f.id = :filterId
        UNION
        SELECT  hp.*
        FROM    q
        JOIN    "Selection"."FilterFolder" hp
        ON      hp.id = q."parentFolderId"
        )
SELECT  f.id
FROM    "Selection"."Filter" f
where f.id = :filterId and
(f."createdByUserId" = 1 or
exists(select 1 from q where "isShared" = TRUE LIMIT 1))
'''

inClause = text(sharedFilterQuery,bindparams=[bindparam('filterId',filterId)])

f = session.query(Filter)\
.filter(Filter.description == None)\
.filter(Filter.id.in_(inClause)).first()

rawDescription: SQLAlchemy - Combine Textual query with a filter


code:
invalid_mask = np.isnan(imp.statistics_)
valid_mask = np.logical_not(invalid_mask)
valid_idx, = np.where(valid_mask)

rawDescription: Know feature names after imputation

description: Know feature names after imputation


code:
class Foo :
    def call(self) :
        pass

foo = Foo()
foo.call() #1
Foo.call(foo) #2

rawDescription: 'Self' of python vs 'this' of cpp/c#

description: 'Self' of python vs 'this' of cpp/c#


code:
if all([b == choice for b in board[0:2]]):
   ...

rawDescription: I want to go thought list with if to check if multiple elements are equal to that I want


code:
with open('out.txt', 'a') as f:
    for i in range(0,2):
        x[i] = np.array([1,2,3,8,3])
        np.savetxt(f, x[i])

rawDescription: python, save data to file in loop

description: Python, save data to file in loop


code: np.sum(frame[:, :, 0])

rawDescription: In python what is the most efficient way to get the sum of values in a 2d numpy array?


code:
import umpy as np
import matplotlib.pyplot as plt
mean, cov, n_samples = np.array([0.,0.]), np.array([[1.0,0.5],[0.5,1.0]]), 100
data=np.random.multivariate_normal(mean,cov,size=n_samples)
pdf = np.zeros(data.shape[0])
cons = 1./((2*np.pi)**(data.shape[1]/2.)*np.linalg.det(cov)**(-0.5))
X, Y = np.meshgrid(data.T[0], data.T[1])
def pdf(point):
  return cons*np.exp(-np.dot(np.dot((point-mean),np.linalg.inv(cov)),(point-mean).T)/2.)
zs = np.array([pdf(np.array(ponit)) for ponit in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)
fig = plt.figure()
ax3D = fig.add_subplot(111, projection='3d')
surf = ax3D.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,linewidth=0, antialiased=Fals)
surf.show()

rawDescription: Bivariate Gaussian density function in Numpy and Matplotlib


code:
import subprocess
import shlex                          # to split the command that follows
command = 'ffmpeg -i sample.avi'      # your command goes here
subprocess.call(shlex.split(command))

rawDescription: capture screenshot/frame of a video file

description: Capture screenshot/frame of a video file


code: return render_to_response('ftest/display.html', {'activation_key': activation_key})

rawDescription: How do you print a hash in Django 1.7 and store it in a database?

description: Print a hash in Django 1.7 and store it in a database


code:
@property
def ratio_covered(self):
    """Return a numerator and denominator for the coverage ratio."""
    numerator = self.n_executed + self.n_executed_branches
    denominator = self.n_statements + self.n_branches
    return numerator, denominator

rawDescription: How does coverage calculate its percentages?


code:
# for the min + 1
sorted(glob.iglob('*.log'), key=os.path.getctime)[1]

# for the newest
sorted(glob.iglob('*.log'), key=os.path.getctime)[-1]

# for the second newest ( max - 1)
sorted(glob.iglob('*.log'), key=os.path.getctime)[-2]

rawDescription: python second newest file

description: Python second newest file


code:
from scrapy import signals
from scrapy.xlib.pydispatch import dispatcher

class ProductSpider(Spider):
    name = "debug1"
    start_urls = ['http://www.test.tw/in/5/']

    def __init__(self):
        self.driver = webdriver.Firefox()
        dispatcher.connect(self.close, signals.spider_closed)

    def close(self, spider):
        self.driver.quit()

    def parse(self, response):
        self.driver.get(response.url)
        WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.media-body")))

    def spider_detail(self, spider):
        self.driver.close()

rawDescription: selenium: driver.close() from next function

description: Selenium: driver.close() from next function