code:
from nltk.tokenize.regexp import regexp_tokenize

str1 = 'The api allows the user to achieve following goals: (a) aXXXXXX ,(b)bXXXX, (c) cXXXXX.'

parts =  regexp_tokenize(str1, r'\(\w\)\s*', gaps=True)

start_of_sentence = parts.pop(0)

for part in parts:
    print(" ".join((start_of_sentence, part)))

rawDescription: How to segment text into sub-sentences based on enumerators?

description: Segment text into sub-sentences based on enumerators


code:
import schedule
import time

def job():
    print("I'm working...")

schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

rawDescription: Send Http Request at user set time (python back end)


code:
columns = ['column1', 'column2', 'column3', 'column4', 'column5']
results = statement.executeQuery("select %s from %s where column_id = '%s'" % (",".join(columns), table, id))

rawDescription: Jython, Query multiple columns dynamically


code:
from .ModelOne import ModelOne
from .ModelTwo import ModelTwo

rawDescription: syncdb doesn't create table models

description: Syncdb doesn't create table models


code:
data = json.load(data_file)
for obj in data:
  pprint(obj['objectId'])

rawDescription: Python: Printing json element in a loop until the JSON is done.


code: from bitbucketrepo.api import application

rawDescription: Running a Python file with Flask, nginx and uWSGI in Ubuntu


code:
import urllib2

def main():
    # omitted all the connection stuff...
    query = "INSERT INTO metadb (name, type , year ) values ( %s, %s, %d)"
    params = (escape_string("Valentine's day"), "movie", 2010)
    cursor.execute(query, params)

def escape_string(str):
    return urllib2.quote(str).replace("%","%%")

if __name__ == "__main__":
    main()

rawDescription: Python SQL entry not returing search result


code:
import os
os.getcwd()

rawDescription: How to write a whole string to a file in Python and where does the file go?

description: Write a whole string to a file in Python and where does the file go


code:
rows1 = np.genfromtxt('stack30874236.txt',names=None,skip_header=4,skip_footer=10)
rows2 =np.genfromtxt('stack30874236.txt',names=None,skip_header=17)
rows=np.concatenate([rows1[:,1:],rows2[:,1:]],axis=1)
rows
rows.T

rawDescription: Parse multicolumn string using python

description: Parse multicolumn string using python


