utilities.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import uuid
  2. import hashlib
  3. from .. import constants
  4. ROUND = constants.DEFAULT_PRECISION
  5. def bit_mask(flags):
  6. """Generate a bit mask.
  7. :type flags: dict
  8. :return: int
  9. """
  10. bit = 0
  11. true = lambda x, y: (x | (1 << y))
  12. false = lambda x, y: (x & (~(1 << y)))
  13. for mask, position in constants.MASK.items():
  14. func = true if flags.get(mask) else false
  15. bit = func(bit, position)
  16. return bit
  17. def hash(value):
  18. """Generate a hash from a given value
  19. :param value:
  20. :rtype: str
  21. """
  22. hash_ = hashlib.md5()
  23. hash_.update(repr(value).encode('utf8'))
  24. return hash_.hexdigest()
  25. def id():
  26. """Generate a random UUID
  27. :rtype: str
  28. """
  29. return str(uuid.uuid4()).upper()
  30. def id_from_name(name):
  31. """Generate a UUID using a name as the namespace
  32. :type name: str
  33. :rtype: str
  34. """
  35. return str(uuid.uuid3(uuid.NAMESPACE_DNS, name)).upper()
  36. def rgb2int(rgb):
  37. """Convert a given rgb value to an integer
  38. :type rgb: list|tuple
  39. :rtype: int
  40. """
  41. is_tuple = isinstance(rgb, tuple)
  42. rgb = list(rgb) if is_tuple else rgb
  43. colour = (int(rgb[0]*255) << 16) + (int(rgb[1]*255) << 8) + int(rgb[2]*255)
  44. return colour
  45. def round_off(value, ndigits=ROUND):
  46. """Round off values to specified limit
  47. :param value: value(s) to round off
  48. :param ndigits: limit (Default value = ROUND)
  49. :type value: float|list|tuple
  50. :return: the same data type that was passed
  51. :rtype: float|list|tuple
  52. """
  53. is_tuple = isinstance(value, tuple)
  54. is_list = isinstance(value, list)
  55. value = list(value) if is_tuple else value
  56. value = [value] if not is_list and not is_tuple else value
  57. value = [round(val, ndigits) for val in value]
  58. if is_tuple:
  59. value = tuple(value)
  60. elif not is_list:
  61. value = value[0]
  62. return value
  63. def rounding(options):
  64. """By evaluation the options determine if precision was
  65. enabled and what the value is
  66. :type options: dict
  67. :rtype: bool, int
  68. """
  69. round_off_ = options.get(constants.ENABLE_PRECISION)
  70. if round_off_:
  71. round_val = options[constants.PRECISION]
  72. else:
  73. round_val = None
  74. return (round_off_, round_val)