home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 February / maximum-cd-2011-02.iso / DiscContents / digsby_setup85.exe / lib / util / primitives / strings.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-11-24  |  21.9 KB  |  607 lines

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