home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2012 January / maximum-cd-2012-01.iso / DiscContents / digsby_setup.exe / lib / util / primitives / funcs.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-10-05  |  15.1 KB  |  521 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.6)
  3.  
  4. from __future__ import with_statement
  5. from functional import ObjectList
  6. from refs import stupidref, better_ref
  7. from collections import defaultdict
  8. from error_handling import traceguard
  9. import functools
  10. import operator
  11. import pprint
  12. import sys
  13. import traceback
  14.  
  15. try:
  16.     sentinel
  17. except NameError:
  18.     sentinel = object()
  19.  
  20.  
  21. def get(obj, key, default = sentinel):
  22.     
  23.     try:
  24.         return obj[key]
  25.     except (IndexError, KeyError):
  26.         if default is sentinel:
  27.             raise 
  28.         default is sentinel
  29.         return default
  30.     except TypeError:
  31.         
  32.         try:
  33.             return getattr(obj, key)
  34.         except AttributeError:
  35.             if default is sentinel:
  36.                 raise 
  37.             default is sentinel
  38.             return default
  39.         except:
  40.             None<EXCEPTION MATCH>AttributeError
  41.         
  42.  
  43.         None<EXCEPTION MATCH>AttributeError
  44.  
  45.  
  46.  
  47. def ischeck(f):
  48.     
  49.     def checker(v):
  50.         
  51.         try:
  52.             r = f(v)
  53.         except Exception:
  54.             return False
  55.  
  56.         if type(r) is bool:
  57.             return r
  58.         return True
  59.  
  60.     return checker
  61.  
  62.  
  63. def itercheck(x, exclude = (basestring,)):
  64.     
  65.     try:
  66.         iter(x)
  67.     except:
  68.         return False
  69.  
  70.     if not isinstance(x, exclude):
  71.         return True
  72.     return False
  73.  
  74. isint = ischeck(int)
  75. isiterable = ischeck(itercheck)
  76. isnumber = ischeck(float)
  77.  
  78. def make_first(seq, item):
  79.     seq[:] = [] + _[1]
  80.  
  81.  
  82. def do(seq_or_func, seq = None):
  83.     if seq is None:
  84.         for x in seq_or_func:
  85.             pass
  86.         
  87.     else:
  88.         for x in seq:
  89.             seq_or_func(x)
  90.         
  91.  
  92.  
  93. def find(seq, item):
  94.     
  95.     try:
  96.         return seq.index(item)
  97.     except ValueError:
  98.         return -1
  99.  
  100.  
  101.  
  102. def groupby(seq, key = (lambda x: x)):
  103.     res = defaultdict(list)
  104.     for item in seq:
  105.         res[key(item)].append(item)
  106.     
  107.     for k in res:
  108.         yield (k, res[k])
  109.     
  110.  
  111.  
  112. class Delegate(ObjectList):
  113.     VETO = object()
  114.     
  115.     def __init__(self, iterable = [], ignore_exceptions = None, collect_values = False):
  116.         list.__init__(self, iterable)
  117.         self.__dict__['collect_values'] = collect_values
  118.         None(object.__setattr__, self, 'ignore_exceptions' if ignore_exceptions is not None else tuple())
  119.  
  120.     
  121.     def __iadd__(self, f):
  122.         if isinstance(f, list):
  123.             for thing in f:
  124.                 self.__iadd__(thing)
  125.             
  126.         else:
  127.             self.append(f)
  128.         return self
  129.  
  130.     
  131.     def __isub__(self, f):
  132.         if not isiterable(f):
  133.             f = (f,)
  134.         
  135.         for x in f:
  136.             self.remove(x)
  137.         
  138.         return self
  139.  
  140.     
  141.     def __ipow__(self, d):
  142.         self(**d)
  143.         return self
  144.  
  145.     
  146.     def __imul__(self, a):
  147.         self(*a)
  148.         return self
  149.  
  150.     
  151.     def __idiv__(self, tup):
  152.         (a, k) = tup
  153.         self(*a, **k)
  154.         return self
  155.  
  156.     
  157.     def __call__(self, *a, **k):
  158.         result = [
  159.             None]
  160.         for call in self:
  161.             
  162.             try:
  163.                 result.append(call(*a, **k))
  164.             except self.ignore_exceptions:
  165.                 self.remove(call)
  166.             except Exception:
  167.                 traceback.print_exc()
  168.  
  169.             if result[-1] is self.VETO:
  170.                 break
  171.             
  172.             if not self.collect_values:
  173.                 result = result[-1:]
  174.                 continue
  175.         
  176.         if self.collect_values:
  177.             result.pop(0)
  178.         else:
  179.             result = result[-1]
  180.         return result
  181.  
  182.     
  183.     def call_and_clear(self, *a, **k):
  184.         copy = Delegate(self, self.ignore_exceptions, self.collect_values)
  185.         del self[:]
  186.         result = copy(*a, **k)
  187.         return result
  188.  
  189.     
  190.     def __repr__(self):
  191.         funcinfo = funcinfo
  192.         import util
  193.         return '<%s: [%s]>' % (type(self).__name__, (', '.join,)((lambda .0: for f in .0:
  194. funcinfo(f))(self)))
  195.  
  196.     
  197.     def add_unique(self, cb):
  198.         if cb not in self:
  199.             self.append(cb)
  200.         
  201.  
  202.     
  203.     def remove_maybe(self, cb):
  204.         if cb in self:
  205.             self.remove(cb)
  206.         
  207.  
  208.  
  209. objset = object.__setattr__
  210.  
  211. class PausableDelegate(Delegate):
  212.     
  213.     def __init__(self):
  214.         Delegate.__init__(self)
  215.         objset(self, 'paused', False)
  216.  
  217.     
  218.     def __call__(self, *a, **k):
  219.         if self.paused:
  220.             (None, None, self.paused_calls.append)((lambda : Delegate.__call__(self, *a, **k)))
  221.             return None
  222.         return Delegate.__call__(self, *a, **k)
  223.  
  224.     
  225.     def pause(self):
  226.         if not self.paused:
  227.             objset(self, 'paused', True)
  228.             objset(self, 'paused_calls', [])
  229.             return True
  230.         return False
  231.  
  232.     
  233.     def unpause(self):
  234.         if self.paused:
  235.             objset(self, 'paused', False)
  236.             return True
  237.         return False
  238.  
  239.  
  240.  
  241. class WeakDelegate(object):
  242.     
  243.     def __init__(self):
  244.         self.cbs = []
  245.  
  246.     
  247.     def append(self, cb, obj = None):
  248.         self.cbs.append(better_ref(cb, obj = obj))
  249.  
  250.     
  251.     def __iadd__(self, cb):
  252.         self.cbs.append(better_ref(cb))
  253.         return self
  254.  
  255.     
  256.     def __isub__(self, cb):
  257.         new_cbs = []
  258.         for cbref in self.cbs:
  259.             callback = cbref()
  260.             if cb is not callback:
  261.                 new_cbs.append(cb)
  262.                 continue
  263.         
  264.         self.cbs = new_cbs
  265.         return self
  266.  
  267.     
  268.     def __call__(self, *a, **k):
  269.         new_cbs = []
  270.         cbs = self.cbs[:]
  271.         self.cbs[:] = []
  272.         for cbref in cbs:
  273.             callback = cbref()
  274.             if callback is not None:
  275.                 new_cbs.append(cbref)
  276.                 
  277.                 try:
  278.                     callback(*a, **k)
  279.                 except Exception:
  280.                     traceback.print_exc()
  281.                 except:
  282.                     None<EXCEPTION MATCH>Exception
  283.                 
  284.  
  285.             None<EXCEPTION MATCH>Exception
  286.         
  287.         self.cbs[:] = new_cbs
  288.  
  289.  
  290.  
  291. def autoassign(self, locals):
  292.     for key, value in locals.iteritems():
  293.         if key == 'self':
  294.             continue
  295.         
  296.         setattr(self, key, value)
  297.     
  298.  
  299.  
  300. def flatten(seq):
  301.     lst = []
  302.     for el in seq:
  303.         if isinstance(el, (list, tuple)):
  304.             lst.extend(flatten(el))
  305.             continue
  306.         lst.append(el)
  307.     
  308.     return lst
  309.  
  310.  
  311. def dictargs(**argmap):
  312.     
  313.     def decorator(func):
  314.         
  315.         def newf(self, response):
  316.             
  317.             try:
  318.                 args = _[1]
  319.             except KeyError:
  320.                 print >>sys.stderr, 'Error matching argument for', func.__name__
  321.                 raise 
  322.  
  323.             return func(self, *args)
  324.  
  325.         newf = (None, functools.wraps(func))(newf)
  326.         return newf
  327.  
  328.     return decorator
  329.  
  330.  
  331. def dictargcall(func, argdict, argmapping):
  332.     argdict = argdict.copy()
  333.     args = []
  334.     kwargs = { }
  335.     code = func.func_code
  336.     argcount = code.co_argcount
  337.     argnames = code.co_varnames[:argcount]
  338.     if not func.func_defaults:
  339.         pass
  340.     defaults = ()
  341.     _takes_args = bool(code.co_flags & 4)
  342.     takes_kwargs = bool(code.co_flags & 8)
  343.     if argnames and argnames[0] == 'self':
  344.         argnames = argnames[1:]
  345.         argcount -= 1
  346.     
  347.     for argname in argnames[:argcount - len(defaults)]:
  348.         if argname not in argmapping:
  349.             raise ValueError('required argument %s is not in mapping\ngiven mapping: %s' % (argname, pprint.pformat(argmapping)))
  350.         argname not in argmapping
  351.         real_name = argmapping[argname]
  352.         if real_name not in argdict:
  353.             raise ValueError('required argument "%s" (%s) is not in argument dictionary\ngiven arguments: %s' % (argname, real_name, pprint.pformat(argdict)))
  354.         real_name not in argdict
  355.         args.append(argdict[real_name])
  356.         del argdict[real_name]
  357.     
  358.     default_index = 0
  359.     for argname in argnames[argcount - len(defaults):]:
  360.         if argname not in argmapping or argmapping[argname] not in argdict:
  361.             args.append(defaults[default_index])
  362.         else:
  363.             args.append(argdict[argmapping[argname]])
  364.             del argdict[argmapping[argname]]
  365.         default_index += 1
  366.     
  367.     if takes_kwargs:
  368.         for k, v in argdict.iteritems():
  369.             if k in argmapping:
  370.                 kwargs[argmapping[k]] = v
  371.                 continue
  372.             kwargs[str(k)] = v
  373.         
  374.     
  375.     if not takes_kwargs:
  376.         return func(*args)
  377.     return func(*args, **kwargs)
  378.  
  379.  
  380. def funcToMethod(func, clas, method_name = None):
  381.     func.im_class = clas
  382.     func.im_func = func
  383.     func.im_self = None
  384.     if not method_name:
  385.         method_name = func.__name__
  386.     
  387.     clas.__dict__[method_name] = func
  388.  
  389.  
  390. def attach_method(obj, func, name = None):
  391.     if not name:
  392.         pass
  393.     name = func.__name__
  394.     cls = obj.__class__
  395.     cls.temp_foo = func
  396.     obj.__setattr__(name, cls.temp_foo)
  397.     del cls.temp_foo
  398.  
  399.  
  400. class InheritableProperty(object):
  401.     
  402.     def __init__(self, fget = None, fset = None, fdel = None, doc = None):
  403.         self.fget = fget
  404.         self.fset = fset
  405.         self.fdel = fdel
  406.         self.__doc__ = doc
  407.  
  408.     
  409.     def __get__(self, obj, objtype = None):
  410.         if obj is None:
  411.             return self
  412.         if callable(self.fget):
  413.             return self.fget(obj)
  414.         if isinstance(self.fget, basestring):
  415.             return getattr(obj, self.fget)()
  416.         raise AttributeError('unreadable attribute')
  417.  
  418.     
  419.     def __set__(self, obj, value):
  420.         if callable(self.fset):
  421.             return self.fset(obj, value)
  422.         if isinstance(self.fset, basestring):
  423.             return getattr(obj, self.fset)(value)
  424.         raise AttributeError("can't set attribute")
  425.  
  426.     
  427.     def __delete__(self, obj):
  428.         if callable(self.fdel):
  429.             return self.fdel(obj)
  430.         if isinstance(self.fdel, basestring):
  431.             return getattr(obj, self.fdel)()
  432.         raise AttributeError("can't delete attribute")
  433.  
  434.  
  435. iproperty = InheritableProperty
  436.  
  437. def gen_sequence(func):
  438.     cannotcompile = cannotcompile
  439.     import util.introspect
  440.     
  441.     def wrapper(*args, **kwargs):
  442.         gen = func(*args, **kwargs)
  443.         val = gen.next()
  444.         
  445.         try:
  446.             gen.send(stupidref(gen))
  447.         except StopIteration:
  448.             pass
  449.  
  450.         return val
  451.  
  452.     wrapper = cannotcompile((functools.wraps(func),)(wrapper))
  453.     return wrapper
  454.  
  455.  
  456. def removedupes(seq, key = (lambda x: x)):
  457.     s = set()
  458.     uniqueseq = []
  459.     for elem in seq:
  460.         if key(elem) not in s:
  461.             uniqueseq.append(elem)
  462.             s.add(key(elem))
  463.             continue
  464.     
  465.     return uniqueseq
  466.  
  467.  
  468. def lispify(*args):
  469.     
  470.     try:
  471.         iter(args[0])
  472.     except:
  473.         pass
  474.  
  475.     args = args[0]
  476.     return reduce((lambda x, y: (lambda : x(y(*a, **k)))
  477. ), args)
  478.  
  479.  
  480. class CallCounter(object):
  481.     
  482.     def __init__(self, trigger, func, *args, **kwargs):
  483.         self._count = -1
  484.         self._trigger = trigger
  485.         self._func = func
  486.         self._args = args
  487.         self._kwargs = kwargs
  488.         self()
  489.  
  490.     
  491.     def __call__(self):
  492.         self._count += 1
  493.         if self._count == self._trigger:
  494.             self._func(*self._args, **self._kwargs)
  495.         
  496.  
  497.     
  498.     def func_code(self):
  499.         return self._func.func_code
  500.  
  501.     func_code = property(func_code)
  502.  
  503.  
  504. def readonly(attr):
  505.     return property(operator.attrgetter(attr))
  506.  
  507.  
  508. def takemany(n, iterable):
  509.     while n > 0:
  510.         yield iterable.next()
  511.         n -= 1
  512.  
  513.  
  514. def boolify(s):
  515.     return s.lower() in ('yes', 'true', '1')
  516.  
  517. if __name__ == '__main__':
  518.     import doctest
  519.     doctest.testmod(verbose = True)
  520.  
  521.