home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_2649 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  51.3 KB  |  1,676 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __all__ = [
  5.     'Decimal',
  6.     'Context',
  7.     'DefaultContext',
  8.     'BasicContext',
  9.     'ExtendedContext',
  10.     'DecimalException',
  11.     'Clamped',
  12.     'InvalidOperation',
  13.     'DivisionByZero',
  14.     'Inexact',
  15.     'Rounded',
  16.     'Subnormal',
  17.     'Overflow',
  18.     'Underflow',
  19.     'ROUND_DOWN',
  20.     'ROUND_HALF_UP',
  21.     'ROUND_HALF_EVEN',
  22.     'ROUND_CEILING',
  23.     'ROUND_FLOOR',
  24.     'ROUND_UP',
  25.     'ROUND_HALF_DOWN',
  26.     'setcontext',
  27.     'getcontext']
  28. import copy
  29. ROUND_DOWN = 'ROUND_DOWN'
  30. ROUND_HALF_UP = 'ROUND_HALF_UP'
  31. ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
  32. ROUND_CEILING = 'ROUND_CEILING'
  33. ROUND_FLOOR = 'ROUND_FLOOR'
  34. ROUND_UP = 'ROUND_UP'
  35. ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
  36. NEVER_ROUND = 'NEVER_ROUND'
  37. ALWAYS_ROUND = 'ALWAYS_ROUND'
  38.  
  39. class DecimalException(ArithmeticError):
  40.     
  41.     def handle(self, context, *args):
  42.         pass
  43.  
  44.  
  45.  
  46. class Clamped(DecimalException):
  47.     pass
  48.  
  49.  
  50. class InvalidOperation(DecimalException):
  51.     
  52.     def handle(self, context, *args):
  53.         if args:
  54.             if args[0] == 1:
  55.                 return Decimal((args[1]._sign, args[1]._int, 'n'))
  56.         
  57.         return NaN
  58.  
  59.  
  60.  
  61. class ConversionSyntax(InvalidOperation):
  62.     
  63.     def handle(self, context, *args):
  64.         return (0, (0,), 'n')
  65.  
  66.  
  67.  
  68. class DivisionByZero(DecimalException, ZeroDivisionError):
  69.     
  70.     def handle(self, context, sign, double = None, *args):
  71.         if double is not None:
  72.             return (Infsign[sign],) * 2
  73.         return Infsign[sign]
  74.  
  75.  
  76.  
  77. class DivisionImpossible(InvalidOperation):
  78.     
  79.     def handle(self, context, *args):
  80.         return (NaN, NaN)
  81.  
  82.  
  83.  
  84. class DivisionUndefined(InvalidOperation, ZeroDivisionError):
  85.     
  86.     def handle(self, context, tup = None, *args):
  87.         if tup is not None:
  88.             return (NaN, NaN)
  89.         return NaN
  90.  
  91.  
  92.  
  93. class Inexact(DecimalException):
  94.     pass
  95.  
  96.  
  97. class InvalidContext(InvalidOperation):
  98.     
  99.     def handle(self, context, *args):
  100.         return NaN
  101.  
  102.  
  103.  
  104. class Rounded(DecimalException):
  105.     pass
  106.  
  107.  
  108. class Subnormal(DecimalException):
  109.     pass
  110.  
  111.  
  112. class Overflow(Inexact, Rounded):
  113.     
  114.     def handle(self, context, sign, *args):
  115.         if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_HALF_DOWN, ROUND_UP):
  116.             return Infsign[sign]
  117.         if sign == 0:
  118.             if context.rounding == ROUND_CEILING:
  119.                 return Infsign[sign]
  120.             return Decimal((sign, (9,) * context.prec, (context.Emax - context.prec) + 1))
  121.         if sign == 1:
  122.             if context.rounding == ROUND_FLOOR:
  123.                 return Infsign[sign]
  124.             return Decimal((sign, (9,) * context.prec, (context.Emax - context.prec) + 1))
  125.  
  126.  
  127.  
  128. class Underflow(Inexact, Rounded, Subnormal):
  129.     pass
  130.  
  131. _signals = [
  132.     Clamped,
  133.     DivisionByZero,
  134.     Inexact,
  135.     Overflow,
  136.     Rounded,
  137.     Underflow,
  138.     InvalidOperation,
  139.     Subnormal]
  140. _condition_map = {
  141.     ConversionSyntax: InvalidOperation,
  142.     DivisionImpossible: InvalidOperation,
  143.     DivisionUndefined: InvalidOperation,
  144.     InvalidContext: InvalidOperation }
  145.  
  146. try:
  147.     import threading
  148. except ImportError:
  149.     import sys
  150.     
  151.     class MockThreading:
  152.         
  153.         def local(self, sys = sys):
  154.             return sys.modules[__name__]
  155.  
  156.  
  157.     threading = MockThreading()
  158.     del sys
  159.     del MockThreading
  160.  
  161.  
  162. try:
  163.     threading.local
  164. except AttributeError:
  165.     if hasattr(threading.currentThread(), '__decimal_context__'):
  166.         del threading.currentThread().__decimal_context__
  167.     
  168.     
  169.     def setcontext(context):
  170.         if context in (DefaultContext, BasicContext, ExtendedContext):
  171.             context = context.copy()
  172.             context.clear_flags()
  173.         
  174.         threading.currentThread().__decimal_context__ = context
  175.  
  176.     
  177.     def getcontext():
  178.         
  179.         try:
  180.             return threading.currentThread().__decimal_context__
  181.         except AttributeError:
  182.             context = Context()
  183.             threading.currentThread().__decimal_context__ = context
  184.             return context
  185.  
  186.  
  187.  
  188. local = threading.local()
  189. if hasattr(local, '__decimal_context__'):
  190.     del local.__decimal_context__
  191.  
  192.  
  193. def getcontext(_local = local):
  194.     
  195.     try:
  196.         return _local.__decimal_context__
  197.     except AttributeError:
  198.         context = Context()
  199.         _local.__decimal_context__ = context
  200.         return context
  201.  
  202.  
  203.  
  204. def setcontext(context, _local = local):
  205.     if context in (DefaultContext, BasicContext, ExtendedContext):
  206.         context = context.copy()
  207.         context.clear_flags()
  208.     
  209.     _local.__decimal_context__ = context
  210.  
  211. del threading
  212. del local
  213.  
  214. class Decimal(object):
  215.     __slots__ = ('_exp', '_int', '_sign', '_is_special')
  216.     
  217.     def __new__(cls, value = '0', context = None):
  218.         self = object.__new__(cls)
  219.         self._is_special = False
  220.         if isinstance(value, _WorkRep):
  221.             self._sign = value.sign
  222.             self._int = tuple(map(int, str(value.int)))
  223.             self._exp = int(value.exp)
  224.             return self
  225.         if isinstance(value, Decimal):
  226.             self._exp = value._exp
  227.             self._sign = value._sign
  228.             self._int = value._int
  229.             self._is_special = value._is_special
  230.             return self
  231.         if isinstance(value, (int, long)):
  232.             self._exp = 0
  233.             self._int = tuple(map(int, str(abs(value))))
  234.             return self
  235.         if isinstance(value, (list, tuple)):
  236.             if len(value) != 3:
  237.                 raise ValueError, 'Invalid arguments'
  238.             len(value) != 3
  239.             if value[0] not in (0, 1):
  240.                 raise ValueError, 'Invalid sign'
  241.             value[0] not in (0, 1)
  242.             for digit in value[1]:
  243.                 if not isinstance(digit, (int, long)) or digit < 0:
  244.                     raise ValueError, 'The second value in the tuple must be composed of non negative integer elements.'
  245.                 digit < 0
  246.             
  247.             self._sign = value[0]
  248.             self._int = tuple(value[1])
  249.             return self
  250.         if isinstance(value, float):
  251.             raise TypeError('Cannot convert float to Decimal.  ' + 'First convert the float to a string')
  252.         isinstance(value, float)
  253.         if isinstance(value, basestring):
  254.             if _isinfinity(value):
  255.                 self._exp = 'F'
  256.                 self._int = (0,)
  257.                 self._is_special = True
  258.                 return self
  259.             if _isnan(value):
  260.                 (sig, sign, diag) = _isnan(value)
  261.                 self._is_special = True
  262.                 if len(diag) > context.prec:
  263.                     (self._sign, self._int, self._exp) = context._raise_error(ConversionSyntax)
  264.                     return self
  265.                 self._sign = sign
  266.                 self._int = tuple(map(int, diag))
  267.                 return self
  268.             
  269.             try:
  270.                 (self._sign, self._int, self._exp) = _string2exact(value)
  271.             except ValueError:
  272.                 _isnan(value)
  273.                 _isnan(value)
  274.                 _isinfinity(value)
  275.                 self._is_special = True
  276.                 (self._sign, self._int, self._exp) = context._raise_error(ConversionSyntax)
  277.             except:
  278.                 isinstance(value, Decimal) if context is None else isinstance(value, (int, long))
  279.  
  280.             return self
  281.         raise TypeError('Cannot convert %r to Decimal' % value)
  282.  
  283.     
  284.     def _isnan(self):
  285.         return 0
  286.  
  287.     
  288.     def _isinfinity(self):
  289.         if self._exp == 'F':
  290.             if self._sign:
  291.                 return -1
  292.             return 1
  293.         return 0
  294.  
  295.     
  296.     def _check_nans(self, other = None, context = None):
  297.         self_is_nan = self._isnan()
  298.         if other is None:
  299.             other_is_nan = False
  300.         else:
  301.             other_is_nan = other._isnan()
  302.         if self_is_nan or other_is_nan:
  303.             if context is None:
  304.                 context = getcontext()
  305.             
  306.             if self_is_nan == 2:
  307.                 return context._raise_error(InvalidOperation, 'sNaN', 1, self)
  308.             if other_is_nan == 2:
  309.                 return context._raise_error(InvalidOperation, 'sNaN', 1, other)
  310.             if self_is_nan:
  311.                 return self
  312.             return other
  313.         return 0
  314.  
  315.     
  316.     def __nonzero__(self):
  317.         if self._is_special:
  318.             return 1
  319.         return sum(self._int) != 0
  320.  
  321.     
  322.     def __cmp__(self, other, context = None):
  323.         other = _convert_other(other)
  324.         if self._is_special or other._is_special:
  325.             ans = self._check_nans(other, context)
  326.             if ans:
  327.                 return 1
  328.             return cmp(self._isinfinity(), other._isinfinity())
  329.         if not self and not other:
  330.             return 0
  331.         if other._sign < self._sign:
  332.             return -1
  333.         if self._sign < other._sign:
  334.             return 1
  335.         self_adjusted = self.adjusted()
  336.         other_adjusted = other.adjusted()
  337.         if self_adjusted == other_adjusted and self._int + (0,) * (self._exp - other._exp) == other._int + (0,) * (other._exp - self._exp):
  338.             return 0
  339.         if self_adjusted > other_adjusted and self._int[0] != 0:
  340.             return -1 ** self._sign
  341.         if self_adjusted < other_adjusted and other._int[0] != 0:
  342.             return --1 ** self._sign
  343.         context = context._shallow_copy()
  344.         rounding = context._set_rounding(ROUND_UP)
  345.         flags = context._ignore_all_flags()
  346.         res = self.__sub__(other, context = context)
  347.         context._regard_flags(*flags)
  348.         context.rounding = rounding
  349.         if not res:
  350.             return 0
  351.         if res._sign:
  352.             return -1
  353.         return 1
  354.  
  355.     
  356.     def __eq__(self, other):
  357.         if not isinstance(other, (Decimal, int, long)):
  358.             return False
  359.         return self.__cmp__(other) == 0
  360.  
  361.     
  362.     def __ne__(self, other):
  363.         if not isinstance(other, (Decimal, int, long)):
  364.             return True
  365.         return self.__cmp__(other) != 0
  366.  
  367.     
  368.     def compare(self, other, context = None):
  369.         other = _convert_other(other)
  370.         if (self._is_special or other) and other._is_special:
  371.             ans = self._check_nans(other, context)
  372.             if ans:
  373.                 return ans
  374.         
  375.         return Decimal(self.__cmp__(other, context))
  376.  
  377.     
  378.     def __hash__(self):
  379.         if self._is_special:
  380.             if self._isnan():
  381.                 raise TypeError('Cannot hash a NaN value.')
  382.             self._isnan()
  383.             return hash(str(self))
  384.         i = int(self)
  385.         if self == Decimal(i):
  386.             return hash(i)
  387.         return hash(str(self.normalize()))
  388.  
  389.     
  390.     def as_tuple(self):
  391.         return (self._sign, self._int, self._exp)
  392.  
  393.     
  394.     def __repr__(self):
  395.         return 'Decimal("%s")' % str(self)
  396.  
  397.     
  398.     def __str__(self, eng = 0, context = None):
  399.         if self._isnan():
  400.             minus = '-' * self._sign
  401.             if self._int == (0,):
  402.                 info = ''
  403.             else:
  404.                 info = ''.join(map(str, self._int))
  405.             if self._isnan() == 2:
  406.                 return minus + 'sNaN' + info
  407.             return minus + 'NaN' + info
  408.         if self._isinfinity():
  409.             minus = '-' * self._sign
  410.             return minus + 'Infinity'
  411.         tmp = map(str, self._int)
  412.         numdigits = len(self._int)
  413.         leftdigits = self._exp + numdigits
  414.         if eng and not self:
  415.             if self._exp < 0 and self._exp >= -6:
  416.                 s = '-' * self._sign + '0.' + '0' * abs(self._exp)
  417.                 return s
  418.             exp = ((self._exp - 1) // 3 + 1) * 3
  419.             s = '-' * self._sign + s
  420.             return s
  421.         if self._exp == 0:
  422.             pass
  423.         elif self._exp < 0 and adjexp >= 0:
  424.             tmp.insert(leftdigits, '.')
  425.         elif self._exp < 0 and adjexp >= -6:
  426.             tmp[0:0] = [
  427.                 '0'] * int(-leftdigits)
  428.             tmp.insert(0, '0.')
  429.         elif numdigits > dotplace:
  430.             tmp.insert(dotplace, '.')
  431.         elif numdigits < dotplace:
  432.             tmp.extend([
  433.                 '0'] * (dotplace - numdigits))
  434.         
  435.         if adjexp:
  436.             if not context.capitals:
  437.                 tmp.append('e')
  438.             else:
  439.                 tmp.append('E')
  440.                 if adjexp > 0:
  441.                     tmp.append('+')
  442.                 
  443.             tmp.append(str(adjexp))
  444.         
  445.         if eng:
  446.             while tmp[0:1] == [
  447.                 '0']:
  448.                 tmp[0:1] = []
  449.             if len(tmp) == 0 and tmp[0] == '.' or tmp[0].lower() == 'e':
  450.                 tmp[0:0] = [
  451.                     '0']
  452.             
  453.         
  454.         if self._sign:
  455.             tmp.insert(0, '-')
  456.         
  457.         return ''.join(tmp)
  458.  
  459.     
  460.     def to_eng_string(self, context = None):
  461.         return self.__str__(eng = 1, context = context)
  462.  
  463.     
  464.     def __neg__(self, context = None):
  465.         if self._is_special:
  466.             ans = self._check_nans(context = context)
  467.             if ans:
  468.                 return ans
  469.         
  470.         if not self:
  471.             sign = 0
  472.         elif self._sign:
  473.             sign = 0
  474.         else:
  475.             sign = 1
  476.         if context is None:
  477.             context = getcontext()
  478.         
  479.         if context._rounding_decision == ALWAYS_ROUND:
  480.             return Decimal((sign, self._int, self._exp))._fix(context)
  481.         return Decimal((sign, self._int, self._exp))
  482.  
  483.     
  484.     def __pos__(self, context = None):
  485.         if self._is_special:
  486.             ans = self._check_nans(context = context)
  487.             if ans:
  488.                 return ans
  489.         
  490.         sign = self._sign
  491.         if not self:
  492.             sign = 0
  493.         
  494.         if context is None:
  495.             context = getcontext()
  496.         
  497.         if context._rounding_decision == ALWAYS_ROUND:
  498.             ans = self._fix(context)
  499.         else:
  500.             ans = Decimal(self)
  501.         ans._sign = sign
  502.         return ans
  503.  
  504.     
  505.     def __abs__(self, round = 1, context = None):
  506.         if self._is_special:
  507.             ans = self._check_nans(context = context)
  508.             if ans:
  509.                 return ans
  510.         
  511.         if not round:
  512.             if context is None:
  513.                 context = getcontext()
  514.             
  515.             context = context._shallow_copy()
  516.             context._set_rounding_decision(NEVER_ROUND)
  517.         
  518.         if self._sign:
  519.             ans = self.__neg__(context = context)
  520.         else:
  521.             ans = self.__pos__(context = context)
  522.         return ans
  523.  
  524.     
  525.     def __add__(self, other, context = None):
  526.         other = _convert_other(other)
  527.         if context is None:
  528.             context = getcontext()
  529.         
  530.         shouldround = context._rounding_decision == ALWAYS_ROUND
  531.         exp = min(self._exp, other._exp)
  532.         negativezero = 0
  533.         if context.rounding == ROUND_FLOOR and self._sign != other._sign:
  534.             negativezero = 1
  535.         
  536.         if not self and not other:
  537.             sign = min(self._sign, other._sign)
  538.             if negativezero:
  539.                 sign = 1
  540.             
  541.             return Decimal((sign, (0,), exp))
  542.         if not self:
  543.             exp = max(exp, other._exp - context.prec - 1)
  544.             ans = other._rescale(exp, watchexp = 0, context = context)
  545.             if shouldround:
  546.                 ans = ans._fix(context)
  547.             
  548.             return ans
  549.         if not other:
  550.             exp = max(exp, self._exp - context.prec - 1)
  551.             ans = self._rescale(exp, watchexp = 0, context = context)
  552.             return ans
  553.         op1 = _WorkRep(self)
  554.         op2 = _WorkRep(other)
  555.         (op1, op2) = _normalize(op1, op2, shouldround, context.prec)
  556.         result = _WorkRep()
  557.         if op1.sign != op2.sign:
  558.             if op1.int == op2.int:
  559.                 return Decimal((negativezero, (0,), exp))
  560.             if op1.sign == 1:
  561.                 result.sign = 1
  562.                 op1.sign = op2.sign
  563.                 op2.sign = op1.sign
  564.             else:
  565.                 result.sign = 0
  566.         elif op1.sign == 1:
  567.             result.sign = 1
  568.             (op1.sign, op2.sign) = (0, 0)
  569.         else:
  570.             result.sign = 0
  571.         if op2.sign == 0:
  572.             result.int = op1.int + op2.int
  573.         else:
  574.             result.int = op1.int - op2.int
  575.         result.exp = op1.exp
  576.         ans = Decimal(result)
  577.         if shouldround:
  578.             ans = ans._fix(context)
  579.         
  580.         return ans
  581.  
  582.     __radd__ = __add__
  583.     
  584.     def __sub__(self, other, context = None):
  585.         other = _convert_other(other)
  586.         if self._is_special or other._is_special:
  587.             ans = self._check_nans(other, context = context)
  588.             if ans:
  589.                 return ans
  590.         
  591.         tmp = Decimal(other)
  592.         tmp._sign = 1 - tmp._sign
  593.         return self.__add__(tmp, context = context)
  594.  
  595.     
  596.     def __rsub__(self, other, context = None):
  597.         other = _convert_other(other)
  598.         tmp = Decimal(self)
  599.         tmp._sign = 1 - tmp._sign
  600.         return other.__add__(tmp, context = context)
  601.  
  602.     
  603.     def _increment(self, round = 1, context = None):
  604.         if self._is_special:
  605.             ans = self._check_nans(context = context)
  606.             if ans:
  607.                 return ans
  608.             return Decimal(self)
  609.         L = list(self._int)
  610.         L[-1] += 1
  611.         spot = len(L) - 1
  612.         while L[spot] == 10:
  613.             L[spot] = 0
  614.             if spot == 0:
  615.                 L[0:0] = [
  616.                     1]
  617.                 break
  618.             
  619.             L[spot - 1] += 1
  620.             spot -= 1
  621.         ans = Decimal((self._sign, L, self._exp))
  622.         if context is None:
  623.             context = getcontext()
  624.         
  625.         if round and context._rounding_decision == ALWAYS_ROUND:
  626.             ans = ans._fix(context)
  627.         
  628.         return ans
  629.  
  630.     
  631.     def __mul__(self, other, context = None):
  632.         other = _convert_other(other)
  633.         if context is None:
  634.             context = getcontext()
  635.         
  636.         resultsign = self._sign ^ other._sign
  637.         resultexp = self._exp + other._exp
  638.         shouldround = context._rounding_decision == ALWAYS_ROUND
  639.         if not self or not other:
  640.             ans = Decimal((resultsign, (0,), resultexp))
  641.             if shouldround:
  642.                 ans = ans._fix(context)
  643.             
  644.             return ans
  645.         if self._int == (1,):
  646.             ans = Decimal((resultsign, other._int, resultexp))
  647.             return ans
  648.         if other._int == (1,):
  649.             ans = Decimal((resultsign, self._int, resultexp))
  650.             return ans
  651.         op1 = _WorkRep(self)
  652.         op2 = _WorkRep(other)
  653.         ans = Decimal((resultsign, map(int, str(op1.int * op2.int)), resultexp))
  654.         return ans
  655.  
  656.     __rmul__ = __mul__
  657.     
  658.     def __div__(self, other, context = None):
  659.         return self._divide(other, context = context)
  660.  
  661.     __truediv__ = __div__
  662.     
  663.     def _divide(self, other, divmod = 0, context = None):
  664.         other = _convert_other(other)
  665.         if context is None:
  666.             context = getcontext()
  667.         
  668.         sign = self._sign ^ other._sign
  669.         if not self and not other:
  670.             if divmod:
  671.                 return context._raise_error(DivisionUndefined, '0 / 0', 1)
  672.             return context._raise_error(DivisionUndefined, '0 / 0')
  673.         if not self:
  674.             if divmod:
  675.                 otherside = Decimal(self)
  676.                 otherside._exp = min(self._exp, other._exp)
  677.                 return (Decimal((sign, (0,), 0)), otherside)
  678.             exp = self._exp - other._exp
  679.             return Decimal((sign, (0,), exp))
  680.         if not other:
  681.             if divmod:
  682.                 return context._raise_error(DivisionByZero, 'divmod(x,0)', sign, 1)
  683.             return context._raise_error(DivisionByZero, 'x / 0', sign)
  684.         shouldround = context._rounding_decision == ALWAYS_ROUND
  685.         op1 = _WorkRep(self)
  686.         op2 = _WorkRep(other)
  687.         (op1, op2, adjust) = _adjust_coefficients(op1, op2)
  688.         res = _WorkRep((sign, 0, op1.exp - op2.exp))
  689.         if divmod and res.exp > context.prec + 1:
  690.             return context._raise_error(DivisionImpossible)
  691.         prec_limit = 10 ** context.prec
  692.         while None:
  693.             while op2.int <= op1.int:
  694.                 res.int += 1
  695.                 op1.int -= op2.int
  696.                 continue
  697.                 op1
  698.             if res.exp == 0 and divmod:
  699.                 if res.int >= prec_limit and shouldround:
  700.                     return context._raise_error(DivisionImpossible)
  701.                 otherside = Decimal(op1)
  702.                 frozen = context._ignore_all_flags()
  703.                 exp = min(self._exp, other._exp)
  704.                 otherside = otherside._rescale(exp, context = context, watchexp = 0)
  705.                 context._regard_flags(*frozen)
  706.                 return (Decimal(res), otherside)
  707.             res.int *= 10
  708.             res.exp -= 1
  709.             adjust += 1
  710.             op1.int *= 10
  711.             op1.exp -= 1
  712.             if res.exp == 0 and divmod and op2.int > op1.int:
  713.                 if res.int >= prec_limit and shouldround:
  714.                     return context._raise_error(DivisionImpossible)
  715.                 otherside = Decimal(op1)
  716.                 frozen = context._ignore_all_flags()
  717.                 exp = min(self._exp, other._exp)
  718.                 otherside = otherside._rescale(exp, context = context)
  719.                 context._regard_flags(*frozen)
  720.                 return (Decimal(res), otherside)
  721.             continue
  722.             ans = Decimal(res)
  723.         return ans
  724.  
  725.     
  726.     def __rdiv__(self, other, context = None):
  727.         other = _convert_other(other)
  728.         return other.__div__(self, context = context)
  729.  
  730.     __rtruediv__ = __rdiv__
  731.     
  732.     def __divmod__(self, other, context = None):
  733.         return self._divide(other, 1, context)
  734.  
  735.     
  736.     def __rdivmod__(self, other, context = None):
  737.         other = _convert_other(other)
  738.         return other.__divmod__(self, context = context)
  739.  
  740.     
  741.     def __mod__(self, other, context = None):
  742.         other = _convert_other(other)
  743.         if self._is_special or other._is_special:
  744.             ans = self._check_nans(other, context)
  745.             if ans:
  746.                 return ans
  747.         
  748.         if self and not other:
  749.             return context._raise_error(InvalidOperation, 'x % 0')
  750.         return self._divide(other, 3, context)[1]
  751.  
  752.     
  753.     def __rmod__(self, other, context = None):
  754.         other = _convert_other(other)
  755.         return other.__mod__(self, context = context)
  756.  
  757.     
  758.     def remainder_near(self, other, context = None):
  759.         other = _convert_other(other)
  760.         if self._is_special or other._is_special:
  761.             ans = self._check_nans(other, context)
  762.             if ans:
  763.                 return ans
  764.         
  765.         if self and not other:
  766.             return context._raise_error(InvalidOperation, 'x % 0')
  767.         if context is None:
  768.             context = getcontext()
  769.         
  770.         context = context._shallow_copy()
  771.         flags = context._ignore_flags(Rounded, Inexact)
  772.         (side, r) = self.__divmod__(other, context = context)
  773.         if r._isnan():
  774.             context._regard_flags(*flags)
  775.             return r
  776.         context = context._shallow_copy()
  777.         rounding = context._set_rounding_decision(NEVER_ROUND)
  778.         if other._sign:
  779.             comparison = other.__div__(Decimal(-2), context = context)
  780.         else:
  781.             comparison = other.__div__(Decimal(2), context = context)
  782.         context._set_rounding_decision(rounding)
  783.         context._regard_flags(*flags)
  784.         s1 = r._sign
  785.         s2 = comparison._sign
  786.         (r._sign, comparison._sign) = (0, 0)
  787.         if r < comparison:
  788.             r._sign = s1
  789.             comparison._sign = s2
  790.             self.__divmod__(other, context = context)
  791.             return r._fix(context)
  792.         r._sign = s1
  793.         comparison._sign = s2
  794.         rounding = context._set_rounding_decision(NEVER_ROUND)
  795.         (side, r) = self.__divmod__(other, context = context)
  796.         context._set_rounding_decision(rounding)
  797.         if r._isnan():
  798.             return r
  799.         decrease = not side._iseven()
  800.         rounding = context._set_rounding_decision(NEVER_ROUND)
  801.         side = side.__abs__(context = context)
  802.         context._set_rounding_decision(rounding)
  803.         s1 = r._sign
  804.         s2 = comparison._sign
  805.         (r._sign, comparison._sign) = (0, 0)
  806.         return r._fix(context)
  807.  
  808.     
  809.     def __floordiv__(self, other, context = None):
  810.         return self._divide(other, 2, context)[0]
  811.  
  812.     
  813.     def __rfloordiv__(self, other, context = None):
  814.         other = _convert_other(other)
  815.         return other.__floordiv__(self, context = context)
  816.  
  817.     
  818.     def __float__(self):
  819.         return float(str(self))
  820.  
  821.     
  822.     def __int__(self):
  823.         if self._is_special:
  824.             if self._isnan():
  825.                 context = getcontext()
  826.                 return context._raise_error(InvalidContext)
  827.             if self._isinfinity():
  828.                 raise OverflowError, 'Cannot convert infinity to long'
  829.             self._isinfinity()
  830.         
  831.         if self._exp >= 0:
  832.             s = ''.join(map(str, self._int)) + '0' * self._exp
  833.         else:
  834.             s = ''.join(map(str, self._int))[:self._exp]
  835.         if s == '':
  836.             s = '0'
  837.         
  838.         sign = '-' * self._sign
  839.         return int(sign + s)
  840.  
  841.     
  842.     def __long__(self):
  843.         return long(self.__int__())
  844.  
  845.     
  846.     def _fix(self, context):
  847.         if self._is_special:
  848.             return self
  849.         if context is None:
  850.             context = getcontext()
  851.         
  852.         prec = context.prec
  853.         ans = self._fixexponents(context)
  854.         if len(ans._int) > prec:
  855.             ans = ans._round(prec, context = context)
  856.             ans = ans._fixexponents(context)
  857.         
  858.         return ans
  859.  
  860.     
  861.     def _fixexponents(self, context):
  862.         folddown = context._clamp
  863.         Emin = context.Emin
  864.         ans = self
  865.         ans_adjusted = ans.adjusted()
  866.         return ans
  867.  
  868.     
  869.     def _round(self, prec = None, rounding = None, context = None):
  870.         if context is None:
  871.             context = getcontext()
  872.         
  873.         if rounding is None:
  874.             rounding = context.rounding
  875.         
  876.         if prec is None:
  877.             prec = context.prec
  878.         
  879.         if not self:
  880.             if prec <= 0:
  881.                 dig = (0,)
  882.                 exp = (len(self._int) - prec) + self._exp
  883.             else:
  884.                 dig = (0,) * prec
  885.                 exp = len(self._int) + self._exp - prec
  886.             ans = Decimal((self._sign, dig, exp))
  887.             context._raise_error(Rounded)
  888.             return ans
  889.         if prec == 0:
  890.             temp = Decimal(self)
  891.             temp._int = (0,) + temp._int
  892.             prec = 1
  893.         elif prec < 0:
  894.             exp = self._exp + len(self._int) - prec - 1
  895.             temp = Decimal((self._sign, (0, 1), exp))
  896.             prec = 1
  897.         else:
  898.             temp = Decimal(self)
  899.         numdigits = len(temp._int)
  900.         if prec == numdigits:
  901.             return temp
  902.         expdiff = prec - numdigits
  903.         if expdiff > 0:
  904.             tmp = list(temp._int)
  905.             tmp.extend([
  906.                 0] * expdiff)
  907.             ans = Decimal((temp._sign, tmp, temp._exp - expdiff))
  908.             return ans
  909.         lostdigits = self._int[expdiff:]
  910.         if lostdigits == (0,) * len(lostdigits):
  911.             ans = Decimal((temp._sign, temp._int[:prec], temp._exp - expdiff))
  912.             context._raise_error(Rounded)
  913.             return ans
  914.         this_function = getattr(temp, self._pick_rounding_function[rounding])
  915.         ans = this_function(prec, expdiff, context)
  916.         context._raise_error(Rounded)
  917.         context._raise_error(Inexact, 'Changed in rounding')
  918.         return ans
  919.  
  920.     _pick_rounding_function = { }
  921.     
  922.     def _round_down(self, prec, expdiff, context):
  923.         return Decimal((self._sign, self._int[:prec], self._exp - expdiff))
  924.  
  925.     
  926.     def _round_half_up(self, prec, expdiff, context, tmp = None):
  927.         if tmp is None:
  928.             tmp = Decimal((self._sign, self._int[:prec], self._exp - expdiff))
  929.         
  930.         if self._int[prec] >= 5:
  931.             tmp = tmp._increment(round = 0, context = context)
  932.             if len(tmp._int) > prec:
  933.                 return Decimal((tmp._sign, tmp._int[:-1], tmp._exp + 1))
  934.         
  935.         return tmp
  936.  
  937.     
  938.     def _round_half_even(self, prec, expdiff, context):
  939.         tmp = Decimal((self._sign, self._int[:prec], self._exp - expdiff))
  940.         half = self._int[prec] == 5
  941.         if half:
  942.             for digit in self._int[prec + 1:]:
  943.                 if digit != 0:
  944.                     half = 0
  945.                     break
  946.                     continue
  947.             
  948.         
  949.         if half:
  950.             if self._int[prec - 1] & 1 == 0:
  951.                 return tmp
  952.         
  953.         return self._round_half_up(prec, expdiff, context, tmp)
  954.  
  955.     
  956.     def _round_half_down(self, prec, expdiff, context):
  957.         tmp = Decimal((self._sign, self._int[:prec], self._exp - expdiff))
  958.         half = self._int[prec] == 5
  959.         if half:
  960.             for digit in self._int[prec + 1:]:
  961.                 if digit != 0:
  962.                     half = 0
  963.                     break
  964.                     continue
  965.             
  966.         
  967.         if half:
  968.             return tmp
  969.         return self._round_half_up(prec, expdiff, context, tmp)
  970.  
  971.     
  972.     def _round_up(self, prec, expdiff, context):
  973.         tmp = Decimal((self._sign, self._int[:prec], self._exp - expdiff))
  974.         for digit in self._int[prec:]:
  975.             if digit != 0:
  976.                 tmp = tmp._increment(round = 1, context = context)
  977.                 if len(tmp._int) > prec:
  978.                     return Decimal((tmp._sign, tmp._int[:-1], tmp._exp + 1))
  979.                 return tmp
  980.             digit != 0
  981.         
  982.         return tmp
  983.  
  984.     
  985.     def _round_ceiling(self, prec, expdiff, context):
  986.         if self._sign:
  987.             return self._round_down(prec, expdiff, context)
  988.         return self._round_up(prec, expdiff, context)
  989.  
  990.     
  991.     def _round_floor(self, prec, expdiff, context):
  992.         if not self._sign:
  993.             return self._round_down(prec, expdiff, context)
  994.         return self._round_up(prec, expdiff, context)
  995.  
  996.     
  997.     def __pow__(self, n, modulo = None, context = None):
  998.         n = _convert_other(n)
  999.         if context is None:
  1000.             context = getcontext()
  1001.         
  1002.         if not n._isinteger():
  1003.             return context._raise_error(InvalidOperation, 'x ** (non-integer)')
  1004.         if not self and not n:
  1005.             return context._raise_error(InvalidOperation, '0 ** 0')
  1006.         if not n:
  1007.             return Decimal(1)
  1008.         if self == Decimal(1):
  1009.             return Decimal(1)
  1010.         if self._sign:
  1011.             pass
  1012.         sign = not n._iseven()
  1013.         n = int(n)
  1014.         if self._isinfinity():
  1015.             if modulo:
  1016.                 return context._raise_error(InvalidOperation, 'INF % x')
  1017.             if n > 0:
  1018.                 return Infsign[sign]
  1019.             return Decimal((sign, (0,), 0))
  1020.         if not modulo and n > 0 and (self._exp + len(self._int) - 1) * n > context.Emax and self:
  1021.             tmp = Decimal('inf')
  1022.             tmp._sign = sign
  1023.             context._raise_error(Rounded)
  1024.             context._raise_error(Inexact)
  1025.             context._raise_error(Overflow, 'Big power', sign)
  1026.             return tmp
  1027.         elength = len(str(abs(n)))
  1028.         firstprec = context.prec
  1029.         if not modulo and firstprec + elength + 1 > DefaultContext.Emax:
  1030.             return context._raise_error(Overflow, 'Too much precision.', sign)
  1031.         mul = Decimal(self)
  1032.         val = Decimal(1)
  1033.         context = context._shallow_copy()
  1034.         context.prec = firstprec + elength + 1
  1035.         spot = 1
  1036.         while spot <= n:
  1037.             spot <<= 1
  1038.             continue
  1039.             self._isinfinity() if n < 0 else self
  1040.         spot >>= 1
  1041.         while spot:
  1042.             val = val.__mul__(val, context = context)
  1043.             if modulo is not None:
  1044.                 val = val.__mod__(modulo, context = context)
  1045.             
  1046.             spot >>= 1
  1047.         context.prec = firstprec
  1048.         if context._rounding_decision == ALWAYS_ROUND:
  1049.             return val._fix(context)
  1050.         return val
  1051.  
  1052.     
  1053.     def __rpow__(self, other, context = None):
  1054.         other = _convert_other(other)
  1055.         return other.__pow__(self, context = context)
  1056.  
  1057.     
  1058.     def normalize(self, context = None):
  1059.         if self._is_special:
  1060.             ans = self._check_nans(context = context)
  1061.             if ans:
  1062.                 return ans
  1063.         
  1064.         dup = self._fix(context)
  1065.         if dup._isinfinity():
  1066.             return dup
  1067.         if not dup:
  1068.             return Decimal((dup._sign, (0,), 0))
  1069.         end = len(dup._int)
  1070.         exp = dup._exp
  1071.         while dup._int[end - 1] == 0:
  1072.             exp += 1
  1073.             end -= 1
  1074.             continue
  1075.             dup
  1076.         return Decimal((dup._sign, dup._int[:end], exp))
  1077.  
  1078.     
  1079.     def quantize(self, exp, rounding = None, context = None, watchexp = 1):
  1080.         return self._rescale(exp._exp, rounding, context, watchexp)
  1081.  
  1082.     
  1083.     def same_quantum(self, other):
  1084.         return self._exp == other._exp
  1085.  
  1086.     
  1087.     def _rescale(self, exp, rounding = None, context = None, watchexp = 1):
  1088.         if context is None:
  1089.             context = getcontext()
  1090.         
  1091.         if watchexp:
  1092.             if context.Emax < exp or context.Etiny() > exp:
  1093.                 return context._raise_error(InvalidOperation, 'rescale(a, INF)')
  1094.             if not self:
  1095.                 ans = Decimal(self)
  1096.                 ans._int = (0,)
  1097.                 ans._exp = exp
  1098.                 return ans
  1099.             diff = self._exp - exp
  1100.             digits = len(self._int) + diff
  1101.             if watchexp and digits > context.prec:
  1102.                 return context._raise_error(InvalidOperation, 'Rescale > prec')
  1103.             tmp = Decimal(self)
  1104.             tmp._int = (0,) + tmp._int
  1105.             digits += 1
  1106.         tmp = tmp._round(digits, rounding, context = context)
  1107.         tmp._exp = exp
  1108.         tmp_adjusted = tmp.adjusted()
  1109.         if tmp and tmp_adjusted < context.Emin:
  1110.             context._raise_error(Subnormal)
  1111.         elif tmp and tmp_adjusted > context.Emax:
  1112.             return context._raise_error(InvalidOperation, 'rescale(a, INF)')
  1113.         return tmp
  1114.  
  1115.     
  1116.     def to_integral(self, rounding = None, context = None):
  1117.         if self._is_special:
  1118.             ans = self._check_nans(context = context)
  1119.             if ans:
  1120.                 return ans
  1121.         
  1122.         if self._exp >= 0:
  1123.             return self
  1124.         if context is None:
  1125.             context = getcontext()
  1126.         
  1127.         flags = context._ignore_flags(Rounded, Inexact)
  1128.         ans = self._rescale(0, rounding, context = context)
  1129.         context._regard_flags(flags)
  1130.         return ans
  1131.  
  1132.     
  1133.     def sqrt(self, context = None):
  1134.         if not self:
  1135.             exp = self._exp // 2
  1136.             if self._sign == 1:
  1137.                 return Decimal((1, (0,), exp))
  1138.             return Decimal((0, (0,), exp))
  1139.         self
  1140.         if context is None:
  1141.             context = getcontext()
  1142.         
  1143.         if self._sign == 1:
  1144.             return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
  1145.         tmp = Decimal(self)
  1146.         expadd = tmp._exp // 2
  1147.         context = context._shallow_copy()
  1148.         flags = context._ignore_all_flags()
  1149.         firstprec = context.prec
  1150.         context.prec = 3
  1151.         Emax = context.Emax
  1152.         Emin = context.Emin
  1153.         context.Emax = DefaultContext.Emax
  1154.         context.Emin = DefaultContext.Emin
  1155.         half = Decimal('0.5')
  1156.         maxp = firstprec + 2
  1157.         rounding = context._set_rounding(ROUND_HALF_EVEN)
  1158.         while None:
  1159.             context.prec = min(2 * context.prec - 2, maxp)
  1160.             ans = half.__mul__(ans.__add__(tmp.__div__(ans, context = context), context = context), context = context)
  1161.             if context.prec == maxp:
  1162.                 break
  1163.                 continue
  1164.             continue
  1165.             context.prec = firstprec
  1166.             prevexp = ans.adjusted()
  1167.             ans = ans._round(context = context)
  1168.             context.prec = firstprec + 1
  1169.         lower = ans.__sub__(Decimal((0, (5,), ans._exp - 1)), context = context)
  1170.         context._set_rounding(ROUND_UP)
  1171.         if lower.__mul__(lower, context = context) > tmp:
  1172.             ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context = context)
  1173.         else:
  1174.             upper = ans.__add__(Decimal((0, (5,), ans._exp - 1)), context = context)
  1175.             context._set_rounding(ROUND_DOWN)
  1176.             if upper.__mul__(upper, context = context) < tmp:
  1177.                 ans = ans.__add__(Decimal((0, (1,), ans._exp)), context = context)
  1178.             
  1179.         ans._exp += expadd
  1180.         context.prec = firstprec
  1181.         context.rounding = rounding
  1182.         ans = ans._fix(context)
  1183.         rounding = context._set_rounding_decision(NEVER_ROUND)
  1184.         context.Emax = Emax
  1185.         context.Emin = Emin
  1186.         return ans._fix(context)
  1187.  
  1188.     
  1189.     def max(self, other, context = None):
  1190.         other = _convert_other(other)
  1191.         if self._is_special or other._is_special:
  1192.             sn = self._isnan()
  1193.             on = other._isnan()
  1194.             if sn or on:
  1195.                 if on == 1 and sn != 2:
  1196.                     return self
  1197.                 if sn == 1 and on != 2:
  1198.                     return other
  1199.                 return self._check_nans(other, context)
  1200.         
  1201.         ans = self
  1202.         c = self.__cmp__(other)
  1203.         if c == 0:
  1204.             if self._sign != other._sign:
  1205.                 if self._sign:
  1206.                     ans = other
  1207.                 
  1208.             elif self._exp < other._exp and not (self._sign):
  1209.                 ans = other
  1210.             elif self._exp > other._exp and self._sign:
  1211.                 ans = other
  1212.             
  1213.         elif c == -1:
  1214.             ans = other
  1215.         
  1216.         if context is None:
  1217.             context = getcontext()
  1218.         
  1219.         if context._rounding_decision == ALWAYS_ROUND:
  1220.             return ans._fix(context)
  1221.         return ans
  1222.  
  1223.     
  1224.     def min(self, other, context = None):
  1225.         other = _convert_other(other)
  1226.         if self._is_special or other._is_special:
  1227.             sn = self._isnan()
  1228.             on = other._isnan()
  1229.             if sn or on:
  1230.                 if on == 1 and sn != 2:
  1231.                     return self
  1232.                 if sn == 1 and on != 2:
  1233.                     return other
  1234.                 return self._check_nans(other, context)
  1235.         
  1236.         ans = self
  1237.         c = self.__cmp__(other)
  1238.         if c == 0:
  1239.             if self._sign != other._sign:
  1240.                 if other._sign:
  1241.                     ans = other
  1242.                 
  1243.             elif self._exp > other._exp and not (self._sign):
  1244.                 ans = other
  1245.             elif self._exp < other._exp and self._sign:
  1246.                 ans = other
  1247.             
  1248.         elif c == 1:
  1249.             ans = other
  1250.         
  1251.         if context is None:
  1252.             context = getcontext()
  1253.         
  1254.         if context._rounding_decision == ALWAYS_ROUND:
  1255.             return ans._fix(context)
  1256.         return ans
  1257.  
  1258.     
  1259.     def _isinteger(self):
  1260.         if self._exp >= 0:
  1261.             return True
  1262.         rest = self._int[self._exp:]
  1263.         return rest == (0,) * len(rest)
  1264.  
  1265.     
  1266.     def _iseven(self):
  1267.         if self._exp > 0:
  1268.             return 1
  1269.         return self._int[-1 + self._exp] & 1 == 0
  1270.  
  1271.     
  1272.     def adjusted(self):
  1273.         
  1274.         try:
  1275.             return self._exp + len(self._int) - 1
  1276.         except TypeError:
  1277.             return 0
  1278.  
  1279.  
  1280.     
  1281.     def __reduce__(self):
  1282.         return (self.__class__, (str(self),))
  1283.  
  1284.     
  1285.     def __copy__(self):
  1286.         if type(self) == Decimal:
  1287.             return self
  1288.         return self.__class__(str(self))
  1289.  
  1290.     
  1291.     def __deepcopy__(self, memo):
  1292.         if type(self) == Decimal:
  1293.             return self
  1294.         return self.__class__(str(self))
  1295.  
  1296.  
  1297. rounding_functions = [] if name.startswith('_round_') else _[1]
  1298. for name in rounding_functions:
  1299.     globalname = name[1:].upper()
  1300.     val = globals()[globalname]
  1301.     Decimal._pick_rounding_function[val] = name
  1302.  
  1303. del name
  1304. del val
  1305. del globalname
  1306. del rounding_functions
  1307.  
  1308. class Context(object):
  1309.     
  1310.     def __init__(self, prec = None, rounding = None, traps = None, flags = None, _rounding_decision = None, Emin = None, Emax = None, capitals = None, _clamp = 0, _ignored_flags = None):
  1311.         if flags is None:
  1312.             flags = []
  1313.         
  1314.         if _ignored_flags is None:
  1315.             _ignored_flags = []
  1316.         
  1317.         for name, val in locals().items():
  1318.             if val is None:
  1319.                 setattr(self, name, copy.copy(getattr(DefaultContext, name)))
  1320.                 continue
  1321.             None if not isinstance(flags, dict) else dict if traps is not None and not isinstance(traps, dict) else dict
  1322.             setattr(self, name, val)
  1323.         
  1324.         del self.self
  1325.  
  1326.     
  1327.     def __repr__(self):
  1328.         s = []
  1329.         s.append('Context(prec=%(prec)d, rounding=%(rounding)s, Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self))
  1330.         ', '.join([] + [](_[1]) + ']')
  1331.         ', '.join([] + [](_[2]) + ']')
  1332.         return ', '.join(s) + ')'
  1333.  
  1334.     
  1335.     def clear_flags(self):
  1336.         for flag in self.flags:
  1337.             self.flags[flag] = 0
  1338.         
  1339.  
  1340.     
  1341.     def _shallow_copy(self):
  1342.         nc = Context(self.prec, self.rounding, self.traps, self.flags, self._rounding_decision, self.Emin, self.Emax, self.capitals, self._clamp, self._ignored_flags)
  1343.         return nc
  1344.  
  1345.     
  1346.     def copy(self):
  1347.         nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(), self._rounding_decision, self.Emin, self.Emax, self.capitals, self._clamp, self._ignored_flags)
  1348.         return nc
  1349.  
  1350.     __copy__ = copy
  1351.     
  1352.     def _raise_error(self, condition, explanation = None, *args):
  1353.         error = _condition_map.get(condition, condition)
  1354.         if error in self._ignored_flags:
  1355.             return error().handle(self, *args)
  1356.         self.flags[error] += 1
  1357.         if not self.traps[error]:
  1358.             return condition().handle(self, *args)
  1359.         raise error, explanation
  1360.  
  1361.     
  1362.     def _ignore_all_flags(self):
  1363.         return self._ignore_flags(*_signals)
  1364.  
  1365.     
  1366.     def _ignore_flags(self, *flags):
  1367.         self._ignored_flags = self._ignored_flags + list(flags)
  1368.         return list(flags)
  1369.  
  1370.     
  1371.     def _regard_flags(self, *flags):
  1372.         if flags and isinstance(flags[0], (tuple, list)):
  1373.             flags = flags[0]
  1374.         
  1375.         for flag in flags:
  1376.             self._ignored_flags.remove(flag)
  1377.         
  1378.  
  1379.     
  1380.     def __hash__(self):
  1381.         raise TypeError, 'Cannot hash a Context.'
  1382.  
  1383.     
  1384.     def Etiny(self):
  1385.         return int((self.Emin - self.prec) + 1)
  1386.  
  1387.     
  1388.     def Etop(self):
  1389.         return int((self.Emax - self.prec) + 1)
  1390.  
  1391.     
  1392.     def _set_rounding_decision(self, type):
  1393.         rounding = self._rounding_decision
  1394.         self._rounding_decision = type
  1395.         return rounding
  1396.  
  1397.     
  1398.     def _set_rounding(self, type):
  1399.         rounding = self.rounding
  1400.         self.rounding = type
  1401.         return rounding
  1402.  
  1403.     
  1404.     def create_decimal(self, num = '0'):
  1405.         d = Decimal(num, context = self)
  1406.         return d._fix(self)
  1407.  
  1408.     
  1409.     def abs(self, a):
  1410.         return a.__abs__(context = self)
  1411.  
  1412.     
  1413.     def add(self, a, b):
  1414.         return a.__add__(b, context = self)
  1415.  
  1416.     
  1417.     def _apply(self, a):
  1418.         return str(a._fix(self))
  1419.  
  1420.     
  1421.     def compare(self, a, b):
  1422.         return a.compare(b, context = self)
  1423.  
  1424.     
  1425.     def divide(self, a, b):
  1426.         return a.__div__(b, context = self)
  1427.  
  1428.     
  1429.     def divide_int(self, a, b):
  1430.         return a.__floordiv__(b, context = self)
  1431.  
  1432.     
  1433.     def divmod(self, a, b):
  1434.         return a.__divmod__(b, context = self)
  1435.  
  1436.     
  1437.     def max(self, a, b):
  1438.         return a.max(b, context = self)
  1439.  
  1440.     
  1441.     def min(self, a, b):
  1442.         return a.min(b, context = self)
  1443.  
  1444.     
  1445.     def minus(self, a):
  1446.         return a.__neg__(context = self)
  1447.  
  1448.     
  1449.     def multiply(self, a, b):
  1450.         return a.__mul__(b, context = self)
  1451.  
  1452.     
  1453.     def normalize(self, a):
  1454.         return a.normalize(context = self)
  1455.  
  1456.     
  1457.     def plus(self, a):
  1458.         return a.__pos__(context = self)
  1459.  
  1460.     
  1461.     def power(self, a, b, modulo = None):
  1462.         return a.__pow__(b, modulo, context = self)
  1463.  
  1464.     
  1465.     def quantize(self, a, b):
  1466.         return a.quantize(b, context = self)
  1467.  
  1468.     
  1469.     def remainder(self, a, b):
  1470.         return a.__mod__(b, context = self)
  1471.  
  1472.     
  1473.     def remainder_near(self, a, b):
  1474.         return a.remainder_near(b, context = self)
  1475.  
  1476.     
  1477.     def same_quantum(self, a, b):
  1478.         return a.same_quantum(b)
  1479.  
  1480.     
  1481.     def sqrt(self, a):
  1482.         return a.sqrt(context = self)
  1483.  
  1484.     
  1485.     def subtract(self, a, b):
  1486.         return a.__sub__(b, context = self)
  1487.  
  1488.     
  1489.     def to_eng_string(self, a):
  1490.         return a.to_eng_string(context = self)
  1491.  
  1492.     
  1493.     def to_sci_string(self, a):
  1494.         return a.__str__(context = self)
  1495.  
  1496.     
  1497.     def to_integral(self, a):
  1498.         return a.to_integral(context = self)
  1499.  
  1500.  
  1501.  
  1502. class _WorkRep(object):
  1503.     __slots__ = ('sign', 'int', 'exp')
  1504.     
  1505.     def __init__(self, value = None):
  1506.         if value is None:
  1507.             self.sign = None
  1508.             self.int = 0
  1509.             self.exp = None
  1510.         elif isinstance(value, Decimal):
  1511.             self.sign = value._sign
  1512.             cum = 0
  1513.             for digit in value._int:
  1514.                 cum = cum * 10 + digit
  1515.             
  1516.             self.int = cum
  1517.             self.exp = value._exp
  1518.         else:
  1519.             self.sign = value[0]
  1520.             self.int = value[1]
  1521.             self.exp = value[2]
  1522.  
  1523.     
  1524.     def __repr__(self):
  1525.         return '(%r, %r, %r)' % (self.sign, self.int, self.exp)
  1526.  
  1527.     __str__ = __repr__
  1528.  
  1529.  
  1530. def _normalize(op1, op2, shouldround = 0, prec = 0):
  1531.     numdigits = int(op1.exp - op2.exp)
  1532.     if numdigits < 0:
  1533.         numdigits = -numdigits
  1534.         tmp = op2
  1535.         other = op1
  1536.     else:
  1537.         tmp = op1
  1538.         other = op2
  1539.     if shouldround and numdigits > prec + 1:
  1540.         tmp_len = len(str(tmp.int))
  1541.         other_len = len(str(other.int))
  1542.         if numdigits > other_len + prec + 1 - tmp_len:
  1543.             extend = prec + 2 - tmp_len
  1544.             if extend <= 0:
  1545.                 extend = 1
  1546.             
  1547.             tmp.int *= 10 ** extend
  1548.             tmp.exp -= extend
  1549.             other.int = 1
  1550.             other.exp = tmp.exp
  1551.             return (op1, op2)
  1552.     
  1553.     tmp.int *= 10 ** numdigits
  1554.     tmp.exp -= numdigits
  1555.     return (op1, op2)
  1556.  
  1557.  
  1558. def _adjust_coefficients(op1, op2):
  1559.     adjust = 0
  1560.     while op2.int > op1.int:
  1561.         op1.int *= 10
  1562.         op1.exp -= 1
  1563.         adjust += 1
  1564.         continue
  1565.         op1
  1566.     while op1.int >= 10 * op2.int:
  1567.         op2.int *= 10
  1568.         op2.exp -= 1
  1569.         adjust -= 1
  1570.         continue
  1571.         op2
  1572.     return (op1, op2, adjust)
  1573.  
  1574.  
  1575. def _convert_other(other):
  1576.     if isinstance(other, Decimal):
  1577.         return other
  1578.     if isinstance(other, (int, long)):
  1579.         return Decimal(other)
  1580.     raise TypeError, 'You can interact Decimal only with int, long or Decimal data types.'
  1581.  
  1582. _infinity_map = {
  1583.     'inf': 1,
  1584.     'infinity': 1,
  1585.     '+inf': 1,
  1586.     '+infinity': 1,
  1587.     '-inf': -1,
  1588.     '-infinity': -1 }
  1589.  
  1590. def _isinfinity(num):
  1591.     num = str(num).lower()
  1592.     return _infinity_map.get(num, 0)
  1593.  
  1594.  
  1595. def _isnan(num):
  1596.     num = str(num).lower()
  1597.     if not num:
  1598.         return 0
  1599.     sign = 0
  1600.     if num[0] == '+':
  1601.         num = num[1:]
  1602.     elif num[0] == '-':
  1603.         num = num[1:]
  1604.         sign = 1
  1605.     
  1606.     if num.startswith('nan'):
  1607.         if len(num) > 3 and not num[3:].isdigit():
  1608.             return 0
  1609.         return (1, sign, num[3:].lstrip('0'))
  1610.     if num.startswith('snan'):
  1611.         if len(num) > 4 and not num[4:].isdigit():
  1612.             return 0
  1613.         return (2, sign, num[4:].lstrip('0'))
  1614.     return 0
  1615.  
  1616. DefaultContext = Context(prec = 28, rounding = ROUND_HALF_EVEN, traps = [
  1617.     DivisionByZero,
  1618.     Overflow,
  1619.     InvalidOperation], flags = [], _rounding_decision = ALWAYS_ROUND, Emax = 999999999, Emin = -999999999, capitals = 1)
  1620. BasicContext = Context(prec = 9, rounding = ROUND_HALF_UP, traps = [
  1621.     DivisionByZero,
  1622.     Overflow,
  1623.     InvalidOperation,
  1624.     Clamped,
  1625.     Underflow], flags = [])
  1626. ExtendedContext = Context(prec = 9, rounding = ROUND_HALF_EVEN, traps = [], flags = [])
  1627. Inf = Decimal('Inf')
  1628. negInf = Decimal('-Inf')
  1629. Infsign = (Inf, negInf)
  1630. NaN = Decimal('NaN')
  1631. import re
  1632. _parser = re.compile('\n#    \\s*\n    (?P<sign>[-+])?\n    (\n        (?P<int>\\d+) (\\. (?P<frac>\\d*))?\n    |\n        \\. (?P<onlyfrac>\\d+)\n    )\n    ([eE](?P<exp>[-+]? \\d+))?\n#    \\s*\n    $\n', re.VERBOSE).match
  1633. del re
  1634.  
  1635. def _string2exact(s):
  1636.     m = _parser(s)
  1637.     if m is None:
  1638.         raise ValueError('invalid literal for Decimal: %r' % s)
  1639.     m is None
  1640.     if m.group('sign') == '-':
  1641.         sign = 1
  1642.     else:
  1643.         sign = 0
  1644.     exp = m.group('exp')
  1645.     if exp is None:
  1646.         exp = 0
  1647.     else:
  1648.         exp = int(exp)
  1649.     intpart = m.group('int')
  1650.     if intpart is None:
  1651.         intpart = ''
  1652.         fracpart = m.group('onlyfrac')
  1653.     else:
  1654.         fracpart = m.group('frac')
  1655.         if fracpart is None:
  1656.             fracpart = ''
  1657.         
  1658.     exp -= len(fracpart)
  1659.     mantissa = intpart + fracpart
  1660.     tmp = map(int, mantissa)
  1661.     backup = tmp
  1662.     while tmp and tmp[0] == 0:
  1663.         del tmp[0]
  1664.     if not tmp:
  1665.         if backup:
  1666.             return (sign, tuple(backup), exp)
  1667.         return (sign, (0,), exp)
  1668.     mantissa = tuple(tmp)
  1669.     return (sign, mantissa, exp)
  1670.  
  1671. if __name__ == '__main__':
  1672.     import doctest
  1673.     import sys
  1674.     doctest.testmod(sys.modules[__name__])
  1675.  
  1676.