Skip to content

Instantly share code, notes, and snippets.

View kezabelle's full-sized avatar

Keryn Knight kezabelle

View GitHub Profile
@kezabelle
kezabelle / ohitspython.py
Last active August 29, 2015 14:22
... Why can't I see `__get_dynamic_attr` on a Django Feed?!
class A(object):
def b(self): return True
def _c(self): return True
def __d(self): return True
dir(A())
# ['_A__d', ..., '_c', 'b']
@kezabelle
kezabelle / pypy.2.5.1.py
Created May 29, 2015 12:56
Yay, PyPy doesn't work like CPython 2.7
Python 2.7.9 (9c4588d731b7fe0b08669bd732c2b676cb0a8233, Mar 31 2015, 07:51:58)
[PyPy 2.5.1 with GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>> from datetime import datetime
>>>> datetime.strftime(datetime.now(), format='%Y')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: strftime() got an unexpected keyword argument 'format'
>>>> datetime.strftime(datetime.now(), '%Y')
'2015'
@kezabelle
kezabelle / errors.md
Created May 22, 2015 13:52
Error messages I encountered while trying to get mod_pagespeed working in a Vagrant box where the guest's port80 is mapped to the hosts's 1080 ...

Errors

4xx status code, preventing rewriting of ...

Ok so for some reason pagespeed is doing a fetch (presumably an HTTP sub-request) but getting an invalid response. It would be useful to know which. 404 because it can't find the files? 403 because I've got the permissions wrong?

Fetch failed to start ...

I don't know what that means. I presume it was unable to even start what I expect is the same HTTP sub-request mechanism previously mentioned, but as debug messages go, I cannot even begin to guess at where the problem lies.

@kezabelle
kezabelle / models.py
Created April 20, 2015 08:12
Is there a better way of handling sometimes prefetched data in Django models than this?
class MyRelation(models.Model):
"""
This simple example demonstrates the fat model which needs some related data,
but obviously can't know [without introspecting as I'm doing here] whether or
not it needs to eagerly fetch the data, or whether it can just enumerate
the prefetch results.
"""
def prefetched_active_users(self):
# assumes .prefetch_related('users') has happened.
@kezabelle
kezabelle / screenslop.py
Last active August 29, 2015 14:16
Taking screenshots of URLs at various resolutions, using selenium & python. Assumes Django, so tries to remove django-debug-toolbar as necessary.
#! /usr/bin/env python
from sys import exit
from datetime import datetime
from itertools import product
from selenium import webdriver
RESOLUTIONS = (
(360, 480),
(400, 600),
(480, 320),
@kezabelle
kezabelle / db_thingie.py
Last active August 29, 2015 14:16
Sketching a db adapter where I get to keep the grepability of SQL itself.
class MyThing(namedtuple('MyThing', 'a b c d')):
def __table__(self):
return 'my_thing_table'
mything = MyThing(a=1, b=2, c=3, d=4)
# should all happen in begin;commit;close
with DBThingie() as query: # hits __init__ and __enter__ ?
query("insert into ? (?) values (?)", mything) # hits __call__?
query("update ? set (?) where (?)", mything) # hits __call__?
@kezabelle
kezabelle / ffs.py
Last active January 26, 2016 11:24
Gods I hate you python string formatting
>>> x = u'\u2019'
>>> '%s' % x
u'\u2019'
>>> '%(x)s' % {'x': x}
u'\u2019'
>>> '{}'.format(x)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 0: ordinal not in range(128)
>>> {0!s}'.format(x)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 0: ordinal not in range(128)
@kezabelle
kezabelle / settings.py
Created January 14, 2015 11:22
Django logging config at the project level. I'd have thought this would work, but instead it's a ValueError
# Logging config should be merged with the defaults in
# django.util.log.configure_logging() which is called
# by django.setup()
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'loggers': {}
}
for app in INSTALLED_APPS:
LOGGING['loggers'][app] = {
@kezabelle
kezabelle / deferred.py
Last active August 29, 2015 14:08
getting everything but deferred attributes for a given Django model. Because otherwise, doing getattr() forces evaluation of deferred fields.
# see https://github.com/django/django/blob/c32bc1a7a7bbb3d5bd0a2c11bc77dd5ab1c32fbc/django/db/models/base.py#L415
# and http://stackoverflow.com/questions/4523651/how-to-tell-which-fields-have-been-deferred-onlyd-in-a-django-queryset
concrete_fieldnames = (x.attname for x in obj._meta.concrete_fields)
non_deferred = dict(
(attr, getattr(obj, attr))
for attr in concrete_fieldnames
if not isinstance(obj.__class__.__dict__.get(attr), DeferredAttribute)
)
@kezabelle
kezabelle / titlechange.js
Created November 5, 2014 08:55
Changing a tab/window's document title when it isn't in focus. Supports modern browsers, in theory. Does nothing in older ones, hopefully.
/*
if the browser supports it, and the page isn't in focus (tabbed away, etc)
we change the title to whatever is passed into the anonymous function,
as a reminder.
*/
(function(hidden_title, undefined) {
var has_document;
var has_title;
var has_event_handler;
var original_title;