code:
df = df.reset_index()
df = df.set_index(['X','Y'])
df.ix[ df[df['Stuff']>10].index.unique() ]

rawDescription: Subsetting data by group criteria in Pandas


code:
inp='''Starting Nmap 6.40 ( http://nmap.org ) at 2014-02-15 22:20 PST
Nmap scan report for 192.168.1.1
Host is up (0.00025s latency).
MAC Address: ZZ:ZZ:11:ZZ:ZZ:ZZ (Cisco-Linksys)
Nmap scan report for 192.168.1.2
Host is up (0.0084s latency).
MAC Address: ZZ:ZZ:A1:2E:ZZ:ZZ (Apple)
Nmap scan report for 192.168.1.9
Host is up (0.012s latency).
MAC Address: A4:ZZ:57:17:ZZ:ZZ (Seiko Epson)
Nmap scan report for 192.168.1.103
Host is up (0.036s latency).
MAC Address: ZZ:ZZ:6D:05:ZZ:ZZ (Apple)'''
import re
r1 = re.compile(r'Nmap scan report for ([0-9.]*)[^:]*[^(]*\(Seiko Epson\)')
r1.search(inp).group(1)

rawDescription: Regex Match on IP Address Before Known String


code: df.where(df.eq(df.max(1), 0), -1)

rawDescription: Pandas : vectorized operations on maximum values per row


code:
md5sum('photo.jpg')
image = pyexiv2.ImageMetadata('photo.jpg')
image.read()
image['Exif.Image.ImageDescription'] = '%030x' % random.randrange(256**15)
image.write()
md5sum('photo.jpg')

rawDescription: How can I change an image's MD5 hash in Python?

description: Change an image's MD5 hash in Python


code: result = np.hstack([np.genfromtxt(fileName,delimiter=" ") for fileName in FILE_LIST])

rawDescription: Numpy Concatenate to empty array

description: Numpy Concatenate to empty array


code:
newfile = "namePart1" + dictionary[key] + "namePart2"
shutil.copyfile("cfn5e10_1.lp", newfile)

rawDescription: run cp command to make a copy of a file or change a file name in Python

description: Run cp command to make a copy of a file or change a file name in Python


code:
species = ["H2O", "CO2", "O2"]
coeff = ['1', '-4', '3']

pos = [c + s for c, s in zip(coeff, species) if int(c) > 0]
neg = [c[1:] + s for c, s in zip(coeff, species) if int(c) < 0]
print ("+".join(pos))+"="+("+".join(neg))

rawDescription: Printing from 2 lists on one line

description: Printing from 2 lists on one line


code:
class Unit():
    def __init__(self):
        self.last = pygame.time.get_ticks()
        self.cooldown = 300

    def fire(self):
        # fire gun, only if cooldown has been 0.3 seconds since last
        now = pygame.time.get_ticks()
        if now - self.last >= self.cooldown:
            self.last = now
            spawn_bullet()

rawDescription: How to wait some time in pygame?

description: Wait some time in pygame


code:
from tornado.websocket import WebSocketHandler

class WebSocketBase(WebSocketHandler):
    @gen.coroutine
    def on_message(self, message):
        response = yield gen.Task(tasks.sleep.apply_async, args=[3])
        self.write_message(str(response.result))

rawDescription: Python Tornado: how can I make this asynchronous ?


code:
import csv
import pyodbc

MDB = 'c:/path/to/my.mdb'
DRV = '{Microsoft Access Driver (*.mdb)}'
PWD = 'mypassword'

conn = pyodbc.connect('DRIVER=%s;DBQ=%s;PWD=%s' % (DRV,MDB,PWD))
curs = conn.cursor()

SQL = 'SELECT * FROM mytable;' # insert your query here
curs.execute(SQL)

rows = curs.fetchall()

curs.close()
conn.close()

# you could change the 'w' to 'a' for subsequent queries
csv_writer = csv.writer(open('mytable.csv', 'w'), lineterminator='\n')

for row in rows:
    csv_writer.writerow(row)

rawDescription: Query crashes MS Access

description: Query crashes MS Access


code:
def afunc():
   a = ['foo', 'bar', 'zot']
   b = ('oof', 'rab', 'toz')
   return
import dis; dis.dis(afunc)

rawDescription: Python: How expensive is to create a small list many times?


code:
from difflib import SequenceMatcher
def matcher(s1, s2):
    if s1 == s2:
        return 0
    elif SequenceMatcher(None, s1, s2).ratio() > 0.8: # 80% similarity-match
        return 1
    return 2

rawDescription: function in python that finds the first string can become the same as the second string by inserting or deleting a single character

description: Function in python that finds the first string can become the same as the second string by inserting or deleting a single character


code:
dividend_set = stock.dividend_set.all().order_by('date')
dividends = list(dividend_set)
for dividend in dividends:
    dividend.extra_value1 = 'foo'
    dividend.extra_value2 = 'bar'
# now pass the dividends list to your template as part of your context rather than the qs

rawDescription: django edit queryset objects without affecting database

description: Django edit queryset objects without affecting database


code:
import os
from array import array

#with open('data.bin', 'wb') as fout:
#   fout.write(os.urandom(16800000))

with open('data.bin', 'rb') as fin:
    arr = array('L')
    arr.fromfile(fin, 16800000 / 4)
    arr.byteswap()
    checksum = sum(arr) & 0xFFFFFFFF

rawDescription: Python: calculating checksum of a file for a weird protocol


code:
# Create an array of 16-bit signed integers
a = array.array("h", range(10))
# Write to file in big endian order
if sys.byteorder == "little":
    a.byteswap()
with open("data", "wb") as f:
    a.tofile(f)
# Read from file again
b = array.array("h")
with open("data", "rb") as f:
    b.fromfile(f, 10)
if sys.byteorder == "little":
    b.byteswap()

rawDescription: How to read/write binary 16-bit data in Python 2.x?

description: Read/write binary 16-bit data in Python 2.x


code:
event = {
    'summary': calendar_event_form.cleaned_data['name'],
    'location': calendar_event_form.cleaned_data['location'],
    'description': calendar_event_form.cleaned_data['description'],
    'start': {
        'date': start_string, #date here
        'timeZone': tz_str,
    },
    'end': {
        'date': end_string, #date here
        'timeZone': tz_str,
    },
}

rawDescription: Creating an 'all day' event using google calendar api in python


code: myfile = getfile.read()

rawDescription: Python: Pretty printing a xml file directly from a tar.gz package


code:
import csv
from itertools import izip

with open('source.csv') as f:
    reader = csv.reader(f)
    # filter data
    data = (row for row in reader if row[1].strip() in ('5', '8'))
    # make a new variable
    data = (row + [int(row[2]) * 3] for row in data)
    # transpose data
    data = izip(*data)
    # write data to a new csv file
    with open('destination.csv', 'w') as fw:
        csv.writer(fw).writerows(data)

rawDescription: Python: how to do basic data manipulation like in R?


code:
def initialize_upload(options):
  youtube = get_authenticated_service()

  tags = None
  if options.keywords:
    tags = options.keywords.split(",")

  insert_request = youtube.videos().insert(
    part="snippet,status",
    body=dict(
      snippet=dict(
        title=options.title,
        description=options.description,
        tags=tags,
        categoryId=options.category
      ),
      status = dict(
        privacyStatus=options.privacyStatus
      )
    ),
    media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True)
  )

  resumable_upload(insert_request)

rawDescription: Is there a way to auto-resume interrupted uploads to youtube using Python GData?


code:
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../')

rawDescription: PATH issue with pytest 'ImportError: No module named YadaYadaYada'


code:
import tkinter as tk

def get_size():
    w = root.winfo_width()
    h = root.winfo_height()
    print(w, h)

root = tk.Tk()
root.minsize(200, 200)
root.maxsize(1000, 1000)

btn = tk.Button(root, text = 'Get Current Window Size',\
                command = get_size)
btn.pack(expand = True)

root.mainloop()

rawDescription: Tkinter allow window resizing from-to a certain amount


code:
import pandas as pd

df = pd.DataFrame(data={'x':[1, 2, 3, 4, pd.np.nan], 'y':['a', 'a', 'a', 'b', 'b']})

funcs = {'x':'mean'}

print(df.groupby('y').agg(funcs))
#    x
# y
# a  2
# b  4

rawDescription: Pandas: Where is the function for mean that ignores NaN


rawDescription: Pandas replacing values on specific columns


rawDescription: round a single column in pandas

description: Round a single column in pandas


rawDescription: Removing unicode \u2026 like characters in a string in python2.7


code: text = re.sub(r'james', str(x), text, count=1)

rawDescription: replace same pattern with different replace value

description: Replace same pattern with different replace value


code:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.textinput import TextInput
from kivy.properties import  VariableListProperty

class MyTextInput(TextInput):
    padding =  VariableListProperty(['24dp', '48dp'])

class MyApp(App):
    def build(self):
        return MyTextInput(text='This is an example text', multiline=False)

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

rawDescription: Kivy TextInput and Fonts

description: Kivy TextInput and Fonts


code: value_when_true if condition else value_when_false

rawDescription: Putting a simple if-then statement on one line


rawDescription: How to simulate onclick (JavaScript) using Selenium/Python

description: Simulate onclick (JavaScript) using Selenium/Python


code:
import subprocess
outlookpath2doc = '"C:/Program Files (x86)\Microsoft Office\Office14\OUTLOOK.EXE"'
compose = '/c ipm.note'
recipients = '/m "recipient@example.com; recipient2@example.com&subject=Please take a look at this"'
attachment = '/a "' + path2doc + '"'
command = ' '.join([outlookpath2doc, compose, recipients, attachment])
process = subprocess.Popen(command, shell=False, stdout=subprocess.PIPE)

rawDescription: Python: Open outlook compose instance with attachments


code: df.loc[df['Symbol'] == 'TSLA']

rawDescription: Using Index in Python to return all values associated with a User Input


rawDescription: Connect user login views, form with pre-exist user which is created by Django admin


code:
np.issubdtype(np.complex128, np.number)
np.issubdtype(np.int32, np.number)
np.issubdtype(np.str_, np.number)
np.issubdtype('O', np.number) # 'O' is object

rawDescription: numpy.asarray: how to check up that its result dtype is numeric?

description: Numpy.asarray: how to check up that its result dtype is numeric


code: all(isinstance(x, Number) for x in mylist)

rawDescription: Checking list values

description: Checking list values


rawDescription: How do i get pandas.replace to work only on specified column?

description: Get pandas.replace to work only on specified column


code:
H_bis = np.sum(M[1:2*n**2:2, :2*n**2] * M[:2*n**2:2, :2*n**2].conjugate(), axis=1)
H_bis = H_bis * H_bis.conjugate()
H_bis = -np.sum(H_bis)

rawDescription: Python 3: Optimizing summation over scipy arrays


code:
# worker.py

def work(ui):
    some_result = do_something()
    ui.update(some_result)
    other_result = do_something_else()

# ui.py

import worker

class Ui(object):
    def some_action(self):
        worker.work(self)

    def update(self, data):
        self.show_data_somewhere(data)

rawDescription: How can I update an instance variable from within a called module

description: Update an instance variable from within a called module


code:
def run(self):
        wx.CallAfter(self.sendToMainThread, "\n###\n\n")
        text = "Executing: %s\n" % (self.cmd)
        wx.CallAfter(self.sendToMainThread, text)

        child = pexpect.spawn(self.cmd)
        while True:
            try:
                if self.stopFlag:
                    line = "Stop Buttont Clicked, Stopping External Command... \n"
                    wx.CallAfter(self.sendToMainThread, line)
                    child.terminate(True)
                    child.close()
                    break
                child.expect('\n')
                line = child.before
                wx.CallAfter(self.sendToMainThread, line)
            except pexpect.EOF:
                child.close()
                break
        if child.exitstatus != None and child.exitstatus != 0:
            line = "Command Execution Problem, return code is %d\n" % child.exitstatus
            wx.CallAfter(self.sendToMainThread, line)
        #it looks like next line never happens because of the exception handling above.
        #child.close() make sure child return a code.
        elif child.exitstatus == None:
            line = "Command Execution was interrupted.\n"
            wx.CallAfter(self.sendToMainThread, line)

        #sending an end signal to main thread. command is finished.
        wx.CallAfter(Publisher().sendMessage, "endthread", True)

