rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if opener == "else" or "elif":
if opener in ("else", "elif"):
def interesting_lines(self, firstline): """Generator which yields context lines, starting at firstline.""" # The indentation level we are currently in: lastindent = INFINITY # For a line to be interesting, it must begin with a block opening # keyword, and have less indentation than lastindent. for line_index in xrange(firstline, -1, -1): indent, text, opener = self.get_line_info(line_index) if indent < lastindent: lastindent = indent if opener == "else" or "elif": # We also show the if statement lastindent += 1 if opener and line_index < firstline: yield line_index, text
return scheme, url[len(scheme) + 1:]
return scheme.lower(), url[len(scheme) + 1:]
def splittype(url): """splittype('type:opaquestring') --> 'type', 'opaquestring'.""" global _typeprog if _typeprog is None: import re _typeprog = re.compile('^([^/:]+):') match = _typeprog.match(url) if match: scheme = match.group(1) return scheme, url[len(scheme) + 1:] return None, url
epoch = time.gmtime(0)[0]
gm_epoch = time.gmtime(0)[0:3] loc_epoch = time.localtime(0)[0:3]
def test_formatdate(self): now = 1005327232.109884 epoch = time.gmtime(0)[0] # When does the epoch start? if epoch == 1970: # traditional Unix epoch matchdate = 'Fri, 09 Nov 2001 17:33:52 -0000' elif epoch == 1904: # Mac epoch matchdate = 'Sat, 09 Nov 1935 16:33:52 -0000' else: matchdate = "I don't understand your epoch" gdate = Utils.formatdate(now) self.assertEqual(gdate, matchdate)
if epoch == 1970:
if gm_epoch == (1970, 1, 1):
def test_formatdate(self): now = 1005327232.109884 epoch = time.gmtime(0)[0] # When does the epoch start? if epoch == 1970: # traditional Unix epoch matchdate = 'Fri, 09 Nov 2001 17:33:52 -0000' elif epoch == 1904: # Mac epoch matchdate = 'Sat, 09 Nov 1935 16:33:52 -0000' else: matchdate = "I don't understand your epoch" gdate = Utils.formatdate(now) self.assertEqual(gdate, matchdate)
elif epoch == 1904:
elif loc_epoch == (1904, 1, 1):
def test_formatdate(self): now = 1005327232.109884 epoch = time.gmtime(0)[0] # When does the epoch start? if epoch == 1970: # traditional Unix epoch matchdate = 'Fri, 09 Nov 2001 17:33:52 -0000' elif epoch == 1904: # Mac epoch matchdate = 'Sat, 09 Nov 1935 16:33:52 -0000' else: matchdate = "I don't understand your epoch" gdate = Utils.formatdate(now) self.assertEqual(gdate, matchdate)
__slots__ = ('_exp','_int','_sign') def __init__(self, value="0", context=None):
__slots__ = ('_exp','_int','_sign', '_is_special') def __new__(cls, value="0", context=None):
def setcontext(context, _local=local): """Set this thread's context to context.""" if context in (DefaultContext, BasicContext, ExtendedContext): context = context.copy() context.clear_flags() _local.__decimal_context__ = context
if context is None: context = getcontext()
self = object.__new__(cls) self._is_special = False if isinstance(value, _WorkRep): if value.sign == 1: self._sign = 0 else: self._sign = 1 self._int = tuple(map(int, str(value.int))) self._exp = int(value.exp) return self if isinstance(value, Decimal): self._exp = value._exp self._sign = value._sign self._int = value._int self._is_special = value._is_special return self
def __init__(self, value="0", context=None): """Create a decimal point instance.
value = str(value) if isinstance(value, basestring): if _isinfinity(value): self._exp = 'F' self._int = (0,) sign = _isinfinity(value) if sign == 1: self._sign = 0 else: self._sign = 1 return if _isnan(value): sig, sign, diag = _isnan(value) if len(diag) > context.prec: self._sign, self._int, self._exp = \ context._raise_error(ConversionSyntax) return if sig == 1: self._exp = 'n' else: self._exp = 'N' self._sign = sign self._int = tuple(map(int, diag)) return try: self._sign, self._int, self._exp = _string2exact(value) except ValueError: self._sign, self._int, self._exp = context._raise_error(ConversionSyntax) return
if value >= 0: self._sign = 0 else: self._sign = 1 self._exp = 0 self._int = tuple(map(int, str(abs(value)))) return self
def __init__(self, value="0", context=None): """Create a decimal point instance.
return if isinstance(value, _WorkRep): if value.sign == 1: self._sign = 0 else: self._sign = 1 self._int = tuple(value.int) self._exp = int(value.exp) return if isinstance(value, Decimal): self._exp = value._exp self._sign = value._sign self._int = value._int return
return self
def __init__(self, value="0", context=None): """Create a decimal point instance.
raise TypeError("Cannot convert %r" % value) def _convert_other(self, other): """Convert other to Decimal. Verifies that it's ok to use in an implicit construction. """ if isinstance(other, Decimal): return other if isinstance(other, (int, long)): other = Decimal(other) return other raise TypeError, "You can interact Decimal only with int, long or Decimal data types."
if context is None: context = getcontext() if isinstance(value, basestring): if _isinfinity(value): self._exp = 'F' self._int = (0,) self._is_special = True if _isinfinity(value) == 1: self._sign = 0 else: self._sign = 1 return self if _isnan(value): sig, sign, diag = _isnan(value) self._is_special = True if len(diag) > context.prec: self._sign, self._int, self._exp = \ context._raise_error(ConversionSyntax) return self if sig == 1: self._exp = 'n' else: self._exp = 'N' self._sign = sign self._int = tuple(map(int, diag)) return self try: self._sign, self._int, self._exp = _string2exact(value) except ValueError: self._is_special = True self._sign, self._int, self._exp = context._raise_error(ConversionSyntax) return self raise TypeError("Cannot convert %r to Decimal" % value)
def __init__(self, value="0", context=None): """Create a decimal point instance.
if self._exp == 'n': return 1 elif self._exp == 'N': return 2
if self._is_special: exp = self._exp if exp == 'n': return 1 elif exp == 'N': return 2
def _isnan(self): """Returns whether the number is not actually one.
if context is None: context = getcontext() if self._isnan() == 2: return context._raise_error(InvalidOperation, 'sNaN', 1, self) if other is not None and other._isnan() == 2: return context._raise_error(InvalidOperation, 'sNaN', 1, other) if self._isnan(): return self if other is not None and other._isnan():
self_is_nan = self._isnan() if other is None: other_is_nan = False else: other_is_nan = other._isnan() if self_is_nan or other_is_nan: if context is None: context = getcontext() if self_is_nan == 2: return context._raise_error(InvalidOperation, 'sNaN', 1, self) if other_is_nan == 2: return context._raise_error(InvalidOperation, 'sNaN', 1, other) if self_is_nan: return self
def _check_nans(self, other = None, context=None): """Returns whether the number is not actually one.
if isinstance(self._exp, str):
if self._is_special:
def __nonzero__(self): """Is the number non-zero?
return self._int != (0,)*len(self._int)
return sum(self._int) != 0
def __nonzero__(self): """Is the number non-zero?
if context is None: context = getcontext() other = self._convert_other(other) ans = self._check_nans(other, context) if ans: return 1
other = _convert_other(other) if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return 1 return cmp(self._isinfinity(), other._isinfinity())
def __cmp__(self, other, context=None): if context is None: context = getcontext() other = self._convert_other(other)
if self._isinfinity() and other._isinfinity(): return 0 if self._isinfinity(): return (-1)**self._sign if other._isinfinity(): return -((-1)**other._sign) if self.adjusted() == other.adjusted() and \
self_adjusted = self.adjusted() other_adjusted = other.adjusted() if self_adjusted == other_adjusted and \
def __cmp__(self, other, context=None): if context is None: context = getcontext() other = self._convert_other(other)
elif self.adjusted() > other.adjusted() and self._int[0] != 0:
elif self_adjusted > other_adjusted and self._int[0] != 0:
def __cmp__(self, other, context=None): if context is None: context = getcontext() other = self._convert_other(other)
elif self.adjusted < other.adjusted() and other._int[0] != 0:
elif self_adjusted < other_adjusted and other._int[0] != 0:
def __cmp__(self, other, context=None): if context is None: context = getcontext() other = self._convert_other(other)
if context is None: context = getcontext() other = self._convert_other(other)
other = _convert_other(other)
def compare(self, other, context=None): """Compares one to another.
ans = self._check_nans(other, context) if ans: return ans
if (self._is_special or other and other._is_special): ans = self._check_nans(other, context) if ans: return ans
def compare(self, other, context=None): """Compares one to another.
if context is None: context = getcontext()
def to_eng_string(self, context=None): """Convert to engineering-type string.
if context is None: context = getcontext() ans = self._check_nans(context=context) if ans: return ans
if self._is_special: ans = self._check_nans(context=context) if ans: return ans
def __neg__(self, context=None): """Returns a copy with the sign switched.
if context is None: context = getcontext() ans = self._check_nans(context=context) if ans: return ans
if self._is_special: ans = self._check_nans(context=context) if ans: return ans
def __pos__(self, context=None): """Returns a copy, unless it is a sNaN.
if context is None: context = getcontext() ans = self._check_nans(context=context) if ans: return ans
if self._is_special: ans = self._check_nans(context=context) if ans: return ans
def __abs__(self, round=1, context=None): """Returns the absolute value of self.
other = self._convert_other(other) ans = self._check_nans(other, context) if ans: return ans if self._isinfinity(): if self._sign != other._sign and other._isinfinity(): return context._raise_error(InvalidOperation, '-INF + INF') return Decimal(self) if other._isinfinity(): return Decimal(other)
if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return ans if self._isinfinity(): if self._sign != other._sign and other._isinfinity(): return context._raise_error(InvalidOperation, '-INF + INF') return Decimal(self) if other._isinfinity(): return Decimal(other)
def __add__(self, other, context=None): """Returns self + other.
op1.int.reverse() op2.int.reverse()
def __add__(self, other, context=None): """Returns self + other.
result.int = resultint = map(operator.add, op1.int, op2.int) carry = 0 for i in xrange(len(op1.int)): tmp = resultint[i] + carry carry = 0 if tmp > 9: carry = 1 tmp -= 10 resultint[i] = tmp if carry: resultint.append(1)
result.int = op1.int + op2.int
def __add__(self, other, context=None): """Returns self + other.
result.int = resultint = map(operator.sub, op1.int, op2.int) loan = 0 for i in xrange(len(op1.int)): tmp = resultint[i] - loan loan = 0 if tmp < 0: loan = 1 tmp += 10 resultint[i] = tmp assert not loan while resultint[-1] == 0: resultint.pop() resultint.reverse()
result.int = op1.int - op2.int
def __add__(self, other, context=None): """Returns self + other.
if context is None: context = getcontext() other = self._convert_other(other) ans = self._check_nans(other, context=context) if ans: return ans
other = _convert_other(other) if self._is_special or other._is_special: ans = self._check_nans(other, context=context) if ans: return ans
def __sub__(self, other, context=None): """Return self + (-other)""" if context is None: context = getcontext() other = self._convert_other(other)
if context is None: context = getcontext() other = self._convert_other(other)
other = _convert_other(other)
def __rsub__(self, other, context=None): """Return other + (-self)""" if context is None: context = getcontext() other = self._convert_other(other)
if context is None: context = getcontext() ans = self._check_nans(context=context) if ans: return ans
if self._is_special: ans = self._check_nans(context=context) if ans: return ans return Decimal(self)
def _increment(self, round=1, context=None): """Special case of add, adding 1eExponent
other = self._convert_other(other) ans = self._check_nans(other, context) if ans: return ans
def __mul__(self, other, context=None): """Return self * other.
if self._isinfinity(): if not other: return context._raise_error(InvalidOperation, '(+-)INF * 0') return Infsign[resultsign] if other._isinfinity(): if not self: return context._raise_error(InvalidOperation, '0 * (+-)INF') return Infsign[resultsign]
if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return ans if self._isinfinity(): if not other: return context._raise_error(InvalidOperation, '(+-)INF * 0') return Infsign[resultsign] if other._isinfinity(): if not self: return context._raise_error(InvalidOperation, '0 * (+-)INF') return Infsign[resultsign]
def __mul__(self, other, context=None): """Return self * other.
op1 = list(self._int) op2 = list(other._int) op1.reverse() op2.reverse() if len(op2) > len(op1): op1, op2 = op2, op1 _divmod = divmod accumulator = [0]*(len(self._int) + len(other._int)) for i in xrange(len(op2)): if op2[i] == 0: continue mult = op2[i] carry = 0 for j in xrange(len(op1)): carry, accumulator[i+j] = _divmod( mult * op1[j] + carry + accumulator[i+j], 10) if carry: accumulator[i + j + 1] += carry while not accumulator[-1]: accumulator.pop() accumulator.reverse() ans = Decimal( (resultsign, accumulator, resultexp))
op1 = _WorkRep(self) op2 = _WorkRep(other) ans = Decimal( (resultsign, map(int, str(op1.int * op2.int)), resultexp))
def __mul__(self, other, context=None): """Return self * other.
other = self._convert_other(other) ans = self._check_nans(other, context) if ans: if divmod: return (ans, ans) else:
sign = self._sign ^ other._sign if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: if divmod: return (ans, ans)
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
sign = self._sign ^ other._sign if not self and not other: if divmod: return context._raise_error(DivisionUndefined, '0 / 0', 1) return context._raise_error(DivisionUndefined, '0 / 0') if self._isinfinity() and other._isinfinity(): if not divmod:
if self._isinfinity() and other._isinfinity(): if divmod: return (context._raise_error(InvalidOperation, '(+-)INF // (+-)INF'), context._raise_error(InvalidOperation, '(+-)INF % (+-)INF'))
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
else: return (context._raise_error(InvalidOperation, '(+-)INF // (+-)INF'), context._raise_error(InvalidOperation, '(+-)INF % (+-)INF')) if not divmod: if other._isinfinity(): context._raise_error(Clamped, 'Division by infinity') return Decimal((sign, (0,), context.Etiny())) if self._isinfinity(): return Infsign[sign] if not self: exp = self._exp - other._exp if exp < context.Etiny(): exp = context.Etiny() context._raise_error(Clamped, '0e-x / y') if exp > context.Emax: exp = context.Emax context._raise_error(Clamped, '0e+x / y') return Decimal( (sign, (0,), exp) ) if not other: return context._raise_error(DivisionByZero, 'x / 0', sign) if divmod: if other._isinfinity(): return (Decimal((sign, (0,), 0)), Decimal(self))
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
if not self:
return Infsign[sign] if other._isinfinity(): if divmod: return (Decimal((sign, (0,), 0)), Decimal(self)) context._raise_error(Clamped, 'Division by infinity') return Decimal((sign, (0,), context.Etiny())) if not self and not other: if divmod: return context._raise_error(DivisionUndefined, '0 / 0', 1) return context._raise_error(DivisionUndefined, '0 / 0') if not self: if divmod:
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
if not other:
exp = self._exp - other._exp if exp < context.Etiny(): exp = context.Etiny() context._raise_error(Clamped, '0e-x / y') if exp > context.Emax: exp = context.Emax context._raise_error(Clamped, '0e+x / y') return Decimal( (sign, (0,), exp) ) if not other: if divmod:
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
return context._raise_error(DivisionByZero, 'x / 0', sign)
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
res = _WorkRep( (sign, [0], (op1.exp - op2.exp)) )
res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) )
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
while( (len(op2.int) < len(op1.int) and op1.int[0]) or (len(op2.int) == len(op1.int) and op2.int <= op1.int)): res._increment() op1.subtract(op2.int)
while op2.int <= op1.int: res.int += 1 op1.int -= op2.int
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
if len(res.int) > context.prec and shouldround:
if res.int >= prec_limit and shouldround:
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
if op1.int == [0]*len(op1.int) and adjust >= 0 and not divmod:
if op1.int == 0 and adjust >= 0 and not divmod:
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
if (len(res.int) > context.prec) and shouldround:
if res.int >= prec_limit and shouldround:
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
if op1.int != [0]*len(op1.int): res.int.append(1)
if op1.int != 0: res.int *= 10 res.int += 1
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
res.int.append(0) op1.int.append(0)
op1.int *= 10
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
if res.exp == 0 and divmod and (len(op2.int) > len(op1.int) or (len(op2.int) == len(op1.int) and op2.int > op1.int)):
if res.exp == 0 and divmod and op2.int > op1.int:
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
other = self._convert_other(other)
other = _convert_other(other)
def __rdiv__(self, other, context=None): """Swaps self/other and returns __div__.""" other = self._convert_other(other) return other.__div__(self, context=context)
other = self._convert_other(other)
other = _convert_other(other)
def __rdivmod__(self, other, context=None): """Swaps self/other and returns __divmod__.""" other = self._convert_other(other) return other.__divmod__(self, context=context)
other = self._convert_other(other) ans = self._check_nans(other, context) if ans: return ans if self and not other: return context._raise_error(InvalidOperation, 'x % 0') return self._divide(other, 3, context)[1] def __rmod__(self, other, context=None): """Swaps self/other and returns __mod__.""" other = self._convert_other(other) return other.__mod__(self, context=context) def remainder_near(self, other, context=None): """ Remainder nearest to 0- abs(remainder-near) <= other/2 """ if context is None: context = getcontext() other = self._convert_other(other) ans = self._check_nans(other, context) if ans: return ans if self and not other: return context._raise_error(InvalidOperation, 'x % 0')
def __mod__(self, other, context=None): """ self % other """ if context is None: context = getcontext() other = self._convert_other(other)
other = self._convert_other(other)
other = _convert_other(other)
def __rfloordiv__(self, other, context=None): """Swaps self/other and returns __floordiv__.""" other = self._convert_other(other) return other.__floordiv__(self, context=context)
if self._isnan(): context = getcontext() return context._raise_error(InvalidContext) elif self._isinfinity(): raise OverflowError, "Cannot convert infinity to long"
if self._is_special: if self._isnan(): context = getcontext() return context._raise_error(InvalidContext) elif self._isinfinity(): raise OverflowError, "Cannot convert infinity to long"
def __int__(self): """Converts self to a int, truncating if necessary.""" if self._isnan(): context = getcontext() return context._raise_error(InvalidContext) elif self._isinfinity(): raise OverflowError, "Cannot convert infinity to long" if not self: return 0 sign = '-'*self._sign if self._exp >= 0: s = sign + ''.join(map(str, self._int)) + '0'*self._exp return int(s) s = sign + ''.join(map(str, self._int))[:self._exp] return int(s) tmp = list(self._int) tmp.reverse() val = 0 while tmp: val *= 10 val += tmp.pop() return int(((-1) ** self._sign) * val * 10.**int(self._exp))
tmp = list(self._int) tmp.reverse() val = 0 while tmp: val *= 10 val += tmp.pop() return int(((-1) ** self._sign) * val * 10.**int(self._exp))
def __int__(self): """Converts self to a int, truncating if necessary.""" if self._isnan(): context = getcontext() return context._raise_error(InvalidContext) elif self._isinfinity(): raise OverflowError, "Cannot convert infinity to long" if not self: return 0 sign = '-'*self._sign if self._exp >= 0: s = sign + ''.join(map(str, self._int)) + '0'*self._exp return int(s) s = sign + ''.join(map(str, self._int))[:self._exp] return int(s) tmp = list(self._int) tmp.reverse() val = 0 while tmp: val *= 10 val += tmp.pop() return int(((-1) ** self._sign) * val * 10.**int(self._exp))
if self._isinfinity() or self._isnan():
if self._is_special:
def _fix(self, prec=None, rounding=None, folddown=None, context=None): """Round if it is necessary to keep self within prec precision.
if self._isinfinity():
if self._is_special:
def _fixexponents(self, prec=None, rounding=None, folddown=None, context=None): """Fix the exponents and return a copy with the exponent in bounds.""" if self._isinfinity(): return self if context is None: context = getcontext() if prec is None: prec = context.prec if folddown is None: folddown = context._clamp Emin, Emax = context.Emin, context.Emax Etop = context.Etop() ans = Decimal(self) if ans.adjusted() < Emin: Etiny = context.Etiny() if ans._exp < Etiny: if not ans: ans._exp = Etiny context._raise_error(Clamped) return ans ans = ans._rescale(Etiny, context=context) #It isn't zero, and exp < Emin => subnormal context._raise_error(Subnormal) if context.flags[Inexact]: context._raise_error(Underflow) else: if ans: #Only raise subnormal if non-zero. context._raise_error(Subnormal) elif folddown and ans._exp > Etop: context._raise_error(Clamped) ans = ans._rescale(Etop, context=context) elif ans.adjusted() > Emax: if not ans: ans._exp = Emax context._raise_error(Clamped) return ans context._raise_error(Inexact) context._raise_error(Rounded) return context._raise_error(Overflow, 'above Emax', ans._sign) return ans
Emin, Emax = context.Emin, context.Emax Etop = context.Etop()
Emin = context.Emin
def _fixexponents(self, prec=None, rounding=None, folddown=None, context=None): """Fix the exponents and return a copy with the exponent in bounds.""" if self._isinfinity(): return self if context is None: context = getcontext() if prec is None: prec = context.prec if folddown is None: folddown = context._clamp Emin, Emax = context.Emin, context.Emax Etop = context.Etop() ans = Decimal(self) if ans.adjusted() < Emin: Etiny = context.Etiny() if ans._exp < Etiny: if not ans: ans._exp = Etiny context._raise_error(Clamped) return ans ans = ans._rescale(Etiny, context=context) #It isn't zero, and exp < Emin => subnormal context._raise_error(Subnormal) if context.flags[Inexact]: context._raise_error(Underflow) else: if ans: #Only raise subnormal if non-zero. context._raise_error(Subnormal) elif folddown and ans._exp > Etop: context._raise_error(Clamped) ans = ans._rescale(Etop, context=context) elif ans.adjusted() > Emax: if not ans: ans._exp = Emax context._raise_error(Clamped) return ans context._raise_error(Inexact) context._raise_error(Rounded) return context._raise_error(Overflow, 'above Emax', ans._sign) return ans
if ans.adjusted() < Emin:
ans_adjusted = ans.adjusted() if ans_adjusted < Emin:
def _fixexponents(self, prec=None, rounding=None, folddown=None, context=None): """Fix the exponents and return a copy with the exponent in bounds.""" if self._isinfinity(): return self if context is None: context = getcontext() if prec is None: prec = context.prec if folddown is None: folddown = context._clamp Emin, Emax = context.Emin, context.Emax Etop = context.Etop() ans = Decimal(self) if ans.adjusted() < Emin: Etiny = context.Etiny() if ans._exp < Etiny: if not ans: ans._exp = Etiny context._raise_error(Clamped) return ans ans = ans._rescale(Etiny, context=context) #It isn't zero, and exp < Emin => subnormal context._raise_error(Subnormal) if context.flags[Inexact]: context._raise_error(Underflow) else: if ans: #Only raise subnormal if non-zero. context._raise_error(Subnormal) elif folddown and ans._exp > Etop: context._raise_error(Clamped) ans = ans._rescale(Etop, context=context) elif ans.adjusted() > Emax: if not ans: ans._exp = Emax context._raise_error(Clamped) return ans context._raise_error(Inexact) context._raise_error(Rounded) return context._raise_error(Overflow, 'above Emax', ans._sign) return ans
elif folddown and ans._exp > Etop: context._raise_error(Clamped) ans = ans._rescale(Etop, context=context) elif ans.adjusted() > Emax: if not ans: ans._exp = Emax
else: Etop = context.Etop() if folddown and ans._exp > Etop:
def _fixexponents(self, prec=None, rounding=None, folddown=None, context=None): """Fix the exponents and return a copy with the exponent in bounds.""" if self._isinfinity(): return self if context is None: context = getcontext() if prec is None: prec = context.prec if folddown is None: folddown = context._clamp Emin, Emax = context.Emin, context.Emax Etop = context.Etop() ans = Decimal(self) if ans.adjusted() < Emin: Etiny = context.Etiny() if ans._exp < Etiny: if not ans: ans._exp = Etiny context._raise_error(Clamped) return ans ans = ans._rescale(Etiny, context=context) #It isn't zero, and exp < Emin => subnormal context._raise_error(Subnormal) if context.flags[Inexact]: context._raise_error(Underflow) else: if ans: #Only raise subnormal if non-zero. context._raise_error(Subnormal) elif folddown and ans._exp > Etop: context._raise_error(Clamped) ans = ans._rescale(Etop, context=context) elif ans.adjusted() > Emax: if not ans: ans._exp = Emax context._raise_error(Clamped) return ans context._raise_error(Inexact) context._raise_error(Rounded) return context._raise_error(Overflow, 'above Emax', ans._sign) return ans
return ans context._raise_error(Inexact) context._raise_error(Rounded) return context._raise_error(Overflow, 'above Emax', ans._sign)
ans = ans._rescale(Etop, context=context) else: Emax = context.Emax if ans_adjusted > Emax: if not ans: ans._exp = Emax context._raise_error(Clamped) return ans context._raise_error(Inexact) context._raise_error(Rounded) return context._raise_error(Overflow, 'above Emax', ans._sign)
def _fixexponents(self, prec=None, rounding=None, folddown=None, context=None): """Fix the exponents and return a copy with the exponent in bounds.""" if self._isinfinity(): return self if context is None: context = getcontext() if prec is None: prec = context.prec if folddown is None: folddown = context._clamp Emin, Emax = context.Emin, context.Emax Etop = context.Etop() ans = Decimal(self) if ans.adjusted() < Emin: Etiny = context.Etiny() if ans._exp < Etiny: if not ans: ans._exp = Etiny context._raise_error(Clamped) return ans ans = ans._rescale(Etiny, context=context) #It isn't zero, and exp < Emin => subnormal context._raise_error(Subnormal) if context.flags[Inexact]: context._raise_error(Underflow) else: if ans: #Only raise subnormal if non-zero. context._raise_error(Subnormal) elif folddown and ans._exp > Etop: context._raise_error(Clamped) ans = ans._rescale(Etop, context=context) elif ans.adjusted() > Emax: if not ans: ans._exp = Emax context._raise_error(Clamped) return ans context._raise_error(Inexact) context._raise_error(Rounded) return context._raise_error(Overflow, 'above Emax', ans._sign) return ans
ans = self._check_nans(context=context) if ans: return ans if self._isinfinity(): return Decimal(self)
def _round(self, prec=None, rounding=None, context=None): """Returns a rounded version of self.
n = self._convert_other(n) if n._isinfinity() or n.adjusted() > 8: return context._raise_error(InvalidOperation, 'x ** INF') ans = self._check_nans(n, context) if ans: return ans if not n._isinfinity() and not n._isinteger():
if self._is_special or n._is_special or n.adjusted() > 8: if n._isinfinity() or n.adjusted() > 8: return context._raise_error(InvalidOperation, 'x ** INF') ans = self._check_nans(n, context) if ans: return ans if not n._isinteger():
def __pow__(self, n, modulo = None, context=None): """Return self ** n (mod modulo)
other = self._convert_other(other)
other = _convert_other(other)
def __rpow__(self, other, context=None): """Swaps self/other and returns __pow__.""" other = self._convert_other(other) return other.__pow__(self, context=context)
if context is None: context = getcontext() ans = self._check_nans(context=context) if ans: return ans
if self._is_special: ans = self._check_nans(context=context) if ans: return ans
def normalize(self, context=None): """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" if context is None: context = getcontext()
if context is None: context = getcontext() ans = self._check_nans(exp, context) if ans: return ans if exp._isinfinity() or self._isinfinity(): if exp._isinfinity() and self._isinfinity(): return self return context._raise_error(InvalidOperation, 'quantize with one INF')
if self._is_special or exp._is_special: ans = self._check_nans(exp, context) if ans: return ans if exp._isinfinity() or self._isinfinity(): if exp._isinfinity() and self._isinfinity(): return self if context is None: context = getcontext() return context._raise_error(InvalidOperation, 'quantize with one INF')
def quantize(self, exp, rounding = None, context=None, watchexp = 1): """Quantize self so its exponent is the same as that of exp.
if self._isnan() or other._isnan(): return self._isnan() and other._isnan() and True if self._isinfinity() or other._isinfinity(): return self._isinfinity() and other._isinfinity() and True
if self._is_special or other._is_special: if self._isnan() or other._isnan(): return self._isnan() and other._isnan() and True if self._isinfinity() or other._isinfinity(): return self._isinfinity() and other._isinfinity() and True
def same_quantum(self, other): """Test whether self and other have the same exponent.
if self._isinfinity(): return context._raise_error(InvalidOperation, 'rescale with an INF') ans = self._check_nans(context=context) if ans: return ans
if self._is_special: if self._isinfinity(): return context._raise_error(InvalidOperation, 'rescale with an INF') ans = self._check_nans(context=context) if ans: return ans
def _rescale(self, exp, rounding = None, context=None, watchexp = 1): """Rescales so that the exponent is exp.
if tmp and tmp.adjusted() < context.Emin:
tmp_adjusted = tmp.adjusted() if tmp and tmp_adjusted < context.Emin:
def _rescale(self, exp, rounding = None, context=None, watchexp = 1): """Rescales so that the exponent is exp.
elif tmp and tmp.adjusted() > context.Emax:
elif tmp and tmp_adjusted > context.Emax:
def _rescale(self, exp, rounding = None, context=None, watchexp = 1): """Rescales so that the exponent is exp.
ans = self._check_nans(context=context) if ans: return ans if self._exp >= 0: return self
def to_integral(self, rounding = None, context=None): """Rounds to the nearest integer, without raising inexact, rounded.""" if context is None: context = getcontext() ans = self._check_nans(context=context) if ans: return ans if self._exp >= 0: return self flags = context._ignore_flags(Rounded, Inexact) ans = self._rescale(0, rounding, context=context) context._regard_flags(flags) return ans
if context is None: context = getcontext() ans = self._check_nans(context=context) if ans: return ans
if self._is_special: ans = self._check_nans(context=context) if ans: return ans if self._isinfinity() and self._sign == 0: return Decimal(self)
def sqrt(self, context=None): """Return the square root of self.
if self._isinfinity(): return Decimal(self)
def sqrt(self, context=None): """Return the square root of self.
if context is None: context = getcontext() other = self._convert_other(other) sn = self._isnan() on = other._isnan() if sn or on: if on == 1 and sn != 2: return self if sn == 1 and on != 2: return other return self._check_nans(other, context)
other = _convert_other(other) if self._is_special or other._is_special: sn = self._isnan() on = other._isnan() if sn or on: if on == 1 and sn != 2: return self if sn == 1 and on != 2: return other return self._check_nans(other, context)
def max(self, other, context=None): """Returns the larger value.
if context is None: context = getcontext() other = self._convert_other(other) sn = self._isnan() on = other._isnan() if sn or on: if on == 1 and sn != 2: return self if sn == 1 and on != 2: return other return self._check_nans(other, context)
other = _convert_other(other) if self._is_special or other._is_special: sn = self._isnan() on = other._isnan() if sn or on: if on == 1 and sn != 2: return self if sn == 1 and on != 2: return other return self._check_nans(other, context)
def min(self, other, context=None): """Returns the smaller value.
self.int = []
self.int = 0
def __init__(self, value=None): if value is None: self.sign = None self.int = [] self.exp = None if isinstance(value, Decimal): if value._sign: self.sign = -1 else: self.sign = 1 self.int = list(value._int) self.exp = value._exp if isinstance(value, tuple): self.sign = value[0] self.int = value[1] self.exp = value[2]
self.int = list(value._int)
cum = 0 for digit in value._int: cum = cum * 10 + digit self.int = cum
def __init__(self, value=None): if value is None: self.sign = None self.int = [] self.exp = None if isinstance(value, Decimal): if value._sign: self.sign = -1 else: self.sign = 1 self.int = list(value._int) self.exp = value._exp if isinstance(value, tuple): self.sign = value[0] self.int = value[1] self.exp = value[2]
if len(int1) > len(int2):
if int1 > int2:
def __cmp__(self, other): if self.exp != other.exp: raise ValueError("Operands not normalized: %r, %r" % (self, other)) if self.sign != other.sign: if self.sign == -1: return -1 else: return 1 if self.sign == -1: direction = -1 else: direction = 1 int1 = self.int int2 = other.int if len(int1) > len(int2): return direction * 1 if len(int1) < len(int2): return direction * -1 for i in xrange(len(int1)): if int1[i] > int2[i]: return direction * 1 if int1[i] < int2[i]: return direction * -1 return 0
if len(int1) < len(int2):
if int1 < int2:
def __cmp__(self, other): if self.exp != other.exp: raise ValueError("Operands not normalized: %r, %r" % (self, other)) if self.sign != other.sign: if self.sign == -1: return -1 else: return 1 if self.sign == -1: direction = -1 else: direction = 1 int1 = self.int int2 = other.int if len(int1) > len(int2): return direction * 1 if len(int1) < len(int2): return direction * -1 for i in xrange(len(int1)): if int1[i] > int2[i]: return direction * 1 if int1[i] < int2[i]: return direction * -1 return 0
for i in xrange(len(int1)): if int1[i] > int2[i]: return direction * 1 if int1[i] < int2[i]: return direction * -1
def __cmp__(self, other): if self.exp != other.exp: raise ValueError("Operands not normalized: %r, %r" % (self, other)) if self.sign != other.sign: if self.sign == -1: return -1 else: return 1 if self.sign == -1: direction = -1 else: direction = 1 int1 = self.int int2 = other.int if len(int1) > len(int2): return direction * 1 if len(int1) < len(int2): return direction * -1 for i in xrange(len(int1)): if int1[i] > int2[i]: return direction * 1 if int1[i] < int2[i]: return direction * -1 return 0
def _increment(self): curspot = len(self.int) - 1 self.int[curspot]+= 1 while (self.int[curspot] >= 10): self.int[curspot] -= 10 if curspot == 0: self.int[0:0] = [1] break self.int[curspot-1] += 1 curspot -= 1 def subtract(self, alist): """Subtract a list from the current int (in place). It is assured that (len(list) = len(self.int) and list < self.int) or len(list) = len(self.int)-1 (i.e. that int(join(list)) < int(join(self.int))) """ selfint = self.int selfint.reverse() alist.reverse() carry = 0 for x in xrange(len(alist)): selfint[x] -= alist[x] + carry if selfint[x] < 0: carry = 1 selfint[x] += 10 else: carry = 0 if carry: selfint[x+1] -= 1 last = len(selfint)-1 while len(selfint) > 1 and selfint[last] == 0: last -= 1 if last == 0: break selfint[last+1:]=[] selfint.reverse() alist.reverse() return
def _increment(self): curspot = len(self.int) - 1 self.int[curspot]+= 1 while (self.int[curspot] >= 10): self.int[curspot] -= 10 if curspot == 0: self.int[0:0] = [1] break self.int[curspot-1] += 1 curspot -= 1
if shouldround and numdigits > len(other.int) + prec + 1 -len(tmp.int): extend = prec + 2 -len(tmp.int) if extend <= 0: extend = 1 tmp.int.extend([0]*extend) tmp.exp -= extend other.int[:] = [0]*(len(tmp.int)-1)+[1] other.exp = tmp.exp return op1, op2 tmp.int.extend([0] * numdigits) tmp.exp = tmp.exp - numdigits numdigits = len(op1.int) - len(op2.int) if numdigits < 0: numdigits = -numdigits tmp = op1 else: tmp = op2 tmp.int[0:0] = [0] * numdigits
if shouldround and numdigits > prec + 1: tmp_len = len(str(tmp.int)) other_len = len(str(other.int)) if numdigits > (other_len + prec + 1 - tmp_len): extend = prec + 2 - tmp_len if extend <= 0: extend = 1 tmp.int *= 10 ** extend tmp.exp -= extend other.int = 1 other.exp = tmp.exp return op1, op2 tmp.int *= 10 ** numdigits tmp.exp -= numdigits
def _normalize(op1, op2, shouldround = 0, prec = 0): """Normalizes op1, op2 to have the same exp and length of coefficient. Done during addition. """ # Yes, the exponent is a long, but the difference between exponents # must be an int-- otherwise you'd get a big memory problem. numdigits = int(op1.exp - op2.exp) if numdigits < 0: numdigits = -numdigits tmp = op2 other = op1 else: tmp = op1 other = op2 if shouldround and numdigits > len(other.int) + prec + 1 -len(tmp.int): # If the difference in adjusted exps is > prec+1, we know # other is insignificant, so might as well put a 1 after the precision. # (since this is only for addition.) Also stops MemoryErrors. extend = prec + 2 -len(tmp.int) if extend <= 0: extend = 1 tmp.int.extend([0]*extend) tmp.exp -= extend other.int[:] = [0]*(len(tmp.int)-1)+[1] other.exp = tmp.exp return op1, op2 tmp.int.extend([0] * numdigits) tmp.exp = tmp.exp - numdigits numdigits = len(op1.int) - len(op2.int) # numdigits != 0 => They have the same exponent, but not the same length # of the coefficient. if numdigits < 0: numdigits = -numdigits tmp = op1 else: tmp = op2 tmp.int[0:0] = [0] * numdigits return op1, op2
"""Adjust op1, op2 so that op2.int+[0] > op1.int >= op2.int.
"""Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.
def _adjust_coefficients(op1, op2): """Adjust op1, op2 so that op2.int+[0] > op1.int >= op2.int. Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp. Used on _WorkRep instances during division. """ adjust = 0 #If op1 is smaller, get it to same size if len(op2.int) > len(op1.int): diff = len(op2.int) - len(op1.int) op1.int.extend([0]*diff) op1.exp -= diff adjust = diff #Same length, wrong order if len(op1.int) == len(op2.int) and op1.int < op2.int: op1.int.append(0) op1.exp -= 1 adjust+= 1 return op1, op2, adjust if len(op1.int) > len(op2.int) + 1: diff = len(op1.int) - len(op2.int) - 1 op2.int.extend([0]*diff) op2.exp -= diff adjust -= diff if len(op1.int) == len(op2.int)+1 and op1.int > op2.int: op2.int.append(0) op2.exp -= 1 adjust -= 1 return op1, op2, adjust
if len(op2.int) > len(op1.int): diff = len(op2.int) - len(op1.int) op1.int.extend([0]*diff) op1.exp -= diff adjust = diff if len(op1.int) == len(op2.int) and op1.int < op2.int: op1.int.append(0)
while op2.int > op1.int: op1.int *= 10
def _adjust_coefficients(op1, op2): """Adjust op1, op2 so that op2.int+[0] > op1.int >= op2.int. Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp. Used on _WorkRep instances during division. """ adjust = 0 #If op1 is smaller, get it to same size if len(op2.int) > len(op1.int): diff = len(op2.int) - len(op1.int) op1.int.extend([0]*diff) op1.exp -= diff adjust = diff #Same length, wrong order if len(op1.int) == len(op2.int) and op1.int < op2.int: op1.int.append(0) op1.exp -= 1 adjust+= 1 return op1, op2, adjust if len(op1.int) > len(op2.int) + 1: diff = len(op1.int) - len(op2.int) - 1 op2.int.extend([0]*diff) op2.exp -= diff adjust -= diff if len(op1.int) == len(op2.int)+1 and op1.int > op2.int: op2.int.append(0) op2.exp -= 1 adjust -= 1 return op1, op2, adjust
adjust+= 1 return op1, op2, adjust if len(op1.int) > len(op2.int) + 1: diff = len(op1.int) - len(op2.int) - 1 op2.int.extend([0]*diff) op2.exp -= diff adjust -= diff if len(op1.int) == len(op2.int)+1 and op1.int > op2.int: op2.int.append(0)
adjust += 1 while op1.int >= (10 * op2.int): op2.int *= 10
def _adjust_coefficients(op1, op2): """Adjust op1, op2 so that op2.int+[0] > op1.int >= op2.int. Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp. Used on _WorkRep instances during division. """ adjust = 0 #If op1 is smaller, get it to same size if len(op2.int) > len(op1.int): diff = len(op2.int) - len(op1.int) op1.int.extend([0]*diff) op1.exp -= diff adjust = diff #Same length, wrong order if len(op1.int) == len(op2.int) and op1.int < op2.int: op1.int.append(0) op1.exp -= 1 adjust+= 1 return op1, op2, adjust if len(op1.int) > len(op2.int) + 1: diff = len(op1.int) - len(op2.int) - 1 op2.int.extend([0]*diff) op2.exp -= diff adjust -= diff if len(op1.int) == len(op2.int)+1 and op1.int > op2.int: op2.int.append(0) op2.exp -= 1 adjust -= 1 return op1, op2, adjust
headers = {'content-type': "application/x-www-form-urlencoded"}
headers = {} if method == 'POST': headers['content-type'] = "application/x-www-form-urlencoded"
def __init__(self, fp=None, headers=None, outerboundary="", environ=os.environ, keep_blank_values=0, strict_parsing=0): """Constructor. Read multipart/* until last part.
try: _os.unlink(self._bakfile) except _os.error:
try: self._os.unlink(self._bakfile) except self._os.error:
def _commit(self): try: _os.unlink(self._bakfile) except _os.error: pass
_os.rename(self._dirfile, self._bakfile) except _os.error:
self._os.rename(self._dirfile, self._bakfile) except self._os.error:
def _commit(self): try: _os.unlink(self._bakfile) except _os.error: pass
f = _open(self._dirfile, 'w', self._mode)
f = self._open(self._dirfile, 'w', self._mode)
def _commit(self): try: _os.unlink(self._bakfile) except _os.error: pass
def __init__(self, file):
def __init__(self, file, mode): self._mode = mode
def __init__(self, file): self._dirfile = file + _os.extsep + 'dir' self._datfile = file + _os.extsep + 'dat' self._bakfile = file + _os.extsep + 'bak' # Mod by Jack: create data file if needed try: f = _open(self._datfile, 'r') except IOError: f = _open(self._datfile, 'w') f.close() self._update()
f = _open(self._datfile, 'w')
f = _open(self._datfile, 'w', self._mode)
def __init__(self, file): self._dirfile = file + _os.extsep + 'dir' self._datfile = file + _os.extsep + 'dat' self._bakfile = file + _os.extsep + 'bak' # Mod by Jack: create data file if needed try: f = _open(self._datfile, 'r') except IOError: f = _open(self._datfile, 'w') f.close() self._update()
f = _open(self._dirfile, 'w')
f = _open(self._dirfile, 'w', self._mode)
def _commit(self): try: _os.unlink(self._bakfile) except _os.error: pass try: _os.rename(self._dirfile, self._bakfile) except _os.error: pass f = _open(self._dirfile, 'w') for key, (pos, siz) in self._index.items(): f.write("%s, (%s, %s)\n" % (`key`, `pos`, `siz`)) f.close()
f = _open(self._dirfile, 'a')
f = _open(self._dirfile, 'a', self._mode)
def _addkey(self, key, (pos, siz)): self._index[key] = (pos, siz) f = _open(self._dirfile, 'a') f.write("%s, (%s, %s)\n" % (`key`, `pos`, `siz`)) f.close()
print >> sys.stderr, _(__doc__) % globals()
print >> sys.stderr, __doc__ % globals()
def usage(code, msg=''): print >> sys.stderr, _(__doc__) % globals() if msg: print >> sys.stderr, msg sys.exit(code)
elif ttype not in [tokenize.COMMENT, token.INDENT, token.DEDENT, token.NEWLINE, tokenize.NL]: print >>sys.stderr, _('*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"') % { 'token': tstring, 'file': self.__curfile, 'lineno': self.__lineno} self.__state = self.__waiting
def __openseen(self, ttype, tstring, lineno): if ttype == tokenize.OP and tstring == ')': # We've seen the last of the translatable strings. Record the # line number of the first line of the strings and update the list # of messages seen. Reset state for the next batch. If there # were no strings inside _(), then just ignore this entry. if self.__data: self.__addentry(EMPTYSTRING.join(self.__data)) self.__state = self.__waiting elif ttype == tokenize.STRING: self.__data.append(safe_eval(tstring)) # TBD: should we warn if we seen anything else?
wid = WhichWindow(message)
if type(message) == type(1): wid = WhichWindow(message) else: wid = message
def do_activateEvt(self, event): (what, message, when, where, modifiers) = event wid = WhichWindow(message) if wid and self._windows.has_key(wid): window = self._windows[wid] window.do_activate(modifiers & 1, event) else: MacOS.HandleEvent(event)
self.do_activateEvt(self, nev)
self.do_activateEvt(nev)
def do_suspendresume(self, event): # Is this a good idea??? (what, message, when, where, modifiers) = event w = FrontWindow() if w: nev = (activateEvt, w, when, where, message&1) self.do_activateEvt(self, nev)
name = self.menu.GetItem(item)
name = self.menu.GetMenuItemText(item)
def dispatch(self, id, item, window, event): if item == 1: Menu.dispatch(self, id, item, window, event) else: name = self.menu.GetItem(item) OpenDeskAcc(name)
def open(self): self.wid = NewWindow((40, 40, 400, 400), self.__class__.__name__, 1,
def open(self, bounds=(40, 40, 400, 400), resid=None): if resid <> None: self.wid = GetNewWindow(resid, -1) else: self.wid = NewWindow(bounds, self.__class__.__name__, 1,
def open(self): self.wid = NewWindow((40, 40, 400, 400), self.__class__.__name__, 1, 0, -1, 1, 0) self.do_postopen()
Continuation are represented by an embedded newline then
Continuations are represented by an embedded newline then
def _read(self, fp, fpname): """Parse a sectioned setup file.
and just about everything else is ignored.
and just about everything else are ignored.
def _read(self, fp, fpname): """Parse a sectioned setup file.