code:
#!/usr/bin/env python

''' Text Location Demo
    Open a Tkinter window just under the location of the insertion cursor
    of a Text widget.

    See http://stackoverflow.com/q/34237313/4014959

    Written by PM 2Ring 2015.12.12
'''

import Tkinter as tk

#Some random text to display in the Text widget
lorem_ipsum = '''Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Aenean lacinia tortor quis quam vehicula semper. Curabitur
faucibus, purus a egestas bibendum, velit metus hendrerit nulla, non
lobortis dolor mi in dolor. Aliquam ultrices felis sit amet dolor
gravida, id ullamcorper odio rutrum. Fusce consectetur tempor nibh, non
dictum dolor dictum nec. In hac habitasse platea dictumst. Morbi laoreet
consequat metus, at lacinia nisl suscipit id. Quisque vitae sodales
velit, a lobortis nisl. Praesent varius convallis efficitur. Vivamus
fringilla at risus nec viverra. Proin suscipit, lorem sed laoreet
ultricies, velit massa ornare nunc, vel egestas nibh ex vitae leo.'''

lorem_ipsum = lorem_ipsum.replace('\n', ' ')

class TextLocationDemo(object):
    ''' Text widget cursor location demo '''
    def __init__(self):
        root = tk.Tk()
        root.title("Text Location Demo")

        tk.Button(root, text="Show cursor location",
            command=self.location_cb).pack()

        # Create a Text widget, with word wrapping
        self.textwidget = tw = tk.Text(root, wrap=tk.WORD)
        tw.pack()
        tw.insert(tk.END, lorem_ipsum)

        root.mainloop()

    def alert(self, geometry, msg):
        ''' Display `msg` in an Alert with given geometry,
            which is a tuple of (width, height, ox, oy)
        '''
        top = tk.Toplevel()
        # widget geometry parameter must be given in X windows format
        top.geometry("%dx%d%+d%+d" % geometry)

        msg = tk.Message(top, text=msg, width=geometry[0])
        msg.pack()

        button = tk.Button(top, text="Ok", command=top.destroy)
        button.pack()

    def location_cb(self):
        ''' Determine the location of the insertion cursor
            and display it in a window just under that location
        '''
        w = self.textwidget

        # Get the Text widget's current location
        pos_x, pos_y = w.winfo_rootx(), w.winfo_rooty()

        # Get the bounding box of the insertion cursor
        cursor = tk.INSERT
        bbox = w.bbox(cursor)
        if bbox is None:
            print('Cursor is not currently visible. Scrolling...')
            w.see(cursor)
            bbox = w.bbox(cursor)

        bb_x, bb_y, bb_w, bb_h = bbox

        #Open a window just beneath the insertion cursor
        width = 200
        height = 80
        ox = pos_x + bb_x
        oy = pos_y + bb_y + bb_h
        s = 'Cursor: (%d, %d)' % (ox, oy)
        print(s)

        geometry = (width, height, ox, oy)
        self.alert(geometry, s)

TextLocationDemo()

rawDescription: Make a new window open below the blinking cursor using Tkinter


code:
#! /usr/bin/python3.2

def sign(x): return 0 if not x else x // abs(x)

def extrema (l):
    return [l[0]] + [e for i, e in enumerate(l[:-1]) if i and sign(e-l[i-1])==sign(e-l[i+1])] + [l[-1]]

l1 = [1, 3, 9, 1, 2, 7, 8]
print (extrema (l1))

rawDescription: Contracting in python

description: Contracting in python


code:
def distance(self, other):
    dist = math.hypot(self.x - other.x, self.y - other.y)
    return dist

rawDescription: Defining Python Classes

description: Defining Python Classes


code:
import numpy as np
np.array([[[datetime.now(),np.zeros(2)] for x in range(10)]])

rawDescription: Create a list of int & DateTime in Python


code:
import matplotlib.pyplot as plt

fig = plt.figure()

plt.subplot(221) # 2 rows, 2 columns, plot 1
plt.plot([1,2,3])

plt.subplot(222) # 2 rows, 2 columns, plot 2
plt.plot([3,1,3])

plt.subplot(223) # 2 rows, 2 columns, plot 3
plt.plot([3,2,1])

plt.subplot(224) # 2 rows, 2 columns, plot 4
plt.plot([1,3,1])

plt.show()

fig.savefig('test.pdf')

rawDescription: plotting multiple graph from a csv file and output to a single pdf/svg

description: Plotting multiple graph from a csv file and output to a single pdf/svg


code:
keylist = dict_1.keys()
array_1 = numpy.array([dict_1[key] for key in keylist])
array_2 = numpy.array([dict_2[key] for key in keylist])

if numpy.allclose(array_1, array_2):
    print('Equal')
else:
    print('Not equal')

rawDescription: Compare Dictionaries for close enough match


code:
from urllib import urlopen
import re

def run():
    re1 = '^RUN'
    re2 = '^    "--url'
    file_url = "https://raw.githubusercontent.com/bgruening/docker-recipes/master/galaxy-exom-seq/Dockerfile"
    data = urlopen(file_url)
    for line in data:
        if re.search(re1, line) or re.search(re2, line):
            print(line.rstrip('\\\n'))

if __name__ == '__main__':
    run()

rawDescription: how to concatenate multiple lines separated by \

description: Concatenate multiple lines separated by \


code:
while True:
    cmds.pickWalk(d='left')
    children = cmds.listRelatives(cmds.ls(sl=True), children=True, typ='transform')
    if children:
        break

rawDescription: Item highlight for only items with child items


code:
list_a = [0,1,2,3,4]
list_b = ["a", "b", "c"]
pos    = [0, 2, 4]

assert(len(list_b) == len(pos))
acc = 0
for i in range(len(list_b)):
    list_a.insert(pos[i]+acc, list_b[i])
    acc += 1

print(list_a)

rawDescription: How to insert multiple values by index into list at one time

description: Insert multiple values by index into list at one time


code:
from itertools import tee, filterfalse
def partition(pred, iterable):
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2)

rawDescription: Is there a functional programming idiom for filtering a list into trues and falses?


code:
def f():

    import __main__

    __main__.g()

rawDescription: How exactly do modules in Python work?

description: How exactly do modules in Python work


code:
from __future__ import division
import csv
from collections  import defaultdict

def default_factory():
   return { "sum": 0, "max": None, "min": None, "count": 0}

reader = csv.DictReader(open(r'sd.csv'))

dates = defaultdict(default_factory)
rows = []
for row in reader:
    date = row["Date"]
    sd = int(row["Snowdepth"])
    rows.append([date, sd])
    month = date.split("/")[0]
    r = dates[month]
    r["sum"] += sd
    max = r["max"]
    r["max"] = sd if max is None else sd if sd > max else max
    min = r["min"]
    r["min"] = sd if min is None else sd if sd < min else min
    r["count"] += 1

for date in dates:
    r = dates[date]
    r["avg"] = r["sum"]/r["count"]

writer = csv.writer(open(r'TestAvg.csv', 'w'))
writer.writerow(["Date", "SD", "max", "min", "mean"])
for row in rows:
    r = dates[row[0].split("/")[0]]
    writer.writerow(row + [r["max"], r["min"], r["avg"]])

rawDescription: Aggregate daily data to calculate monthly average


code:
import os
import shutil

gid = 20      # Target group id
uid = 501     # Target user id

os.setegid(gid)
os.seteuid(uid)

from_file = '/var/root/rootfile'       # File to copy from (tested on OS X)
to_file = 'rootfile'                   # Filename to copy to
shutil.copyfile(from_file, to_file)

# Switch back to root
os.setegid(0)
os.seteuid(0)

rawDescription: create a file from python with owner specified

description: Create a file from python with owner specified


code:
if isinstance(var, numbers.Integral):
    pass # whatever

rawDescription: Version agnotstic checking if a variable is an integer?


rawDescription: Output file formatting

description: Output file formatting


code:
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_selection import SelectPercentile
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline

def read_input(path):
    with open(path) as handle:
        lines = (line.rsplit(",", 1) for line in handle)
        return [text for text, label in lines]

# Assuming each line in ``neg5000.csv`` and ``pos5000.csv`` is a
# UTF-8-encoded tweet.
neg_tweets = read_input("neg5000.csv")
pos_tweets = read_input("pos5000.csv")

X = np.append(neg_tweets, pos_tweets)
y = np.append(np.full(len(neg_tweets), -1, dtype=int),
              np.full(len(pos_tweets), 1, dtype=int))

p = Pipeline([
    ("vectorizer", CountVectorizer()),
    ("selector", SelectPercentile(percentile=20)),
    ("nb", MultinomialNB())
])

p.fit(X, y)
print(p.predict(["I love this car"]))

rawDescription: How to improve my feature selection for a NB classifier?

description: Improve my feature selection for a NB classifier


code:
try:
    job = session.query(Jobs).with_lockmode('update').filter(
         Jobs.started == None).first()
    # do something
    session.commit()
except Exception as exc:
    # debugs an exception
    session.rollback()

rawDescription: sqlalchemy concurrency update issue

description: Sqlalchemy concurrency update issue


code:
import sys
import time
from PyQt4.QtGui import QApplication, QWidget
from PyQt4.QtCore import QTimer, Qt

class MyWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.timer = QTimer()
        self.timer.setInterval(5000)
        self.timer.timeout.connect(self.check_state)
        self.timer.start()

    def check_state(self):
        if self.windowState() == Qt.WindowMinimized:
            # Window is minimised. Restore it.
            self.setWindowState(Qt.WindowNoState)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    widget = MyWidget()
    widget.show()
    sys.exit(app.exec_())

rawDescription: PyQt4 how to restore a minimized window?

description: PyQt4 how to restore a minimized window


code:
import webapp2
import StringIO

class MainPage(webapp2.RequestHandler):
   def get(self):
     old_stdout = sys.stdout
     new_stdout = StringIO.StringIO()
     sys.stdout = new_stdout
     mainfunc()
     self.response.out.write(new_stdout.getvalue())
     sys.stdout = old_stdout

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

rawDescription: Does Google App Engine actually implement "normal" CGI?


code:
import scrapy
from scrapy.exceptions import CloseSpider
from scrapy.spider import BaseSpider
from scrapy.http import Request

class Product(scrapy.Item):
    brand = scrapy.Field()
    title = scrapy.Field()

class aqaqspider(BaseSpider):
    name = "jabong"
    allowed_domains = ["jabong.com"]
    start_urls = [
        "http://www.jabong.com/women/clothing/womens-tops/?page=1",
    ]
    page = 1

    def parse(self, response):
        products = response.xpath("//li[@data-url]")

        if not products:
            raise CloseSpider("No more products!")

        for product in products:
            item = Product()
            item['brand'] = product.xpath(".//span[contains(@class, 'qa-brandName')]/text()").extract()[0].strip()
            item['title'] = product.xpath(".//span[contains(@class, 'qa-brandTitle')]/text()").extract()[0].strip()
            yield item

        self.page += 1
        yield Request(url="http://www.jabong.com/women/clothing/womens-tops/?page=%d" % self.page,
                      headers={"Referer": "http://www.jabong.com/women/clothing/womens-tops/", "X-Requested-With": "XMLHttpRequest"},
                      callback=self.parse,
                      dont_filter=True)

rawDescription: How to scrape website with infinte scrolling?

description: Scrape website with infinte scrolling


code:
start = os.times()
limit = 5  # seconds of user time
while True:
    # your code here
    check = os.times()
    if check.user - start.user > limit:
        break

rawDescription: How to keep track of execution time?