code:
import csv
toCSV = [{'name':'bob','age':25,'weight':200},
         {'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(toCSV)

rawDescription: How do I convert this list of dictionaries to a csv file? [Python]

description: Convert this list of dictionaries to a csv file? [Python]


code:
for i in f:
    filename = 'tas_%s.txt' % str(i)
    filepath = os.path.join('test', filename)

    # anything else remains unchanged

rawDescription: Python How to generate file name

description: Python How to generate file name


code: sqrt((x - center_x) ** 2 + (y - center_y) ** 2)

rawDescription: Python: Checking If Coordinates Are Within Circle


code:
import requests

r = requests.get('http://192.168.0.200:9090/')
if "ArduinoOn" in r.text:
    print ('True')

rawDescription: look for words on html with python

description: Look for words on html with python


code: a = list(set(a))

rawDescription: Combining list elements in python?

description: Combining list elements in python


code:
# ...
updateLeaveCounts()
p.refresh_from_db()
self.assertEqual(p.batch_processed, True)
# ...

rawDescription: Django TestCase not saving my models

description: Django TestCase not saving my models


code:
reader = csv.reader(file, quotechar='"', delimiter=',', quoting=csv.QUOTE_ALL, skipinitialspace=True)
for line_num, line in enumerate(reader, start=1):
    try:
        if line[16] == "S":
            total = total + line[2]
    except IndexError:
        # show offending line
        print(line_num, line)
        # reraise to halt execution
        raise

rawDescription: Parsing CSV files with Python IF specific data exists


code:
dir()
locals().keys()
def foo():
    return locals().keys(), globals().keys()

foo()

rawDescription: How to reference other scopes from dir()

description: Reference other scopes from dir()


code:
class base_option(models.Model):
    warval = models.ForeignKey(war)
    caption = models.CharField(max_length=20)
    user = models.ForeignKey(User)

class text_option(base_option):
    text = models.TextField(blank=True,null=True)

class url_option(base_option):
    url = models.URLField(blank=True,null=True)

rawDescription: Django:What to use modelform,formset,model formset for the following scenario?


code:
import re
import sys

seen = set()

infile = open("/var/log/user.log","r")
outfile = open("/var/log/intruders.txt","w")

pattern = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
regexp = re.compile(pattern, re.VERBOSE)

for line in infile:
  mo = regexp.search(line)
  if mo is not None:
     ip_addr = mo.group()
     if ip_addr not in seen:
         seen.add(ip_addr)
         outfile.write("%s\n" % ip_addr)

infile.close()
outfile.close()

rawDescription: Python log parsing for IP's

description: Python log parsing for IP's


code:
p1 = subprocess.Popen(shlex.split('ls -ltr'), stdout=subprocess.PIPE,
                                              stderr=subprocess.PIPE)
p2 = subprocess.Popen(shlex.split('less'), stdin=p1.stdout)

rawDescription: How to get interactive output from a piped command in Python?

description: Get interactive output from a piped command in Python


code:
from re import sub
sub("<[^>]*>", "", "
The is a string.
")
sub("<[^>]*>", "", "This is another string.")

rawDescription: Removing variable length characters from a string in python


code:
emails = ["z@c.com", "a@c.com"]
salaries = [50, 60]
ids = [2, 1]

intermediate = zip(emails, salaries, ids)
intermediate.sort()

result = zip(*intermediate)

rawDescription: How to sort a list alphabetically and have additional lists sorted in the same order

description: Sort a list alphabetically and have additional lists sorted in the same order


code:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import FormRequest, Request

from robots_immo.items import AnnonceItem

class ElyseAvenueSpider(BaseSpider):

    name = "elyse_avenue"
    allowed_domains = ["elyseavenue.com"] # i fixed this
    start_urls = ["http://www.elyseavenue.com/"] # i added this

    def parse(self, response):
        yield FormRequest.from_response(response, formname='moteurRecherche', formdata={'recherche_distance_km_0':'20', 'recherche_type_logement':'9'}, callback=self.parseAnnonces)

    def parseAnnonces(self, response):
        hxs = HtmlXPathSelector(response)
        annonces = hxs.select('//div[@id="contenuCentre"]/div[@class="blocVignetteBien"]')
        items = []
        for annonce in annonces:
            item = AnnonceItem()
            item['nom'] = annonce.select('span[contains(@class,"nomBienImmo")]/a/text()').extract()
            item['superficie'] = annonce.select('table//tr[2]/td[2]/span/text()').extract()
            item['prix'] = annonce.select('span[@class="prixVignette"]/span[1]/text()').extract()
            items.append(item)
        return items

rawDescription: Can't get through a form with scrapy

description: Can't get through a form with scrapy


code:
from collections import defaultdict

class PropertyDict (dict):
    def __getattr__ (self, attr):
        if self.has_key(attr):
            return self.__getitem__(attr)
        return object.__getattr(self, attr)

    def __setattr__ (self, attr, value):
        self.__setitem__(attr, value)

class Record (PropertyDict):
    def __init__ (self, title = None, color = None, action = None, data = None):
        self.title = title
        self.color = color
        self.action = action
        self.data = data

class Page (PropertyDict):
    def __init__ (self):
        self.records = defaultdict(Record)

papers = defaultdict(Page)
papers[1].records[1] = Record('group', 'red', 'open', 'group1')
papers[1].records[2] = Record('group', 'green', 'open', 'group2')

papers[2].records[7].title = "ffff"
papers[1].records[1].title = 'title :-) '

print(papers[1].records[1])
print(papers)

rawDescription: Struct-like in python

description: Struct-like in python


code:
from django.utils.translation import ugettext_lazy as _
_("word_I_want_to_use")

rawDescription: django - i18n - create translation but use it later?

description: Django - i18n - create translation but use it later


code:
def __bool__(self):
    return self.var1 == "Hello world"

rawDescription: Returning result of class function in Python


code: [i for i, s in enumerate(f_list) if '>' in s]

rawDescription: Find index of strings within a list that contain a specific character


code:
def recursive_search(items, key):
    found = []
    for item in items:
        if isinstance(item, list):
            found += recursive_search(item, key)
        elif isinstance(item, dict):
            if key in item:
                found.append(item)
            found += recursive_search(item.values(), key)
    return found

found = recursive_search(items, 'sub_9')

rawDescription: Check a key exist in entire list or dict in python


code:
img = np.random.randint(0, 9 , (3, 3, 3))
lut2 = img[1,2,:] # so that we know exactly the answer

# compare two matrices
img == lut2

array([[[False, False, False],
        [False, False, False],
        [False,  True, False]],

       [[False, False, False],
        [False, False, False],
        [ True,  True,  True]],

       [[ True, False, False],
        [ True, False, False],
        [False, False, False]]], dtype=bool)

# rows with all true are the matching ones
np.where( (img == lut2).sum(axis=2) == 3 )

(array([1]), array([2]))

rawDescription: getting indices when comparing multidimensional arrays

description: Getting indices when comparing multidimensional arrays


code:
def get_status_output(*args, **kwargs):
    p = subprocess.Popen(*args, **kwargs)
    stdout, stderr = p.communicate()
    return p.returncode, stdout, stderr

rawDescription: Replacement for getstatusoutput in Python 3


code:
from webapp2_extras.appengine.auth.models import User
myusers = User.query().fetch()

rawDescription: webapp2 user store, how do you query it

description: Webapp2 user store, how do you query it


code:
new_file = open('test.mid', 'wb')
myMIDI.writeFile(new_file)
new_file.close()
new_file = open('test.mid', 'rb')
return send_file(new_file, mimetype='audio/midi')

rawDescription: How do I allow users to download a MIDI file with Flask without getting a 0 byte download?

description: Allow users to download a MIDI file with Flask without getting a 0 byte download


code:
class CategoryAliasRoot(db.Model):
    count = db.IntegerProperty()
    # Not actually used in current code; just here to avoid having an empty
    # model definition.

    __singleton_keyname = "categoryaliasroot"

    @classmethod
    def get_instance(cls):
            # get_or_insert is inherently transactional; no chance of
            # getting two of these objects.
        return cls.get_or_insert(cls.__singleton_keyname, count=0)

class CategoryAlias(db.Model):
    alias = db.StringProperty()

    @classmethod
    def get_or_create(cls, category_alias):
        alias_root = CategoryAliasRoot.get_instance()
        def txn():
            existing_alias = cls.all().ancestor(alias_root).filter('alias = ', category_alias).get()
            if existing_alias is None:
                existing_alias = CategoryAlias(parent=alias_root, alias=category_alias)
                existing_alias.put()

            return existing_alias

        return db.run_in_transaction(txn)

    def keyname_for_category(self):
        return "category_" + self.key().id

    def rename(self, new_name):
        self.alias = new_name
        self.put()

class Category(db.Model):
    pass

class Item(db.Model):
    name = db.StringProperty()

def get_or_create_item(category_name, item_name):

    def txn(category_keyname):
        category_key = Key.from_path('Category', category_keyname)

        existing_category = db.get(category_key)
        if existing_category is None:
            existing_category = Category(key_name=category_keyname)
            existing_category.put()

        existing_item = Item.all().ancestor(existing_category).filter('name = ', item_name).get()
        if existing_item is None:
            existing_item = Item(parent=existing_category, name=item_name)
            existing_item.put()

        return existing_item

    cat_alias = CategoryAlias.get_or_create(category_name)
    return db.run_in_transaction(txn, cat_alias.keyname_for_category())

rawDescription: How do I ensure data integrity for objects in google app engine without using key names?

description: Ensure data integrity for objects in google app engine without using key names


rawDescription: Python pandas - MultiIndexed Series to Dataframe


code:
from collections import Counter
commonctr = Counter(a) & Counter(b)  # multiset intersection
common = list(commonctr.elements())  # convert back to list
print(common)

rawDescription: What is the logic i should follow to print common elements in two lists


code:
import dis
def colon(x):
    return x[:]
def new_list(x):
    return list(x)
dis.dis(colon)
dis.dis(new_list)

rawDescription: python list copy: is there a difference between old[:] and list(old)?

description: Python list copy: is there a difference between old[:] and list(old)


code:
class DelimitedFile(file):
    def write(self, value):
            super(DelimitedFile, self).write(value.replace(";", "; "))

f = DelimitedFile("foo", "w")
f.write("hello;world")
f.close()
open("foo").read()

rawDescription: Insert whitespace after delimiter with CSV writer


rawDescription: How to simultaneously assign value to dictionary?

description: Simultaneously assign value to dictionary


code: reload(module)

rawDescription: How can I reload objects in my namespace in ipython

description: Reload objects in my namespace in ipython


code:
with open('test.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') # open the csv file
    medianGoodPixels = [] #vector to pixels
    Lux = [] #vector to LUX
    sdVer = [] # vector to the version
    NewCsvTable = [] #will be a matrix with 3 cols, LUX, pixels, and version
    header = next(spamreader)  #Returns the header
    lux_col, pixel_col, version_col = header.index('LUX'), header.index('pixel'),\
                                      header.index('version')

    #Now iterate over rest of the rows.
    for row in spamreader:
        Lux.append(row[lux_col])
        sdVer.append(row[version_col])
        medianGoodPixels.append(row[pixel_col])

rawDescription: How to reduce matrix cols in python?

description: Reduce matrix cols in python


code:
import numpy as np
import skimage.io
from skimage.transform import rotate
tr_1 = numpy.random.rand(5,300)
training_inputs = [np.reshape(tr_1[x,:], (3,10,10)) for x in range(len(tr_1))]
f0 = rotate(training_inputs[1][0], 90, resize=True)
f1 = rotate(training_inputs[1][1], 90, resize=True)
f2 = rotate(training_inputs[1][2], 90, resize=True)
f = np.rollaxis(np.dstack((f0, f1, f2)), 2, 0)

rawDescription: Rotating an Image in Python

description: Rotating an Image in Python


code:
def insertionsort(alldata, key):
    for i in alldata :
        temp = alldata[i]
        j = i
        while j > 0 and alldata[i][key] < alldata[j - 1][key]:
           alldata[j] = alldata[j - 1]
           j -= 1
        alldata[j] = temp

rawDescription: How to do an insertion sort on a list of dictionaries in python?

description: Do an insertion sort on a list of dictionaries in python


code:
output = []
non_zero_temp = []
length = len(main_lists)
i = 0
while i < length:
    zeros = []
    while i < length and main_lists[i] == 0:
        i += 1
        zeros.append(0)
    if len(zeros) != 0 and len(zeros) < 5:
        non_zero_temp += zeros
    elif len(zeros) > 5:
        if len(non_zero_temp) > 0 and i < length:
            output.append(non_zero_temp)
            non_zero_temp = []
    else:
        non_zero_temp.append(main_lists[i])
        i += 1
if len(non_zero_temp) > 0:
    output.append(non_zero_temp)
print(output)

[[123, 432, 5, 54, 0, 654, 645, 34, 23, 12], [123, 1, 312, 312, 132, 3, 123]]

rawDescription: Split Integer List in Python

description: Split Integer List in Python


code:
base_list = [{'number':"123", 'key2':"sample value"},{'number':"3", 'key2':"sample value"},{'number':"55", 'key2':"sample value"},{'number':"43", 'key2':"sample value"},]

result = sorted(base_list, key=lambda x: int(x['number']))

print(result)
# Output
[{'key2': 'sample value', 'number': '3'}, {'key2': 'sample value', 'number': '43'}, {'key2': 'sample value', 'number': '55'}, {'key2': 'sample value', 'number': '123'}]

rawDescription: List ordering based on dict key value with string number


code:
from datetime import datetime, timedelta
from django import template
from django.utils.timesince import timesince

register = template.Library()

@register.filter
def age(value):
    now = datetime.now()
    try:
        difference = now - value
    except:
        return value

    if difference <= timedelta(minutes=1):
        return 'just now'
    return '%(time)s ago' % {'time': timesince(value).split(', ')[0]}

rawDescription: How to display "x days ago" type time using Humanize in Django template?

description: Display "x days ago" type time using Humanize in Django template


code:
from tkinter import *

root = Tk()
button = Button(root, text="Example button")
button.pack()

root.geometry("200x200")

root.mainloop()

rawDescription: Set the size of main window

description: Set the size of main window


code:
import subprocess

subprocess.check_call(['/my/file/path/programname.sh', 'arg1', 'arg2', arg3])

rawDescription: Python: subprocess and running a bash script with multiple arguments


code:
text='hi how are you'
example=text.split()
print(' '.join(example[0:4:2]))

rawDescription: From list to sentence on python3

description: From list to sentence on python3


code:
def read_signal(filename):
    with open(filename) as fh1:
        d = {}
        for line in fh1:
            (t, s) = line.split()
            d[int(t)] = s
        for i in range(15,61):
            if i in sorted(d):
                j = d[i]
            print ("Time: " + str(i) + "s -> Signal: " + j)
read_signal("signals.txt")

rawDescription: Data and signal extraction from a file

description: Data and signal extraction from a file


code:
def __str__(self):
    ...
def __repr__(self):
    return self.__str__()

rawDescription: Python __str__ and lists

description: Python __str__ and lists


rawDescription: Query with many (equals by name) keys

description: Query with many (equals by name) keys


rawDescription: Removing loops in a list in python

description: Removing loops in a list in python


code:
def get_tenants_or_johns(house):
    johns = Person.objects.filter(name='John')
    tenants = house.tenants.all()
    return johns | tenants

rawDescription: Creating a queryset which represents a union of querysets


code:
# Safe since everything in the namespace begins with 'Q'
from PyQt4.QtGui import *

class MyMessageBox(QMessageBox):

    # This is a much better way to extend __init__
    def __init__(self, *args, **kwargs):
        super(MyMessageBox, self).__init__(*args, **kwargs)
        # Anything else you want goes below

    # We only need to extend resizeEvent, not every event.
    def resizeEvent(self, event):

        result = super(MyMessageBox, self).resizeEvent(event)

        details_box = self.findChild(QTextEdit)
        # 'is not' is better style than '!=' for None
        if details_box is not None:
            details_box.setFixedSize(details_box.sizeHint())

        return result

rawDescription: How to allow resizing of QMessageBox in PyQt4

description: Allow resizing of QMessageBox in PyQt4


code:
x1 = (50 - 10) * np.random.random(10000) + 10
x2 = (75 - 25) * np.random.random(10000) + 25

x1.sort()
x2.sort()
x2 = x2[::-1] # reverse the array

# The overlap point should fall where the difference is smallest
diff = np.abs(x1 - x2)

# get the index of where the minimum occurs
loc = np.where(diff == np.min(diff))

q1 = x1[loc]    # 38.79087351
q2 = x2[loc]    # 38.79110941

rawDescription: Find Value that Partitions two Numpy Arrays Equally


rawDescription: Python: Extract all values in a dictionary into assignment statements?


code:
#!/usr/bin/python3

import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)

x1 = [2.13, 2.135, 2.139, 2.14, 2.143]
y1 = range(len(x1))

x2 = [0, 100, 200, 350, 450]

ax1 = fig.add_subplot(111)
ax1.plot(x1, y1)
ax1.grid(True)

ax2 = ax1.twiny()

ax2.set_xticks(x1)
ax2.set_xbound(ax1.get_xbound())
ax2.set_xticklabels(x2)

fig.savefig("15.png")

rawDescription: set second x axis zero position

description: Set second x axis zero position


code: datetime.datetime.strptime(max(datum for datum in data.keys()), "%Y-%m-%d %H:%M").strftime("%d.%m.%Y %H:%M")

rawDescription: Converting Date to String (strftime) in one Line


code:
def set_axes_height(ax, h):
    fig = ax.figure
    aw, ah = np.diff(ax.transAxes.transform([(0, 0), (1, 1)]), axis=0)[0]
    fw, fh = fig.get_size_inches()
    dpi = fig.get_dpi()
    scale = h / (ah / dpi)
    fig.set_size_inches(fw*scale, fh*scale, forward=True)

rawDescription: Adjust figure size with respect to the axes size?


code:
class baba():
    def __init__(self, **kwargs):
        for i in kwargs:
            setattr(self, i, kwargs[i])

b = baba(a=1,b=2,c=4,d=5)
print(b.a) # prints 1

rawDescription: Is there a short way to instantiate a class with the constructor params?


code:
a = 6.75
a.as_integer_ratio()
import math
math.pi.as_integer_ratio()

rawDescription: Check if a number is rational in Python

description: Check if a number is rational in Python


code:
result_queue = multiprocessing.Queue()
montecarlos = [MonteCarlo(result_queue, f,fargs) for fargs in farglist]
jobs = [multiprocessing.Process(mc) for mc in montecarlos]
for job in jobs: job.start()
for job in jobs: job.join()
results = [result_queue.get() for mc in montecarlos]

rawDescription: Can I get a return value from multiprocessing.Process?

description: Get a return value from multiprocessing.Process


rawDescription: Is there anyway to get maximum value in a column using mongoengine?


code:
tempList = []
while True:
    dailyTemp = raw_input("Enter average daily temperature or -100 to quit: ")
    tempList = tempList.append(dailyTemp)

rawDescription: How do I create a list from raw_input in Python 2.7.2?

description: Create a list from raw_input in Python 2.7.2


code:
while 1:
    # do init stuff
    screen.fill(0)
    # .... (all main loop init stuff here)

    for event in pygame.event.get():
        # test events, set key states
        if event.type == pygame.KEYDOWN:
            if event.key==K_w:
                keys[0]=True
        # .... (all event stuff)

    # Indent moves back to main game loop
    # test key states here...
    if keys[0]:
        playerpos[1]-=5
    elif keys[2]:
        playerpos[1]+=5
    # .... (and so on)

rawDescription: Pygame Keyup/Keydown

description: Pygame Keyup/Keydown


code:
MAX_READ_SIZE = 4096
def forward_to_serial():
    while True:
        data = proc.stdout.read1(MAX_READ_SIZE)
        if not data:
            break  # EOF
        ser.write(data)

rawDescription: Forwarding the in and output of a serial link to the stdin and stdout of an other process


code:
def f(n):
    s = str(n)
    l = len(s)
    for n in (n for n in range(1, l + 1) if l % n == 0):
        ints = [int(''.join(x)) for x in zip(*[iter(s)]*n)]
        if sum(ints) == 100:
            return True
    return False

rawDescription: Testing the equality of the sum of a digits within a number on python?


code:
from threading import Lock
lock = Lock()

def send_to_master(msg):
    context = zmq.Context()

    with lock:
        s = context.socket(zmq.PAIR)
        s.connect("tcp://localhost:9001")
        s.send(msg)

        # result received from the service
        data = s.recv()

        s.close()

    return data

...

rawDescription: Sending back right information from distributed work on concurrent requests


code:
os.path.join(*datapath)
os.path.abspath(os.path.join(*(['/'] + datapath)))

rawDescription: How to make file path from list of strings using itertools?

description: Make file path from list of strings using itertools


code:
import pdb
import yourmodule
pdb.run('yourmodule.foo()')

rawDescription: Debugging code in the Python interpreter


code:
for key in c.keys():
    for dictionary in foobar():
        if key in dictionary.values():
            print("Found: ", key)

rawDescription: Check if a key is present in any of the dictionaries in a tuple containing multiple dictionaries returned by a function


code:
map(lambda x: "Python is " + x, mylist)

["Python is " + x for x in mylist]

rawDescription: Concatenate list of string in Python

description: Concatenate list of string in Python


code: any(name in line for name in illegal_names)

rawDescription: Pythonic way to find any item from a list within a string


code:
from operator import itemgetter

new_list = sorted(list, key=itemgetter(1,0))

rawDescription: Tie-breaking in sort

description: Tie-breaking in sort


code:
data - vector[:,None]
data / vector[:,None]

rawDescription: Numpy: Divide each row by a vector element


code:
from django.conf import settings
from django.template.loaders.app_directories import app_template_dirs

import os

template_files = []
for template_dir in (settings.TEMPLATE_DIRS + app_template_dirs):
    for dir, dirnames, filenames in os.walk(template_dir):
        for filename in filenames:
            template_files.append(os.path.join(dir, filename))

rawDescription: Get all templates django detects from TEMPLATE_LOADERS and TEMPLATE_DIRS


code:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
import openpyxl
import xlsxwriter
import pyperclip

driver = ""

def setup():
    global driver
    driver = webdriver.Firefox()
    driver.get("http://www.gps-coordinates.net/")
    assert 'Google Map' in driver.title

def sele(address):
    global driver
    query = driver.find_element_by_id('address')
    query.clear()
    query.send_keys(address)
    query.send_keys(Keys.RETURN)
    driver.implicitly_wait(0.7)
    query.send_keys(Keys.DOWN) #To solve in case there is autocomplete by Google
    query.send_keys(Keys.RETURN)
    button = driver.find_element_by_xpath("//*[@id='wrap']/div[2]/div[4]/div[1]/form[1]/div[2]/div/button")
    button.click()
    driver.implicitly_wait(0.7)
    try:
        alert=driver.switch_to_alert()
        alert.accept()
        latlong = ['Fail','Fail']
        return latlong
    except Exception :
        latraw = driver.find_element_by_id('latitude')
        longraw = driver.find_element_by_id('longitude')
        newquery = driver.find_element_by_id('address')
        lat = latraw.get_attribute('value')
        long = longraw.get_attribute('value')
        query = newquery.get_attribute('value')
        return [lat,long,query]

def wrapper(inputad,outputad,k):
    InFile = openpyxl.load_workbook(inputad)
    Sheet = InFile['Sheet1']
    workbook = xlsxwriter.Workbook(outputad)
    worksheet = workbook.add_worksheet()
    TotalLength = Sheet.max_row
    ProgressChecker = 0

    for i in range(1, TotalLength +1):
        ProgressChecker = ProgressChecker + 1
        addtext = Sheet[i][k].value
        try:
            latlong = sele(addtext)
            worksheet.write(i,0,addtext)
            worksheet.write(i,1,latlong[0])
            worksheet.write(i,2,latlong[1])
            worksheet.write(i,2,latlong[2])
            print("Progress: ", ProgressChecker, " out of " ,TotalLength)
        except Exception :
            worksheet.write(i,0,addtext)
            worksheet.write(i,1,"Failure Inside Iteration")
            print("Progress: ", ProgressChecker, " out of " ,TotalLength)
            continue
    complete = "complete"
    return complete

rawDescription: Selenium handling pop-up&Google Autocomplete


code:
import re
m = re.compile('(?u)[^\W0-9]\w*')
m.match('a')
m.match('9')
m.match('ab')
m.match('a9')
m.match('unicöde')
m.match('ödipus')

rawDescription: Match unicode in ply's regexes

description: Match unicode in ply's regexes


code:
def boolify(s):
    if s == 'True':
        return True
    if s == 'False':
        return False
    raise ValueError("huh?")

def autoconvert(s):
    for fn in (boolify, int, float):
        try:
            return fn(s)
        except ValueError:
            pass
    return s

rawDescription: Automatically Type Cast Parameters In Python


rawDescription: Select range of rows in query

description: Select range of rows in query


code:
try:
  # your insert here
  pass
except sqlite.IntegrityError:
  # data is duplicate insert
  pass

rawDescription: Web scraping with python and sqlite. How to store scraped data effectively?


code:
s='17GB'
for i,c in enumerate(s):
    if not c.isdigit():
        break
number=int(s[:i])
unit=s[i:]

rawDescription: Separate number from unit in a string in Python


code:
cut = slice(400, 600)
intval = np.trapz(np.trapz(func[cut, cut], y[cut], dx=x[1]-x[0]),
                  x[cut], dx=x[1]-x[0])

rawDescription: Integrating heatmap values within specific window


rawDescription: How to tell if string starts with a number?

description: Tell if string starts with a number


code:
if isinstance(iterable, basestring):
    iterable = iterable.split(',')

rawDescription: Python, elegant way to test for a set/list/tuple, expecting strings


code:
#!/sw/bin/python2.5

import warnings, sys

def customwarn(message, category, filename, lineno, file=None, line=None):
    sys.stdout.write(warnings.formatwarning(message, category, filename, lineno))

warnings.showwarning = customwarn
warnings.warn("test warning")

rawDescription: How to redirect python warnings to a custom stream?

description: Redirect python warnings to a custom stream


code:
any(exit_code !=0 for exit_code in result_list)
all(exit_code==0 for exit_code in result_list)

rawDescription: How to check 'if condition' for each item in a list

description: Check 'if condition' for each item in a list


code:
import re
html = open("main.html").read()
for match in re.findall('\<<<INCLUDE.*?\>>>',s):
    name = match.replace("<<<INCLUDE ","").replace(">>>","")
    content = open(name).read()
    html = html.replace(match,content)

open("processed.html","w").write(html)

rawDescription: Combining text files like how 'include' in PHP works using python


code:
from tkinter import *

def change_color(event):
    if event.type == "7":   # Enter
        event.widget.itemconfigure("one", fill="blue")
    elif event.type == "8": # Leave
        event.widget.itemconfigure("one", fill="white")

root = Tk()
f = Frame(root)
c = Canvas(f, bg="black")
f.pack()
c.pack()

line1      = c.create_line(10, 0,10,50, fill="white", tag="one")
line_side1 = c.create_line( 0,25,10,25, fill="white", tag="one")
line2      = c.create_line(30, 0,30,50, fill="white", tag="one")
line_side2 = c.create_line(30,25,40,25, fill="white", tag="one")

c.tag_bind("one", "<Enter>", change_color)
c.tag_bind("one", "<Leave>", change_color)

root.mainloop()

rawDescription: How can I bind multiple canvas elements together in order to change their color simultaneously?

description: Bind multiple canvas elements together in order to change their color simultaneously


code:
from itertools import chain
import pandas as pd

L = [
    [11, ['Blue','Green','Yellow'] , 1],
    [21, ['White','Green','Brown'] , 0],
    [31, ['Orange','Yellow']       , 0],
    [41, ['White','Orange','Brown'], 1],
]

colors = set(chain(*(row[1] for row in L)))
def row2obj(row):
    obj = {c: int(c in row[1]) for c in colors}
    obj['id'] = row[0]
    obj['vote'] = row[2]
    return obj

df = pd.DataFrame.from_records(row2obj(row) for row in L)

rawDescription: How can I convert list to DataFrame, where items of list will act as column in DataFrame?

description: Convert list to DataFrame, where items of list will act as column in DataFrame


code:
t = np.random.normal(size=100)
t[0] = vol
df = pd.DataFrame(t.cumsum())

rawDescription: Python pandas: Setting row values in Pandas using data of that column


code:
import datetime
from google.appengine.ext import db
from google.appengine.tools import bulkloader

class Contact(db.Model):

    date = db.DateTimeProperty(auto_now_add=True)

    owner = db.StringProperty()

    companyname = db.StringProperty()

    companyemail = db.EmailProperty()

def myfunc(x):
    temp = x.split(":mailto:")
    if len(temp) > 0:
        temp = temp[-1].split(":")
    else:
        return "defaultvalue"
    if len(temp) > 0:
        temp = temp[0]
    else:
        return "defaultvalue"
    temp = temp.split("<1>")[0]
    if temp is None or len(temp) < 5:
        return "defaultvalue"
    return temp

def mysecfunc(x):
    return x.split("<0>")[0]

class ContactLoader(bulkloader.Loader):
    def __init__(self):
        bulkloader.Loader.__init__(self, 'Contact',
                                   [
                                    ('companyname',mysecfunc),
                                    ('owner', lambda x:"somevalue"),
                                    ('companyemail',myfunc),
                                    ("date",lambda x:datetime.datetime.now()),
                                   ])

loaders = [ContactLoader]

rawDescription: Import large chunk of data into Google App Engine Data Store at one go


code: cmd = ['python', '-u', 'print.py']

rawDescription: How can I make subprocess get the stdout and stderr in order?

description: Make subprocess get the stdout and stderr in order


code:
from subprocess import check_call, STDOUT
from tempfile import NamedTemporaryFile

with NamedTemporaryFile() as f:
    check_call(['/etc/init.d/networking', 'restart'], stdout=f, stderr=STDOUT)
    f.seek(0)
    output = f.read()

rawDescription: Python subprocess check_output much slower then call


code:
score = 0
prev  = 0

for (x,y) in zip(seqA,seqB):

    if x == y:
        if prev == 1:
            score = score +3
        else:
            score = score +1
        prev = 1

    if x !=y :
        score = score - 1
        prev = 0

rawDescription: Comparing two lists and "looking back"

description: Comparing two lists and "looking back"


code:
class box ():

    def __init__ (self, name):
        self.name = name
        self.contents = []

    def store (self, junk):
        self.contents.append(junk)

    def open (self):
        return self.contents

rawDescription: Static class variables in Python -- Lists & Objects


code:
import sys

sys.stdout.close()
sys.stderr.close()

rawDescription: How to close stdout/stderr window in python?

description: Close stdout/stderr window in python


code:
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('create table t (id,a,b,c);')
conn.commit()
d = {0:[1.0,2.0,3.0]}
import itertools as it
c.execute('insert into t values (?,?,?,?)',[i for i in it.chain(d.keys(),*d.values())])
conn.commit()
results = c.execute('select * from t where id = 0').fetchall()
results

rawDescription: Convert python dictionary of lists to SQLite database


code:
my_str = "(4,301)"
num = -int(my_str.translate(None,"(),"))

rawDescription: Convert a number enclosed in parentheses (string) to a negative integer (or float) using Python?


code:
x
pd.rolling_mean(x, 3)
y
pd.rolling_mean(y, 3)

rawDescription: pandas rolling_mean of timedelta64 produces float64

description: Pandas rolling_mean of timedelta64 produces float64


code:
import Tkinter as tk
import ttk

DATA = {
    "filename":"file.txt",
    "filesize":"500kb",
    "maxcolwidth": {
        "col1":"300",
        "col2":"2",
        "col3":"3"
        },
    "numberofcolumns":"3",
    "datatypes": {
        "col1":"string",
        "col2":"int",
        "col3":"int"
        },
    "rowcount":"400"
    }

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.tree = ttk.Treeview(self, columns=("value",))
        self.vsb = ttk.Scrollbar(self, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=self.vsb.set)

        self.vsb.pack(side="right", fill="y")
        self.tree.pack(side="top", fill="both", expand=True)

        self.addNode(value=DATA, parentNode="")

    def addNode(self, value, parentNode="", key=None):
        if key is None:
            id = ""
        else:
            id = self.tree.insert(parentNode, "end", text=key)

        if isinstance(value, dict):
            self.tree.item(id, open=True)
            for (key, value) in value.iteritems():
                self.addNode(value, id, key)
        else:
            self.tree.item(id, values=(value,))

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Python - Turn dictionary into hierarchical tree like structure to be displayed in tkinter


code:
# Inherit from object. This is important.
class Vec2(object):
    def __init__(self):
        self.data = [0.0, 0.0]

    def __getitem__(self, index):
        return self.data[index]

    def __setitem__(self, index, val):
        self.data[index] = val

    @property
    def x(self):
        return self.data[0]
    @x.setter
    def x(self, val):
        self.data[0] = val

    @property
    def y(self):
        return self.data[1]
    @y.setter
    def y(self, val):
        self.data[1] = val

rawDescription: Attribute aliasing using __setattr__ in Python


code:
from itertools import ifilter
with open(fname, 'rb') as inp:
     filtered_inp = ifilter(lambda x: x.startswith('A'), inp)
     a = np.genfromtxt(filtered_inp)

rawDescription: Skip rows when reading data from file using numpy.genfromtxt


code:
from PIL import Image, ImageTk
import io

# needed to hold references
images = {}

def test(url):
    fp = urlopen(url)
    data = fp.read()
    fp.close()

    image = Image.open(io.BytesIO(data))
    photo = ImageTk.PhotoImage(image)
    images[url] = photo
    return photo

root = tk.Tk()

# define imagecmd callback imagecmd=test in order to handle the images
html = TkinterHtml(root, fontscale=0.8, imagecmd=test)

rawDescription: Python Tkinter TkinterHtml not functioning


rawDescription: How to retain only letter, digit, space using at most re module?

description: Retain only letter, digit, space using at most re module


code:
from pylab import figure, show, rand, colorbar
from matplotlib.patches import Ellipse
from matplotlib.collections import PatchCollection
from matplotlib import cm

#dummy data
A = rand(88)

#todo: are the i and j loops in the right order for the data?
spots = [Ellipse(xy=(i*475/11. + 18,j*275/8. + 16 + 16*(i%2 > 0)),
                 width=20, height=25)
        for i in range(11) for j in range(8)]

fig = figure()
ax = fig.add_subplot(111, aspect='equal')

p = PatchCollection(spots, cmap=cm.cubehelix_r)
p.set_array(A)
p.set_edgecolor('face')
ax.add_collection(p)
colorbar(p)

ax.set_xlim(0, 420)
ax.set_ylim(280, 0)

show()

rawDescription: Transform sensor intensity values to pixel intensity in python


code:
st = "hello world"
' '.join(format(ord(x), 'b') for x in st)
' '.join(format(x, 'b') for x in bytearray(st))

rawDescription: Convert string to binary in python

description: Convert string to binary in python


code:
matches = []
zipped_strings = zip(s1,s2,s3)
startpos = -1
for i in len(zipped_strings):
  c1,c2,c3 = zipped_strings[i]
  # if you're not inside a match,
  #  look for matching characters and save the match start position
  if startpos==-1 and c1==c2==c3:
    startpos = i
  # if you are inside a match,
  #  look for non-matching characters, save the match to matches, reset startpos
  elif startpos>-1 and not c1==c2==c3:
    matches.append((startpos,i,s1[startpos:i]))
    # matches will contain (startpos,endpos,matchstring) tuples
    startpos = -1
# if you're still inside a match when you run out of string, save that match too!
if startpos>-1:
  endpos = len(zipped_strings)
  matches.append((startpos,endpos,s1[startpos:endpos]))

rawDescription: SequenceMatcher for multiple inputs, not just two?


code:
import itertools

def partition(items, predicate=bool):
    a, b = itertools.tee((predicate(item), item) for item in items)
    return ((item for pred, item in a if not pred),
            (item for pred, item in b if pred))

odd, even = partition(numbers, lambda n: n % 2 == 0)

rawDescription: Python yield multiple assignment

description: Python yield multiple assignment


code:
def test():
    print('boo')

async def async_test():
    return test()

rawDescription: How can I create native coroutine from function object?

description: Create native coroutine from function object


code:
class WebSite(models.Model):
    ...
    maintenance_page = ForeignKey('app_name.Page')

class Page(models.Model):
    ...
    website = ForeignKey('app_name.WebSite')

rawDescription: Django split Models in différents models.py files give me import loops


code: next(itertools.islice(xrange(10), 5, 5 + 1))

rawDescription: Get the nth item of a generator in Python


code:
('/\d+',JsonHandler)

class JsonHandler(webapp.RequestHandler):
  def get(self):
    if self.request.get("fmt") == "json": #check the query string in the get handler
      self.response.out.write("hello")

rawDescription: Why cant map the url to my request handler


code:
b = {}
for k,v in a.items():
    d = defaultdict(int)
    for i in v:
        d[i] += 1
    b[k] = d.items()

rawDescription: Remove duplicate values from a defaultdict python


code:
import kivy
kivy.require('1.8.0')

from kivy.app import App
from kivy.lang import Builder

root = Builder.load_string('''
VideoPlayer:
    source: 'http://www.debone.com/VivVilConGminorRV578.mpg'
''')

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

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

rawDescription: How to play videos from the web like youtube in kivy

description: Play videos from the web like youtube in kivy


code:
import random
import urllib
import urllib2

url = 'https://www.interactivebrokers.com/java/classes/latest.jnlp?counter=' + str(random.random())

def download_file_1(url):
    urllib.urlretrieve(url + ".jnlp", "latest.jnlp")

def download_file_2(url):
    jnlpfile = urllib2.urlopen(url + ".jnlp")
    output = open('test.jnlp','wb')
    output.write(jnlpfile.read())
    output.close()

rawDescription: How to open Interactive Brokers' TWS from within Python

description: Open Interactive Brokers' TWS from within Python


code:
for z,b in zip(a,c):
    mouse.smooth_move(903, z)
    mouse.click()
    mouse.click(3)
    mouse.smooth_move(927, b)
    mouse.click()

rawDescription: Making a copy pasting script with autopy


code: [b for a in ((x,-x) for x in range(1, 10 + 1)) for b in a]

rawDescription: How to generate an alternating range?

description: Generate an alternating range


code:
# take EWMA in both directions with a smaller span term

fwd = ewma( x, span=15 ) # take EWMA in fwd direction
## This part should not be a problem, right?

bwd = ewma( x[::-1], span=15 ) # take EWMA in bwd direction
## x[::-1] means to go thr x, from end to beginning(!), with a step of -1
## (hence it is going from the back to the front)

c = np.vstack(( fwd, bwd[::-1] )) # lump fwd and bwd together
c = np.mean( c, axis=0 ) # average
## Then we reverse ewma into a beginning-to-end order
## and take the average of fwd and bwd
## IMO, better written just as:

#c =  0.5*(fwd + bwd[::-1])

rawDescription: Exponential Smoothing Average

description: Exponential Smoothing Average


code:
d = {}
f = open('scores.txt', 'r')
for line in f.readlines():
    name,score = line.split(":")
    d[name] = int(score)

rawDescription: How to split lines in a file and put data into a dictionary in python

description: Split lines in a file and put data into a dictionary in python


code:
from Tkinter import *

root=Tk()

sizex = 600
sizey = 400
posx  = 0
posy  = 0
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))