rawDescription: pexpect run long bash command hang wxpython GUI

description: Pexpect run long bash command hang wxpython GUI


code:
df = DataFrame(np.random.rand(10, 5))
df

rawDescription: how does boxplot in pandas/python work?

description: How does boxplot in pandas/python work


code:
class CaptchaFormBase(forms.Form):  # or forms.ModelForm, if appropriate

    captcha = CaptchaField()

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        # this is the same as assigning to self request then deleting the key

        super(CaptchaFormBase, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(CaptchaFormBase, self).clean()

        success = self.is_valid()
        utils.update_captcha_access(self.request, success)

        if not success:
            # this will put things in non_field_errors, you may want to put it in self.errors['captcha']
            raise forms.ValidationError("Captcha validation failed")

        # always make it easy to see that you're returning cleaned_data
        return self.cleaned_data

class PostCaptchaForm(PostForm, CaptchaFormBase):
    pass

class ThreadCaptchaForm(ThreadForm, CaptchaFormBase):
    pass

rawDescription: DRY up similar form classes

description: DRY up similar form classes


code:
import smtplib, imaplib, email

imap_host = "mail.example.com"
smtp_host = "mail.example.com"
smtp_port = 587
user = "xyz"
passwd = "xyz"
msgid = 7
from_addr = "from.me@example.com"
to_addr = "to.you@example.com"

# open IMAP connection and fetch message with id msgid
# store message data in email_data
client = imaplib.IMAP4(imap_host)
client.login(user, passwd)
client.select('INBOX')
status, data = client.fetch(msgid, "(RFC822)")
email_data = data[0][1]
client.close()
client.logout()

# create a Message instance from the email data
message = email.message_from_string(email_data)

# replace headers (could do other processing here)
message.replace_header("From", from_addr)
message.replace_header("To", to_addr)

# open authenticated SMTP connection and send message with
# specified envelope from and to addresses
smtp = smtplib.SMTP(smtp_host, smtp_port)
smtp.starttls()
smtp.login(user, passwd)
smtp.sendmail(from_addr, to_addr, message.as_string())
smtp.quit()

rawDescription: Forwarding an email with python smtplib

description: Forwarding an email with python smtplib


rawDescription: Back-convert a list (formatted as a string) into a list


code:
import numpy as np
from numpy.ctypeslib import ndpointer

def wrapped_ndptr(*args, **kwargs):
  base = ndpointer(*args, **kwargs)
  def from_param(cls, obj):
    if obj is None:
      return obj
    return base.from_param(obj)
  return type(base.__name__, (base,), {'from_param': classmethod(from_param)})

ComplexArrayType = wrapped_ndptr(dtype=np.complex128, ndim=1, flags='C_CONTIGUOUS')
DoubleArrayType = wrapped_ndptr(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS')

rawDescription: How can I pass null to an external library, using ctypes, with an argument declared with ctypeslib.ndpointer?

description: Pass null to an external library, using ctypes, with an argument declared with ctypeslib.ndpointer


code:
import numpy as np
from matplotlib.mlab import griddata

x = np.array([0,0,1,1])
y = np.array([0,1,0,1])
z = np.array([0,10,20,30])
xi = np.arange(x.min(),x.max()+1)
yi = np.arange(y.min(),y.max()+1)
ar = griddata(x,y,z,xi,yi)

# ar is now
# array([[  0.,  20.],
#        [ 10.,  30.]])

rawDescription: How to plot 3D data as 2D grid colormap in Python?

description: Plot 3D data as 2D grid colormap in Python


code: isinstance('asd',(str,bool,int))

rawDescription: Why isinstance() method returning True (Python 3.xx)


code:
output = PdfFileWriter()
for rownum, row in enumerate(reader):
    if rownum == 0:
        header = row
    else:
        for col in row:
            d[header[colnum]] = col
            colnum += 1
        # or, more concisely:
        # d = dict((header[colnum], value) for (colnum, value) in enumerate(row))
        # or use a dict comprehension if you're on a sufficiently recent version
        # or best of all, use a csv.DictReader object instead of creating the dictionary yourself

        packet = StringIO.StringIO()

        can = canvas.Canvas(packet, pagesize=(621,405))
        can.drawString(340, 147, d['FirstName'])
        can.save()

        packet.seek(0)
        new_pdf = PdfFileReader(packet)

        # I would check whether this can be read once and still have getPage called multiple times
        existing_pdf = PdfFileReader(file(order, 'rb'))

        front = existing_pdf.getPage(0)
        back = existing_pdf.getPage(1)
        back.mergePage(new_pdf.getPage(0))
        output.addPage(front)
        output.addPage(back)

outputStream = file(token+'_merged.pdf', 'wb')
output.write(outputStream)
outputStream.close()

rawDescription: Same value from dictionary is being applied


code:
class Member(Base):
    __table__ = Table('members', metadata, autoload=True)
    club = relationship(Club, backref="members")
    def __repr__(self):
        return "<Member: %s of %s>" % (self.name, self.club.name)

rawDescription: Retrieving ForeignKey mapped objects in Python with SqlAlchemy


code:
def remove(self, item):
    finalSet=[]
    for item in self.s_list:
        if item not in finalSet:
            finalSet.append(item)
            return finalSet

rawDescription: Object Oriented Programming removing repeated items (Python)


code:
import logging
import logging.handlers
#create a logger object:
logger = logging.getLogger("MyLogger")
#define a memory handler:
memHandler = logging.handlers.MemoryHandler(capacity = 1024*10)
logger.addHandler(memHandler)
#...
#initialization code with several logging events (for example, loading a configuration file to a 'conf' object)
#everything is logged by the memory handler
#...
#after configuration is loaded, a new logging handler is defined for a log file:
fileHandler = logging.FileHandler(conf.get("main","log_file"),'w')
#flush the memory handler into the new file handler:
memHandler.setTarget(fileHandler)
memHandler.flush()
memHandler.close()
logger.removeHandler(memHandler)
logger.addHandler(handler)

rawDescription: Including previously logged events in a new logging handler


code:
rot_points  = (i.rotated(self.orientation.get_angle()) for i in points)
real_points = [self.pos+i*self.scale for i in rot_points]

rawDescription: Help me lambda-nize this

description: Help me lambda-nize this


code: 'Percentage used: {:.2%}'.format(.4).center(60, '-')

rawDescription: Nesting string format

description: Nesting string format


code:
b = random.randint(2, 38)
a = random.randint(1, b - 1)
c = random.randint(b + 1, 39)
return [a, b - a, c - b, 40 - c]

rawDescription: Generate multiple random numbers to equal a value in python


code:
theVariable = tk.StringVar()
tk.Entry(..., textvariable=theVariable)
tk.Label(..., textvariable=theVariable)

rawDescription: How to get input from Entry and set it as the text in a Label

description: Get input from Entry and set it as the text in a Label


code:
class HandlerFinder(object):
    """Searches for handler implementations across multiple objects.
    """
    # See <http://stackoverflow.com/questions/4637792> for why this is
    # necessary.

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

    def __getattr__(self, name):
        for o in self.backing_objects:
            if hasattr(o, name):
                return getattr(o, name)
        else:
            raise AttributeError("%r not found on any of %r"
                % (name, self.backing_objects))

rawDescription: pygtk gtk.Builder.connect_signals onto multiple objects?

description: Pygtk gtk.Builder.connect_signals onto multiple objects


rawDescription: Saving Scripts for PythonTurtle

description: Saving Scripts for PythonTurtle


code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig = plt.figure(figsize=(12, 12))

ax = Axes3D(fig) # ax = fig.add_subplot(111, projection='3d')
ax.set_title("Plot 3d",fontsize=14)
ax.set_xlabel('Voltage (V)', fontsize=12)
ax.set_ylabel('Pulse Delay(ms)', fontsize=12)
ax.set_zlabel('Pulse Width(ms)', fontsize=12)
ax.grid(True, linestyle='-', color='0.75')

# 'i15' and 'f15' are not known as numerical types.
# You can use only 'i8' (np.int64) and 'f16' (np.float128) or 'f8' (np.float64).
# 'f16' seems not to be recognized as a valid type for the scatter library.
# I think that 'f8' and 'i8' are quoit enough.
data = np.genfromtxt('./sample.txt', dtype=[('col1', 'f8'), ('col2', 'i8'), ('col3',   'i8'), ('col4', 'S15')])

# scatter does not take for the c option a list of colours such as ['g', 'g', 'r', ...].
# In this case, we will define data for each colour, not a color for each scatter point.
m = data["col4"]
data1 = data[m == "PASS"]
data2 = data[m != "PASS"]

for dat, color in [(data1, 'g'), (data2, 'r')]:
    # Don't forget that having empty data columns may raise exceptions ...
    try:
        x, y, z = dat['col1'], dat['col2'], dat['col3']
        ax.scatter(xs=x, ys=y, zs=z, s=50, c=color, marker='o', linewidths=0)
    except:
        pass

plt.show()

rawDescription: 3d surface plot genfromtxt

description: 3d surface plot genfromtxt


code:
import os
os.path.basename(file)

rawDescription: python find last in string

description: Python find last in string


code:
import numpy as np
x, y, z = np.loadtxt('new.csv', delimiter=',', unpack=True)

rawDescription: Assign variables imported from csv

description: Assign variables imported from csv


code:
pygame.mixer.init(frequency=22050,size=-16,channels=4)
sound1 = pygame.mixer.Sound('sound1.wav')
sound2 = pygame.mixer.Sound('sound2.wav')
chan1 = pygame.mixer.find_channel()
chan1.queue(sound1)
chan2 = pygame.mixer.find_channel()
chan2.queue(sound2)
time.sleep(10)

rawDescription: Pygame mixer only plays one sound at a time


code:
s="Ben went to the shop"
L=s.split()
import itertools
print('\n'.join(' '.join(i) for i in list(itertools.permutations(L))))

rawDescription: Shuffle elements in a string and get all the possible arrangements


rawDescription: Points for thousand mark and decimal mark


code:
class ContactWizard(SessionWizardView):
    template_name = "invite.html"

    def done(self, form_list, **kwargs):
        form_data = process_form_data(form_list, self.request.user)

        return render_to_response('invitedone.html', {'form_data': form_data})

rawDescription: Django: how do i request username in SessionWizardView?


code:
fi = "myoriginal.gbk"
fo = "mynewfile.gbk"

original_records = list(SeqIO.parse(fi, "gb"))

for result in results:
    result = result.split("\t")
    start = int(result[0])
    end = int(result[1])

    for record in original_records:
        record.features.append(SeqFeature(FeatureLocation(start, end), type = "misc_feat"))
        SeqIO.write(record, fo, "gb")

rawDescription: Improve genbank feature addition

description: Improve genbank feature addition


code:
import random
my_list = ['A'] * 5 + ['B'] * 5 + ['C'] * 90
random.choice(my_list)

rawDescription: Python Weighted Random

description: Python Weighted Random


code:
import os

filename = os.path.basename(__file__)
print ('this is generated by ' + filename)

rawDescription: How can python return the filename currently being processed under Windows


code: """spam is an object that supports indexing."""

rawDescription: Duck typing to allow tuples, lists, or something that can be treated like one


code:
# Boto 3
ec2.create_instances(ImageId='<ami-image-id>', MinCount=1, MaxCount=5)

rawDescription: How to create an ec2 instance using boto3

description: Create an ec2 instance using boto3


code:
for i, question_dict in enumerate(questions):
    print(i, question_dict['question'])

rawDescription: Reading from dictionaries nested in a list


code:
import time

time.sleep(1) # Sleeps for one second.

rawDescription: How to add a delay to part of a script in Python?

description: Add a delay to part of a script in Python


code:
import os.path as osp
osp.join(osp.dirname(__file__), 'config.ini')

rawDescription: How to apply relative directory in python when imported from different module?

description: Apply relative directory in python when imported from different module


code:
NEWLINE_SIZE_IN_BYTES = 1  # 2 on Windows?
with open('data.dat', 'w') as fout:
    np.savetxt(fout, model, delimiter=",", fmt='%.3f')
    fout.seek(NEWLINE_SIZE_IN_BYTES, 2)
    fout.truncate()

rawDescription: numpy.savetxt() stop newline on final line

description: Numpy.savetxt() stop newline on final line


code:
s1 = '''This string contains """ so use triple-single-quotes.'''
s2 = """This string contains ''' so use triple-double-quotes."""

rawDescription: When to use triple single quotes instead of triple double quotes


code:
import xlrd
try:
    work_book = xlrd.open_workbook('file_name.xls', on_demand=True)
finally:
    work_book.release_resources()

rawDescription: How to speed up: opening a data file in python

description: Speed up: opening a data file in python


code:
import os, sys
import win32com.client
import win32clipboard

def Copy():

    win32clipboard.OpenClipboard()

    # Pfad zum Template
    path_to_temp = r"C:\004_Python_Workspace\Persek\Template.xls"

    # Pfad zum Testpaket
    xlsPath = r"C:\004_Python_Workspace\Testfolder\Testanweisung_LK_ASL.xls"

    # Blattname im Template und im Testpaket
    Sheet = 'ECU_Config'

    excel_app = win32com.client.dynamic.Dispatch('Excel.Application')

    ###### Kopiere ECU_Config aus Template #####
    excel_workbook1 = excel_app.Workbooks.Open(path_to_temp)

    excel_workbook1.Worksheets(Sheet).UsedRange.Copy()

    ###### Fuege in das neue Testpaket ein #####
    excel_workbook2 = excel_app.Workbooks.Open(xlsPath)
    excel_workbook2.Worksheets(Sheet).Range('A1').PasteSpecial()
    excel_workbook2.worksheets(Sheet).Columns('A:B').AutoFit()
    excel_workbook2.Close(SaveChanges=True)
    del excel_workbook2

    excel_workbook1.Close()
    del excel_workbook1
    excel_app.Quit()

    win32clipboard.CloseClipboard()

rawDescription: Error by doing Copy Paste with win32com (Glade GTK Python)


code:
import lxml.html as lh
doc = lh.parse('http://www.bom.gov.au/nsw/forecasts/sydney.shtml?ref=hdr')
doc.xpath('.//div[@class="day main"]//em[@class="max"]/text()')

rawDescription: How to get content from HTML page and print in Python?

description: Get content from HTML page and print in Python


code:
class QuestionForm(forms.Form):
    answer = forms.CharField()

def questions(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        if form.is_valid():
            # Process the data in form.cleaned_data
            return HttpResponseRedirect('/done/')
    else:
        form = QuestionForm() # An unbound form

    return render_to_response('questions.html', {'form': form,})

rawDescription: Display form in Django not based on Models/Form


code:
subkeyword = (
        Session.query(Subkeyword.subkeyword_id, Subkeyword.subkeyword_word)
        .filter_by(subkeyword_company_id=self.e_company_id)
        .filter_by(subkeyword_word=subkeyword_word)
        .filter_by(subkeyword_active=True)
        .one()
    )

rawDescription: How to break a line of chained methods in Python?

description: Break a line of chained methods in Python


code:
def combine(a, b, a_weight, b_weight):
    if isinstance(a, tuple):
        return tuple(combine(x,y,a_weight,b_weight) for x,y in zip(a,b))
    elif isinstance(a, dict):
        return dict((k, combine(a[k],b[k],a_weight,b_weight)) for k in a)
    #add other data structures here if you need to (e.g. list, set, etc.)
    else: #assume a number
        return ((a * a_weight) + (b * b_weight)) / (a_weight + b_weight)

rawDescription: Weighted average of 2 tuples, each having 2 dictionaries (of dictionaries)


code:
from tkinter import *
from tkinter import messagebox as box

def main_menu():
    window = Tk()
    window.title('Juke Box')
    window.geometry('800x480')
    window.configure(background = 'black')

    label = Label(window, text = 'Juke-Box', fg = 'light green',
                  bg = 'black', font = (None, 30), height = 2)
    label.pack(side = TOP)

    gridFrame = Frame(window, bg='black') # New frame to store buttons

    # Grid uses sticky instead of anchor, but in this scenario it is not really necessary
    # I have left it in case you need it for some other reason

    Jam = Button(gridFrame, text = 'The Jam', width = 25, height = 2)
    Jam.grid(row=0, column=0, pady = 10, padx = 25, sticky=W)
    Roses = Button(gridFrame, text = 'The Stone Roses', width = 25, height = 2)
    Roses.grid(row=1, column=0, pady = 10, padx = 25, sticky=W)

    Smiths = Button(gridFrame, text = 'The Smiths', width = 25, height = 2)
    Smiths.grid(row=2, column=0, pady = 10, padx = 25, sticky =W)

    Wedding = Button(gridFrame, text = 'The Wedding Pressent', width = 25, height = 2)
    Wedding.grid(row=3, column=0, pady = 10, padx = 25, sticky =W)

    Blondie = Button(gridFrame, text = 'Blondie', width = 25, height = 2)
    Blondie.grid(row=4, column=0, pady = 10, padx = 25, sticky =W)

    Clash = Button(gridFrame, text = 'Clash', width = 25, height = 2)
    Clash.grid(row=5, column=0, pady = 10, padx = 25, sticky =W)

    Madness = Button(gridFrame, text = 'Madness', width = 25, height = 2)
    Madness.grid(row=0, column=1, pady = 10, padx = 25, sticky =N)

    Pistols = Button(gridFrame, text = 'The Sex Pistols', width = 25, height = 2)
    Pistols.grid(row=1, column=1, pady = 10, padx = 25, sticky =N)

    gridFrame.pack(side=BOTTOM)
    # Place it a the bottom or top or wherever you want it to go

    window.mainloop()

main_menu()

rawDescription: Using Anchor In Tkinter

description: Using Anchor In Tkinter


code:
def copy_relations(self, oldinstance):
    for image in oldinstance.image_set.all():
        image.pk = None
        image.plugin = self
        image.save()

rawDescription: Django CMS losing data from draft to live


code:
from sqlalchemy.dialects.mysql import DATETIME
df.to_sql('trading_data', engine, dtype={'date_time': DATETIME(fsp=6)}, if_exists='replace', index=False)
df_sql = pd.read_sql_query('SELECT * FROM trading_data', engine)
df_sql.head()

rawDescription: Pandas: milliseconds dropped when writing data to MySQL


code:
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
import Tkinter as tk

class MainFrame(tk.Frame):

    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.text = tk.Text(self)
        self.text.pack(side=tk.TOP)
        tk.Button(
            self, text='print coordinate', command=self.print_coordinate
        ).pack(side=tk.TOP)

    def print_coordinate(self):
        """Calculate and print the lower right screen coordinate of the
        character at the current text cursor position.
        """
        character = self.text.get(tk.INSERT)
        x, y, width, height = self.text.bbox(tk.INSERT)
        #
        # The line end has a width spanning the whole line until the right
        # border of the text widget but it makes more sense to view it as
        # having zero width in this context.
        #
        screen_x = x + (0 if character == u'\n' else width) + self.winfo_rootx()
        screen_y = y + height + self.winfo_rooty()
        print(screen_x, screen_y)

def main():
    root = tk.Tk()
    mainframe = MainFrame(root)
    mainframe.pack()
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Get position of last character in Tkinter Text widget


code:
class X:
  def Y(self): pass

type(X.Y)

rawDescription: Get defining class of unbound method object in Python 3


code:
def step_hist(ax, X, num_x_bins=10,
              hatch_from= -2, hatch_till=0.5,
              orientation='h'):
    #make histogram by hand.
    hist, edges = np.histogram(X, bins=num_x_bins)
    #generate (x,y) points for a step-plot
    edges = np.repeat(edges, 2)
    hist = np.hstack((0, np.repeat(hist, 2), 0))
    #plot step_hist
    #indices where we want the  plot hatached
    fill_region  =(hatch_from<edges)&(edges<hatch_till)
    #apply hatching my using fill_between.
    if orientation == 'h':
        ax.fill_between(edges[fill_region],
                        hist[fill_region], 0,
                        color='none', edgecolor='k',
                        hatch='xxx')
        ax.plot(edges, hist, 'k')
    elif orientation == 'v':
        ax.fill_betweenx(edges[fill_region],
                        hist[fill_region], 0,
                        color='none', edgecolor='k',
                        hatch='xxx')
        ax.plot(hist, edges, 'k')

a, b = np.random.randn(500), np.random.randn(500)

ax_top = plt.subplot(221)
ax_right = plt.subplot(224)
ax_cent = plt.subplot(223)

ax_cent.scatter(a, b, c='k')
step_hist(ax_top, a)
step_hist(ax_right, a, orientation='v')

rawDescription: Histogram fill from a specified x/y value


rawDescription: Creating several profile classes in django


code:
class TransformTable:
    target_dict = {}

    def productid(self, value):
        ...
    def name(self, value):
        validity_check(value)
        self.target_dict['Product'] = value.strip().capitalize()
    def description(self, value):
        ...

    def _default(self, value):
        sys.stderr.write('Unknown key!\n')

    def __call__(self, fieldname, value):
        getattr(self, fieldname, self._default)(value)

transformtable = TransformTable() # create callable instance

transformtable(fieldname, value) # use it

rawDescription: Dictionary based switch-like statement with actions


rawDescription: date range filter in django

description: Date range filter in django


code:
dta['SUNACTIVITY_2'] = dta['SUNACTIVITY']
dta['SUNACTIVITY_2'] = (dta['SUNACTIVITY_2'] - dta['SUNACTIVITY_2'].mean()) /     (dta['SUNACTIVITY_2'].std())
plt.acorr(dta['SUNACTIVITY_2'],maxlags = len(dta['SUNACTIVITY_2']) -1, linestyle = "solid", usevlines = False, marker='')
plt.show()

rawDescription: What is the difference between auto-correlation in matplotlib and auto-correlation in pandas.tools.plotting?


code:
from django.shortcuts import render_to_response
from django.template import RequestContext

def my_personalized_view(request):
  return render_to_response('something.html',
                             {},
                             context_instance=RequestContext(request))

rawDescription: django double "extends", problem with login

description: Django double "extends", problem with login


code:
class Whois(object):
    _whois_by_query_cache = {}

    def __init__(self, query):
        """Initializes the instance variables to defaults. See :meth:`lookup`
        for details on how to submit the query."""
        self.query = query
        self.domain = None
        # ... other fields.

    def lookup(self):
        """Submits the `whois` query and stores results internally."""
        # ... implementation

rawDescription: What Python way would you suggest to check whois database records?


code:
from scikits.audiolab import Sndfile
import numpy as np

f = Sndfile(fname, 'r')
data = np.array(f.read_frames(f.nframes), dtype=np.float64)
f.close()
return data

rawDescription: Faster way to convert from 24 bit wav pcm format to float?


code:
import itertools as it

# add_doublet accomplishes step 2
def add_doublet(t):
    for i in range(len(t)):
        for j in range(i+1, len(t)+1):
            yield t[:j] + (t[i],) + t[j:]

def all_doublet_tuples(n):
    for unique_tuple in it.permutations(range(n), n-1):
        for doublet_tuple in add_doublet(unique_tuple):
            yield doublet_tuple

from pprint import pprint

n = 3
pprint(list(all_doublet_tuples(n)))

rawDescription: Iterate over all lists with one duplicate


code:
# This is a simple mapping which associates the old keys with the new ones
translations = {'translated_key_1': 'key_one',
                'translated_key_2': 'key_two'}

# iterate through the map
for k,v in translations.iteritems():
    # you could also replace with try except
    if v in first_dict:
        second_dict[k] = first_dict[v]

rawDescription: Condense successive 'try' blocks

description: Condense successive 'try' blocks


code:
def B():
   for x in A():
     if x is None:
       yield
     else:
       break

   # continue, x contains value A yielded

rawDescription: Python generators and coroutines

description: Python generators and coroutines


code:
import pandas as pd

df = pd.read_csv("cc2012xyz2_5_5dp.csv", header=None)
Labels = df[0].values
X0 = df[1].values
Y0 = df[2].values

ax = plt.gca()

plt.plot(X0, Y0)
ax.set_aspect("equal")

tick_len = 0.015
text_offset = 0.06

idx = np.arange(14, 47, 4)
x, y = X0[idx], Y0[idx]
xp, yp = X0[idx-1], Y0[idx-1]
xn, yn = X0[idx+1], Y0[idx+1]

labels = Labels[idx]
angle = np.arctan2(yn-yp, xn-xp) + np.pi / 2
x1, y1 = x + tick_len*np.cos(angle), y + tick_len*np.sin(angle)
x2, y2 = x + text_offset*np.cos(angle), y + text_offset*np.sin(angle)
from matplotlib.collections import LineCollection

tick_lines = LineCollection(np.c_[x, y, x1, y1].reshape(-1, 2, 2), color="k", lw=1)
ax.add_collection(tick_lines)
for i in range(len(idx)):
    plt.text(x2[i], y2[i], str(labels[i]), va="center", ha="center")

ax.set_xlim(-0.1, 0.8)
ax.set_ylim(0, 1.0)

rawDescription: Annotation along a curve in matplotlib

description: Annotation along a curve in matplotlib


code:
from Tkinter import *
from turtle import *
import turtle

forward(100)
ts = turtle.getscreen()

ts.getcanvas().postscript(file="duck.eps")

rawDescription: Python Turtle Module- Saving an image

description: Python Turtle Module- Saving an image


code:
class TestMeta(type(TestCase)):
    def patch_method(cls, meth):
        raise NotImplementedError

    def __new__(mcls, name, bases, dct):
        to_patch = []

        for methname, meth in dct.items():
            if methname.startswith('test') and callable(meth):
                to_patch.append(methname)

        cls = super().__new__(mcls, name, bases, dct)

        for methname in to_patch:
            meth = getattr(cls, methname)
            meth = cls.patch_method(meth)
            setattr(cls, methname, meth)

        return cls

class PatchedTestCase(TestCase, metaclass=TestMeta):
    @classmethod
    def patch_method(cls, meth):
        meth = patch('spotlight.middleware.extract_host_name',
                     new=lambda host_name: TEST_DOMAIN)(meth)

        meth = patch('spotlight.middleware.extract_host_key',
                     new=lambda host_key: company_name_to_db(TEST_DOMAIN))(meth)

        return meth

class MyTestCase(PatchedTestCase, TestFreshProvisionedEachTest):
    ...

rawDescription: patching all methods in a subclass in Python

description: Patching all methods in a subclass in Python


code:
with open("myfile.txt") as infile:
    text = infile.read()

# manipulate text here

with open("myfile.txt", "w") as outfile:
    outfile.write(text)

rawDescription: fileinput.Fileinput .read() function for entire file

description: Fileinput.Fileinput .read() function for entire file


rawDescription: Python Random Slice Idiom

description: Python Random Slice Idiom


code:
def pageDownload(webPage):
    # Downloads the page

    while not url.endswith('appendixc'):
        print('Downloading page %s...' % url)
        res = requests.get(url)
        res.raise_for_status()

        soup = bs4.BeautifulSoup(res.text)

        return soup

def getProjects(downloadedPage):
    # gets the projects contents

    soup = downloadedPage
    book =  soup.find_all('div', {'class': "book", 'title' : 'Practice Projects'})
    print(book)

rawDescription: Having Trouble scraping

description: Having Trouble scraping


code:
class BinaryTree():
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

    def tree_insert(self, data):
        if (data < self.data):
            if (self.left != None):
                self.tree_insert(data, self.left)
            else:
                self.left = BinaryTree(data)
        else:
            if (self.right != None):
                self.tree_insert(data, self.right)
            else:
                self.right = BinaryTree(data)

rawDescription: Python not defined recursive function?

description: Python not defined recursive function


code:
def makeList(self, aNode=None):
    if aNode is None:
        aNode = self.root
    treeaslist = [aNode.data]
    if aNode.lChild:
        treeaslist.extend(self.makeList(aNode.lChild))
    if aNode.rChild:
        treeaslist.extend(self.makeList(aNode.rChild))
    return treeaslist

rawDescription: Using self.xxxx as default parameter - Python


code:
import subprocess
proc = subprocess.Popen( [ '/usr/local/bin/monitor' ], stdout=subprocess.PIPE )
stdout, _ = proc.communicate()

rawDescription: Running a "piping" script from an os.system() command


code:
from subprocess import call
call(["appname", "arguments"])

rawDescription: Pass a string to the command line

description: Pass a string to the command line


code:
appended_data = []
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    appended_data.append(data) ## store dataframes in list
appended_data = pd.concat(appended_data, axis=1) ## see documentation for more info

appended_data .to_excel('appedned.xlsx')

rawDescription: Appending pandas dataframes generated in a for loop


code:
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import numpy as np
import dicom

class Annotator(object):
    def __init__(self, axes):
        self.axes = axes

        self.xdata = []
        self.ydata = []

    def mouse_move(self, event):
        if not event.inaxes:
            return

        x, y = event.xdata, event.ydata

        self.xdata.append(x)
        self.ydata.append(y)
        line = Line2D(self.xdata,self.ydata)
        line.set_color('r')
        self.axes.add_line(line)

        plt.draw()

    def mouse_release(self, event):
        # Erase x and y data for new line
        self.xdata = []
        self.ydata = []

path = '../sample.dcm'

data = dicom.read_file(path)

img = data.pixel_array

fig, axes = plt.subplots()
axes.imshow(img[0])
plt.axis("off")
plt.gray()
annotator = Annotator(axes)
plt.connect('motion_notify_event', cursor.mouse_move)
plt.connect('button_release_event', cursor.mouse_release)

axes.plot()

plt.show()

rawDescription: How to add visual annotations to an image using python in a jupyter notebook?

description: Add visual annotations to an image using python in a jupyter notebook


code:
from cocos.director import director
from cocos.layer import base_layers

import sys
import math
import os

import pyglet
import cocos

world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
    def __init__(self, world_width, world_height):
        self.world_width = world_width
        self.world_height = world_height
        super(NetworkMap, self).__init__()
        bg = cocos.layer.ColorLayer(170,170,0,255,width=500,height=500)
        self.px_width = world_width
        self.px_height = world_height
        self.add(bg,z=0)

class TestScene(cocos.scene.Scene):
    def __init__(self):
        super(TestScene,self).__init__()

    def on_enter(self):
        director.push_handlers(self.on_cocos_resize)
        super(TestScene, self).on_enter()

    def on_cocos_resize(self, usable_width, usable_height):
        self.f_refresh_marks()

    def f_refresh_marks(self):
        pass

def main():
    director.init(world_width, world_height, do_not_scale=True)
    scene = TestScene()
    world_map = NetworkMap(world_width, world_height)
    scroller = cocos.layer.ScrollingManager()
    scroller.add(world_map)
    scene.add(scroller)
    director.run(scene)

if __name__ == '__main__': main()

rawDescription: Cocos2d: AttributeError: 'Director' object has no attribute '_window_virtual_width'


code:
import inspect
import functools

def test_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(func.__name__, args, kwargs)
        res = func(*args, **kwargs)
        return res
    return wrapper

def make_test_deco_type(decorator):
    class TestDecoType(type):
        def __new__(cls, clsname, bases, dct):
            for name, value in dct.items():
                if name.startswith('test') and inspect.isroutine(value):
                    dct[name] = decorator(value)
            return super().__new__(cls, clsname, bases, dct)
    return TestDecoType

class Potato(object, metaclass=make_test_deco_type(test_decorator)):
    def test_method(self):
        print('in method')

class Spud(Potato):
    def test_derived(self):
        print('in derived')

rawDescription: Propagating class decorators to inherited classes


code:
import itertools as it
A = {1:'one', 2:'two', 3: 'three'}
list(it.combinations(A.keys(), 2))

rawDescription: iterating in a dictionary.. (double iteration) python

description: Iterating in a dictionary.. (double iteration) python


code: self.clients = []

rawDescription: Multiple, Simultaneous Factories and Protocols in Twisted: Same Service, Different Ports


code:
THREADS_PER_INCH = 4
STEPS_PER_REV = 400

Current_steps = 0

def move(n):
    """
    Given an input, n, measured in inches of position from zero,
    compute the number of steps required to move the {WHAT IS IT?}
    from its current position to the target position. Print the
    number of clockwise/counterclockwise steps required.
    """
    global Current_steps
    target_inches = float(n)
    target_steps = int(target_inches * THREADS_PER_INCH * STEPS_PER_REV)

    if target_steps == Current_steps:
        print("Already here! Nothing to do...")
    elif target_steps > Current_steps:
        print("Turn CCW, {} steps".format(target_steps - Current_steps))
    else: # target_steps < Current_steps
        print("Turn CW, {} steps".format(Current_steps - target_steps))

    Current_steps = target_steps

move(.5)    # move up 1/2 of inch
move(.125)

rawDescription: Having trouble with code and program flow


code:
import requests

def get(url):
    try:
        res = requests.get(url)
        return res.json()
    except:
        return False

data = get('http://example.com')
print(data)

rawDescription: How to get json data from another website in Flask?

description: Get json data from another website in Flask


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

fig,ax = plt.subplots(1)

# Generate some random data
hist1,bins1 = np.histogram(np.random.normal(2,1,1000),bins=np.arange(-2,8,0.5))
hist2,bins2 = np.histogram(np.random.normal(4,1,1000),bins=np.arange(0,10,0.5))

# 'step' draws the lines, 'bar' fills them
ax.step(bins1[:-1],hist1,'k',linestyle='-',linewidth=2,where='post')
ax.bar(bins1[:-1],hist1,width=0.5,linewidth=0,facecolor='k',alpha=0.3)
ax.step(bins2[:-1],hist2,'k',linestyle='--',linewidth=2,where='post')
ax.bar(bins2[:-1],hist2,width=0.5,linewidth=0,facecolor='k',alpha=0.1)

plt.show()

rawDescription: histtype='stepfilled' option using bar function

description: Histtype='stepfilled' option using bar function


code:
class MyDoc(Document):
    pass

coll = MyDoc._get_collection()
coll.database.command(
    "text",
    coll.name,
    search="alice",
    project={"name": 1, "_id": 0},
    limit=10)

rawDescription: Full text search MongoDB/Mongoengine

description: Full text search MongoDB/Mongoengine


code:
import re
p = re.compile(r'<place of birth="([^"]*)')
location_info = "<place of birth=\"Stockholm\">"
match = p.search(location_info)
if match:
    print(match.group(1))

rawDescription: Regex in Python - Substring with single "re.sub" call


code:
linetoremove = input('What line would you like to remove? (1 up to 10)')
with open('highscore.txt', 'r') as fin:
    data = fin.read().splitlines(True)
del data[int(linetoremove)-1]
with open('highscore.txt', 'w') as fout:
    fout.writelines(data)

rawDescription: Removing a line from a text document

description: Removing a line from a text document


code:
import urllib2

request = urllib2.Request('http://example.com/path')
response = urllib2.urlopen(request)
content = response.read()

# now make the second request, just as above

rawDescription: Python script to do a GET request on 2 urls in a cron job


rawDescription: How to split string array to 2-dimension char array in python

description: Split string array to 2-dimension char array in python


code:
_sentinel = object()

class C:
   def __init__(self, x):
      self.x = x

   def f(self, n=_sentinel):
      if n is _sentinel:
          n = self.x

rawDescription: How to use default value for input, which is a member of self (Python)?

description: Use default value for input, which is a member of self (Python)


code:
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')

rawDescription: Making a Foreign Key to an option of two different classes in Django


code:
movedZip = pathZip + zipFileName + ".zip"
os.rename(zipFile, movedZip)

rawDescription: string substitution not working for html insert

description: String substitution not working for html insert


code:
MIGRATION_MODULES = {
     'django.contrib.auth' : 'myapp.auth_migrations',
     'myapp': 'myapp.migrations'  # this line is only to clarify. IT'S NOT NEEDED AT ALL
}

rawDescription: How can I tell django 1.7 to put migration into specific folder

description: Tell django 1.7 to put migration into specific folder


code:
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
import numpy as np

fig = plt.figure(1)
ax = fig.add_subplot(111)

# set up axis
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.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

# draw curve
x = np.arange(-2.5,2.5,0.01)
line, = ax.plot(x, x**2)

#set bounds
ax.set_ybound(-1,7)

# create grid
#ax.xaxis.set_major_locator(MultipleLocator(1))
#ax.xaxis.set_minor_locator(MultipleLocator(0.2))
#ax.yaxis.set_major_locator(MultipleLocator(1))
#ax.yaxis.set_minor_locator(MultipleLocator(0.2))
#ax.xaxis.grid(True,'minor')
#ax.yaxis.grid(True,'minor')
#ax.xaxis.grid(True,'major',linewidth=2)
#ax.yaxis.grid(True,'major',linewidth=2)

#adjust grid on the 2s
#for idx,loc in enumerate(ax.xaxis.get_majorticklocs()):
    #if loc !=0 and loc % 2 == 0: ax.get_xgridlines()[idx].set_c('r')
#for idx,loc in enumerate(ax.yaxis.get_majorticklocs()):
    #if loc !=0 and loc % 2 == 0: ax.get_ygridlines()[idx].set_c('r')

## THIS IS THE EDIT
ax.xaxis.set_minor_locator(MultipleLocator(0.2))
ax.yaxis.set_minor_locator(MultipleLocator(0.2))
ax.xaxis.grid(True,'minor',linewidth=2)
ax.yaxis.grid(True,'minor',linewidth=2)

minor_grid_lines = [tick.gridline for tick in ax.xaxis.get_minor_ticks()]
for idx,loc in enumerate(ax.xaxis.get_minorticklocs()):
    if loc % 2.0 == 0: minor_grid_lines[idx].set_c('r' )
    elif loc % 1.0 == 0: minor_grid_lines[idx].set_c('g' )
    else: minor_grid_lines[idx].set_c( 'b' )

plt.show()

rawDescription: How can I produce student-style graphs using matplotlib?

description: Produce student-style graphs using matplotlib


code:
import wx

class TestPanel(wx.Panel):
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, size=(100, 100), *args)
        self.SetBackgroundColour('red')
        self.Layout()

class ExampleFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent)

        self.panel = wx.Panel(self)
        self.panel.SetMinSize((-1, -1))
        self.panel.SetBackgroundColour(wx.WHITE)

        self.filesize = TestPanel(self.panel, -1)

        hSizer = wx.BoxSizer(wx.HORIZONTAL)
        hSizer.Add(self.filesize, 0, wx.CENTER)

        vSizer = wx.BoxSizer(wx.VERTICAL)
        vSizer.Add(hSizer, 1, wx.EXPAND)
        self.panel.SetSizer(vSizer)

import wx.lib.inspection
app = wx.App(False)
frame = ExampleFrame(None)
frame.Show()
wx.lib.inspection.InspectionTool().Show()
app.MainLoop()

rawDescription: size of panel in panel using wxPython incorrect

description: Size of panel in panel using wxPython incorrect


code:
while True:
        proc1 = subprocess.Popen(cmd.split(), shell=False)
        time.sleep(600)
        os.system("killall -9 mplayer")
        proc1.kill()

rawDescription: Python kill a subprocess(that starts another process) and start it again


code:
from Tkinter import *

root = Tk()
root.geometry("300x200")

navbar = Frame(root, bg="green", width=100)
navbar.pack(anchor=W, fill=Y, expand=False, side=LEFT)  # <----

content_frame = Frame(root, bg="orange")
content_frame.pack(anchor=N, fill=BOTH, expand=True, side=LEFT )

root.mainloop()

rawDescription: Tkinter Frame Doesn't Fill Remaining Space


code:
path = []
previous = destination
while previous != origin:
    path.append(previous)
    previous = predecessor_map[previous]

rawDescription: Build a list using specific keys in a dict (python)?


code:
class __ModuleInitializer:
    def __init__(self):
        print('Module was initialized')

    def __del__(self):
        print('Module was deinitialized')

__module_init = __ModuleInitializer()

rawDescription: Automatic (de)initialization on module import


code:
# celery_experiment.py

from celery import task, group, chain, chord
from celery.signals import task_sent, task_postrun, task_prerun

import time
import logging

import random
random.seed()

logging.basicConfig(level=logging.DEBUG)

### HANDLERS ###
@task_prerun.connect()
def task_starting_handler(sender=None, task_id=None, task=None, args=None, kwargs=None, **kwds):
    try:
        logging.info('[%s] starting' % kwargs['id'])
    except KeyError:
        pass

@task_postrun.connect()
def task_finished_handler(sender=None, task_id=None, task=None, args=None, kwargs=None, retval=None, state=None, **kwds):
    try:
        logging.info('[%s] finished' % kwargs['id'])
    except KeyError:
        pass

def random_sleep(id):
    slp = random.randint(1, 3)
    logging.info('[%s] sleep for %ssecs' % (id, slp))
    time.sleep(slp)

@task()
def thing(id):
    logging.info('[%s] begin' % id)
    random_sleep(id)
    logging.info('[%s] end' % id)

def exec_exp():
    st = thing.si(id='st')
    st_arr = [thing.si(id='st_arr1_a'), thing.si(id='st_arr1_b'), thing.si(id='st_arr1_c'),]
    st_arr2 = [thing.si(id='st_arr2_a'), thing.si(id='st_arr2_b'),]
    st2 = thing.si(id='st2')
    st3 = thing.si(id='st3')
    st4 = thing.si(id='st4')

    grp1 = group(st_arr)
    grp2 = group(st_arr2)

    # chn can chain two groups together because they are seperated by a single subtask
    chn = (st | grp1 | st2 | grp2 | st3 | st4)

    # in chn2 you can't chain two groups together. what will happen is st3 will start before grp2 finishes
    #chn2 = (st | st2 | grp1 | grp2 | st3 |  st4)

    r = chn()
    #r2 = chn2()

rawDescription: celery - chaining groups and subtasks. -> out of order execution

description: Celery - chaining groups and subtasks. -> out of order execution


code:
import numpy
import scipy.optimize as scimin
import matplotlib.pyplot as mpl

datax=numpy.array([1,2,3,4,5]) # data coordinates
datay=numpy.array([2.95,6.03,11.2,17.7,26.8])
constraintmaxx=numpy.array([0]) # list of maximum constraints
constraintmaxy=numpy.array([1.2])

# least square fit without constraints
def fitfunc(x,p): # model $f(x)=a x^2+c
    a,c=p
    return c+a*x**2
def residuals(p): # array of residuals
    return datay-fitfunc(datax,p)
p0=[1,2] # initial parameters guess
pwithout,cov,infodict,mesg,ier=scimin.leastsq(residuals, p0,full_output=True) #traditionnal least squares fit

# least square fir with constraints
def sum_residuals(p): # the function we want to minimize
    return sum(residuals(p)**2)
def constraints(p): # the constraints: all the values of the returned array will be >=0 at the end
    return constraintmaxy-fitfunc(constraintmaxx,p)
pwith=scimin.fmin_slsqp(sum_residuals,pwithout,f_ieqcons=constraints) # minimization with constraint

# plotting
ax=mpl.figure().add_subplot(1,1,1)
ax.plot(datax,datay,ls="",marker="x",color="blue",mew=2.0,label="Datas")
ax.plot(constraintmaxx,constraintmaxy,ls="",marker="x",color="red",mew=2.0,label="Max points")
morex=numpy.linspace(0,6,100)
ax.plot(morex,fitfunc(morex,pwithout),color="blue",label="Fit without constraints")
ax.plot(morex,fitfunc(morex,pwith),color="red",label="Fit with constraints")
ax.legend(loc=2)
mpl.show()

rawDescription: How can I do a least squares fit in python, using data that is only an upper limit?

description: Do a least squares fit in python, using data that is only an upper limit


code:
import subprocess
game = subprocess.Popen(['gnugo', '--mode', 'gtp'], stdin=subprocess.PIPE)
game.stdin.write(b"...")
...

rawDescription: Why does subprocess.Popen hang when opening gnugo?


code:
class MyModel(models.Model):
    timestamp = models.DateTimeField(default=lambda: timezone.now())

rawDescription: Mocking default=timezone.now for unit tests


code:
class Main(webapp2.RequestHandler):
    def get(self):
        self.response.set_cookie('lastvisit', 'test', max_age=360, path='/')

rawDescription: Setting a Cookie on a browser using Python


code:
text="abcd
The seating
\n
fghi
Going Down
\n
"
re.sub(r'(?s)
(.+?)
', '', text)

rawDescription: Regex to remove certain text when matched


code:
def create_sql(self, opts, args):
    #I've left out the error handling.
    strtime = datetime.datetime.now().strftime("%D %H:%M")
    vals = (strtime, opts.message, opts.keywords, False)
    return "insert into mytable values (?, ?, ?, ?)", vals

def create(self, opts, args):
    self.execute(*self.create_sql(opts, args))
    self.commit()

rawDescription: How should I rewrite my database execute/commit to make it amenable to unit testing?


code:
from datetime import date

startdate = date(startyear, 1, 1)
enddate = date(endyear, 12, 31)

rawDescription: How to get starting date from year in python

description: Get starting date from year in python


code:
df_new = df.groupby('video_id').agg({"ios_id": {"count": "count",
                                                "distinct": "unique"},
                                     "feed_position": np.average,
                                     "time_watched": np.sum,
                                     "video_length": np.sum})

rawDescription: How to perform aggregate options on one groupby column, giving two column outputs

description: Perform aggregate options on one groupby column, giving two column outputs


code:
import json

class IntDate(int):
    def __str__(self):
        return r'"\/Date(%s)\/"' % super(IntDate, self).__str__()

print(json.dumps({'date': IntDate(1371071409)}))

rawDescription: Serializing ASP.NET style JSON dates with Python


code:
line_types = {"cr-lf": '\r\n',
              "lf": '\n',
              "cr": '\r'}
document = window.get_active_document()
newline = line_types[document.get_newline_type().value_nick]
insert_mark = document.get_insert()
offset = document.get_iter_at_mark(insert_mark)
line = offset.get_line()
# we subtract 1 because get_chars_in_line() counts the newline character
# there is a special case with the last line if it doesn't have a newline at the end
# we deal with that later
line_length = offset.get_chars_in_line() - len(newline)
end_of_line = document.get_iter_at_line_offset(line, line_length)
if end_of_line.get_char() != newline[0]:
    end_of_line = document.get_iter_at_offset(end_of_line.get_offset()+len(newline))
# if the above code is correct this should select from the current insert point
# to the end of line
document.move_mark(insert_mark, end_of_line)

rawDescription: How to get the length of the current line (or the offset of the end of the line) in a Gedit plugin

description: Get the length of the current line (or the offset of the end of the line) in a Gedit plugin


code:
s = 'blah blah blah... _ABC_superman_is_cool_CBA_ ...blah blah _ABC_blah_CBA_...'
re.findall('_ABC_(.*?)_CBA_', s)

rawDescription: Regex: match sequence of not a certain string


code:
for t in results:
   (jName, kName) = t

   union(jName, kName)

rawDescription: Is there a friendly name for this data structure?


code:
replacements = {2:0,3:5,15:7,25:30,115:120,1215:1220}

with open('input.txt', 'r') as fin, open('output.txt', 'w') as fout:
    pos_a = 22 # 0-indexed position of 'A' in every line
    for line in fin:
        left_side = line[:pos_a + 1]
        num_to_convert = line[pos_a + 1: pos_a + 5]
        right_side = line[pos_a + 5:]

        # String formatting to preserve padding as per original file
        newline = '{}{:>4}{}'.format(left_side,
                                        replacements[int(num_to_convert)],
                                        right_side)
        fout.write(newline)

rawDescription: Python replace integers by integers only at particular location


code:
from django.db import models

class MyModel(models.Model):
  created = models.DateField(auto_now_add=True)
  modified = models.DateField(auto_now=True)

rawDescription: Designing a model that retains revision history


code: return {m.name: [func(g, m) for g in groups] for m in messages}

rawDescription: How do we use comprehension here

description: How do we use comprehension here


code:
def __init__(self, name):
    self.name = name
    self.hp = 300
    ...
    self.weapon = None

rawDescription: Class attributes not passing to objects

description: Class attributes not passing to objects


code: [elem for i, elem in enumerate(A) if i %10 in (0, 1)]

rawDescription: Getting two consecutive elements from a list every ten elements


rawDescription: How can I use python itertools.groupby() to group a list of strings by their first character?

description: Use python itertools.groupby() to group a list of strings by their first character


code:
a = 0xA
b = 0xa
a + b
hex(a + b)

rawDescription: Is there a way to do math with hexadecimals in Python 3?


code:
import tokenize
if sys.hexversion >= 0x03000000d:
    tokenize_func = tokenize.tokenize
else:
    tokenize_func = tokenize.generate_tokens

rawDescription: Python 3: tokenize library changes

description: Python 3: tokenize library changes


code:
import re
results = re.findall(r'\bhttp://www\.someDomainName\.com/\d+\b', long_string)

rawDescription: How do I extract some string from a long string in Python?

description: Extract some string from a long string in Python


code:
from threading import Thread
from time import sleep

def call_at_interval(period, callback, args):
    while True:
        sleep(period)
        callback(*args)

def setInterval(period, callback, *args):
    Thread(target=call_at_interval, args=(period, callback, args)).start()

def hello(word):
    print("hello", word)

setInterval(10, hello, 'world!')

rawDescription: How set a loop that repeats at a certain interval in python?


code:
from elasticsearch import Elasticsearch

es = Elasticsearch()

es.update(
    index="test",
    doc_type="test1",
    id="1",
    body={"script": "ctx._source.tags+=new_tag",
          "params": {
             "new_tag" : "search"
            }
          }
    )

rawDescription: Not clear how to upsert ElasticSearch using python elasticsearch


rawDescription: Resetting the values that do not meet the specified condition


code:
import random
import unittest

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.seq = range(10)

    def test_shuffle(self):
        # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, range(10))

        # should raise an exception for an immutable sequence
        self.assertRaises(TypeError, random.shuffle, (1,2,3))

    def test_choice(self):
        element = random.choice(self.seq)
        self.assertTrue(element in self.seq)

    def test_sample(self):
        with self.assertRaises(ValueError):
            random.sample(self.seq, 20)
        for element in random.sample(self.seq, 5):
            self.assertTrue(element in self.seq)

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

rawDescription: Dependent unit tests

description: Dependent unit tests


code:
import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'

rawDescription: Serializing list to JSON

description: Serializing list to JSON


code:
class Products(models.Model):
    ...
    def get_absolute_url(self):
        return "/products/%s/" % self.slug

rawDescription: (haystack + whoosh) {{ result.object.get_absolute_url }} is not working


code:
import db # assume this is your db module

class Class(object):
    def __init__(self):
        self.id = None
        self.name = None

    def get_by_id(self, id):
        records = db.execute('select * from table where id=%s' % str(id))
        if records:
            self.id = records[0]['id']
            self.name = records[0]['name']

    def save(self):
        db.execute('update table set name=%s where id=%s' % (self.name, str(self.id)))

rawDescription: Addressing instance name string in __init__(self) in Python


code:
for index, row in rche_df.iterrows():
    if isinstance(row.wgs1984_latitude, float):
        row = row.copy()
        target = row.address_chi
        dict_temp = geocoding(target)
        rche_df.loc[index, 'wgs1984_latitude'] = dict_temp['lat']
        rche_df.loc[index, 'wgs1984_longitude'] = dict_temp['long']

rawDescription: Updating value in iterrow for pandas

description: Updating value in iterrow for pandas


rawDescription: python select all but one column from multidimensional array

description: Python select all but one column from multidimensional array


code:
def listFolders(self, path):
    fId = self.getPathId(path) #get the id of the parent folder
    files = self.drive_service.children().list(folderId=fId).execute() #Request children
    files = files["items"] #All of the items in the folder

    folders = []
    for i in range(len(files)):
        sId = files[i]["id"]
        sFile = self.drive_service.files().get(fileId=sId).execute()
        if sFile["labels"]["trashed"] == False and sFile["mimeType"] == "application/vnd.google-apps.folder":
            self.addPath(path+sFile["title"]+"/", sFile["id"])
            folders.append(sFile["title"])
    return folders

rawDescription: Google Drive folder ID

description: Google Drive folder ID


rawDescription: Python - How to perform indirect sorting with a user-defined function?


code:
result = (csproperties
          .replace(oms + "CSLicenseKey=", oms + "CSLicenseKey="+ keystore[n])
          .replace(oms + "LogFile=",
                   oms + "LogFile=" + logs + 'ContentServer_' + cs_id[n] +'.log')
          .replace(oms + "PABName=",
                   oms + "PABName=" + pse + 'ContentServer_' + cs_id[n] + '.PSE'))
...
f.write(result)

rawDescription: read and write only a line not the full file

description: Read and write only a line not the full file


code:
participant_list = [ { 'Id': 5, 'name':'bob'}, {'Id': 4, 'name': 'sally'} ]
", ".join([str(p["Id"]) for p in participant_list])

rawDescription: Python way to join subsets of an element into a string?


code:
df
df.mode(axis=1)

rawDescription: pandas: how to find the most frequent value of each row?

description: Pandas: how to find the most frequent value of each row


code:
class EditableListCtrl(wx.ListCtrl, listmix.TextEditMixin,listmix.CheckListCtrlMixin):
    ''' TextEditMixin allows any column to be edited. '''

    #----------------------------------------------------------------------
    def __init__(self, parent, ID=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0):
        """Constructor"""
        wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
        listmix.TextEditMixin.__init__(self)
        listmix.CheckListCtrlMixin.__init__(self)

rawDescription: combine wxpython EditableListCtrl AND CheckListCtrlMixin

description: Combine wxpython EditableListCtrl AND CheckListCtrlMixin


code: from math import sqrt as _sqrt

rawDescription: Not exporting functions from Python module


code:
my_foo_bar = FooBar.objects.create(field=value)
my_foo_bar.images.add(my_foo_image)
# or
FooImage.objects.create(model=my_foo_bar, image=my_image)

rawDescription: Add images to a children class

description: Add images to a children class


code:
# For backwards compatibility, provide lower-case names for our Date
# and Angle classes, and also allow "Lon" to be spelled "Long".
date = Date
angle = Angle
LongLatCoordinate = LonLatCoordinate

rawDescription: Difference between ephem.date(. . .) and ephem.Date(. . .) in PyEphem


code:
import re
text = '''age=12,name=bob,hobbies="games,reading",phrase="I'm cool!"'''
regex = re.compile(
    r'''
        (?P<key>\w+)=      # Key consists of only alphanumerics
        (?P<quote>["']?)   # Optional quote character.
        (?P<value>.*?)     # Value is a non greedy match
        (?P=quote)         # Closing quote equals the first.
        ($|,)              # Entry ends with comma or end of string
    ''',
    re.VERBOSE
    )

d = {match.group('key'): match.group('value') for match in regex.finditer(text)}

print(d)  # {'name': 'bob', 'phrase': "I'm cool!", 'age': '12', 'hobbies': 'games,reading'}

rawDescription: How to split comma-separated key-value pairs with quoted commas

description: Split comma-separated key-value pairs with quoted commas


code:
class SharedDataClass(object):
  shared_data = SharedData()

rawDescription: Shared Memory for Python Classes

description: Shared Memory for Python Classes


code: link_string = '<a href="/search/?q=%%23%s"> %s </a>'

rawDescription: escape % character in Python

description: Escape % character in Python


code:
import gtk, glib

class example:
    def __init__(self):
        window = gtk.Window()
        window.set_title("example")
        window.resize(600,400)
        box = gtk.HBox(homogeneous = True, spacing = 2)
        self.buf = gtk.TextBuffer()
        self.buf.connect("changed", self.buf_on_change)
        textInput = gtk.TextView(self.buf)
        box.add(textInput)
        self.lbl = gtk.Label()
        box.add(self.lbl)
        window.add(box)
        window.connect("destroy", gtk.main_quit)
        window.show_all()

        self.timer = glib.timeout_add(1000, self.renderText)

    def buf_on_change(self, buf):
        glib.source_remove(self.timer)
        self.timer = glib.timeout_add(1000, self.renderText)

    def renderText(self):
        txt = self.buf.get_text(*self.buf.get_bounds())
        # perform computation-intensive text-manipulation here
        self.lbl.set_text(txt)
        return False

if __name__ == '__main__':
    example()
    gtk.main()

rawDescription: how to wait for a pause in user input in a gtk.TextBuffer?

description: Wait for a pause in user input in a gtk.TextBuffer


code:
Score = {}
for id, document in TD.iteritems():
    counts = Score[id] = Counter()
    for otherid, otherdocument in TD.iteritems():
        if otherid == id:
            continue  # Skip current document
        counts.update(document.viewkeys() & otherdocument.viewkeys())

rawDescription: Updating my dictionary in python

description: Updating my dictionary in python


code:
import os

def CalcAndDisplayShipping(weight):

   UNDER_SIX = 1.1
   TWO_TO_SIX = 2.2
   SIX_TO_TEN = 3.7
   OVER_TEN = 3.8

   shipping = 0.0

   if weight > 10:
      shipping = weight * OVER_TEN
   elif weight > 6:
      shipping = weight * SIX_TO_TEN
   elif weight > 2:
      shipping = weight * TWO_TO_SIX
   else:
      shipping = weight * UNDER_SIX

   print ("Shipping Charge: $", shipping)

weight = float(input("Enter package weight: "))

CalcAndDisplayShipping(weight)

rawDescription: python passing parameter modules

description: Python passing parameter modules


code:
def oneOfK(label):
    rows = label.shape[0];
    rowsIndex=np.arange(rows,dtype="int")
    oneKLabel = np.zeros((rows,10))
    #oneKLabel = np.zeros((rows,np.max(label)+1))
    oneKLabel[rowsIndex,label.astype(int)]=1
    return oneKLabel

rawDescription: Built in function in numpy to interpret an Integer as a numpy array with index = integer value set


code:
import django.utils.timezone as tz
import datetime

my_tz = tz.get_default_timezone() # The one in settings.TIME_ZONE

# My dates:
date1 = tz.make_aware(datetime.datetime.now(), my_tz)
date2 = tz.make_aware(datetime.datetime(2015,5,1), my_tz)

# Get timezone names
date1.tzname() # CST
date2.tzname() # CDT

# Get offset from UTC
date1.utcoffset() # datetime.timedelta(-1, 64800) is UTC-6
date2.utcoffset() # datetime.timedelta(-1, 68400) is UTC-5

# Get daylight saving time
date1.dst() # datetime.timedelta(0)
date2.dst() # datetime.timedelta(0, 3600) is +1 hour

rawDescription: Get timezone offset in django/python

description: Get timezone offset in django/python


code:
servoMin = 500
servoMid = 1500
servoMax = 2500
servoTilt = 1500
servostep = 100

def servo1_up():
  global servoTilt
  servoTilt += servostep
  if servoTilt > servoMax:
    servoTilt = servoMax
  port.write("#15P%dT100\r\n" % servoTilt)

rawDescription: servo increment in python

description: Servo increment in python


code:
class SystemTrayIcon(QtGui.QSystemTrayIcon):
    def __init__(self, parent = None):
        QtGui.QSystemTrayIcon.__init__(self, icon, parent)
        traySignal = "activated(QSystemTrayIcon::ActivationReason)"
        self.connect(self, QtCore.SIGNAL(traySignal), self._activateRoutine)
        self.balloon = balloonWidget(name)

    def _activateRoutine(self, reason):
        if reason == QtGui.QSystemTrayIcon.Trigger:
            self.balloon.show(self.geometry())

class balloonWidget(QtGui.QWidget):
    def __init__(self,name):
        QtGui.QWidget.__init__(self, parent = None, flags = QtCore.Qt.Popup)

        self.name = name

        self.offsetX = 10
        self.offsetY = 10

        self.outInfo = QtGui.QLabel(self)

        self.setStyleSheet("QWidget {border:5px solid rgb(170, 170, 255);}")

    def show(self,coord):
        richText = tr('Any text with Rich Format')
        self.outInfo.setText(richText)
        self.outInfo.show()
        self.adjustSize()

        origin = QtGui.QDesktopWidget().availableGeometry().bottomRight()

        if coord.y() < origin.y()/2:
            moveY = coord.bottomLeft().y() + self.offsetY
        else:
            moveY = coord.topLeft().y() - (self.height() + self.offsetY)

        if coord.x() + self.width() + self.offsetX >= origin.x():
            moveX = origin.x() - (self.width() + self.offsetX)
        else:
            moveX = coord.x()

        self.move(moveX,moveY)
        self.setVisible(True)

    def closeEvent(self, event):
        event.ignore()
        self.hide()

    def mousePressEvent(self, event):
        self.close()

rawDescription: PyQt RichText Formatting in system tray tooltip


code:
class YourHandler(tornado.web.RequestHandler):
    ...
    def write(self, stuff):
        super(YourHandler, self).write('callback(' + json.dumps(stuff) + ')')
        self.set_header('Content-Type', 'application/javascript')

rawDescription: JSONp requests with tornado

description: JSONp requests with tornado


code:
size = 5
inner_size = size - 2
print ('*' * size)
for i in range(inner_size):
    print ('*' + ' ' * inner_size + '*')
print ('*' * size)

rawDescription: Drawing a hollow asterisk square

description: Drawing a hollow asterisk square


code:
data = [('1998-01-20',8) , ('1998-01-22',4) , ('1998-06-18',8 ) , ('1999-07-15' , 7), ('1999-07-21',1)]
dictionary = dict()
for (mydate, val) in data: #
    ym = mydate[0:7]    # the key is only the year month combination (i.e. '1998-01' for example)
    dictionary[ym] = dictionary.get(ym, 0) + val  # return the value for that key or return default 0 (and create key)

data_aggregated = [(key, val) for (key, val) in dictionary.iteritems()] # if you need it back in old format

rawDescription: how to aggregate elements of a list of tuples if the tuples have the same first element?

description: Aggregate elements of a list of tuples if the tuples have the same first element


code:
for product in p:
    dollar_price = product.dollar_price(dollar)
    product.new_field = dollar_price # This line is the problem

rawDescription: How to insert a new field in a queryset object?

description: Insert a new field in a queryset object


code:
backoff_factor=2.0,
initial_delay=0.1,
max_delay=10.0,
min_retries=3,
max_retries=6,
max_retry_period=30.0,

rawDescription: What is App Engine's Cloud Storage Client Library default retry logic?


code:
def selectFile():
    lineEdit.setText(QFileDialog.getOpenFileName())

pushButton.clicked.connect(selectFile)

rawDescription: PyQt4 File select widget

description: PyQt4 File select widget


code:
from scrapy.http import FormRequest
from scrapy.spider import BaseSpider

class MySpider(BaseSpider):
    name = "myspider"
    allowed_domains = ["http://164.100.167.12/"]
    report_date = '30/07/2013'

    def start_requests(self):
        yield FormRequest(url='http://164.100.167.12/pwd/report.php',
                          method='POST',
                          callback=self.parse_page,
                          formdata={'reportdate': self.report_date})

    def parse_page(self, response):
        # save the pdf
        with open('output.pdf', 'w') as f:
            f.write(response.body)

rawDescription: How to write input data processor from known html id?

description: Write input data processor from known html id


code:
class Thing(object):
    all = {}

    def __init__(self, id, also, etc):
        self.id = id
        self.all[id] = self

    @classmethod
    def by_id(cls, id):
        return cls.all[id]

rawDescription: Python Reflection

description: Python Reflection


code:
import sys
sys.ps1 = '$$$ '

rawDescription: PS1() in Python like in Octave?

description: PS1() in Python like in Octave


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

def main():
    t = np.linspace(0, 4*np.pi, 1000)
    fig1, ax = plt.subplots()
    ax.plot(t, np.cos(t))
    ax.plot(t, np.sin(t))

    inception(inception(fig1))
    plt.show()

def fig2rgb_array(fig):
    fig.canvas.draw()
    buf = fig.canvas.tostring_rgb()
    ncols, nrows = fig.canvas.get_width_height()
    return np.fromstring(buf, dtype=np.uint8).reshape(nrows, ncols, 3)

def inception(fig):
    newfig, ax = plt.subplots()
    ax.imshow(fig2rgb_array(fig))
    return newfig

main()

rawDescription: matplotlib: render into buffer / access pixel data

description: Matplotlib: render into buffer / access pixel data


code:
from decimal import *
print(Decimal(8.0) / Decimal(3.0))

rawDescription: Python dividing numbers

description: Python dividing numbers


code:
def get_db_info():

    rds_conn = boto.connect_rds2(profile_name=AWS_PROFILE)
    if not rds_conn:
        print(_red('Cannot connect to AWS.RDS'))
        return

    instances = rds_conn.describe_db_instances()
    if not instances:
        print(_red('No instances found'))
        return

    inst = instances['DescribeDBInstancesResponse']['DescribeDBInstancesResult']['DBInstances'][0]

    dbinfo = {}
    endpoint = inst['Endpoint']
    dbinfo['VPCSecurityGroupId'] = inst['VpcSecurityGroups'][0]['VpcSecurityGroupId']
    dbinfo['dbSecurityGroupName'] = inst['DBSecurityGroups'][0]['DBSecurityGroupName']

    print('')
    print(_blue('db Info ===========>\n'))
    for item in dbinfo:
        print(_green('%20s : %s' % (item, dbinfo[item])))

rawDescription: Access RDS security Group using Boto

description: Access RDS security Group using Boto


code:
g = df.groupby("type")
g.mean()

rawDescription: grouping dataframes in pandas efficiently?

description: Grouping dataframes in pandas efficiently


code:
#!/usr/bin/env python

import paramiko
import getpass

# make a local test file
open('deleteme.txt', 'w').write('you really should delete this]n')

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
    ssh.connect('localhost', username=getpass.getuser(),
        password=getpass.getpass('password: '))
    sftp = ssh.open_sftp()
    sftp.chdir("/tmp/")
    try:
        print(sftp.stat('/tmp/deleteme.txt'))
        print('file exists')
    except IOError:
        print('copying file')
        sftp.put('deleteme.txt', '/tmp/deleteme.txt')
    ssh.close()
except paramiko.SSHException:
    print("Connection Error")

rawDescription: Paramiko / scp - check if file exists on remote host


code:
from operator import itemgetter

all = [ [2,2],[2,1],[1,2],[1,1] ]
result = sorted(all, key=itemgetter(0,1))

rawDescription: how to do this in Python (perl snippet to sort a 2D array)

description: Do this in Python (perl snippet to sort a 2D array)


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

def mjrFormatter(x, pos):
    return "$2^{{{0}}}$".format(x)

def mjrFormatter_no_TeX(x, pos):
    return "2^{0}".format(x)

ax = plt.gca()
ax.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter))
plt.draw()