description: Keep track of execution time


code:
def mykdeplot(df, var, width):
    sns.kdeplot(np.array(getattr(df[df.Group == 'a'], var)), bw=width, label = "Group A")
    sns.kdeplot(np.array(getattr(df[df.Group == 'b'], var)), bw=width, label = "Group B")

mykdeplot(df, 'X1', 3)

rawDescription: How to write a function that uses a pandas data frame variable as input?

description: Write a function that uses a pandas data frame variable as input


code:
formats = {"U": {"text": "upper case", "func": str.upper},
           "L": {"text": "lower case", "func": str.lower},
           "C": {"text": "Capitalization", "func": lambda x: x}
          }

data = '"The most profound technologies are those that disappear: they weave themselves into fabric of everyday life until are indistinguishable from it" [Mark Weiser, The Computer for the 21st Century, Scientific American, Sept. 1991]'

for c in formats:
    print('Press "{}" and "Enter" for {}.'.format(c, formats[c]['text']))

letter = input("Please type a letter and press enter: ")
if letter in formats:
    print(formats[letter]['func'](data))

rawDescription: invalid syntax error, what do i do?

description: Invalid syntax error, what do i do


code:
import tornado.ioloop
import tornado.web
import tornado.websocket

from tornado.options import parse_command_line
from tornado import gen

import logging
import tornadoredis
import json

from urllib.parse import urlparse

from django.core.management.base import NoArgsCommand
from django.conf import settings

logging = logging.getLogger('base.tornado')

# store clients in dictionary..
clients = dict()

# REDIS_URL = 'redis://localhost:6379/'
# REDIS_UPDATES_CHANNEL = 'django_bus'

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def __init__(self, *args, **kwargs):
        self.client_id = None
        self._redis_client = None
        super(WebSocketHandler, self).__init__(*args, **kwargs)
        self._connect_to_redis()
        self._listen()

    def open(self, *args):
        self.client_id = self.get_argument("Id")
        self.stream.set_nodelay(True)
        clients[self.client_id] = self

    def on_message(self, message):
        """
        :param message (str, not-parsed JSON): data from client (web browser)
        """
        print("on message")

    @gen.coroutine
    def _on_update(self, message):
        """
        Receive Message from Redis when data become published and send it to selected client.
        :param message (Redis Message): data from redis
        """
        body = json.loads(message.body)
        if self.client_id == body['client_id']:
            self.write_message(message.body)

    @tornado.gen.engine
    def _listen(self):
        """
        Listening chanel 'REDIS_UPDATES_CHANNEL'
        """
        yield tornado.gen.Task(self._redis_client.subscribe, settings.REDIS_UPDATES_CHANNEL)
        self._redis_client.listen(self._on_update)

    def on_close(self):
        """
        When client will disconnect (close web browser) then shut down connection for selected client
        """
        if self.client_id in clients:
            del clients[self.client_id]
            self._redis_client.unsubscribe(settings.REDIS_UPDATES_CHANNEL)
            self._redis_client.disconnect()

    def check_origin(self, origin):
        """
        Check if incoming connection is in supported domain
        :param origin (str): Origin/Domain of connection
        """
        return True

    def _connect_to_redis(self):
        """
        Extracts connection parameters from settings variable 'REDIS_URL' and
        connects stored client to Redis server.
        """
        redis_url = settings.REDIS_URL
        parsed = urlparse(redis_url)
        self._redis_client = tornadoredis.Client(host=parsed.hostname, port=parsed.port)
        self._redis_client.connect()

app = tornado.web.Application([
    (r'/socket', WebSocketHandler),
])

class Command(NoArgsCommand):
    def handle_noargs(self, **kwargs):
        logging.info('Started Tornado')
        parse_command_line()
        app.listen(8888)
        tornado.ioloop.IOLoop.instance().start()

rawDescription: Tornado websocket + Redis

description: Tornado websocket + Redis


code:
from selenium import webdriver

def soup_maker(url):
    driver = webdriver.Firefox()  # could also be Chrome(), PhantomJS() or other
    driver.get(url)

    # you might also need an Explicit Wait here to wait for the page to load
    # see http://selenium-python.readthedocs.org/waits.html#explicit-waits

    markup = driver.page_source
    driver.close()
    soup = bs(markup, "html.parser")
    return soup

rawDescription: How to get images from link?

description: Get images from link


code:
soup = BeautifulSoup(open("output.html"))
doc = open("output.html", "r").read()
tree = etree.HTML(doc)

rawDescription: using path and beautiful soup on html file converted from pdf

description: Using path and beautiful soup on html file converted from pdf


code:
from Tkinter import *
import cv2.cv as cv

root = Tk()

w = Canvas(root, width=500, height=300, bd = 10, bg = 'white')
w.grid(row = 0, column = 0, columnspan = 2)

b = Button(width = 10, height = 2, text = 'Button1')
b.grid(row = 1, column = 0)
b2 = Button(width = 10, height = 2, text = 'Button2')
b2.grid(row = 1,column = 1)

cv.NamedWindow("camera",1)
capture = cv.CaptureFromCAM(0)

while True:
    img = cv.QueryFrame(capture)
    canvas.create_image(0,0, image=img)
    if cv.WaitKey(10) == 27:
        break

root.mainloop()

rawDescription: How to give Start,stop,capture,Close buttons in Opencv Cam window in python

description: Give Start,stop,capture,Close buttons in Opencv Cam window in python


code:
list(np.arange(5))
type(list(np.arange(5)))
type(list(np.arange(5))[0])
np.arange(5).tolist()
type(np.arange(5).tolist())
type(np.arange(5).tolist()[0])

rawDescription: Why does json.dumps(list(np.arange(5))) fail while json.dumps(np.arange(5).tolist()) works


rawDescription: Django query with an aggregate function

description: Django query with an aggregate function


rawDescription: How do you force wx.ListCtrl scroll bars to auto-lock to the bottom so that the most recent data is shown in the window?

description: Force wx.ListCtrl scroll bars to auto-lock to the bottom so that the most recent data is shown in the window


code:
from contextlib import contextmanager
import unittest

@contextmanager
def resource_manager():
    yield 'foo'

class MyTest(unittest.TestCase):

    def run(self, result=None):
        with resource_manager() as resource:
            self.resource = resource
            super(MyTest, self).run(result)

    def test(self):
        self.assertEqual('foo', self.resource)

unittest.main()

rawDescription: In python, is there a good idiom for using context managers in setup/teardown


code:
actual_clients_emails, actual_client_names = zip(
    *[(partner.email, partner.name)
      for partner in op_client.ResPartner.browse([])])

rawDescription: Create a tuple of lists from a list

description: Create a tuple of lists from a list


code:
degree_list = sorted(
    node_degree,
    key=lambda k: (node_degree[k], node_volumes[k]),
    reverse=True,
)

rawDescription: Multi-Factor sorting of a dictionary in python


code:
import threading
import datetime
import time
import os

def hot_temp():
    with open("/sys/bus/w1/devices/28-0216019bb8ff/w1_slave") as tfile:
        next(tfile)
        secondline = next(tfile)
    temperaturedata = secondline.split(" ")[9]
    temperature = float(temperaturedata[2:])
    temperature = temperature / 1000
    if temperature <= 20.000:
        os.system("sudo python /var/www/html/scripts/heaton.py")
        output = temperature
        with open('/var/www/html/log.txt', 'a') as f:
            print >> f, datetime.datetime.now().time(), "Current Temp: ", output, " (HEATING)"
    elif temperature >= 20.000:
        os.system("sudo python /var/www/html/scripts/heatoff.py")
        output = temperature
        with open('/var/www/html/log.txt', 'a') as f:
            print >> f, datetime.datetime.now().time(), "Current Temp: ", output, "(COOLING)"
    elif temperature >= 30.000:
        os.system("sudo python /var/www/html/scripts/mailheaton.py")
    elif temperature <= 10.000:
        os.system("sudo python /var/www/html/scripts/mailheatoff.py")
    return temperature

while True:
    output = hot_temp()
    with open('/var/www/html/output/hottemp.html', 'w') as f:
        print >> f, output
    time.sleep(1)

rawDescription: Python running script when it shouldn't

description: Python running script when it shouldn't


rawDescription: Slice to " "space in python

description: Slice to " "space in python


code:
import csv

#
# Row tests
#

def test_notblank(row):
    return any(len(i) for i in row)

def test_bnumeric(row):
    return row[1].isdigit()

def do_tests(row, tests=[test_notblank, test_bnumeric]):
    return all(t(row) for t in tests)

#
# Row processing
#

def process_splitb(row):
    b = row[1].split('.')
    row[1] = b[0]
    row.append(b[1])
    return row

def do_processes(row, processes=[process_splitb]):
    for p in processes:
        row = p(row)
    return row

def main():
    with open("in.csv","rb") as inf, open("out.csv","wb") as outf:
        incsv = csv.reader(inf)
        outcsv = csv.writer(outf)

        outcsv.writerow(incsv.next())    # pass header row
        outcsv.writerows(do_processes(row) for row in incsv if do_tests(row))

if __name__=="__main__":
    main()

rawDescription: How to perform multiple changes to a csv file without intervening writes

description: Perform multiple changes to a csv file without intervening writes


code:
from django.forms.fields import DateField

fld = DateField()
dt = request.GET.get('date', '')
formatted_datetime = fld.to_python(dt)

rawDescription: How to convert a string into a localised date in django

description: Convert a string into a localised date in django


code:
rules = (Rule(SgmlLinkExtractor(allow=r"/page/\d+", restrict_xpath=('xxxxx',)),
              callback="details", follow= True),)

rawDescription: get sgml allow regex for "example.xom/page/200/"

description: Get sgml allow regex for "example.xom/page/200/"


code: itertools.product(mykeys, repeat=3)

rawDescription: Cycle through all possible 3 letter combinations


code:
import numpy as np
np.savetxt("foo.csv", np.array(final).T, delimiter=",")

rawDescription: How to print a list of arrays transposed in a csv file

description: Print a list of arrays transposed in a csv file


code:
import tkinter as tk

