code:
# get all the items
matches = re.findall(r'\w+=".+?"', s) + re.findall(r'\w+=[\d.]+',s)

# partition each match at '='
matches = [m.group().split('=', 1) for m in matches]

# use results to make a dict
d = dict(matches)

rawDescription: Simple way to convert a string to a dictionary


code:
# module level variable.  can be initialized later,
# but generally just want to create this once.
db = create_engine('mysql+pymysql://root:@127.0.0.1/mydb')

# module level MetaData collection.
metadata = MetaData()

def add_odm_object(obj, table_name, primary_key, unique_column):
    with db.begin() as connection:

        # will load table_name exactly once, then store it persistently
        # within the above MetaData
        t = Table(table_name, metadata, autoload=True, autoload_with=conn)

        s = t.select(t.c[unique_column] == obj[unique_column])
        rs = connection.execute(s)
        r = rs.fetchone()
        if not r:
            i_res = connection.execute(t.insert(), some_col=obj)
            v_id = i_res.inserted_primary_key[0]
            return v_id
        else:
            return r[primary_key]

rawDescription: Close SQLAlchemy connection

description: Close SQLAlchemy connection


code:
['a{}'.format(i) for i in range(1, 20)]
','.join(['a{}'.format(i) for i in range(1, 20)])

rawDescription: Python: Short way of creating a sequential list with a prefix


code:
import subprocess
host = subprocess.check_output(['hostname', '-I'], shell=True, universal_newlines=True) # a string is returned
curl = subprocess.check_output(['curl', 'ipinfo.io/ip'], shell=True, universal_newlines=True)

rawDescription: Python bash output into string

description: Python bash output into string


code:
@route ('/tagTweets', method='POST')
def tagTweets():
     response.content_type = 'application/json'
     sender = request.json['sender']
     receiver = request.json['receiver']
     message = request.json['message']

rawDescription: Sending JSON through requests module and catching it using bottle.py and cherrypy


code:
def getDateFromTuple(tuple):
    return datetime.datetime.strptime(tuple[0], "%d/%m/%Y %H:%M:%S")

sortedKeyList = sorted(tupleList, key=getDateFromTuple, reverse=True)

rawDescription: How can I sort a date in format: day/month/year hour:min:sec

description: Sort a date in format: day/month/year hour:min:sec


code:
defaults = {'added_by': request.user}
obj, created = SocialGroupMembers.objects.get_or_create(
        social_group=social_group, profile=profile, defaults=defaults)

rawDescription: Django get_or_create, how to say commit=False


code:
from ast import literal_eval
with open('filein.txt') as fIn, open('fileout.txt', 'w+') as fOut:
    for line in fIn:
        first, second = line.split(None, 1)
        for item in literal_eval(second):
            fOut.write('{},{}\n'.format(first, item))

rawDescription: Python parse string

description: Python parse string


code:
from Tkinter import *

gui = Tk()  #create an object
gui.title("xyz")
gui.geometry("900x300")

GuiLabel1 = Label(gui,text="hi everyone!!!!!!")
GuiLabel1.grid(row=0, column=0)

GuiLabel2 = Label(gui,text="File")
GuiLabel2.grid(row=3, column=0)

bar=Entry(gui)
bar.grid(row=1, column=1)

button1= Button(gui, text="Browse", width=test_width)
button1.grid(row=1, column=2)
button2= Button(gui, text="Process", width=test_width)
button2.grid(row=2, column=2)

test_width=20
for ctr in range(4):
    button= Button(gui, text="ABC"+str(ctr+1), width=test_width)
    button.grid(row=3, column=ctr)

## empty column between
gui.columnconfigure(4, minsize=50)
button7= Button(gui, text="ABC")
button7.grid(row=3, column=5)

gui.mainloop()

rawDescription: Python GUI using Tkinter - widget positioning is not proper


code:
items = ['Item'] * 6
for i, item in enumerate(items, start=1):
    number = (i + 1) / 2
    print('{} {}'.format(number, item))

rawDescription: Print Successive Numbers That Appear Twice?


code:
from sqlalchemy import Table, Column, MetaData, DateTime
from datetime import datetime, timedelta

metadata = MetaData()
example = Table('users', metadata,
   Column('expire', DateTime)
)

tomorrow = datetime.now() + timedelta(days=1)

ins = example.insert().values(expire=tomorrow)

rawDescription: Using DATEADD in sqlalchemy

description: Using DATEADD in sqlalchemy


code:
import sys, argparse
parser = argparse.ArgumentParser(description='my illustrative example', argument_default=argparse.SUPPRESS)
parser.add_argument('--content', metavar='file',
                     default='content.txt', type=argparse.FileType('r'),
                     help='file to process (defaults to content.txt)')
parser._parse_known_args(sys.argv[1:], argparse.Namespace())
args = parser.parse_args()

rawDescription: Specifying default filenames with argparse, but not opening them on --help?


rawDescription: python: multidimensional sorting of class object

description: Python: multidimensional sorting of class object


code:
from django.test import Client
c = Client()
response = c.post('/login/', {'username': 'john', 'password': 'smith'})
response.status_code
response = c.get('/customer/details/')
response.content

rawDescription: automated way to check if url loads but not actually run app django?

description: Automated way to check if url loads but not actually run app django


rawDescription: Finding whether a string starts with one of a list's variable-length prefixes


code:
import requests
r = requests.get('http://github.com', allow_redirects=False)
print(r.status_code)

rawDescription: Is there an easy way to request a URL in python and NOT follow redirects?


code:
if __name__ == '__main__':
   log_file = 'log_file.txt'
   f = open(log_file, "w")
   runner = unittest.TextTestRunner(f)
   unittest.main(testRunner=runner)
   f.close()

rawDescription: Log Unittest output to a text file

description: Log Unittest output to a text file


code:
dct = dict(zip(data2['causes'], data2['analyst']))
all_data = mlab.rec_append_fields(data1, 'analyst',
    [dct[x] for x in data1['causes']])

rawDescription: Join Recarrays by attributes in Python

description: Join Recarrays by attributes in Python


code:
for i in range(len(list_of_integers)):
    n = list_of_integers[i]
    remaining = list_of_integers[i+1:]
    found = find_sum(remaining, target_sum, partial_solution + n)
    if found:
        return True

rawDescription: Python stop recursion once solution is found


code:
font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 3, 8) #Creates a font
x = 10 #position of text
y = 20 #position of text
cv.PutText(image,"Hello World!!!", (x,y),font, 255) #Draw the text

rawDescription: how to print a text to a frame in opencv-python

description: Print a text to a frame in opencv-python


code:
def copydoc(fromfunc, sep="\n"):
    """
    Decorator: Copy the docstring of `fromfunc`
    """
    def _decorator(func):
        sourcedoc = fromfunc.__doc__
        if func.__doc__ == None:
            func.__doc__ = sourcedoc
        else:
            func.__doc__ = sep.join([sourcedoc, func.__doc__])
        return func
    return _decorator

class A(object):
  def myfunction():
    """Documentation for A."""
    pass

class B(A):
  @copydoc(A.myfunction)
  def myfunction():
    """Extra details for B."""
    pass

rawDescription: Is there a way to let classes inherit the documentation of their superclass with sphinx?


code:
r = rrule(DAILY,dtstart=datetime(2013,7,15,0,0,0), until=datetime.now())
list(r)
r._until = datetime(2013, 7, 20, 0, 0)
list(r)

rawDescription: How to edit existing rrule?

description: Edit existing rrule


code:
import numpy as np
a = np.arange(12).reshape((3,4))
a
np.diff(a,axis = 1) # row-wise
np.diff(a, axis = 0) # column-wise

rawDescription: Numpy: calculate edges of a matrix

description: Numpy: calculate edges of a matrix


rawDescription: How to efficiently unfold query results into a dictionary

description: Efficiently unfold query results into a dictionary


code:
musical_scale = ['C', 'D', 'E', 'F', 'G', 'A', 'B']
getValue(0, musical_scale)
getValue(9, musical_scale)

rawDescription: How can list[n] point to list[0]? Getting items not in sequence


code:
import matplotlib.pyplot as plt
daysofweek = {1:('Sunday','r'),
              2:('Monday','g'),
              3:('Tuesday','b'),
              4:('Wednesday','yellow'),
              5:('Thursday','k'),
              6:('Friday', 'magenta'),
              7:('Saturday', 'orange')}
ax1 = plt.subplot(111)

xval = [2., 4., 7.]
yval = [2.5, 3.6, 2.7]

for j in range(len(xval)):
    ax1.bar(xval[j], yval[j], width=0.8, bottom=0.0, align='center', color=daysofweek[xval[j]][1], alpha=0.6, label=daysofweek[xval[j]][0])
ax1.set_xticks(xval)
ax1.set_xticklabels([daysofweek[i][0] for i in xval])
ax1.legend()
plt.show()

rawDescription: How to create custom legend in matplotlib based on the value of the barplot?

description: Create custom legend in matplotlib based on the value of the barplot


code:
import matplotlib.pyplot as plt
def main():
    x_values = [1,2,3,4,5]
    y_values_1 = [1,2,3,4,5]
    y_values_2 = [2,4,6,8,10]
    f, ax = plt.subplots(1,1)
    rbar = ax.bar(x_values,y_values_2,color='r')
    bbar = ax.bar(x_values,y_values_1,color='b')
    return rbar, bbar

if __name__ == '__main__':
    rbar, bbar = main()
    # do stuff with the barplot data:
    assert(rbar.patches[0].get_facecolor()==(1.0,0.,0.,1.))
    assert(rbar.patches[0].get_height()==2)

rawDescription: Matplotlib: get colors and x/y data from a bar plot


code:
for your_dir in dirs_to_modify:
    for root, dirs, files in os.walk(your_dir):
        for d in dirs:
            os.chmod(os.path.join(root, d), 777)
        for f in files:
            os.chmod(os.path.join(root, f), 777)

rawDescription: Recursively set all files and folders to 777 from this list


code:
import csv
import io

def csv_generator(data_generator):
    csvfile = io.BytesIO()
    csvwriter = csv.writer(csvfile)

    def read_and_flush():
        csvfile.seek(0)
        data = csvfile.read()
        csvfile.seek(0)
        csvfile.truncate()
        return data

    for row in data_generator:
        csvwriter.writerow(row)
        yield read_and_flush()

def csv_stream_response(response, iterator, file_name="xxxx.csv"):

    response.content_type = 'text/csv'
    response.content_disposition = 'attachment;filename="' + file_name + '"'
    response.charset = 'utf8'
    response.content_encoding = 'utf8'
    response.app_iter = csv_generator(iterator)

    return response

rawDescription: Python: generate xlsx in memory and stream file download?


code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2013-2014  Diego Torres Milano
Created on 2014-12-05 by Culebra v8.18.1
                      __    __    __    __
                     /  \  /  \  /  \  /  \
____________________/  __\/  __\/  __\/  __\_____________________________
___________________/  /__/  /__/  /__/  /________________________________
                   | / \   / \   / \   / \   \___
                   |/   \_/   \_/   \_/   \    o \
                                           \_____/--<
