code:
# put this in some app such as customize/templatetags/admin_modify.py and place the app
# before the 'django.contrib.admin' in the INSTALLED_APPS in settings

from django.contrib.admin.templatetags.admin_modify import *
from django.contrib.admin.templatetags.admin_modify import submit_row as original_submit_row
# or
# original_submit_row = submit_row

@register.inclusion_tag('admin/submit_line.html', takes_context=True)
def submit_row(context):
    ctx = original_submit_row(context)
    ctx.update({
        'show_save_and_add_another': context.get('show_save_and_add_another', ctx['show_save_and_add_another']),
        'show_save_and_continue': context.get('show_save_and_continue', ctx['show_save_and_continue'])
        })
    return ctx

rawDescription: In Django admin, how can I hide Save and Continue and Save and Add Another buttons on a model admin?


code:
columns = pd.MultiIndex.from_arrays([X, Y])
df = DataFrame(Data, columns=columns, index=Z)
df
df1 = df.unstack().reset_index()
df1.columns = ['X', 'Y', 'Z', 'Data']
df1

rawDescription: Convert datafiles 'X' 'Y' 'Z' 'data' format


code:
class VKHandshakeChecker:
    @property
    def answers(self):
        return self.__answers

    @property
    def status(self):
        return self.__status

    def __init__(self,vkapi,maxDepth=6):
        self.vkapi = vkapi
        self.__maxDepth=maxDepth
        self.__answers = list()
        self.__status = 'IDLE'

rawDescription: Python: get value of property

description: Python: get value of property


code:
s = u'\xd0\x92\xd0\xbb\xd0\xb0\xd0\xb4\xd0\xb8\xd0\xbc\xd0\xb8\xd1\x80'
s.encode('latin-1')

rawDescription: Decoding 'raw' string converted to unicode


code:
del sys.modules["mymodule"]
del mymodule

rawDescription: memory impact and scope/lifespan of imported modules python

description: Memory impact and scope/lifespan of imported modules python


code:
class Order(object):
    """Defines an individual order"""
    def __init__(self, input_header, input_line):
        for z in xrange(len(input_header)):
            setattr(self, input_header[z], input_line[z])

orders = {}
input_header = input_list.pop(0)
for a in xrange(len(input_list)):
    orders[a] = Order(input_header, input_list[a])

rawDescription: Creating Class Instances Dynamically in Python


code:
field.fill((255, 255, 255))
runningBlock.update()
runningBlock.draw(field)
lyingBlocks.draw(field)
screen.blit(field, (20, 20))
pygame.display.flip()

rawDescription: pygame sprites and pygame.display.flip() results in artifacts

description: Pygame sprites and pygame.display.flip() results in artifacts


code:
search = oDoc.createSearchDescriptor()
search.SearchRegularExpression = True
search.SearchString = "FOOBAR$"
selsFound = oDoc.findAll(search)
for sel_index in range(0, selsFound.getCount()):
    oSel = selsFound.getByIndex(sel_index)
    try:
        oCursor = oSel.getText().createTextCursorByRange(oSel)
    except (RuntimeException, IllegalArgumentException):
        return
    oCursor.setString("")  # delete
    oCursor.goRight(1, True) # select newline character
    oCursor.setString("")  # delete

rawDescription: Search strings and line breaks with pyUNO


rawDescription: Apply Different Resampling Method to the Same Column (pandas)


code: result = [[[i[0]] + j for j in i[1:][0] ] for i in arr][0]

rawDescription: How to flatten a list in python?

description: Flatten a list in python


code: root.tk.call('wm', 'iconphoto', root._w, PhotoImage(file='ico.gif'))

rawDescription: Change Icon For Tkinter Messagebox

description: Change Icon For Tkinter Messagebox


code:
# create some data
x = np.linspace(-np.pi,np.pi,100)
y = np.cos(2.5*x)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y, mfc='orange', mec='orange', marker='.')

# using 'spines', new in Matplotlib 1.0
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax.axhline(linewidth=2, color='blue')
ax.axvline(linewidth=2, color='blue')
show()

rawDescription: change matplotlib axis settings

description: Change matplotlib axis settings


code:
if data.find ( '!hc call' )!= -1:
   #re1 = 'call(.*?)*'
    re1 = r"call\s\b(.*)\b"
    rg = re.compile(re1,re.IGNORECASE|re.DOTALL)
    m = rg.search(data)
    if m:
        cdata = m.group(1)
        #s.send("PRIVMSG %s %s \r\n" % (CHAN, cdata))
        s.send ("PRIVMSG %s %s \r\n" % (CHAN, 'Querying Radio Reference...'))
        url = "http://radioreference.com/apps/ham/callsign/%s" % cdata
        callsign_query = urllib2.urlopen(url)
        content = callsign_query.read()
        re2 = '(.*?)'
        rg = re.compile(re2,re.IGNORECASE|re.DOTALL)

rawDescription: Python IRC Bot: Set variable from channel


code:
def op(A):
    tmp = np.array(A)
    tmp = tmp[tmp < tr]
    tmp = np.histogram(tmp, x)
    return tmp[0]/sum(tmp[0])

# creates a generator
map(op, X)
# or, to get a list
l1 = list(map(op, X))

rawDescription: Python: how to avoid a loop for normalizing a list of list?


code:
import sys
from PyQt4 import QtCore, QtGui

class MyWin(QtGui.QWidget):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.label = QtGui.QLabel('time', self)
        self.setLayout(QtGui.QVBoxLayout())
        self.layout().addWidget(self.label)

        self.timer = QtCore.QTimer(self)
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.displayTime)
        self.timer.start()

    def displayTime(self):
        self.label.setText(QtCore.QDateTime.currentDateTime().toString())

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    win = MyWin()
    win.show()
    sys.exit(app.exec_())

rawDescription: PyQt4: Printing OS Date/Time to a label

description: PyQt4: Printing OS Date/Time to a label


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

# Create the figure and axes, keeping the object references
fig = plt.figure()
ax = fig.add_subplot(111)

p, = ax.plot(np.linspace(0,1))

# First display
plt.show()

 # Some time to let you look at the result and move/resize the figure
plt.pause(3)

# Replace the contents of the Axes without making a new window
ax.cla()
p, = ax.plot(2*np.linspace(0,1)**2)

# Since the figure is shown already, use draw() to update the display
plt.draw()
plt.pause(3)

# Or you can get really fancy and simply replace the data in the plot
p.set_data(np.linspace(-1,1), 10*np.linspace(-1,1)**3)
ax.set_xlim(-1,1)
ax.set_ylim(-1,1)

plt.draw()

rawDescription: Update/Refresh matplotlib plots on second monitor


code:
CI=true
TRAVIS=true

rawDescription: how to know if my Python tests are running in coverage mode?

description: Know if my Python tests are running in coverage mode


code:
t = (
    ('dog', 'Dog'),
    ('cat', 'Cat'),
    ('fish', 'Fish'),
)
def contains(w, t):
    return any(w == e[0] for e in t)

contains('fish', t)
contains('dish', t)

rawDescription: Looking for values in nested tuple

description: Looking for values in nested tuple


code:
for pair in zip(elem1, elem2):
    testResults(*pair) # unpack pair here

rawDescription: Pass multiple elements of multiple lists to a function in python


code:
while True:

    for event in pygame.event.get():

        if event.type == KEYDOWN:
            keypressed = True

            #Set your changetype and color variables

        if event.type == KEYUP:

            keypressed = False;

    if keypressed:

        Color_Update(changeType, color)
        Color_Draw(red, green, blue)

    pygame.display.update()

rawDescription: Python/Pygame: How to break a while loop initiated by KEYDOWN event with a KEYUP event?


code:
import sys
sys.stdout.write("\x1b[6n");a=sys.stdin.read(10)

a
sys.stdin.isatty()

rawDescription: How can I get the cursor's position in an ANSI terminal?

description: Get the cursor's position in an ANSI terminal


rawDescription: Splitting strings in an array - python

description: Splitting strings in an array - python


code:
import Tkinter as tk

root = tk.Tk()

def clicked(event):
    var.set('Clicked the button')

def released(event):
    var.set('Released the button')

var = tk.StringVar()
var.set('Nothing to see here')
label = tk.Label(root, textvar=var)
label.pack()

but = tk.Button(root, text='Button')
but.bind("<Button-1>", clicked)
but.bind("<ButtonRelease-1>", released)
but.pack()

root.mainloop()

rawDescription: Run function from Python 2 Tkinter button when pressed then run another when released


code:
db = SQLAlchemy(app)

class MyTable(db.Model):
    ...

class MyOtherTable(db.Model):
    ...

db.metadata.create_all(db.engine, tables=[
    MyTable.__table__,
    ...
])

rawDescription: flask-sqlalchemy use of drop_all and create_all for specific tables

description: Flask-sqlalchemy use of drop_all and create_all for specific tables


code:
def limitSizeDay(*args):
    value = dayValue.get();
    if len(value) > 2: dayValue.set(value[:2]);

dayValue = StringVar();
dayValue.trace('w', limitSizeDay);

day_entry1=Entry(List1, bg="#282B2B", fg="white", width=2, textvariable=dayValue);
day_entry1.place(x=77, y=58);

rawDescription: (Python) How to limit an entry box to 2 characters max


code: from six.moves import builtin  # works for both python 2 and 3

rawDescription: How to use python modules that were renamed 3 in a cross compatible way?

description: Use python modules that were renamed 3 in a cross compatible way


code:
s='''
Username: Bob
Password: Coolness

'''

from subprocess import Popen,PIPE
p = Popen(['cat','-'], stdin=PIPE, stdout=PIPE)
stdoutdata, _ = p.communicate(s)

rawDescription: File in memory, Python

description: File in memory, Python


code:
from decimal import Decimal
a = [Decimal('0.4441'), Decimal('0.3821'), Decimal('0.4414'), Decimal('0.3391')]
a = [float(n) for n in a]
a

rawDescription: convert a list with decimal number and data type to just numbers

description: Convert a list with decimal number and data type to just numbers


code:
from itertools import groupby

def multiplicies( factors ):
    """ [x,x,x,,y,y] -> [(x,3), (y,2)] """
    return ((k, sum(1 for _ in group)) for k, group in groupby(factors))

def combinate(facs, cutoff=None):
    facs = tuple(multiplicies(facs))

    results = set()
    def explode(base, expanded):
        # `k` is the key for the caching
        # if the function got called like this before return instantly
        k = (base, expanded)
        if k in results:
            return
        results.add(k)

        # pick a factor
        for (f,m) in base:
            # remove it from the bases
            newb = ((g, (n if g!=f else n-1)) for g,n in base)
            newb = tuple((g,x) for g,x in newb if x > 0)

            # do we cutoff yet?
            if cutoff is None or len(newb) + len(expanded) < cutoff:
                explode(newb, tuple(sorted(expanded + (f,))))

            # multiply the pick with each factor in expanded
            for pos in range(len(expanded)):
                newexp = list(expanded)
                newexp[pos] *= f
                explode(newb, tuple(sorted(newexp)))

    explode(facs, ())
    # turn the `k` (see above) into real factor lists
    return set((tuple((x**y) for x,y in bases) + expanded)
        for (bases, expanded) in results)

# you dont even need the cutoff here!
combinate([2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3])
# but you need it for
combinate([2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3,5,7,9,11], 5)

rawDescription: non-prime factorings with some repeats

description: Non-prime factorings with some repeats


code:
for k, v in freqs.items():
    print(k, v)

rawDescription: Python Indexing

description: Python Indexing


code:
CMS_TEMPLATES = (
    ('base.html', gettext('default')),
    ('2col.html', gettext('2 Column')),
    ('3col.html', gettext('3 Column')),
    ('extra.html', gettext('Some extra fancy template')),
)

rawDescription: aldryn django-cms adding template

description: Aldryn django-cms adding template


code:
import scrapy
import json

class RentObject(scrapy.Item):
    address = scrapy.Field()
    purpose = scrapy.Field()
    # Add more fields as needed