rawDescription: matplotlib: change yaxis tick labels

description: Matplotlib: change yaxis tick labels


code:
obj = Template("$$$$Tag$$$$")
obj.safe_substitute({})
obj.safe_substitute({'Tag':1})
obj = Template("$$$Tag$$$") #First $ escapes the second $
obj.safe_substitute({'Tag':1})

rawDescription: Python String Templates

description: Python String Templates


code:
class Foo(object):

    def __init__(self):
        self.values = {'a': 0, 'b': 0}

    def bar(self, cmd):
        if cmd == "do_this":
            index = 'a'
        elif cmd == "do_that":
            index = 'b'

        filename = "file-%d.txt" % index
        f = open("filename", "w")

        ...

        self.values[index] = something

rawDescription: Python Reference to Member Variable Which is Immutable


code:
import urllib2
import json
import csv

def getRows(data):
    # ?? this totally depends on what's in your data
    return []

url = "http://www.yahoo.com/something"
data = urllib2.urlopen(url).read()
data = json.loads(data)

fname = "mydata.csv"
with open(fname,'wb') as outf:
    outcsv = csv.writer(outf)
    outcsv.writerows(getRows(data))

rawDescription: Download JSON data and convert it to CSV using Python


code:
import threading

class Server(threading.Thread):
    def __init__(self):
        super(Server, self).__init__()
        self.messages = []
        self.running = False

    def run(self):    # changed name start for run
        self.running = True
        self.work()

    def send_mess(self, message):
        self.messages.append(message)

    def handle_mess(self):
        for mess in self.messages:
            self.do_calculations(mess)

    def work(self):
        while self.running:
            self.handle_mess()
            self.do_some_important_stuff()

    def do_some_important_stuff(self):
        pass
    def do_calculations(self):
        pass