class GUI(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        mainLabel = tk.Label(self, text='Example for pop up input box')
        mainLabel.pack()

        mainButton = tk.Button(self, text='Click me', command=self.on_click)
        mainButton.pack()

        top = self.top = tk.Toplevel(self)
        myLabel = tk.Label(top, text='Enter your username below')
        myLabel.pack()

        self.myEntryBox = tk.Entry(top)
        self.myEntryBox.pack()

        mySubmitButton = tk.Button(top, text='Hello', command=self.send)
        mySubmitButton.pack()

        top.withdraw()

    def send(self):
        self.username = self.myEntryBox.get()
        self.myEntryBox.delete(0, 'end')
        self.top.withdraw()
        print(self.username)

    def on_click(self):
        self.top.deiconify()

gui = GUI()
gui.mainloop()

rawDescription: Tkinter Button does not appear on TopLevel?


code:
s = "Good muffins cost $3.88\nin New York.  Please buy me\n"
ll = [[word_tokenize(w), ' '] for w in s.split()]
list(itertools.chain(*list(itertools.chain(*ll))))

rawDescription: How can I use word_tokenize in nltk and keep the spaces?

description: Use word_tokenize in nltk and keep the spaces


code:
a
int(''.join(str(i) for i in a), 2)

rawDescription: Converting an array of 0 and 1 to integer


code:
class Codons(object):

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

        def codons(self, frame_one, frame_two, frame_three):

                while frame_one <=len(self.seq):
                    yield (self.seq[frame_one:frame_one+3])
                    frame_one += 3

                while frame_two <=len(self.seq):
                    yield (self.seq[frame_two:frame_two+3])
                    frame_two += 3

                while frame_three <=len(self.seq):
                    yield (self.seq[frame_three:frame_three+3])
                    frame_three += 3

test_codons = Codons("ATCGTG-")

val = test_codons.codons(0,1,2)

print("Codons are: ")
for i in val:
        print(i)

print("")

rawDescription: Reading at three different frames

description: Reading at three different frames


code:
from PIL import Image

img = Image.open(r'yRc2a.png')
img = img.convert('RGBA')
img = img.crop((0, 0, 82, 82))
img.save(r'out.png')

rawDescription: How to read a bitmap file and crop it afterwards?

description: Read a bitmap file and crop it afterwards


code: cvr = final['First Word Sum'] / final['First Word Clicks']

rawDescription: Referencing Column Titles That Contain Spaces in Python 3 (Pandas)


rawDescription: Django one to one relation queryset

description: Django one to one relation queryset


rawDescription: Tweepy performing search only on letters not whole word


code:
domain = 'subdomain.domain.ext'
name, ext = domain.split('.')[-2:]

rawDescription: python domain name split name and extension

description: Python domain name split name and extension


code:
import os
import urllib

DOWNLOADS_DIR = '/python-downloader/downloaded'

# For every line in the file
for url in open('urls.txt'):
    # Split on the rightmost / and take everything on the right side of that
    name = url.rsplit('/', 1)[-1]

    # Combine the name and the downloads directory to get the local filename
    filename = os.path.join(DOWNLOADS_DIR, name)

    # Download the file if it does not exist
    if not os.path.isfile(filename):
        urllib.urlretrieve(url, filename)

rawDescription: Download files from a list if not already downloaded


code:
import numpy
a = numpy.zeros(3)
b = numpy.ones(3)
numpy.vstack((a,b)).T

rawDescription: Bind columns (from vectors) for numpy

description: Bind columns (from vectors) for numpy


rawDescription: Heroku endpoint

description: Heroku endpoint


code:
class Building():
    def __init__(self):
        self.rooms = []

b = Building()
b.rooms.append(Room(room_type, days, occupied, when_free))

rawDescription: python class adds instances of itself to a list

description: Python class adds instances of itself to a list


code:
from collections import namedtuple
Person = namedtuple("Person", "name age")
Person("Alice", 33)
alice = _
bob = Person(age=27, name="Bob")
alice == bob
bob.age

rawDescription: Class versus list (accessors coding style)


code: list(itertools.product("ABCD", "1234"))

rawDescription: any python module can support enumerate 2 lists and do the "cross multiplication"?

description: Any python module can support enumerate 2 lists and do the "cross multiplication"


code:
soup = BeautifulSoup(page)
message = soup.find("script")

rawDescription: How to find a substring in a string - by specifying the beginning and end of it?

description: Find a substring in a string - by specifying the beginning and end of it


code:
#!/usr/bin/env python3
from functools import partial
from subprocess import Popen, PIPE, DEVNULL

def get_chunks(generator_command, convert_command, chunk_size=1024):
    with Popen(generator_command, stdin=DEVNULL,
               stdout=PIPE, stderr=DEVNULL) as generator_process, \
         Popen(convert_command, stdin=generator_process.stdout,
               stdout=PIPE, stderr=DEVNULL) as convert_process:
        yield from iter(partial(convert_process.stdout.read, chunk_size), b'')
    return generator_process.returncode, convert_process.returncode

rawDescription: Deadlock When Streaming From subprocess.Popen And Using Two Subcommands


code:
bmonth = self.get_argument('bmonth', '')
bday = self.get_argument('bday', '')
byear = self.get_argument('byear', '')

bd = datetime.datetime(int(byear), int(bmonth), int(bday))
min_age = datetime.timedelta(weeks = 52*13)
if datetime.datetime.now() - bd < min_age:
    response = tornado.escape.json_encode({"error":"true", "msg":
                     "You must be 13 years of age or older to join uSocial'N"})

rawDescription: Python age verification

description: Python age verification


code:
def veggies(foods):
  if not foods:
    return []
  if foods[0].is_vegetarian:
    return [foods[0]] + veggies(foods[1:])
  return veggies(foods[1:])

rawDescription: Return a list of vegans

description: Return a list of vegans


code:
def shape(self):
    return self.path()

rawDescription: How to get mouse hover events for shapes with a hole in a QGraphicsItem?

description: Get mouse hover events for shapes with a hole in a QGraphicsItem


code:
def bin2(x):
    binary_digits = []

    while x:
        binary_digits.append(x & 1)
        x >>= 1

    return "".join(str(digit) for digit in reversed(binary_digits))

rawDescription: Integer to binary without multiplication or division


code:
import requests
import json
def make_request(method, url, token ,data=None, params=None, headers=None, timeout=60):
    headers = {'x-li-format': 'json', 'Content-Type': 'application/json'}
    params = {}
    kw = dict(data=data, params=params, headers=headers, timeout=timeout)
    params.update({'oauth2_access_token': token})
    return requests.request(method.upper(), url, **kw)

def submit_share(comment, title, description, submitted_url, submitted_image_url, token):
    post = {
        'comment': comment,
        'content': {
        'title': title,
        'submitted-url': submitted_url,
        'submitted-image-url': submitted_image_url,
        'description': description
    },
    'visibility': {
        'code': 'anyone'
    }
    }
    url = 'https://api.linkedin.com/v1/people/~/shares'
    try:
        response = make_request('POST', url, token,data=json.dumps(post))
        response = response.json()
        return response
    except Exception:
        return False

rawDescription: Python Linkedin, How to share content on user's wall


code:
#!/usr/bin/env python

# Code goes here

rawDescription: Which Python intrpetor should I be putting in .py header?


code:
import configparser

class ConfigParserMultiOpt(configparser.RawConfigParser):
  """ConfigParser allowing duplicate keys. Values are stored in a list"""

  def __init__(self):
    configparser.RawConfigParser.__init__(self, empty_lines_in_values=False, strict=False)

  def _read(self, fp, fpname):
    """Parse a sectioned configuration file.

    Each section in a configuration file contains a header, indicated by
    a name in square brackets (`[]'), plus key/value options, indicated by
    `name' and `value' delimited with a specific substring (`=' or `:' by
    default).

    Values can span multiple lines, as long as they are indented deeper
    than the first line of the value. Depending on the parser's mode, blank
    lines may be treated as parts of multiline values or ignored.

    Configuration files may include comments, prefixed by specific
    characters (`#' and `;' by default). Comments may appear on their own
    in an otherwise empty line or may be entered in lines holding values or
    section names.
    """
    elements_added = set()
    cursect = None                        # None, or a dictionary
    sectname = None
    optname = None
    lineno = 0
    indent_level = 0
    e = None                              # None, or an exception
    for lineno, line in enumerate(fp, start=1):
      comment_start = None
      # strip inline comments
      for prefix in self._inline_comment_prefixes:
        index = line.find(prefix)
        if index == 0 or (index > 0 and line[index-1].isspace()):
          comment_start = index
          break
      # strip full line comments
      for prefix in self._comment_prefixes:
        if line.strip().startswith(prefix):
          comment_start = 0
          break
      value = line[:comment_start].strip()
      if not value:
        if self._empty_lines_in_values:
          # add empty line to the value, but only if there was no
          # comment on the line
          if (comment_start is None and
              cursect is not None and
              optname and
              cursect[optname] is not None):
              cursect[optname].append('') # newlines added at join
        else:
          # empty line marks end of value
          indent_level = sys.maxsize
        continue
      # continuation line?
      first_nonspace = self.NONSPACECRE.search(line)
      cur_indent_level = first_nonspace.start() if first_nonspace else 0
      if (cursect is not None and optname and
          cur_indent_level > indent_level):
          cursect[optname].append(value)
      # a section header or option header?
      else:
        indent_level = cur_indent_level
        # is it a section header?
        mo = self.SECTCRE.match(value)
        if mo:
          sectname = mo.group('header')
          if sectname in self._sections:
            if self._strict and sectname in elements_added:
              raise DuplicateSectionError(sectname, fpname,
                                          lineno)
            cursect = self._sections[sectname]
            elements_added.add(sectname)
          elif sectname == self.default_section:
            cursect = self._defaults
          else:
            cursect = self._dict()
            self._sections[sectname] = cursect
            self._proxies[sectname] = configparser.SectionProxy(self, sectname)
            elements_added.add(sectname)
          # So sections can't start with a continuation line
          optname = None
        # no section header in the file?
        elif cursect is None:
          raise MissingSectionHeaderError(fpname, lineno, line)
        # an option line?
        else:
          mo = self._optcre.match(value)
          if mo:
            optname, vi, optval = mo.group('option', 'vi', 'value')
            if not optname:
              e = self._handle_error(e, fpname, lineno, line)
            optname = self.optionxform(optname.rstrip())
            if (self._strict and
              (sectname, optname) in elements_added):
              raise configparser.DuplicateOptionError(sectname, optname, fpname, lineno)
            elements_added.add((sectname, optname))
            # This check is fine because the OPTCRE cannot
            # match if it would set optval to None
            if optval is not None:
              optval = optval.strip()
              # Check if this optname already exists
              if (optname in cursect) and (cursect[optname] is not None):
                # If it does, convert it to a tuple if it isn't already one
                if not isinstance(cursect[optname], tuple):
                  cursect[optname] = tuple(cursect[optname])
                cursect[optname] = cursect[optname] + tuple([optval])
              else:
                cursect[optname] = [optval]
            else:
                # valueless option handling
                cursect[optname] = None
          else:
            # a non-fatal parsing error occurred. set up the
            # exception but keep going. the exception will be
            # raised at the end of the file and will contain a
            # list of all bogus lines
            e = self._handle_error(e, fpname, lineno, line)
    # if any parsing errors occurred, raise an exception
    if e:
        raise e
    self._join_multiline_values()

rawDescription: Handling duplicate keys with ConfigParser


code:
desc_vect = desc_vect.tocsr()

n_docs = desc_vect.shape[0]
tfidftables = [{} for _ in xrange(n_docs)]
terms = tfidf_vectorizer.get_feature_names()

for i, j in zip(*desc_vect.nonzero()):
    tfidftables[i][terms[j]] = X[i, j]

rawDescription: Linking text feature names to their tfidf value


code:
import string
import re
file = open('sample.txt')
numbers = [[int(num) for num in re.findall(r'\d+', i)] for i in file.readlines()]
#output [[100], [40], [160], [400], [700]]

rawDescription: separating strings and numbers in text file

description: Separating strings and numbers in text file


code:
lookup_table = dict( zip( old_num, new_num ) ) # create your translation dict
vect_lookup = np.vectorize( lookup_table.get ) # create a function to do the translation
ELEM[:, 1:] = vect_lookup( ELEM[:, 1:] ) # Reassign the elements you want to change

rawDescription: Renumbering a 1D mesh in Python

description: Renumbering a 1D mesh in Python


code: myList[:] = []

rawDescription: Is there a specific command to delete all elements of a list?


code:
from a import *
goodbye = hello
del hello

rawDescription: Can I import as only for a function, and have the rest imported as they are?

description: Import as only for a function, and have the rest imported as they are


code:
from selenium.webdriver.common.keys import Keys
driver.find_element_by_id('checkBoxClavier').send_keys( Keys.SPACE )

rawDescription: Python script with Selenium not able to click on a button


code:
import timeit
lst = range(10)
timeit.timeit('lst.index(9)', 'from __main__ import lst', number = 1000000)
timeit.timeit('from __main__ import lst', number = 1000000)

rawDescription: Timeit module - Passing objects to setup?


code:
import bz2

class SimpleBZ2File(object):

    def __init__(self,path,readsize=1024):
        self.decomp = bz2.BZ2Decompressor()
        self.rawinput = open(path,'rb')
        self.eof = False
        self.readsize = readsize
        self.leftover = ''

    def tell(self):
        return self.rawinput.tell()

    def __iter__(self):
        while not self.eof:
            rawdata = self.rawinput.read(self.readsize)
            if rawdata == '':
                self.eof = True
            else:
                data = self.decomp.decompress(rawdata)
                if not data:
                    continue #we need to supply more raw to decompress
                newlines = list(data.splitlines(True))
                yield self.leftover + newlines[0]
                self.leftover = ''
                for l in newlines[1:-1]:
                    yield l
                if newlines[-1].endswith('\n'):
                    yield newlines[-1]
                else:
                    self.leftover = newlines[-1]
        if self.leftover:
            yield self.leftover
        self.rawinput.close()

rawDescription: How to get the internal position while reading bzip2 file

description: Get the internal position while reading bzip2 file


rawDescription: to get particular value out of django array

description: To get particular value out of django array


code:
# Fetch all fields
allfields=jira.fields()
# Make a map from field name -> field id
nameMap = {field['name']:field['id'] for field in allfields}
# Fetch an issue
issue = jira.issue('ABC-1')
# You can now look up custom fields by name using the map
getattr(issue.fields, nameMap[custom_name])

rawDescription: jira python customfield

description: Jira python customfield


rawDescription: python: string of hex values to binary

description: Python: string of hex values to binary


code:
from collections import defaultdict
item = defaultdict(dict)

rawDescription: How can I initialize a Field() to contain a nested python dict?

description: Initialize a Field() to contain a nested python dict


code:
import random
source = [x,y,z]

deviationFromPoint = 10

for _ in range(numberOfAdditionalPoints):
  newCoords = [source[i] + random.random() * deviationFromPoint for i in range(3)]
  newPoint = Point(newCoords) # Or whatever constructor you have for your points.

rawDescription: generate a random cluster of points around a given point python

description: Generate a random cluster of points around a given point python


code:
exonstarts = [10,50,100]
exonends = [20,60,110]
zip(exonstarts, exonends)

rawDescription: Quick basic loop

description: Quick basic loop


code: html = urllib.urlopen(url).read()

rawDescription: Is it possible to force urllib to just fetch plain html, not images, scripts, etc?


code:
def permute(a, i, seen=set()):
    if i == len(a):
        if tuple(a) not in seen:
            seen.add(tuple(a))
            print(a)
    else:
        for j in xrange(i,len(a)):
            a[i], a[j] = a[j], a[i]
            permute(a, i + 1,seen)
            a[i], a[j] = a[j], a[i]

print(permute([1, 1, 3], 0))
[1, 1, 3]
[1, 3, 1]
[3, 1, 1]

rawDescription: python lists numbers

description: Python lists numbers


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

raw_data = np.random.random((30,30))

fig, axes = plt.subplots(ncols=3)

axes[0].imshow(raw_data, interpolation='nearest')
axes[0].set(title='Raw Data', xticks=[], yticks=[])

axes[1].imshow(ndimage.uniform_filter(raw_data, 3), interpolation='nearest')
axes[1].set(title='Uniform Filter', xticks=[], yticks=[])

axes[2].imshow(ndimage.gaussian_filter(raw_data, 3), interpolation='nearest')
axes[2].set(title='Gaussian Filter', xticks=[], yticks=[])

fig.tight_layout()
plt.show()

rawDescription: What is the equivalent of matlab's smooth3 function in python?


rawDescription: Easiest way to rm -rf in Python

description: Easiest way to rm -rf in Python


code:
from functools import wraps

class GenerativeBase(object):
    def _generate(self):
        s = self.__class__.__new__(self.__class__)
        s.__dict__ = self.__dict__.copy()
        return s

def _generative(func):
    @wraps(func)
    def decorator(self, *args, **kw):
        new_self = self._generate()
        func(new_self, *args, **kw)
        return new_self
    return decorator

class TaskQueue(GenerativeBase):
    @_generative
    def region(self, reg_id):
        self.reg_id = reg_id

    @_generative
    def task(self, callable, *args, **kw):
        self.tasks.append((callable, args, kw))

rawDescription: Python class method chaining

description: Python class method chaining


rawDescription: to keep a Tkinter widget on top of the others

description: To keep a Tkinter widget on top of the others


code:
import os
import urllib
import webapp2

from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers

class MainHandler(webapp2.RequestHandler):
  def get(self):
    upload_url = blobstore.create_upload_url('/upload', gs_bucket_name='bucket_name')
    self.response.out.write('')
    self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
    self.response.out.write("""Upload File: <input type="file" name="file">
 <input type="submit"
        name="submit" value="Submit"> </form>""")

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):
    upload_files = self.get_uploads('file')  # 'file' is file upload field in the form

    blob_info = upload_files[0]
    self.redirect('/serve/%s' % blob_info.key())

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, resource):
    resource = str(urllib.unquote(resource))
    blob_info = blobstore.BlobInfo.get(resource)
    self.send_blob(blob_info)