labels = []

def myClick():
    del labels[:] # remove any previous labels from if the callback was called before
    myframe=Frame(root,width=400,height=300,bd=2,relief=GROOVE)
    myframe.place(x=10,y=10)
    x=myvalue.get()
    value=int(x)
    for i in range(value):
        labels.append(Label(myframe,text=" mytext "+str(i)))
        labels[i].place(x=10,y=10+(30*i))
        Button(myframe,text="Accept").place(x=70,y=10+(30*i))

def myClick2():
    if len(labels) > 0:
        labels[0].config(text="Click2!")
    if len(labels) > 1:
        labels[1].config(text="Click2!!")

mybutton=Button(root,text="OK",command=myClick)
mybutton.place(x=420,y=10)

mybutton2=Button(root,text="Change",command=myClick2)
mybutton2.place(x=420,y=80)

myvalue=Entry(root)
myvalue.place(x=450,y=10)

root.mainloop()

rawDescription: Python Tkinter: addressing Label widget created by for loop


code:
import re
match = re.search(r'(\d+)\s*([+*/-])\s*(\d+)', '42 + 7')
match.group(1)  # <-- num1
match.group(2)  # <-- operation
match.group(3)  # <-- num2

rawDescription: Taking apart strings in Python

description: Taking apart strings in Python


