Skip to content

Instantly share code, notes, and snippets.

@stephenmcd
stephenmcd / cache_stats.py
Created August 3, 2012 02:40
Quick cache stats scraper using django-debug-toolbar's cache panel.
#!/usr/bin/env python
import os
import sys
import urllib
name, url, num = sys.argv[1:]
print name, url, num
first = not os.path.exists("output.csv")
f = open("output.csv", "a")
@stephenmcd
stephenmcd / trans_stats.py
Created June 18, 2012 11:33
A super-messy Django translation file parser.
import os
translators = []
languages = []
for root, dirs, files in os.walk("mezz_current/mezzanine"):
if root.endswith("locale"):
languages.extend(dirs)
for name in files:
if name == "django.po":
@stephenmcd
stephenmcd / requirements_report.py
Created June 18, 2012 00:45
Build a report of Python requirements for multiple repositories.
#!/usr/bin/env python
"""
Given the current directory contains multiple repositories, each with a
requirements/project.txt file, build a report of all requirements.
"""
import os
reqs = {}
@stephenmcd
stephenmcd / slumber_django_testclient.py
Created February 8, 2012 04:58
Subclass of ``slumber.API`` that patches ``requests.request`` with Django test client compatible HTTP requests.
from collections import namedtuple
from django.test import TestCase
from requests.auth import HTTPBasicAuth
import slumber
class SlumberTestClientAPI(slumber.API):
"""
Subclass of ``slumber.API`` that patches ``requests.request``
@stephenmcd
stephenmcd / declauser.py
Created January 21, 2012 02:16
Convert 3-clause BSD licenses to 2-clause in a directory of projects, commit and push to BitBucket and GitHub
#!/usr/bin/env python
import os
cwd = os.path.abspath(os.getcwd())
for project in os.listdir("."):
path = os.path.join(cwd, project)
if not os.path.isdir(path):
@stephenmcd
stephenmcd / tag_closer.py
Created November 18, 2011 20:07
HTMLParser that closes open tags
class TagCloser(HTMLParser):
"""
HTMLParser that closes open tags. Call close_tags with a HTML
string arg which returns it with any required closing tags
appended.
"""
def __init__(self):
HTMLParser.__init__(self)
self.tags = []
@stephenmcd
stephenmcd / gist:1374413
Created November 17, 2011 20:27
Sort object list by index of attribute in a keylist
def sort_by_keylist(objects, attr, keylist):
indexes = dict([(x, i) for i, x in enumerate(keylist)])
return sorted(objects, key=lambda x: indexes.get(getattr(x, attr)))
@stephenmcd
stephenmcd / gist:1341065
Created November 5, 2011 03:32
Trap every object method
class Foo(object):
def __getattribute__(self, name):
attr = object.__getattribute__(self, name)
if callable(attr):
def wrapper(*args, **kwargs):
try:
return attr(*args, **kwargs)
except Exception, e:
print "%s failed with exc %s" % (name, e)
@stephenmcd
stephenmcd / gist:1318777
Created October 27, 2011 04:29
Estimated project cost of a Mercurial repository
# A one-liner for calculating the cost of a project using a Mercurial repo.
# Replace:
# ignore|paths - pipe separated strings in paths to ignore
# eg: embedded libraries and generated code.
# mins_per_loc - estimated minutes per line of code.
# hourly_rate - hourly dollar rate being charged.
$ hg log --stat | egrep -v 'ignore|paths' | grep '|' | awk '{s+=$3} END {print "$" s / 60 * mins_per_loc * hourly_rate}'
@stephenmcd
stephenmcd / gist:1129135
Created August 6, 2011 07:28
Mini Mock
class MiniMock(object):
"""
A callable object that will always return a value for any
attribute/index/slice/call accessed. The value returned is a new
MiniMock instance allowing for successful chained access.
"""
def __getitem__(self, value):
"""