s = Server()
s.start()    # now is in another another thread running
s.join()     # wait for it to finnish

rawDescription: Can I make one method of class run in background?

description: Make one method of class run in background


code:
class MyView(generic.TemplateView):
    template_name = 'template_name.html'

    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        context.update({'key1': 'value1'})
        return context

rawDescription: Returning template_name + args in class-based views


code:
#! /usr/bin/python
import glob
import shutil

path = '/xxxx/Dir/*.txt'
files=glob.glob(path)
for file in files:
    f=open(file)
    total = 0
    for line in f:
        if "TPR_4" in line:
            total += 1
            if total > 1:
                break  # no need to go through the file any further
    f.close()
    if total == 1:
        shutil.copy(file, 'xxxx/Test/')

rawDescription: Python: Read multiple files and move them to a directory according to their content


code:
lines = []
for line in driver.page_source.splitlines():
    lines.append(line)
    if 'LABEL TEXT 1' in line:
        id_l1 = lines[-2].split('"', 2)[1]

rawDescription: Webdriver - Locate Input via Label (Python)


code:
class AuthenticationMiddleware(object):
    def process_request(self, request):
        assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."

        request.user = SimpleLazyObject(lambda: get_user(request))

rawDescription: where django store request['user'] in what file

description: Where django store request['user'] in what file