class ScrapeSpider(scrapy.Spider):

    name = "rent_hk"
    allowed_domains = ['591.com.hk']
    start_urls = ['http://rent.591.com.hk/?hl=en-us#list' ]

    page_number = 0
    page_num_max = 5 # for test purposes grab only up to 5 pages

    def parse(self, response):

        if 'page_number' in response.meta:
            result_dict = json.loads(response.body)  # get data as dict
            for object in result_dict['items']:
                ro = RentObject()
                ro['address'] = object['address']
                ro['purpose'] = object['purpose']
                yield ro

        # Make request for (next page) JSON data
        self.page_number += 1

        payload = {
            'm': 'home',
            'c': 'search',
            'a': 'rslist',
            'type': '1',
            'p': str(self.page_number),
            'searchtype': '1'
        }

        if self.page_number < self.page_num_max:
            request = scrapy.FormRequest(url='http://rent.591.com.hk/',
                                         method='GET',
                                         formdata=payload,
                                         headers={'Referer': 'http://rent.591.com.hk/?hl=en-us',
                                                  'X-Requested-With': 'XMLHttpRequest'},
                                         callback=self.parse)
            request.meta['page_number'] = self.page_number
            yield request

rawDescription: Howto use scrapy to crawl a website which hides the url as href="javascript:;" in the next button


code: sum(len(set(x - i for i, x in enumerate(t))) for t in nums)

rawDescription: Summing Consecutive Ranges Pythonically

description: Summing Consecutive Ranges Pythonically


code:
self.urlopen.stop()
# points to the real `urlopen()` now
urllib2.urlopen()
# put the patch in place again
self.urlopen.start()

rawDescription: Temporary "unpatching" functionality within mock.side_effect


code:
parser.add_option("-o", action="callback", dest="output", callback=my_callback)

def my_callback(option, opt, value, parser):
     if len(parser.rargs) > 0:
         next_arg = parser.rargs[0]
         if not next_arg.startswith("-"):
             # Next argument is not another option
             del parser.rargs[0]
             setattr(parser.values, option.dest, next_arg)
             return
     # If not processed, set the default value
     setattr(parser.values, option.dest, "output.txt")

rawDescription: Python: Can optparse have the ACTION attribute to act both like STORE and STORE_TRUE?


code:
from poster.encode import multipart_encode, MultipartParam
from google.appengine.api import urlfetch

class VideoUploadHandler(webapp2.RequestHandler):
    def post(self):
        title = self.request.get('title')
        description = self.request.get('description')
        payload = {
            'api_password'    : 'my_password',
            'project_id'      : 'my_project_id',
            'name'            : title,
            'description'     : description,
            }
        file_data = self.request.POST['video']
        payload['file'] = MultipartParam('file', filename=file_data.filename,
                                              filetype=file_data.type,
                                              fileobj=file_data.file)
        data,headers= multipart_encode(payload)
        send_url = "https://upload.wistia.com"
        resp = urlfetch.fetch(url=send_url, payload="".join(data), method=urlfetch.POST, headers=headers)
        logging.info(resp)
        self.redirect("/")

rawDescription: HTML, jQuery, Python - Form File Upload (GAE)


code:
# python startup file
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
    readline.read_history_file(histfile)
except IOError:
    pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter

rawDescription: How to repeat last command in python interpreter shell?

description: Repeat last command in python interpreter shell


code:
from apscheduler.scheduler import Scheduler

schedule = Scheduler()
jobs = schedule.get_jobs() #jobs is a list of apscheduler jobs
jobs_kwargs = map(lambda k: k.kwargs, jobs)

rawDescription: Get a list of object properties from list of objects in python


code:
import matplotlib.pyplot as plt

x = range(0,1000)
y = [i*2 for i in x]

plt.plot(x,y)

x_ticks = [day for day in x if day%365 == 0] # Only pull out full years
x_labels = ['Year ' + str(i) for i in range(len(x_ticks))]

plt.xticks(x_ticks, x_labels)
plt.show()

rawDescription: Python - Changing Matplotlib Axis from Days to Years


code:
def data_reader(file_name, first_surface):
    flux = []
    SEM = []
    depth = []

    with open (file_name) as inf:
        lines = inf.readlines()
        for (i, line,) in enumerate(lines):
            if ' surface  %d' %first_surface in line:
                data = (lines[i+1].strip())
                fields = data.split()
                numbers = list(map(float,fields))
                flux.append(numbers[0])
                SEM.append(numbers[1])
                first_surface += 1
                depth.append(first_surface - 101)

    return (flux, SEM, first_surface)

rawDescription: Function Overwriting Data

description: Function Overwriting Data


code:
def get_config():
    config.read("config/map.ini")
    ser = serial.Serial(3)
    ser.write(bytes("D" + '\r\n', encoding='ascii'))
    time.sleep(1)
    while ser.inWaiting() > 0:
        r = ser.readline()
        r = r.decode('UTF-8').replace('\r\n', '')
        r = r.split()
        config.set("map", r[0], r[1].replace('V', ''))
        time.sleep(0.01)

    f = open("config/map.ini", "w")
    config.write(f)
    ser.close()

rawDescription: Python Serial function returns incomplete list of items.


code:
import re

def sampleRounder(match):
    return str(int(float(match.group(1)))) #base=10

s = "this is v = 2342.2\n and another v = 231.003\n and some stuff..."

print(re.sub("v = ([0-9]*\.[0-9]+|[0-9]+)\\n", sampleRounder, s))

rawDescription: Python find and replace numbers based on pattern


code:
import re

# example string from your file
s='05-03 12:53:15.251 ACTION_MOVE, (596.00, 841.00) '

# The unescaped round brackets will capture the numbers
r =re.match(r'\d+-\d+\s+\d+:\d+:(\d+\.\d+)\s+[A-Z_]+,\s+\(\d+\.\d+,\s+\d+\.\d+\)', s)

r.groups(0)  # Will output ('15.251',)

rawDescription: filtering logcat timestamp in python

description: Filtering logcat timestamp in python


rawDescription: Python - Create matrix from a string

description: Python - Create matrix from a string


code:
# all the imports
import sqlite3
from flask import Flask
from contextlib import closing

# configuration
DATABASE = './flaskr.db'
DEBUG = True

# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)

def init_db():
    with closing(connect_db()) as db:
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()

def connect_db():
    return sqlite3.connect(app.config['DATABASE'])

if __name__ == '__main__':
    init_db()
    #app.run()

rawDescription: Creating sqlite3 database from .sql file in Windows 8


code:
from reportlab.platypus.flowables import Image

class RotatedImage(Image):

    def wrap(self,availWidth,availHeight):
        h, w = Image.wrap(self,availHeight,availWidth)
        return w, h
    def draw(self):
        self.canv.rotate(90)
        Image.draw(self)

I = RotatedImage('../images/somelogo.gif')

rawDescription: A simple method for rotate images in reportlab


code:
def get(self, request, format=None, **kwargs):
    cart = get_cart(request)
    cart_serializer = CartSerializer(cart)
    another_serializer = AnotherSerializer(another_object)

    return Response({
        'cart': cart_serializer.data,
        'another': another_serializer.data,
        'yet_another_field': 'yet another value',
    })

rawDescription: Multiple Models in Django Rest Framework?


code:
def match_compare_key(self):
    """The match compare key for sorting.

    Current implementation:

    1. rules without any arguments come first for performance
    reasons only as we expect them to match faster and some
    common ones usually don't have any arguments (index pages etc.)
    2. The more complex rules come first so the second argument is the
    negative length of the number of weights.
    3. lastly we order by the actual weights.

    :internal:
    """
    return bool(self.arguments), -len(self._weights), self._weights

rawDescription: URL routing conflicts for static files in Flask dev server


code:
wins = {"player1": 0, "player2": 0}
this, other = "player1", "player2"
for i in range(rounds_count): # really, variable i don't use
    this, other = other, this # swap players
    if end_game():
        wins[this] +=1
    else:
        wins[other] += 1

rawDescription: Python - select the other element in a dictionary


code:
from django.test.client import Client
c = Client()

# request the web page:
response = c.get('/form/')

# get the Form object:
form = response.context['myform']

form_data = form.cleaned_data
my_form_data = {} # put your filled-out data in here...
form_data.update(my_form_data)

# submit the form back to the web page:
new_form = forms.Form(form_data)
if new_form.is_valid():
    c.post('/form/', new_form.cleaned_data)

rawDescription: How do I submit a form given only the HTML source?

description: Submit a form given only the HTML source


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

# Create the figure and axis
fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(0, 10))

# mMke the initial polygon with all vertices set to 0
pts = [[0,0], [0,0], [0,0], [0,0]]
patch = plt.Polygon(pts)
ax.add_patch(patch)

def init():
    return patch,

def animate(i):
    # Randomly set the vertices
    x1= 5*np.random.rand((1))[0]
    x2= 5*np.random.rand((1))[0]
    x3= 5*np.random.rand((1))[0] + 5
    x4= 5*np.random.rand((1))[0] + 5

    y1= 5*np.random.rand((1))[0]
    y2= 5*np.random.rand((1))[0]
    y3= 5*np.random.rand((1))[0] + 5
    y4= 5*np.random.rand((1))[0] + 5

    patch.set_xy([[x1,y1], [x2,y2], [x3,y3], [x4,y4]])

    return patch,

anim = animation.FuncAnimation(fig,animate,init_func=init,frames=36,interval=1000,blit=True)

plt.show()

rawDescription: Using Matplotlib-Patch inside an animation


code:
def choosek():
    os.chdir("./Desktop/Stories/Kid")
    f = str(os.getlogin())
    g = "/Users/"
    h = "/Desktop/Stories/Kid"
    i = g+f+h
    e = os.listdir(i)
    names = [] # the list with the file names
    limit = 22 # maximum entries in the choicebox --> e[1] until e[22]
    for i in xrange(1, len(e)): # starting from 1 because you don't want e[0] in there
        if(i > limit):
            break # so if you have 100 files, it will only list the first 22
        else:
            names.append(e[i])
    choicebox(msg="Please select a story.",title="Please Select a Story",choices=names)

rawDescription: How do I create a list, then len() it, then make an entry for every 'section' in that list in Python?

description: Create a list, then len() it, then make an entry for every 'section' in that list in Python


code:
class Author(models.Model):
    first_name = models.CharField()
    last_name = models.CharField()

    def _get_full_name(self):
       return '{0} {1}'.format(self.first_name, self.last_name)

    full_name = property(_get_full_name)

    class Meta:
       unique_together = ("first_name", "last_name")

rawDescription: Django: Constraint on mutiple model fields


code:
def user():
    if request.args(0) == 'login' and request.post_vars.username:
        request.post_vars.username = request.vars.username = request.post_vars.username.upper() # changes field to all uppercase
    return dict(form=auth())

rawDescription: Web2py - Howto Auto Convert Username field to uppercase


code: glines = (line.strip() for line in lines)

rawDescription: Python: most effcient way to strip line from text file


code:
from collections import deque
import httplib2

def create_data_files(data_url, split_factor=0.7):

    h = httplib2.Http()
    resp_headers, content = h.request(data_url, "GET")
    # for python3
    content = content.decode()

    lines = deque(content.split('\n'))

    stop = len(lines) * split_factor
    training, test = [], []
    i = 0
    while lines:
        l = lines.popleft()
        if i <= stop:
            training.append(l)
        else:
            test.append(l)
        i +=1

    training_str, test_str = '\n'.join(training), '\n'.join(test)
    return training_str, test_str

rawDescription: Reading file from the internet and split into 2


rawDescription: Efficient Vector / Point class in Python


code:
import csv
import sys
import os

with open('some_new_file.csv', 'w') as w, open(sys.argv[1], 'r') as r:
    reader, writer = csv.reader(r), csv.writer(w)
    for row in reader:
        if any(x == '0' for x in (row[2], row[3], row[4])):
            row[9] = 'Label'
        writer.writerow(row)

os.remove('{}'.format(sys.argv[1]))
os.rename('some_new_file.csv', '{}'.format(sys.argv[1]))

rawDescription: CSV Writing to File Difficulties