code:
import xml.etree.ElementTree as xee

content='''

  something for link
  tttttk
  tyt for link

'''

def text_content(node):
    result=[]
    for elem in node.getiterator():
        text=elem.text
        if text and text.strip():
            result.append(text)
    return result

container_trs=xee.fromstring(content)
adict={}
for elem in container_trs:
    adict[elem]=text_content(elem)
print(adict)
# {<Element td at b767e52c>: ['tttttk'], <Element td at b767e58c>: ['tyt for link'], <Element td at b767e36c>: ['something for link']}

rawDescription: Python ElementTree Check the node / element type


code:
for i in range(len(words)):
    for j in range(i+1, len(words)):
        word, other_word = words[i], words[j]
        ...

rawDescription: optimize word by word comparison

description: Optimize word by word comparison


code:
def funct(objnameOrType):
   dispatcher = {str: getObjByName,
                 type1: getObjByType1,
                 type2: getObjByType2}
   t = type(objnameOrType)
   obj = dispatcher[t](objnameOrType)
   doStuffWithObj(obj)

rawDescription: Elegant pattern for mutually exclusive keyword args?


rawDescription: getting aggregates of aggregates in pandas

description: Getting aggregates of aggregates in pandas


code:
with open('returns.csv', 'wb') as f:
    writer = csv.writer(f)
    for val in daily_returns:
        writer.writerow([val])

rawDescription: Writing a Python list into a single CSV column


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

from PyQt4 import QtGui, QtCore

class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.pushButtonImage = QtGui.QPushButton(self)
        self.pushButtonImage.setText("Insert Image!")
        self.pushButtonImage.clicked.connect(self.on_pushButtonImage_clicked)

        self.textEditImage = QtGui.QTextEdit(self)
        self.textEditImage.setPlainText("Insert an image here:")

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.pushButtonImage)
        self.layoutVertical.addWidget(self.textEditImage)

    def on_pushButtonImage_clicked(self):
        filePath = QtGui.QFileDialog.getOpenFileName(
            self,
            "Select an image",
            ".",
            "Image Files(*.png *.gif *.jpg *jpeg *.bmp)"
        )

        if not filePath.isEmpty():
            self.insertImage(filePath)

    def insertImage(self, filePath):
        imageUri = QtCore.QUrl(QtCore.QString("file://{0}".format(filePath)))
        image    = QtGui.QImage(QtGui.QImageReader(filePath).read())

        self.textEditImage.document().addResource(
            QtGui.QTextDocument.ImageResource,
            imageUri,
            QtCore.QVariant(image)
        )

        imageFormat = QtGui.QTextImageFormat()
        imageFormat.setWidth(image.width())
        imageFormat.setHeight(image.height())
        imageFormat.setName(imageUri.toString())

        textCursor = self.textEditImage.textCursor()
        textCursor.movePosition(
            QtGui.QTextCursor.End,
            QtGui.QTextCursor.MoveAnchor
        )
        textCursor.insertImage(imageFormat)

        # This will hide the cursor
        blankCursor = QtGui.QCursor(QtCore.Qt.BlankCursor)
        self.textEditImage.setCursor(blankCursor)

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.show()

    sys.exit(app.exec_())

rawDescription: Inserting QImage after string in QTextEdit


code:
from xlsxwriter.workbook import Workbook

workbook = Workbook('sequences.xlsx')
worksheet = workbook.add_worksheet()

red = workbook.add_format({'color': 'red'})
green = workbook.add_format({'color': 'green'})

sequences = [
    'ACAAGATG',
    'CCATTGTC',
    'CCCCGGCC',
    'CCTGCTGC',
    'GCTGCTCT',
    'CGGGGCCA',
    'GGCCACCG',
]

worksheet.set_column('A:A', 40)

for row_num, sequence in enumerate(sequences):

    format_pairs = []

    # Get each DNA base character from the sequence.
    for base in sequence.upper():

        # Prefix each base with a format.
        if base == 'A' or base == 'T':
            format_pairs.extend((red, base))

        elif base == 'G' or base == 'C':
            format_pairs.extend((green, base))

        else:
            # Non base characters are unformatted.
            format_pairs.append(base)

    worksheet.write_rich_string(row_num, 0, *format_pairs)

workbook.close()

rawDescription: Python: list of strings, change color of character if found (using xlsxwriter)


rawDescription: python match.group() but not mmatched

description: Python match.group() but not mmatched


