Skip to content

Instantly share code, notes, and snippets.

@Hujun
Hujun / kd_shuffle.py
Created October 9, 2018 12:07
Knuth-Durstenfeld Shuffle is a improved version of Fisher-Yates Shuffle algorithm
import random
def knuth_durstenfeld_shuffle(arr):
for i in range(len(arr) - 1, 0, -1):
j = random.randint(0, i)
arr[i], arr[j] = arr[j], arr[i]
@Hujun
Hujun / docker-compose.yml
Last active March 12, 2019 23:13
Rancher(v1.6) + Nginx docker deployment config
version: "2"
services:
rancher:
image: rancher/server:stable
container_name: "rancher-server"
restart: always
ports:
- "8080:8080"
volumes:
- ./rancher/mysql:/var/lib/mysql
@Hujun
Hujun / rand_str.py
Created February 28, 2018 06:42
Random string generation
from string import (
ascii_letters,
digits,
)
from random import choice
from typing import Iterable
LETTERS_AND_DIGITS = ascii_letters + digits
def rand_str(n: int, s: Iterable = LETTERS_AND_DIGITS) -> str:
#!/usr/bin/env python
# encoding: utf-8
# adjacency matrix
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
@Hujun
Hujun / tag_gen.py
Created September 16, 2017 07:31
HTML Tag Generator
def tag(name, *content, cls=None, **attrs):
"""Generate one or more HTML tags"""
if cls is not None:
attrs['class'] = cls
if attrs:
attr_str = ''.join(' %s="%s"' % (attr, value)
for attr, value
in sorted(attrs.items())
else:
@Hujun
Hujun / unicode_util.py
Created September 16, 2017 05:55
Unicode Utilities
# from <<Fluent Python>> ch4: Text versus Bytes
from unicodedata import normalize
import string
def nfc_equal(str1, str2):
"""
s1 = 'café'
s2 = 'cafe\u0301'
@Hujun
Hujun / get_argnames.py
Created November 1, 2016 09:42
Get defined argument names of given callable
# from falcon.util
import functools
import inspect
import six
def get_argnames(func):
if six.PY2:
if isinstance(func, functools.partial):
spec = inspect.getargspec(func.func)
@Hujun
Hujun / get_bound_method.py
Created November 1, 2016 08:52
Get methods of a given object
# from falcon.util
# use `six` module for compatibility in essence
import six
def get_bound_method(obj, method_name):
method = getattr(obj, method_name, None)
if method is not None:
if six.get_method_self(method) is None:
raise AttributeError('method {} not found'.format(method_name))
@Hujun
Hujun / cached_property.py
Created October 20, 2016 10:10
Cached Property
# from werkzeug.utils
# a decorator that converts a function into a lazy property
# derived from built-in property and override __get__ and __set__
class Missing(object):
def __repr__(self):
return 'no value'
def __reduce__(self):
return '_missing'
@Hujun
Hujun / escape.py
Created October 13, 2016 03:34
Form HTML Safe Sequence
s = s.replace('&', '&amp').replace('<', '&lt;').replace('>', '&gt;').reqlace('"', '&quot')