description: CSV Writing to File Difficulties


code:
urlparts = url.split('/')

if key.startswith('http://'):
    return key
elif key.startswith('/'):
    return '/'.join(urlparts[:2], key[1:])
else:
    urlparts[len(urlparts) - 1] = key
    return '/'.join(urlparts)

rawDescription: Manipulating Directory Paths in Python

description: Manipulating Directory Paths in Python


rawDescription: Identifying References in Python

description: Identifying References in Python


code:
import tempfile
import base64
import os

from PIL import Image

from openerp import models, fields, api
from openerp.exceptions import UserError

class MyModel(models.Model):
    [...]
    image = fields.Binary()

    @api.multi
    def open_image(self):
        self.ensure_one()
        if not self.image:
            raise UserError("no image on this record")
        # decode the base64 encoded data
        data = base64.decodestring(self.image)
        # create a temporary file, and save the image
        fobj = tempfile.NamedTemporaryFile(delete=False)
        fname = fobj.name
        fobj.write(data)
        fobj.close()
        # open the image with PIL
        try:
            image = Image.open(fname)
            # do stuff here
        finally:
            # delete the file when done
            os.unlink(fname)

rawDescription: how to get full path from binary image in odoo

description: Get full path from binary image in odoo


code:
import socket, SOAPpy # SOAPpy is a package
socket.__file__
# .../python2.5/socket.pyc
socket.__path__
# AttributeError: 'module' object has no attribute '__path__'
SOAPpy.__file__
# .../2.5/site-packages/SOAPpy/__init__.pyc
SOAPpy.__path__
# ['.../2.5/site-packages/SOAPpy']

rawDescription: how to get module location

description: Get module location


code:
import itertools
lst = [-4, -2, 1, 2, 5, 0]
[x for x in itertools.product(lst, repeat=3) if sum(x) == 0]

rawDescription: Comprehensions in Python to sample tuples from a list


code:
def payload_to_json(payload, max_size = 256):
    json_string = json.dumps(payload, separators = (',', ':'))
    chars_to_strip = len(json_string) - max_size
    if chars_to_strip <= 0:
        return json_string
    key_count = len(payload)
    chars_per_key, extras = divmod(chars_to_strip, key_count)
    leftover = 0
    for i, key in enumerate(payload):
        to_strip = chars_per_key + (i < extras)
        orig_len = len(payload[key])
        if orig_len < to_strip:
            payload[key] = ''
            leftover += to_strip - orig_len
        else:
            payload[key] = payload[key][:-to_strip]
    if leftover:
        return slow_payload_to_json(payload, max_size)
    else:
        return json.dumps(payload, separators = (',', ':'))

rawDescription: How to truncate data in a dict so that the resulting JSON isn't longer than n bytes?

description: Truncate data in a dict so that the resulting JSON isn't longer than n bytes


code:
import re

text =  'the text stuff <*to test*> to find a way to extract all text'\
        'that is <*included in special tags*> less than star and greater'\
        'than star'

txtsearch = re.findall('<\*(.*?)\*>', text)

if txtsearch:
    print(txtsearch)

# ['to test', 'included in special tags']

rawDescription: Attempting to extract text that is within tags <*word word word*> n times in each line via Python


code:
import random

def generate_data(size):
    mu, sigma = 4 ** 2, 0.16
    return [random.gauss(mu, sigma) for _ in range(size)]

def mean(ls):
    return sum(ls) / len(ls)

print(mean(generate_data(10)))     #15.976644889526114
print(mean(generate_data(100)))    #16.004123848232233
print(mean(generate_data(1000)))   #16.00164187802018
print(mean(generate_data(10000)))  #16.001000022147206

rawDescription: square of a number using gaussian distribution

description: Square of a number using gaussian distribution


code:
converted = map(tuple, points) # Python 2
converted = list(map(tuple, points)) # or BlackBear's answer for Python 3
converted = [tuple(x) for x in points] # another variation of the same

rawDescription: python: elegant and code saving way to convert a list

description: Python: elegant and code saving way to convert a list


rawDescription: Is there a way to encode unicode into a human readable variant of base64 (in python)


code:
parser.add_argument("--input", help='Input file');
parser.add_argument("--output", help='Output file');

rawDescription: Argparse positional arguments with prefix


code:
def displayFractions(n):
    for i in range(1, n+1):
        print('{:.3f}'.format(i/n, i/i), end=', ')

rawDescription: How to print fractions in a function using range and string formatting?

description: Print fractions in a function using range and string formatting


code:
from django.forms.models import inlineformset_factory
GuestOnMeetingInline = inlineformset_factory(GuestOnMeeting, Meeting)
meeting = Meeting.objects.all()[0]
form = MeetingForm(instance=meeting)
formset = GuestOnMeetingInline(instance=meeting)

rawDescription: Django: save many-to-many in a form

description: Django: save many-to-many in a form


code:
'''
Simple and fast image transforms to mimic:
 - brightness
 - contrast
 - erosion
 - dilation
'''

import cv2
from pylab import array, plot, show, axis, arange, figure, uint8

# Image data
image = cv2.imread('imgur.png',0) # load as 1-channel 8bit grayscale
cv2.imshow('image',image)
maxIntensity = 255.0 # depends on dtype of image data
x = arange(maxIntensity)

# Parameters for manipulating image data
phi = 1
theta = 1

# Increase intensity such that
# dark pixels become much brighter,
# bright pixels become slightly bright
newImage0 = (maxIntensity/phi)*(image/(maxIntensity/theta))**0.5
newImage0 = array(newImage0,dtype=uint8)

cv2.imshow('newImage0',newImage0)
cv2.imwrite('newImage0.jpg',newImage0)

y = (maxIntensity/phi)*(x/(maxIntensity/theta))**0.5

# Decrease intensity such that
# dark pixels become much darker,
# bright pixels become slightly dark
newImage1 = (maxIntensity/phi)*(image/(maxIntensity/theta))**2
newImage1 = array(newImage1,dtype=uint8)

cv2.imshow('newImage1',newImage1)

z = (maxIntensity/phi)*(x/(maxIntensity/theta))**2

# Plot the figures
figure()
plot(x,y,'r-') # Increased brightness
plot(x,x,'k:') # Original image
plot(x,z, 'b-') # Decreased brightness
#axis('off')
axis('tight')
show()

# Close figure window and click on other window
# Then press any keyboard key to close all windows
closeWindow = -1
while closeWindow<0:
    closeWindow = cv2.waitKey(1)
cv2.destroyAllWindows()

rawDescription: What's the fastest way to increase color image contrast with OpenCV in python (cv2)?


code:
sum = 0
for k,v in d.iteritems():
    sum += v

rawDescription: How to add up each count in defaultdict?

description: Add up each count in defaultdict


code:
words_b = []
for n in num:
    words_b.append(words[n])
words = words_b

rawDescription: Can you manually sort a list in python?

description: Manually sort a list in python


code:
f = open('path/to/file')
N = int(f.readline().strip())
A = []
while len(A) < N:
    A.extend(int(i) for i in f.readline().strip().split())

rawDescription: input with delimiters in python

description: Input with delimiters in python


code:
def formfield_for_dbfield(self, db_field, **kwargs):
    if db_field.name == 'body':
        kwargs.pop('request', None)
        kwargs['widget'] = TinyMCE(attrs={'cols': 80, 'rows': 30})
        return db_field.formfield(**kwargs)
    return super(EmailTemplateAdmin, self).formfield_for_dbfield(db_field, **kwargs)

rawDescription: ModelTranslation, Django Admin and Widgets


code:
class BaseClass:
    itemList = []
    def addItem(self, thing):
        self.itemList.append(thing)

class Child1(BaseClass):
    itemList = []

class Child2(BaseClass):
    itemList = []

# each class has its own "itemList"
# now we can instantiate each class and use the different itemLists:

c1 = Child1()
c1.addItem("foo")

c2 = Child2()
c2.addItem("bar")

c3 = Child1()
c3.addItem("foo2")

print(str(Child1.itemList)) # prints: ['foo', 'foo2']
print(str(Child2.itemList)) # prints: ['bar']

rawDescription: Writing a Python method to reference the Class attribute in the derived class, rather than base class


code:
def subseq(needle, haystack):
    if not needle: return True
    if len(needle) > len(haystack): return False
    if needle[0] == haystack[0]:
        return subseq(needle[1:], haystack[1:])
    else:
        return subseq(needle, haystack[1:])

rawDescription: A recursive version of a code

description: A recursive version of a code


code:
def main_loop():
    while True:
        data = generate_data()
        if not data:
            break
        for s in sockproc:
             if hasattr(sockproc, "process") and sockproc.process.is_alive():
                  sockproc.process.terminate()
             sockproc.process = Process(target = send_data, args=(sockproc.socket, data))
             sockproc.run()
        sleep(300)

rawDescription: How to send data to multiple client in parallel every five minutes

description: Send data to multiple client in parallel every five minutes


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

class GCSServingHandler(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self):
    read_path = "/path/to/gcs file/"  # The leading chars should not be "/gs/"
    blob_key  = blobstore.create_gs_key("/gs/" + read_path)

    f_name = "file name"
    f_type = "file type" # Such as 'text/plain'

    self.response.headers['Content-Type'] = f_type
    self.response.headers['Content-Disposition'] = "attachment; filename=\"%s\";"%f_name
    self.response.headers['Content-Disposition'] += " filename*=utf-8''" + urllib2.quote(f_name.encode("utf8"))

    self.send_blob(blob_key)

rawDescription: Memory leak in reading files from Google Cloud Storage at Google App Engine (python)


code:
from Tkinter import *
import ttk

root = Tk()
root.title("This space intentionally left blank")
root.minsize(800,200)
mainframe = ttk.Frame(root)
mainframe.grid(column = 0, row = 0)

tokens = [0,1,2,3,4,5,6]
tok_vars = []
for token in tokens:
    var = StringVar()
    var.set(token)
    tok_vars.append(var)

for ii,var in enumerate(tok_vars):
    ttk.Label(mainframe, textvariable=tok_vars[x]).grid(column=ii+1, row=2)

root.mainloop()

rawDescription: Separating list items into columns with single label call


code:
import os

cl_dir = 'dir'

try:
    os.mkdir(cl_dir)
except OSError:
    pass  # os.mkdir will raise an exception if there's the directory. Ignore that.

with open(os.path.join(cl_dir, 'copy_success.txt'), 'w') as f:
    f.write('Copy done')

rawDescription: Write a text file named copy_success.txt with content "Copy done"


code: entries_expanded[:] = [{'id':entry['id'], 'supplier':myfunction(entry['supplier'])} for entry in entries_expanded]

rawDescription: Python: create a list of dictionaries using a list comprehension


code: [w for w in words if sorted(w) == letters]

rawDescription: Python regular expression that will find words made out of specific letters. Letters must be used once only


code:
#create a QDateTimeEdit object
myDTE = QtGui.QDateTimeEdit()

#get current date and time
now = QtCore.QDateTime.currentDateTime()

#set current date and time to the object
myDTE.setDateTime(now)

#set date only
today = QtCore.QDate.currentDate()
myDTE.setDate(today)

#set time only
this_moment = QtCore.QTime.currentTime()
myDTE.setTime(this_moment)

#set an arbitrary date
some_date = QtCore.QDate(2011,4,22) #Year, Month, Day
myDTE.setDate(some_date)

#set an arbitrary time
some_time = QtCore.QTime(16,33,15) #Hours, Minutes, Seconds (Only H and M required)
myDTE.setTime(some_time)

#set an arbitrary date and time
someDT = QtCore.QDateTime(2011,4,22,16,33,15)
myDTE.setDateTime(someDT)

rawDescription: PyQT4 change qDateTimeEdit time value?

description: PyQT4 change qDateTimeEdit time value


code:
from itertools import permutations
l = [1,2,3]
all_permutations = []
for i in range(2, len(l) + 1):
    all_permutations.extend(list(permutations(l, i)))
all_permutations.extend(l)
all_permutations

rawDescription: Finding Permutation of Numbers