@author: Diego Torres Milano
@author: Jennifer E. Swofford (ascii art snake)
'''

import re
import sys
import os

import unittest

from com.dtmilano.android.viewclient import ViewClient, CulebraTestCase

class CulebraTests(CulebraTestCase):

    @classmethod
    def setUpClass(cls):
        cls.kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': False}
        cls.kwargs2 = {'startviewserver': True, 'forceviewserveruse': False, 'autodump': False, 'ignoreuiautomatorkilled': True}
        cls.options = {'start-activity': None, 'multi-device': False, 'unit-test-class': True, 'save-screenshot': None, 'use-dictionary': False, 'dictionary-keys-from': 'id', 'scale': 1, 'find-views-with-content-description': True, 'window': -1, 'orientation-locked': None, 'save-view-screenshots': None, 'find-views-by-id': True, 'do-not-verify-initial-screen-dump': True, 'use-regexps': False, 'auto-regexps': None, 'use-jar': False, 'verbose-comments': False, 'gui': True, 'find-views-with-text': True, 'prepend-to-sys-path': False, 'output': '/Users/diego/tmp/settings-wifi.py', 'unit-test-method': None, 'interactive': False}
        cls.sleep = 5

    def setUp(self):
        super(CulebraTests, self).setUp()

    def tearDown(self):
        super(CulebraTests, self).tearDown()

    def preconditions(self):
        if not super(CulebraTests, self).preconditions():
            return False
        return True

    def testSomething(self):
        if not self.preconditions():
            self.fail('Preconditions failed')

        self.vc.dump(window=-1)
        self.vc.findViewWithTextOrRaise(re.compile(u'Wi.Fi')).touch()
        self.vc.sleep(CulebraTests.sleep)
        self.vc.dump(window=-1)
        try:
            self.assertIsNotNone(self.vc.findViewWithText(u'OFF'))
        except:
            self.vc.findViewWithTextOrRaise(u'ON').touch()

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

rawDescription: Python - turn off wifi with MonkeyRunner


code: re.sub(r"\bksu\b", "King Saud University", string, flags=re.I, count=1)

rawDescription: how to replace only the first word in regular expression in python

description: Replace only the first word in regular expression in python


code:
#Create connection to ec2, credentials stored in environment
ec2_conn = connect_ec2()

conn = regions[3].connect(aws_access_key_id= access, aws_secret_access_key = secret_key)
loadbalancers = conn.get_all_load_balancers()
for lb in loadbalancers:
    for i in lb.instances:
        #Here, 'i' is an InstanceInfo object, not a full Instance
        instance_id = i.id

        #Query based on the instance_id we've got
        #This function actually gives reservations, not instances
        reservations = ec2_conn.get_all_instances(instance_ids=[instance_id])
        #pull out our single instance
        instance = reservations[0].instances[0]

        #Now we've got the full instance and we can get parameters from here
        print(instance.public_dns_name)

rawDescription: How do i get the public dns of an instance in AWS using BOTO python

description: Get the public dns of an instance in AWS using BOTO python


rawDescription: How do you get the logical NAND of two variables in Python

description: Get the logical NAND of two variables in Python


code:
@app.route('/callback/<address>')
def callback(address):
    sid = get_sid_from_address(address)
    socketio.send('payment seen on blockchain', room=sid)

@socketio.on('address')
def socketlisten(address):
    associate_address_with_sid(address, request.sid)

rawDescription: How can I send a message from a flask route to a socket using flask-socketio

description: Send a message from a flask route to a socket using flask-socketio


code:
master=Tk()
knowledge_slice1 =     (40.0/100) * 360
thinking_slice1 =      (30.0/100) * 360
communication_slice1 = (20.0/100) * 360
application_slice1 =   (10.0/100) * 360

course1_pie = Canvas(master, width=265, height=265, bg = 'white')
course1_pie.pack()
knowarc=course1_pie.create_arc((5, 5, 250, 250), fill = "#FFFFAA",
   start= 0,
   extent = knowledge_slice1)
thinkarc=course1_pie.create_arc((5, 5, 250, 250), fill = "#C0FEA4",
   start= knowledge_slice1,
   extent = thinking_slice1)
commarc=course1_pie.create_arc((5, 5, 250, 250), fill = "#AFAFFF",
   start= knowledge_slice1 + thinking_slice1,
   extent = communication_slice1)
apparc=course1_pie.create_arc((5, 5, 250, 250), fill = "#FFD490",
   start= knowledge_slice1 + thinking_slice1 + communication_slice1,
   extent =application_slice1)

hover_text=course1_pie.create_text((125,260),text="")

def know_enter(event):
   course1_pie.itemconfig(hover_text,text="Knowledge Category")
def think_enter(event):
   course1_pie.itemconfig(hover_text,text="Thinking Category")
def comm_enter(event):
   course1_pie.itemconfig(hover_text,text="Communication Category")
def app_enter(event):
   course1_pie.itemconfig(hover_text,text="Application Category")
def any_leave(event):
   course1_pie.itemconfig(hover_text,text="")

course1_pie.tag_bind(knowarc,'<Enter>',know_enter)
course1_pie.tag_bind(knowarc,'<Leave>',any_leave)
course1_pie.tag_bind(thinkarc,'<Enter>',think_enter)
course1_pie.tag_bind(thinkarc,'<Leave>',any_leave)
course1_pie.tag_bind(commarc,'<Enter>',comm_enter)
course1_pie.tag_bind(commarc,'<Leave>',any_leave)
course1_pie.tag_bind(apparc,'<Enter>',app_enter)
course1_pie.tag_bind(apparc,'<Leave>',any_leave)

rawDescription: How to show categories of pie chart when hovered over?

description: Show categories of pie chart when hovered over


code: from ..forms import MyModelForm

rawDescription: Import forms in template tags

description: Import forms in template tags


code:
def cell1():
    print("In cell1!")
    while True:
        choice = input("pick 'ONE' or 'TWO' (or type 'quit' to exit):")
        if choice == "ONE":
            return option1
        elif choice == "TWO":
            return option2
        elif choice == "quit":
            return None
        else:
            print("I'm sorry, I didn't understand that.")

def option1():             # these other two functions are very basic in my example
    print("In option1!")   # but you can make them as complex as you want
    return option2

def option2():
    print("in option2!")
    return cell1

def control_loop(initial_state=cell1):
    state = initial_state
    while state is not None:
        state = state() # the next state is the return value of the previous state

rawDescription: Function called without being told to

description: Function called without being told to


rawDescription: Python regex and string replacement

description: Python regex and string replacement


code:
def setup():
    logger = logging.getLogger('mytest')
    formatter = logging.Formatter('%(asctime)s %(message)s')
    fileHandler = logging.FileHandler('mylog.log')
    fileHandler.setLevel(logging.DEBUG)
    fileHandler.setFormatter(formatter)
    logger.addHandler(fileHandler)

    logger.critical("before setting Level on logger, effective level = {}".format(
            logger.getEffectiveLevel()))

    #THIS WON'T BE logged becuse logger level is WARN
    # and DEBUG < WARN
    logger.debug('logging debug before setting debug level')

    logger.setLevel(logging.DEBUG)

    logger.critical("after setting Level on logger, effective level = {}".format(
            logger.getEffectiveLevel()))

    #THIS WILL BE logged in mylog.log because DEBUG >= DEBUG
    logger.debug('logging debug after setting debug level')

    fileHandler.setLevel(logging.CRITICAL)

    #THIS WON'T BE logged in mylog.log because fileHandler level is CRITICAL--->
    # and DEBUG < CRITICAL
    logger.debug("this won't be printed in mylog.log")

    #THIS WILL BE logged in mylog.log BECAUSE CRITICAL >= CRITICAL--->
    logger.critical("logging at critical level")

rawDescription: Python logging custom handler and formatter nothing gets logged


code:
# insert this after lines '#Right figure', 'figure()'

r = boxplot(data, sym="w") # outlier are computed but not drawn

top_points = r["fliers"][0].get_data()[1]
bottom_points = r["fliers"][2].get_data()[1]
plot(np.ones(len(top_points)), top_points, "x", color="blue", markersize=1)
plot(np.ones(len(bottom_points)), bottom_points, ".", color="blue")
#if you have several boxplots this "np.ones(len(bottom_points))" is the number of plot you want to draw in, so 1s for the first [2,2,2,2,...] for the second ect.

rawDescription: Matplotlib: Boxplot outlier color change if keyword sym is used


code:
def merge(a, b):
    if isinstance(a, dict) and isinstance(b, dict):
        d = dict(a)
        d.update({k: merge(a.get(k, None), b[k]) for k in b})
        return d

    if isinstance(a, list) and isinstance(b, list):
        return [merge(x, y) for x, y in itertools.izip_longest(a, b)]

    return a if b is None else b

rawDescription: Python: Merging two arbitrary data structures


code:
listAtoB = dict(zip(listA, listB))

listAtoB[3] # Z2 O95409 V595 **p.His3Leu** Dase - Hophaly type 5 (HPE5) [609637]

rawDescription: working with 2 lists

description: Working with 2 lists


code:
# Get shell command line arguments
import sys
print( sys.argv )

# If you want user input
user_input = raw_input('Please enter your value: ')

rawDescription: how can I implement a program to interact with me using python?

description: Implement a program to interact with me using python


code:
myHTML = """

<title>I am an HTML Page<title>

Some content here.

"""

rawDescription: working with html on python code

description: Working with html on python code


code: row[-3], row[-4] = 'http://www.foo.com/' + row[-3], 'http://www.foo.com/' + row[-4]

rawDescription: simplify appending domain to filenames in python

description: Simplify appending domain to filenames in python


code:
class ValueField(serializers.WritableField):
  #called when serializing a field to a string. (for example when calling seralizer.data)
  def to_native(self, obj):
    return obj;

  """
  Called when deserializing a field from a string
  (for example when calling is_valid which calles restore_object)
  """
  def from_native(self, data):
    return data

class MyFieldSerializer(serializers.ModelSerializer):
  value = ValueField(source='get_value', required=False)

  def restore_object(self, attrs, instance=None):
    """
    Called by is_valid (before calling save)
    Create or update a new instance, given a dictionary
    of deserialized field values.

    Note that if we don't define this method, then deserializing
    data will simply return a dictionary of items.
    """
    if instance:
        # Update existing instance
        instance.user = attrs.get('user', instance.user)
        instance.name = attrs.get('name', instance.name)
    else:
        # Create new instance
        instance = MyField.get_or_create(end_user=attrs['user'],
                                            name=attrs['name'],
                                            value=attrs['get_value'])[0]

    instance.value = attrs['get_value']
    return instance

  def save_object(self, obj, **kwargs):
    #called when saving the instance to the DB
    instance = MyField.get_or_create(end_user=obj.user,
                                            name=obj.name,
                                            value=obj.value)[0]
  class Meta:
    model = MyField
    fields = ('id', 'user', 'name', 'value')

rawDescription: django rest framework and model inheritance

description: Django rest framework and model inheritance


code:
import sys

if sys.version_info >= (3,2):
    install_requires = ["threadpool >= 1.2.7"]
else:
    install_requires = ["threadpool >= 1.2.3"]

setup(..., install_requires=install_requires)

rawDescription: install_requires based on python version

description: Install_requires based on python version


rawDescription: Django: get subset of a model with at least one related model


code:
Stmt      << ( selectToken +
                columnNameList('columns') +
                Optional( CaselessKeyword('where') + whereExpression('where'), "" ) +
                Each( [ Optional( CaselessKeyword('group by') + columnNameList('group'), "" ).setDebug(),
                        Optional( CaselessKeyword('order by') + columnNameList('order'), "" ).setDebug() ]
                    )
            )

rawDescription: pyparsing, Each, results name

description: Pyparsing, Each, results name


rawDescription: Find closest matching number in dictionary (python)


code:
from tkinter import *

def cel_na_fahr(event):
    print(ent1.get())
    e = ".0"
    a = float(ent1.get())
    a = round((32+9/5*a),2)
    a = str(a)
    if a.endswith(e):
        a=a.replace(".0","")
        ent2.delete(0,END)
        ent2.insert(0,a)
    else:
        ent2.delete(0,END)
        ent2.insert(0,a)

def fahr_na_cel(event):
    print(ent2.get())
    e = ".0"
    a = float(ent2.get())
    a = round(5/9*(a-32),2)
    a = str(a)
    if a.endswith(e):
        a=a.replace(".0","")
        ent1.delete(0,END)
        ent1.insert(0,a)
    else:
        ent1.delete(0,END)
        ent1.insert(0,a)

root = Tk()

root.geometry("300x180+400+400")

fr1 = Frame(root, padx=5, pady=40)
fr1.pack(side=TOP)

fr2 = Frame(root)
fr2.pack(side=TOP)

lbl1 = Label(fr1, text="cel to fahr   ")
lbl1.pack(side=LEFT)

ent1 = Entry(fr1)
ent1.pack(side=RIGHT)

lbl2 = Label(fr2, text="fahr to cel   ")
lbl2.pack(side=LEFT)

ent2 = Entry(fr2)
ent2.pack(side=RIGHT)

ent1.bind('<KeyRelease>', cel_na_fahr)
ent2.bind('<KeyRelease>', fahr_na_cel)

root.mainloop()

rawDescription: Python 3.4 tkinter real-time temperature converter


rawDescription: Django or python manipulate email addresses and reason about domains


code:
def contains_consecutive_duplicates(xs):
    for i in range(1, len(xs) - 1):
        if xs[i] == xs[i-1] or xs[i] == xs[i+1]:
            return True
    return False

rawDescription: Looping with Consecutive Elements

description: Looping with Consecutive Elements


code:
from collections import defaultdict
import csv

INPUT = "myfile.csv"
ANGLE_SZ = 22.5
SPEED_SZ = 1.

def read_csv(fname, skip_header=False, **kwargs):
    with open(fname, "rb") as inf:
        incsv = csv.reader(inf, **kwargs)
        if skip_header:
            header = next(incsv, None)
        for row in incsv:
            yield row

def main():
    data = defaultdict(lambda: defaultdict(list))
    for d,s in read_csv(INPUT, skip_header=True):
        data[int(d/ANGLE_SZ)][int(s/SPEED_SZ)].append((d,s))

    # data[][] now contains all your data, sorted into buckets

if __name__=="__main__":
    main()

rawDescription: iterating through data and splitting into different categories

description: Iterating through data and splitting into different categories


code:
def viewfunc(request):
   objids = request.POST.getlist('obj_id')
   names = request.POST.getlist('obj_name')
   sizes = request.POST.getlist('obj_size')
   numbers = request.POST.getlist('obj_number')
   res = []
   for objid, name, size, number in zip(objids,names,sizes,numbers):
       innerlist = []
       innerlist.append(objid+', '+name+', '+size+', '+number)
       res.append(innerlist)
   """
    now res has all objects as list elements
   """

rawDescription: how to submit a form with multiple objects - django

description: Submit a form with multiple objects - django


code:
global WINDOW_HEIGHT,WINDOW_WIDTH
while True:
    for event in pygame.event.get():
        if event.type == VIDEORESIZE:
            DISPLAY = pygame.display.set_mode(event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE) # Here, the integers are supposed to be being changed
            WINDOW_WIDTH, WINDOW_HEIGHT = DISPLAY.get_size()
            print("%d, %d" % (WINDOW_WIDTH, WINDOW_HEIGHT))

drawArena()

rawDescription: Integer variables not updating in python


code:
# Import the os module, for the os.walk function
import os

# Set the directory you want to start from
rootDir = '.'
for dirName, subdirList, fileList in os.walk(rootDir):
    print('Found directory: %s' % dirName)
    for fname in fileList:
        print('\t%s' % fname)

    for i, elem in reversed(list(enumerate(subdirList[:]))):
        if "[" in elem:
            del subdirList[i]

rawDescription: Recursively listing a directory, but excluding any folders with a certain character


rawDescription: Number list with no repeats and ordered

description: Number list with no repeats and ordered


code:
import numpy as np

def solve_gaussian(val,data_array,sigma_array):
    return (1. / sigma_array) * np.exp(- (val - data_array) * (val - data_array) / (2 * sigma_array * sigma_array))

def solve_kde(xlist,data_array,sigma_array):
    kde_array = np.array([])
    for xx in xlist:
        single_kde = solve_gaussian(xx,data_array,sigma_array)
        if np.ndim(kde_array) == 3:
            kde_array = np.concatenate((kde_array,single_kde[np.newaxis,:,:]),axis=0)
        else:
            kde_array = np.dstack(single_kde)
    return kde_array

xlist = np.linspace(0,1,101) #Adjust as needed
kde_array = solve_kde(xlist,data_array,sigma_array)
kde_vector = np.sum(np.sum(kde_array,axis=2),axis=1)
mode_guess = xlist[np.argmax(kde_vector)]

rawDescription: KDE in python with different mu, sigma / mapping a function to an array


code: [x for x in os.listdir(...) if not os.path.isdir(os.path.join(..., x))]

rawDescription: Pythonic way to remove directories from a file listing


code:
import subprocess
out_fd = open('test_file','w')
def os_system_dd():
   out_fd.write("executing the time dd command\n")
   cmd_list = ['time','dd','if=/dev/random', 'of=/home/anand/sys_entropy_random',
                           'bs=1M' ,'count=5']
   a = subprocess.Popen(cmd_list,stderr=out_fd) # notice stderr
   a.communicate()

if __name__ == '__main__':
   os_system_dd()

rawDescription: python subprocess dd and stdout

description: Python subprocess dd and stdout


code: new_list = [item for item in itertools.product(*start_list) if sum(item) == 200]

rawDescription: Python creating a list with itertools.product?


code:
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

subplots = []
rows = 2
columns = 2

for n in range(rows * columns):
    host = host_subplot(rows, columns, n + 1, axes_class=AA.Axes)

    par1 = host.twinx()
    par2 = host.twinx()

    offset = 60

    par2.axis["right"] = par2.get_grid_helper().new_fixed_axis(
        loc="right",
        axes=par2,
        offset=(offset, 0),
    )

    par2.axis["right"].toggle(all=True)

    host.set_xlabel("Distance")
    host.set_ylabel("Density")
    par1.set_ylabel("Temperature")
    par2.set_ylabel("Velocity")

    subplots.append({
        'density': host,
        'temperature': par1,
        'velocity': par2,
    })

subplots[0]['density'].plot([1, 2, 3])
subplots[2]['temperature'].plot([1, 2, 3])
plt.tight_layout()
plt.savefig('result2.png', dpi=300)

rawDescription: Python: Suplots with two secondary-axis

description: Python: Suplots with two secondary-axis


code:
US['city'].value_counts()
UK['count'] = UK['city'].map(US['city'].value_counts())
UK

rawDescription: Pandas: Return count of matching values between two DataFrame variables


code:
def _fetch_exrates(year,month,day):
    import json
    import urllib.request
    f = urllib.request.urlopen('http://openexchangerates.org/api/historical/'+year+'-'+month+'-'+day+'.json?app_id=188bd7b8d2634e4cb0602ab5b3c223e7')
    charset = f.info().get_param('charset', 'utf8')
    data = f.read()
    decoded = json.loads(data.decode(charset))
    print(json.dumps(decoded, indent=4))

print('Please but the year in the form of YYYY and the month as MM and day as DD')
year = raw_input('choose a year :',)
month = raw_input('choose a month :',)
day = raw_input('choose a day :',)
_fetch_exrates(year,month,day)

rawDescription: Inserting date into URL and Getting currency data for that date


code:
var2D.setValue(var3D((x2D, y2D,
                      zcut * ones(var2D.mesh.numberOfCells) + dx/2.), order=0))

rawDescription: How to extract a plane from a 3D variable in FiPy (3D to 2D)

description: Extract a plane from a 3D variable in FiPy (3D to 2D)


code:
for i in doc.iter(tag='{http://www.tei-c.org/ns/1.0}ab'):
    innerText = i.text+''.join((text.tail or '') for text in i.iter()).strip()
    print(i.tag, innerText)

rawDescription: Traversing TEI in Python 3, text comes up empty for some entities


code:
from collections import defaultdict
from functools import partial

defaultdict(partial(numpy.ndarray, 0))

rawDescription: Creating a defaultdict with empty numpy array


code:
...

def On_Idle(self, event):
    if not self.queued_batch:
        wx.CallLater(1000, self.Do_Batch)
        self.queued_batch = True

def Do_Batch(self):
    # <- insert your stuff here
    self.queued_batch = False

...

rawDescription: wxPython: Using EVT_IDLE

description: WxPython: Using EVT_IDLE


code:
FourGLints = GLint * 4
viewport = FourGLints(0, 1, 2, 3)

rawDescription: OpenGL Picking with Pyglet

description: OpenGL Picking with Pyglet


code:
driver.find_elements_by_xpath("//iframe")
iframes = driver.find_elements_by_xpath("//iframe")
iframes[0]
driver.switch_to_frame(iframes[0])

rawDescription: Indexing iframes Python

description: Indexing iframes Python


code:
def isNear(self, p):
    self.distToPoint(p)
    ...

rawDescription: Python call function within class

description: Python call function within class


code:
import operator
get_truth(1.0, operator.gt, 0.0)

...

def get_truth(inp, relate, cut):
    return relate(inp, cut)
    # you don't actually need an if statement here

rawDescription: How to pass an operator to a python function?

description: Pass an operator to a python function


code:
import numpy
a = numpy.array([1,2,3])
b = numpy.array([1,3])
c = [a,b]
sorted(c,key=len)

rawDescription: Sorting a list of Image Matrices (Numpy nd arrays) by image size


code:
class ListWithOffset(list):
    def __init__(self, offset, *a, **kw):
        self.offset = offset
        super().__init__(*a, **kw)

    def __getitem__(self, i):
        return super().__getitem__(self, self._adjust_idx(i))

    def __setitem__(self, i, value):
        return super().__setitem__(self, self._adjust_idx(i), value)

    def __delitem__(self, i):
        return super().__delitem__(self, self._adjust_idx(i))

    def _adjust_idx(self, i):
        if isinstance(i, slice):
            return slice(i.start - self.offset if i.start is not None else None,
                         i.stop - self.offset if i.stop is not None else None,
                         i.step)
        else:
            return i - self.offset

rawDescription: Array in python with arbitrary index

description: Array in python with arbitrary index


code:
import sys, time

from PyQt4 import QtCore, QtGui

class MyDialog(QtGui.QDialog):
    def __init__(self,parent=None):
        QtGui.QDialog.__init__(self,parent)
        layout = QtGui.QVBoxLayout()
        self.msg = QtGui.QLabel('some sort of status')
        self.buttonbox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok, QtCore.Qt.Horizontal, self)
        self.buttonbox.accepted.connect(self.accept)
        layout.addWidget(self.msg)
        layout.addWidget(self.buttonbox)
        self.setLayout(layout)

    def set_msg(self, new_msg):
        self.msg.setText(new_msg)

    def set_function_on_accept(self,fcn):
        self.function = fcn

    def accept(self):
        self.function()

class Command(object):
    def do(self):
        self.setupUi()

    def do_work(self):
        self.pre()
        self.run()
        self.post()

    def pre(self):
        # do setup stuff for run method
        time.sleep(1)
        self.diag.set_msg("stuff setup")
        QtGui.QApplication.processEvents()

    def run(self):
        # do actual work
        time.sleep(1)
        self.diag.set_msg("work done")
        QtGui.QApplication.processEvents()

    def post(self):
        # clean up after run
        time.sleep(1)
        self.diag.set_msg("cleaned up")
        QtGui.QApplication.processEvents()

    def setupUi(self):
        # create a ui for this command
        diag = MyDialog()
        self.diag = diag
        diag.set_function_on_accept(self.do_work)
        diag.show()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    command = Command()
    command.do()
    sys.exit(app.exec_())

rawDescription: QDialog switch to non-modal after accept not redrawing


code:
def requestonly(view, attr=None):
    ismethod = False
    if attr is None:
        attr = '__call__'
    if inspect.isroutine(view):
        fn = view
    elif inspect.isclass(view):
        try:
            fn = view.__init__
        except AttributeError:
            return False
        ismethod = hasattr(fn, '__call__')
    else:
        try:
            fn = getattr(view, attr)
        except AttributeError:
            return False

    try:
        argspec = inspect.getargspec(fn)
    except TypeError:
        return False

    args = argspec[0]

    if hasattr(fn, im_func) or ismethod:
        # it's an instance method (or unbound method on py2)
        if not args:
            return False
        args = args[1:]
    if not args:
        return False

    if len(args) == 1:
        return True

    defaults = argspec[3]
    if defaults is None:
        defaults = ()

    if args[0] == 'request':
        if len(args) - len(defaults) == 1:
            return True

    return False

rawDescription: Pyramid: how come view callables accept either one or two parameters?


code:
set_1 = file1()
set_2 = file2()

rawDescription: sending variables between functions

description: Sending variables between functions


code:
a = 5  # assigns the variable a to 5
a == 5 # returns true
a == 4 # returns false
a = 4 # a is now 4
a == 4 # returns true

rawDescription: Can someone please explain to me

description: Can someone please explain to me


code:
grouped = df.groupby('trip_num')
decel_df = grouped.apply(get_deceleration_risk)
steer_df = grouped.apply(get_steering_risk)
...
dfTrips = pd.concat([decel_df, steer_df, ...], axis=1)
dfTrips.columns = ['Harsh_Deceleration', 'Harsh_Steering', ...]

rawDescription: Avoiding for loop in a pandas data frame when working on selected rows


code:
def isAdjacent(Coord1, Coord2):
    if abs(Coord1[0] - Coord2[0]) > 1 or abs(Coord1[1] - Coord2[1]) > 1:
        return False
    else:
        return True

def CheckForAdjacency(Coordinates):
    Adjacent = 0
    for i in range(len(Coordinates) - 1):
        if isAdjacent(Coordinates[i], Coordinates[i +1]):
            Adjacent += 1
    return Adjacent

rawDescription: Checking a string for adjacent characters on the keyboard


code:
import sys
import cgi

sys.stdout.write("Content-Type: application/json")
sys.stdout.write("\n")
sys.stdout.write("\n")

form = cgi.FieldStorage()

sys.stdout.write(json.dumps({ 'data': form.getvalue('ac_number')}))

rawDescription: Accessing passed data through ajax call in my python script


code:
from pyzipcode import ZipCodeDatabase
zcdb = ZipCodeDatabase()
zipcode = zcdb[54115]
zipcode.zip
zipcode.city
zipcode.state
zipcode.longitude
zipcode.latitude
zipcode.timezone

rawDescription: lightweight python library to query city/state name by zip code?

description: Lightweight python library to query city/state name by zip code


code:
col0 = []
col1 = []
col2 = []
col3 = []
col4 = []

f = open('cdc_data.tsv', 'r')
contents = f.read()
lines = contents.split('\n')    # split file into seperate lines
for line in lines:
    if (line[0:1] == '#'):   # filter out comments
       continue

    split_line = line.split('\t')   # split line into seperate words seperated by TAB

    if (len(split_line) < 5): # drop any line that isn't 5 columns
       continue

    # assign each column into a separate list
    col0.append(split_line[0])
    col1.append(split_line[1])
    col2.append(split_line[2])
    col3.append(split_line[3])
    col4.append(split_line[4])

rawDescription: Turning columns into lists from csv with Python


code:
import threading
import urllib.request
import urllib.error

import time

start_time = time.time()

req = urllib.request.Request("http://fake-response.appspot.com/")

class Fetcher(threading.Thread):
    def __init__(self):
        self.text = "No response yet!"
        super().__init__()

    def run(self):
        try:
            response = urllib.request.urlopen(req)
            self.text = response.read().decode('latin1')
        except (urllib.error.HTTPError, urllib.error.URLError) as e:
            print(e)

fetcher = Fetcher()

print("Initial text is \"%s\"" % fetcher.text)

fetcher.start()

text = fetcher.text

while time.time() - start_time < 15:
    print("%s - text: \"%s\"" % (time.strftime("%H:%M:%S"), fetcher.text))
    # This should print '<TIME> - text: "No response yet!"' for ten seconds
    # After that, '<TIME> - text: {"response":"This request has finished sleeping for 10 seconds"}' should be displayed

    time.sleep(0.5)

rawDescription: Fetch data in background - maybe using threads


code:
import matplotlib.dates as md
import matplotlib.pyplot as plt
from  datetime import *

val = [6, 6.5, 7, 6.5, 6, 5.5, 5, 4.5, 4, 4.5, 5, 5.5]
datenumes = [datetime(2014, 3, 10, 8, 2, 2),
    datetime(2014, 3, 10, 8, 2, 26),
    datetime(2014, 3, 10, 10, 4, 45),
    datetime(2014, 3, 10, 10, 5, 11),
    datetime(2014, 3, 10, 12, 5, 32),
    datetime(2014, 3, 10, 12, 5, 50),
    datetime(2014, 3, 10, 15, 6, 10),
    datetime(2014, 3, 10, 16, 6, 54),
    datetime(2014, 3, 10, 17, 8, 31),
    datetime(2014, 3, 10, 18, 8, 55),
    datetime(2014, 3, 10, 19, 9, 20),
    datetime(2014, 3, 10, 22, 9, 35)]

# creates list of datetimes where ticks should be set
ticks = [datetime(2014, 3, 10, 8, 0, 0),
        datetime(2014, 3, 10, 10, 0, 0),
        datetime(2014, 3, 10, 12, 0, 0),
        datetime(2014, 3, 10, 14, 0, 0),
        datetime(2014, 3, 10, 16, 0, 0),
        datetime(2014, 3, 10, 18, 0, 0),
        datetime(2014, 3, 10, 20, 0, 0),
        datetime(2014, 3, 10, 22, 0, 0) ]

# generate labels for the datetimes used as ticks
ticklabels = [str(tick)[11:] for tick in ticks]

#  PLOT
fig=plt.figure(figsize=(20,10))
ax=plt.gca()
plt.xticks( rotation=25 )

# set the ticks according to the list tick
ax.set_xticks(ticks)
##  set labels to human readable format
ax.set_xticklabels(ticklabels)

plt.title("Temperature")
plt.ylabel(r'Temperature, $^{o}C$')
ax.plot(datenumes, val, marker='.', lw=0)
plt.show()

rawDescription: Python: plot timestamp data frame matplotlib


code:
def up_to_kahn(lst):
    return lst if ("kahn" not in lst) else lst[:lst.index("kahn")]

assert up_to_kahn(["kirk", "spock", "luke", "charlie", "kahn", "bob"]) == \
    ["kirk", "spock", "luke", "charlie"]
assert up_to_kahn(["ernie", "kahn", "bert", "teal'c"]) == ["ernie"]

rawDescription: return a new list from a list stopped at certain location

description: Return a new list from a list stopped at certain location


code:
if __name__ == '__main__':
    processes = create_processes(2, time.sleep, 4)
    start_all(processes, 0)

rawDescription: single call to multiprocessing.Process.start() spawning 100s of processes in Windows when running in PyDev

description: Single call to multiprocessing.Process.start() spawning 100s of processes in Windows when running in PyDev


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

class StandardProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    something = models.CharField(max_length=255)

class ArtistProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    style = models.CharField(max_length=255)
    music = models.CharField(max_length=255)
    bank_account = models.CharField(max_length=255)

rawDescription: How to create custom user profile using Django 1.5?

description: Create custom user profile using Django 1.5


code:
from collections import defaultdict
A = [ 1, 2, 3, 4 , 2, 1 ]
d = defaultdict(list)
for i,x in enumerate(A):
   d[x].append(i)
d

rawDescription: How to build a dict of indices of occurences of elements in a list in Python?

description: Build a dict of indices of occurences of elements in a list in Python


code:
img = Image.open(source)
progressive_img = StringIO()
img.save(progressive_img, "JPEG", quality=80, optimize=True, progressive=True)
photo = uploader.upload_picture_to_album(title=title, file_obj=progressive_img)

rawDescription: Python Pillow: Make image progressive before sending to 3rd party server


code:
app_name = app_name or __name__

config = config_str_to_obj(config)
app = Flask(app_name, static_url_path=config.SOME_CONFIGURATION_NAME)

configure_app(app, config)
...

rawDescription: Is it possible to change `template_folder` after initialisation?


rawDescription: Regular expression in loops

description: Regular expression in loops


code:
import sys
if sys.version_info[0] < 3:
    import Tkinter as tk     ## Python 2.x
else:
    import tkinter as tk     ## Python 3.x

master = tk.Tk()
master.geometry("125x100")

def key_in(event):
    ch=event.char.lower()
    print("key_in", ch)
    if "a" <= ch <= "z":
        variable.set("five")
    if event.keysym=="Return":
        print("Enter key pressed")

def ok(arg):
    print("ok called", variable.get())

variable = tk.StringVar(master)
options=("one", "two", "three", "four", "five")
op=tk.OptionMenu(master, variable, *options, command=ok)
op.grid()
variable.set("two")

op.bind_all('<Key>', key_in)
op.focus_set()

tk.Button(master, text="Exit", bg="red",
          command=master.quit).grid(row=1)

master.mainloop()

rawDescription: Can you have a TKinter drop down menu that can jump to an entry by typing?

description: Have a TKinter drop down menu that can jump to an entry by typing


rawDescription: Remove matching items in a list

description: Remove matching items in a list


code:
class SomeClass():
    def __init__(self, things):
        self._things = things

    def get_the_thing(self, bok):
        return self._things[bok - 1]

rawDescription: How can I dump those if's?

description: Dump those if's


code: answer_user = input("\n%s %s %s:" % (a, c, b))

rawDescription: Why does my input always display none in python?


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setWindowTitle(self.tr('Document Printer'))
        self.table = QtGui.QTableWidget(200, 5, self)
        for row in range(self.table.rowCount()):
            for col in range(self.table.columnCount()):
                item = QtGui.QTableWidgetItem('(%d, %d)' % (row, col))
                item.setTextAlignment(QtCore.Qt.AlignCenter)
                self.table.setItem(row, col, item)
        self.table.setHorizontalHeaderLabels(
            'SKU #|NAME|DESCRIPTION|QUANTITY|PRICE'.split('|'))
        self.buttonPrint = QtGui.QPushButton('Print', self)
        self.buttonPrint.clicked.connect(self.handlePrint)
        self.buttonPreview = QtGui.QPushButton('Preview', self)
        self.buttonPreview.clicked.connect(self.handlePreview)
        layout = QtGui.QGridLayout(self)
        layout.addWidget(self.table, 0, 0, 1, 2)
        layout.addWidget(self.buttonPrint, 1, 0)
        layout.addWidget(self.buttonPreview, 1, 1)

    def handlePrint(self):
        dialog = QtGui.QPrintDialog()
        if dialog.exec_() == QtGui.QDialog.Accepted:
            self.handlePaintRequest(dialog.printer())

    def handlePreview(self):
        dialog = QtGui.QPrintPreviewDialog()
        dialog.paintRequested.connect(self.handlePaintRequest)
        dialog.exec_()

    def handlePaintRequest(self, printer):
        document = QtGui.QTextDocument()
        cursor = QtGui.QTextCursor(document)
        table = cursor.insertTable(
            self.table.rowCount(), self.table.columnCount())
        for row in range(table.rows()):
            for col in range(table.columns()):
                cursor.insertText(self.table.item(row, col).text())
                cursor.movePosition(QtGui.QTextCursor.NextCell)
        document.print_(printer)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())

rawDescription: How to create printable list that correctly spans multiple pages

description: Create printable list that correctly spans multiple pages


code:
masked_array = np.ma.array (a, mask=np.isnan(a))
cmap = matplotlib.cm.jet
cmap.set_bad('w',1.)
ax.imshow(masked_array, interpolation='nearest', cmap=cmap)

rawDescription: How can I plot NaN values as a special color with imshow in matplotlib?

description: Plot NaN values as a special color with imshow in matplotlib


code:
import signal
import sys

from PyQt4.QtCore import QTimer
from PyQt4.QtGui import QApplication, QMessageBox

# Your code here

def sigint_handler(*args):
    """Handler for the SIGINT signal."""
    sys.stderr.write('\r')
    if QMessageBox.question(None, '', "Are you sure you want to quit?",
                            QMessageBox.Yes | QMessageBox.No,
                            QMessageBox.No) == QMessageBox.Yes:
        QApplication.quit()

if __name__ == "__main__":
    signal.signal(signal.SIGINT, sigint_handler)
    app = QApplication(sys.argv)
    timer = QTimer()
    timer.start(500)  # You may change this if you wish.
    timer.timeout.connect(lambda: None)  # Let the interpreter run each 500 ms.
    # Your code here.
    sys.exit(app.exec_())

rawDescription: What is the correct way to make my PyQt application quit when killed from the console (Ctrl-C)?


code:
import gc
gc.get_objects()  # returns a list of objects tracked by CPython's garbage collector

rawDescription: Objects in memory python

description: Objects in memory python


code:
def function():

   sent_pos = [('increasing', 'VBG'), ('of', 'IN'), ('mutation', 'NN')]
   rule1 = [('', 'VBG'), ('', 'IN'), ('', 'NN')]
   rule2 = [('', 'NN'), ('', 'IN'), ('', 'NN')]
   rule3 = [('', 'ADJ'), ('', 'IN'), ('', 'NN')]

   rules = [rule1, rule2, rule3]

   for element in rules:
        counter = 0
        for i in range(len(sent_pos)):
            if sent_pos[i][1] == element[i][1]:
                counter += 1
        if counter == len(sent_pos):
            return True
   return False

rawDescription: lists of tuples by a tuple element?

description: Lists of tuples by a tuple element


code:
if SQLParameters[i] is True:
    SQLParameters[i] = 'T'
elif SQLParameters[i] is False:
    SQLParameters[i] = 'F'

rawDescription: Pythonic Boolean Conversion

description: Pythonic Boolean Conversion


code:
if not authenticated:
    print('Authentication failed')
    sys.exit(1)
else:
    print('Successfully authenticated!')
    proc = subprocess.Popen([program])

rawDescription: How can I stop a program's execution with python?

description: Stop a program's execution with python


code:
def filtered_gen(gen):
    for item in gen:
        result = expensive_function(item)
        if result < 5:
            yield result

rawDescription: Possible to capture the returned value from a Python list comprehension for use a condition?


code:
list1 = ['a','b','c','d']
list2 = ['r','t','y','h']
[''.join(pair) for pair in zip(list1, list2)]

rawDescription: Combining two lists in python3

description: Combining two lists in python3


code:
def index(self):
    if request.params.has_key('session'):
      access_token = simplejson.loads(request.params['session'])['access_token']
      graph = facebook.GraphAPI(access_token)
      tmpl_context.user = graph.get_object("me")
      return render('/index.mako')
    return render('/oauth_redirect.mako')

rawDescription: Pylons and Facebook

description: Pylons and Facebook


rawDescription: python distribute elements of a list into part of a sql query

description: Python distribute elements of a list into part of a sql query


code:
import time
from Queue import PriorityQueue

class Task(object):
    def __init__(self, fn, crontab):
        # TODO: it should be possible to pass args, kwargs
        # so that fn can be called with fn(*args, **kwargs)
        self.fn = fn
        self.crontab = crontab

    def get_next_fire_date(self):
        # TODO: evaluate next fire date based on self.crontab
        pass

class Scheduler(object):
    def __init__(self):
        self.event_queue = PriorityQueue()
        self.new_task = False

    def schedule_task(self, fn, crontab):
        # TODO: add scheduling language, crontab or something
        task = Task(fn, crontab)
        next_fire = task.get_next_fire_date()
        if next_fire:
            self.new_task = True
            self.event_queue.put((next_fire, task))

    def run(self):
        self.new_task = False

        # TODO: do we really want an infinite loop?
        while True:
            # TODO: actually we want .get() with timeout and to handle
            # the case when the queue is empty
            next_fire, task = self.event_queue.get()

            # incremental sleep so that we can check
            # if new tasks arrived in the meantime
            sleep_for = int(next_fire - time.time())
            for _ in xrange(sleep_for):
                time.sleep(1)
                if self.new_task:
                    self.new_task = False
                    self.event_queue.put((next_fire, task))
                    continue

            # TODO: run in separate thread?
            task.fn()

            time.sleep(1)
            next_fire = task.get_next_fire_date()

            if next_fire:
                event_queue.put((next_fire, task))

def test():
    return 'hello world'

sch = Scheduler()
sch.schedule_task(test, '5 * * * *')
sch.schedule_task(test, '0 22 * * 1-5')
sch.schedule_task(test, '1 1 * * *')
sch.run()

rawDescription: How Python threading Timer work internally?


code:
import numpy
a = numpy.array([[1,2,3],[4,5,6]])
b = numpy.array([[3,4,5],[6,7,8]])
c = numpy.array([[9,10,11],[12,1,2]])
d = numpy.array([a,b,c])
d
d.shape
numpy.median(d, axis=0)

rawDescription: Median combining fits images in python

description: Median combining fits images in python


code:
def my_rounding(x):
    return math.ceil(x) if x > 0. else math.floor(x)

rawDescription: Python - What is the best way to round a float up in magnitude to an integer


code:
def calcDistanceMatrixFastEuclidean3(nDimPoints):
  nDimPoints = array(nDimPoints)
  n,m = nDimPoints.shape
  data = nDimPoints[:,0]
  delta = (data - data[:,newaxis])**2
  for d in xrange(1,m):
    data = nDimPoints[:,d]
    delta += (data - data[:,newaxis])**2
  return sqrt(delta)

rawDescription: Why Does Looping Beat Indexing Here?

description: Why Does Looping Beat Indexing Here


code: tuple([tuple(df[col]) for col in df])

rawDescription: create a tuple from columns in a pandas DataFrame

description: Create a tuple from columns in a pandas DataFrame


code:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# an Engine, which the Session will use for connection
# resources
some_engine = create_engine('postgresql://scott:tiger@localhost/')

# create a configured "Session" class
Session = sessionmaker(bind=some_engine)

# create a Session
session = Session()

# work with sess
myobject = MyObject('foo', 'bar')
session.add(myobject)
session.commit()

rawDescription: Driver python for postgresql

description: Driver python for postgresql


code:
import subprocess

def selector():
    filename = askopenfilename()
    p = subprocess.Popen(["dmtxread", "-n", filename], stdout=subprocess.PIPE)
    stdout, stderr = p.communicate()
    res.insert(INSERT, stdout)
    res.pack()

rawDescription: Python - reading 2D codes, improper output in Tkinter


code:
def scan(self, words):

    result = []
    words = words.split()

    for i in words:
        ...

rawDescription: Python: list iteration works but single string doesn't


code:
import wx

DATA = [
    (1, 'nudge nudge'),
    (2, 'wink wink'),
    (1, 'I bet she does'),
    (3, 'say no more!'),
]

class Frame(wx.Frame):
    def __init__(self):
        super(Frame, self).__init__(None)
        panel = wx.Panel(self)
        self.text = wx.StaticText(panel)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.AddStretchSpacer(1)
        sizer.Add(self.text, 0, wx.ALIGN_CENTER)
        sizer.AddStretchSpacer(1)
        panel.SetSizer(sizer)
        self.index = 0
        self.update()
    def update(self):
        duration, label = DATA[self.index]
        self.text.SetLabel(label)
        self.index = (self.index + 1) % len(DATA)
        wx.CallLater(int(duration * 1000), self.update)

if __name__ == '__main__':
    app = wx.App(None)
    frame = Frame()
    frame.SetTitle('Example')
    frame.SetSize((400, 300))
    frame.Center()
    frame.Show()
    app.MainLoop()

rawDescription: wxpython using time.sleep() without blocking complete GUI

description: Wxpython using time.sleep() without blocking complete GUI


rawDescription: How to use a localized "short format" when formatting dates in Django?

description: Use a localized "short format" when formatting dates in Django


code:
class UserResource(ModelResource):
   class Meta:
       queryset = User.objects.all()
       resource_name = 'user'
       excludes = ['id','email', 'password', 'is_active', 'is_staff', 'is_superuser']
       list_allowed_methods = ['post']
       detail_allowed_methods = ['get']
       default_format = "application/json"
       filtering = {
           'username': ALL,
       }
       authorization= Authorization()

def obj_create(self, bundle, request = None, **kwargs):
    bundle.obj = self._meta.object_class()
    for key, value in kwargs.items():
        setattr(bundle.obj, key, value)
    bundle = self.full_hydrate(bundle)

    self.is_valid(bundle,request)

    if bundle.errors:
        self.error_response(bundle.errors, request)

    # Save FKs just in case.
    self.save_related(bundle)

    obj = None
    try:
        obj = self.obj_get(request, username=bundle.obj.username) # here it checks withe username is already exists or not
    except self._meta.object_class.DoesNotExist:
        pass

    # if user already found then just build the bundle else it will create the new user
    if obj:
        bundle = self.build_bundle(obj=obj, request=request)
    else:
        # Save parent
        bundle.obj.save()
        # Now pick up the M2M bits.
        m2m_bundle = self.hydrate_m2m(bundle)
        self.save_m2m(m2m_bundle)

    return bundle

rawDescription: obj_create not working in tastypie

description: Obj_create not working in tastypie


code:
def extract_data(mock_make_request):
    """Helper function that return data passed to make_request() mock
    Check also if you have some calls and then reset it"""
    assert mock_make_request.called
    args, kwargs = mock_make_request.call_args
    mock_make_request.reset_mock()
    try:
        return kwargs['data']
    except TypeError:
        return args[0]

@patch("productioncodemodule.make_request")
def test_data(mock_make_request):
    """... your code that make do_something() call..."""
    data = extract_data(mock_make_request)
    """... your assert here..."""

rawDescription: Can a Python mock object return the params it was given?


code:
EQ_JOIN.merge(
  lambda row: {'right': row['right'].coerce_to('array').map(
                          lambda pair: [r.expr('organization_') + pair[0], pair[1]]
                        ).coerce_to('object')}
)

rawDescription: How does one rename all keys in right side of a join result to prepend a value?

description: Rename all keys in right side of a join result to prepend a value


code:
import csv
import urllib2
from bs4 import BeautifulSoup

with open('listing.csv', 'wb') as f:
    writer = csv.writer(f)
    for i in range(39):
        url = "http://www.admision.unmsm.edu.pe/res20130914/A/011/{}.html".format(i)
        u = urllib2.urlopen(url)
        try:
            html = u.read()
        finally:
            u.close()
        soup=BeautifulSoup(html)
        for tr in soup.find_all('tr')[2:]:
            tds = tr.find_all('td')
            row = [elem.text.encode('utf-8') for elem in tds[:4]]
            writer.writerow(row)

rawDescription: Export scraped tables to CSV

description: Export scraped tables to CSV


code:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
# print plt.xlim()
plt.xlim(0, 10000)
# or
# plt.xlim(xmin=0, xmax=10000)

rawDescription: Setting an axis in matplotlib

description: Setting an axis in matplotlib


code:
import os
import glob
import pandas as pd

def get_merged_csv(flist, **kwargs):
    return pd.concat([pd.read_csv(f, **kwargs) for f in flist], ignore_index=True)

path =r'C:\DRO\DCL_rawdata_files' # use your path
fmask = os.path.join(path, '*.csv')
allFiles = sorted(glob.glob(fmask), key=os.path.getmtime)

frame = get_merged_csv(allFiles[:-1], index_col=None, header=0)

rawDescription: python, pandas, csv import and more

description: Python, pandas, csv import and more


code:
youtube.videos().list(id="QkhBcLk_8f0",part="snippet").execute()

{u'etag': u'"YxyobdYztCvdjXOUqpUttvF39GM/nr0_6QcUDyGR0D_Gxz762lsqqfU"',
 u'items': [{u'etag': u'"YxyobdYztCvdjXOUqpUttvF39GM/n7wasYBTHMM3SB4Jtsxu6JeDFPA"',
   u'id': u'QkhBcLk_8f0',
   u'kind': u'youtube#video',
   u'snippet': {u'categoryId': u'27',
    u'channelId': u'UCzu2OUGZlNtXPom3KNPGFzg',
    u'channelTitle': u'FFreeThinker',
    u'description': u'http://facebook.com/ScienceReason ... Great Minds, Great Words: Richard Feynman - The Uncertainty of Knowledge ... The Nature and Purpose of the Universe.\n\nPlaylist "Great Minds, Great Words":\n\u2022 http://www.youtube.com/user/FFreeThinker#grid/user/CC4F721030F8D4D1\n\n---\nPlease SUBSCRIBE to Science & Reason:\n\u2022 http://www.youtube.com/FFreeThinker\n\u2022 http://www.youtube.com/ScienceTV\n\u2022 http://www.youtube.com/Best0fScience\n\u2022 http://www.youtube.com/RationalHumanism\n---\n\nRichard Feynman (1918-1988) was an American  physicist  known for his work in the path integral formulation of quantum mechanics, the theory of quantum electrodynamics and the physics of the superfluidity of supercooled liquid helium, as well as in particle physics (he proposed the parton model).\n\nFor his contributions to the development of quantum electrodynamics, Feynman, jointly with Julian Schwinger and Sin-Itiro Tomonaga, received the Nobel Prize in Physics in 1965. He developed a widely used pictorial representation scheme for the mathematical expressions governing the behavior of subatomic particles, which later became known as Feynman diagrams. During his lifetime, Feynman became one of the best-known scientists in the world.\n\nHe assisted in the development of the atomic bomb and was a member of the panel that investigated the Space Shuttle Challenger disaster. In addition to his work in theoretical physics, Feynman has been credited with pioneering the field of quantum computing, and introducing the concept of nanotechnology (creation of devices at the molecular scale). He held the Richard Chace Tolman professorship in theoretical physics at the California Institute of Technology.\n\nFeynman was a keen popularizer of physics through both books and lectures, notably a 1959 talk on top-down nanotechnology called "There\'s Plenty of Room at the Bottom" and "The Feynman Lectures on Physics". Feynman also became known through his semi-autobiographical books ("Surely You\'re Joking, Mr. Feynman!" and "What Do You Care What Other People Think?") and books written about him, such as "Tuva or Bust!"\n\nHe was regarded as an eccentric and free spirit. He was a prankster, juggler, safecracker, proud amateur painter, and bongo player. He liked to pursue a variety of seemingly unrelated interests, such as art, percussion, Maya hieroglyphs, and lock picking.\n\nFeynman also had a deep interest in biology, and was a friend of the geneticist and microbiologist Esther Lederberg, who developed replica plating and discovered bacteriophage lambda. They had several mutual physicist friends who, after beginning their careers in nuclear research, moved for moral reasons into genetics, among them Le\xf3 Szil\xe1rd, Guido Pontecorvo, and Aaron Novick.\n\n\u2022 http://en.wikipedia.org/wiki/Richard_Feynman\n.',
    u'liveBroadcastContent': u'none',
    u'localized': {u'description': u'http://facebook.com/ScienceReason ... Great Minds, Great Words: Richard Feynman - The Uncertainty of Knowledge ... The Nature and Purpose of the Universe.\n\nPlaylist "Great Minds, Great Words":\n\u2022 http://www.youtube.com/user/FFreeThinker#grid/user/CC4F721030F8D4D1\n\n---\nPlease SUBSCRIBE to Science & Reason:\n\u2022 http://www.youtube.com/FFreeThinker\n\u2022 http://www.youtube.com/ScienceTV\n\u2022 http://www.youtube.com/Best0fScience\n\u2022 http://www.youtube.com/RationalHumanism\n---\n\nRichard Feynman (1918-1988) was an American  physicist  known for his work in the path integral formulation of quantum mechanics, the theory of quantum electrodynamics and the physics of the superfluidity of supercooled liquid helium, as well as in particle physics (he proposed the parton model).\n\nFor his contributions to the development of quantum electrodynamics, Feynman, jointly with Julian Schwinger and Sin-Itiro Tomonaga, received the Nobel Prize in Physics in 1965. He developed a widely used pictorial representation scheme for the mathematical expressions governing the behavior of subatomic particles, which later became known as Feynman diagrams. During his lifetime, Feynman became one of the best-known scientists in the world.\n\nHe assisted in the development of the atomic bomb and was a member of the panel that investigated the Space Shuttle Challenger disaster. In addition to his work in theoretical physics, Feynman has been credited with pioneering the field of quantum computing, and introducing the concept of nanotechnology (creation of devices at the molecular scale). He held the Richard Chace Tolman professorship in theoretical physics at the California Institute of Technology.\n\nFeynman was a keen popularizer of physics through both books and lectures, notably a 1959 talk on top-down nanotechnology called "There\'s Plenty of Room at the Bottom" and "The Feynman Lectures on Physics". Feynman also became known through his semi-autobiographical books ("Surely You\'re Joking, Mr. Feynman!" and "What Do You Care What Other People Think?") and books written about him, such as "Tuva or Bust!"\n\nHe was regarded as an eccentric and free spirit. He was a prankster, juggler, safecracker, proud amateur painter, and bongo player. He liked to pursue a variety of seemingly unrelated interests, such as art, percussion, Maya hieroglyphs, and lock picking.\n\nFeynman also had a deep interest in biology, and was a friend of the geneticist and microbiologist Esther Lederberg, who developed replica plating and discovered bacteriophage lambda. They had several mutual physicist friends who, after beginning their careers in nuclear research, moved for moral reasons into genetics, among them Le\xf3 Szil\xe1rd, Guido Pontecorvo, and Aaron Novick.\n\n\u2022 http://en.wikipedia.org/wiki/Richard_Feynman\n.',
     u'title': u'Great Minds: Richard Feynman - The Uncertainty Of Knowledge'},
    u'publishedAt': u'2010-03-04T15:12:56.000Z',
    u'tags': [u'great',
     u'minds',
     u'words',
     u'richard',
     u'feynman',
     u'uncertainty',
     u'knowledge',
     u'nature',
     u'purpose',
     u'universe',
     u'god',
     u'religion',
     u'atheists',
     u'atheism',
     u'science',
     u'physicists',
     u'quantum',
     u'mechanics',
     u'electrodynamics',
     u'superfluidity',
     u'nobel',
     u'prize',
     u'theoretical',
     u'physics',
     u'atomic',
     u'bomb',
     u'space',
     u'nano',
     u'technology'],
    u'thumbnails': {u'default': {u'height': 90,
      u'url': u'https://i.ytimg.com/vi/QkhBcLk_8f0/default.jpg',
      u'width': 120},
     u'high': {u'height': 360,
      u'url': u'https://i.ytimg.com/vi/QkhBcLk_8f0/hqdefault.jpg',
      u'width': 480},
     u'maxres': {u'height': 720,
      u'url': u'https://i.ytimg.com/vi/QkhBcLk_8f0/maxresdefault.jpg',
      u'width': 1280},
     u'medium': {u'height': 180,
      u'url': u'https://i.ytimg.com/vi/QkhBcLk_8f0/mqdefault.jpg',
      u'width': 320},
     u'standard': {u'height': 480,
      u'url': u'https://i.ytimg.com/vi/QkhBcLk_8f0/sddefault.jpg',
      u'width': 640}},
    u'title': u'Great Minds: Richard Feynman - The Uncertainty Of Knowledge'}}],
 u'kind': u'youtube#videoListResponse',
 u'pageInfo': {u'resultsPerPage': 1, u'totalResults': 1}}

rawDescription: How to get a single video from YouTube using its id?

description: Get a single video from YouTube using its id


code:
log = subprocess.Popen(mycmd,
                       stdin = subprocess.PIPE, stdout = subprocess.PIPE,
                       stderr = subprocess.PIPE)

rawDescription: Not able to fetch log files from shell using python


code:
class YourView(CreateView):
    form = YourFormClass  # no arguments here

    def get_form_kwargs(self):
        kwargs = super(YourViewName, self).get_form_kwargs()
        kwargs['initial'] = {}  # your initial data here
        return kwargs

rawDescription: Django and Crispy Forms- Can not get default value to work in Radio Select widget.


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

list1 = np.arange(1,13)
list1_y = np.array([1]*12)
a = np.array([2,5,8,11])
kmeans = sklearn.cluster.KMeans(n_clusters=a.shape[0],n_init=1,init=a.reshape((a.shape[0],1)))
kmeans.fit(list1.reshape((list1.shape[0],1)))
labels = kmeans.labels_
plt.scatter(list1, list1_y, c=labels.astype(np.float))
plt.show()

rawDescription: Forming sub-lists with pre-defined averages from an initial list


rawDescription: Access multiple (row, column) combinations in a numpy array


code:
for i in range(len(listNew)):
    # Have we exceeded the previous list's length? Time to just write data in.
    if i >= len(listPrevious):
        listPrevious.append(listNew[i])
        continue

    if listNew[i] != listPrevious[i]:
        listPrevious[i] = listNew[i]

rawDescription: How to compare each item in two lists of unknown lengths, order, and with duplicate values while minimizing writes and preserving position in Python?

description: Compare each item in two lists of unknown lengths, order, and with duplicate values while minimizing writes and preserving position in Python


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

import TeraGui

class MainWindow(QMainWindow, TeraGui.Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.actionSelect.triggered.connect(self.Select)

    def Select(self):
        dialog = Dialog(self)
        dialog.exec_()
        self.ShowPath.setText(dialog.path)

class Dialog(QDialog, TeraGui.Ui_SelectFiles):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setupUi(self)
        self.ChooseDirButton.clicked.connect(self.ChooseDirectory)
        self.path = ''

    def ChooseDirectory(self):
        self.path = str(QFileDialog.getExistingDirectory(
            self, "Select Directory"))

app = QApplication(sys.argv)
form = MainWindow()
form.show()
app.exec_()

rawDescription: PyQt: Connecting a button in a dialog

description: PyQt: Connecting a button in a dialog


code:
import wx

class Frame(wx.Frame):
    def __init__(self, title):
        wx.Frame.__init__(self, None, title=title, size=(300,200))

        self.panel = wx.Panel(self)
        box = wx.BoxSizer(wx.VERTICAL)
        m_text = wx.StaticText(self.panel, -1, 'File Uploaded!')
        m_text.SetSize(m_text.GetBestSize())

        box.Add(m_text, 0, wx.ALL, 10)
        self.panel.SetSizer(box)
        self.panel.Layout()

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.onClose, self.timer)
        self.timer.Start(5000)

    def onClose(self, event):
        self.Close()

app = wx.App(redirect=True)
top = Frame('test')
top.Show()
app.MainLoop()

rawDescription: pop up a window with text in it and automatically close it after certain time

description: Pop up a window with text in it and automatically close it after certain time


code:
fp = codecs.open('outputfile6.txt', encoding='utf-8')
lines1 = fp.readlines()
fp.close()
fb = codecs.open('outputfile6.txt', 'w')
for j in range(0,len(lines1)):
    if j>end:
        fb.write(lines1[j].encode('UTF-8'))

fb.close()

rawDescription: Write to a file from another file and delete line from file


code:
# regular class
class ClassOne(Base):
    __tablename__ = 'one'
    id = Column(Integer, primary_key=True)

class ClassTwo(Base):
    __tablename__ = 'two'
    id = Column(Integer, primary_key=True)

def map_to_alt_tb(cls, metadata, schemaname):
    m = class_mapper(cls)
    cls2 = type(
        "AltClass",
        (object, ),
        {}
    )
    table = m.local_table.tometadata(metadata, schemaname)
    mapper(cls2, table)
    return cls2

alt_cls = map_to_alt_db(ClassTwo, somemetadata, "alt_schema")

rawDescription: Qualifying table names with database names in sqlalchemy


code:
last_line = None
for row in reader0:
    if last_line is None:
        last_line = row
        continue

    # now compare row to last_line

    last_line = row

rawDescription: parse CSV file and compare line by line

description: Parse CSV file and compare line by line


code:
def main():
    # Start the scheduler
    filename = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'tmp')) + '\\' + 'spider.log'
    logging.basicConfig(filename=filename, level=logging.DEBUG,format='%(levelname)s[%(asctime)s]: %(message)s')
    sched = Scheduler()
    sched.start()
    sched.add_interval_job(run_job, minutes=30)

rawDescription: Make APScheduler run in background in web app


code: f = open('something.mp3', 'rb')

rawDescription: Transfering MP3 format to FTP using python


rawDescription: IPython: Plot graphics when running an external script within IPython in pylab mode


code:
while True:
    name = input("What is your name? ").strip()
    if len(name.split()) == 1:
        name = name.title()
        break
    else:
        print("Too long! Make it shorter!")

rawDescription: Python input only accept one argument

description: Python input only accept one argument


code:
from PIL import Image

im = Image.open("sweet_pic.ppm")
im.save("sweet_pic.jpg")

rawDescription: PPM to JPEG/JPG conversion for Python 3.4.1


code:
from django.core.files.images import get_image_dimensions
class myForm(forms.ModelForm):
   class Meta:
       model = myModel
   def clean_picture(self):
       picture = self.cleaned_data.get("picture")
       if not picture:
           raise forms.ValidationError("No image!")
       else:
           w, h = get_image_dimensions(picture)
           if w != 100:
               raise forms.ValidationError("The image is %i pixel wide. It's supposed to be 100px" % w)
           if h != 200:
               raise forms.ValidationError("The image is %i pixel high. It's supposed to be 200px" % h)
       return picture

rawDescription: Validate image size in django admin

description: Validate image size in django admin


code:
import os
import bz2

#os.chdir("D:/test")

username = 'username'
password = 'password'
computer_name = os.environ['COMPUTERNAME']

compressed = bz2.compress(username + '\0' + password + '\0' + computer_name)

with open("Session.dat", "wb") as f:
    f.write(compressed)

with open("Session.dat", "rb") as f:
    d_data = bz2.decompress(f.read())

print(d_data.split('\0'))

rawDescription: Simple encryption and decryption of strings by using bz2 in Python


code:
from setuptools import setup, find_packages, Extension
from Cython.Distutils import build_ext

ext_modules=[
    Extension("package.wrapper.wrap",    # location of the resulting .so
             ["package/wrapper/wrap.pyx"],) ]

setup(name='package',
      packages=find_packages(),
      cmdclass = {'build_ext': build_ext},
      ext_modules = ext_modules,
     )

rawDescription: Customize location of .so file generated by Cython


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

fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

x,y = np.random.rand(100),np.random.rand(100)

ax1.plot(x,y,'ko')
ax2.plot(x,y,'ko')

i = 10

transFigure = fig.transFigure.inverted()

coord1 = transFigure.transform(ax1.transData.transform([x[i],y[i]]))
coord2 = transFigure.transform(ax2.transData.transform([x[i],y[i]]))

line = matplotlib.lines.Line2D((coord1[0],coord2[0]),(coord1[1],coord2[1]),
                               transform=fig.transFigure)
fig.lines = line,

ax1.plot(x[i],y[i],'ro',markersize=20)
ax2.plot(x[i],y[i],'ro',markersize=20)

plt.show()

rawDescription: Drawing lines between two plots in Matplotlib


code:
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

related = MIMEMultipart('form-data', '*****')  # second argument is the boundary.
file_part = MIMEApplication(
    open('1103290736_2016_03_23_13_32_55.zip', 'rb').read(),
    # optional: set a subtype: 'zip',
)
file_part.add_header('Content-disposition', 'form-data; name="uploadedfile"')
related.attach(file_part)

body = related.as_string().split('\n\n', 1)[1]
headers = dict(related.items())
headers['User-Agent'] = 'Dalvik/1.6.0 (Linux; U; Android 4.4.2; S503+ Build/KOT49H)'

r = session.post(url, data=body, headers=headers)

rawDescription: python set-up boundary for POST using multipart/form-data with requests

description: Python set-up boundary for POST using multipart/form-data with requests


code:
def doit(inf, ouf, thestring, separator='SEPARATOR\n'):
  thestring += '\n'
  for line in inf:
    # here we're always at the start-of-block separator
    assert line == separator
    blockid = next(inf)
    if blockid == thestring:
      # found block of interest, use enumerate to count its lines
      for c, line in enumerate(inf):
        if line == separator: break
      assert line == separator
      # emit results and terminate function
      ouf.writelines((separator, thestring, '(%d)' % c, separator))
      inf.close()
      ouf.close()
      return
    # non-interesting block, just skip it
    for line in inf:
      if line == separator: break

rawDescription: Bash or Python for extracting blocks from text files


code:
def in_ipython():
    try:
        __IPYTHON__
    except NameError:
        return False
    else:
        return True

rawDescription: Detect executable (python? ipython?) in .pythonrc.py


code:
#models.py
upload_path = 'files'
class Model(models.Model):
    file = models.FileField(upload_to=lambda x,y: upload_path)

#tests.py
@mock.patch('models.upload_path', 'files/test')
class ModelTest(object):
    ...

rawDescription: Django - how to change FileField upload_to path during testing


code:
last = set(lst[0])
res = [lst[0]]
for item in lst[1:]:
    last &= set(item)
    res.append(list(last))

rawDescription: Python: How to only retain elements from all previous sublists while iterating over list?


code:
distances = (a-b)**2
distances = distances.sum(axis=-1)
distances = np.sqrt(distances)

rawDescription: In Numpy, find Euclidean distance between each pair from two arrays


code:
def http_proxy_connect(address, proxy = None, auth = None, headers = {}):
  """
  Establish a socket connection through an HTTP proxy.

  Arguments:
    address (required)     = The address of the target
    proxy (def: None)      = The address of the proxy server
    auth (def: None)       = A tuple of the username and password used for authentication
    headers (def: {})      = A set of headers that will be sent to the proxy

  Returns:
    A 3-tuple of the format:
      (socket, status_code, headers)
    Where `socket' is the socket object, `status_code` is the HTTP status code that the server
     returned and `headers` is a dict of headers that the server returned.
  """
  import socket
  import base64

  def valid_address(addr):
    """ Verify that an IP/port tuple is valid """
    return isinstance(addr, (list, tuple)) and len(addr) == 2 and isinstance(addr[0], str) and isinstance(addr[1], (int, long))

  if not valid_address(address):
    raise ValueError('Invalid target address')

  if proxy == None:
    s = socket.socket()
    s.connect(address)
    return s, 0, {}

  if not valid_address(proxy):
    raise ValueError('Invalid proxy address')

  headers = {
    'host': address[0]
  }

  if auth != None:
    if isinstance(auth, str):
      headers['proxy-authorization'] = auth
    elif auth and isinstance(auth, (tuple, list)):
      if len(auth) == 1:
        raise ValueError('Invalid authentication specification')

      t = auth[0]
      args = auth[1:]

      if t.lower() == 'basic' and len(args) == 2:
        headers['proxy-authorization'] = 'Basic ' + base64.b64encode('%s:%s' % args)
      else:
        raise ValueError('Invalid authentication specification')
    else:
      raise ValueError('Invalid authentication specification')

  s = socket.socket()
  s.connect(proxy)
  fp = s.makefile('r+')

  fp.write('CONNECT %s:%d HTTP/1.0\r\n' % address)
  fp.write('\r\n'.join('%s: %s' % (k, v) for (k, v) in headers.items()) + '\r\n\r\n')
  fp.flush()

  statusline = fp.readline().rstrip('\r\n')

  if statusline.count(' ') < 2:
    fp.close()
    s.close()
    raise IOError('Bad response')
  version, status, statusmsg = statusline.split(' ', 2)
  if not version in ('HTTP/1.0', 'HTTP/1.1'):
    fp.close()
    s.close()
    raise IOError('Unsupported HTTP version')
  try:
    status = int(status)
  except ValueError:
    fp.close()
    s.close()
    raise IOError('Bad response')

  response_headers = {}

  while True:
    tl = ''
    l = fp.readline().rstrip('\r\n')
    if l == '':
      break
    if not ':' in l:
      continue
    k, v = l.split(':', 1)
    response_headers[k.strip().lower()] = v.strip()

  fp.close()
  return (s, status, response_headers)

rawDescription: Establishing a TCP connection through an authenticated HTTP proxy?


code:
from pyspark.sql.functions import row_number
from pyspark.sql import Window

w = Window.partitionBy("some_column").orderBy("some_other_column")
df.withColumn("rn", row_number().over(w))

rawDescription: How can I enumerate rows in groups with Spark/Python?

description: Enumerate rows in groups with Spark/Python


code:
intersection = queryset1 & queryset2

union = queryset1 | queryset2

rawDescription: Union and Intersection of Arrays in Django


code:
view = QWebView()
netmanager = view.page().networkAccessManager()
netmanager.setNetworkAccessible(QNetworkAccessManager.NotAccessible)
view.setHtml(html)

rawDescription: pyqt - prevent requests for images and javascript files

description: Pyqt - prevent requests for images and javascript files


code:
import pandas as pd

pd.melt(df, id_vars=['SAMPLE_ID', 'ROW', 'COL'], var_name='Field', value_name='Value')

rawDescription: Bulding Dataframe with additional entries from existing one


code:
class TaskFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, parent = None, id = -1, title="ScrolledPanel", size = (500, 600))
        MainPanel = wx.Panel(self)
        NewPanel = scrolled.ScrolledPanel(parent = MainPanel, pos = (100, 100), size = (300, 200), id = -1, style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER, name="panel" )

        PanelSizer  = wx.BoxSizer()
        InsidePanel = wx.Panel(NewPanel)
        self.Button = wx.Button(parent=InsidePanel, id = -1, label="Log", pos=(500, 30), size=(50, 20))
        PanelSizer.Add(InsidePanel, proportion=1)

        NewPanel.SetSizer(PanelSizer)
        NewPanel.SetupScrolling()

rawDescription: How come ScrolledPanel in wxpython not working this way?


code:
import datetime
a = datetime.datetime.strptime("8:30pm", "%I:%M%p")
today = datetime.datetime.today()

result = datetime.datetime.combine(today.date(), a.time())

# result == datetime.datetime(2011, 12, 25, 20, 30)

rawDescription: Add current day to a specified hour and minute in Python


code:
inv_index = collections.defaultdict(set)

vocabulary = set(self.vocab)
for i, document in enumerate(self.docs):
    in_document = vocabulary & set(document)
    for word in in_document:
        inv_index[word].add(i)

rawDescription: Efficient saving of an index of docs where a word of a vocabulary occurs


code:
root.protocol('WM_DELETE_WINDOW', doSomething)  # root is your root window

def doSomething():
    # check if saving
    # if not:
    root.destroy()

rawDescription: Overriding Tkinter "X" button control (the button that close the window)


code:
S = (input("Enter a string: "))
S = S.lower()
alpha = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()! "
L = []
#counts the occurrence of characters in a string.
#then puts them in a list
for char in S:
     if char in alpha:
          count = S.count(char)
     L.append(char)
     L.append(count)
#turns list into a nested list
L2 = []
i = 0
while i <len(L):
        L2.append(L[i:i+2])
        i += 2
#checks that the lists dont appear more than once
L3 = []
for i in L2:
     if i not in L3:
          L3.append(i)

# print out the letters and count of the letter
for i,k in L3:
     print(i,k)

rawDescription: Count the occurrence of characters in a string


code:
class LRUCache2(LRUCache):
    def __init__(self, maxsize, missing=None, getsizeof=None, evict=None):
        LRUCache.__init__(self, maxsize, missing, getsizeof)
        self.__evict = evict

    def popitem(self):
        key, val = LRUCache.popitem(self)
        evict = self.__evict
        if evict:
            evict(key, val)
        return key, val

rawDescription: Python functools.lru_cache eviction callback or equivalent


rawDescription: Returning only one boolean statement if two matrices identical


code:
import sys
import math
import time
from PyQt4 import QtGui, QtCore
class MyFrame(QtGui.QGraphicsView):
    def __init__( self, parent = None ):
        super(MyFrame, self).__init__(parent)
        self.resize(800,600)
        self.scene = QtGui.QGraphicsScene()
        self.setScene(self.scene)

    def doAnimation(self):
        for x in range(5):

            self.scene.clear();
            y = 100*(math.cos(x+200))

            pen1   = QtGui.QPen(QtGui.QColor(QtCore.Qt.red))
            brush1 = QtGui.QBrush(pen1.color().darker(255))
            item1 = self.scene.addEllipse(x, y, 100, 100, pen1,brush1)

            pen2   = QtGui.QPen(QtGui.QColor(QtCore.Qt.green))
            brush2 = QtGui.QBrush(pen2.color().darker(150))
            item2 = self.scene.addEllipse(x-25, y+100, 150, 150, pen2,brush2)

            pen3   = QtGui.QPen(QtGui.QColor(QtCore.Qt.blue))
            brush3 = QtGui.QBrush(pen3.color().darker(150))
            item3 = self.scene.addEllipse(x-50, y+250, 200, 200, pen3,brush3)

            QtGui.QApplication.processEvents()
            time.sleep(1)

app = QtGui.QApplication([])
f = MyFrame()
f.show()
f.doAnimation()
app.exec_()

rawDescription: How to update something like graph in pyqt

description: Update something like graph in pyqt


code:
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.request"
)

rawDescription: How do I use context_instance in my template

description: Use context_instance in my template


code:
tuple_list = zip(appliedFieldOP, appliedFieldOP2)
filtered = filter(lambda x: x1+1000 >= x[0] >= x1-1000, tuple_list)

rawDescription: Python find matching array

description: Python find matching array


code:
class MyMixin(object):

    def get_context_data(self, **kwargs):
        context = super(MyMixin, self).get_context_data(**kwargs)
        context['panel_info'] = get_panel_info()
        return context

class MyView(MyMixin, DetailView):
   ...

rawDescription: How to use Django mixin?

description: Use Django mixin


code: E1 = Entry(top, bd = 5, show="*")

rawDescription: Hiding password entry input in python

description: Hiding password entry input in python


code:
import foo
bar = foo.bar
del foo

rawDescription: Python modules scope

description: Python modules scope


code:
from bulbs.config import Config, DEBUG
from bulbs.rexster import Graph
from bulbs.titan import Graph

config = Config('http://localhost:8182/graphs/ramgraph')
g = Graph(config)

class inser_class():
    ponnapu = g.vertices.create(name="reddy", age="26", state="TELNGANA", mobn="111111111")
    pr = g.vertices.create(name="ramnath" ,age="25" , state="TELNGANA", mobn="1111111")
    tanu = g.vertices.create (name="ponnapu",age="27",state="AP",mobn="11111111111111")
    g.edges.create(pr, "knows", tanu)
    g.edges.create(pr, "friends", ponnapu)
    g.edges.create(ponnapu, "dontknow",tanu)

rawDescription: What is my mistake?

description: What is my mistake


code:
for i, o in enumerate(obj_list):
    if o.attr == known_value:
        del obj_list[i]
        break

rawDescription: OOP python - removing class instance from a list


code:
def remove_zeros(*all_quizzes):
    result = []
    for each_quiz in all_quizzes:
        updated_quiz_list = []
        for number in each_quiz:
            if number != 0:
                updated_quiz_list.append(number)
        result.append(updated_quiz_list)
    return result

rawDescription: Applying a function to multiple lists in Python


code:
cc = [('us', .2), ('gb', .2), ('de', .1), ('fr', .05), ('it', .05)]
distribution = n / sum(dist for c, dist in cc)
countries = []
for c, dist in cc:
    countries.extend([c] * int(round(distribution * dist)))
# rounding errors may mean we have too few, add until we have enough
while len(countries) < n:
    countries.append(random.choice(cc)[0])
random.shuffle(countries)

rawDescription: Zip two lists of unequal length to form a dictionary. Values to be randomly picked from one of the lists


code:
def process_view(self, request, view_func, view_args, view_kwargs):
    if some_clause:
        return render(request, 'foo.html', {'foo': 'bar'})

    return view_func(request, view_args, view_kwargs)

rawDescription: Django custom middleware rendering has no csrf token


code:
from scipy.linalg import eigh

eigvals, eigvecs = eigh(A, B, eigvals_only=False)

rawDescription: Numpy: Generalized Eigenvalue ProbIem

description: Numpy: Generalized Eigenvalue ProbIem


code:
from PySide import QtGui, QtCore
import sys

def listItems():
    itemList = ("first","second","etc..")
    return itemList

class tabDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)

        self.tabWidget = QtGui.QTabWidget()
        self.mainTab = mainTab(self)
        self.secondTab = secondTab(self)

        self.tabWidget.addTab(self.mainTab, self.tr("Main"))
        self.tabWidget.addTab(self.secondTab, self.tr("Second "))

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(self.tabWidget)
        self.setLayout(mainLayout)

    def additemToList(self):
        item = self.mainTab.fileNameEdit.text()
        self.mainTab.projectListCombo.addItem(item)
        self.secondTab.projectListCombo.addItem(item)

class mainTab(QtGui.QWidget):
    def __init__(self,  parent=tabDialog):
        QtGui.QWidget.__init__(self, parent)
        self.q = 1234
        self.createGroup = QtGui.QGroupBox(self.tr("Add Item to list"))
        self.fileNameEdit = QtGui.QLineEdit(self)
        self.fileNameEdit.setPlaceholderText("new item")

        self.createButton = QtGui.QPushButton('add',self)
        self.createButton.clicked.connect(parent.additemToList)

        self.createLayout = QtGui.QGridLayout()
        self.createLayout.addWidget(self.fileNameEdit,1,2)
        self.createLayout.addWidget(self.createButton,1,3)
        self.setLayout(self.createLayout)
        self.createGroup.setLayout(self.createLayout)

        self.addGroup = QtGui.QGroupBox(self.tr("list items"))
        self.projectLabel = QtGui.QLabel(self.tr("item : "))
        self.projectListCombo = QtGui.QComboBox(self)
        self.projectListCombo.addItems(listItems())
        self.addLayout = QtGui.QHBoxLayout()
        self.addLayout.addWidget(self.projectLabel)
        self.addLayout.addWidget(self.projectListCombo)
        self.addGroup.setLayout(self.addLayout)

        self.mainLayout = QtGui.QVBoxLayout()
        self.mainLayout.addWidget(self.createGroup)
        self.mainLayout.addWidget(self.addGroup)
        self.setLayout(self.mainLayout)

class secondTab(QtGui.QWidget):
    def __init__(self,  parent=tabDialog):
        QtGui.QWidget.__init__(self, parent)
        self.initUI()

    def initUI(self):

        self.addGroup = QtGui.QGroupBox(self.tr("list items"))
        self.projectLabel = QtGui.QLabel(self.tr("item : "))
        self.projectListCombo = QtGui.QComboBox(self)
        self.projectListCombo.addItems(listItems())
        self.addLayout = QtGui.QHBoxLayout()
        self.addLayout.addWidget(self.projectLabel)
        self.addLayout.addWidget(self.projectListCombo)
        self.addGroup.setLayout(self.addLayout)

        self.mainLayout = QtGui.QVBoxLayout()
        self.mainLayout.addWidget(self.addGroup)
        self.setLayout(self.mainLayout)

def main():
    app = QtGui.QApplication(sys.argv)
    tabdialog = tabDialog()
    tabdialog.show()
    app.exec_()

if __name__ == '__main__':
    main()

rawDescription: pySide QComboBox refresh

description: PySide QComboBox refresh


rawDescription: Convert string into term

description: Convert string into term


code:
from twill import commands
commands.go("http://www.thepiratebay.se/login")
commands.form("loginform", "username", "blah")
commands.form("loginform", "password", "blah")
commands.submit()

rawDescription: Logging into website with requests

description: Logging into website with requests


code:
def Fight():

    player_wins = 0
    alien_wins = 0

    while player_wins <= 3 and alien_wins <= 3:

        player_roll = random.randint(0, 10)
        alien_roll = random.randint(0, 7)

        if player_roll > alien_roll:
            contents.set("You manage to fire a shot of your laser pistol and the alien backs off.")
            player_wins += 1

        elif alien_roll > player_roll:
            contents.set("The alien reaches out and strikes you with its claws.")
            alien_wins += 1

        elif alien_roll == player_roll:
            contents.set("You both grapple eachother and eventually back off.")

    if player_wins == 3:
        contents.set("You manage to overcome the alien. It leaps from wall to wall and crawls into the vents.")
        win = True
    elif alien_wins == 3:
        contents.set("You lose the fight to the alien. Game Over!")
    return

rawDescription: Using two counters in a loop

description: Using two counters in a loop


code:
widget = {}
for i in range(1,11):
    for j in range(1,11):
        widget[i,j] = Entry(...)

rawDescription: Assigning names to Tkinter 'entry'

description: Assigning names to Tkinter 'entry'


code:
def normalize(ip):
    if '/' in ip:
        return [ip]

    ocets = [ocet.replace(' ','') for ocet in ip.split('.')]
    if len(ocets) == 4: ocets += ocets
    if len(ocets) == 7:
        if (re.search('-',ocets[3])):
            for i,v in enumerate(ocets[3:]):
                if i == 0:
                    last = ocets[4]
                    ocets[3],ocets[4] = ocets[3].split('-')
                else:
                    if 4+i < len(ocets):
                        newVal = last
                        last = ocets[4+i]
                        ocets[4+i] = newVal
                    else:
                        ocets.append(last)

    if len(ocets) != 8:
        return 'ERROR WITH: %s not right size %d' % ('.'.join(ocets),len(ocets))
    for i,ocet in enumerate(ocets):
        if (re.search('\*',ocet)):
            ocets[i] = '0'
            ocets[i+4] = '255'

        if (re.search('-',ocets[i])):
            ocets[i],ocets[i+4] = ocets[i].split('-')[0:2]
    newIP = netaddr.iprange_to_cidrs('.'.join(ocets[0:4]) ,'.'.join(ocets[4:]))
    return newIP

rawDescription: Normalizing IP addresses

description: Normalizing IP addresses


code:
scores = []
for game in games:
    score.append(game.state.getScore())

rawDescription: Why is there a for in a sentence?

description: Why is there a for in a sentence


code:
query
re.split(r'(&|\^|)', query)

rawDescription: python - How to know what re used to split a string?

description: Python - How to know what re used to split a string


code:
start = 24*(pd.to_datetime('2002-05-01') - pd.to_datetime('1989-01-01')).days
end = 24*(pd.to_datetime('2006-11-20') - pd.to_datetime('1989-01-01')).days - 1
temp_values = df.loc[df['id'].between(start, end), 'temp'].values

rawDescription: Python/Pandas -- Converting row number to hour and then slicing


code:
for child in doc.getroot().iterchildren("*"):
    print(child.tag, child.attrib)

rawDescription: How to best iterate (breadth-first) over an lxml etree using Python

description: Best iterate (breadth-first) over an lxml etree using Python


code:
len_counts = [
    (1, 24), # 24 1-length words
    (2, 39), # 39 2-length words
    ...
]

rawDescription: random values with uneven distribution

description: Random values with uneven distribution


code: res = es.search(index="test-index", body={"query": {"match_all": {}}},  from_=20, size=100, _source=False)

rawDescription: How to specify meta parameters in search query

description: Specify meta parameters in search query


code:
def parse_file(self):
    with open(self.filename, 'r') as f:
        content = f.readlines()

        # Recreate content without lines that start with @ and +
        content = [line for line in content if not line[0] in '@+']

        # Now the lines you want are alternating, so you can make a dict
        # from key/value pairs of lists content[0::2] and content[1::2]
        data = dict(zip(content[0::2], content[1::2]))

    return data

rawDescription: read fastq file into dictionary

description: Read fastq file into dictionary


code:
def addWithLabel(parent,label,wxCtrl):
       sz_h1 = wx.BoxSizer(wx.HORIZONTAL)
       txt = wx.StaticText(parent,-1,label)
       sz_h1.Add(txt)
       sz_h1.Add(wxCtrl)
       return sz_h1

my_vertical_sizer.Add(addWithLabel(my_parent,"Some Label:",wx.TextCtrl(my_parent,-1)))

rawDescription: How to implement a wx.TextCtrl in a wx.GridBagSizer?

description: Implement a wx.TextCtrl in a wx.GridBagSizer


code:
from Tkinter import *
import random

root = Tk()

def retrieve_input(event):
    random_number = random.randint(1, 10)
    inp = float(number_space.get())
    if inp == random_number:
        print("You got it!")
    else:
        print("That's not the number.")
        print("The number was {}".format(random_number) + '.')

def startAgain():
    number_space.delete(0, 'end')

number = Label(root, text="Guess a number between 1 and 10:")
number.grid(row=0)
number_space = Entry(root)
number_space.grid(row=0, column=1)
butt = Button(root, text="Generate a new random number", command=startAgain)
butt.grid(row=1, column=0)

number_space.bind("<Return>", retrieve_input)

root.mainloop()

rawDescription: Calling a variable through a button in Tkinter


code:
from datetime import timedelta
delta = timedelta(days=7)
df_score_mean = df.apply(lambda x: np.mean(df['score'][df['ts'] <= x['ts'] + delta]), axis=1)

rawDescription: How to use days as window for pandas rolling_apply function

description: Use days as window for pandas rolling_apply function


rawDescription: Converting a list of Characters to a list of numbers


code:
lambda key: mydict[key]

def temp_function(key):
    return mydict[key]

rawDescription: Methods for sorting a dictionary

description: Methods for sorting a dictionary


rawDescription: Python: How to get UTC time given TIMEZONE