app = webapp2.WSGIApplication([('/', MainHandler),
                               ('/upload', UploadHandler),
                               ('/serve/([^/]+)?', ServeHandler)],
                              debug=True)

rawDescription: Examples of Google Cloud Storage Used With Google App Engine (Python)


code:
def prime(number):
    oldnum = number
    factor = 1
    while number > 1:
        factor += 1
        if number % factor == 0:
            if 1 < factor < oldnum:
                return False # is not prime
            number //= factor
    return True # is prime!

rawDescription: Prime number finder

description: Prime number finder


rawDescription: Python removing all negative values in array


code:
import os
import tempfile
import shutil
from contextlib import contextmanager

@contextmanager
def tempinput(file_):
    temp = tempfile.NamedTemporaryFile(delete=False)
    shutil.copyfileobj(file_, temp)
    temp.close()
    yield temp.name
    os.unlink(temp.name)

with tempinput(request.params['xls_file'].file) as tempfilename:
    workbook = xlrd.open_workbook(tempfilename)

rawDescription: How to read Excel files from a stream (not a disk-backed file) in Python?

description: Read Excel files from a stream (not a disk-backed file) in Python


code:
import numpy as np
s = '\x01\x05\x03\xff'
a = np.fromstring(s, dtype='uint8')

rawDescription: How do I create a numpy array from string?

description: Create a numpy array from string


code:
import tar
import os

path = "."

for root, dirs, files in os.walk(path):
    for name in files:
        file = os.path.join(root, name)
        tarfile.open(file)
        tar.extractall(in_the_subdirectory_of_the_tarfile)
        tar.close

rawDescription: Uncompress files for each subdirectory of each folder


code:
from random import randrange
channel_id = "%032x" % randrange(16**32)

from subprocess import Popen
# HERE YOU PASS ONLY THOSE PARAMETERS YOU WANT (i.e. without --disable-*)
# BUT YOU MAY NEED --dom-automation FOR SOME ROUTINES
chrome = Popen(" ".join([
    PATH_TO_CHROME_EXE,
    "--no-first-run", "--dom-automation",
    ("--testing-channel=\"NamedTestingInterface:%s\"" % channel_id),
]))

try:
    from selenium.webdriver.chrome.service import Service
    chromedriver_server = Service(PATH_TO_CHROMEDRIVER, 0)
    chromedriver_server.start()
    from selenium.webdriver import Remote
    driver = Remote(chromedriver_server.service_url,
        {"chrome.channel": channel_id, "chrome.noWebsiteTestingDefaults": True})

    driver.get(MY_WEBPAGE)
    # DO YOUR WORK

finally:
    chromedriver_server.stop()
    driver.quit()

chrome.kill()
chrome.wait()

rawDescription: how to override default set of chrome command line switches in selenium

description: Override default set of chrome command line switches in selenium


code:
def boolean_search_and_multi(self, text):
    and_tokens = self.tokenize(text)
    results = set(self._inverted_index[and_tokens[0]])
    for tok in and_tokens[1:]:
        results.intersection_update(self._inverted_index[tok])
    return list(results)

rawDescription: Python: intersection of lists/sets

description: Python: intersection of lists/sets


code:
# Simulate network
out = net.sim(x_test)

rawDescription: Neurolab - predicted values for test set


code:
import urllib
xml_file= urllib.urlopen("somefileID.xml")

rawDescription: Retrieve a page's XML for Python parsing


code:
from ast import literal_eval
with open('yourfile') as fin:
    your_list = literal_eval(fin.read())

rawDescription: Reading a list from a file, and converting it into a list of Python dictionaries


code:
import atomac, time
from atomac.AXKeyCodeConstants import *

# to allow me to make firefox frontmost while testing
time.sleep(5)

# get a reference to the running app
firefox = atomac.getAppRefByLocalizedName('Firefox')

# get the window of the reference
firefoxwindow = firefox.windowsR()[0]

# send key sequence to go to my home folder
firefoxwindow.sendKeyWithModifiers('h',[COMMAND,SHIFT])

# send key sequence to select first file there
firefoxwindow.sendKeyWithModifiers('a',[COMMAND])

# press the now active Open button
openbutton = firefoxwindow.buttons('Open')[0]
openbutton.Press()

rawDescription: How do I control a non-browser window that is part of Firefox?

description: Control a non-browser window that is part of Firefox


code:
baseprob = []

for i in range(1,s): #changed to do a range 1-s instead of 1000

     #must use the loop variable here, not s (s is always the same)
     matrix_n = numpy.linalg.matrix_power(matrix, i)

     baseprob.append(matrix_n.item(0))

rawDescription: Making histogram out of matrix entries?

description: Making histogram out of matrix entries


code:
from collections import defaultdict
dic = defaultdict(list)
dic['a'].extend(['1a','2a','3a'])
dic['a'].extend(['4a','5a'])
dic['b'].extend(['1b','2b'])

rawDescription: Python How can I get all values same name keys from dictionary


code:
class a:
    @classmethod
    def b(cls):
        print("hello")

a.b() #'hello'

rawDescription: how to use a method with no args in python?

description: Use a method with no args in python


code:
import threading, importedlib

class Child:
    def __init__(self, parent):
        self.parent=parent

    def run(self):
        importedlib.runajob(parent.VAL1, parent.VAL2)

class Mother(threading.Thread):
    def __init__(self,val1,val2):
        self.VAL1 = val1
        self.VAL2 = val2

    def connectandrun():
        c= Child(self)
        for i in range(5):
            c.run(i)

rawDescription: what's the alternative to nested classes in Python

description: What's the alternative to nested classes in Python


code:
from django.core import serializers
data = serializers.serialize("xml", SomeModel.objects.all())

rawDescription: How to generated xml file in Django

description: Generated xml file in Django


rawDescription: Regular Expression search/replace help needed, Python


code:
import os

devnull = open(os.devnull, 'w')
subprocess.call(shlex.split(
    '/usr/local/itms/bin/iTMSTransporter -m lookupMetadata '
    '-apple_id %s -destination %s' % (self,apple_id, self.destination)),
  stdout=devnull, stderr=devnull)

rawDescription: Suppressing output in python subprocess call


code:
from Tkinter import *
import sys
master = Tk()
def callback():
    master.destroy()
    sys.exit()