code:
from django.db.models import *  # NOQA isort:skip
from django.contrib.gis.db.models.aggregates import *  # NOQA
from django.contrib.gis.db.models.fields import (  # NOQA
    GeometryCollectionField, GeometryField, LineStringField,
    MultiLineStringField, MultiPointField, MultiPolygonField, PointField,
    PolygonField, RasterField,
)
from django.contrib.gis.db.models.manager import GeoManager  # NOQA

rawDescription: GeoDjango - Which tables should inherit from django.contrib.gis.db.models?


code:
X = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
np.random.choice(X, 3, replace=False)

rawDescription: How to draw N elements of random indices from numpy array without repetition?

description: Draw N elements of random indices from numpy array without repetition


code:
for label in wizard.findChildren(QLabel):
    label.setOpenExternalLinks(True)

rawDescription: How to make links in a QWizard's subtitle clickable?

description: Make links in a QWizard's subtitle clickable


rawDescription: converting user input in python

description: Converting user input in python


code:
from lxml import etree

# ...

responseXmlRoot = etree.fromstring(response.content)
operationStatus = responseXmlRoot.xpath("//*[local-name()='status']/@*[local-name()='isSuccess']")
if not operationStatus or operationStatus[0] != 'true':
    errorDetails = responseXmlRoot.xpath("//*[local-name()='detail']/descendant::*/text()")
    raise Exception("Exception when trying to post user's credentials to NetSuitr. " + str(errorDetails[0]))

rawDescription: Python XPath processing library supporting 'local-name()' function


code:
def __eq__(self, other):
    return self.name == other.name \
        and self.row == other.row \
        and self.col == other.col \
        and self.up is other.up \
        and self.down is other.down \
        and self.left is other.left \
        and self.right is other.right

rawDescription: Determine if two dictionaries are equal Python error


code: 2 ** 2 ** numpy.arange(5)

rawDescription: How can I use numpy to calculate a series effectively?

description: Use numpy to calculate a series effectively


code:
import os.path

visited = set()
for path in path_list:
    head, tail = os.path.split(path)
    while head and tail:
        if head in visited:
            break
        head, tail = os.path.split(head)
    else:
        process(path)
        visited.add(path)

rawDescription: How to determine if a path is a subdirectory of another?

description: Determine if a path is a subdirectory of another


code:
import uno

def setMargin():
    doc = XSCRIPTCONTEXT.getDocument()
    oStyle = doc.StyleFamilies.getByName("PageStyles").getByName("Default")
    oStyle.TopMargin = 5000  #Not sure what the units are

rawDescription: Margin Openoffice python

description: Margin Openoffice python


code:
def fancyMap(array, low, high):
    array = [int(numeric_string) for numeric_string in array]
    minimum = min(array)
    maximum = max(array)

    diff = maximum - minimum
    diffScale = high - low

    return map ( lambda x: int((int(x)-minimum)*(float(diffScale)/diff)+low), array)

rawDescription: In Python, how can I map values onto other another scale?


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
x = [0, 0.2, 0.4, 0.6, 0.8]
y = [0, 0.5, 1, 1.5, 2.0]
colors = ['k']*len(x)
ax.scatter(x, y, c=colors, alpha=0.5)
ax.set_xlim((0,2))
ax.set_ylim((0,2))
x0,x1 = ax.get_xlim()
y0,y1 = ax.get_ylim()
ax.set_aspect(abs(x1-x0)/abs(y1-y0))
ax.grid(b=True, which='major', color='k', linestyle='--')
fig.savefig('test.png', dpi=600)
plt.close(fig)

rawDescription: How do I make a matplotlib scatter plot square?

description: Make a matplotlib scatter plot square


code:
struct.Struct('!Bffffff').size  # network byte order
struct.Struct('=Bffffff').size  # native byte order, no alignment.
struct.Struct('>Bffffff').size  # big endian
struct.Struct('<Bffffff').size  # little endian
struct.Struct('@Bffffff').size  # native byte order, alignment.

rawDescription: Python struct.Struct.size returning unexpected value


code:
import re
re.sub('(s|S)uite\s+\w+\s*', '', 'Suite 134A xxx')

rawDescription: Partial Variable length string removal in Python


code:
def amax2(x, *args, **kwargs):
    if 'key' not in kwargs:
        return numpy.amax(x,*args,**kwargs)
    else:
        key = kwargs.pop('key') # e.g. len, pop so no TypeError: unexpected keyword
        x_key = numpy.vectorize(key)(x) # apply key to x element-wise
        axis = kwargs.get('axis') # either None or axis is set in kwargs
        if len(args)>=2: # axis is set in args
            axis = args[1]

        # The following is kept verbose, but could be made more efficient/shorter
        if axis is None: # max of flattened
            max_flat_index = numpy.argmax(x_key, axis=axis)
            max_tuple_index = numpy.unravel_index(max_flat_index, x.shape)
            return x[max_tuple_index]
        elif axis == 0: # max in each column
            max_indices = numpy.argmax(x_key, axis=axis)
            return numpy.array(
                 [ x[max_i, i] # reorder for col
                     for i, max_i in enumerate(max_indices) ],
                 dtype=x.dtype)
        elif axis == 1: # max in each row
            max_indices = numpy.argmax(x_key, axis=axis)
            return numpy.array(
                 [ x[i, max_i]
                     for i, max_i in enumerate(max_indices) ],
                 dtype=x.dtype)

rawDescription: A key in numpy.amax

description: A key in numpy.amax


code:
pygame.font.get_fonts()
f2 = pygame.font.match_font(u'paktypetehreer')
f2
font = pygame.font.Font(f2, 60)
f = font.render(u"maçã, joão", 1, (255,255,255))
scr.blit(f, (200,100))

rawDescription: Pygame Font.render() cropping uppercase letters with acute accents, tilde or circunflex


code:
seen_items = set()
w = []
for item in v:
    if item not in seen_items:
        w.append(item)
        seen_items.add(item)

rawDescription: Python removing repetitions using list(set(v)) changes array order


code:
import time
import serial

# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
    port='COM2',
    baudrate=9600,
    timeout=1,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_TWO,
    bytesize=serial.SEVENBITS
)
ser.isOpen()
# Reading the data from the serial port. This will be running in an infinite loop.

while 1 :
        # get keyboard input
        bytesToRead = ser.inWaiting()
        data = ser.read(bytesToRead)
        time.sleep(1)
        print(data)

rawDescription: Reading from RS 232 port using python

description: Reading from RS 232 port using python


code: [m.groupdict() for m in regex.finditer(search_string)]

rawDescription: Python re.findall with groupdicts

description: Python re.findall with groupdicts


code:
def unquote(s):
    """unquote('abc%20def') -> 'abc def'."""
    list = s.split('%')
    res = [list[0]]
    del list[0]
    for item in list:
        if item[1:2]:
            try:
                res.append(chr(int(item[:2], 16))
                     + item[2:])
            except ValueError:
                res.append('%' + item)
        else:
            res.append('%' + item)
    return "".join(res)

rawDescription: Reason for Python 3's unquote making an alias of chr and int?


code:
def days_in_year(years, df_eq):
    df=df_eq.copy()
    for year in years:
        beg=pd.datetime(year,1,1)
        end=pd.datetime(year+1,1,1)
        df[year]=(df.end.where(df.end<=end,other=end)\
-df.start.where(df.start<=end,other=end).where(df.start>beg, beg))/(end-beg)
    return df

years=range(2011,2015)
df = days_in_year(years,df_eq)
first_sample_output=df.groupby(['char1'])[years].sum().reset_index()
second_sample_output=df.groupby(['char1','char2'])[years].sum().reset_index()

rawDescription: Pandas Efficient Way to Calculate Annual Inventory Based on Equipment Date Ranges


code:
from django.core.paginator import Paginator

def search(request):
    if 'results' in request.GET and request.GET['results']:
        page = request.GET.get('page', 1)

        results = request.GET['results']
        word = words.objects.filter(title__icontains = results).order_by('title')
        paginator = Paginator(word, 25) # Show 25 contacts per page
        word = paginator.page(page)
        return render_to_response('myapp/search.html',
                 {'word': word, 'query': results })
    else:
        return render(request, 'myapp/search.html')

rawDescription: How to paginate search results in Django?

description: Paginate search results in Django


code: C = [[x + y for x,y in zip(w,v)] for w,v in zip(A,B)]

rawDescription: How can I take two matrices as input

description: Take two matrices as input


code:
lst = [
        {
            'id': '1',
            'elements': 'A',
            'table': 'maps/partials/a.html',
            'chart': 'maps/partials/charts/a.html',
        },
        {
            'id': '2',
            'elements': 'B',
            'table': 'maps/partials/census/b.html',
            'chart': 'maps/partials/charts/b.html',
        },
        {
            'id': '3',
            'elements': ('C','D','E','F'),
            'table': 'maps/partials/census/common.html',
            'chart': 'maps/partials/charts/common.html',
        }]
some_arr = ['E','2011','English','Total']
st = set(some_arr)

from collections import Iterable
for d in lst:
    val = d["elements"]
    if isinstance(val, Iterable) and not isinstance(val, str):
        if any(ele in st for ele in val):
            print(d["id"])
    else:
        if val in st:
            print(d["id"])

rawDescription: How to retreive values from list: python

description: Retreive values from list: python


code:
import urllib, re, json
from bs4 import BeautifulSoup as bs

def img_data_filter(tag):
    if tag.name == "script" and tag.text.strip().startswith("var lazyImgs"):
        return True
    return False

response = urllib.urlopen("https://www.tripadvisor.it/Restaurant_Review-g3174493-d3164947-Reviews-Le_Ciaspole-Tret_Fondo_Province_of_Trento_Trentino_Alto_Adige.html")
soup = bs(response.read(), 'html.parser')
img_data = soup.find(img_data_filter)

js = img_data.text
js = js.replace("var lazyImgs = ", '')
js = re.sub(r";\s+var lazyHtml.+", '', js, flags=re.DOTALL)

imgs = json.loads(js)
suffix = 1

for img in imgs:
    img_url = img["data"]

    if not "media/photo-s" in img_url:
        continue

    img_name = img_url[img_url.rfind('/')+1:-4]
    img_name = "%s-%03d.jpg" % (img_name, suffix)
    suffix += 1

    urllib.urlretrieve(img_url, img_name)

rawDescription: Can I download a lazy load image?

description: Download a lazy load image


code:
import os
fp = os.path.join(request.folder,'private','tables.pkl')

rawDescription: web2py: Where should I store private, application-specific files?

description: Web2py: Where should I store private, application-specific files


code:
def readCountries(filename):
    open_file = open(filename, 'r')
    new_list = []
    contents = open_file.readlines()
    for i in range(len(contents)):
         lsSplit = contents[i].split(",")
         new_list.append([lsSplit[0], float(lsSplit[1].strip()), int(lsSplit[2])])
    open_file.close()
    return new_list

rawDescription: method which reads a file and returns a list of countries

description: Method which reads a file and returns a list of countries


code: from django.core.management.commands.compilemessages import compile_messages

rawDescription: How to compile gettext translations in setup.py of a Django app

description: Compile gettext translations in setup.py of a Django app


code:
class BrokenLinkEmailsMiddleware(object):

    def process_response(self, request, response):
        """
        Send broken link emails for relevant 404 NOT FOUND responses.
        """
        if response.status_code == 404 and not settings.DEBUG:
            domain = request.get_host()
            path = request.get_full_path()
            referer = request.META.get('HTTP_REFERER', 'None')
            is_not_search_engine = '?' not in referer
            is_ignorable = self.is_ignorable_404(path)
            if is_not_search_engine and not is_ignorable:
                ua = request.META.get('HTTP_USER_AGENT', '<none>')
                ip = request.META.get('REMOTE_ADDR', '<none>')
                mail_managers(
                    "Broken link on %s" % domain,
                    "Referrer: %s\nRequested URL: %s\nUser agent: %s\nIP address: %s\n" % (referer, path, ua, ip),
                    fail_silently=True)
        return response

    def is_ignorable_404(self, uri):
        """
        Returns True if a 404 at the given URL *shouldn't* notify the site managers.
        """
        return any(pattern.search(uri) for pattern in settings.IGNORABLE_404_URLS)