code:
maxlength = 0
maxwords = [ ]  # unnecessary: will be re-initialized below
for word in inputcorpus:
    if len(word) > maxlength:
        maxlength = len(word)
        maxwords = [ word ]
    elif len(word) == maxlength:
        maxwords.append(word)

rawDescription: Is this an efficient way of finding the longest words (plural) in a string?


code: ctypes.windll.user32.SystemParametersInfoW(0x14, 0, 'C:\\somepic.jpg', 0)

rawDescription: Python Windows Wallpaper

description: Python Windows Wallpaper


code:
d = {}
with open('t.txt') as f:
  for line in f:
     if line.startswith('>'):
        key = line.strip()
        if key not in d:
            d[key] = []
     else:
        d[key].append(line.strip())

d
sequence_list = [''.join(k) for k in d.values()]
sequence_list

rawDescription: Compiling lines from file that are separated by a certain element . Python


code:
df
df.index = pd.to_datetime(df.index)
df
df.sort_index()  # you can also do this inplace=True

rawDescription: How to apply to_datetime or with sort_index so that the dates are sorted?

description: Apply to_datetime or with sort_index so that the dates are sorted


code:
import numpy as np

data = numpy.array(data)
result = numpy.zeros(shape=(data[:,0].max()+1, data[:,1].max()+1), dtype=int)
result[data[:,0], data[:,1]] = data[:,2]