description: Finding Permutation of Numbers


code:
df
another_df
df = df.combine_first(another_df)
df

rawDescription: is there a quick way to fill out missing data in pandas dataframe w/o change the whole row?

description: Is there a quick way to fill out missing data in pandas dataframe w/o change the whole row


code:
from tornado import gen, web, httpclient

class StreamingHandler(web.RequestHandler):
    @web.asynchronous
    @gen.coroutine
    def get(self):
        client = httpclient.AsyncHTTPClient()

        self.write('some opening')
        self.flush()

        requests = [
            httpclient.HTTPRequest(
                url='http://httpbin.org/delay/' + str(delay),
                streaming_callback=self.on_chunk
            ) for delay in [5, 4, 3, 2, 1]
        ]

        # `map()` doesn't return a list in Python 3
        yield list(map(client.fetch, requests))

        self.write('some closing')
        self.finish()

    def on_chunk(self, chunk):
        self.write('some chunk')
        self.flush()

rawDescription: Tornado streaming HTTP response as AsyncHTTPClient receives chunks


code:
i, j = zip(*pruneme) # assuming that pruneme is a python list
m[i, j] = 0.
m.eliminate_zeros()

rawDescription: efficiently set a large number of SciPy sparse matrix entries to zero

description: Efficiently set a large number of SciPy sparse matrix entries to zero


code:
class KittenFactory(object):
    def __create_teh_secret_objectz(self):
        class Kitten(object):
            i_can_haz_invisible = True
        return Kitten()

rawDescription: How to restrict users from creating a python object?

description: Restrict users from creating a python object


code:
import numpy as np

h = int(raw_input("Type your first array's range: "))
xy_1 = np.random.randint(0, 1000, (h, 2))
a = xy_1

h = int(raw_input("Type your first array's range: "))
xy_2 = np.random.randint(0, 1000, (h, 2))
b = xy_2
ans = (a[:, 0] - b[:, 0, None]) ** 2 + (a[:, 1] - b[:, 1, None]) ** 2

a_indexes, b_indexes = np.nonzero(ans < 300)

rawDescription: Return index of tuple in array of pairs with python


code:
# Multiplications are computed left-to-right, so the partial
# product never gets too big.
return 1.416e-28 * x**23 * np.exp(-4.545*x) * x**24

rawDescription: using math.log to handle massive numbers

description: Using math.log to handle massive numbers


code:
import System.Drawing
import System.Windows.Forms

from System.Drawing import *
from System.Windows.Forms import *

class MainForm(Form):
  def __init__(self):
    self.InitializeComponent()
    self.pen = System.Drawing.Pen(System.Drawing.Color.Black);

  def InitializeComponent(self):
    self._pictureBox1 = System.Windows.Forms.PictureBox()
    self._pictureBox1.BeginInit()
    self.SuspendLayout()
    #
    # pictureBox1
    #
    self._pictureBox1.Location = System.Drawing.Point(13, 13)
    self._pictureBox1.Name = "pictureBox1"
    self._pictureBox1.Size = System.Drawing.Size(259, 237)
    self._pictureBox1.TabIndex = 0
    self._pictureBox1.TabStop = False
    self._pictureBox1.Click += self.PictureBox1Click
    #
    # MainForm
    #
    self.ClientSize = System.Drawing.Size(284, 262)
    self.Controls.Add(self._pictureBox1)
    self.Name = "MainForm"
    self.Text = "PyWinForm"
    self._pictureBox1.EndInit()
    self.ResumeLayout(False)

  def PictureBox1Click(self, sender, e):
    g = self._pictureBox1.CreateGraphics()
    g.DrawLine(self.pen, 10, 10, 400, 200)

rawDescription: How to draw lines in IronPython with Winforms?

description: Draw lines in IronPython with Winforms


code:
l = ['export_p-01.xml', ...]
sorted(l, key = lambda x: int(x.split(".")[0].split("-")[-1]))

rawDescription: custom order of a python list

description: Custom order of a python list


code:
help_data.repartition(5).saveAsTextFile(
    path="s3://help-test/logs/help",
    compressionCodecClass="org.apache.hadoop.io.compress.GzipCodec"
)

rawDescription: How to save a spark RDD in gzip format through pyspark

description: Save a spark RDD in gzip format through pyspark


code:
import tkinter as tk

root = tk.Tk()

scalevar = tk.IntVar()
scalevar.set(50)

scale = tk.Scale(root, from_=0, to=100,
                 variable=scalevar, orient="horizontal")
label = tk.Label(root, textvariable=scalevar)

scale.pack(side="top", fill="x", expand=True)
label.pack(side="top", fill="x", expand=True)

root.mainloop()

rawDescription: Scale value in label

description: Scale value in label


code:
from scipy.optimize import curve_fit
import numpy
import matplotlib.pyplot as plt

xdata=[100.0, 0.0, 90.0, 20.0, 80.0] #is my list with y values, which contains 0 values - edit, you need some raw data which you fit, I inserted some
ydata=[0.001, 1.0, 0.02, 0.56, 0.03] #is my list with x values

transf_y=[]
for i in range(len(ydata)):
    transf_y.append(ydata[i]+0.00001) #Adding something to avoid zero values

x1=numpy.array(xdata,dtype=float)
y1=numpy.array(transf_y,dtype=float)

def func(x, a, c, d):
    return a * numpy.exp(-c*x)+d

popt, pcov = curve_fit(func, x1, y1,p0 = (1, 1e-6, 1))

print ("a = %s , c = %s, d = %s" % (popt[0], popt[1], popt[2]))

#ok, sorting your data
pairs = []
for i, j in zip(x1, y1):
    pairs.append([i,j])

sortedList = sorted(pairs, key = lambda x:x[0])
sorted_x = numpy.array(sortedList)[:,0]
sorted_y = numpy.array(sortedList)[:,1]

#adjusting interval to the limits of your raw data
xx = numpy.linspace(0, 100.0, 1000)
yy = func(xx, *popt)

#and  everything looks fine
plt.plot(sorted_x,sorted_y, 'o',label='Original Data')
plt.plot(xx,yy,label='Fitted Data')

plt.legend(loc='upper left')
plt.show()

rawDescription: Wrong graph with scipy.optimize.curve_fit (similar to moving average)


rawDescription: Choosing axis in numpy array using select method


type: string

match_mapping_type: string

rawDescription: Creating analyzed and not_analyzed index on all fields in Elasticsearch


code:
COLORS = ["red", "blue", "black", "yellow", "green"]
NUMBERS = ['0', '1', '2', '3', '4']
PANELS = ["Things", "More things", "Ultra!"]

import random
import wx

class TabPanel(wx.Panel):
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)
        self.SetBackgroundColour(random.choice(COLORS))
        self.listBox = wx.ListBox(self, size=(200, -1), choices=NUMBERS, style=wx.LB_SINGLE)
#        self.button = wx.Button(self, label="Something else here? Maybe!")

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.listBox, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
#        self.sizer.Add(self.button, proportion=1, flag=wx.ALL)

        self.SetSizer(self.sizer)

class MyNotebook(wx.Notebook):
    def __init__(self, *args, **kwargs):
        wx.Notebook.__init__(self, *args, **kwargs)

        self.panels = []
        for name in PANELS:
            panel = TabPanel(self)
            self.panels.append(panel)
            self.AddPage(panel, name)

class MyPanel(wx.Panel):
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)

        self.notebook = MyNotebook(self, size=(400, -1))
#        self.button = wx.Button(self, label="Something else here? Maybe!")

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.notebook, proportion=0, flag=wx.EXPAND)
#        self.sizer.Add(self.button, proportion=0)
        self.SetSizer(self.sizer)

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.panel = MyPanel(self)

        self.status = self.CreateStatusBar()

        self.menubar = wx.MenuBar()
        first=wx.Menu()
        second=wx.Menu()
        first.Append(wx.NewId(), "New", "Creates A new file")
        first.Append(wx.NewId(), "ADID", "Yo")
        self.menubar.Append(first, "File")
        self.menubar.Append(second, "Edit")
        self.SetMenuBar(self.menubar)

        self.Show()

app = wx.App(False)
win = MainWindow(None, size=(600, 400))
app.MainLoop()

rawDescription: wxpython: How to set width and height of a wxnotebook?

description: Wxpython: How to set width and height of a wxnotebook


rawDescription: Python Pandas Group by Column A and Sum Contents of Column B


code:
import numpy as np
def plot_file(ax, fnme, cols=[], label=None):
    data = np.genfromtxt(
      fnme,
      skip_header=0,
      skip_footer=0,
      names=[str(col) for col in cols],
    )
    ax.plot(*[data[str(col)] for col in cols], label=label)

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 3))
PLOT_INDEXES = range(0,2)
for i in PLOT_INDEXES:
    ax = plt.subplot(1, len(PLOT_INDEXES), i+1)
    plot_file(ax, 'test_{0}.txt'.format(i), cols=[0, 1], label=str(i))
plt.show()

rawDescription: Strange behaviour of Subplot in Matplotlib when used by plotfile


code:
with open('connections.cfg') as fp:
    config = ConfigParser()
    config.readfp(fp)
    sections = config.sections()

rawDescription: Closing file opened by ConfigParser

description: Closing file opened by ConfigParser


rawDescription: NLTK chunked parse tree, save it into a file and loading it with CorpusReader class


code:
import numpy as np
share_prices  = np.array([100,102,104,106,104, 109, 110])
median_price = np.median(share_prices)
104.0
average_price = np.average(share_prices)
105.0
min_price = np.min(share_prices)
100
max_price = np.max(share_prices)
110

rawDescription: How to convert numpy time series stock data with day resolution to month or week resolution

description: Convert numpy time series stock data with day resolution to month or week resolution


code:
import os
import shutil

def maven_to_eclipse(maven_dir, eclipse_dir):
    # assumes mode of maven_dir will be the same as eclipse_dir
    new_mode = os.stat(maven_dir).st_mode
    if os.path.exists(eclipse_dir):
        # if new_dir doesn't exist
        # create it with same permissions as old_dir
        os.mkdirs(eclipse_dir, new_mode)

    # create directories under new_dir: src, ebscontent, ebscontent/META-INF
    # use os.path.join to work on multiple os
    os.mkdir(os.path.join(eclipse_dir, 'src'), new_mode)
    os.mkdir(os.path.join(eclipse_dir, 'ebscontent'), new_mode)
    os.mkdir(os.path.join(eclipse_dir, 'ebscontent', 'META-INF'), new_mode)

    # cp old/deployment.xml new/ebsconent/META-INF/deployment.xml
    shutil.copy2(os.path.join(maven_dir, 'deployment.xml'),
        os.path.join(eclipse_dir, 'ebscontent', 'META-INF', 'deployment.xml'))

    # cp old/jboss-esb-unfiltered.xml new/ebsconent/META-INF/jboss-esb-unfiltered.xml
    shutil.copy2(os.path.join(maven_dir, 'jboss-esb-unfiltered.xml'),
        os.path.join(eclipse_dir, 'ebscontent', 'META-INF', 'jboss-esb-unfiltered.xml'))

    # cp old/log4j.xml new/ebsconent/log4j.xml
    shutil.copy2(os.path.join(maven_dir, 'log4j.xml'),
        os.path.join(eclipse_dir, 'ebscontent', 'log4j.xml'))

    # cp old/readme.txt new/readme.txt
    shutil.copy2(os.path.join(maven_dir, 'readme.txt'),
        os.path.join(eclipse_dir, 'readme.txt'))

if __name__ == '__main__':
    base_path = 'C:\\Path\\To\\Maven Dirs'
    maven_dirs = ('my_example', 'another_example', 'third_example')
    for maven_dir in maven_dirs:
        maven_to_eclipse(os.path.join(base_path, maven_dir),
            os.path.join(base_bath, maven_dir + '_eclipse'))

rawDescription: How can I convert a batch of Mavenized examples into a format that Eclipse understands?

description: Convert a batch of Mavenized examples into a format that Eclipse understands