rawDescription: Django — send 404 emails without referrer


code:
render(request, 'configs/output.txt', {'configs': configs},
       content_type="text/plain")

rawDescription: Django: export view with variables as a plain text download


code:
import Tkinter as tk

class Example(tk.Frame):
  def __init__(self, parent):
      tk.Frame.__init__(self, parent)
      self.text = CustomText(self, wrap="word")
      self.text.pack(side="top", fill="both", expand=True)
      self.label = tk.Label(self, anchor="w")
      self.label.pack(side="bottom", fill="x")

      # this is where we tell the custom widget what to call
      self.text.set_callback(self.callback)

  def callback(self, result, *args):
      '''Updates the label with the current cursor position'''
      index = self.text.index("insert")
      self.label.configure(text="index: %s" % index)

class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)

        # Danger Will Robinson!
        # Heavy voodoo here. All widget changes happen via
        # an internal Tcl command with the same name as the
        # widget:  all inserts, deletes, cursor changes, etc
        #
        # The beauty of Tcl is that we can replace that command
        # with our own command. The following code does just
        # that: replace the code with a proxy that calls the
        # original command and then calls a callback. We
        # can then do whatever we want in the callback.
        private_callback = self.register(self._callback)
        self.tk.eval('''
            proc widget_proxy {actual_widget callback args} {

                # this prevents recursion if the widget is called
                # during the callback
                set flag ::dont_recurse(actual_widget)

                # call the real tk widget with the real args
                set result [uplevel [linsert $args 0 $actual_widget]]

                # call the callback and ignore errors, but only
                # do so on inserts, deletes, and changes in the
                # mark. Otherwise we'll call the callback way too
                # often.
                if {! [info exists $flag]} {
                    if {([lindex $args 0] in {insert replace delete}) ||
                        ([lrange $args 0 2] == {mark set insert})} {
                        # the flag makes sure that whatever happens in the
                        # callback doesn't cause the callbacks to be called again.
                        set $flag 1
                        catch {$callback $result {*}$args } callback_result
                        unset -nocomplain $flag
                    }
                }

                # return the result from the real widget command
                return $result
            }
            ''')
        self.tk.eval('''
            rename {widget} _{widget}
            interp alias {{}} ::{widget} {{}} widget_proxy _{widget} {callback}
        '''.format(widget=str(self), callback=private_callback))

    def _callback(self, result, *args):
        self.callback(result, *args)

    def set_callback(self, callable):
        self.callback = callable

if __name__ == "__main__":
  root = tk.Tk()
  frame = Example(root)
  frame.pack(side="top", fill="both", expand=True)
  root.mainloop()

rawDescription: binding to cursor movement doesnt change INSERT mark

description: Binding to cursor movement doesnt change INSERT mark


rawDescription: Convert '\x00' to ASCII in Python 3

description: Convert '\x00' to ASCII in Python 3


code:
import os
import webbrowser

html = '<html> ...  generated html string ...</html>'
path = os.path.abspath('temp.html')
url = 'file://' + path

with open(path, 'w') as f:
    f.write(html)
webbrowser.open(url)

rawDescription: Launch HTML code in browser (that is generated by BeautifulSoup) straight from Python


code:
class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
    def process_request(self, request, client_address):
        self.client_address = client_address
        return SimpleXMLRPCServer.SimpleXMLRPCServer.process_request(
            self, request, client_address)

server=SimpleXMLRPCServer.MyXMLRPCServer((host, port))

rawDescription: how can I get the ip address of the request in a regested function of python xmlrpc server

description: Get the ip address of the request in a regested function of python xmlrpc server


code:
from sqlalchemy.dialects.postgresql import ARRAY

class MyTable:
    __tablename__ = 'mytable'

    id = Column(Integer, primary_key=True)
    text_array = Column(ARRAY(Unicode))

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

rawDescription: Creating an array column within my model definition


code:
def count_obs(df, interval=7):
    idx = df['Date']
    df['temp'] = 1
    by_day = df.set_index('Date').resample('D').fillna(0)
    csum = by_day['temp'].cumsum()
    by_day['Count'] = csum - csum.shift(interval).fillna(0)
    return by_day.ix[by_day.index.isin(idx), 'Count']

df.groupby('Id').apply(count_obs)

rawDescription: Count number of observations by group in past week using pandas


code:
from c import modeltocopy
from b import dynamic_model as dyn_model_factory

ShadowModel = dyn_model_factory('ShadowModel', app_label='fake', fields=modeltocopy._meta.fields)

rawDescription: Importing a dynamically generated model class in `__init__.py`


code:
from itertools import chain
pd.DataFrame(list(chain.from_iterable(
    ((k, v) for v in vals) for (k, vals) in dct.items())),
    columns=('Column1', 'Column2'))

rawDescription: Create a dataframe from dictionary - python


code:
import numpy as np
from scipy.optimize import leastsq

def f(var,xs):
    return var[0]*np.exp(-var[1]*xs)+var[2]

def func(var, xs, ys):
    return f(var,xs) - ys

def dfunc(var,xs,ys):
    v = np.exp(-var[1]*xs)
    return [v,-var[0]*xs*v,np.ones(len(xs))]

xs = np.linspace(0,4,50)
ys = f([2.5,1.3,0.5],xs)
yn = ys + 0.2*np.random.normal(size=len(xs))
fit = leastsq(func,[10,10,10],args=(xs,yn),Dfun=dfunc,col_deriv=1)

rawDescription: method signature for jacobian func in scipy least squares

description: Method signature for jacobian func in scipy least squares


rawDescription: Prepending 1d array onto each 2d array of a 3d array


code:
import csv
import sys
from collections import Counter

def load_csv(fname, **kwargs):
    with open(fname, 'rb') as inf:
        in_csv = csv.reader(inf, **kwargs)
        return list(in_csv)

def save_csv(fname, data, header=None, **kwargs):
    with open(fname, 'wb') as outf:
        out_csv = csv.writer(outf, **kwargs)
        if header is not None:
            out_csv.writerow(header)
        out_csv.writerows(data)

def main(in_fname, out_fname):
    data = load_csv(in_fname, delimiter='\t')

    filtered = (row for row in data if len(Counter(row).items()) >= 4)
    # save_csv(out_fname, filtered, delimiter='\t')     # just skip this step!

    replace = dict(zip(
        ['A', 'G',  'C', 'T',  'Y',  'R', 'W',  'S',  'K',  'M', 'X', 'N', '-'],
        ['2', '19', '5', '29', '17', '7', '11', '13', '23', '3', '0', '0', '0']
    ))
    replaced = ([replace.get(item, item) for item in row] for row in filtered)
    save_csv(out_fname, replaced, delimiter='\t')

if __name__=="__main__":
    if len(sys.argv) < 3:
        print('Usage: myprog.py input.csv output.csv')
    else:
        main(sys.argv[1], sys.argv[2])

rawDescription: Python - tmp file or object

description: Python - tmp file or object


code:
import importlib
def allImports(globals):
    mod = importlib.import_module('Test', globals['__name__'])

    try:
        keys = mod.__all__
    except AttributeError:
        keys = dir(mod)

    for key in keys:
        if not key.startswith('_'):
            globals[key] = getattr(mod, key)

# …

allImports(globals())
Test # should work, you can also look into dir(Test) to find the class.

rawDescription: Python - Undefined class name after dynamic import


code:
import itertools
L = [1,2,3]
itertools.product(L,L)
list(_)

rawDescription: List multiplication

description: List multiplication


code:
def graphData(dateIndex,irValue):

    fig = plt.figure()
    ax1 = plt.subplot2grid((5,4), (0,0), rowspan=4, colspan=4)#, axisbg='#07000d')
    ax1 = plt.subplot(1,1,1)

    date = mdates.strpdate2num('%Y-%m-%d %H:%M:%S')

    datenum = [date(i) for i in dateIndex] # Apply your date function here.

    ax1.plot_date(datenum, irValue)
    ax1.grid(True)
    ax1.spines['bottom'].set_color("#5998ff")
    ax1.tick_params(axis='y')
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y %H:%M:%S'))

    fig.autofmt_xdate()

    plt.show()

rawDescription: Plot XLabel date format from object 'dateIndex'


code:
def intersect(List1, List2):
    # empty list for values that match
    ret = []
    for i in List2:
        for j in List1:
            if i in j:
                ret.append(j)
    return ret

List1 = ['abcd12', 'efgh34', 'ijkl56', 'mnop78']
List2 = ['abc', 'ijk']
print(intersect(List1, List2))

rawDescription: Matching two string lists that partially match into another list


code:
class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value
        self.show_hide_dialog() # or generate an event in general
    # ...

rawDescription: Bind event to variable in Python

description: Bind event to variable in Python


code:
from functools import partial
class Container(BoxLayout):
    container=ObjectProperty(None)
    SelectGamePopup = Popup(title='Start A New Game', size_hint=(None, None))
    ...
    def newGame(self):
        BlankLayout = BoxLayout(orientation='vertical')
        BlankGrid = GridLayout(cols=3, size_hint_y=7)
        DismissButton = Button(text='Back', size_hint_y=1)
        DismissButton.bind(on_press=Container.SelectGamePopup.dismiss)

        for files in os.listdir(os.path.join(os.getcwd(), 'Games')):
            addFile = files.rstrip('.ini')
            # normal button
            MydynamicButton = Button(text=addFile)
            # bind and send
            MydinamicButton.bind(on_press = partial(self.gamechooser ,addFile)) #use partila to send argument to callback
            BlankGrid.add_widget(MydinamicButton)

        BlankLayout.add_widget(BlankGrid)
        BlankLayout.add_widget(DismissButton)

        Container.SelectGamePopup.content = BlankLayout
        Container.SelectGamePopup.size=(self.container.width - 10, self.container.height - 10)
        Container.SelectGamePopup.open()
    # you can use *args to get all extra argument that comes with on_press in a list
    def gameChooser(self, game ,*args):
        Container.SelectGamePopup.dismiss
        print(game)

rawDescription: Kivy Builder - Dynamic Button on_press

description: Kivy Builder - Dynamic Button on_press


code:
def compute_hhi(buyer_month):
    total = float(buyer_month['Amount'].sum())
    top_3_amts = buyer_month['Amount'].order(ascending = False)[0:3]
    hhi_elements = [(value/total)**2 for value in top_3_amts]
    hhi = sum(hhi_elements)
    return hhi

grouped = df.groupby(['Buyer','Month'])
hhis = grouped.apply(compute_hhi)

rawDescription: Calculating 3-firm HHI in Pandas

description: Calculating 3-firm HHI in Pandas


rawDescription: How do I get the individual digits of a number?

description: Get the individual digits of a number


code:
variable = core_func(arguments)

func2(variable)

func3(variable)

rawDescription: python use output from one function in other functions without calling all the other functions

description: Python use output from one function in other functions without calling all the other functions


code:
from collections import defaultdict
dir_dict = defaultdict(lambda: defaultdict(set))
for x in objects:
     dir_dict[x.state][x.city].add(x.address)

dir_list = dir_dict.keys()

rawDescription: A more pythonic approach to the following algorithm


rawDescription: Grouping a Pandas Dataframe by Date with Python and Plotting


code:
import numpy as np
np.s_[1:2:3]
Out[1]: slice(1, 2, 3)

rawDescription: Slice syntax to object

description: Slice syntax to object


code:
def recursiveLength(theString):
    if theString == '': return 0
    return 1 + recursiveLength(theString[1:])

rawDescription: Python string length recursion

description: Python string length recursion


rawDescription: Double-decoding unicode in python

description: Double-decoding unicode in python


code:
my_dialog = QDialog(self)
my_dialog.exec_()  # blocks all other windows until this window is closed.

rawDescription: How to create a modal window in pyqt?

description: Create a modal window in pyqt


code:
binary_expression1 = Table.id==1
binary_expression1
binary_expression2 = Table.id==1
binary_expression2
binary_expression1.compare(binary_expression2)

description: Unittesting sqlalchemy BinaryExpressions