rawDescription: How to create a 2d numpy array from a list of tuples

description: Create a 2d numpy array from a list of tuples


code:
results=[key for key, value in adictionary.items() if str(key).startswith('target')
             and value > 0 ]

rawDescription: Python list syntax help

description: Python list syntax help


code:
sum = np.zeros(len(data[0]))

for vector in data[1:]:
    vector = map(float, vector)
    sum = np.add(vector, sum)

rawDescription: Using iterator to sum arrays in python

description: Using iterator to sum arrays in python


code:
L = [['Text', 'Count']]
for line in inputFile:
    L.append([var, var5])

rawDescription: Transform list output from for loop

description: Transform list output from for loop


rawDescription: Select from dictionary using pandas series


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

    def _get_x(self):
        """I'm the 'x' property."""
        return self._x
    def _set_x(self, value):
        self._x = value
    def _del_x(self):
        del self._x
    x = property(_get_x, _set_x, _del_x)

rawDescription: why my code run wrong ,it is about '@property'

description: Why my code run wrong ,it is about '@property'


code:
head = repo.lookup_reference('HEAD').resolve()
head = repo.head

branch_name = head.name

rawDescription: How to get the current checked out Git branch name through pygit2?

description: Get the current checked out Git branch name through pygit2


code:
if self.game_over:
    self.game_over = False
    self.game.start_new_game()
    # ...

