Skip to content

Instantly share code, notes, and snippets.

def all_equal(iterable):
"""
Check if all items are equal to each other.
>>> all_equal([1, 1, 1])
True
>>> all_equal([1, 2, 1])
False
Args:
iterable (iterable): a series of items to be checked
from concurrent.futures import as_completed
import warnings
def async_map(executor, func, *iterables):
"""Execute the given function asynchronously and yield the args-result pairs.
Args:
executor (Executor): An opened concurrent.future.Executor.
func (function(*args)): Function to be executed.
from functools import lru_cache
class AttributeManager(object):
"""
A base class of attribute manager.
The name of the attribute are scanned and saved from the owner classes.
The value of each instance are saved as __name
import os
def ensure_dir(path):
d = os.path.dirname(path)
if not os.path.exists(d):
os.makedirs(d)
from collections import Iterable, Mapping
from operator import methodcaller
def flatten(it, map_iter='values'):
"""
Iterator that walk through nested iterable.
If the initial item is not iterable, only itself will be yielded.
Args:
from itertools import product
def named_product(**kwargs):
"""
Cartesian product of input iterables with keys.
Due to how python handle kwargs, the order of the keys is not conserved.
>>> dict(x=1, y='a') in list(named_product(x=[1, 2], y=['a', 'b']))
True
"""
import pickle
from itertools import count
from collections import Mapping
class PickleRecorder:
def __init__(self, path):
self.path = path
from string import ascii_letters, digits
def checker(c, good=set('-_.() '+ascii_letters+digits)):
return c in good
def valid_filename(filename):
return ''.join(filter(checker, filename)).strip()
from bisect import bisect_left
from collections import Mapping
from functools import total_ordering
@total_ordering
class frozendict(Mapping):
"""
Sorted immutable mapping with hash and total ordering.
fn func(seq: &[u8]) -> u64 {
let n = seq.len();
let mut sum = 0u64;
for i in 0..n {
let j = (i + 1) % n;
if seq[i] == seq[j] {
sum += seq[i] as u64
}
}