Skip to content

Instantly share code, notes, and snippets.

// Note that the path doesn't matter for routing; any WebSocket
// connection gets bumped over to WebSocket consumers
socket = new WebSocket("ws://127.0.0.1:7000/chat/");
socket.onmessage = function(e) {
alert(e.data);
}
socket.onopen = function() {
socket.send("hello world");
}
// Call onopen directly if socket is already open
// Note that the path doesn't matter for routing; any WebSocket
// connection gets bumped over to WebSocket consumers
socket = new WebSocket("ws://127.0.0.1:7000/chat/");
socket.onmessage = function(e) {
alert(e.data);
}
socket.onopen = function() {
socket.send("hello world");
}
// Call onopen directly if socket is already open
import datetime
import time
import re
def stringToTimedelta(string):
try:
timestring, daystring = string.lower().split(',')
day = int(re.search(r'day (\d+)', daystring).group(1))
def blockify(lines):
assert len({len(line) for line in lines}) in {0, 1}
return [''.join(section)
for section in zip(*lines)]
if __name__ == '__main__':
assert blockify([]) == []
assert blockify(['AAA', 'BBB', 'CCC']) == ['ABC', 'ABC', 'ABC']
import uuid
import random
def ordered_uniquification(items):
seen = set()
for item in items:
if not item in seen:
seen.add(item)
yield item
@rectangletangle
rectangletangle / gist:807febc7b54d551dcc85
Last active August 29, 2015 14:02
Quickly select a random model from a Django queryset
import random
def fast_random_model(callback, queryset):
""" Attempts to quickly retrieve a single randomly selected object from a
queryset, then passes it to the callback if successful. """
# This implementation avoids using `order by random()` which is notoriously
# slow with large tables in Postgres.
count = queryset.count()
import re
# This is the literal code as copied from the file, for our purposes it's equivalent to the code below.
"""
def extract_hashtag_values(text, pattern=settings.HASHTAG_PATTERN):
for hashtag_match in re.finditer(pattern, text):
yield hashtag_match.group(1)
"""
@rectangletangle
rectangletangle / gist:1368fd548694ec8cd4c3
Last active August 29, 2015 14:01
A PERFECTLY NORMAL AND SANE FIZZBUZZ
print('\n'.join((exec('def fizzbuzz():\n\tfor i in range({}):\n\t\t'.format('*' + repr((locals().update({'start': 1, 'stop': 101}), start, stop)[1:])) + '\n\t\t'.join('elif i == {}:\n\t\t\tyield "{}"'.format(i, 'Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or i)[abs(~i) if i == 1 else None:] for i in range(start, stop))), locals()['fizzbuzz'])[1]()))
@rectangletangle
rectangletangle / gist:0a0d5a2e84dd3178d348
Last active January 29, 2022 17:32
Python 3 Monkeypatch Context Manager
""" This is a convenient way to monkeypatch a method or attribute of a Python
object. This is great for situations where you want to modify a global
object within a limited scope, i.e., your typical class or module when
testing. This was tested and works with Python 2.7 and 3.4. """
import contextlib
@contextlib.contextmanager
def monkeypatched(object, name, patch):
""" Temporarily monkeypatches an object. """