code:
from matplotlib import pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Create X, Y and Z arrays
x = range(0,250)
y = range(0,250)
X, Y = np.meshgrid(x, y)
Z = np.zeros((250,250))
# Locations of the spikes. These are some made up numbers.
dataX = np.array([25,80,90,145,180])
dataY = np.array([170,32,130,10,88])
# Set spikes to 100
Z[dataX,dataY] = 100
# Plot
fig = plt.figure()
ax = fig.add_subplot(1,1,1, projection='3d')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.plot_surface(X, Y, Z)
plt.show()

rawDescription: How to convert scatter plot into a surface plot?

description: Convert scatter plot into a surface plot


code:
with open(wholefName) as fh:
    json.dumps(fh.read().splitlines())

rawDescription: Python iterate to remove newlines takes too long. Can my code be optimized better?


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

fig = plt.figure()
ax = fig.add_subplot(111)
axp = ax.imshow(np.random.randint(0, 100, (100, 100)))
# Adding the colorbar
cbaxes = fig.add_axes([0.1, 0.1, 0.03, 0.8])  # This is the position for the colorbar
cb = plt.colorbar(axp, cax = cbaxes)
plt.show()

rawDescription: Can I place a vertical colorbar to the left of the plot in matplotlib?

description: Place a vertical colorbar to the left of the plot in matplotlib


code: Thread.objects.raw('SELECT ... FROM myapp_thread WHERE ...')

rawDescription: Django Models Create a Coustom Query

description: Django Models Create a Coustom Query


code:
class Base(object):
    def __init__(self, collection=None, classname=None):
        self.__collection__ = collection or self.__class__.__name__

class Thing(Base):
    def __init__(self, **kwargs):
        #super(Thing, self).__init__()
        Base.__init__(self, **kwargs)
        #self.__dict__.update(kwargs)

t = Thing(collection='foobar')
print(t.__collection__)

rawDescription: Inheriting Python Class args from Super

description: Inheriting Python Class args from Super


code:
import random
x = random.randint(2, 10)
y = random.randint(2, 10)
answer = int(input("How much is {} * {}?".format(x, y)))

rawDescription: Python 3.4.1 - putting variables into input


rawDescription: Sorted function using compare function

description: Sorted function using compare function


code:
def magicify(list, letter):
    return list[list.index(letter):]+list[:list.index(letter)]

rawDescription: Shift list from given term

description: Shift list from given term


code:
from django.core.validators import RegexValidator
from django.db import models

class MyModel(models.Model):
    # Notice the ? in the regex.
    factory_id = models.CharField(max_length=10,
                                  validators=[
                                      RegexValidator(r'^[0-9]{4}-?[0-9]{5}$')
                                  ])

    def save(self, *args, **kwargs):
        """ This step is just formatting: add the dash if missing """
        if '-' not in self.factory_id:
            self.factory_id = '{0}-{1}'.format(
                 self.factory_id[:4], self.factory_id[4:])

        # Continue the model saving
        super(MyModel, self).save(*args, **kwargs)

rawDescription: Custom Model Field for formatting char field data


code:
class PostDetailView(BlogMixin,CreateView):
    """ A view for displaying a single post """
    template_name = 'post.html'
    model = Comment
    fields = ['body','author_name']
    def get_context_data(self, **kwargs):

        context = super(PostDetailView, self).get_context_data(**kwargs)
        context['post'] =  Post.objects.get(pk=self.kwargs['pk'])
        return context

    def form_valid(self, form):
        # self.object = form.save()
        obj = form.save(commit=False)
        obj.parent_post = Post.objects.get(pk=self.kwargs['pk'])
        obj.save()

        return redirect('post-detail', self.kwargs['pk'])

rawDescription: Django ModelForm within DetailView

description: Django ModelForm within DetailView


code:
from bs4 import BeautifulSoup
import sys

# version compatibility shim
if sys.hexversion < 0x3000000:
    # Python 2.x
    from urlparse import urljoin
    from urllib import urlopen
else:
    # Python 3.x
    from urllib.parse import urljoin
    from urllib.request import urlopen

START_URL = "https://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Desmond.html"
STEPS = 7
ITEM = 18

def get_soup(url):
    with urlopen(url) as page:
        return BeautifulSoup(page.read(), 'lxml')

def main():
    url = START_URL
    for step in range(STEPS):
        print("\nStep {}: looking at '{}'".format(step, url))
        # get the right item (Python arrays start indexing at 0)
        links = get_soup(url).find_all("a")
        rel_url = links[ITEM - 1]["href"]
        # convert from relative to absolute url
        url = urljoin(url, rel_url)
        print("  go to '{}'".format(url))

if __name__=="__main__":
    main()

rawDescription: Stuck on this task

description: Stuck on this task


code:
def editstr(s):
    n = s.count(' ')
    if n == 0: return s
    return s[:-2*n/3].replace(' ', '%20')

rawDescription: cracking code interview 1.4

description: Cracking code interview 1.4


code:
import operator

hosts = ['a1.xxx.com', 'a2.xxx.com', 'a90.xxx.com', 'a100.xxx.com']

def filter_hosts(hosts, number, op=operator.gt):
    return [host for host in hosts
            if op(int(host.split('.', 1)[0][1:]), number)]

print(filter_hosts(hosts, 10))
print(filter_hosts(hosts, 10, op=operator.lt))

rawDescription: lambda function and filtering in python

description: Lambda function and filtering in python


code:
for y in range(years):
    y += 1
    for m in range(month):
        rain = float(input('How many inch of rainfall have fallen: '))
        total_rain += rain
    print("In the year", y,"There will be:", total_rain," inches of rain")
    #reset variable
    total_rain = 0

rawDescription: Nested loop for python

description: Nested loop for python


code:
results = Path.objects.all()
for s in search.split():
    results = results.filter(path__icontains = s)

rawDescription: Django db search keywords, not exact text


code:
from socketIO_client import SocketIO

class SocketIOClient(SocketIO):
    """
    Fix for library bug
    """

    def _should_stop_waiting(self, for_connect=False, for_callbacks=False):
        if for_connect:
            for namespace in self._namespace_by_path.values():
                is_namespace_connected = getattr(
                    namespace, '_connected', False)
                #Added the check and namespace.path
                #because for the root namespaces, which is an empty string
                #the attribute _connected is never set
                #so this was hanging when trying to connect to namespaces
                # this skips the check for root namespace, which is implicitly connected
                if not is_namespace_connected and namespace.path:
                    return False
            return True
        if for_callbacks and not self._has_ack_callback:
            return True
        return super(SocketIO, self)._should_stop_waiting()

rawDescription: Python and Socket.IO - App hangs after connection


code:
io_loop = IOLoop()
io_loop.make_current()

rawDescription: Tornado Ioloop in thread

description: Tornado Ioloop in thread


code:
import sys
import os
import time

def clock():
    Minutes = 0
    Hours = 1
    ampm = "AM"

    while True:
        Minutes += 1

        if Minutes == 60:
            Minutes = 0
            Hours += 1

        if Hours == 12:
            Hours = 1
            Minutes = 0
            ampm = ("AM" if (ampm == "PM") else "PM")

        ReadLine = ("\t{0:>2} : {1:>2} {2} \r").format(Hours, Minutes,ampm)
        sys.stdout.write(ReadLine)
        sys.stdout.flush()
        time.sleep(60)
clock()

rawDescription: So I want to make a clock in Python that displays both A.M. and P.M


code:
#login
session['user'] = user_id

@app.before_request
def before_request():
    current_user = user_obj
    g.user = current_user

rawDescription: Global variables in python flask web application


code:
# nodeID
nodeID2
nodeID3
# nodeID2
nodeID4
nodeID5
nodeID
# isolatedNode
# nodeID5

rawDescription: Read Disconected Graph in igraph for python


code: zf.write(os.path.join(root, filename), filename, zipfile.ZIP_DEFLATED)

rawDescription: How can I add only a file to zip and not the folder path leading to it in Python?

description: Add only a file to zip and not the folder path leading to it in Python


rawDescription: Access django dict through shell after aggregate annotate


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

import random

class Rectangle:
    def __init__ (self, width, height, parent = None):
        self.width = width
        self.height = height
        self.parent = parent
        self.children = []

    @property
    def level (self):
        return 0 if not self.parent else 1 + self.parent.level

    def split (self):
        if self.children: raise Exception ('Already split')
        ratio = random.random () * .5 + .25 #split between 1/4 and 3/4
        if self.width > self.height:
            width = int (ratio * self.width)
            self.children = [Rectangle (width, self.height, self),
                Rectangle (self.width - width, self.height, self) ]
        else:
            height = int (ratio * self.height)
            self.children = [Rectangle (self.width, height, self),
                Rectangle (self.width, self.height - height, self) ]

    def splitUntilLevel (self, maxLevel):
        if maxLevel <= self.level: return
        self.split ()
        for child in self.children: child.splitUntilLevel (maxLevel)

    def __str__ (self):
        s = '{}{} x {}\n'.format (' ' * (2 * self.level), self.width, self.height)
        for child in self.children: s += str (child)
        return s

r = Rectangle (100, 100)
r.splitUntilLevel (3)
print (r)

rawDescription: Tree in python: recursive children creating


code:
fig = plt.figure()

for a,b,c in zip(zmin,zmax,plot_no):
    ra = alpha[(data_m200>mlim)*(data_z>a)*(data_z<b)] # RA FOR ZCOSMO
    dec = delta[(data_m200>mlim)*(data_z>a)*(data_z<b)] # DEC FOR ZCOSMO
    ra_zphot = alpha[(data_m200>mlim)*(zphot>a)*(zphot<b)] # RA FOR ZPHOT
    dec_zphot = delta[(data_m200>mlim)*(zphot>a)*(zphot<b)] # DEC FOR ZPHOT

    ax = fig.add_subplot(2,5,c)
    ax.scatter(ra,dec,color='red',s=5.0,label=''+str(a)+'<zcosmo<'+str(b)+'')
    ax.scatter(ra_zphot,dec_zphot,color='blue',s=5.0,label=''+str(a)+'<zphot<'+str(b)+'')
    ax.legend(loc='best',scatterpoints=2)

fig.show()

rawDescription: Matplotlib subplots inside a for loop

description: Matplotlib subplots inside a for loop


rawDescription: Creating pandas Dataframe and renaming change 0.10.0 to 0.13.1


code: count = len(set(d["code"] for d in li))

rawDescription: How do I most efficienty check the unique elements in a list?

description: Most efficienty check the unique elements in a list


code:
# script.py

conn = mysql.connector.connect(
        user = "myuser",
        password = "SuperSecretPassword",
        host = "127.0.0.1",
        database = "MyDatabase")

def MyFunc(x, y):

    # Process some data here, then write it to the DB

    cursor = conn.cursor()
    cursor.execute("INSERT INTO table a, b, c VALUES(1,2,3)")
    conn.commit()

    MyFunc(x, y)

rawDescription: Best practice for database connection in recursive function?


code:
rectangle2 = rectangle.copy()
random.shuffle(rectangle2)

rawDescription: Python: shuffle and create a new array

description: Python: shuffle and create a new array


code:
from decimal import Decimal
a = [(Decimal("0.99"), ), (Decimal("0.0"), ), (Decimal("113.84"), )]
sum(i[0] for i in a) #Because they're in a tuple

rawDescription: Python String Formatting

description: Python String Formatting


rawDescription: List B append in list A - but when B removed A also empty


code: [x.text for x in bk.xpath("//book/*")]

rawDescription: How to make XPath return 'None' in Python if no data found?

description: Make XPath return 'None' in Python if no data found


code:
op = type("MyOptionParser", (OptionParser,object), {"foo": lambda self: "foo" })
op().foo()

rawDescription: Does Python have something like anonymous inner classes of Java?


code:
from sqlalchemy import types
from dateutil.tz import tzutc
from datetime import datetime

class UTCDateTime(types.TypeDecorator):

    impl = types.DateTime

    def process_bind_param(self, value, engine):
        if value is not None:
            return value.astimezone(tzutc())

    def process_result_value(self, value, engine):
        if value is not None:
            return datetime(value.year, value.month, value.day,
                            value.hour, value.minute, value.second,
                            value.microsecond, tzinfo=tzutc())