code:
p.hset('blah', 'meh', 1)
p.hset('foo', 'bar', 1)
p.command_stack

rawDescription: View Commands in Pipeline in Redis-Py?

description: View Commands in Pipeline in Redis-Py


code:
for file_name in file_list:
    file_obj = open(file_name)
    file_obj.read()
    f.write(file_obj.read())

rawDescription: Skip first row in python

description: Skip first row in python


code:
y = df['a'].apply(lambda x: x.replace(year=1967, month=6, day=25)).tolist()
ax = plt.subplot()
ax.plot(df.index, y)
ax.yaxis.set_major_locator(HourLocator())
ax.yaxis.set_major_formatter(DateFormatter('%H:%M'))

rawDescription: how to plot time on y-axis in '%H:%M' format in matplotlib?

description: Plot time on y-axis in '%H:%M' format in matplotlib


code:
def set_name(self, new_name):
    old_name = self.name
    self.name = new_name

    print("Model name is now: %s" % new_name)
    if old_name != new_name:
        # name has changed - tell anyone who cares
        # (maybe bailiffs?)
        pub.sendMessage("NAME CHANGED", name=self.name)

rawDescription: Text entry in MVC architecture

description: Text entry in MVC architecture


code:
from multiprocessing import Process, Queue
from flaky.library import FlakyClient
import time

TIMEOUT_IN_SECS = 10

def make_flaky_call(queue):
    result = FlakyClient.call()
    queue.put(result)
    queue.put('END')

q = Queue()
proc = Process(target=make_flaky_call, args=(q,))
proc.start()
content = 0
result = None
while content != 'END':
    try:
        content = q.get(timeout=TIMEOUT_IN_SECS)
        if content != 'END':
            result = content
    except Empty:
        proc.terminate()
        raise Exception("Timeout during call to FlakyClient.call().")

rawDescription: How can you safeguard yourself from a flaky library call that might hang indefinitely?

description: Safeguard yourself from a flaky library call that might hang indefinitely


code:
def getMessageAuthor():
    author_id = []
    # get a list of ids and author_ids for every message
    for author in coll_message.find():
        author_id.append( (author['_id'], author['author_id']))
    # iterate through every author_ids to find the corresponding username
    for id, item in author_id:
        message = coll_message.find_one({"_id": id}, {"text": 1, "pub_date": 1})
        author = coll_user.find_one({"_id": item}, {"username": 1})
        merged = dict(chain((message.items() + author.items())))

rawDescription: How can I join data from two MongoDB collections in Python?

description: Join data from two MongoDB collections in Python


code:
lst=[]
if some_var == True:
    lst.append('a')
lst.append('b')
lst.append('c')
if other_var == 1:
    lst.append('d')
lst.append('e')

rawDescription: Joining a list in python with different conditions


code:
get_freq = lambda ts: (ts.last() - ts.first()).astype('timedelta64[h]') / len(ts)
twitterDataFrame['frequency'] = twitterDataFrame.groupby('UserID')['CreatedAtForCalculations'].transform(get_freq)

rawDescription: Pandas Split-Apply-Combine

description: Pandas Split-Apply-Combine


code:
x = sympy.Symbol("x")
f = sympy.Function("f")
y = x * f(x)
y
y.diff(x)

rawDescription: Differentiating a product with an unknown function - sympy


code:
for line in log:
    print(line)

rawDescription: How do get Python to print the contents of a file


code:
store['vat'] = json.dumps(store['vat'])
store

rawDescription: What is a more succinct way of converting python boolean to javascript boolean literals?


code:
import itertools
l = [[['a','b','c'], '2'], [['d','e','f'], '3']]
[list(itertools.chain.from_iterable(i)) for i in l]

rawDescription: Concatenate list and number in a sublist in Python


rawDescription: Read hex characters and convert them to utf-8 using python 3


code:
data = pd.read_csv('data.txt',names=['X1','X2','Y'])
clf = LDA()
clf.fit(data.loc[:,'X1':'X2'].values, data.Y)

rawDescription: Loading data with Pandas and performing LDA with SkLearn


code:
Levenshtein.editops("FBBDE", "BCDASD")
[('delete', 0, 0), ('replace', 2, 1), ('insert', 4, 3), ('insert', 4, 4), ('replace', 4, 5)]

rawDescription: How to modify Levenshtein algorithm, to know if it inserted, deleted, or substituted a character?

description: Modify Levenshtein algorithm, to know if it inserted, deleted, or substituted a character


code:
from PySide import QtCore, QtGui

try:
  _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
  _fromUtf8 = lambda s: s

class Ui_MainWindow(object):
  def setupUi(self, MainWindow):
    self.mainwindow=MainWindow
    MainWindow.setObjectName(_fromUtf8("MainWindow"))
    MainWindow.resize(400, 300)
    self.centralWidget = QtGui.QWidget(MainWindow)
    self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
    self.mMyButton = QtGui.QPushButton(self.centralWidget)
    self.mMyButton.setGeometry(QtCore.QRect(140, 90, 99, 27))
    self.mMyButton.setObjectName(_fromUtf8("mMyButton"))
    MainWindow.setCentralWidget(self.centralWidget)
    self.menuBar = QtGui.QMenuBar(MainWindow)
    self.menuBar.setGeometry(QtCore.QRect(0, 0, 400, 25))
    self.menuBar.setObjectName(_fromUtf8("menuBar"))
    MainWindow.setMenuBar(self.menuBar)
    self.mainToolBar = QtGui.QToolBar(MainWindow)
    self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
    MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
    self.statusBar = QtGui.QStatusBar(MainWindow)
    self.statusBar.setObjectName(_fromUtf8("statusBar"))
    MainWindow.setStatusBar(self.statusBar)

    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)
    self.mMyButton.clicked.connect(self.showNewWindow)

  def retranslateUi(self, MainWindow):
    MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
    self.mMyButton.setText(QtGui.QApplication.translate("MainWindow", "Addition", None, QtGui.QApplication.UnicodeUTF8))

  def showNewWindow(self):
    ui = Ui_NewWindow()
    ui.setupUi(QtGui.QDialog())
    ui.NewWindow.exec_()

try:
  _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
  _fromUtf8 = lambda s: s

