2018-08-03 03:24:57 +02:00
|
|
|
import difflib
|
2019-03-08 02:07:22 +01:00
|
|
|
from typing import Sequence, List
|
2018-08-03 03:24:57 +02:00
|
|
|
|
|
|
|
|
2019-03-08 02:07:22 +01:00
|
|
|
def humanize(n: int, precision=2, prefix="bin", suffix="B") -> str:
|
2018-08-03 03:30:17 +02:00
|
|
|
"""
|
|
|
|
Return a humanized string representation of a number (of bytes).
|
|
|
|
Adapted from Doug Latornell - http://code.activestate.com/recipes/577081/
|
|
|
|
"""
|
|
|
|
abbrevs = {
|
|
|
|
"dec": [
|
|
|
|
(1000 ** 5, 'P' + suffix),
|
|
|
|
(1000 ** 4, 'T' + suffix),
|
|
|
|
(1000 ** 3, 'G' + suffix),
|
|
|
|
(1000 ** 2, 'M' + suffix),
|
|
|
|
(1000 ** 1, 'k' + suffix)
|
|
|
|
],
|
|
|
|
"bin": [
|
|
|
|
(1 << 50, 'Pi' + suffix),
|
|
|
|
(1 << 40, 'Ti' + suffix),
|
|
|
|
(1 << 30, 'Gi' + suffix),
|
|
|
|
(1 << 20, 'Mi' + suffix),
|
|
|
|
(1 << 10, 'ki' + suffix)
|
|
|
|
]
|
|
|
|
}
|
|
|
|
factor, suffix = next(((f, s) for f, s in abbrevs[prefix] if n >= f), (1, suffix))
|
|
|
|
return "{1:.{0}f}".format(precision, n / factor).rstrip("0").rstrip(".") + suffix
|
|
|
|
|
|
|
|
|
2019-03-08 02:07:22 +01:00
|
|
|
def case_insensitive_close_matches(word: str, possibilities: Sequence[str], n=3, cutoff=0.6) -> List[str]:
|
2018-08-03 03:24:57 +02:00
|
|
|
"""
|
|
|
|
Python's difflib.get_close_matches does case sensitive sequence matching, this function decorates the library
|
|
|
|
function to make it case insensitive.
|
|
|
|
"""
|
|
|
|
possibilities = {sequence.lower(): sequence for sequence in possibilities}
|
|
|
|
close_matches = difflib.get_close_matches(word.lower(), possibilities, n=n, cutoff=cutoff)
|
|
|
|
return [possibilities[m] for m in close_matches]
|
2018-10-28 13:07:11 +01:00
|
|
|
|
|
|
|
|
2019-03-08 02:07:22 +01:00
|
|
|
def markdown_escape(text: str) -> str:
|
2018-10-28 13:07:11 +01:00
|
|
|
"""
|
|
|
|
Escape markdown.
|
|
|
|
"""
|
|
|
|
special = ("\\", "`", "*", "_", "{", "}", "[", "]", "(", ")", "#", "+", "-", ".", "!", "|")
|
|
|
|
table = {s: f"\\{s}" for s in special}
|
|
|
|
return text.translate(str.maketrans(table))
|