rawDescription: Can SQLAlchemy DateTime Objects Only Be Naive?


code: d.replace(r':.*', '', regex=True)

rawDescription: split several columns using pandas

description: Split several columns using pandas


code:
from Tkinter import *

def blink():
    e.config(bg='green')
    e.after(1000, lambda: e.config(bg='white')) # after 1000ms

root = Tk()
e = Entry(root)
e.pack()
b = Button(root, text='blink', command=blink)
b.pack()
root.mainloop()

rawDescription: Time delay Tkinter

description: Time delay Tkinter


code:
def footToMeter(foot):
    return foot * .305

print("Feet \t Meters")
for foot in range(1,11):
    print(foot, "\t", footToMeter(foot))

rawDescription: Printing two def function side by side Python 3


code:
import pandas as pd
df = pd.read_csv('df.csv',index_col=0)
df_combined = df.groupby(['yyyymmdd','hr']).max()
df_combined

rawDescription: Combine similar rows to one row in python dataframe


code:
import wx
import wx.lib.mixins.listctrl as listmix

class FillBD2Frame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "FillBD2", size=(400, 300))
        self.Centre()
        FillBD2(self)

class MyListCtrl(wx.ListCtrl):
    def __init__(self, parent, ID=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0):
        wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
        self.parent=parent
        self.DataMap={}

class FillPanel(wx.Panel, listmix.ColumnSorterMixin):

    def __init__(self, parent, DataMap, ctrl_type=1):
        wx.Panel.__init__(self, parent, wx.ID_ANY, style=wx.WANTS_CHARS)
        self.parent = parent

        self.list_ctrl = MyListCtrl(self,
                                    style=wx.LC_REPORT|wx.BORDER_SUNKEN|wx.LC_SORT_ASCENDING)

        gr=2
        self.list_ctrl.InsertColumn(0, 'path',                              width=30*gr)
        self.list_ctrl.InsertColumn(1, 'name',                              width=30*gr)

        if ctrl_type == 1:
            self.list_ctrl.InsertColumn(2, 'size(real)',  wx.LIST_FORMAT_RIGHT, width=15*gr)
            self.list_ctrl.InsertColumn(3, 'size(dest)',  wx.LIST_FORMAT_RIGHT, width=15*gr)
        elif ctrl_type == 2:
            self.list_ctrl.InsertColumn(2, 'size(dest)',  wx.LIST_FORMAT_RIGHT, width=15*gr)

        listmix.ColumnSorterMixin.__init__(self, 4)

        self.list_ctrl.DataMap = DataMap
        self.fillListCtrl(ctrl_type)
        self.list_ctrl.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.list_ctrl, 1, wx.EXPAND)
        self.SetSizer(sizer)

    def fillListCtrl(self, ctrl_nr=1):
        self.list_ctrl.DeleteAllItems()
        self.list_ctrl.Refresh()
        index=0
        for key, data in self.list_ctrl.DataMap.items():
            self.list_ctrl.InsertStringItem(index, data[0])
            self.list_ctrl.SetStringItem(index, 1, data[1])
            self.list_ctrl.SetStringItem(index, 2, str(data[2]))
            if ctrl_nr==1:
                self.list_ctrl.SetStringItem(index, 3, str(data[3]))

            self.list_ctrl.SetItemData(index, key)
            index+=1
        self.list_ctrl.SetItemState(0, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)

    def GetListCtrl(self):
        return(self.list_ctrl)

    def OnColClick(self, event):
        self.itemDataMap = self.list_ctrl.DataMap
        event.Skip()

class FillBD2(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, wx.ID_ANY, style=wx.WANTS_CHARS)
        self.parent=parent

        DataMap_1={
            0:("pth1", "nam1", 62, 70),
            1:("pth2", "nam2", 22, 30),
            2:("pth3", "nam3", 57, 60),
            4:("pth4", "nam4",  9, 10)
        }

        DataMap_2={
            0:("pth5", "nam5", 45, 50),
            1:("pth6", "nam6", 81, 90),
            2:("pth7", "nam7", 33, 40),
            4:("pth8", "nam8", 13, 20)
        }

        self.testen=  wx.Button(self, -1, "&test",  (-1, -1), wx.DefaultSize)

        list_panel = FillPanel(self, DataMap_1)
        list_panel_2 = FillPanel(self, DataMap_2, ctrl_type=2)

        # create sizers
        vsizer = wx.BoxSizer(wx.VERTICAL)
        hsizer = wx.BoxSizer(wx.HORIZONTAL)

        vsizer.Add(self.testen, 0, wx.ALL, 5)
        hsizer.Add(list_panel, 1, wx.ALL|wx.EXPAND, 5)
        hsizer.Add(list_panel_2, 1, wx.ALL|wx.EXPAND, 5)
        vsizer.Add(hsizer, 1, wx.EXPAND)
        self.SetSizer(vsizer)

if __name__=='__main__':
    app = wx.App()
    frame = FillBD2Frame().Show()
    app.MainLoop()

rawDescription: is it possible, to have two sortable ListCtrls in one window?

description: Is it possible, to have two sortable ListCtrls in one window


code:
class ParentEvents(models.Model):
    name=models.CharField(max_length=70)

    def __unicode__(self):
        return u"%s" % self.name

rawDescription: How to Display the attribute value and not the ParentEvent Object in the Foreign key dropdown?


code:
import csv
with open('headers.csv', 'rb') as csvfile:
   header_reader = csv.reader(csvfile)
   headers = header_reader[0]
#You now have the headers from the first line of the CSV
#Extract the headers you want to repeat
repeat_headers = headers[1:5]  #contains [External,Internal,Total,Result]

#Build new list
new_headers = [headers[0]] + repeat_headers   #Your first element is at position 0
for i in xrange(5, len(headers)):             #Your remaining elements start at position 5
   new_headers.append(headers[i])
   new_headers += repeat_headers

rawDescription: Copying the column index of csv file

description: Copying the column index of csv file


code: A = [[] for _ in range(10)]

description: Python a=[[],]*10


code:
import pprint
import urllib.request
u = urllib.request.urlopen('http://www.python.org')
pprint.pprint(dict(u.getheaders()))

rawDescription: Grabbing headers from webpage with python


code:
myPixmap = QtGui.QPixmap(_fromUtf8('image.jpg'))
myScaledPixmap = myPixmap.scaled(self.label.size(), Qt.KeepAspectRatio)
self.label.setPixmap(myScaledPixmap)

rawDescription: PyQt:How do I display a image properly?

description: PyQt:How do I display a image properly


code:
def matrix_factorization(R, P, Q, K, steps=5000, alpha=0.0002, beta=0.02):
    for step in xrange(steps):
        for i in R.keys():
            for j in R[i].keys():
                eij = R[i][j] - sum([P[i][k] * Q[j][k] for k in xrange(K)])
                for k in xrange(K):
                    P_temp = P[i][k]
                    Q_temp = Q[j][k]

                    P[i][k] = P_temp + alpha * (2 * eij * Q_temp - beta * P_temp)
                    Q[j][k] = Q_temp + alpha * (2 * eij * P_temp - beta * Q_temp)

        e = 0
        for i in R.keys():
            for j in R[i].keys():
                e += pow(R[i][j] - sum([P[i][k] * Q[j][k] for k in xrange(K)]), 2)
                for k in xrange(K):
                    e += (beta/2) * (pow(P[i][k], 2) + pow(Q[j][k], 2))
        if e < 0.001:
            break
    return P,Q

rawDescription: Using dictionary for matrix factorization and "nan" came up in dictionary.values()


code:
In [13]: "+".join(random.sample(sentences,3))
Out[13]: 'a+b+c'

rawDescription: Python: Non repeating random values from list


code:
from xlwings import Workbook, Range
import pandas as pd
wb = Workbook()  # Pass in the path of a file to work with an existing Workbook
df = pd.DataFrame([[1., 2.], [3., 4.]], columns=['one', 'two'])
Range('A1', index=False).value = df # send it over to Excel
data = Range('A1').table.value  # read it back
pd.DataFrame(data[1:], columns=data[0])

rawDescription: Importing arrays from Excel to Python Pandas using Pyxll


code:
class PostAdmin(admin.ModelAdmin):
    list_display=['get_tags']

    def get_tags(self, post):
        tags = []
        for tag in post.tags.all():
            tags.append(str(tag))
        return ', '.join(tags)

rawDescription: Make Django-taggit show the value of the tags in admin


code:
def __str__(self):
    local_data = self.__dict__.copy()

    local_data['status'] = "[POISONED]" if self.poisoned else ""

    local_data['weapon'] = " " if not self.weapon else ','.join(self.weapon)

    return ('NAME: {name} {status}\n' \
            'XP:   {xp}\n' \
            'HP:   {hit_points}\n' \
            'SP:   {spell_points}\n' \
            'STR:  {strength}\n' \
            'DEX:  {dexterity}\n' \
            'WEAPON: {weapon}\n' \
            'SPELL:  {spell}\n' \
            'ITEM:   {item}\n' \
            'AURA:   {aura}\n' \
            ).format(**local_data)

rawDescription: Printing individual list objects within __str__ using .format(**self.__dict__)


rawDescription: Pandas Split on '. '

description: Pandas Split on '. '


code:
import tkinter as tk
import os
import tkinter.filedialog
import tkinter.messagebox

class Main(tk.Tk):

    def __init__(self, *args, **kwargs):
        '''This initialisation runs the whole program'''
        #textBoxList = []

        tk.Tk.__init__(self, *args, **kwargs)
        self.title('Untitled')
        self.geometry('500x500')
        self.canvas = tk.Canvas(self)
        self.scroll = tk.Scrollbar(self, orient='vertical', command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.scroll.set)
        self.frame = tk.Frame(self.canvas) # frame does not get pack() as it needs to be embedded into canvas throught canvas.
        self.scroll.pack(side='right', fill='y')
        self.canvas.pack(fill='both', expand='yes')
        self.canvas.create_window((0,0), window=self.frame, anchor='nw')
        self.frame.bind('<Configure>', lambda x: self.canvas.configure(scrollregion=self.canvas.bbox('all'))) # lambda function

        # 1st Text Widget
        self.journal = tk.Text(self.frame)
        self.vsb = tk.Scrollbar(self.frame)
        self.vsb.config(command=self.journal.yview)
        self.journal.config(yscrollcommand=self.vsb.set)
        self.journal.grid(row=0, column=0) # grid instead
        self.vsb.grid(row=0, column=1, sticky='ns') # grid instead

        #2nd Text Widget
        self.good = tk.Text(self.frame)
        self.vsb2 = tk.Scrollbar(self.frame)
        self.vsb2.config(command=self.good.yview)
        self.good.config(yscrollcommand=self.vsb2.set)
        self.good.grid(row=1, column=0) # grid instead
        self.vsb2.grid(row=1, column=1, sticky='ns') # grid instead

root = Main()
root.mainloop()

rawDescription: How to have multiple text widgets with scrollbars in a frame on tkinter

description: Have multiple text widgets with scrollbars in a frame on tkinter


code:
fig = sm.qqplot(test, line='45');

# Grab the lines with blue dots
dots = fig.findobj(lambda x: hasattr(x, 'get_color') and x.get_color() == 'b')

[d.set_alpha(0.3) for d in dots]

rawDescription: How to change plot properties of statsmodels qqplot? (Python)

description: Change plot properties of statsmodels qqplot? (Python)


rawDescription: Convert standard format date string to datetime object


code:
class TwoWay:
    def __init__(self):
       self.d = {}
    def add(self, k, v):
       self.d[k] = v
       self.d[v] = k
    def remove(self, k):
       self.d.pop(self.d.pop(k))
    def get(self, k):
       return self.d[k]

rawDescription: A data-structure for 1:1 mappings in python?


code:
while True:
    if select.select([sys.stdin], [], [], 10)[0]:
        ...

rawDescription: Check for user Input on stdin during whole execution time