b = Button(master, text="Click to close", command=callback)
b.pack()
mainloop()

rawDescription: create a standalone py server application for mac

description: Create a standalone py server application for mac


code:
m = np.random.random((6, 2))
m
m.take([0, 2, 5], axis=0)

rawDescription: Slice numpy array wth list of wanted rows


rawDescription: XML file as input

description: XML file as input


code:
import numpy as np

# Generate some data that lies along a line

x = np.mgrid[-2:5:120j]
y = np.mgrid[1:9:120j]
z = np.mgrid[-5:3:120j]

data = np.concatenate((x[:, np.newaxis],
                       y[:, np.newaxis],
                       z[:, np.newaxis]),
                      axis=1)

# Perturb with some Gaussian noise
data += np.random.normal(size=data.shape) * 0.4

# Calculate the mean of the points, i.e. the 'center' of the cloud
datamean = data.mean(axis=0)

# Do an SVD on the mean-centered data.
uu, dd, vv = np.linalg.svd(data - datamean)

# Now vv[0] contains the first principal component, i.e. the direction
# vector of the 'best fit' line in the least squares sense.

# Now generate some points along this best fit line, for plotting.

# I use -7, 7 since the spread of the data is roughly 14
# and we want it to have mean 0 (like the points we did
# the svd on). Also, it's a straight line, so we only need 2 points.
linepts = vv[0] * np.mgrid[-7:7:2j][:, np.newaxis]

# shift by the mean to get the line in the right place
linepts += datamean

# Verify that everything looks right.

import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d as m3d

ax = m3d.Axes3D(plt.figure())
ax.scatter3D(*data.T)
ax.plot3D(*linepts.T)
plt.show()

rawDescription: Fitting a line in 3D

description: Fitting a line in 3D


code:
df['asq_cum']=df['asq'].cumsum()
df

rawDescription: Pandas and sum and cum sum in same dataframe


rawDescription: How to draw a matrix sparsity pattern with color code in python?

description: Draw a matrix sparsity pattern with color code in python


code:
import json
data = ["string", "string2", True, 20]
string_variable = json.dumps(data)
#
# now pass string_variable through drag and drop
#
returned = json.loads(string_variable)

rawDescription: How to set multiple items into a GtkSelection for Treeview drag and drop

description: Set multiple items into a GtkSelection for Treeview drag and drop


code:
from pprint import pprint
import requests

url = "http://irvingmasjid.org/salah2016.php"
response = requests.get(url)

pprint(response.json())

rawDescription: getting data from specific table/website using XPATH

description: Getting data from specific table/website using XPATH


code:
topping_list = ['ham', 'cheese']
Pizza.objects.filter(topping__name__in=topping_list)

rawDescription: django query with Q and multiple categories

description: Django query with Q and multiple categories


code:
#views.py
class SearchCandidate(generic.DetailView):

    model = Job
    template_name = 'dashboard/screening-results.html'

    def get_context_data(self, **kwargs):
        context = super(SearchCandidate, self).get_context_data(**kwargs)
        context['candidate_list'] = self.object.applied_to.filter(
            get_query(self.request.GET['q'], ['candidate__user__first_name', 'candidate__user__last_name'])
    ).order_by('candidate')

        return context

rawDescription: Django query in detailview

description: Django query in detailview


code:
for line in file:
    res =".".join(re.split(r'\(\d+\)', line))
    writer.write(res.strip('.'))

rawDescription: Python - Replace parenthesis with periods and remove first and last period


rawDescription: How to create a numpy matrix/2d array from multiple 2d arrays?

description: Create a numpy matrix/2d array from multiple 2d arrays


code:
import numpy as np
from numpy import linspace, array
from odeintw import odeintw
import matplotlib.pyplot as plt

def system(M, t):
    A, B, C = M
    dA_dt = A.dot(C) + B.dot(C)
    dB_dt = B.dot(C)
    dC_dt = C
    return array([dA_dt, dB_dt, dC_dt])

t = np.linspace(0, 1.5, 1000)

#A_initial= [1, 2, 2.3, 4.3, 2.1, 5.2, 2.13, 3.43]
A_initial = np.array([[1 + 2.1j, 2 + 5.2j], [2.3 + 2.13j, 4.3 + 3.43j]])

# B_initial= [7, 2.7, 1.23, 3.3, 3.1, 5.12, 1.13, 3]
B_initial = np.array([[7 + 3.1j, 2.7 + 5.12j], [1.23 + 1.13j, 3.3 + 3j]])

# C_initial= [0.5, 0.9, 0.63, 0.43, 0.21, 0.5, 0.11, 0.3]
C_initial = np.array([[0.5 + 0.21j, 0.9 + 0.5j], [0.63 + 0.11j, 0.43 + 0.3j]])

M_initial = np.array([A_initial, B_initial, C_initial])
sol = odeintw(system, M_initial, t)

A = sol[:, 0, :, :]
B = sol[:, 1, :, :]
C = sol[:, 2, :, :]

plt.figure(1)
plt.plot(t, A[:, 0, 0].real, label='A(t)[0,0].real')
plt.plot(t, A[:, 0, 0].imag, label='A(t)[0,0].imag')
plt.legend(loc='best')
plt.grid(True)
plt.xlabel('t')

A_evals = np.linalg.eigvals(A)

plt.figure(2)
plt.plot(t, A_evals[:,0].real, 'b.', markersize=3, mec='b')
plt.plot(t, A_evals[:,0].imag, 'r.', markersize=3, mec='r')
plt.plot(t, A_evals[:,1].real, 'b.', markersize=3, mec='b')
plt.plot(t, A_evals[:,1].imag, 'r.', markersize=3, mec='r')
plt.ylim(-200, 1200)
plt.grid(True)
plt.title('Real and imaginary parts of the eigenvalues of A(t)')
plt.xlabel('t')
plt.show()

rawDescription: How to plot the Eigenvalues when solving matrix coupled differential equations in PYTHON?

description: Plot the Eigenvalues when solving matrix coupled differential equations in PYTHON


rawDescription: how can limit the chracters in FloatField in django forms

description: How can limit the chracters in FloatField in django forms


code:
df *= 100
df = pandas.DataFrame(df, dtype=str)
df += '%'

ew = pandas.ExcelWriter('test.xlsx')
df.to_excel(ew)
ew.save()

rawDescription: Writing Percentages in Excel Using Pandas


rawDescription: how to translate "0x%llx" from C to python

description: Translate "0x%llx" from C to python


code: nose.run(argv=['me.py', '-V'])

rawDescription: Override existing configuration when using nose in Python in a script


code:
title = u"Klüft skräms inför på fédéral électoral große"
import unicodedata
unicodedata.normalize('NFKD', title).encode('ascii','ignore')
'Kluft skrams infor pa federal electoral groe'

rawDescription: Convert a Unicode string to a string in Python (containing extra symbols)


rawDescription: how to iterate over different kwargs?

description: Iterate over different kwargs


code:
cs = pyplot.contourf(x,y,z,levels=np.arange(50, 220, 20), cmap=pyplot.cm.jet, extend="both")
cs.cmap.set_under('k')
cs.set_clim(50, 210)
cb = pyplot.colorbar(cs)

rawDescription: Python matplotlib change default color for values exceeding colorbar range


code:
all_Lists = [list(np.random.randn(30).cumsum()) for i in range(10)]

fig, ax = plt.subplots()

for n, curv in enumerate(all_Lists):
    ax.cla()
    ax.plot(curv)
    fig.savefig()

rawDescription: Python: Pyplot in loop --> curves are cumulated per iteration, not separately plotted


code:
def _tot_get_deposit(self, cr, uid, ids, name, arg, context=None):
    res = {}
    results = []
    for deposit in self.browse(cr, uid, ids, context=context):
        sum = 0.0
        sum = A - B
        results.append( sum )
    return (res,results)

rawDescription: subtract two values in the field

description: Subtract two values in the field


code:
selected_classes = []
classes = sorted(classes, key=lambda c: c.score)
for clas in classes:
    if not clas.clashes_with(selected_classes):
        selected_classes.append(clas)

rawDescription: Automated Class timetable optimize crawler?


code:
from networkx.algorithms.traversal.depth_first_search import dfs_tree

subtree_at_2 = dfs_tree(t, 2)

rawDescription: subtree with networkX

description: Subtree with networkX


rawDescription: how to make a random text string csv comform with python?

description: Make a random text string csv comform with python


code:
import bisect
list_of_dates = [
    date(2015, 1, 15), date(2015, 2, 1), date(2015, 3, 31),
    date(2015, 4, 25), date(2015, 5, 23), date(2015, 6, 11)]
bisect.bisect(list_of_dates, date(2015, 4, 30))
bisect.bisect(list_of_dates, date(2015, 4, 25))
bisect.bisect_left(list_of_dates, date(2015, 4, 25))

rawDescription: How to find in a sorted list of dates where a specific date lies in between, in Python?

description: Find in a sorted list of dates where a specific date lies in between, in Python


code:
myRow = myTable(
          column_a = 'foo',
          column_b = 'bar')

myRow.column_c = 1 + 2

mySession.update(myRow)

rawDescription: Python - Import CSV file and save it into Database SQLAlchemy


code:
def is_prime(n):
    return all(n % i != 0 for i in range(2, n))

def order(numbers, current=[]):
    if not numbers:
        return current

    for i, n in enumerate(numbers):
        if current and not is_prime(n + current[-1]):
            continue

        result = order(numbers[:i] + numbers[i + 1:], current + [n])

        if result:
            return result

    return False

result = order(range(500))

for i in range(len(result) - 1):
    assert is_prime(result[i] + result[i + 1])

rawDescription: Code is taking too much time

description: Code is taking too much time


code:
class MyDelegate(QtGui.QItemDelegate):

    def createEditor(self, parent, option, index):
        if index.column() == 2:
            return super(MyDelegate, self).createEditor(parent, option, index)
        return None

    def setEditorData(self, editor, index):
        if index.column() == 2:
            # Gets display text if edit data hasn't been set.
            text = index.data(Qt.EditRole) or index.data(Qt.DisplayRole)
            editor.setText(text)

delegate = MyDelegate()
tableview.setItemDelegate(delegate)

rawDescription: Edit table in PyQt QAbstractTableModel without deletion of content


code:
from pylab import *
plot([1,3,2])
gca()
gca().add_patch(Rectangle((1,1),1,1))
savefig("rect.png")

rawDescription: Draw rectangle (add_patch) in pylab mode


code:
class getExistingDirectories(QFileDialog):
    def __init__(self, *args):
        QFileDialog.__init__(self, *args)
        self.setOption(self.DontUseNativeDialog, True)
        self.setFileMode(self.Directory)
        self.setOption(self.ShowDirsOnly, True)
        self.findChildren(QListView)[0].setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.findChildren(QTreeView)[0].setSelectionMode(QAbstractItemView.ExtendedSelection)

rawDescription: How to select multiple directories with KFileDialog?

description: Select multiple directories with KFileDialog


