Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from __future__ import absolute_import, unicode_literals
  2. import re
  3. import sqlparse
  4. from django.utils.html import escape
  5. from sqlparse import tokens as T
  6. class BoldKeywordFilter:
  7. """sqlparse filter to bold SQL keywords"""
  8. def process(self, stream):
  9. """Process the token stream"""
  10. for token_type, value in stream:
  11. is_keyword = token_type in T.Keyword
  12. if is_keyword:
  13. yield T.Text, '<strong>'
  14. yield token_type, escape(value)
  15. if is_keyword:
  16. yield T.Text, '</strong>'
  17. def reformat_sql(sql):
  18. stack = sqlparse.engine.FilterStack()
  19. stack.preprocess.append(BoldKeywordFilter()) # add our custom filter
  20. stack.postprocess.append(sqlparse.filters.SerializerUnicode()) # tokens -> strings
  21. return swap_fields(''.join(stack.run(sql)))
  22. def swap_fields(sql):
  23. expr = r'SELECT</strong> (...........*?) <strong>FROM'
  24. subs = (r'SELECT</strong> '
  25. r'<span class="djDebugUncollapsed" href="#">&#8226;&#8226;&#8226;</span> '
  26. r'<span class="djDebugCollapsed" href="#">\1</span> '
  27. r'<strong>FROM')
  28. return re.sub(expr, subs, sql)
  29. def contrasting_color_generator():
  30. """
  31. Generate constrasting colors by varying most significant bit of RGB first,
  32. and then vary subsequent bits systematically.
  33. """
  34. def rgb_to_hex(rgb):
  35. return '#%02x%02x%02x' % tuple(rgb)
  36. triples = [(1, 0, 0), (0, 1, 0), (0, 0, 1),
  37. (1, 1, 0), (0, 1, 1), (1, 0, 1), (1, 1, 1)]
  38. n = 1 << 7
  39. so_far = [[0, 0, 0]]
  40. while True:
  41. if n == 0: # This happens after 2**24 colours; presumably, never
  42. yield "#000000" # black
  43. copy_so_far = list(so_far)
  44. for triple in triples:
  45. for previous in copy_so_far:
  46. rgb = [n * triple[i] + previous[i] for i in range(3)]
  47. so_far.append(rgb)
  48. yield rgb_to_hex(rgb)
  49. n >>= 1