code:
baz.mro()
[cls.__name__ for cls in baz.mro()]
' > '.join([cls.__name__ for cls in baz.mro()])

rawDescription: Print class stack in python

description: Print class stack in python


code:
defaults = {'rating': 5}
Rating.objects.update_or_create(restaurant_id=1, user_id=1, defaults=defaults)

rawDescription: How do I edit an object if it exist or create an object that doesn't exist in Django?

description: Edit an object if it exist or create an object that doesn't exist in Django


code:
from spiders.spider_one import SpiderOne
from spiders.spider_two import SpiderTwo

# scrapy api
from scrapy import signals, log
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy.settings import Settings

file = "your_file.json" #your results
TO_CRAWL = [SpiderOne,SpiderTwo]

# list of crawlers that are running
RUNNING_CRAWLERS = []

def spider_closing(spider):
    """Activates on spider closed signal"""
    log.msg("Spider closed: %s" % spider, level=log.INFO)
    RUNNING_CRAWLERS.remove(spider)
    if not RUNNING_CRAWLERS:
        reactor.stop()

log.start(loglevel=log.DEBUG)
for spider in TO_CRAWL:
    settings = Settings()
    settings.set("USER_AGENT", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36")
    settings.set("FEED_FORMAT",'json')
    settings.set("FEED_URI",file)
    # settings.set("ITEM_PIPELINES",{ 'pipelines.CustomPipeline': 300})
    settings.set("DOWNLOAD_DELAY",1)
    crawler = Crawler(settings)
    crawler_obj = spider()
    RUNNING_CRAWLERS.append(crawler_obj)

    # stop reactor when spider closes
    crawler.signals.connect(spider_closing, signal=signals.spider_closed)
    crawler.configure()
    crawler.crawl(crawler_obj)
    crawler.start()

# blocks process so always keep as the last statement
reactor.run()

rawDescription: How can I put all the results of 2 spiders in one XML with scrapy?

description: Put all the results of 2 spiders in one XML with scrapy


code:
import copy

def MAXJ(lista):
    static = lista
    output = copy.deepcopy(lista)
    for i in range(len(lista)):
        for j in range(len(lista[i])):
            if(i != 0):
                output[i][j] = output[i][j] + lista[i-1][j]
                if(j != 0):
                    output[i][j] = output[i][j] + lista[i-1][j-1]
                if(j != len(lista[i]) - 1):
                    output[i][j] = output[i][j] + lista[i-1][j+1]
            if(i != len(lista) - 1):
                output[i][j] = output[i][j] + lista[i+1][j]
                if(j != 0):
                    output[i][j] = output[i][j] + lista[i+1][j-1]
                if(j != len(lista[i]) - 1):
                    output[i][j] = output[i][j] + lista[i+1][j+1]
            if(j != 0):
                output[i][j] = output[i][j] + lista[i][j-1]
            if(j != len(lista[i]) - 1):
                output[i][j] = output[i][j] + lista[i][j+1]
            print("List:", lista, "\n","OutPut:", output, sep = '')
MAXJ([[1, 2, 3, 2],[0, 0, 1, 2]])

rawDescription: Strange list assignment

description: Strange list assignment


code:
from shutil import copyfileobj

with open('bigInputfile.txt', 'rb') as input:
    with bz2.BZ2File('bigInputfile.txt.bz2', 'wb', compresslevel=9) as output:
        copyfileobj(input, output)

rawDescription: Big file compression with python

description: Big file compression with python


code:
# create dict from first csv, with url as key
with open("first.csv", "r") as f:
    first = {rows[0]: rows[1:] for rows in list(csv.reader(f))}

# compare second csv and append rank
with open("second.csv", "r") as f:
    for row in csv.reader(f):
        if row[0] in first: # row[0] = url
            first[row[0]].append(row[1]) # row[1] = rank

# convert dict back to list
merged = [(k,) + tuple(v) for k, v in first.items()]

# write list to output csv
with open("output.csv", "w") as f:
    csv.writer(f).writerows(merged)

rawDescription: Match two columns in CSV; copy value from one CSV to other if equal


code:
def merge(key, l1, l2):
    k1 = { d[key] for d in l1 }
    k2 = { d[key] for d in l2 }
    keys = k1.intersection(k2)
    f1 = [ d for d in l1 if d[key] in keys ]
    f2 = [ d for d in l2 if d[key] in keys ]
    return f1, f2

rawDescription: Merging two python lists of dicts

description: Merging two python lists of dicts


code:
def updateQListWidget(qlistwidget, values):
        """ Updates a QListWidget object with a list of values
        ARGS:
            qlistwidget  - QListWidget object
            values       - list of values to add to list widget
        """
        qlistwidget.clear()
        qlist = QtCore.QStringList()
        for v in values:
            s = QtCore.QString(v)
            qlist.append(s)
        qlistwidget.addItems(qlist)

rawDescription: PyQt4: Databinding?

description: PyQt4: Databinding


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

root = Tk()
spin = Spinbox(root, from_=0, to=9, width=3,
               font=Font(family='Helvetica', size=36, weight='bold'))
spin.pack()

rawDescription: Python 3.4, How to increase the size of the tkinter spinbox widget arrowheads?


code:
from importlib import import_module
mod = raw_input(":")
sys = import_module(mod)
sys
sys.version_info # Just to demonstrate

rawDescription: How to convert strings to variables for import? python

description: Convert strings to variables for import? python


rawDescription: Sorting sections in a config file using configparser


code:
cur.execute("SELECT hostName FROM mytable WHERE hostName=?", [hostName])
data = cur.fetchall()
cont = session.get('http://%s' % hostName).content
cur.execute("INSERT INTO mytable (hostName,content) VALUES (?,?)", [hostName, cont])

rawDescription: sqlite3 doesn't write web content on my table

description: Sqlite3 doesn't write web content on my table


code:
import subprocess
subprocess.Popen(['wget', '-O', MYFILENAME+'.png', 'http://images.websnapr.com/?url='+MYURL+'&size=s&nocache=82']).wait()

rawDescription: How to save web page as image using python

description: Save web page as image using python


code:
import ntpath
ntpath.dirname('C:\\documents and settings\\Dan\\yada\\1.txt')

rawDescription: Using os.path.dirname on windows path

description: Using os.path.dirname on windows path


code:
import os
def listdir(dirpath):
    if isinstance(dirpath,unicode):
        dirpath = dirpath.encode('utf8')
    return [p.decode('utf8') for p in os.listdir(dirpath)]

rawDescription: Change Python filesystem encoding

description: Change Python filesystem encoding


rawDescription: How to use least squares with weight matrix in python?

description: Use least squares with weight matrix in python


code: filehandler_dbg = logging.FileHandler(logger.name + '-debug.log', mode='w')

rawDescription: How do I get logger to delete existing log file before writing to it again?

description: Get logger to delete existing log file before writing to it again


code:
import threading, traceback, sys
class DebugLock(object):
    def __init__(self):
        self._lock = threading.Lock()
    def acquire(self):
        print >>sys.stderr, "acquired", self
        #traceback.print_tb
        self._lock.acquire()
    def release(self):
        print >>sys.stderr, "released", self
        #traceback.print_tb
        self._lock.release()
    def __enter__(self):
        self.acquire()
    def __exit__(self, type, value, traceback):
        self.release()

rawDescription: Is it possible to subclass Lock() objects in Python? If not, other ways to debug deadlock?


code:
import requests
from bs4 import BeautifulSoup

url = 'http://www.example.com'
page_request = requests.get(url)
page_source = page_request.text
soup = BeautifulSoup(page_source)

rawDescription: getting information from a webpage for an application using python

description: Getting information from a webpage for an application using python


rawDescription: how to have pyspeech ignore certain words

description: Have pyspeech ignore certain words


code:
self.response.headers['Content-Type'] = 'application/csv'
writer = csv.writer(self.response.out)
writer.writerow(['foo','foo,bar', 'bar'])

rawDescription: how to create a downloadable csv file in appengine

description: Create a downloadable csv file in appengine


code:
rb1 = ttk.Radiobutton(self.frame, text='5', variable=self.my_var, value=5,command=self.selected)
rb2 = ttk.Radiobutton(self.frame, text='10', variable=self.my_var, value=10,command=self.selected)
rb3 = ttk.Radiobutton(self.frame, text='15', variable=self.my_var, value=15,command=self.selected)
self.rb1.grid(row=0)
self.rb2.grid(row=1)
self.rb3.grid(row=2)

def selected(self):
     if self.my_var.get()==5:
        "do something"
     elif self.my_var.get()==10:
        "do something"
     else:
        "do something"

rawDescription: Tkinter: How to set ttk.Radiobutton activated and get its value?


code:
seq = [(0, 1), (1, 2), (2, 2), (3, 2), (4, 1), (5, 3), (6, 3), (7, 2)]
from itertools import groupby
from operator import itemgetter
[list(items) for key,items in groupby(seq,key=itemgetter(1))]

rawDescription: How to group sequences of tuples with similar elements keeping order?

description: Group sequences of tuples with similar elements keeping order


code:
with requests.Session() as c:

    #  adding this line was the key
    c.get('https://us.etrade.com/e/t/invest/markets?ploc=c-MainNav')

    r=c.get('https://www.etrade.wallst.com/v1/stocks/snapshot/snapshot.asp?symbol=' + symbol + '&rsO=new')

    etradeMarkup = BeautifulSoup(r.text)

rawDescription: etrade scraping with python requests doesn't want to work with cross-domain urls

description: Etrade scraping with python requests doesn't want to work with cross-domain urls


code:
map.connect(R'/{path:.*?}.sass', controller='SassController', action='index')

#in the SassController
def index(self, path):
    return path

rawDescription: How to match all .sass request to a particular controller in pylons?

description: Match all .sass request to a particular controller in pylons


code:
import os
os.system("gksudo software-center")

rawDescription: Linux acquire root permissions through a password popup


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('ShowTime!', self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)
        self._dialog = None

    def handleButton(self):
        if self._dialog is None:
            self._dialog = QtGui.QMessageBox(self)
            self._dialog.setWindowTitle('Messages')
            self._dialog.setModal(False)
            pos = self.pos()
            pos.setX(pos.x() + self.width() + 10)
            self._dialog.move(pos)
        self._dialog.setText(
            'The time is: %s' % QtCore.QTime.currentTime().toString())
        self._dialog.show()

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: how to check if PyQt window exists

description: Check if PyQt window exists


code:
status_dict = dict(my_thing.STATUSES)
return status_dict[value]

rawDescription: Get django field "choice" from arbitrary value


code:
pattern = "%.4f"
floats = [pattern % i for i in floats]

rawDescription: Using python map to replace all floats in a list with rounded floats of type str


code:
d = {}
for sub in a:
   d.setdefault(tuple(sub[:2]),[]).append(sub[2:])

[k+tuple(map(sum, zip(*v))) for k,v in d.items()]

rawDescription: Python: adding elements in nested list if the first two elements are the same


code:
from matplotlib import pyplot

f = pyplot.figure()
a = f.add_subplot(111, frameon=False) # Remove frame
a.plot(...)

myimg = pyplot.imread(...)
imgaxes = f.add_axes(a.get_position(), # new axes with same position
    label='image', # label to ensure imgaxes is different from a
    zorder=-1, # put image below the plot
    xticks=[], yticks=[]) # remove the ticks
img = imgaxes.imshow(myimg, aspect='auto') # ensure image takes all the place

# now, to modify things
img.set_alpha(...)
imgaxes.set_xlim((x1, x2)) # x1 and x2 must be calculated from
                           # image size, origin, and zoom factor

rawDescription: Scale image in matplotlib without changing the axis


rawDescription: python what is this line doing?

description: Python what is this line doing


rawDescription: How to append or concatenate 'n' numpy arrays?

description: Append or concatenate 'n' numpy arrays


code:
from Tkinter import *

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

    def move(self):
        info = self.b.grid_info()
        previous_row = int(info["row"]) #int() needed because datas are stored as string
        self.b.grid(row=previous_row+1)

    def initUI(self):
        for i in range(5):
            l = Label(self, text="Row {0}".format(i))
            l.grid(row=i, column=0)

        self.b =  Button(self, text="Moving button", command=self.move)
        self.b.grid(row=0, column=1)

        self.pack()

root = Tk()
app = Example(root)
root.mainloop()

rawDescription: Setting the rows to variables in Tkinter


rawDescription: Capturing a line from multiline text based on search string


code:
import time
endTime = time.time() + 12*60*60 # 12 hours from now
while time.time() < endTime:
    captureImage()
    time.sleep(30)

rawDescription: Creating time lapse images in python

description: Creating time lapse images in python


code:
dot11elt = p.getlayer(Dot11Elt)
while dot11elt and dot11elt.ID != 221:
    dot11elt = dot11elt.payload.getlayer(Dot11Elt)
if dot11elt:
    ...  # dot11elt.ID == 221:

rawDescription: How to extract vendor data using scapy from a probe request

description: Extract vendor data using scapy from a probe request


rawDescription: Enabling SQL statements for SQLAlchemy / Pyramid from the command line


code:
class Foo:
    # static method
    @staticmethod
    def test():
        pass

    # class variable
    c = {'name' : test }

rawDescription: referencing static methods from class variable

description: Referencing static methods from class variable


code:
class crange:
    def __init__(self, *args, **kwargs):
        args = [ord(arg) for arg in args]
        kwargs = {key: ord(val) for key, val in kwargs.items()}
        self.range = range(*args, **kwargs)

    def __iter__(self):
        for n in self.range:
            yield chr(n)

    def __contains__(self, c):
        return ord(c) in self.range

    def __getitem__(self, i):
        if isinstance(i, slice):
            ret = crange('\x00')
            ret.range = self.range[i]
            return ret
        else:
            return chr(self.range[i])

    def __repr__(self):
        return  "crange({}, {})".format(
            repr(chr(self.range.start)), repr(chr(self.range.stop)))

r = crange('a', 'f')
print(list(r))
print('b' in r)
print('f' in r)
print(r[:2])

rawDescription: How do I extend, mimic, or emulate the range function?

description: Extend, mimic, or emulate the range function


rawDescription: PHP's virtual() command causes raw Python code to display on the webpage instead of executing it


code:
resp = c.get(rule.rule)
try:
    json_data = resp.loads(resp.data) # this line will throw exception if not JSON
    log.debug(resp)
    log.debug(json_data)
except:
    pass

rawDescription: loop through all rules in blueprint and check json against file, flask

description: Loop through all rules in blueprint and check json against file, flask


code: file_date = str(input("Enter file date: "))

rawDescription: Python 3.2 - Concatenate and string formatting behavior not behaving as expected


code:
def main(args):
    ...

if __name__ == '__main__':
    args = parse_args()
    main(args)

rawDescription: python, unittest, test a script with command line args

description: Python, unittest, test a script with command line args


code:
first_items = itertools.imap(lambda x: x[0], list_of_tuples)
repeated_tuple = itertools.repeat(some_tuple, len(list_of_tuples))
items = itertools.izip(repeated_tuple, first_items)
result = itertools.starmap(lambda x,y: x + (y,), items)

rawDescription: Is there a point to using nested iterators?


code:
arr = np.array([22/7, 1/13])           # init array
arr                                    # np.array default printing
arr[0]                                 # int default printing
np.set_printoptions(precision=24)      # increase np.array print "precision"
arr                                    # np.array high-"precision" print
float.hex(arr[0])                      # actual underlying representation

rawDescription: Why is numpy array's .tolist() creating long doubles?


code:
m = __import__('A.B', globals(), locals(), ['C'])
C = getattr(m, 'C')
c = C()

rawDescription: How to import a class on the-fly-and Instantiate it as an object?

description: Import a class on the-fly-and Instantiate it as an object


code:
from urllib import urlencode
urlencode({'b':'bbbb', 'c':'ccc'})

rawDescription: easy way to change a dict data to url Parameter

description: Easy way to change a dict data to url Parameter


rawDescription: how to combine two columns with an if/else in python pandas?

description: Combine two columns with an if/else in python pandas


code: open(filename, 'w').close()

rawDescription: How to empty a file using Python

description: Empty a file using Python


code: return float(self.header_height) / float(self.header_width)

rawDescription: Django Model/Template Arithmetic Issue

description: Django Model/Template Arithmetic Issue


code:
ax=plt.gca()
#ax.get_xticks() will get the current ticks
ax.set_xticklabels(map(str, ax.get_xticks()/5.0))

rawDescription: change X ticks in matplotlib plot

description: Change X ticks in matplotlib plot


code:
room1IsLoaded = False

while gameLoop == 1:
  if not room1IsLoaded:
    spritegroup.add(coin)
    room1IsLoaded = True

rawDescription: Removing a sprite from Pygame.Group which is declared in a loop


code:
def process_dict(dictionary):
    import re
    rgx = re.compile(r"^(ds)\[(.+?)\]\.(index|type)$")

    processed = {}

    for k, v in dictionary.items():
        # does k have the format ds[some_key].index etc
        m = rgx.search(k)
        if m:
            # create the embedded path
            ds, ident, attr = m.groups()
            processed.setdefault(ds, {}).setdefault(ident, {})[attr] = v
        else:
            processed[k] = v

    return processed

rawDescription: How to split dictionary keys into multiple separate keys in python?

description: Split dictionary keys into multiple separate keys in python


code:
#tasks.py file
from lxml import etree
from celery import Celery

app = Celery('tasks', broker='amqp://guest@localhost//')

@app.task
def print_book(book_xml):
    book = etree.fromstring(book_xml)
    # do something interesting ...
    print(etree.tostring(book, pretty_print=True))

#caller.py file
from tasks import print_book
from lxml import etree

for _, book in etree.iterparse('Books.xml', tag="Book"):
    book_xml = etree.tostring(book)
    print_book.delay(book_xml)

rawDescription: Split and then pretty Print xml to be stored in a List


code: objs += env.Object(target=..., source=..., FORTRANMODPATH=...)

rawDescription: SCons build with multiple environments

description: SCons build with multiple environments


code:
# First I split each term in the scope list.
scope_list = [term.split() for term in scope_list]
# Then the query is built.
or_args = [and_(
    my_table.product == scope[0],
    my_table.release.in_(scope[1:])) for scope in scope_list]
results = session.query(my_table).filter(or_(*or_args)).all()

rawDescription: dynamic query filter with SQLalchemy operators

description: Dynamic query filter with SQLalchemy operators


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

# changing matplotlib the default style
matplotlib.style.use('ggplot')

plt.rcParams['lines.linewidth']=3
plt.rcParams['axes.facecolor']='b'
plt.rcParams['xtick.color']='r'

# dataframe plot
df = pd.DataFrame(np.random.randn(36, 3))
df.plot()

plt.show()

rawDescription: Matplotlib: Overriding "ggplot" default style properties


rawDescription: Convert Year/Month/Day to Day of Year in Python


code: arr = np.concatenate((np.zeros(deficit, dtype=arr.dtype), arr))

rawDescription: Pad 0's Of Numpy Array To Nearest Power Of Two


code:
from collections import defaultdict
m = {'a': 2, 'b': 1, 'c': 2, 'd': 1}
dd = defaultdict(list)
for k, v in m.iteritems():
    dd[v].append(k)

dict(dd)

rawDescription: Invert keys and values of the original dictionary


code:
import re
from random import sample

sentences = []
for i in range(23):
    with open('w_acad_{}.txt'.format(i)) as f:
        sentences += re.findall(r".*?[\.\!\?]+", f.read())

selected = sample(sentences, 1000)
with open('out.txt', 'w') as f:
    f.write(''.join(selected))

rawDescription: Get random sentences from a set of text files


rawDescription: Python passing format specifier in

description: Python passing format specifier in


code:
rows = cursor.fetchall()
for i, row in enumerate(rows):
    cursor.execute("UPDATE Table SET order = %s WHERE name = %s", (i, row.name))
    db.commit()

rawDescription: Increment row MySql Python

description: Increment row MySql Python


code:
import os
os.open("lock", os.O_CREAT|os.O_EXCL)

rawDescription: Only allow 1 instance of a python script


code:
from itertools import chain, product
result = chain.from_iterable(product(*lists) for lists in powerset([L1,L2,L3]))
list(result)

rawDescription: product of lists, not necessarily all the lists at the same time

description: Product of lists, not necessarily all the lists at the same time


code:
import re
from itertools import islice

pattern = re.compile(r'textA|textB|textC|textD')

with open('file.html', 'r') as lines:
    for line in islice(lines, 18, 19):
        line = pattern.sub('', line)

rawDescription: Python's map function on attributes

description: Python's map function on attributes


rawDescription: sort tuples in lists in python

description: Sort tuples in lists in python


code: [next(y for y in itemList if y.i == x) for x in indexList]

rawDescription: Pythonic way: Sort array items based on a class member and another array


code:
from fabric.api import cd,sudo
with cd('somepath'):
    sudo('./execute_script.sh')

rawDescription: is there a way to use fabric run() and sudo() at a time?

description: Is there a way to use fabric run() and sudo() at a time


code:
model = gtk.ListStore(gobject.TYPE_STRING, gtk.gdk.Pixbuf, gobject.TYPE_STRING)
iconview = gtk.IconView(model)

renderer = gtk.CellRendererPixbuf()
renderer.set_property('follow-state', True)
iconview.pack_start(renderer)
iconview.set_attributes(renderer,pixbuf=1)  #pixbuf is the column number corresponding to the pixbuf to render in the model

rawDescription: How to get the control over the selection in a gtk.IconView?

description: Get the control over the selection in a gtk.IconView


code:
rdd = sc.parallelize([("foo", 1), ("foo", 2), ("bar", 3)])

rdd.reduceByKey(lambda x, y : x + y).collect() # Sum for each key
# Gives [('foo', 3), ('bar', 3)]

x.reduceByKey(max).collect() # Max for each key
# Gives [('foo', 2), ('bar', 3)]

rawDescription: pySpark forEach function on a key

description: PySpark forEach function on a key


rawDescription: Execute Python with pygtk without terminal appear


code:
#0001_initial.py (or followings)
class Migration(migrations.Migration):

    operations = [
        migrations.RunSQL("CREATE TABLE..."),
        ...
    ]

rawDescription: How to create table during Django tests with managed = False?

description: Create table during Django tests with managed = False


rawDescription: How to match begin URL with REGEX in Django

description: Match begin URL with REGEX in Django


code:
if any(c not in 'abc' for c in _str):  # Don't use str as a name.
    print('Wrong character')

rawDescription: Check if a string contains only given characters


code:
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'Book1.xlsx')
ws = wb.Worksheets("Sheet1")

