Skip to content

Instantly share code, notes, and snippets.

View SegFaultAX's full-sized avatar

Michael-Keith Bernard SegFaultAX

View GitHub Profile
@SegFaultAX
SegFaultAX / gist:10939429
Created April 16, 2014 22:34
Dotted path expansion in Clojure
(defn deep-merge-with
"Like merge-with, but preserves shared key paths, recursively."
[f & maps]
(letfn [(merge-elem [m e]
(let [k (key e) v (val e) src (m k)]
(if src
(if (and (map? src) (map? v))
(assoc m k (merge2 src v))
(assoc m k (f src v)))
(assoc m k v))))
@SegFaultAX
SegFaultAX / gist:10941721
Last active May 19, 2023 09:20
clojure.walk in Python
from functools import partial
def identity(e):
return e
def walk(inner, outer, coll):
if isinstance(coll, list):
return outer([inner(e) for e in coll])
elif isinstance(coll, dict):
return outer(dict([inner(e) for e in coll.iteritems()]))
@SegFaultAX
SegFaultAX / gist:1f8900efb422888eabab
Last active July 11, 2016 19:40
clojure.core/partition and clojure.core/partition-all in Python
def take_while(fn, coll):
"""Yield values from coll until fn is False"""
for e in coll:
if fn(e):
yield e
else:
return
def partition(n, coll, step=None):
return take_while(lambda e: len(e) == n,
def categorize(fn, coll):
"""Like group_by, but fn returns multiple keys"""
acc = {}
for e in coll:
keys = fn(e)
for key in keys:
if key not in acc:
acc[key] = []
acc[key].append(e)
@SegFaultAX
SegFaultAX / gist:629a3a8c15b0fd188000
Last active August 29, 2015 14:01
Python -> Lua serialization
SPECIAL_DELIM = [("[{}[".format("="*n), "]{}]".format("="*n)) for n in range(10)]
def type_of(v, *types):
return any(isinstance(v, t) for t in types)
def get_delim(s):
if '"' not in s: and "\n" not in s:
return ('"', '"')
for op, cl in SPECIAL_DELIM:
if op not in s and cl not in s:
@SegFaultAX
SegFaultAX / gist:9b05d9922ecd2b49c304
Last active August 22, 2021 02:40
CSV file splitter (each file after the split keeps the header line)
#!/usr/bin/env python
import csv
import argparse
from itertools import islice
def load_csv(filename, headers=None):
reader = csv.reader(open(filename, "rU"))
if headers is None:
headers = next(reader)
@SegFaultAX
SegFaultAX / gist:7916de1d008e94814257
Last active August 22, 2021 02:40
Elapsed time context manager with checkpoints
from __future__ import print_function
import time
import contextlib
def format_checkpoints(cps):
pairs = [cps[i:i+2] for i in range(len(cps)-1)]
fmts = ["{0[0]} to {1[0]} in {2:.04f}s".format(start, end, end[1] - start[1])
for start, end in pairs]
return ", ".join(fmts)
@SegFaultAX
SegFaultAX / gist:f48fe6930d18b52118ab
Last active August 29, 2015 14:05
Reducers in Python [incomplete]
import copy
class ReducedException(Exception):
def __init__(self, reduced_value):
super(ReducedException, self).__init__()
self.reduced_value = reduced_value
def conj(coll, *es):
"""Conjoin elements to coll. Works correctly for most collection types"""
@SegFaultAX
SegFaultAX / gist:d51da36f7eb65f58db7d
Last active August 22, 2021 02:40
Eager, re-entrant elapsed time logger
from __future__ import print_function
import time
import functools
import contextlib
LOG_FMT = "{name}: {cp} @{total:0.4f}s ({dur:0.4f}s since {prev})"
def coroutine(f):
@functools.wraps(f)
def coro(*args, **kwargs):
@SegFaultAX
SegFaultAX / gist:520fe589dfe22ec10ae8
Created March 7, 2015 09:14
Internal Iterators in Python
class Enumerable(object):
def map(self, fn):
acc = []
self.each(lambda xs: acc.append(fn(xs)))
return self.__class__(acc)
collect = map
def filter(self, pred):
acc = []