rawDescription: Wait for user input in Kivy

description: Wait for user input in Kivy


code:
import tkinter as tk
from tkinter import ttk

LARGE_FONT= ("Verdana", 12)

class MainWindowController(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.container = tk.Frame(self)
        self.container.grid_rowconfigure(0, weight=1)
        self.container.grid_columnconfigure(0, weight=1)
        self.container.pack(side="top", fill="both", expand=True)

        self.frames = {}

        for F in (StartPage, PageOne, PageTwo):
            frame = F(self.container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.so = tk.Text(self.container, state="disabled", font=("Arial", 14),
                          width=70, height=12, bd=1, relief="groove")
        self.so.grid(row=1, column=0, sticky="nsew", pady=(60, 0))
        self.update_stack_order()

        self.show_frame(StartPage)

    def update_stack_order(self):
        self.so.config(state="normal")
        self.so.delete("1.0", "end")
        self.so.insert("end", "Stack order of the widgets of self.container (0 means top)\n\n\n")
        for i, child in enumerate(reversed(self.container.winfo_children())):
            self.so.insert("end", str(i) + "\t" + repr(child) + "\n\n")
        self.so.config(state="disabled")

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        self.update_stack_order()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        label = ttk.Label(self, text="START PAGE", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button = ttk.Button(self, text="Visit Page 1",
                            command=lambda: controller.show_frame(PageOne))
        button.pack()

        button2 = ttk.Button(self, text="Visit Page 2",
                            command=lambda: controller.show_frame(PageTwo))
        button2.pack()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        label = ttk.Label(self, text="PAGE ONE", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button1 = ttk.Button(self, text="Back to Home",
                            command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 = ttk.Button(self, text="Page Two",
                            command=lambda: controller.show_frame(PageTwo))
        button2.pack()

class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        label = ttk.Label(self, text="PAGE TWO", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button1 = ttk.Button(self, text="Back to Home",
                            command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 = ttk.Button(self, text="Page One",
                            command=lambda: controller.show_frame(PageOne))
        button2.pack()

app = MainWindowController()
app.mainloop()

rawDescription: Warning users that unsaved changes will be lost


code:
#This will create the object only once
return User.get_or_insert(key_name="id%d" % unique_user_id,
                          id=unique_user_id,
                          name = current_name)

#This will create the object and update some properties
#You can't change the value of key_name
user = User.get_or_insert(key_name="id%d" % unique_user_id,
                          id=unique_user_id)
user.name = name
user.put()
return user

rawDescription: Is auto_now_add property updated each time when put is called?


rawDescription: How to order a list of tuples by the integer value of a certain index of each, in Python?

description: Order a list of tuples by the integer value of a certain index of each, in Python


code: newChaps = sorted(chaps, key=lambda obj: obj.version)

rawDescription: Sorting chapters numbers, like 1.2.1 or 1.4.2.4


code:
df['time'] = pd.to_datetime(df['time'], unit='s')
df = df.set_index('time').tz_localize('US/Eastern').tz_convert('UTC').tz_convert(None).reset_index()
df['time'] = df['time'].dt.date

rawDescription: Pandas date time formatting with timezone shifting


code:
from Tkinter import *

class CanvasDemo(Frame):
    def __init__(self, width=200, height=200):
        Frame.__init__(self, root)
        self.canvas = Canvas(self)
        self.canvas.pack(fill="both", expand="1")
        self.canvas.create_rectangle(50, 25, 150, 75, fill="bisque", tags="r1")
        self.canvas.create_line(0,0, 50, 25, arrow="last", tags="to_r1")
        self.canvas.bind("<B1-Motion>", self.move_box)
        self.canvas.bind("<ButtonPress-1>", self.start_move)

    def move_box(self, event):
        deltax = event.x - self.x
        deltay = event.y - self.y
        self.canvas.move("r1", deltax, deltay)
        coords = self.canvas.coords("to_r1")
        coords[2] += deltax
        coords[3] += deltay
        self.canvas.coords("to_r1", *coords)
        self.x = event.x
        self.y = event.y

    def start_move(self, event):
        self.x = event.x
        self.y = event.y

root = Tk()
canvas = CanvasDemo(root)
canvas.pack()
mainloop()

rawDescription: How to connect two state circles with an arrow in tkinter?

description: Connect two state circles with an arrow in tkinter


rawDescription: How to hide Chromedriver console window?

description: Hide Chromedriver console window


rawDescription: Python: can you tell the name of the calling shell?


code:
class CaseInsensitiveMultiDict(MultiDict):
    def __init__(self, mapping=None):
        super().__init__(mapping)
        # map lowercase keys to the real keys
        self.lower_key_map = {key.lower(): key for key in self}

    def __contains__(self, key):
        return key.lower() in self.lower_key_map

    def getlist(self, key):
        return super().getlist(self.lower_key_map.get(key.lower()))

    def pop(self, key):
        return super().pop(self.lower_key_map.get(key.lower()))

class CaseInsensitiveArgument(Argument):
    def source(self, request):
        return CaseInsensitiveMultiDict(super().source(request))

parser = RequestParser(argument_class=CaseInsensitiveArgument)

rawDescription: Can Flask-Restful accept case-insensitive argument names?


code:
class listener(StreamListener):

    def __init__(self):
        super().__init__()
        self.counter = 0
        self.limit = 10

    def on_status(self, status):
        try:
            userid = status.user.id_str
            geo = str(status.coordinates)
            if geo != "None":
                print(userid + ',' + geo)
            else:
                print("No coordinates")
            self.counter += 1
            if self.counter < self.limit:
                return True
            else:
                twitterStream.disconnect()
        except BaseException as e:
            print('failed on_status,',str(e))
            time.sleep(5)

rawDescription: Limit tweepy stream to a specific number


code: __eq__(self, other)

rawDescription: How does this App Engine Ndb syntax work?


code:
def loadFinished():
    elements = web.page().mainFrame().findAllElements(css_selector)
    for index in range(elements.count()):
        print(elements.at(index).geometry())

rawDescription: get coordinates of an element in QWebView of QtWebKit, PyQt4 and autoscroll to its position

description: Get coordinates of an element in QWebView of QtWebKit, PyQt4 and autoscroll to its position


rawDescription: How can I add some string to a list in order to make a count word? [Python]

description: Add some string to a list in order to make a count word? [Python]


code:
import someModule
someModule.init(NECESSARY_DATA)
x = someModule.someClass(range(1, 5))

rawDescription: Pass Variable On Import

description: Pass Variable On Import


code:
# Widget that modifies the output of a FileField
class OutputWidget(AdminFileWidget):
    # Overloaded django magic
    def render(self, name, value, attrs=None):
        output = []
        # This is the place where we edit the output
        if value and getattr(value, "url", None):
            image_url = value.url
            output.append(u' ' % (image_url, image_url, image_url))
        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))

# ModelAdmin class that is applied to the model
class MyModelSettings(admin.ModelAdmin):
    # Overloaded django magic
    def formfield_for_dbfield(self, db_field, **kwargs):
        # Look for the field we want to edit and register the widget with it
        if db_field.name == 'nameOfFieldIWantToEdit':
            request = kwargs.pop("request", None)
            kwargs['widget'] = OutputWidget
            return db_field.formfield(**kwargs)
        return super(MyModelSettings,self).formfield_for_dbfield(db_field, **kwargs)

# Register my overloaded settings with the model
admin.site.register(MyModel, MyModelSettings)

rawDescription: Adding custom button or a tag to django admin


code:
r = datetime.datetime(*time.strptime(s, "%Y-%m-%d %H:%M:%S")[:6])
r.year

rawDescription: How to access values in datetime Python?

description: Access values in datetime Python


code: myfield = fields.Many2one("res.partner", domain=[('mygroup', '=', 'yourgroup')])

rawDescription: How to add group based filter for many2one field in odoo

description: Add group based filter for many2one field in odoo


code:
def but_last(p):
    first = True
    for x in p:
        if not first:
            yield last
        first = False
        last = x

for layerId, layer in but_last(enumerate(neurons)):
    do_your_stuff(layerId, layer)

rawDescription: How to end loop one iteration earlier?

description: End loop one iteration earlier


code:
q_sum = (session.query(
            Projects.id.label("project_id"),
            func.sum(case([(Tasks.complete == True, 1)], else_=0)).label("x"),
            func.sum(case([(and_(
                Tasks.deadline != None,
                Tasks.completeDate != None,
                Tasks.deadline > Tasks.completeDate), 1)],
                else_=0)).label("y"),
            func.count(Tasks.id).label("total"),
            )
        .join(Goals, Projects.goals)
        .join(Strategies, Goals.strategies)
        .join(Tasks, Strategies.tasks)
        .group_by(Projects.id)
        )

# (project_id, x, y, total)
for p in q_sum:
    print(p)

rawDescription: database field created by a relational field in flask sqlalchemy models

description: Database field created by a relational field in flask sqlalchemy models


code:
try:
    import simplejson as json
except ImportError:
    import json

rawDescription: Python JSON decoding performance

description: Python JSON decoding performance