PageRenderTime 41ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/petri/common/utils/string.py

https://github.com/EricSchles/hackerunion.org
Python | 102 lines | 98 code | 4 blank | 0 comment | 0 complexity | 2e9ac190dd1c1d14f37931c3423e37bd MD5 | raw file
Possible License(s): GPL-3.0
  1. import re
  2. import random
  3. import hashlib
  4. import datetime
  5. BASE62_SYMBOLS="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  6. BASE36_SYMBOLS="abcdefghijklmnopqrstuvwxyz0123456789"
  7. BASE26_SYMBOLS="abcdefghijklmnopqrstuvwxyz"
  8. ENCODING_SYMBOLS=BASE36_SYMBOLS
  9. SHRINK_RE = re.compile(r'(?<=\w)[aeiou](?=\w)', re.IGNORECASE)
  10. def key_encode(n, encoding_symbols=ENCODING_SYMBOLS):
  11. "Convert a number to a minimal-length alphanumeric encoding."
  12. numsym = len(encoding_symbols)
  13. s = ""
  14. if n < 0:
  15. raise ValueError("Unencoded keys must be positive integers")
  16. while True:
  17. s = encoding_symbols[n % numsym] + s
  18. n = n / numsym - 1
  19. if n < 0:
  20. return s
  21. def key_decode(s, encoding_symbols=ENCODING_SYMBOLS):
  22. "Convert minimal-length alphanumeric string to the corresponding decimal value."
  23. numsym = len(encoding_symbols)
  24. try:
  25. n = 0
  26. ls = len(s) - 1
  27. for (i, c) in enumerate(s):
  28. n = numsym * n + encoding_symbols.index(c) + (i < ls and 1 or 0)
  29. return n
  30. except ValueError:
  31. raise ValueError("Invalid symbol found in encoded key")
  32. def key_max(digits, encoding_symbols=ENCODING_SYMBOLS):
  33. "Return the maximum value encodable in a certain number of symbols."
  34. numsym = len(encoding_symbols)
  35. result = 0
  36. for i in range(digits):
  37. if i == 0:
  38. result += numsym - 1
  39. else:
  40. result += numsym ** (i + 1)
  41. digits -= 1
  42. return result
  43. def force_int(s, default=0):
  44. "Convert a string to an integer; on failure, return 0."
  45. try:
  46. return int(s)
  47. except:
  48. return default
  49. def none_if_blank(s):
  50. return None if s is None or len(s) == 0 else s
  51. def smart_title(s):
  52. return s.title() if len(s) and s[0].isalpha() else s
  53. def random_string(max_length=32):
  54. return hashlib.md5("%s%s" % (random.randint(0, 100000), datetime.datetime.now())).hexdigest()[:min(max_length, 32)]
  55. def shrink(s, max_length, prefix=False, stupidify=False):
  56. if len(s) <= max_length:
  57. return s
  58. if stupidify:
  59. s = SHRINK_RE.sub('', s)
  60. return s if len(s) <= max_length else ('...' + s[3:max_length] if prefix else s[:max_length-3] + '...')
  61. def random_pin(*args, **kwargs):
  62. return str(random.randint(0, 99999)).zfill(5)
  63. def random_code(*args, **kwargs):
  64. return random_string(max_length=8)
  65. def sanitize_string(s):
  66. return re.sub(r'[^a-z\s]', '', ' '.join(s.lower().split()))