Skip to content

Instantly share code, notes, and snippets.

Tim Heap timheap

Block or report user

Report or block timheap

Hide content and notifications from this user.

Learn more about blocking users

Contact Support about this user’s behavior.

Learn more about reporting abuse

Report abuse
View GitHub Profile
@timheap
timheap / etag_cache.py
Created Oct 2, 2018
A nice decorator for Flask views that supports ETag and Last-Modified headers, responding with a 304 Not Modified where possible
View etag_cache.py
import logging
from functools import wraps
from flask import Response, make_response, request
from werkzeug.http import parse_date
def check_empty_iterator(iterator, message="Iterator was not empty"):
try:
next(iterator)
@timheap
timheap / filelock.py
Last active Aug 2, 2018
Python multiprocess FileLock class using fcntl.flock()
View filelock.py
import fcntl
import os
from contextlib import contextmanager
MODE_NAMES = {
fcntl.LOCK_SH: 'shared',
fcntl.LOCK_EX: 'exclusive',
}
@timheap
timheap / chunksof.py
Last active Jan 13, 2019
Split a generator up in to chunks of size `n`, without walking the list or keeping items in memory needlessly
View chunksof.py
from itertools import chain, islice
class splitter:
"""Helper class for splitat."""
def __init__(self, iterable, count):
self.iterator = iter(iterable)
self.count = count
self.queue = []
@timheap
timheap / next_in_order.py
Last active Mar 21, 2018
Get the next/previous items in a queryset in relation to a reference object.
View next_in_order.py
"""
Get the next/previous items in a queryset in relation to a reference object.
"""
from django.db.models import Q
def next_in_order(queryset, reference):
"""
Get the next items in a QuerySet according to its ordering, in relation to
@timheap
timheap / test_data_helpers.py
Created Feb 6, 2018
Some helpers for making POST data for Wagtail / Django form tests
View test_data_helpers.py
def _nested_form_data(data):
if isinstance(data, dict):
items = data.items()
elif isinstance(data, list):
items = enumerate(data)
for key, value in items:
key = str(key)
if isinstance(value, (dict, list)):
for child_keys, child_value in _nested_form_data(value):
@timheap
timheap / comp.py
Last active Jun 28, 2017
Automatic partially-applied binary operators ala Haskell, for Python
View comp.py
class Comparator():
"""Support 'partial binding' of built in operators."""
def __call__(self, a):
"""For support of nested PendingOperations, comparator(a) == a"""
return a
# A bunch of boring operators
def __lt__(self, b):
return PendingOperation(lambda a: self(a) < b)
View forms.py
from django.core.exceptions import ValidationError
from django import forms
class UsernameValidatorForm(forms.Form):
username = forms.CharField()
def clean_username(self):
username = self.cleaned_data['username']
@timheap
timheap / m2m.py
Last active Aug 3, 2016 — forked from alexgleason/m2m.py
Many to many relationships in Wagtail
View m2m.py
from django.db import models
from wagtail.wagtailsnippets.models import register_snippet
from wagtail.wagtailcore.models import Page
from wagtail.wagtailadmin.edit_handlers import InlinePanel
@register_snippet
class Category(models.Model):
"""
@timheap
timheap / update-prs.sh
Created Dec 12, 2015
Automatically rebase a collection of branches on upstream/master, run the tests, and push to origin if the tests pass
View update-prs.sh
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
upstream='upstream/master'
if ! ( git diff --exit-code && git diff --cached --exit-code ) ; then
echo "Working tree is dirty, aborting"
exit 1
View syncdir
#!/bin/bash
# A dodgy ripoff of rsync for my music files
#
# Usage: To copy the contents of "Zechs Marquise/Getting Paid/" and "Grails/"
# from your music library to your mounted phone:
#
# syncdir --source $HOME/Music \
# --destination /mnt/phone/Music \
# "Zechs Marquise/Getting Paid/" \
# "Grails/"
You can’t perform that action at this time.