home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 June / maximum-cd-2009-06.iso / DiscContents / digsby_setup.exe / lib / util / primitives / strings.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-02-26  |  19.7 KB  |  555 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. import mapping
  5. import HTMLParser
  6. import StringIO
  7. import re
  8. import string
  9. import sys
  10. import traceback
  11.  
  12. try:
  13.     _
  14. except NameError:
  15.     
  16.     _ = lambda x: x
  17.  
  18.  
  19. def strftime_u(timeobj, fmt):
  20.     if isinstance(fmt, unicode):
  21.         fmt = fmt.encode('utf-8')
  22.     
  23.     return timeobj.strftime(fmt).decode('locale')
  24.  
  25.  
  26. def strfileobj(writefunc):
  27.     s = StringIO()
  28.     writefunc(s)
  29.     return s.getvalue()
  30.  
  31.  
  32. def strincrement(s):
  33.     return str(int(s) + 1)
  34.  
  35.  
  36. def tuple2hex(t):
  37.     return ''.join((lambda .0: for c in .0:
  38. '%02x' % c)(t[:3]))
  39.  
  40.  
  41. def format_xhtml(s, f):
  42.     s = s.replace('\n', '<br />')
  43.     font_attrs = None(None, [
  44.         None,
  45.         None,
  46.         filter,
  47.         (lambda e: bool(e)) if f.bold else '' if f.italic else '' if f.size is not None else '' if f.face is not None else ''])
  48.     style_elems = None(None, [
  49.         None,
  50.         None,
  51.         filter,
  52.         (lambda s: bool(s)) if f.foregroundcolor is not None else '' if f.backgroundcolor not in (None, (255, 255, 255, 255)) else '' if f.underline else '' if font_attrs else ''])
  53.     if style_elems:
  54.         span_style = '; '.join(style_elems)
  55.         return '<span style="%s;">%s</span>' % (span_style, s)
  56.     else:
  57.         return s
  58.  
  59. fontsizes = ((lambda x: x < 8), (lambda x: x == 8), (lambda x: x in (9, 10)), (lambda x: x in (11, 12, 13)), (lambda x: x in (14, 15, 16)), (lambda x: x in (17, 18, 19)), (lambda x: x > 19))
  60.  
  61. def Point2HTMLSize(n):
  62.     for i, f in enumerate(fontsizes):
  63.         if f(n):
  64.             return i + 1
  65.             continue
  66.     
  67.  
  68.  
  69. class StrippingParser(HTMLParser.HTMLParser):
  70.     from htmlentitydefs import entitydefs
  71.     
  72.     def __init__(self, valid_tags = ()):
  73.         HTMLParser.HTMLParser.__init__(self)
  74.         self.valid_tags = valid_tags
  75.         self.result = ''
  76.         self.endTagList = []
  77.  
  78.     
  79.     def handle_data(self, data):
  80.         if data:
  81.             self.result = self.result + data
  82.         
  83.  
  84.     
  85.     def handle_starttag(self, tag, attrs):
  86.         if tag == 'br':
  87.             self.result += '\n'
  88.         
  89.  
  90.     
  91.     def handle_charref(self, name):
  92.         self.result += chr(int(name))
  93.  
  94.     
  95.     def handle_entityref(self, name):
  96.         self.result += self.entitydefs.get(name, '')
  97.  
  98.     
  99.     def unknown_starttag(self, tag, attrs):
  100.         if tag in self.valid_tags:
  101.             self.result = self.result + '<' + tag
  102.             for k, v in attrs:
  103.                 if string.lower(k[0:2]) != 'on' and string.lower(v[0:10]) != 'javascript':
  104.                     self.result = '%s %s="%s"' % (self.result, k, v)
  105.                     continue
  106.             
  107.             endTag = '</%s>' % tag
  108.             self.endTagList.insert(0, endTag)
  109.             self.result = self.result + '>'
  110.         
  111.  
  112.     
  113.     def unknown_endtag(self, tag):
  114.         if tag in self.valid_tags:
  115.             self.result = '%s</%s>' % (self.result, tag)
  116.             remTag = '</%s>' % tag
  117.             self.endTagList.remove(remTag)
  118.         
  119.  
  120.     
  121.     def cleanup(self):
  122.         for j in range(len(self.endTagList)):
  123.             self.result = self.result + self.endTagList[j]
  124.         
  125.  
  126.  
  127. parser = StrippingParser()
  128.  
  129. def scrape_clean(text):
  130.     
  131.     def fixup(m):
  132.         text = m.group(0)
  133.         if text[:1] == '<':
  134.             return ''
  135.         
  136.         if text[:2] == '&#':
  137.             
  138.             try:
  139.                 if text[:3] == '&#x':
  140.                     return unichr(int(text[3:-1], 16))
  141.                 else:
  142.                     return unichr(int(text[2:-1]))
  143.             except ValueError:
  144.                 pass
  145.             except:
  146.                 None<EXCEPTION MATCH>ValueError
  147.             
  148.  
  149.         None<EXCEPTION MATCH>ValueError
  150.         if text[:1] == '&':
  151.             import htmlentitydefs
  152.             entity = htmlentitydefs.entitydefs.get(text[1:-1])
  153.             if entity:
  154.                 if entity[:2] == '&#':
  155.                     
  156.                     try:
  157.                         return unichr(int(entity[2:-1]))
  158.                     except ValueError:
  159.                         pass
  160.                     except:
  161.                         None<EXCEPTION MATCH>ValueError
  162.                     
  163.  
  164.                 None<EXCEPTION MATCH>ValueError
  165.                 return unicode(entity, 'iso-8859-1')
  166.             
  167.         
  168.         return text
  169.  
  170.     return re.sub('(?s)<[^>]*>|&#?\\w+;', fixup, text)
  171.  
  172.  
  173. def strip_html(s, valid_tags = ()):
  174.     parser.valid_tags = valid_tags
  175.     parser.feed(s)
  176.     parser.close()
  177.     parser.cleanup()
  178.     result = parser.result
  179.     parser.result = ''
  180.     return result
  181.  
  182.  
  183. def strip_html2(s):
  184.     if not s:
  185.         return s
  186.     
  187.     BeautifulSoup = BeautifulSoup
  188.     import util.BeautifulSoup
  189.     soup = BeautifulSoup(s.replace('<br>', '\n').replace('<br/>', '\n').replace('<br />', '\n'))
  190.     return ''.join((lambda .0: for e in .0:
  191. if isinstance(e, unicode):
  192. econtinue)(soup.recursiveChildGenerator()))
  193.  
  194.  
  195. def strip_html_and_tags(s, invalid_tags):
  196.     if not s:
  197.         return s
  198.     
  199.     BeautifulSoup = BeautifulSoup
  200.     import util.BeautifulSoup
  201.     soup = BeautifulSoup(s.replace('<br>', '\n').replace('<br/>', '\n').replace('<br />', '\n'))
  202.     for tag in invalid_tags:
  203.         for result in soup.findAll(name = tag):
  204.             result.replaceWith('')
  205.         
  206.     
  207.     return ''.join((lambda .0: for e in .0:
  208. if isinstance(e, unicode):
  209. econtinue)(soup.recursiveChildGenerator()))
  210.  
  211.  
  212. def srv_str_to_tuple(address, default_port):
  213.     if address.find(':') != -1:
  214.         (host, port) = address.split(':')
  215.         port = int(port)
  216.     else:
  217.         host = address
  218.         port = default_port
  219.     return (host, port)
  220.  
  221.  
  222. def get_between(s, start_str, end_str):
  223.     start_i = s.find(start_str)
  224.     end_i = s.find(end_str, start_i)
  225.     if start_i > end_i or -1 in (start_i, end_i):
  226.         return None
  227.     else:
  228.         return s[start_i + len(start_str):end_i]
  229.  
  230.  
  231. def strlist(s):
  232.     lines = s.split('\n')
  233.     for y, line in enumerate(lines):
  234.         i = line.find('#')
  235.         if i != -1:
  236.             lines[y] = line[:i]
  237.             continue
  238.     
  239.     return '\n'.join(lines).split()
  240.  
  241. _curlymatcher = re.compile('\\$\\{(?P<expr>.*?)\\}', re.DOTALL)
  242.  
  243. def curly(s, frame = 2, source = None):
  244.     
  245.     def evalrepl(match, source = (source,)):
  246.         f = sys._getframe(frame)
  247.         if source is None:
  248.             source = { }
  249.         elif isinstance(source, dict):
  250.             source = source
  251.         elif hasattr(source, '__dict__'):
  252.             source = source.__dict__
  253.         elif hasattr(source, '__slots__'):
  254.             source = (dict,)((lambda .0: for x in .0:
  255. (x, getattr(source, x)))(source.__slots__))
  256.         else:
  257.             raise AssertionError('not sure what to do with this argument: %r' % source)
  258.         locals = mapping.dictadd(f.f_locals, source)
  259.         
  260.         try:
  261.             res = eval(match.group('expr'), f.f_globals, locals)
  262.         except Exception:
  263.             e = None
  264.             traceback.print_exc()
  265.             return ''
  266.             raise e
  267.  
  268.         return u'%s' % (res,)
  269.  
  270.     return _curlymatcher.sub(evalrepl, s)
  271.  
  272.  
  273. def cprint(s):
  274.     print curly(s, frame = 3)
  275.  
  276.  
  277. def replace_newlines(s, replacement = ' / ', newlines = (u'\n', u'\r')):
  278.     for newline in newlines[1:]:
  279.         s = s.replace(newline, newlines[0])
  280.     
  281.     while s.find(newlines[0] * 2) != -1:
  282.         s = s.replace(newlines[0] * 2, newlines[0])
  283.     return s.strip().replace(newlines[0], replacement)
  284.  
  285.  
  286. def nicenumber(n, sep = ',', decimal = '.'):
  287.     (n, decimalpoint, decimalpart) = str(n).partition(decimal)
  288.     n = str(n)[::-1]
  289.     n = (sep.join,)((lambda .0: for i in .0:
  290. n[i:i + 3])(xrange(0, len(n), 3)))[::-1]
  291.     return ''.join([
  292.         n,
  293.         decimalpoint,
  294.         decimalpart])
  295.  
  296.  
  297. def nicebytecount(bytes):
  298.     if bytes == 0:
  299.         return '0B'
  300.     
  301.     count = 0
  302.     while bytes >= 1024:
  303.         bytes = bytes / 1024
  304.         count = count + 1
  305.     return (None if int(bytes) == bytes else '%.2f' + ' %sB') % (bytes, ('', 'k', 'M', 'G', 'T', 'P')[count])
  306.  
  307.  
  308. class istr(unicode):
  309.     
  310.     def __new__(self, strng):
  311.         return unicode.__new__(self, _(strng))
  312.  
  313.     
  314.     def __init__(self, strng):
  315.         self.real = strng
  316.  
  317.     
  318.     def __cmp__(self, other):
  319.         if type(self) == type(other):
  320.             return cmp(self.real, other.real)
  321.         else:
  322.             return unicode.__cmp__(self, other)
  323.  
  324.     
  325.     def __eq__(self, other):
  326.         return not bool(self.__cmp__(other))
  327.  
  328.  
  329.  
  330. def nicetimecount(seconds, max = 2, sep = ' '):
  331.     seconds = int(seconds)
  332.     if seconds < 0:
  333.         return '-' + nicetimecount(abs(seconds), max = max, sep = sep)
  334.     
  335.     (minutes, seconds) = divmod(seconds, 60)
  336.     (hours, minutes) = divmod(minutes, 60)
  337.     (days, hours) = divmod(hours, 24)
  338.     (years, days) = divmod(days, 365)
  339.     i = 0
  340.     res = []
  341.     for thing in _('years days hours minutes seconds').split():
  342.         if not vars()[thing]:
  343.             continue
  344.         else:
  345.             res.append('%d%s' % (vars()[thing], thing[0]))
  346.             i += 1
  347.         if i == max:
  348.             break
  349.             continue
  350.     elif not res:
  351.         res = [
  352.             '0s']
  353.     
  354.     return sep.join(res)
  355.  
  356.  
  357. def unpack_pstr(s):
  358.     unpack = unpack
  359.     import struct
  360.     l = unpack('B', s[0])[0]
  361.     return (s[1:1 + l], s[1 + l:])
  362.  
  363.  
  364. def pack_pstr(s):
  365.     pack = pack
  366.     import struct
  367.     return pack('B', len(s)) + s
  368.  
  369.  
  370. def preserve_newlines(s):
  371.     return preserve_whitespace(s, nbsp = False)
  372.  
  373.  
  374. def preserve_whitespace(s, nbsp = True):
  375.     s = s.replace('\r\n', '\n').replace('\n', '<br />')
  376.     _re = re.compile('(\\s{2,})')
  377.     if not nbsp:
  378.         return s
  379.     
  380.     match = _re.search(s)
  381.     while match:
  382.         spaces = match.groups()[0]
  383.         s = s.replace(spaces, len(spaces) * ' ', 1)
  384.         match = _re.search(s)
  385.     return s
  386.  
  387.  
  388. class EncodedString(object):
  389.     
  390.     def __init__(self, s, encodings = None):
  391.         if encodings is None:
  392.             encodings = ()
  393.         
  394.         self.encodings = tuple(encodings)
  395.         self._data = s
  396.  
  397.     
  398.     def encode(self, encoding):
  399.         return EncodedString(self._data.encode(encoding), self.encodings + (encoding,))
  400.  
  401.     
  402.     def decodeAll(self):
  403.         s = self
  404.         while s.encodings:
  405.             s = s.decode()
  406.         return s
  407.  
  408.     
  409.     def decode(self):
  410.         encoding = self.encodings[-1]
  411.         newencodings = self.encodings[:-1]
  412.         return EncodedString(self._data.decode(encoding), newencodings)
  413.  
  414.     
  415.     def __getattr__(self, attr):
  416.         if attr in ('encodings', '_data', 'encode', 'decode', 'decodeAll'):
  417.             return object.__getattribute__(self, attr)
  418.         else:
  419.             return self._data.__getattribute__(attr)
  420.  
  421.     
  422.     def __repr__(self):
  423.         return '<%s (%s) encodings=%r>' % (type(self).__name__, repr(self._data), self.encodings)
  424.  
  425.     
  426.     def __str__(self):
  427.         if type(self._data) is str:
  428.             return self._data
  429.         else:
  430.             raise TypeError('%r cannot be implicitly converted to str')
  431.  
  432.     
  433.     def __unicode__(self):
  434.         if type(self._data) is unicode:
  435.             return self._data
  436.         else:
  437.             raise TypeError('%r cannot be implicitly converted to unicode')
  438.  
  439.  
  440. estring = EncodedString
  441.  
  442. def try_all_encodings(s):
  443.     successes = []
  444.     import encodings
  445.     codecs = set(encodings.aliases.aliases.values())
  446.     for c in codecs:
  447.         
  448.         try:
  449.             decoded = s.decode(c)
  450.         except (Exception,):
  451.             continue
  452.             continue
  453.  
  454.         if isinstance(decoded, unicode):
  455.             
  456.             try:
  457.                 recoded = decoded.encode('utf8')
  458.             except UnicodeEncodeError:
  459.                 continue
  460.             except:
  461.                 None<EXCEPTION MATCH>UnicodeEncodeError
  462.             
  463.  
  464.         None<EXCEPTION MATCH>UnicodeEncodeError
  465.         if isinstance(recoded, str) and isinstance(decoded, unicode):
  466.             codec = c
  467.             successes.append((s, codec, decoded, recoded))
  468.             continue
  469.     else:
  470.         decoded = None
  471.         recoded = None
  472.         codec = None
  473.     return successes
  474.  
  475.  
  476. def saferepr(obj):
  477.     
  478.     try:
  479.         return repr(obj)
  480.     except Exception:
  481.         
  482.         try:
  483.             return '<%s>' % obj.__class__.__name__
  484.         except Exception:
  485.             return '<??>'
  486.         except:
  487.             None<EXCEPTION MATCH>Exception
  488.         
  489.  
  490.         None<EXCEPTION MATCH>Exception
  491.  
  492.  
  493.  
  494. def wireshark_format(data):
  495.     out = StringIO()
  496.     safe = set(string.printable) - set(string.whitespace) | set(' ')
  497.     
  498.     def hex(s):
  499.         return ' '.join((lambda .0: for ch in .0:
  500. '%02X' % ord(ch))(s))
  501.  
  502.     
  503.     def safe_bin(s):
  504.         return (''.join,)((lambda .0: for ch in .0:
  505. None if ch in safe else '.')(s))
  506.  
  507.     
  508.     def pad(s, l, ch = ' '):
  509.         return s + ch * (l - len(s))
  510.  
  511.     w = out.write
  512.     space = '    '
  513.     while data:
  514.         chunk1 = data[:8]
  515.         chunk2 = data[8:16]
  516.         data = data[16:]
  517.         w(pad(hex(chunk1), 24))
  518.         w(space)
  519.         w(pad(hex(chunk2), 24))
  520.         w(space)
  521.         w(pad(safe_bin(chunk1), 8))
  522.         w(space)
  523.         w(pad(safe_bin(chunk2), 8))
  524.         w('\n')
  525.         continue
  526.         (None,)
  527.     return out.getvalue()
  528.  
  529.  
  530. def to_hex(string, spacer = ' '):
  531.     return spacer.join((lambda .0: for byte in .0:
  532. '%02X' % ord(byte))(string))
  533.  
  534.  
  535. def byte_print(string_, spacer = ' '):
  536.     import string as strng
  537.     output = ''
  538.     for i in range(len(string_) / 16 + 1):
  539.         line = string_[i * 16:i * 16 + 16]
  540.         pline = (''.join,)((lambda .0: for x in .0:
  541. None if x in strng.printable else '.')(line))
  542.         pline = pline.replace('\n', ' ')
  543.         pline = pline.replace('\r', ' ')
  544.         pline = pline.replace('\t', ' ')
  545.         pline = pline.replace('\x0b', ' ')
  546.         pline = pline.replace('\x0c', ' ')
  547.         output += to_hex(line) + ' ' + pline + '\n'
  548.     
  549.     return output
  550.  
  551. if __name__ == '__main__':
  552.     import doctest
  553.     doctest.testmod(verbose = True)
  554.  
  555.