code:
@coroutine
def _threaded(self, count, target_func):
    """
    Given a target coroutine, spawn $count threads to run copies of them. In
    order to properly use this, do not call the coroutine before calling this,
    e.g.

        @coroutine
        def foo(self):
            ...

        def bar(self):
            ...
            self._threaded(10, self.foo)    # <- do not call self.foo,
                                            # just the reference

    @param count        The number of threads to spawn
    @param target_func  The reference to the target coroutine
    @returns            The subnet mask
    """
    result = None

    messages = Queue()

    def default_target_run(index):
        target = target_func()
        while True:
            item = messages.get()
            if item is GeneratorExit:
                target.close()
                return
            else:
                target.send({'index': index, 'item': item})

    # ensure code is testable
    target_run = default_target_run
    try:
        target_run = self._threaded.target_run
    except AttributeError:
        pass

    result = ThreadPool(count).map_async(target_run, range(count))

    try:
        while True:
            item = (yield)
            messages.put(item)
    except GeneratorExit:
        # allow all threads to quit
        # by making sure all of them receives the exit message
        for i in xrange(count):
            messages.put(GeneratorExit)

    result.ready()

rawDescription: Multiple threads with the same coroutine?


code:
def column_label(column_number):
    column_labels = []
    column_number = column_number + 1
    while column_number > 0:
        column_number, modulo = divmod(column_number - 1, 26)
        column_labels.append(string.uppercase[modulo])
    return ''.join(reversed(column_labels))

rawDescription: how to calculate a value from other fields in excel sheet using formulas

description: Calculate a value from other fields in excel sheet using formulas


code: Y = Y[random.choice(Y.keys())]

rawDescription: Networkx node traversal

description: Networkx node traversal


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

from matplotlib.table import Table

def table_plot(data):
    fig, ax = plt.subplots()
    ax.set_axis_off()

    tb = Table(ax, bbox=[0,0,1,1])

    nrows, ncols = data.shape
    width, height = 1.0 / ncols, 1.0 / nrows

    for (i, j), val in np.ndenumerate(data):
        tb.add_cell(i, j, width, height, text=str(val) if val else '', loc='center')

    for i in range(data.shape[0]):
        tb.add_cell(i, -1, width, height, text=str(i), loc='right',
                    edgecolor='none', facecolor='none')
    for i in range(data.shape[1]):
        tb.add_cell(-1, i, width, height/2, text=str(i), loc='center',
                    edgecolor='none', facecolor='none')

    tb.set_fontsize(16)
    ax.add_table(tb)
    return fig

coords = ((1,2), (2,5), (1,2), (5, 5), (4, 5))

# get maximum value for both x and y to allocate the array
x, y = map(max, zip(*coords))
data = np.zeros((x+1, y+1), dtype=int)

for i, j in coords:
    data[i,j] += 1

table_plot(data)
plt.show()

rawDescription: Count frequencies of x, y coordinates, display in 2D and plot


code:
bin = df.iloc[i].copy()  # to avoid modifying the original dataframe
for _ in range(j):
    bin['bin'] += 5
    df = df.append(bin, ignore_index=True)

rawDescription: last value carried forward in pandas

description: Last value carried forward in pandas


code:
import os, sys

#stuff

def restart():
    args = sys.argv[:]  # get shallow copy of running script args
    args.insert(0, sys.executable)  # give it the executable
    os.execv(sys.executable, args)  # execute the script with current args, effectively relaunching it, can modify args above to change how it relaunches

rawDescription: Close Python script, then immediately relaunch


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

driver = webdriver.Chrome()
driver.get("https://kissanime.to/Anime/Hunter-x-Hunter-2011-Dub")

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//a[contains(@title,'Episode')]")))

episodes = driver.find_elements_by_xpath("//a[contains(@title,'Episode')]")
print(len(episodes))

driver.close()

rawDescription: find_elements_by_partial_link_text won't locate the elements

description: Find_elements_by_partial_link_text won't locate the elements


code:
from Tkinter import *

# First create application class

class Application(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)

        self.lbox_list = [('Adam', 'Mitric' ),
                           ('Lucy', 'Devic'  ),
                           ('Bob' , 'Freamen'),
                           ('Amanda', 'Ling' ),
                           ('Susan', 'Cascov')]

        self.pack()
        self.create_widgets()

    # Create main GUI window
    def create_widgets(self):
        self.search_var = StringVar()
        self.search_var.trace("w", lambda name, index, mode: self.update_list())
        self.entry = Entry(self, textvariable=self.search_var, width=13)
        self.lbox1 = Listbox(self, width=20, height=15)
        self.lbox2 = Listbox(self, width=20, height=15)         # Second List Box. Maybe you can use treeview ?

        self.entry.grid(row=0, column=0, padx=10, pady=3)
        self.lbox1.grid(row=1, column=0, padx=10, pady=5)
        self.lbox2.grid(row=1, column=1, padx=10, pady=5)

        # Function for updating the list/doing the search.
        # It needs to be called here to populate the listbox.
        self.update_list()

    def update_list(self):
        search_term = self.search_var.get()

        # Just a generic list to populate the listbox

        self.lbox1.delete(0, END)
        self.lbox2.delete(0, END)       # Deletng from second listbox

        passed = []                     # Need this to check for colisions

        for item in self.lbox_list:
            if search_term.lower() in item[0].lower():
                self.lbox1.insert(END, item[0])
                self.lbox2.insert(END, item[1])
                passed.append(item)

        for item in self.lbox_list:
            if search_term.lower() in item[1].lower() and item not in passed:
                self.lbox1.insert(END, item[0])
                self.lbox2.insert(END, item[1])

root = Tk()
root.title('Filter Listbox Test')
app = Application(master=root)
app.mainloop()

rawDescription: Tkinter search / filter bar - csv file

description: Tkinter search / filter bar - csv file


code:
def rreverse(s):
    if s == "":
        return s
    else:
        return rreverse(s[1:]) + s[0]

rawDescription: Python reversing a string using recursion


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

import multiprocessing
# We must import this explicitly, it is not imported by the top-level
# multiprocessing module.
import multiprocessing.pool
import time

from random import randint

class NoDaemonProcess(multiprocessing.Process):
    # make 'daemon' attribute always return False
    def _get_daemon(self):
        return False
    def _set_daemon(self, value):
        pass
    daemon = property(_get_daemon, _set_daemon)

# We sub-class multiprocessing.pool.Pool instead of multiprocessing.Pool
# because the latter is only a wrapper function, not a proper class.
class MyPool(multiprocessing.pool.Pool):
    Process = NoDaemonProcess

def sleepawhile(t):
    print("Sleeping %i seconds..." % t)
    time.sleep(t)
    return t

def work(num_procs):
    print("Creating %i (daemon) workers and jobs in child." % num_procs)
    pool = multiprocessing.Pool(num_procs)

    result = pool.map(sleepawhile,
        [randint(1, 5) for x in range(num_procs)])

    # The following is not really needed, since the (daemon) workers of the
    # child's pool are killed when the child is terminated, but it's good
    # practice to cleanup after ourselves anyway.
    pool.close()
    pool.join()
    return result

def test():
    print("Creating 5 (non-daemon) workers and jobs in main process.")
    pool = MyPool(5)

    result = pool.map(work, [randint(1, 5) for x in range(5)])

    pool.close()
    pool.join()
    print(result)

if __name__ == '__main__':
    test()

rawDescription: Python Process Pool non-daemonic?

description: Python Process Pool non-daemonic


code:
import random

results = {}

for _ in range(1000):
    d1 = random.randint(1,6)
    d2 = random.randint(1,6)
    results[d1+d2] = results.setdefault(d1+d2, 1) + 1

for roll, count in results.iteritems():
    print('Rolled %d %d times, or %.2f %%' % (roll, count, count/1000.))

rawDescription: Python - Rolled 2 6-side die 1000 times

description: Python - Rolled 2 6-side die 1000 times


code:
def remove_module_docstring(app, what, name, obj, options, lines):
    if what == "module" and name == "hpclogging.logger" and 'members' in options:
        del lines[:]

def setup(app):
    app.connect("autodoc-process-docstring", remove_module_docstring)

rawDescription: Sphinx: How do I document all classes/members of a module but not the module itself


code:
def stretchEyes(image, newWidth):
    return pygame.transform.scale(image, (image.get_height(), newWidth))

eyes = stretchEyes(eyes, image.get_width()*3) # Stretch to three times width
# Blitting takes in the top left position, so we don't need to do any maths here!
screen.blit(eyes, (x,y))

rawDescription: Is it possible to stretch an image in pygames?


rawDescription: Extract specific data entries(as groups) from a list and store in separate lists?


code:
import http.client
conn = http.client.HTTPSConnection("www.python.org")
conn.request("GET", "/")
r1 = conn.getresponse()
print(r1.status, r1.reason)
data1 = r1.read()  # This will return entire content.
# The following example demonstrates reading data in chunks.
conn.request("GET", "/")
r1 = conn.getresponse()
while not r1.closed:
    print(r1.read(200)) # 200 bytes
# Example of an invalid request
conn.request("GET", "/parrot.spam")
r2 = conn.getresponse()
print(r2.status, r2.reason)
data2 = r2.read()
conn.close()

rawDescription: Perform handshake only once

description: Perform handshake only once


code:
import Tkinter as tk

root = tk.Tk()
image = tk.PhotoImage(file="myfile.gif")
label = tk.Label(image=image)
label.pack()
root.mainloop()

rawDescription: How to load an image into a python 3.4 tkinter window?

description: Load an image into a python 3.4 tkinter window


code:
def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

rawDescription: how code a function similar to itertools.product in python 2.5

description: How code a function similar to itertools.product in python 2.5


code:
loader = gtk.gdk.PixbufLoader('jpeg')
loader.write(pic)
loader.close()

pixbuf = loader.get_pixbuf()

rawDescription: How to load image files to gtk.gdk.Pixbuf from stream?

description: Load image files to gtk.gdk.Pixbuf from stream


code:
xs = matplotlib.dates.date2num(xs)    # You need to keep this line

hfmt = matplotlib.dates.DateFormatter('%H:%M:%S')
ax1.xaxis.set_major_formatter(hfmt)
ax1.plot(xs, ys)   # You have this already

rawDescription: Matplotlib - when plotting time it puts decimal zeros after the seconds


code:
minval, maxval = 20, 80
df = pd.DataFrame(np.random.randint(0, 100, (20,6)))
df[((df > minval) & (df < maxval)).all(axis=1)]

rawDescription: Selecting with query where conditions are met for all columns


code:
for row in c.execute("SELECT name, age FROM ..."):
    name, age = row
    break
else:
    print("not found")

rawDescription: Check if a row exists in sqlite3?

description: Check if a row exists in sqlite3


rawDescription: python - simple way to join 2 arrays/lists based on common values

description: Python - simple way to join 2 arrays/lists based on common values


code:
response = HttpResponse(mimetype='audio/mpeg')
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
response['Accept-Ranges'] = 'bytes'
response['X-Sendfile'] = smart_str(path_to_file)
return response

rawDescription: Django: how to give mp3 file correctly

description: Django: how to give mp3 file correctly


rawDescription: How do I efficiently split all the data in str in python?

description: Efficiently split all the data in str in python


code: Y = np.delete(X, 1, axis=1)

rawDescription: How to remove nth element in all numpy arrays in a numpy array?

description: Remove nth element in all numpy arrays in a numpy array


code:
def find_overlap(a, b):
    i = 0
    j = 0
    len_a = len(a)
    len_b = len(b)
    in_overlap = False
    best_count = 0
    best_start = (-1, -1)
    best_end = (-1, -1)

    while i < len_a and j < len_b:

        if a[i] == b[j]:
            if in_overlap:
                # Keep track of the length of the overlapping region
                count += 1
            else:
                # This is a new overlapping region, set count to 1 record start
                in_overlap = True
                count = 1
                start = (i, j)
            # Step indicies
            i += 1
            j += 1
            end = (i, j)
            if count > best_count:
                # Is this the longest overlapping region so far?
                best_count = count
                best_start = start
                best_end = end
        # If not in a an overlapping region, only step one index
        elif a[i] < b[j]:
            in_overlap = False
            i += 1
        elif b[j] < a[i]:
            in_overlap = False
            j += 1
        else:
            # This should never happen
            raise
    # End of loop

    return best_start, best_end