cells = ws.Range("A1:C1").Value[0]
ws.Range("D1").Value = ' '.join(cells)

offset = 0
for cell, color in zip(cells, [3, 4, 5]):
    ws.Range("D1").GetCharacters(offset, len(cell)+1).Font.ColorIndex = color
    offset += len(cell) + 1

wb.SaveAs(r'Output.xlsx')
excel.Application.Quit()

rawDescription: Copy data in three Excel cells and paste into fourth with font color changed for each of the three


code: [sum(x) for x in zip(*C)]

rawDescription: sum of N lists element-wise python

description: Sum of N lists element-wise python


code: ammo_count = AliasProperty(lambda self: len(self._ammo), bind=['_ammo'])

rawDescription: How can I bind to the length of a ListProperty?

description: Bind to the length of a ListProperty


code:
match = re.search(r"1.3", "abc123xyz")
if match:
    doSomethingWith(match.group(0))

rawDescription: Python: Getting text of a Regex match

description: Python: Getting text of a Regex match


code:
import textwrap
lines = textwrap.wrap(text, width=40)
y_text = h
for line in lines:
    width, height = font.getsize(line)
    draw.text(((w - width) / 2, y_text), line, font=font, fill=FOREGROUND)
    y_text += height

rawDescription: python PIL draw multiline text on image

description: Python PIL draw multiline text on image


rawDescription: Python dictionaries - find second key in tuple which yields minimum value