Skip to content

Instantly share code, notes, and snippets.

View poros's full-sized avatar

Antonio Uccio Verardi poros

View GitHub Profile
@poros
poros / stop_gen.py
Created October 7, 2015 09:23
Stop a generator midway
lines = (for line in open("run/foo/access-log"))
# PYTHON 3 ONLY!!!
for i,line in enumerate(lines):
print line
if i == 10: lines.close()
@poros
poros / trace_gen.py
Created October 7, 2015 09:41
Trace a generator for debugging
def trace(source):
for item in source:
print item
yield item
r404 = trace(r for r in log if r['status'] == 404)
@poros
poros / storelast_gen.py
Created October 7, 2015 09:43
Generator storing the last value returned
class storelast(object):
def __init__(self,source):
self.source = source
def next(self):
item = self.source.next()
self.last = item
return item
def __iter__(self):
return self
@poros
poros / cleanupjob_class.py
Created October 26, 2015 01:03
Using objects and decorators instead of classes with just one method and some constants
from job_class import Job
def delete_expired_stuff(time):
print "Delete expired stuff before %s" % time
class CleanupJob(Job):
# configuration: run at 5am
run_at = '05:00'
# implementation: nuke expired sessions
@poros
poros / container.py
Last active October 30, 2015 01:40
Containers and magic methods
from md5 import md5
class FakeHashRing(object):
def __init__(self, nodes):
self.nodes = list(nodes)
def _hash(self, key):
return int(md5(str(key).encode('utf-8')).hexdigest(), 16) % len(self.nodes)
@poros
poros / state_machine.py
Created March 25, 2017 17:40
Basic state machine implementation in Python using namedtuples as states and functions as transitions
from collections import namedtuple
import re
import sys
SIGNALFX_API = 'https://app.signalfx.com/#/'
RES_TYPE_RE= re.compile(r"^(?P<type>\S+?)\..*:$")
# STATES