rawDescription: How to find the largest contiguous, overlapping region in a set of sorted arrays

description: Find the largest contiguous, overlapping region in a set of sorted arrays


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

data = np.random.randn(10,3)
df = pd.DataFrame(abs(data))
plt.stackplot(np.arange(10),[df[0],df[1],df[2]])
plt.show()

rawDescription: How to add black lines to stacked pandas area plot?

description: Add black lines to stacked pandas area plot


code:
import matplotlib.pyplot as plt
import math

my_lists = [[i*math.exp(-x/10.) for x in range(10) ] for i in range(1,7)]
legend_names = ["line 1", "line 2", "line 3", "line 4", "line 5", "line 6"]
for ydata, name in zip(my_lists, legend_names):
    plt.plot(ydata, label = name)
plt.legend(loc = 'best')
plt.show()

rawDescription: Plotting 3 lists of the same size, with individual labels


code:
# open file and parse values
with open('values.csv') as f:
    searches = [x.split(',')[1] for x in f.read().splitlines()]

# function to check string
def checkString(text):
    # iterate over searches and check each one
    for search in searches:
        if search in text:
            return True
    return False

rawDescription: Python: Find string in line based on lookup


code:
uint8_data = ...
image_data = tf.image.encode_png(uint8_data)

rawDescription: Converting uint8 array to image

description: Converting uint8 array to image


code:
import math

class UndrawnTurtle():
    def __init__(self):
        self.x, self.y, self.angle = 0.0, 0.0, 0.0
        self.pointsVisited = []
        self._visit()

    def position(self):
        return self.x, self.y

    def xcor(self):
        return self.x

    def ycor(self):
        return self.y

    def forward(self, distance):
        angle_radians = math.radians(self.angle)

        self.x += math.cos(angle_radians) * distance
        self.y += math.sin(angle_radians) * distance

        self._visit()

    def backward(self, distance):
        self.forward(-distance)

    def right(self, angle):
        self.angle -= angle

    def left(self, angle):
        self.angle += angle

    def setpos(self, x, y = None):
        """Can be passed either a tuple or two numbers."""
        if y == None:
            self.x = x[0]
            self.y = y[1]
        else:
            self.x = x
            self.y = y
        self._visit()

    def _visit(self):
        """Add point to the list of points gone to by the turtle."""
        self.pointsVisited.append(self.position())

    # Now for some aliases. Everything that's implemented in this class
    # should be aliased the same way as the actual api.
    fd = forward
    bk = backward
    back = backward
    rt = right
    lt = left
    setposition = setpos
    goto = setpos
    pos = position

ut = UndrawnTurtle()

rawDescription: Hide Turtle Window?

description: Hide Turtle Window


code:
from Tkinter import *
from PIL import ImageTk
import urllib

# initialize window

root = Tk()
root.geometry('640x480')

# retrieve and download image

location = 'https://www.python.org/static/community_logos/python-logo.png'
image = open('image.png', 'wb')
image.write(urllib.urlopen(location).read())
image.close()

# create canvas for drawing

canvas = Canvas(root, width = 640, height = 480)
canvas.place_configure(x = 0, y = 0, width = 640, height = 480)

# load image with PIL and draw to canvas

image = ImageTk.PhotoImage(file = 'image.png')
canvas.create_image(10, 10, image = image, anchor = NW)

# start program

root.mainloop()

rawDescription: How can I access pictures/text on a website and display them with Tkinter?

description: Access pictures/text on a website and display them with Tkinter


code:
headshape = (2,3,4)
headdata = rand(2*3*4)

head_shaped_short = headdata.reshape(headshape[::-1]).swapaxes(0,2)

rawDescription: Loading Analyze 7.5 format images in python


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

indices = [[1, 3], [2], [4]]               # <-----
vals = [[1, 2.5], [1.5], [3.5]]            # <-----
labels = ['Group 1', 'Group 2', 'Group 3']

color_space = iter(cm.Paired(np.linspace(0, 1, len(vals))))
for xs, ys, label in zip(indices, vals, labels):
    col = next(color_space)
    plt.bar(xs, ys, width=1, color=col, label=label)

plt.legend(loc='best')
plt.show()

rawDescription: How to add more items to the matplotlib legend?

description: Add more items to the matplotlib legend


code:
import pexpect

ssh_command = 'ssh user@your.server.com'
child = pexpect.spawn(ssh_command)

default_prompt = 'user@server:~/# '
child.expect(default_prompt)

kill_command = 'killall process_name'
child.sendline(kill_command)

rawDescription: Send ctrl-C to OSX Terminal in an SSH Session in Python


code:
queryset = Foo.objects.filter(base_query_stuff)
if bar_criteria:
     queryset = queryset.filter(bar_stuff)
if cheese_criteria:
     queryset = queryset.filter(cheese_stuff)

return queryset

rawDescription: django: using Q to filter taking into account blank choice scenario

description: Django: using Q to filter taking into account blank choice scenario


code:
import pyodbc

pyodbc.pooling = False
conn = pyodbc.connect(db_connection_string)
conn.close()

rawDescription: SQLAlchemy / pyODBC not releasing database connection


code:
class EventSystem(object):

    def __init__(self):
        self.queue = Queue.Queue()
    self.parent_thread = threading.current_thread()          # <-- Added
    self.thread = threading.Thread(target=self_process_loop)
    self.thread.start()

def _process_loop(self):
    while self.parent_thread.is_alive():                    # <-- Changed
        try:
            event = self.queue.get(timeout=1)               # <-- Timeout added
        except Queue.Empty:
            continue
        else:
            self._handle_event(event)

def _handle_event(self, event):
    ...

rawDescription: Managing an event loop in a thread

description: Managing an event loop in a thread


code:
for f in os.listdir(__path__):
  mod = os.path.splitext(f)[0]
  if mod not in ['__init__','__pycache__','level_base']:
    __all__.append(mod)

rawDescription: Using pkgutil.iter_modules with py2app

description: Using pkgutil.iter_modules with py2app


code:
from nltk.corpus import wordnet as wn
ss = wn.synset('dog.n.01')
offset = str(ss.offset()).zfill(8) + '-' + ss.pos()
offset

rawDescription: How do I extract the offset of a WordNet synset give a synset in Python NLTK?

description: Extract the offset of a WordNet synset give a synset in Python NLTK


code:
textEditorExecutablePath = 'C:\\Program Files (x86)\\Notepad2\\Notepad2.exe'
filepathToOpen = 'C:\\file.txt'
subprocess.Popen([textEditorExecutablePath, filepathToOpen])

rawDescription: How would I call 32bit exes in Windows 64bit with python?


code:
from django.db import IntegrityError

class Property(models.Model):
    owner = models.ForeignKey(Owner)

    def save(self, *args, **kwargs):
        if self.owner.type == "Individual":
            if Property.objects.filter(owner=self.owner).exists():
                raise IntegrityError
        super(Property, self).save(*args, **kwargs)

rawDescription: How to model "One or Many" relationship in Django?

description: Model "One or Many" relationship in Django


rawDescription: Find a Hamiltonian Path on a tournament with adjacency lists in Python


code:
def parse_get_account(self, response):
    j = json.loads(response.body_as_unicode())
    if j['d'][0] != "":
        item = ParkerItem()
        item['account'] = j['d'][0]
        return Request(method="GET", url=(url + '?' + urllib.urlencode(querystring)), headers=headers, callback=self.parse_third_request, meta={'item': item})

rawDescription: Best practices with multi page scrapy code


code:
email = forms.EmailField(
    widget = forms.TextInput(attrs={'placeholder': 'Email', 'class': 'myClass', 'size': 'mySize'}))

rawDescription: how to add multiple attrs in Django forms

description: Add multiple attrs in Django forms


code: dset.attrs["Name"] = "My Dataset"

rawDescription: Dictionary-like efficient storing of scipy/numpy arrays


code:
import random
shape = ['triangle' , 'square' , 'circle' , 'cross']
color = ['green' , 'red' , 'blue' , 'pink']
random.shuffle(shape)
random.shuffle(color)
list(zip(shape, color))
random.shuffle(color)
random.shuffle(shape)
list(zip(shape, color))
random.shuffle(color)
random.shuffle(shape)
list(zip(shape, color))
random.shuffle(shape)
random.shuffle(color)
list(zip(shape, color))
random.shuffle(shape)
random.shuffle(color)
list(zip(shape, color))
random.shuffle(shape)
random.shuffle(color)
list(zip(shape, color))

rawDescription: Random selection from list with condition - Python


code: [d[key] for key in keys]

rawDescription: Get list of values from dict

description: Get list of values from dict


code:
fp = webdriver.FirefoxProfile()
fp.set_preference("javascript.enabled", False)
self.driver = webdriver.Firefox(firefox_profile=fp)

rawDescription: How to crawl 'hidden' JS for locally saved html

description: Crawl 'hidden' JS for locally saved html


code:
import numpy as np
df["new_col"] = df["col1"] - np.minimum(0,df["col2"])

rawDescription: Get the min of [0, x] element wise for a column


code:
#!/usr/bin/env python3

import re

str="[class,'STOCK'],[symbol,'AAII'],[open,2.60],[high,2.70],[low,2.53],[close,2.60],[volume,458500],[date,'21-Dec-04'],[openClosePDiff,0.0],[highLowPDiff,0.067],[closeEqualsLow,'false'],[closeEqualsHigh,'false']"
str = re.sub('^\[','',str)
str = re.sub('\]$','',str)
array = str.split("],[")
for line in array:
    print(line)

rawDescription: Split stock quote to tokens in Python

description: Split stock quote to tokens in Python


code:
import urllib

url = 'http://www.website.com/x.csv'
urllib.urlretrieve(url, 'b.csv')

file_a = open('a.csv', 'r')
file_b = open('b.csv', 'r')
file_out = open('out.csv', 'w')

list_a = [x.strip() for x in file_a.read().split(',')]
list_b = [x.strip() for x in file_b.read().split(',')]
list_out = list(set(list_a) - set(list_b)) # Reverse if necessary

file_out.write(','.join(list_out))
file_out.close()

rawDescription: Comparing keywords in a page or CSV file: PHP ? Bash?


code:
if all(a[i]<b[i+1]  for i in range(1,3)):
    print("Yes")
else:
    print("No")

rawDescription: Comparing values of parts of two tuples in python


code:
import Tkinter
class App:
    def __init__(self):
        self.root = Tkinter.Tk()
        Tkinter.Label(self.root, text="main window").pack()
        self.window = Tkinter.Toplevel()
        self.window.overrideredirect(True)
        Tkinter.Label(self.window, text="Additional window").pack()
        self.root.bind("<Unmap>", self.OnUnMap)
        self.root.bind("<Map>", self.OnMap)
        self.root.mainloop()
    def OnMap(self, e):
        self.window.wm_deiconify()
    def OnUnMap(self, e):
        self.window.wm_withdraw()
app=App()

rawDescription: Python Tkinter: Remove window border

description: Python Tkinter: Remove window border


code:
from subprocess import STDOUT, check_call
import os

check_call(['apt-get', 'update'], stderr=STDOUT)

rawDescription: how to update/upgrade a linux machine using pure python script