class Ui_NewWindow(object):
  def setupUi(self, NewWindow):
    self.NewWindow=NewWindow
    self.NewWindow.setObjectName(_fromUtf8("NewWindow"))
    self.NewWindow.resize(439, 225)
    self.centralwidget = QtGui.QWidget(NewWindow)
    self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
    self.pushButton_2 = QtGui.QPushButton(self.centralwidget)
    self.pushButton_2.setGeometry(QtCore.QRect(170, 140, 99, 27))
    self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
    self.widget = QtGui.QWidget(self.centralwidget)
    self.widget.setGeometry(QtCore.QRect(40, 30, 365, 89))
    self.widget.setObjectName(_fromUtf8("widget"))
    self.verticalLayout = QtGui.QVBoxLayout(self.widget)
    #self.verticalLayout.setMargin(0)
    self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
    self.horizontalLayout_2 = QtGui.QHBoxLayout()
    self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
    self.label_3 = QtGui.QLabel(self.widget)
    self.label_3.setObjectName(_fromUtf8("label_3"))
    self.horizontalLayout_2.addWidget(self.label_3)
    self.lineEdit = QtGui.QLineEdit(self.widget)
    self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
    self.horizontalLayout_2.addWidget(self.lineEdit)
    self.label_4 = QtGui.QLabel(self.widget)
    self.label_4.setObjectName(_fromUtf8("label_4"))
    self.horizontalLayout_2.addWidget(self.label_4)
    self.lineEdit_2 = QtGui.QLineEdit(self.widget)
    self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))
    self.horizontalLayout_2.addWidget(self.lineEdit_2)
    self.verticalLayout.addLayout(self.horizontalLayout_2)
    self.pushButton = QtGui.QPushButton(self.widget)
    self.pushButton.setObjectName(_fromUtf8("pushButton"))
    self.verticalLayout.addWidget(self.pushButton)
    self.horizontalLayout = QtGui.QHBoxLayout()
    self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
    self.label = QtGui.QLabel(self.widget)
    self.label.setObjectName(_fromUtf8("label"))
    self.horizontalLayout.addWidget(self.label)
    self.label_2 = QtGui.QLabel(self.widget)
    self.label_2.setObjectName(_fromUtf8("label_2"))
    self.horizontalLayout.addWidget(self.label_2)
    self.verticalLayout.addLayout(self.horizontalLayout)
    self.menubar = QtGui.QMenuBar(NewWindow)
    self.menubar.setGeometry(QtCore.QRect(0, 0, 439, 25))
    self.menubar.setObjectName(_fromUtf8("menubar"))

    self.statusbar = QtGui.QStatusBar(NewWindow)
    self.statusbar.setObjectName(_fromUtf8("statusbar"))

    self.retranslateUi(NewWindow)
    QtCore.QMetaObject.connectSlotsByName(NewWindow)
    self.pushButton.clicked.connect(self.sum)

  def sum(self):
    summed = float(self.lineEdit.text()) + float(self.lineEdit_2.text())
    self.label_2.setText(str(summed))

  def retranslateUi(self, NewWindow):
    self.NewWindow.setWindowTitle(QtGui.QApplication.translate("NewWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
    self.pushButton_2.setText(QtGui.QApplication.translate("NewWindow", "Exit", None, QtGui.QApplication.UnicodeUTF8))
    self.label_3.setText(QtGui.QApplication.translate("NewWindow", "A = ", None, QtGui.QApplication.UnicodeUTF8))
    self.lineEdit.setText(QtGui.QApplication.translate("NewWindow", "0.0", None, QtGui.QApplication.UnicodeUTF8))
    self.label_4.setText(QtGui.QApplication.translate("NewWindow", "B = ", None, QtGui.QApplication.UnicodeUTF8))
    self.lineEdit_2.setText(QtGui.QApplication.translate("NewWindow", "0.0", None, QtGui.QApplication.UnicodeUTF8))
    self.pushButton.setText(QtGui.QApplication.translate("NewWindow", "Add", None, QtGui.QApplication.UnicodeUTF8))
    self.label.setText(QtGui.QApplication.translate("NewWindow", "Answer  : ", None, QtGui.QApplication.UnicodeUTF8))
    self.label_2.setText(QtGui.QApplication.translate("NewWindow", "0.0", None, QtGui.QApplication.UnicodeUTF8))

if __name__ == "__main__":
  import sys
  app = QtGui.QApplication(sys.argv)
  MainWindow = QtGui.QMainWindow()
  ui = Ui_MainWindow()
  ui.setupUi(MainWindow)
  MainWindow.show()
  sys.exit(app.exec_())

rawDescription: The converted .py file of Qt is not working for opening new window


rawDescription: Python Selenium selecting div class

description: Python Selenium selecting div class


code:
from Tkinter import *

root = Tk()

canvas = Canvas(root)
canvas.grid()

canvas.create_line(0, 0, 20, 20, fill='green', width=2, tags='line1')
canvas.create_line(30, 30, 40, 40, fill='red', width=2, tags='line2')
canvas.create_line(50, 50, 60, 60, fill='blue', width=2,tags='line3')

legend_text = """
-------------------
|   ------     line1    |
|   ------     line2    |
|   ------     line3    |
-------------------"""

legend_frame = LabelFrame(canvas,text='Legend',padx=5, pady=5)
legend_label = Label(legend_frame,text=legend_text)
legend_label.pack()

canvas.create_window(120,200,window=legend_frame,anchor=E)

root.mainloop()

rawDescription: How can I display legend in Tkinter?

description: Display legend in Tkinter


code:
import time
import wx.wizard

class Wizard(wx.wizard.Wizard):
    def __init__(self, parent, title):
        wx.wizard.Wizard.__init__(self, parent, wx.ID_ANY, title)
        self.pages = []
        self.Bind(wx.wizard.EVT_WIZARD_PAGE_CHANGED, self.on_page_changed)

    def add_page(self, page):
        """Add a WizardPage to the pages list"""
        self.pages.append(page)

    def chain_pages(self):
        i = 0
        while 1:
            if i == len(self.pages) - 1:
                break
            else:
                wx.wizard.WizardPageSimple_Chain(self.pages[i],
                                                 self.pages[i + 1])
                i += 1

    def run(self):
        self.RunWizard(self.pages[0])

    def on_page_changed(self, evt):
        # if coming from self.pages[0]
        # and direction is forward
        if evt.GetDirection():
            direction = 'forward'
        else:
            direction = 'backward'

        if evt.GetPage() is self.pages[1]\
        and direction == "forward":
#             self.pages[1].fill_gauge()
            self.pages[1].timer.Start(1000)

class StartPage(wx.wizard.WizardPageSimple):

    def __init__(self, parent, title):
        wx.wizard.WizardPageSimple.__init__(self, parent)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.text = wx.StaticText(self, -1,
        "This is the First Page")
        # self.text.Wrap(parent.GetClientSizeTuple()[0])
        self.sizer.Add(self.text, 0, wx.ALIGN_CENTER | wx.ALL, 5)

class UpdatePage(wx.wizard.WizardPageSimple):
    def __init__(self, parent, title):
        wx.wizard.WizardPageSimple.__init__(self, parent)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.status = wx.StaticText(self, -1, "This is the Second Page")
        self.gauge = wx.Gauge(self, -1, name="Guage")

        self.sizer.Add(self.status, 0, wx.ALIGN_CENTER | wx.ALL, 5)
        self.sizer.Add(self.gauge, 0,
                       wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 10)
        self.SetSizer(self.sizer)

        self.gauge_pos = 0  # Added
        self.timer = wx.Timer(self)  # Added
        self.Bind(wx.EVT_TIMER, self.on_gauge_timer)  # Added

    def update(self, percent, status):
        self.status.SetLabel(status)
        self.gauge.SetValue(percent)
        # self.Refresh()

#     def fill_gauge(self):
#         x = 0
#         while x <= 100:
#             self.update(x, "Gauge is at %d" % x)
#             x += 10
#             time.sleep(1)

    def on_gauge_timer(self, event):  # Added method
        if self.gauge_pos < 100:
            self.gauge_pos += 10
            self.update(self.gauge_pos, "Gauge is at %d" % self.gauge_pos)
        else:
            self.timer.Stop()
            self.gauge_pos = 0

if __name__ == '__main__':
    app = wx.App()
    wizard = Wizard(None, "Updater")
    wizard.add_page(StartPage(wizard, "Updater"))
    wizard.add_page(UpdatePage(wizard, "Updater"))
    wizard.chain_pages()
    wizard.run()
    wizard.Destroy()
    app.MainLoop()

rawDescription: Using a wx.gauge in a wx.wizard

description: Using a wx.gauge in a wx.wizard


code:
import json, re
from bson import json_util

with open("data.tengenjson", "rb") as f:
    # read the entire input; in a real application,
    # you would want to read a chunk at a time
    bsondata = f.read()

    # convert the TenGen JSON to Strict JSON
    # here, I just convert the ObjectId and Date structures,
    # but it's easy to extend to cover all structures listed at
    # http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON
    jsondata = re.sub(r'ObjectId\s*\(\s*\"(\S+)\"\s*\)',
                      r'{"$oid": "\1"}',
                      bsondata)
    jsondata = re.sub(r'Date\s*\(\s*(\S+)\s*\)',
                      r'{"$date": \1}',
                      jsondata)

    # now we can parse this as JSON, and use MongoDB's object_hook
    # function to get rich Python data structures inside a dictionary
    data = json.loads(jsondata, object_hook=json_util.object_hook)

    # just print the output for demonstration, along with the type
    print(data)
    print(type(data))

    # serialise to JSON and print
    print(json_util.dumps(data))

rawDescription: How can I use Python to transform MongoDB's bsondump into JSON?

description: Use Python to transform MongoDB's bsondump into JSON


code:
Enter=[7.12,
       7.14,
       7.24,
       7.45,
       7.28,
       7.31,
       7.18,
       7.25,
       7.33,
       7.38] #A list for the times of cars passing Camera A

Leave=[7.56,
       7.24,
       7.48,
       7.52,
       7.45,
       7.57,
       7.22,
       7.31,
       7.37,
       7.41] #A list for the times of cars passing Camera B

for enter_data, leave_data in zip(Enter, Leave):
    print(leave_data - enter_data)

rawDescription: Subtraction of two items from two lists in for command


code:
import matplotlib.pyplot as plt

plt.plot(x_A,y_A,'g--', label="plot A")
plt.plot(x_B,y_B,'r-o', label="plot A")
plt.legend()
plt.show()

rawDescription: matplotlib.pyplot How to name different lines in the same plot?

description: Matplotlib.pyplot How to name different lines in the same plot


code:
s = StringIO.StringIO()
np.savetxt(s, (1,2,3))
s.getvalue()

rawDescription: Numpy savetxt to a string

description: Numpy savetxt to a string


rawDescription: Python regex for Python function signatures


code:
zipped = ZipFile(...)
zipped.writestr('archive_name', default_storage_object.read())

rawDescription: Adding a file-like object to a Zip file in Python


code:
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
lc = LineCollection(points[edges])
fig = plt.figure()
plt.gca().add_collection(lc)
plt.xlim(points[:,0].min(), points[:,0].max())
plt.ylim(points[:,1].min(), points[:,1].max())
plt.plot(points[:,0], points[:,1], 'ro')
fig.savefig('full_figure.png')

rawDescription: Plotting large numbers of points and edges in matplotlib


code:
import turtle as t
polygon = [(0,0), (0,100), (100,0), (100,100)]
t.goto(0,0)
fp = None
for p in polygon:
  t.goto(p)
  if not fp: fp=p
t.goto(fp)
t.up()
t.goto(90,90)
t.write("90,90")
t.dot(10)
t.goto(50,80)
t.write("50,80")
t.dot(10)
t.done()

rawDescription: Point in convex polygon

description: Point in convex polygon


code:
df['SpeedMean'] = df.groupby('ID')['Duration'].transform(lambda s: s < s.median()).astype(int)
df['SpeedMean'] = df.groupby('ID')['Duration'].transform(lambda s: s < s.mean()).astype(int)
df['SpeedMedian'] = df.groupby('ID')['Duration'].transform(lambda s: s < s.median()).astype(int)
df

rawDescription: Pandas: Applying a function to each group independently


code:
import profile
import numpy as NP

def np_test(a2darray) :
  row_sums = NP.sum(a2darray, axis=1)
  return NP.sum(row_sums)

def stdlib_test2(a2dlist) :
  return sum([sum(row) for row in a2dlist])

A = NP.random.randint(1, 6, 1e7).reshape(1e4, 1e3)
B = NP.ndarray.tolist(A)

profile.run("np_test(A)")
profile.run("stdlib_test2(B)")

rawDescription: Would you use numpy if you were just manipulating a sequence of binary values?


code:
def messageBoxIcon(mbicon, widget=None):
    if widget is not None:
        style = widget.style()
    else:
        style = QtGui.QApplication.style()
    size = style.pixelMetric(
        QtGui.QStyle.PM_MessageBoxIconSize, None, widget)
    if mbicon == QtGui.QMessageBox.Information:
        icon = style.standardIcon(
            QtGui.QStyle.SP_MessageBoxInformation, None, widget)
    elif mbicon == QtGui.QMessageBox.Warning:
        icon = style.standardIcon(
            QtGui.QStyle.SP_MessageBoxWarning, None, widget)
    elif mbicon == QtGui.QMessageBox.Critical:
        icon = style.standardIcon(
            QtGui.QStyle.SP_MessageBoxCritical, None, widget)
    elif mbicon == QtGui.QMessageBox.Question:
        icon = style.standardIcon(
            QtGui.QStyle.SP_MessageBoxQuestion, None, widget)
    else:
        icon = QtGui.QIcon()
    if not icon.isNull():
        return icon.pixmap(size, size)
    return QtGui.QPixmap()

rawDescription: Draw error dialog icon myself in PyQt / PySide


code:
leg=plt.legend(bbox_to_anchor=(1.005, 1), loc=2, borderaxespad=0.)

for l in leg.get_lines():
    l.set_alpha(1)
    l.set_marker('.')

rawDescription: Change size/alpha of markers in the legend box of matplotlib


code: [x for x in itertools.imap(complex,a,b)][1::2]

rawDescription: Can python itertools.imap(func,p,q) work with a conditional test on the index (e.g. to get elements with odd indexes only)?


code:
a = np.random.rand(2,2)
a
a.repeat(2, 0).repeat(2, 1)

rawDescription: Dividing numpy 2D array into finer resolution


code:
def  main():
    done = False
    P = ""
    while not done:
        new_line = input()
        if new_line != "###":
            P += new_line + " "
        else:
            done = True
    poem_words = P.lower().split()
    poem_words.sort()

    # Initialize variables
    temp = ""
    max_count = 0
    icount = 1
    max_word = ""

    # Do the loop
    for i in range(len(poem_words)):
        if temp == poem_words[i]:
            icount += 1
        else:
            temp = poem_words[i]
            icount = 1
        if icount > max_count:
            max_count = icount
            max_word = temp
    print(max_word)
    return

if __name__ == "__main__":
    main()

rawDescription: Python 3: Finding word which appears the most times without using import or counter or dictionary, only simple tools like .split()	and .lower()


code:
for root, dirs, files in os.walk(path):
    # do whatever you want to with dirs and files
    if root != path:
        # one level down, modify dirs in place so we don't go any deeper
        del dirs[:]

rawDescription: Getting sub directories and files using python


code:
import csv

def csv_get(csvfile):
    with open(csvfile) as f:
        for row in csv.reader(f):
            for i in row:
                yield i

def csv_cmp(csvfile1, csvfile2, output):
    row = []
    read_file_2 = csv_get(csvfile2)

    for value_1 in csv_get(csvfile1):
        value_2 = read_file_2.next()
        print("File 1: {} File 2: {}").format(value_1, value_2)
        difference = int(value_1) - int(value_2)
        row.append(difference)

    with open(output, "w") as output_file:
        csv.writer(output_file).writerow(row)

    read_file_2.close()

csv_cmp(csvfile1="C:\\...\\a.csv",
        csvfile2="C:\\...\\b.csv",
        output="C:\\...\\c.csv")

rawDescription: Find the difference of the two csv files


code:
df = pd.DataFrame({'Type' : ['Pokemon', 'Pokemon', 'Bird', 'Pokemon', 'Bird', 'Pokemon', 'Pokemon', 'Bird'],'Name' : ['Jerry', 'Jerry', 'Flappy Bird', 'Mudkip','Pigeon', 'Mudkip', 'Jerry', 'Pigeon']})
f = df.groupby(['Type','Name'])['Type'].agg({'Frequency':'count'})
f.sort('Frequency',ascending=False, inplace=True)

d = {k:list(f.ix[k].index) for k in f.index.levels[0]}
print(d)
# {'Bird': ['Pigeon', 'Flappy Bird'], 'Pokemon': ['Jerry', 'Mudkip']}

rawDescription: Create a dictionary from groupby object,Python


code:
import sys, msvcrt
import time

print("Please press a key to see its value")
while 1:
    print("the key is")
    if msvcrt.kbhit(): # <--------
        key = msvcrt.getch()
        print(key)
        if ord(key) == 27:
            sys.exit()
    time.sleep(0.1)

rawDescription: msvcrt getch pauses script, has to continue

description: Msvcrt getch pauses script, has to continue


code:
n = 6
arr = np.array([n-2, n-1, n, n, n+1, n+1, n+2, n+3])
np.tile(arr, n)
np.tile(arr, n).reshape(n, arr.size)

rawDescription: Creating a numpy array with repetitive pattern


code:
cut_idx = np.unique(np.where(B[:,1:].T)[0],return_index=True)[1]
out_list_ = np.split(X[:,1:].T[B[:,1:].T],cut_idx[1:])

rawDescription: Numpy generation of subsets of global array based on mask