description: Update/upgrade a linux machine using pure python script


code:
def rec_len(thing):
    if isinstance(thing, basestring):
        return 1
    try:
        return sum(rec_len(x) for x in thing)
    except TypeError:
        return 1

rawDescription: Number of Leaves in a Binary Tree Python


code:
import urllib2
urllib2.quote
urllib2.quote("ü")
urllib2.quote('Olá mundo!')

rawDescription: Python. Phrase representation, how to change?


code:
import os, numpy, PIL
from PIL import Image

# Access all PNG files in directory
allfiles=os.listdir(os.getcwd())
imlist=[filename for filename in allfiles if  filename[-4:] in [".png",".PNG"]]

# Assuming all images are the same size, get dimensions of first image
w,h=Image.open(imlist[0]).size
N=len(imlist)

# Create a numpy array of floats to store the average (assume RGB images)
arr=numpy.zeros((h,w,3),numpy.float)

# Build up average pixel intensities, casting each image as an array of floats
for im in imlist:
    imarr=numpy.array(Image.open(im),dtype=numpy.float)
    arr=arr+imarr/N

# Round values in array and cast as 8-bit integer
arr=numpy.array(numpy.round(arr),dtype=numpy.uint8)

# Generate, save and preview final image
out=Image.fromarray(arr,mode="RGB")
out.save("Average.png")
out.show()

rawDescription: How to get an average picture from 100 pictures using PIL?

description: Get an average picture from 100 pictures using PIL


code:
new_idx = s.index + pd.Index(np.arange(1.1, 2.3, .01))
s.reindex(new_idx).interpolate().head()
s.reindex(new_idx).interpolate().tail()

rawDescription: resampling pandas series with numeric index

description: Resampling pandas series with numeric index


rawDescription: Rename .txt files to values separated by comma at first line in file?


code: [ [(x+y)**2 for y in range(10)] for x in range(10)]

rawDescription: 2D lists generation Python

description: 2D lists generation Python


code:
# Create an array of indices
indices = np.arange(y.size)
# Randomize it
np.random.shuffle(indices)

rawDescription: How to sort an array and a matrix together using numpy

description: Sort an array and a matrix together using numpy


code:
a = 12
a is a

rawDescription: Override equals in Python but still have reference equality check


code:
class FTPStreamer(object):
    implements(IReadFile)

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

    def send(self, consumer):
        fetch(url, consumer.write)
        # You also need a Deferred to return here, so the
        # FTP implementation knows when you're done.
        return someDeferred

rawDescription: Twisted, FTP, and "streaming" large files


code:
fruits = "['apple', 'orange', 'banana']"
import ast
fruits = ast.literal_eval(fruits)
fruits
fruits[1]

rawDescription: Converting a string representation of a list into an actual list object


code:
valid={(x,y) for x in range(3) for y in range (3)}
dirs=[(dx,dy) for dx in (-1,0,1) for dy in (-1,0,1) if (dx,dy)!=(0,0)]
def voisins(x,y): return [(x+dx,y+dy) for (dx,dy) in dirs  if (x+dx,y+dy) in valid]

rawDescription: Finding valid neighbor indices in 2d array


code: sudo('curl -o /tmp/test.gz "{}"'.format(url))

rawDescription: Fab file, unable to remote curl a S3 .gzip file


code:
lst = [
    (1, 100),
    (2, 150),
    (3, 200)
]
list(zip(*lst))  # zip(*lst) groups the items that you want to sum
[sum(x) for x in zip(*lst)]

rawDescription: Best way to find the sum of a column in a multi-dimensional array in python?

description: Find the sum of a column in a multi-dimensional array in python


code:
import urllib
import settings
import oauth2 as oauth

try:
    twitter_user = user.social_auth.get(provider='twitter')
except:
    return
if not twitter_user.tokens:
    return
access_token = twitter_user.tokens['oauth_token']
access_token_secret = twitter_user.tokens['oauth_token_secret']

token = oauth.Token(access_token,access_token_secret)
consumer_key = settings.TWITTER_CONSUMER_KEY
consumer_secret = settings.TWITTER_CONSUMER_SECRET
consumer = oauth.Consumer(consumer_key,consumer_secret)
client = oauth.Client(consumer,token)

data = {'status':'Your tweet goes here'}
request_uri = 'https://api.twitter.com/1/statuses/update.json'
resp, content = client.request(request_uri, 'POST', urllib.urlencode(data))

rawDescription: Django users post to twitter

description: Django users post to twitter


code:
test_list = ["1", "2", "5", "6"]
map(int,test_list)
sum(map(int,test_list))

rawDescription: How can I convert a list of strings to a list of integers and then add them?

description: Convert a list of strings to a list of integers and then add them


code:
i1 = Invoice.objects.all()[0]
i2 = Invoice.objects.get(pk=i1.pk)
i1 == i2
id(i1) == id(i2)

rawDescription: Django Test - I can't save my object when I use queryset to get it


code:
rows = [value for row in reader
        for value in [(row[0], row[2]), (row[0], row[3])]]

rawDescription: How to extract two tuples from a single row in a list comprehension?

description: Extract two tuples from a single row in a list comprehension


code:
import gc
def find_subclasses(cls):
    all_refs = gc.get_referrers(cls)
    results = []
    for obj in all_refs:
        # __mro__ attributes are tuples
        # and if a tuple is found here, the given class is one of its members
        if (isinstance(obj, tuple) and
            # check if the found tuple is the __mro__ attribute of a class
            getattr(obj[0], "__mro__", None) is obj):
            results.append(obj[0])
    return results

rawDescription: How to iterate through every class declaration, descended from a particular base class?

description: Iterate through every class declaration, descended from a particular base class


code:
def remove_br(x):
    return x.replace('<br \>','')

convert_dict = {'col_name':remove_br}

df = pd.read_csv('file.csv', converters=converter_dict)

rawDescription: Pandas to_csv with escape characters and other junk causing return to next line


code:
class Test():
      def __cmp__(self, other):
           return -1

rawDescription: Special method __cmp__ doesn't work

description: Special method __cmp__ doesn't work


code:
I = range(0,10)
t = 3
R = [1 if i>=t else 0 for i in I]
R

rawDescription: Alternative to append

description: Alternative to append


code:
lat_ = map(lambda i:radians(i[0]), l)
lon_ = map(lambda i:radians(i[1]), l)

rawDescription: How would I apply the python map function to an multidimensional array


code:
import os
def ping(address):
    return not os.system('ping %s -n 1' % (address,))

rawDescription: How to ping a server/website with windows python?

description: Ping a server/website with windows python


code:
import sqlite3

conn = sqlite3.connect('example.db')

c = conn.cursor()

# Create table
c.execute('''CREATE TABLE stocks
             (date text, trans text, symbol text, qty real, price real)''')

# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

# Save (commit) the changes
conn.commit()

# We can also close the cursor if we are done with it
c.close()

rawDescription: What the simplest database to use with both Python and Matlab?


code:
myList = ['foobar', 'footest', 'not', 'test', 'foothing']
'<{}>'.format(', '.join(i for i in myList if i.startswith('foo')))

rawDescription: Off by one issue with concatenating strings


code:
s = "Wouldn't it be (most) beneficial to have (at least) some idea?"
l = re.split('[()]', s);

rawDescription: Multi-split in Python

description: Multi-split in Python


code:
def create(self, validated_data):

    memberaccount = MemberAccount.objects.create(account = validated_data['account'],
                                            password = validated_data['password'] )
    memberaccount.save()
    User_Datas = validated_data.pop('UserDatas')

    userdata = UserData.objects.create(username = User_Datas.get('username'),
        gender = User_Datas.get('gender'),
        score = User_Datas.get('score'),
        photo = User_Datas.get('photo'),)
    userdata.memberAccount_id = memberaccount

    userdata.save()

    Task_Datas = User_Datas.get('TaskDatas')
    for task in Task_Datas:
        taskdata = TaskData(
            task_name = task.get('task_name'),
            task_is_group = task.get('task_is_group'),
            task_time = task.get('task_time'),
            task_score = task.get('task_score'),
            task_member_list = task.get('task_member_list'),
            task_bulletin = task.get('task_bulletin'),
        )
        taskdata.userData_id = userdata
        taskdata.save()

    return memberaccount

rawDescription: Django REST: How to POST and PUT Data in Nested ModelSerializer


code:
import os
os.chdir(path)

rawDescription: How to change the current working directory

description: Change the current working directory


code: any(x in row for row in graph)

rawDescription: Python - checking if element is in list of lists (pythonic way)


code:
titles = ['art gallery - museum and visits | expand knowledge',
 'lasergame - entertainment | expand knowledge',
 'coffee shop - confort and food | expand knowledge',
]

# Find the longest common suffix by reversing the strings and using a
# library function to find the common "prefix".
common_suffix = os.path.commonprefix([title[::-1] for title in titles])[::-1]

# Strips all titles from the number of characters in the common suffix.
stripped_titles = [title[:-len(common_suffix)] for title in titles]

rawDescription: Find a repeating pattern in a list of strings


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

if 0:  # to generate the file
    delta = 0.025
    x = np.arange(-3.0, 3.0, delta)
    y = np.arange(-2.0, 2.0, delta)
    X, Y = np.meshgrid(x, y)
    Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
    Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
    Z = 10.0 * (Z2 - Z1)

    ax = plt.subplot(111)
    CS = ax.contourf(X, Y, Z)

    pickle.dump(ax, open("mpl_test.pkl", "w"))
    pickle.dump(CS, open("contours.pkl", "w"))

else: # Then at a later time...

    x0 = pickle.load(open("mpl_test.pkl", "r"))
    x1 = pickle.load(open("contours.pkl", "r"))

    v = x1.collections[0].get_paths()[0].vertices   # get the vertices of the contour
    x, y = v[:,0]+.2, v[:,1]+.1                     # shift the contour
    x0.plot(x, y, 'w', linewidth=3)                 # add it to the plot as a white line

rawDescription: Save data from plot to numpy array

description: Save data from plot to numpy array


code:
from matplotlib import pyplot as plt

# group by SourceID and Type, find out how many unique combinations there are
grps = df.groupby(['SourceID', 'Type'])
ngrps = len(grps)

# make a grid of axes
ncols = int(np.sqrt(ngrps))
nrows = -(-ngrps // ncols)

fig, ax = plt.subplots(nrows, ncols, sharex=True, sharey=True)

# iterate over the groups, plot into each axis
for ii, (idx, rows) in enumerate(grps):
    rows.plot(x='hour', y='BSs', style='-s', ax=ax.flat[ii], legend=False,
              scalex=False, scaley=False)

# hide any unused axes
for aa in ax.flat[ngrps:]:
    aa.set_axis_off()

# set the axis limits
ax.flat[0].set_xlim(df['hour'].min() - 1, df['hour'].max() + 1)
ax.flat[0].set_ylim(df['BSs'].min() - 5, df['BSs'].max() + 5)

fig.tight_layout()

rawDescription: Plotting a timeseris graph from pandas dataframe using matplotlib


code:
a=["a", "b", "c", "d", "e"]
b=[1, 2, None, 3, 4]
selectors = [x is not None for x in b]
list(itertools.compress(a, selectors))
list(itertools.compress(b, selectors))

rawDescription: python filter and list and apply "filtered indices" to another list

description: Python filter and list and apply "filtered indices" to another list


code:
item = sizer.GetItem(index)
size = item.GetSize()

rawDescription: How do I get the size of an individual cell of a wx.GridSizer?

description: Get the size of an individual cell of a wx.GridSizer