ÿØÿà JFIF    ÿÛ „ ( %!1!%*+...983,7(-.- PKO]/ Dates.pynu[# Class Date supplies date objects that support date arithmetic. # # Date(month,day,year) returns a Date object. An instance prints as, # e.g., 'Mon 16 Aug 1993'. # # Addition, subtraction, comparison operators, min, max, and sorting # all work as expected for date objects: int+date or date+int returns # the date `int' days from `date'; date+date raises an exception; # date-int returns the date `int' days before `date'; date2-date1 returns # an integer, the number of days from date1 to date2; int-date raises an # exception; date1 < date2 is true iff date1 occurs before date2 (& # similarly for other comparisons); min(date1,date2) is the earlier of # the two dates and max(date1,date2) the later; and date objects can be # used as dictionary keys. # # Date objects support one visible method, date.weekday(). This returns # the day of the week the date falls on, as a string. # # Date objects also have 4 read-only data attributes: # .month in 1..12 # .day in 1..31 # .year int or long int # .ord the ordinal of the date relative to an arbitrary staring point # # The Dates module also supplies function today(), which returns the # current date as a date object. # # Those entranced by calendar trivia will be disappointed, as no attempt # has been made to accommodate the Julian (etc) system. On the other # hand, at least this package knows that 2000 is a leap year but 2100 # isn't, and works fine for years with a hundred decimal digits . # Tim Peters tim@ksr.com # not speaking for Kendall Square Research Corp # Adapted to Python 1.1 (where some hacks to overcome coercion are unnecessary) # by Guido van Rossum # Note that as of Python 2.3, a datetime module is included in the stardard # library. # vi:set tabsize=8: _MONTH_NAMES = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] _DAY_NAMES = [ 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday' ] _DAYS_IN_MONTH = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] _DAYS_BEFORE_MONTH = [] dbm = 0 for dim in _DAYS_IN_MONTH: _DAYS_BEFORE_MONTH.append(dbm) dbm = dbm + dim del dbm, dim _INT_TYPES = type(1), type(1L) def _is_leap(year): # 1 if leap year, else 0 if year % 4 != 0: return 0 if year % 400 == 0: return 1 return year % 100 != 0 def _days_in_year(year): # number of days in year return 365 + _is_leap(year) def _days_before_year(year): # number of days before year return year*365L + (year+3)//4 - (year+99)//100 + (year+399)//400 def _days_in_month(month, year): # number of days in month of year if month == 2 and _is_leap(year): return 29 return _DAYS_IN_MONTH[month-1] def _days_before_month(month, year): # number of days in year before month return _DAYS_BEFORE_MONTH[month-1] + (month > 2 and _is_leap(year)) def _date2num(date): # compute ordinal of date.month,day,year return _days_before_year(date.year) + \ _days_before_month(date.month, date.year) + \ date.day _DI400Y = _days_before_year(400) # number of days in 400 years def _num2date(n): # return date with ordinal n if type(n) not in _INT_TYPES: raise TypeError, 'argument must be integer: %r' % type(n) ans = Date(1,1,1) # arguments irrelevant; just getting a Date obj del ans.ord, ans.month, ans.day, ans.year # un-initialize it ans.ord = n n400 = (n-1)//_DI400Y # # of 400-year blocks preceding year, n = 400 * n400, n - _DI400Y * n400 more = n // 365 dby = _days_before_year(more) if dby >= n: more = more - 1 dby = dby - _days_in_year(more) year, n = year + more, int(n - dby) try: year = int(year) # chop to int, if it fits except (ValueError, OverflowError): pass month = min(n//29 + 1, 12) dbm = _days_before_month(month, year) if dbm >= n: month = month - 1 dbm = dbm - _days_in_month(month, year) ans.month, ans.day, ans.year = month, n-dbm, year return ans def _num2day(n): # return weekday name of day with ordinal n return _DAY_NAMES[ int(n % 7) ] class Date: def __init__(self, month, day, year): if not 1 <= month <= 12: raise ValueError, 'month must be in 1..12: %r' % (month,) dim = _days_in_month(month, year) if not 1 <= day <= dim: raise ValueError, 'day must be in 1..%r: %r' % (dim, day) self.month, self.day, self.year = month, day, year self.ord = _date2num(self) # don't allow setting existing attributes def __setattr__(self, name, value): if self.__dict__.has_key(name): raise AttributeError, 'read-only attribute ' + name self.__dict__[name] = value def __cmp__(self, other): return cmp(self.ord, other.ord) # define a hash function so dates can be used as dictionary keys def __hash__(self): return hash(self.ord) # print as, e.g., Mon 16 Aug 1993 def __repr__(self): return '%.3s %2d %.3s %r' % ( self.weekday(), self.day, _MONTH_NAMES[self.month-1], self.year) # Python 1.1 coerces neither int+date nor date+int def __add__(self, n): if type(n) not in _INT_TYPES: raise TypeError, 'can\'t add %r to date' % type(n) return _num2date(self.ord + n) __radd__ = __add__ # handle int+date # Python 1.1 coerces neither date-int nor date-date def __sub__(self, other): if type(other) in _INT_TYPES: # date-int return _num2date(self.ord - other) else: return self.ord - other.ord # date-date # complain about int-date def __rsub__(self, other): raise TypeError, 'Can\'t subtract date from integer' def weekday(self): return _num2day(self.ord) def today(): import time local = time.localtime(time.time()) return Date(local[1], local[2], local[0]) class DateTestError(Exception): pass def test(firstyear, lastyear): a = Date(9,30,1913) b = Date(9,30,1914) if repr(a) != 'Tue 30 Sep 1913': raise DateTestError, '__repr__ failure' if (not a < b) or a == b or a > b or b != b: raise DateTestError, '__cmp__ failure' if a+365 != b or 365+a != b: raise DateTestError, '__add__ failure' if b-a != 365 or b-365 != a: raise DateTestError, '__sub__ failure' try: x = 1 - a raise DateTestError, 'int-date should have failed' except TypeError: pass try: x = a + b raise DateTestError, 'date+date should have failed' except TypeError: pass if a.weekday() != 'Tuesday': raise DateTestError, 'weekday() failure' if max(a,b) is not b or min(a,b) is not a: raise DateTestError, 'min/max failure' d = {a-1:b, b:a+1} if d[b-366] != b or d[a+(b-a)] != Date(10,1,1913): raise DateTestError, 'dictionary failure' # verify date<->number conversions for first and last days for # all years in firstyear .. lastyear lord = _days_before_year(firstyear) y = firstyear while y <= lastyear: ford = lord + 1 lord = ford + _days_in_year(y) - 1 fd, ld = Date(1,1,y), Date(12,31,y) if (fd.ord,ld.ord) != (ford,lord): raise DateTestError, ('date->num failed', y) fd, ld = _num2date(ford), _num2date(lord) if (1,1,y,12,31,y) != \ (fd.month,fd.day,fd.year,ld.month,ld.day,ld.year): raise DateTestError, ('num->date failed', y) y = y + 1 if __name__ == '__main__': test(1850, 2150) PKO]ΎMMVec.pynu[class Vec: """ A simple vector class Instances of the Vec class can be constructed from numbers >>> a = Vec(1, 2, 3) >>> b = Vec(3, 2, 1) added >>> a + b Vec(4, 4, 4) subtracted >>> a - b Vec(-2, 0, 2) and multiplied by a scalar on the left >>> 3.0 * a Vec(3.0, 6.0, 9.0) or on the right >>> a * 3.0 Vec(3.0, 6.0, 9.0) """ def __init__(self, *v): self.v = list(v) @classmethod def fromlist(cls, v): if not isinstance(v, list): raise TypeError inst = cls() inst.v = v return inst def __repr__(self): args = ', '.join(repr(x) for x in self.v) return 'Vec({0})'.format(args) def __len__(self): return len(self.v) def __getitem__(self, i): return self.v[i] def __add__(self, other): # Element-wise addition v = [x + y for x, y in zip(self.v, other.v)] return Vec.fromlist(v) def __sub__(self, other): # Element-wise subtraction v = [x - y for x, y in zip(self.v, other.v)] return Vec.fromlist(v) def __mul__(self, scalar): # Multiply by scalar v = [x * scalar for x in self.v] return Vec.fromlist(v) __rmul__ = __mul__ def test(): import doctest doctest.testmod() test() PKO]j%&&Dbm.pynu[# A wrapper around the (optional) built-in class dbm, supporting keys # and values of almost any type instead of just string. # (Actually, this works only for keys and values that can be read back # correctly after being converted to a string.) class Dbm: def __init__(self, filename, mode, perm): import dbm self.db = dbm.open(filename, mode, perm) def __repr__(self): s = '' for key in self.keys(): t = repr(key) + ': ' + repr(self[key]) if s: t = ', ' + t s = s + t return '{' + s + '}' def __len__(self): return len(self.db) def __getitem__(self, key): return eval(self.db[repr(key)]) def __setitem__(self, key, value): self.db[repr(key)] = repr(value) def __delitem__(self, key): del self.db[repr(key)] def keys(self): res = [] for key in self.db.keys(): res.append(eval(key)) return res def has_key(self, key): return self.db.has_key(repr(key)) def test(): d = Dbm('@dbm', 'rw', 0600) print d while 1: try: key = input('key: ') if d.has_key(key): value = d[key] print 'currently:', value value = input('value: ') if value is None: del d[key] else: d[key] = value except KeyboardInterrupt: print '' print d except EOFError: print '[eof]' break print d test() PKO]E Range.pyonu[ ^c@sNdZdZdZdddYZdZedkrJendS( s Example of a generator: re-implement the built-in range function without actually constructing the list of values. OldStyleRange is coded in the way required to work in a 'for' loop before iterators were introduced into the language; using __getitem__ and __len__ . cCsyt|dkr,dt|ddfSt|dkr_t|dt|ddfSt|dkr|ddkrtdntd|DStdt|Wntk rtdnXd S( sgTake list of arguments and extract/create proper start, stop, and step values and return in a tupleiiiisstep argument must not be zerocss|]}t|VqdS(N(tint(t.0tx((s*/usr/lib64/python2.7/Demo/classes/Range.pys ss$range() accepts 1-3 arguments, givensArange() arguments must be numbers or strings representing numbersN(tlenRt ValueErrorttuplet TypeError(targlist((s*/usr/lib64/python2.7/Demo/classes/Range.pyt handleargss! cgsAt|\}}}|}x||kr<|V||7}qWdS(s,Function to implement 'range' as a generatorN(R(tatstarttstoptsteptvalue((s*/usr/lib64/python2.7/Demo/classes/Range.pytgenranges toldrangecBs2eZdZdZdZdZdZRS(sClass implementing a range object. To the user the instances feel like immutable sequences (and you can't concatenate or slice them) Done using the old way (pre-iterators; __len__ and __getitem__) to have an object be used by a 'for' loop. cGsEt|\|_|_|_td|j|j|j|_dS(s Initialize start, stop, and step values along with calculating the nubmer of values (what __len__ will return) in the rangeiN(RR R R tmaxR(tselfR ((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__init__,scCsd|j|j|jfS(s-implement repr(x) which is also used by printsrange(%r, %r, %r)(R R R (R((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__repr__2scCs|jS(simplement len(x)(R(R((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__len__6scCs>d|ko|jknr1|j|j|StddS(simplement x[i]isrange[i] index out of rangeN(RR R t IndexError(Rti((s*/usr/lib64/python2.7/Demo/classes/Range.pyt __getitem__:s(t__name__t __module__t__doc__RRRR(((s*/usr/lib64/python2.7/Demo/classes/Range.pyR"s    c Cs9ddl}ddl}|jddd}ttddd}ttddd}||ksu||krtd|||fndGH|j}xtdD]}qW|j}xtdD]}qW|j}x|jdD]}qW|j} ||GdGH||Gd GH| |Gd GHdS( NiiidisEerror in implementation: correct = %s old-style = %s generator = %ssTimings for range(1000):issec (old-style class)ssec (generator)ssec (built-in)(ttimet __builtin__trangetlistRRt Exception( RRtcorrect_resulttoldrange_resulttgenrange_resulttt1Rtt2tt3tt4((s*/usr/lib64/python2.7/Demo/classes/Range.pyttestBs*      t__main__N((RRRRR'R(((s*/usr/lib64/python2.7/Demo/classes/Range.pyts     PKO] Dbm.pycnu[ ^c@s'dddYZdZedS(tDbmcBsPeZdZdZdZdZdZdZdZdZ RS(cCs(ddl}|j||||_dS(Ni(tdbmtopentdb(tselftfilenametmodetpermR((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__init__ s cCsdd}xO|jD]A}t|dt||}|rJd|}n||}qWd|dS(Nts: s, t{t}(tkeystrepr(Rtstkeytt((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__repr__ s cCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__len__scCst|jt|S(N(tevalRR (RR((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt __getitem__scCst||jt|s$ PKO](  READMEnu[Examples of classes that implement special operators (see reference manual): Complex.py Complex numbers Dates.py Date manipulation package by Tim Peters Dbm.py Wrapper around built-in dbm, supporting arbitrary values Range.py Example of a generator: re-implement built-in range() Rev.py Yield the reverse of a sequence Vec.py A simple vector class bitvec.py A bit-vector class by Jan-Hein B\"uhrman (For straightforward examples of basic class features, such as use of methods and inheritance, see the library code.) PKO]u+&& Complex.pynu[# Complex numbers # --------------- # [Now that Python has a complex data type built-in, this is not very # useful, but it's still a nice example class] # This module represents complex numbers as instances of the class Complex. # A Complex instance z has two data attribues, z.re (the real part) and z.im # (the imaginary part). In fact, z.re and z.im can have any value -- all # arithmetic operators work regardless of the type of z.re and z.im (as long # as they support numerical operations). # # The following functions exist (Complex is actually a class): # Complex([re [,im]) -> creates a complex number from a real and an imaginary part # IsComplex(z) -> true iff z is a complex number (== has .re and .im attributes) # ToComplex(z) -> a complex number equal to z; z itself if IsComplex(z) is true # if z is a tuple(re, im) it will also be converted # PolarToComplex([r [,phi [,fullcircle]]]) -> # the complex number z for which r == z.radius() and phi == z.angle(fullcircle) # (r and phi default to 0) # exp(z) -> returns the complex exponential of z. Equivalent to pow(math.e,z). # # Complex numbers have the following methods: # z.abs() -> absolute value of z # z.radius() == z.abs() # z.angle([fullcircle]) -> angle from positive X axis; fullcircle gives units # z.phi([fullcircle]) == z.angle(fullcircle) # # These standard functions and unary operators accept complex arguments: # abs(z) # -z # +z # not z # repr(z) == `z` # str(z) # hash(z) -> a combination of hash(z.re) and hash(z.im) such that if z.im is zero # the result equals hash(z.re) # Note that hex(z) and oct(z) are not defined. # # These conversions accept complex arguments only if their imaginary part is zero: # int(z) # long(z) # float(z) # # The following operators accept two complex numbers, or one complex number # and one real number (int, long or float): # z1 + z2 # z1 - z2 # z1 * z2 # z1 / z2 # pow(z1, z2) # cmp(z1, z2) # Note that z1 % z2 and divmod(z1, z2) are not defined, # nor are shift and mask operations. # # The standard module math does not support complex numbers. # The cmath modules should be used instead. # # Idea: # add a class Polar(r, phi) and mixed-mode arithmetic which # chooses the most appropriate type for the result: # Complex for +,-,cmp # Polar for *,/,pow import math import sys twopi = math.pi*2.0 halfpi = math.pi/2.0 def IsComplex(obj): return hasattr(obj, 're') and hasattr(obj, 'im') def ToComplex(obj): if IsComplex(obj): return obj elif isinstance(obj, tuple): return Complex(*obj) else: return Complex(obj) def PolarToComplex(r = 0, phi = 0, fullcircle = twopi): phi = phi * (twopi / fullcircle) return Complex(math.cos(phi)*r, math.sin(phi)*r) def Re(obj): if IsComplex(obj): return obj.re return obj def Im(obj): if IsComplex(obj): return obj.im return 0 class Complex: def __init__(self, re=0, im=0): _re = 0 _im = 0 if IsComplex(re): _re = re.re _im = re.im else: _re = re if IsComplex(im): _re = _re - im.im _im = _im + im.re else: _im = _im + im # this class is immutable, so setting self.re directly is # not possible. self.__dict__['re'] = _re self.__dict__['im'] = _im def __setattr__(self, name, value): raise TypeError, 'Complex numbers are immutable' def __hash__(self): if not self.im: return hash(self.re) return hash((self.re, self.im)) def __repr__(self): if not self.im: return 'Complex(%r)' % (self.re,) else: return 'Complex(%r, %r)' % (self.re, self.im) def __str__(self): if not self.im: return repr(self.re) else: return 'Complex(%r, %r)' % (self.re, self.im) def __neg__(self): return Complex(-self.re, -self.im) def __pos__(self): return self def __abs__(self): return math.hypot(self.re, self.im) def __int__(self): if self.im: raise ValueError, "can't convert Complex with nonzero im to int" return int(self.re) def __long__(self): if self.im: raise ValueError, "can't convert Complex with nonzero im to long" return long(self.re) def __float__(self): if self.im: raise ValueError, "can't convert Complex with nonzero im to float" return float(self.re) def __cmp__(self, other): other = ToComplex(other) return cmp((self.re, self.im), (other.re, other.im)) def __rcmp__(self, other): other = ToComplex(other) return cmp(other, self) def __nonzero__(self): return not (self.re == self.im == 0) abs = radius = __abs__ def angle(self, fullcircle = twopi): return (fullcircle/twopi) * ((halfpi - math.atan2(self.re, self.im)) % twopi) phi = angle def __add__(self, other): other = ToComplex(other) return Complex(self.re + other.re, self.im + other.im) __radd__ = __add__ def __sub__(self, other): other = ToComplex(other) return Complex(self.re - other.re, self.im - other.im) def __rsub__(self, other): other = ToComplex(other) return other - self def __mul__(self, other): other = ToComplex(other) return Complex(self.re*other.re - self.im*other.im, self.re*other.im + self.im*other.re) __rmul__ = __mul__ def __div__(self, other): other = ToComplex(other) d = float(other.re*other.re + other.im*other.im) if not d: raise ZeroDivisionError, 'Complex division' return Complex((self.re*other.re + self.im*other.im) / d, (self.im*other.re - self.re*other.im) / d) def __rdiv__(self, other): other = ToComplex(other) return other / self def __pow__(self, n, z=None): if z is not None: raise TypeError, 'Complex does not support ternary pow()' if IsComplex(n): if n.im: if self.im: raise TypeError, 'Complex to the Complex power' else: return exp(math.log(self.re)*n) n = n.re r = pow(self.abs(), n) phi = n*self.angle() return Complex(math.cos(phi)*r, math.sin(phi)*r) def __rpow__(self, base): base = ToComplex(base) return pow(base, self) def exp(z): r = math.exp(z.re) return Complex(math.cos(z.im)*r,math.sin(z.im)*r) def checkop(expr, a, b, value, fuzz = 1e-6): print ' ', a, 'and', b, try: result = eval(expr) except: result = sys.exc_type print '->', result if isinstance(result, str) or isinstance(value, str): ok = (result == value) else: ok = abs(result - value) <= fuzz if not ok: print '!!\t!!\t!! should be', value, 'diff', abs(result - value) def test(): print 'test constructors' constructor_test = ( # "expect" is an array [re,im] "got" the Complex. ( (0,0), Complex() ), ( (0,0), Complex() ), ( (1,0), Complex(1) ), ( (0,1), Complex(0,1) ), ( (1,2), Complex(Complex(1,2)) ), ( (1,3), Complex(Complex(1,2),1) ), ( (0,0), Complex(0,Complex(0,0)) ), ( (3,4), Complex(3,Complex(4)) ), ( (-1,3), Complex(1,Complex(3,2)) ), ( (-7,6), Complex(Complex(1,2),Complex(4,8)) ) ) cnt = [0,0] for t in constructor_test: cnt[0] += 1 if ((t[0][0]!=t[1].re)or(t[0][1]!=t[1].im)): print " expected", t[0], "got", t[1] cnt[1] += 1 print " ", cnt[1], "of", cnt[0], "tests failed" # test operators testsuite = { 'a+b': [ (1, 10, 11), (1, Complex(0,10), Complex(1,10)), (Complex(0,10), 1, Complex(1,10)), (Complex(0,10), Complex(1), Complex(1,10)), (Complex(1), Complex(0,10), Complex(1,10)), ], 'a-b': [ (1, 10, -9), (1, Complex(0,10), Complex(1,-10)), (Complex(0,10), 1, Complex(-1,10)), (Complex(0,10), Complex(1), Complex(-1,10)), (Complex(1), Complex(0,10), Complex(1,-10)), ], 'a*b': [ (1, 10, 10), (1, Complex(0,10), Complex(0, 10)), (Complex(0,10), 1, Complex(0,10)), (Complex(0,10), Complex(1), Complex(0,10)), (Complex(1), Complex(0,10), Complex(0,10)), ], 'a/b': [ (1., 10, 0.1), (1, Complex(0,10), Complex(0, -0.1)), (Complex(0, 10), 1, Complex(0, 10)), (Complex(0, 10), Complex(1), Complex(0, 10)), (Complex(1), Complex(0,10), Complex(0, -0.1)), ], 'pow(a,b)': [ (1, 10, 1), (1, Complex(0,10), 1), (Complex(0,10), 1, Complex(0,10)), (Complex(0,10), Complex(1), Complex(0,10)), (Complex(1), Complex(0,10), 1), (2, Complex(4,0), 16), ], 'cmp(a,b)': [ (1, 10, -1), (1, Complex(0,10), 1), (Complex(0,10), 1, -1), (Complex(0,10), Complex(1), -1), (Complex(1), Complex(0,10), 1), ], } for expr in sorted(testsuite): print expr + ':' t = (expr,) for item in testsuite[expr]: checkop(*(t+item)) if __name__ == '__main__': test() PKO]1 1 Rev.pycnu[ ^c@s<dZdddYZdZedkr8endS(s A class which presents the reverse of a sequence without duplicating it. From: "Steven D. Majewski" It works on mutable or inmutable sequences. >>> chars = list(Rev('Hello World!')) >>> print ''.join(chars) !dlroW olleH The .forw is so you can use anonymous sequences in __init__, and still keep a reference the forward sequence. ) If you give it a non-anonymous mutable sequence, the reverse sequence will track the updated values. ( but not reassignment! - another good reason to use anonymous values in creating the sequence to avoid confusion. Maybe it should be change to copy input sequence to break the connection completely ? ) >>> nnn = range(3) >>> rnn = Rev(nnn) >>> for n in rnn: print n ... 2 1 0 >>> for n in range(4, 6): nnn.append(n) # update nnn ... >>> for n in rnn: print n # prints reversed updated values ... 5 4 2 1 0 >>> nnn = nnn[1:-1] >>> nnn [1, 2, 4] >>> for n in rnn: print n # prints reversed values of old nnn ... 5 4 2 1 0 # >>> WH = Rev('Hello World!') >>> print WH.forw, WH.back Hello World! !dlroW olleH >>> nnn = Rev(range(1, 10)) >>> print nnn.forw [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print nnn.back [9, 8, 7, 6, 5, 4, 3, 2, 1] >>> rrr = Rev(nnn) >>> rrr <1, 2, 3, 4, 5, 6, 7, 8, 9> tRevcBs,eZdZdZdZdZRS(cCs||_||_dS(N(tforwtback(tselftseq((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__init__?s cCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__len__CscCs|j|d S(Ni(R(Rtj((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt __getitem__FscCs|j}t|tr'd}d}nHt|trEd}d}n*t|trcd}d}n d}d}g|jD]}t|^qy}|d |j||dS(Ns[]s, s()ts<>ii(Rt isinstancetlistttupletstrRtjoin(RRtwraptseptitemtoutstrs((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__repr__Is    "(t__name__t __module__RRR R(((s(/usr/lib64/python2.7/Demo/classes/Rev.pyR>s   cCs%ddl}ddl}|j|S(Ni(tdoctestRttestmod(RR((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt_testZst__main__N((t__doc__RRR(((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt<s  PKO]nL6 6 Range.pynu["""Example of a generator: re-implement the built-in range function without actually constructing the list of values. OldStyleRange is coded in the way required to work in a 'for' loop before iterators were introduced into the language; using __getitem__ and __len__ . """ def handleargs(arglist): """Take list of arguments and extract/create proper start, stop, and step values and return in a tuple""" try: if len(arglist) == 1: return 0, int(arglist[0]), 1 elif len(arglist) == 2: return int(arglist[0]), int(arglist[1]), 1 elif len(arglist) == 3: if arglist[2] == 0: raise ValueError("step argument must not be zero") return tuple(int(x) for x in arglist) else: raise TypeError("range() accepts 1-3 arguments, given", len(arglist)) except TypeError: raise TypeError("range() arguments must be numbers or strings " "representing numbers") def genrange(*a): """Function to implement 'range' as a generator""" start, stop, step = handleargs(a) value = start while value < stop: yield value value += step class oldrange: """Class implementing a range object. To the user the instances feel like immutable sequences (and you can't concatenate or slice them) Done using the old way (pre-iterators; __len__ and __getitem__) to have an object be used by a 'for' loop. """ def __init__(self, *a): """ Initialize start, stop, and step values along with calculating the nubmer of values (what __len__ will return) in the range""" self.start, self.stop, self.step = handleargs(a) self.len = max(0, (self.stop - self.start) // self.step) def __repr__(self): """implement repr(x) which is also used by print""" return 'range(%r, %r, %r)' % (self.start, self.stop, self.step) def __len__(self): """implement len(x)""" return self.len def __getitem__(self, i): """implement x[i]""" if 0 <= i <= self.len: return self.start + self.step * i else: raise IndexError, 'range[i] index out of range' def test(): import time, __builtin__ #Just a quick sanity check correct_result = __builtin__.range(5, 100, 3) oldrange_result = list(oldrange(5, 100, 3)) genrange_result = list(genrange(5, 100, 3)) if genrange_result != correct_result or oldrange_result != correct_result: raise Exception("error in implementation:\ncorrect = %s" "\nold-style = %s\ngenerator = %s" % (correct_result, oldrange_result, genrange_result)) print "Timings for range(1000):" t1 = time.time() for i in oldrange(1000): pass t2 = time.time() for i in genrange(1000): pass t3 = time.time() for i in __builtin__.range(1000): pass t4 = time.time() print t2-t1, 'sec (old-style class)' print t3-t2, 'sec (generator)' print t4-t3, 'sec (built-in)' if __name__ == '__main__': test() PKO]FI&'&' Complex.pyonu[ ^c@sddlZddlZejdZejdZdZdZddedZdZdZ d dd YZ d Z d d Z dZ edkre ndS(iNg@cCst|dot|dS(Ntretim(thasattr(tobj((s,/usr/lib64/python2.7/Demo/classes/Complex.pyt IsComplexGscCs7t|r|St|tr)t|St|SdS(N(Rt isinstancettupletComplex(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pyt ToComplexJs   icCs5|t|}ttj||tj||S(N(ttwopiRtmathtcostsin(trtphit fullcircle((s,/usr/lib64/python2.7/Demo/classes/Complex.pytPolarToComplexRscCst|r|jS|S(N(RR(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pytReVs cCst|r|jSdS(Ni(RR(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pytIm[s RcBseZdddZdZdZdZdZdZdZdZ d Z d Z d Z d Z d ZdZe ZZedZeZdZeZdZdZdZeZdZdZddZdZRS(icCsd}d}t|r-|j}|j}n|}t|r\||j}||j}n ||}||jd<||jdcCsdG|GdG|Gyt|}Wntj}nXdG|GHt|tsZt|tri||k}nt|||k}|sdG|GdGt||GHndS(Ns tands->s!! !! !! should betdiff(tevaltsystexc_typeRtstrR@(texprtatbRtfuzztresulttok((s,/usr/lib64/python2.7/Demo/classes/Complex.pytcheckops  cCsdGHdtfd tfd!tdfd"tddfd#ttddfd$ttdddfd%tdtddfd&tdtdfd'tdtddfd(ttddtdd ff }ddg}x|D]x}|dcd7<|dd|djksH|dd|djkrd G|dGd G|dGH|dcd7As           J PKO]E Range.pycnu[ ^c@sNdZdZdZdddYZdZedkrJendS( s Example of a generator: re-implement the built-in range function without actually constructing the list of values. OldStyleRange is coded in the way required to work in a 'for' loop before iterators were introduced into the language; using __getitem__ and __len__ . cCsyt|dkr,dt|ddfSt|dkr_t|dt|ddfSt|dkr|ddkrtdntd|DStdt|Wntk rtdnXd S( sgTake list of arguments and extract/create proper start, stop, and step values and return in a tupleiiiisstep argument must not be zerocss|]}t|VqdS(N(tint(t.0tx((s*/usr/lib64/python2.7/Demo/classes/Range.pys ss$range() accepts 1-3 arguments, givensArange() arguments must be numbers or strings representing numbersN(tlenRt ValueErrorttuplet TypeError(targlist((s*/usr/lib64/python2.7/Demo/classes/Range.pyt handleargss! cgsAt|\}}}|}x||kr<|V||7}qWdS(s,Function to implement 'range' as a generatorN(R(tatstarttstoptsteptvalue((s*/usr/lib64/python2.7/Demo/classes/Range.pytgenranges toldrangecBs2eZdZdZdZdZdZRS(sClass implementing a range object. To the user the instances feel like immutable sequences (and you can't concatenate or slice them) Done using the old way (pre-iterators; __len__ and __getitem__) to have an object be used by a 'for' loop. cGsEt|\|_|_|_td|j|j|j|_dS(s Initialize start, stop, and step values along with calculating the nubmer of values (what __len__ will return) in the rangeiN(RR R R tmaxR(tselfR ((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__init__,scCsd|j|j|jfS(s-implement repr(x) which is also used by printsrange(%r, %r, %r)(R R R (R((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__repr__2scCs|jS(simplement len(x)(R(R((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__len__6scCs>d|ko|jknr1|j|j|StddS(simplement x[i]isrange[i] index out of rangeN(RR R t IndexError(Rti((s*/usr/lib64/python2.7/Demo/classes/Range.pyt __getitem__:s(t__name__t __module__t__doc__RRRR(((s*/usr/lib64/python2.7/Demo/classes/Range.pyR"s    c Cs9ddl}ddl}|jddd}ttddd}ttddd}||ksu||krtd|||fndGH|j}xtdD]}qW|j}xtdD]}qW|j}x|jdD]}qW|j} ||GdGH||Gd GH| |Gd GHdS( NiiidisEerror in implementation: correct = %s old-style = %s generator = %ssTimings for range(1000):issec (old-style class)ssec (generator)ssec (built-in)(ttimet __builtin__trangetlistRRt Exception( RRtcorrect_resulttoldrange_resulttgenrange_resulttt1Rtt2tt3tt4((s*/usr/lib64/python2.7/Demo/classes/Range.pyttestBs*      t__main__N((RRRRR'R(((s*/usr/lib64/python2.7/Demo/classes/Range.pyts     PKO]:6  Vec.pyonu[ ^c@s'dddYZdZedS(tVeccBsbeZdZdZedZdZdZdZdZ dZ dZ e Z RS( sx A simple vector class Instances of the Vec class can be constructed from numbers >>> a = Vec(1, 2, 3) >>> b = Vec(3, 2, 1) added >>> a + b Vec(4, 4, 4) subtracted >>> a - b Vec(-2, 0, 2) and multiplied by a scalar on the left >>> 3.0 * a Vec(3.0, 6.0, 9.0) or on the right >>> a * 3.0 Vec(3.0, 6.0, 9.0) cGst||_dS(N(tlisttv(tselfR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__init__scCs.t|tstn|}||_|S(N(t isinstanceRt TypeErrorR(tclsRtinst((s(/usr/lib64/python2.7/Demo/classes/Vec.pytfromlists    cCs)djd|jD}dj|S(Ns, css|]}t|VqdS(N(trepr(t.0tx((s(/usr/lib64/python2.7/Demo/classes/Vec.pys %ssVec({0})(tjoinRtformat(Rtargs((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__repr__$scCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__len__(scCs |j|S(N(R(Rti((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt __getitem__+scCs?gt|j|jD]\}}||^q}tj|S(N(tzipRRR (RtotherR tyR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__add__.s2cCs?gt|j|jD]\}}||^q}tj|S(N(RRRR (RRR RR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__sub__3s2cCs-g|jD]}||^q }tj|S(N(RRR (RtscalarR R((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__mul__8s ( t__name__t __module__t__doc__Rt classmethodR RRRRRRt__rmul__(((s(/usr/lib64/python2.7/Demo/classes/Vec.pyRs       cCsddl}|jdS(Ni(tdoctestttestmod(R!((s(/usr/lib64/python2.7/Demo/classes/Vec.pyttest@s N((RR#(((s(/usr/lib64/python2.7/Demo/classes/Vec.pyts? PKO]FI&'&' Complex.pycnu[ ^c@sddlZddlZejdZejdZdZdZddedZdZdZ d dd YZ d Z d d Z dZ edkre ndS(iNg@cCst|dot|dS(Ntretim(thasattr(tobj((s,/usr/lib64/python2.7/Demo/classes/Complex.pyt IsComplexGscCs7t|r|St|tr)t|St|SdS(N(Rt isinstancettupletComplex(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pyt ToComplexJs   icCs5|t|}ttj||tj||S(N(ttwopiRtmathtcostsin(trtphit fullcircle((s,/usr/lib64/python2.7/Demo/classes/Complex.pytPolarToComplexRscCst|r|jS|S(N(RR(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pytReVs cCst|r|jSdS(Ni(RR(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pytIm[s RcBseZdddZdZdZdZdZdZdZdZ d Z d Z d Z d Z d ZdZe ZZedZeZdZeZdZdZdZeZdZdZddZdZRS(icCsd}d}t|r-|j}|j}n|}t|r\||j}||j}n ||}||jd<||jdcCsdG|GdG|Gyt|}Wntj}nXdG|GHt|tsZt|tri||k}nt|||k}|sdG|GdGt||GHndS(Ns tands->s!! !! !! should betdiff(tevaltsystexc_typeRtstrR@(texprtatbRtfuzztresulttok((s,/usr/lib64/python2.7/Demo/classes/Complex.pytcheckops  cCsdGHdtfd tfd!tdfd"tddfd#ttddfd$ttdddfd%tdtddfd&tdtdfd'tdtddfd(ttddtdd ff }ddg}x|D]x}|dcd7<|dd|djksH|dd|djkrd G|dGd G|dGH|dcd7As           J PKO]cAC<5(5( bitvec.pyonu[ ^c@s{ddlZejjZdefdYZdZddlZdZdZ dZ dfd YZ e Z dS( iNterrorcBseZRS((t__name__t __module__(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR scCsEt|tdks5d|ko/dkn rAtdndS(Niis)bitvec() items must have int value 0 or 1(ttypeR(tvalue((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_value s5cCstjt|\}}d|>}||krMtd||ffnx,|r{|d?}||@rnPn|d}qPW|S(Nls(param, l) = %ri(tmathtfrexptfloatt RuntimeError(tparamtmanttltbitmask((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _compute_lens     cCsit|tdkr$tdn|dkr=||}nd|koT|knsetdn|S(Nissequence subscript not intslist index out of range(Rt TypeErrort IndexError(tlentkey((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_key!s    cCs>t|dt||}}||kr4|}n||fS(Ni(tmaxtmin(Rtitj((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_slice*s  tBitVeccBs eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZRS(cGsd|_d|_t|s!nt|dkr|\}t|tgkrd}d}x+|D]#}|r||B}n|d>}qgW||_t||_qt|tdkr|dkrtdn||_t||_qtdnt|dkr|\}}t|tdkr|dkrNtdn||_t|tdkr{td nt|}||krd GH|jd|>d@|_n||_qtdn td dS( Nliils$bitvec() can't handle negative longss)bitvec() requires array or long parameteriscan't handle negative longss$bitvec()'s 2nd parameter must be intsMwarning: bitvec() value is longer than the length indicates, truncating values%bitvec() requires 0 -- 2 parameter(s)(t_datat_lenRRRR(tselftparamsR Rtbit_masktitemtlengthtcomputed_length((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__init__4sL                    cCs(tt| d||j|j+dS(Ni(RtlongR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytappendbscCsR|r|j}n |j}d}x)|rM|d?||d@dk}}q%W|S(Nii(R(RRtdatatcount((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR&is   #cCs^|r|j}n |j}d}|s4tdnx#|d@sY|d?|d}}q7W|S(Nislist.index(x): x not in listi(Rt ValueError(RRR%tindex((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR(us    cCs"tt| d|||+dS(Ni(RR#(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytinsertscCs||j|=dS(N(R((RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytremovescCso|jd}}xOt|jD]>}|sA||j|>}Pn|d>|d@B|d?}}q W||_dS(Nli(RtrangeR(RR%tresultR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytreverses!cCs/|jd}d|>d|j|>|_dS(Nil(R&RR(Rtc((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytsortscCst|j|jS(N(RRR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytcopyscCs(g}x|D]}|j|q W|S(N(R$(RR,R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytseqs cCsd|j|jfS(Nsbitvec(%r, %r)(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__repr__scGs#t|t|kr1tt|f|}n|j}|dksU|jdkret||jS||jkrt||j}t|| || pt||||S|j|jkrdS|dkrt|d|dS|d?}t|| || pt||||SdS(Nii(RtapplytbitvecRtcmpRR(RtothertrestR t min_length((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__cmp__s    cCs|jS(N(R(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__len__scCs't|j|}|jd|>@dkS(Nli(RRR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __getitem__scCsHt|j|}|r/|jd|>B|_n|jd|>@|_dS(Nl(RRR(RRR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __setitem__scCsIt|j|}|| j||dj|?B|_|jd|_dS(Ni(RRR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __delitem__s#cCst|j||\}}||kr4tddS|rJ|j|?}n |j}||}||jkr|d|>d@}nt||S(Nlili(RRRR(RRRtndatatnlength((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __getslice__s    cGst|j||\}}t|t|krLtt|f|}n|| }||}|j|j|j|j>B|j>B|_|j|||j|_dS(N(RRRR3R4R(RRRtsequenceR7tls_parttms_part((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __setslice__s  cCst|j||\}}|dkrK||jkrKd\|_|_nB||kr|| j||j|?B|_|j|||_ndS(Nil(li(RRR(RRR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __delslice__s  cCs#|j}|||j|j+|S(N(R0R(RR6tretval((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__add__s cCst|tdkr$tdn|dkr=tddS|dkrS|jS|jdkrvtd|j|S|jdkrtd|j|Stdd}x|r|||d}}qW|S(Nissequence subscript not intli(RRRR0RR(Rt multiplierRF((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__mul__ s      cGsWt|t|kr1tt|f|}nt|j|j@t|j|jS(N(RR3R4RRRR(RtotherseqR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__and__scGsWt|t|kr1tt|f|}nt|j|jAt|j|jS(N(RR3R4RRRR(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__xor__%scGsWt|t|kr1tt|f|}nt|j|jBt|j|jS(N(RR3R4RRRR(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__or__.scCs#t|jd|j>d@|jS(Nli(RRR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __invert__7scGs;t|t|kr1tt|f|}n||fS(N(RR3R4(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __coerce__<scCs t|jS(N(tintR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__int__CscCs t|jS(N(R#R(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__long__FscCs t|jS(N(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __float__Is(RRR"R$R&R(R)R*R-R/R0R1R2R9R:R;R<R=R@RDRERGRIRKRLRMRNRORQRRRS(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR2s: .                   ( tsyststderrtwritetrprtt ExceptionRRRRRRRR4(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyts    PKO](( bitvec.pynu[# # this is a rather strict implementation of a bit vector class # it is accessed the same way as an array of python-ints, except # the value must be 0 or 1 # import sys; rprt = sys.stderr.write #for debugging class error(Exception): pass def _check_value(value): if type(value) != type(0) or not 0 <= value < 2: raise error, 'bitvec() items must have int value 0 or 1' import math def _compute_len(param): mant, l = math.frexp(float(param)) bitmask = 1L << l if bitmask <= param: raise RuntimeError('(param, l) = %r' % ((param, l),)) while l: bitmask = bitmask >> 1 if param & bitmask: break l = l - 1 return l def _check_key(len, key): if type(key) != type(0): raise TypeError, 'sequence subscript not int' if key < 0: key = key + len if not 0 <= key < len: raise IndexError, 'list index out of range' return key def _check_slice(len, i, j): #the type is ok, Python already checked that i, j = max(i, 0), min(len, j) if i > j: i = j return i, j class BitVec: def __init__(self, *params): self._data = 0L self._len = 0 if not len(params): pass elif len(params) == 1: param, = params if type(param) == type([]): value = 0L bit_mask = 1L for item in param: # strict check #_check_value(item) if item: value = value | bit_mask bit_mask = bit_mask << 1 self._data = value self._len = len(param) elif type(param) == type(0L): if param < 0: raise error, 'bitvec() can\'t handle negative longs' self._data = param self._len = _compute_len(param) else: raise error, 'bitvec() requires array or long parameter' elif len(params) == 2: param, length = params if type(param) == type(0L): if param < 0: raise error, \ 'can\'t handle negative longs' self._data = param if type(length) != type(0): raise error, 'bitvec()\'s 2nd parameter must be int' computed_length = _compute_len(param) if computed_length > length: print 'warning: bitvec() value is longer than the length indicates, truncating value' self._data = self._data & \ ((1L << length) - 1) self._len = length else: raise error, 'bitvec() requires array or long parameter' else: raise error, 'bitvec() requires 0 -- 2 parameter(s)' def append(self, item): #_check_value(item) #self[self._len:self._len] = [item] self[self._len:self._len] = \ BitVec(long(not not item), 1) def count(self, value): #_check_value(value) if value: data = self._data else: data = (~self)._data count = 0 while data: data, count = data >> 1, count + (data & 1 != 0) return count def index(self, value): #_check_value(value): if value: data = self._data else: data = (~self)._data index = 0 if not data: raise ValueError, 'list.index(x): x not in list' while not (data & 1): data, index = data >> 1, index + 1 return index def insert(self, index, item): #_check_value(item) #self[index:index] = [item] self[index:index] = BitVec(long(not not item), 1) def remove(self, value): del self[self.index(value)] def reverse(self): #ouch, this one is expensive! #for i in self._len>>1: self[i], self[l-i] = self[l-i], self[i] data, result = self._data, 0L for i in range(self._len): if not data: result = result << (self._len - i) break result, data = (result << 1) | (data & 1), data >> 1 self._data = result def sort(self): c = self.count(1) self._data = ((1L << c) - 1) << (self._len - c) def copy(self): return BitVec(self._data, self._len) def seq(self): result = [] for i in self: result.append(i) return result def __repr__(self): ##rprt('.' + '__repr__()\n') return 'bitvec(%r, %r)' % (self._data, self._len) def __cmp__(self, other, *rest): #rprt('%r.__cmp__%r\n' % (self, (other,) + rest)) if type(other) != type(self): other = apply(bitvec, (other, ) + rest) #expensive solution... recursive binary, with slicing length = self._len if length == 0 or other._len == 0: return cmp(length, other._len) if length != other._len: min_length = min(length, other._len) return cmp(self[:min_length], other[:min_length]) or \ cmp(self[min_length:], other[min_length:]) #the lengths are the same now... if self._data == other._data: return 0 if length == 1: return cmp(self[0], other[0]) else: length = length >> 1 return cmp(self[:length], other[:length]) or \ cmp(self[length:], other[length:]) def __len__(self): #rprt('%r.__len__()\n' % (self,)) return self._len def __getitem__(self, key): #rprt('%r.__getitem__(%r)\n' % (self, key)) key = _check_key(self._len, key) return self._data & (1L << key) != 0 def __setitem__(self, key, value): #rprt('%r.__setitem__(%r, %r)\n' % (self, key, value)) key = _check_key(self._len, key) #_check_value(value) if value: self._data = self._data | (1L << key) else: self._data = self._data & ~(1L << key) def __delitem__(self, key): #rprt('%r.__delitem__(%r)\n' % (self, key)) key = _check_key(self._len, key) #el cheapo solution... self._data = self[:key]._data | self[key+1:]._data >> key self._len = self._len - 1 def __getslice__(self, i, j): #rprt('%r.__getslice__(%r, %r)\n' % (self, i, j)) i, j = _check_slice(self._len, i, j) if i >= j: return BitVec(0L, 0) if i: ndata = self._data >> i else: ndata = self._data nlength = j - i if j != self._len: #we'll have to invent faster variants here #e.g. mod_2exp ndata = ndata & ((1L << nlength) - 1) return BitVec(ndata, nlength) def __setslice__(self, i, j, sequence, *rest): #rprt('%s.__setslice__%r\n' % (self, (i, j, sequence) + rest)) i, j = _check_slice(self._len, i, j) if type(sequence) != type(self): sequence = apply(bitvec, (sequence, ) + rest) #sequence is now of our own type ls_part = self[:i] ms_part = self[j:] self._data = ls_part._data | \ ((sequence._data | \ (ms_part._data << sequence._len)) << ls_part._len) self._len = self._len - j + i + sequence._len def __delslice__(self, i, j): #rprt('%r.__delslice__(%r, %r)\n' % (self, i, j)) i, j = _check_slice(self._len, i, j) if i == 0 and j == self._len: self._data, self._len = 0L, 0 elif i < j: self._data = self[:i]._data | (self[j:]._data >> i) self._len = self._len - j + i def __add__(self, other): #rprt('%r.__add__(%r)\n' % (self, other)) retval = self.copy() retval[self._len:self._len] = other return retval def __mul__(self, multiplier): #rprt('%r.__mul__(%r)\n' % (self, multiplier)) if type(multiplier) != type(0): raise TypeError, 'sequence subscript not int' if multiplier <= 0: return BitVec(0L, 0) elif multiplier == 1: return self.copy() #handle special cases all 0 or all 1... if self._data == 0L: return BitVec(0L, self._len * multiplier) elif (~self)._data == 0L: return ~BitVec(0L, self._len * multiplier) #otherwise el cheapo again... retval = BitVec(0L, 0) while multiplier: retval, multiplier = retval + self, multiplier - 1 return retval def __and__(self, otherseq, *rest): #rprt('%r.__and__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) #sequence is now of our own type return BitVec(self._data & otherseq._data, \ min(self._len, otherseq._len)) def __xor__(self, otherseq, *rest): #rprt('%r.__xor__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) #sequence is now of our own type return BitVec(self._data ^ otherseq._data, \ max(self._len, otherseq._len)) def __or__(self, otherseq, *rest): #rprt('%r.__or__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) #sequence is now of our own type return BitVec(self._data | otherseq._data, \ max(self._len, otherseq._len)) def __invert__(self): #rprt('%r.__invert__()\n' % (self,)) return BitVec(~self._data & ((1L << self._len) - 1), \ self._len) def __coerce__(self, otherseq, *rest): #needed for *some* of the arithmetic operations #rprt('%r.__coerce__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) return self, otherseq def __int__(self): return int(self._data) def __long__(self): return long(self._data) def __float__(self): return float(self._data) bitvec = BitVec PKO]cAC<5(5( bitvec.pycnu[ ^c@s{ddlZejjZdefdYZdZddlZdZdZ dZ dfd YZ e Z dS( iNterrorcBseZRS((t__name__t __module__(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR scCsEt|tdks5d|ko/dkn rAtdndS(Niis)bitvec() items must have int value 0 or 1(ttypeR(tvalue((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_value s5cCstjt|\}}d|>}||krMtd||ffnx,|r{|d?}||@rnPn|d}qPW|S(Nls(param, l) = %ri(tmathtfrexptfloatt RuntimeError(tparamtmanttltbitmask((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _compute_lens     cCsit|tdkr$tdn|dkr=||}nd|koT|knsetdn|S(Nissequence subscript not intslist index out of range(Rt TypeErrort IndexError(tlentkey((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_key!s    cCs>t|dt||}}||kr4|}n||fS(Ni(tmaxtmin(Rtitj((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_slice*s  tBitVeccBs eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZRS(cGsd|_d|_t|s!nt|dkr|\}t|tgkrd}d}x+|D]#}|r||B}n|d>}qgW||_t||_qt|tdkr|dkrtdn||_t||_qtdnt|dkr|\}}t|tdkr|dkrNtdn||_t|tdkr{td nt|}||krd GH|jd|>d@|_n||_qtdn td dS( Nliils$bitvec() can't handle negative longss)bitvec() requires array or long parameteriscan't handle negative longss$bitvec()'s 2nd parameter must be intsMwarning: bitvec() value is longer than the length indicates, truncating values%bitvec() requires 0 -- 2 parameter(s)(t_datat_lenRRRR(tselftparamsR Rtbit_masktitemtlengthtcomputed_length((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__init__4sL                    cCs(tt| d||j|j+dS(Ni(RtlongR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytappendbscCsR|r|j}n |j}d}x)|rM|d?||d@dk}}q%W|S(Nii(R(RRtdatatcount((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR&is   #cCs^|r|j}n |j}d}|s4tdnx#|d@sY|d?|d}}q7W|S(Nislist.index(x): x not in listi(Rt ValueError(RRR%tindex((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR(us    cCs"tt| d|||+dS(Ni(RR#(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytinsertscCs||j|=dS(N(R((RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytremovescCso|jd}}xOt|jD]>}|sA||j|>}Pn|d>|d@B|d?}}q W||_dS(Nli(RtrangeR(RR%tresultR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytreverses!cCs/|jd}d|>d|j|>|_dS(Nil(R&RR(Rtc((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytsortscCst|j|jS(N(RRR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytcopyscCs(g}x|D]}|j|q W|S(N(R$(RR,R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytseqs cCsd|j|jfS(Nsbitvec(%r, %r)(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__repr__scGs#t|t|kr1tt|f|}n|j}|dksU|jdkret||jS||jkrt||j}t|| || pt||||S|j|jkrdS|dkrt|d|dS|d?}t|| || pt||||SdS(Nii(RtapplytbitvecRtcmpRR(RtothertrestR t min_length((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__cmp__s    cCs|jS(N(R(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__len__scCs't|j|}|jd|>@dkS(Nli(RRR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __getitem__scCsHt|j|}|r/|jd|>B|_n|jd|>@|_dS(Nl(RRR(RRR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __setitem__scCsIt|j|}|| j||dj|?B|_|jd|_dS(Ni(RRR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __delitem__s#cCst|j||\}}||kr4tddS|rJ|j|?}n |j}||}||jkr|d|>d@}nt||S(Nlili(RRRR(RRRtndatatnlength((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __getslice__s    cGst|j||\}}t|t|krLtt|f|}n|| }||}|j|j|j|j>B|j>B|_|j|||j|_dS(N(RRRR3R4R(RRRtsequenceR7tls_parttms_part((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __setslice__s  cCst|j||\}}|dkrK||jkrKd\|_|_nB||kr|| j||j|?B|_|j|||_ndS(Nil(li(RRR(RRR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __delslice__s  cCs#|j}|||j|j+|S(N(R0R(RR6tretval((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__add__s cCst|tdkr$tdn|dkr=tddS|dkrS|jS|jdkrvtd|j|S|jdkrtd|j|Stdd}x|r|||d}}qW|S(Nissequence subscript not intli(RRRR0RR(Rt multiplierRF((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__mul__ s      cGsWt|t|kr1tt|f|}nt|j|j@t|j|jS(N(RR3R4RRRR(RtotherseqR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__and__scGsWt|t|kr1tt|f|}nt|j|jAt|j|jS(N(RR3R4RRRR(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__xor__%scGsWt|t|kr1tt|f|}nt|j|jBt|j|jS(N(RR3R4RRRR(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__or__.scCs#t|jd|j>d@|jS(Nli(RRR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __invert__7scGs;t|t|kr1tt|f|}n||fS(N(RR3R4(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __coerce__<scCs t|jS(N(tintR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__int__CscCs t|jS(N(R#R(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__long__FscCs t|jS(N(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __float__Is(RRR"R$R&R(R)R*R-R/R0R1R2R9R:R;R<R=R@RDRERGRIRKRLRMRNRORQRRRS(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR2s: .                   ( tsyststderrtwritetrprtt ExceptionRRRRRRRR4(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyts    PKO]w Dates.pycnu[ ^c @spdddddddddd d d g Zd d dddddgZddddddddddddg ZgZdZx%eD]ZejeeeZqW[[ededfZdZ dZ dZ dZ dZ dZe dZd Zd!Zd"d,d#YZd$Zd%efd&YZd'Zed(krled)d*nd+S(-tJanuarytFebruarytMarchtApriltMaytJunetJulytAugustt SeptembertOctobertNovembertDecembertFridaytSaturdaytSundaytMondaytTuesdayt WednesdaytThursdayiiiiilcCs6|ddkrdS|ddkr(dS|ddkS(Niiiiid((tyear((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_is_leap>s cCsdt|S(Nim(R(R((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _days_in_yearCscCs,|d|dd|dd|ddS(Nlmiiicidii((R((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_before_yearFscCs(|dkrt|rdSt|dS(Niii(Rt_DAYS_IN_MONTH(tmonthR((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_in_monthIscCs"t|d|dko t|S(Nii(t_DAYS_BEFORE_MONTHR(RR((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_before_monthMscCs't|jt|j|j|jS(N(RRRRtday(tdate((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _date2numPsicCs}t|tkr(tdt|ntddd}|`|`|`|`||_|dt}d||t|}}|d}t |}||kr|d}|t |}n||t ||}}yt |}Wnt t fk rnXt|ddd}t||}||krX|d}|t||}n|||||_|_|_|S(Nsargument must be integer: %riiimii (ttypet _INT_TYPESt TypeErrortDatetordRRRt_DI400YRRtintt ValueErrort OverflowErrortminRR(tntanstn400RtmoretdbyRtdbm((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _num2dateWs0       !cCstt|dS(Ni(t _DAY_NAMESR%(R)((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_num2daytsR"cBs_eZdZdZdZdZdZdZeZdZ dZ dZ RS( cCsd|kodkns/td|fnt||}d|koU|knsptd||fn||||_|_|_t||_dS(Nii smonth must be in 1..12: %rsday must be in 1..%r: %r(R&RRRRRR#(tselfRRRtdim((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt__init__yscCs3|jj|r"td|n||j|num failedsnum->date failed(R"treprRMR!R@tmaxR(RRR#R/RRR( t firstyeartlastyeartatbtxtdtlordtytfordtfdtld((s*/usr/lib64/python2.7/Demo/classes/Dates.pyttestsP 1            * 8   %-t__main__i:ifN((RAR0RRR.R3tappendRR RRRRRRR$R/R1R"RLt ExceptionRMR[RF(((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt,s6  *           4  . PKO]w Dates.pyonu[ ^c @spdddddddddd d d g Zd d dddddgZddddddddddddg ZgZdZx%eD]ZejeeeZqW[[ededfZdZ dZ dZ dZ dZ dZe dZd Zd!Zd"d,d#YZd$Zd%efd&YZd'Zed(krled)d*nd+S(-tJanuarytFebruarytMarchtApriltMaytJunetJulytAugustt SeptembertOctobertNovembertDecembertFridaytSaturdaytSundaytMondaytTuesdayt WednesdaytThursdayiiiiilcCs6|ddkrdS|ddkr(dS|ddkS(Niiiiid((tyear((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_is_leap>s cCsdt|S(Nim(R(R((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _days_in_yearCscCs,|d|dd|dd|ddS(Nlmiiicidii((R((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_before_yearFscCs(|dkrt|rdSt|dS(Niii(Rt_DAYS_IN_MONTH(tmonthR((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_in_monthIscCs"t|d|dko t|S(Nii(t_DAYS_BEFORE_MONTHR(RR((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_before_monthMscCs't|jt|j|j|jS(N(RRRRtday(tdate((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _date2numPsicCs}t|tkr(tdt|ntddd}|`|`|`|`||_|dt}d||t|}}|d}t |}||kr|d}|t |}n||t ||}}yt |}Wnt t fk rnXt|ddd}t||}||krX|d}|t||}n|||||_|_|_|S(Nsargument must be integer: %riiimii (ttypet _INT_TYPESt TypeErrortDatetordRRRt_DI400YRRtintt ValueErrort OverflowErrortminRR(tntanstn400RtmoretdbyRtdbm((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _num2dateWs0       !cCstt|dS(Ni(t _DAY_NAMESR%(R)((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_num2daytsR"cBs_eZdZdZdZdZdZdZeZdZ dZ dZ RS( cCsd|kodkns/td|fnt||}d|koU|knsptd||fn||||_|_|_t||_dS(Nii smonth must be in 1..12: %rsday must be in 1..%r: %r(R&RRRRRR#(tselfRRRtdim((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt__init__yscCs3|jj|r"td|n||j|num failedsnum->date failed(R"treprRMR!R@tmaxR(RRR#R/RRR( t firstyeartlastyeartatbtxtdtlordtytfordtfdtld((s*/usr/lib64/python2.7/Demo/classes/Dates.pyttestsP 1            * 8   %-t__main__i:ifN((RAR0RRR.R3tappendRR RRRRRRR$R/R1R"RLt ExceptionRMR[RF(((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt,s6  *           4  . PKO]:6  Vec.pycnu[ ^c@s'dddYZdZedS(tVeccBsbeZdZdZedZdZdZdZdZ dZ dZ e Z RS( sx A simple vector class Instances of the Vec class can be constructed from numbers >>> a = Vec(1, 2, 3) >>> b = Vec(3, 2, 1) added >>> a + b Vec(4, 4, 4) subtracted >>> a - b Vec(-2, 0, 2) and multiplied by a scalar on the left >>> 3.0 * a Vec(3.0, 6.0, 9.0) or on the right >>> a * 3.0 Vec(3.0, 6.0, 9.0) cGst||_dS(N(tlisttv(tselfR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__init__scCs.t|tstn|}||_|S(N(t isinstanceRt TypeErrorR(tclsRtinst((s(/usr/lib64/python2.7/Demo/classes/Vec.pytfromlists    cCs)djd|jD}dj|S(Ns, css|]}t|VqdS(N(trepr(t.0tx((s(/usr/lib64/python2.7/Demo/classes/Vec.pys %ssVec({0})(tjoinRtformat(Rtargs((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__repr__$scCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__len__(scCs |j|S(N(R(Rti((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt __getitem__+scCs?gt|j|jD]\}}||^q}tj|S(N(tzipRRR (RtotherR tyR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__add__.s2cCs?gt|j|jD]\}}||^q}tj|S(N(RRRR (RRR RR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__sub__3s2cCs-g|jD]}||^q }tj|S(N(RRR (RtscalarR R((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__mul__8s ( t__name__t __module__t__doc__Rt classmethodR RRRRRRt__rmul__(((s(/usr/lib64/python2.7/Demo/classes/Vec.pyRs       cCsddl}|jdS(Ni(tdoctestttestmod(R!((s(/usr/lib64/python2.7/Demo/classes/Vec.pyttest@s N((RR#(((s(/usr/lib64/python2.7/Demo/classes/Vec.pyts? PKO]IRev.pynu[''' A class which presents the reverse of a sequence without duplicating it. From: "Steven D. Majewski" It works on mutable or inmutable sequences. >>> chars = list(Rev('Hello World!')) >>> print ''.join(chars) !dlroW olleH The .forw is so you can use anonymous sequences in __init__, and still keep a reference the forward sequence. ) If you give it a non-anonymous mutable sequence, the reverse sequence will track the updated values. ( but not reassignment! - another good reason to use anonymous values in creating the sequence to avoid confusion. Maybe it should be change to copy input sequence to break the connection completely ? ) >>> nnn = range(3) >>> rnn = Rev(nnn) >>> for n in rnn: print n ... 2 1 0 >>> for n in range(4, 6): nnn.append(n) # update nnn ... >>> for n in rnn: print n # prints reversed updated values ... 5 4 2 1 0 >>> nnn = nnn[1:-1] >>> nnn [1, 2, 4] >>> for n in rnn: print n # prints reversed values of old nnn ... 5 4 2 1 0 # >>> WH = Rev('Hello World!') >>> print WH.forw, WH.back Hello World! !dlroW olleH >>> nnn = Rev(range(1, 10)) >>> print nnn.forw [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print nnn.back [9, 8, 7, 6, 5, 4, 3, 2, 1] >>> rrr = Rev(nnn) >>> rrr <1, 2, 3, 4, 5, 6, 7, 8, 9> ''' class Rev: def __init__(self, seq): self.forw = seq self.back = self def __len__(self): return len(self.forw) def __getitem__(self, j): return self.forw[-(j + 1)] def __repr__(self): seq = self.forw if isinstance(seq, list): wrap = '[]' sep = ', ' elif isinstance(seq, tuple): wrap = '()' sep = ', ' elif isinstance(seq, str): wrap = '' sep = '' else: wrap = '<>' sep = ', ' outstrs = [str(item) for item in self.back] return wrap[:1] + sep.join(outstrs) + wrap[-1:] def _test(): import doctest, Rev return doctest.testmod(Rev) if __name__ == "__main__": _test() PKO] Dbm.pyonu[ ^c@s'dddYZdZedS(tDbmcBsPeZdZdZdZdZdZdZdZdZ RS(cCs(ddl}|j||||_dS(Ni(tdbmtopentdb(tselftfilenametmodetpermR((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__init__ s cCsdd}xO|jD]A}t|dt||}|rJd|}n||}qWd|dS(Nts: s, t{t}(tkeystrepr(Rtstkeytt((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__repr__ s cCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__len__scCst|jt|S(N(tevalRR (RR((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt __getitem__scCst||jt|s$ PKO]1 1 Rev.pyonu[ ^c@s<dZdddYZdZedkr8endS(s A class which presents the reverse of a sequence without duplicating it. From: "Steven D. Majewski" It works on mutable or inmutable sequences. >>> chars = list(Rev('Hello World!')) >>> print ''.join(chars) !dlroW olleH The .forw is so you can use anonymous sequences in __init__, and still keep a reference the forward sequence. ) If you give it a non-anonymous mutable sequence, the reverse sequence will track the updated values. ( but not reassignment! - another good reason to use anonymous values in creating the sequence to avoid confusion. Maybe it should be change to copy input sequence to break the connection completely ? ) >>> nnn = range(3) >>> rnn = Rev(nnn) >>> for n in rnn: print n ... 2 1 0 >>> for n in range(4, 6): nnn.append(n) # update nnn ... >>> for n in rnn: print n # prints reversed updated values ... 5 4 2 1 0 >>> nnn = nnn[1:-1] >>> nnn [1, 2, 4] >>> for n in rnn: print n # prints reversed values of old nnn ... 5 4 2 1 0 # >>> WH = Rev('Hello World!') >>> print WH.forw, WH.back Hello World! !dlroW olleH >>> nnn = Rev(range(1, 10)) >>> print nnn.forw [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print nnn.back [9, 8, 7, 6, 5, 4, 3, 2, 1] >>> rrr = Rev(nnn) >>> rrr <1, 2, 3, 4, 5, 6, 7, 8, 9> tRevcBs,eZdZdZdZdZRS(cCs||_||_dS(N(tforwtback(tselftseq((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__init__?s cCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__len__CscCs|j|d S(Ni(R(Rtj((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt __getitem__FscCs|j}t|tr'd}d}nHt|trEd}d}n*t|trcd}d}n d}d}g|jD]}t|^qy}|d |j||dS(Ns[]s, s()ts<>ii(Rt isinstancetlistttupletstrRtjoin(RRtwraptseptitemtoutstrs((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__repr__Is    "(t__name__t __module__RRR R(((s(/usr/lib64/python2.7/Demo/classes/Rev.pyR>s   cCs%ddl}ddl}|j|S(Ni(tdoctestRttestmod(RR((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt_testZst__main__N((t__doc__RRR(((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt<s  PKM ]ధoHoHxray-profiler-log.phpnu[ * * PHP Core Exceptions */ public $core_exceptions = array( E_ERROR => 'E_ERROR', //1 E_WARNING => 'E_WARNING', //2 E_PARSE => 'E_PARSE', //4 E_NOTICE => 'E_NOTICE', //8 E_CORE_ERROR => 'E_CORE_ERROR', //16 E_CORE_WARNING => 'E_CORE_WARNING', //32 E_COMPILE_ERROR => 'E_COMPILE_ERROR', //64 E_COMPILE_WARNING => 'E_COMPILE_WARNING', //128 E_USER_ERROR => 'E_USER_ERROR', //256 E_USER_WARNING => 'E_USER_WARNING', //512 E_USER_NOTICE => 'E_USER_NOTICE', //1024 E_STRICT => 'E_STRICT', //2048 E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR', //4096 E_DEPRECATED => 'E_DEPRECATED', //8192 E_USER_DEPRECATED => 'E_USER_DEPRECATED', //16384 E_ALL => 'E_ALL', //32767 ); /** * @var array> */ private $data = array(); /** * @var self|null */ private static $instance = null; private function __construct() { } private function __clone() { } /** * @return string */ protected function wpHomeConstant() { if (defined('WP_HOME') && WP_HOME) { return (string)WP_HOME; } return ''; } /** * @return string */ protected function wpHomeOption() { if (function_exists('get_option')) { $home = get_option('home'); if (is_string($home)) { return $home; } } return ''; } /** * @return string */ public function website() { if (! empty($this->website)) { return $this->website; } $wp_home_constant = $this->wpHomeConstant(); $wp_home_option = $this->wpHomeOption(); if (! empty($wp_home_constant)) { $this->website = $wp_home_constant; } elseif (! empty($wp_home_option)) { $this->website = $wp_home_option; } elseif (is_array($_SERVER) && array_key_exists('SERVER_NAME', $_SERVER)) { $this->website = (string)$_SERVER['SERVER_NAME']; } return $this->website; } /** * @return string */ public function user() { if (!empty($this->user)) { return $this->user; } $parse = parse_url($this->website()); if (is_array($parse) and array_key_exists('host', $parse)) { $this->user = $parse['host']; } return $this->user; } /** * @return string */ public function requestUri() { if (! empty($this->request_uri)) { return $this->request_uri; } if (is_array($_SERVER) && array_key_exists('REQUEST_URI', $_SERVER)) { /* keep path only; drop query/fragment - they may carry secrets: tokens, signed-URL params, emails, API keys */ $uri = (string)$_SERVER['REQUEST_URI']; $uri = explode('?', $uri, 2)[0]; $this->request_uri = explode('#', $uri, 2)[0]; } return $this->request_uri; } /** * @return int */ public function httpCode() { if (! empty($this->http_code)) { return $this->http_code; } if (function_exists('http_response_code')) { $this->http_code = (int)http_response_code(); } return $this->http_code; } /** * @return self */ public static function instance() { if (is_null(self::$instance)) { self::$instance = new self(); self::$instance->clean(); } return self::$instance; } /** * @return array */ public function getData() { return $this->data; } /** * @param int $errno * @param string $errstr * @param ?string $errfile * @param ?int $errline * * @return void */ public function setData($errno, $errstr, $errfile = null, $errline = null) { $this->data[] = array( 'message' => $errstr, 'type' => isset($this->core_exceptions[$errno]) ? $this->core_exceptions[$errno] : 'Undefined: ' . $errno, 'filename' => $errfile, 'lineno' => $errline, ); } /** * @return string|bool */ public function sendData() { $data = $this->prepareSentryData($this->data); if (empty($data)) { return false; } $sentry_response = $this->sendSentryData($data); if (!$sentry_response) { return false; } $this->clean(); return $sentry_response; } /** * @param array $data * * @return string|bool */ private function prepareSentryData($data) { if (empty($data)) { return false; } $formatted = array(); foreach ($data as $row) { $formatted[] = array( "stacktrace" => array( "frames" => array( array( // minimize: drop server path prefix so the OS username is not leaked "filename" => $this->minimizePath($row["filename"]), "lineno" => $row["lineno"], ) ), "frames_omitted" => null, ), "type" => $row['type'], // minimize: scrub embedded absolute paths and cap length "value" => $this->minimizeMessage($row['message']), ); } $xray_version = defined('XRAY_RELEASE') ? XRAY_RELEASE : null; $sentry = array( "release" => $this->release($xray_version), "tags" => array( "php_version" => phpversion(), "xray_version" => $xray_version, ), "extra" => array( 'website' => $this->website(), 'request_uri' => $this->requestUri(), 'http_code' => $this->httpCode(), ), "user" => array( "username" => $this->user(), ), "sentry.interfaces.Exception" => array( "exc_omitted" => null, "values" => $formatted, ), ); // Defence-in-depth against json_encode() returning false (which // would make sendData()'s empty() guard silently drop the whole // Sentry POST). On PHP 7.2+ this flag substitutes U+FFFD for any // malformed UTF-8 in the payload. On older runtimes the flag is // undefined so flags=0; there truncateUtf8() guarantees OUR // truncation never introduces malformed UTF-8, so the patch does no // harm. Note: a RAW error message already malformed before // truncation can still fail json_encode on PHP <7.2 — that is the // exact pre-patch behavior, pre-existing and out of scope here (not // a regression introduced by this fix). $flags = defined('JSON_INVALID_UTF8_SUBSTITUTE') ? JSON_INVALID_UTF8_SUBSTITUTE : 0; return json_encode($sentry, $flags); } /** * Reduce the server path used for the frame.filename field to the file * basename, and redact any leaf that is not a recognised source/asset * file to the literal token ''. In practice frame.filename is * PHP's errfile, which is always the executing source/template script, * so its basename ends in a known code/template/asset extension (.php, * .phtml, .tpl, .twig, .js, .css, ...) and is kept (e.g. "index.php", * "loader.php", "style.css"). Any other leaf is redacted: a bare home * or vhost directory leaf is the account name — possibly a DOTTED OS * username (/home/john.doe) or a domain-named Plesk vhost * (/var/www/vhosts/example.com) — and does NOT end in a source * extension. Matching on a source/asset extension allowlist (rather * than the earlier "any dot means it's a file" test) closes the dotted * directory/username/domain leak that the dot heuristic missed, while * still keeping legitimate dotted source files. The OS username / * filesystem layout therefore never egresses regardless of layout. * * @param string|null $path * * @return string|null */ private function minimizePath($path) { if (!is_string($path) || $path === '') { return $path; } $normalized = trim(str_replace('\\', '/', $path), '/'); if ($normalized === '') { return ''; } $segments = explode('/', $normalized); $basename = end($segments); // Keep the basename only when it is plausibly a real source/asset // file (an errfile always is); otherwise it is a bare // directory/account leaf (dotless OR dotted username/domain) and // must be redacted. $source_ext_pattern = '/\.(php\d?|phtml|phps|inc|module|install' . '|engine|theme|profile|tpl|twig|html?|js|mjs|cjs|jsx|tsx?' . '|css|s[ac]ss|less|xml|ya?ml|json)$/i'; if ( $basename === '' || !preg_match($source_ext_pattern, $basename) ) { return ''; } return $basename; } /** * Minimize a raw PHP error message before it enters the payload: redact * any embedded absolute filesystem path to the literal token '' * and cap the overall length. PHP error strings routinely embed server * paths, query fragments and runtime values that need not be disclosed * off-host. A constant '' replacement (rather than retaining the * basename) ensures a message can never leak a username/domain/layout * regardless of where the path terminates — e.g. an open_basedir or * disk-quota error names a directory whose leaf segment is the account * name or vhost domain. * * @param string|null $message * * @return string|null */ private function minimizeMessage($message) { if (!is_string($message) || $message === '') { return $message; } // Bound the input BEFORE scrubbing: the path-scrub regex must never // run on a huge subject. A PHP error string can be tens of KB (E_ALL, // big traces, var_dumps); on the default pcre.jit=1 the path regex on // such a subject can trip the PCRE JIT stack limit, making // preg_replace return NULL. Capping first (UTF-8-safe) keeps the // regex subject tiny (<= ~1027 bytes) so that never happens; we // remember whether we cut, then scrub the small result and re-append // the '...' suffix afterwards. $max_length = 1024; $truncated = false; if (strlen($message) > $max_length) { $message = $this->truncateUtf8($message, $max_length); $truncated = true; } // Redact absolute *nix paths to the literal token ''. Two // alternatives: // 1. multi-segment (/a/b/c) matched anywhere, so a path embedded // mid-token (e.g. "in/home/bob/x") is still redacted; // 2. single-segment (/home, /var) matched ONLY at a token boundary // (start, whitespace or a delimiter -- the negative lookbehind // rejects a preceding word char or '/'). The boundary guard is // what keeps benign mid-word slashes like "and/or" or // "read/write" intact, so we close the bare-directory leak // (/home, /var in open_basedir / quota errors) without // over-redacting ordinary prose. $scrubbed = preg_replace( '#/(?:[^\s/:"\']+/)+[^\s/:"\']+|(?', $message ); if (!is_string($scrubbed)) { // FAIL CLOSED: on any PCRE engine error never emit the raw // message (it could carry an unredacted absolute path); redact // the whole value instead. return ''; } if ($truncated) { $scrubbed .= '...'; } return $scrubbed; } /** * Truncate a string to at most $max BYTES without splitting a UTF-8 * multibyte sequence. The output is always <= $max bytes and never ends * with a partial codepoint, so it is guaranteed valid UTF-8 (assuming * the input prefix was). Pure PHP with no mbstring/iconv dependency, so * it behaves identically on every supported runtime (PHP 5.4+), unlike * mb_strcut which silently degrades to a byte-wise substr when mbstring * is not loaded. * * @param string $s * @param int $max * * @return string */ private function truncateUtf8($s, $max) { if (!is_string($s) || strlen($s) <= $max) { return $s; } $s = substr($s, 0, $max); $len = strlen($s); // Count trailing UTF-8 continuation bytes (10xxxxxx). $cont = 0; while ($cont < $len && (ord($s[$len - 1 - $cont]) & 0xC0) === 0x80) { $cont++; } if ($cont < $len) { $lead = ord($s[$len - 1 - $cont]); $expected = 1; if ($lead >= 0xF0) { $expected = 4; } elseif ($lead >= 0xE0) { $expected = 3; } elseif ($lead >= 0xC0) { $expected = 2; } // If the final multibyte sequence is incomplete, drop it whole. if (($cont + 1) < $expected) { $len = $len - 1 - $cont; } } return substr($s, 0, $len); } /** * @param string|bool $data * * @return string|bool */ private function sendSentryData($data) { if (!function_exists('curl_init') || empty($data)) { return false; } $ch = curl_init(); $sentry_key = '8e6821f19d214977ace88586bc8569fd'; $url = 'https://cl.sentry.cloudlinux.com/api/23/store/'; curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'X-Sentry-Auth: Sentry sentry_version=7,sentry_timestamp=' . time() . ',sentry_client=php-curl/1.0,sentry_key=' . $sentry_key, )); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_TIMEOUT, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); return $response; } /** * @return void */ public function clean() { $this->data = array(); $this->website = ''; $this->user = ''; $this->request_uri = ''; $this->http_code = 0; } /** * Builds the Sentry release string based on X-Ray version. * * @param string|null $xray_version X-Ray version from XRAY_RELEASE constant. * * @return string Sentry release string. * * @since 0.5-23 */ public function release($xray_version) { $version = 'dev'; if (! empty($xray_version)) { preg_match('/\d+\.\d+(\.\d+)?-\d+/', $xray_version, $matches); if (! empty($matches)) { $version = $matches[0]; } } return 'xray-php-profiler@' . $version; } } } PKM ]R%xray-profiler-css-resource-parser.phpnu[removeNoscriptTags($html); if (0 === strlen($html)) { return; } if (!preg_match_all('/]+href=[\'"](?.+?)[\'"][^>]*>/i', $html, $matches)) { return; } if (!is_array($matches) || empty($matches[0])) { return; } foreach ($matches[0] as $key => $link_fragment) { if (preg_match('/rel=["\']preload["\']/i', $link_fragment)) { // skip preloaded links continue; } if (preg_match('/\bdisabled\b/i', $link_fragment)) { // skip disabled links continue; } $link_url = $matches['href'][$key]; $url_path = parse_url($link_url, PHP_URL_PATH); if (!is_string($url_path)) { continue; } $extension = pathinfo($url_path, PATHINFO_EXTENSION); if ('css' !== $extension) { continue; } $this->count++; } } /** * @return int */ public function getCount() { return $this->count; } /** * Removes NOSCRIPT HTML tags from HTML markup. * * @param string $html HTML code. * * @return string HTML code without NOSCRIPT tags. */ public function removeNoscriptTags($html) { return (string) preg_replace('#(.*?)#is', '', $html); } } } PKM ]G~P P %xray-profiler-web-vitals-injector.phpnu[getScriptsContent(); } /** * Getting scripts content. * * @return string */ public function getScriptsContent() { $content = ''; if (!function_exists('xray_get_tracing_task_id')) { return $content; } $tracing_task_id = xray_get_tracing_task_id(); if (!is_string($tracing_task_id)) { return $content; } $processor_path = CL_PHP_XRAY_PROFILER_PATH . '/assets/web.vitals.min.js'; if (is_readable($processor_path)) { $js_app_code = file_get_contents($processor_path); if (is_string($js_app_code)) { $js_app_code = preg_replace( [ '/' . preg_quote('#cl_id#') . '/', '/' . preg_quote('#cl_api_url#') . '/', ], [ $tracing_task_id, $this->getAPIUrl(), ], $js_app_code, 1 ); if (is_string($js_app_code)) { $content = $this->wrapJsCode($js_app_code); } } } return $content; } /** * Wrap the javascript code in the script tag * * @param string $code * * @return string */ public function wrapJsCode($code) { return ''; } /** * Getting API URL * * @return string */ public function getAPIUrl() { $url = 'https://xray.cloudlinux.com/api/xray/web-vitals'; if ( @file_exists('/opt/cloudlinux/staging_mode') || (defined('CL_STAGING_MODE') && CL_STAGING_MODE) ) { $url = 'https://test-api.imunify360.com/api/xray/web-vitals'; } return $url; } } } PKM ]sdMM(xray-profiler-collector-cacheability.phpnu[setConfig(); $this->setVariables(); } private function __clone() { } /** * @return void */ private function setConfig() { if ( isset($GLOBALS['rocket_config_path']) && !empty($GLOBALS['rocket_config_path']) ) { $rocket_config_path = $GLOBALS['rocket_config_path']; } elseif ( defined('WP_ROCKET_CONFIG_PATH') && WP_ROCKET_CONFIG_PATH !== '' ) { $rocket_config_path = WP_ROCKET_CONFIG_PATH; } if ( class_exists('\WP_Rocket\Buffer\Config') && isset($rocket_config_path) ) { $this->config = new \WP_Rocket\Buffer\Config( [ 'config_dir_path' => $rocket_config_path, ] ); } } /** * @return void */ private function setVariables() { $this->cookies = !empty($_COOKIE) && is_array($_COOKIE) ? $_COOKIE : array(); $this->post = !empty($_POST) && is_array($_POST) ? $_POST : array(); $this->get = !empty($_GET) && is_array($_GET) ? $_GET : array(); $this->server = !empty($_SERVER) && is_array($_SERVER) ? $_SERVER : array(); if ($this->post) { $this->post = array_intersect_key( // Limit $this->post to the values we need, to save a bit of memory. $this->post, [ 'wp_customize' => '', ] ); } } /** * @return self */ public static function instance() { if (is_null(self::$instance)) { self::$instance = new self(); self::$instance->clean(); } return self::$instance; } /** * @return array */ public function getData() { $this->collectData(); return $this->data; } /** * Do tests & fill results. * * @return void */ public function collectData() { $results = array(); // Don't process robots.txt && .htaccess files // (it has happened sometimes with weird server configuration). // Don't process disallowed file extensions (like php, xml, xsl). $results['is_disallowed_file'] = $this->isRejectedFile() || $this->isRejectedExtension(); // Don't cache if in admin. $results['is_admin'] = $this->isAdmin(); // Don't cache if in ajax. $results['is_ajax'] = $this->isAjax(); // Don't process the customizer preview. $results['is_preview'] = $this->isCustomizerPreview(); // Don’t process with query strings parameters, // but the processed content is served if the visitor // comes from an RSS feed, a Facebook action or Google Adsense tracking. $results['is_excluded_by_qs'] = !$this->canProcessQueryString(); // Don't process these pages. $results['is_excluded_by_uri'] = !$this->canProcessUri(); // Don't process page with rejected cookies. // Don't process page when mandatory cookies don't exist. $results['is_excluded_by_cookie'] = $this->hasRejectedCookie() || is_array($this->hasMandatoryCookie()); // Don't process page with these user agents. $results['is_excluded_by_ua'] = !$this->canProcessUserAgent(); // Don't process if mobile detection is activated. $results['is_excluded_by_mobile'] = !$this->canProcessMobile(); // Don't process WordPress search page $results['is_search'] = $this->isSearch(); $this->setData($results); } /** * Tell if the current URI corresponds to a file that must not be processed. * * @return bool */ public function isRejectedFile() { $request_uri = $this->getRequestUriBase(); if (!$request_uri) { return false; } $files = [ 'robots.txt', '.htaccess', ]; foreach ($files as $file) { if (false !== strpos($request_uri, '/' . $file)) { return true; } } return false; } /** * Tell if the current URI corresponds to a file extension that must not be processed. * * @return bool */ public function isRejectedExtension() { $request_uri = $this->getRequestUriBase(); if (!$request_uri) { return false; } if (strtolower($request_uri) === '/index.php') { // `index.php` is allowed. return false; } $extension = pathinfo($request_uri, PATHINFO_EXTENSION); $extensions = [ 'php' => 1, 'xml' => 1, 'xsl' => 1, ]; $is_rejected = $extension && isset($extensions[ $extension ]); return $is_rejected; } /** * Tell if we're in the admin area (or ajax) or not. * Test against ajax added in 2e3c0fa74246aa13b36835f132dfd55b90d4bf9e for whatever reason. * * @return bool */ public function isAdmin() { return is_admin(); } /** * Tell if we're in the admin area (or ajax) or not. * Test against ajax added in 2e3c0fa74246aa13b36835f132dfd55b90d4bf9e for whatever reason. * * @return bool */ public function isAjax() { return defined('DOING_AJAX') && DOING_AJAX; } /** * Tell if we're displaying a customizer preview. * Test added in 769c7377e764a6a8decb4015a167b34043b4b462 for whatever reason. * * @return bool */ public function isCustomizerPreview() { return isset($this->post['wp_customize']); } /** * Don't process with query string parameters, some parameters are allowed though. * * @return bool */ public function canProcessQueryString() { $params = $this->getQueryParams(); if (!$params) { return true; } // The page can be processed if at least one of these parameters is present. $allowed_params = [ 'lang' => 1, 's' => 1, 'permalink_name' => 1, 'lp-variation-id' => 1, ]; if (array_intersect_key($params, $allowed_params)) { return true; } // AccelerateWP not installed if (!$this->config) { return false; } // The page can be processed if at least one of these parameters is present. // @phpstan-ignore-next-line $allowed_params = $this->config->get_config('cache_query_strings'); if (!$allowed_params) { // We have query strings but none is in the list set by the user. return false; } $can = (bool) array_intersect_key($params, array_flip($allowed_params)); return $can; } /** * Some URIs set in the plugin settings must not be processed. * * @return bool */ public function canProcessUri() { // AccelerateWP not installed if (!$this->config) { $uri_pattern = '/(?:.+/)?feed(?:/(?:.+/?)?)?$/|/(?:.+/)?embed/|/(index\.php/)?wp\-json(/.*|$)/'; } else { // URIs not to cache. // @phpstan-ignore-next-line $uri_pattern = $this->config->get_config('cache_reject_uri'); } if (!$uri_pattern) { return true; } $can = !preg_match('#^(' . $uri_pattern . ')$#i', $this->getRequestUriBase()); return $can; } /** * Don't process if some cookies are present. * * @return bool|array */ public function hasRejectedCookie() { if (!$this->cookies) { return false; } // AccelerateWP not installed if (!$this->config) { // @phpcs:ignore Generic.Files.LineLength $rejected_cookies = '#wordpress_logged_in_.+|wp-postpass_|wptouch_switch_toggle|comment_author_|comment_author_email_#'; } else { // @phpstan-ignore-next-line $rejected_cookies = $this->config->get_rejected_cookies(); } if (!$rejected_cookies) { return false; } $excluded_cookies = array(); foreach (array_keys($this->cookies) as $cookie_name) { if (preg_match($rejected_cookies, $cookie_name)) { $excluded_cookies[] = $cookie_name; } } if (!empty($excluded_cookies)) { return $excluded_cookies; } return false; } /** * Don't process if some cookies are NOT present. * * @return bool|array */ public function hasMandatoryCookie() { // AccelerateWP not installed if (!$this->config) { return true; } // @phpstan-ignore-next-line $mandatory_cookies = $this->config->get_mandatory_cookies(); if (!$mandatory_cookies) { return true; } // @phpstan-ignore-next-line $missing_cookies = array_flip(explode('|', $this->config->get_config('cache_mandatory_cookies'))); if (!$this->cookies) { return $missing_cookies; } foreach (array_keys($this->cookies) as $cookie_name) { if (preg_match($mandatory_cookies, $cookie_name)) { unset($missing_cookies[ $cookie_name ]); } } if (empty($missing_cookies)) { return true; } return array_flip($missing_cookies); } /** * Don't process if the user agent is in the forbidden list. * * @return bool */ public function canProcessUserAgent() { if (!$this->getServerInput('HTTP_USER_AGENT')) { return true; } // AccelerateWP not installed if (!$this->config) { $rejected_uas = 'facebookexternalhit|WhatsApp'; } else { // @phpstan-ignore-next-line $rejected_uas = $this->config->get_config('cache_reject_ua'); } if (!$rejected_uas) { return true; } $can = !preg_match('#' . $rejected_uas . '#', $this->getServerInput('HTTP_USER_AGENT')); return $can; } /** * Don't process if the user agent is in the forbidden list. * * @return bool */ public function canProcessMobile() { // AccelerateWP not installed if (!$this->config) { return true; } if (!$this->getServerInput('HTTP_USER_AGENT')) { return true; } // @phpstan-ignore-next-line if ($this->config->get_config('cache_mobile')) { return true; } // @phpcs:ignore Generic.Files.LineLength $uas = '2.0\ MMP|240x320|400X240|AvantGo|BlackBerry|Blazer|Cellphone|Danger|DoCoMo|Elaine/3.0|EudoraWeb|Googlebot-Mobile|hiptop|IEMobile|KYOCERA/WX310K|LG/U990|MIDP-2.|MMEF20|MOT-V|NetFront|Newt|Nintendo\ Wii|Nitro|Nokia|Opera\ Mini|Palm|PlayStation\ Portable|portalmmm|Proxinet|ProxiNet|SHARP-TQ-GX10|SHG-i900|Small|SonyEricsson|Symbian\ OS|SymbianOS|TS21i-10|UP.Browser|UP.Link|webOS|Windows\ CE|WinWAP|YahooSeeker/M1A1-R2D2|iPhone|iPod|Android|BlackBerry9530|LG-TU915\ Obigo|LGE\ VX|webOS|Nokia5800'; if (preg_match('#^.*(' . $uas . ').*#i', $this->getServerInput('HTTP_USER_AGENT'))) { return false; } // @phpcs:ignore Generic.Files.LineLength $uas = 'w3c\ |w3c-|acs-|alav|alca|amoi|audi|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-|dang|doco|eric|hipt|htc_|inno|ipaq|ipod|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-|lg/u|maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|palm|pana|pant|phil|play|port|prox|qwap|sage|sams|sany|sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo|teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|wap-|wapa|wapi|wapp|wapr|webc|winw|winw|xda\ |xda-'; if (preg_match('#^(' . $uas . ').*#i', $this->getServerInput('HTTP_USER_AGENT'))) { return false; } return true; } /** * Tell if we're in the WP’s search page. * * @return bool */ public function isSearch() { if (!array_key_exists('s', $this->getQueryParams()) || is_admin()) { return false; } /** * At this point we’re in the WP’s search page. * This filter allows to cache search results. * * @param bool $cache_search True will force caching search results. */ return !apply_filters('rocket_cache_search', false); } /** * Get the request URI. * * @return string */ public function getRawRequestUri() { if ($this->getServerInput('REQUEST_URI') == '') { return ''; } return '/' . ltrim($this->getServerInput('REQUEST_URI'), '/'); } /** * Get the request URI without the query strings. * * @return string */ public function getRequestUriBase() { $request_uri = $this->getRawRequestUri(); if (!$request_uri) { return ''; } $request_uri = explode('?', $request_uri); return reset($request_uri); } /** * Get the request method. * * @return string */ public function getRequestMethod() { return strtoupper($this->getServerInput('REQUEST_METHOD')); } /** * Get the query string as an array. Parameters are sorted and some are removed. * * @return array */ public function getQueryParams() { if (!$this->get) { return array(); } if (!$this->config) { $config_keys = array( 'utm_source' => 0, 'utm_medium' => 1, 'utm_campaign' => 2, 'utm_expid' => 3, 'utm_term' => 4, 'utm_content' => 5, 'mtm_source' => 6, 'mtm_medium' => 7, 'mtm_campaign' => 8, 'mtm_keyword' => 9, 'mtm_cid' => 10, 'mtm_content' => 11, 'pk_source' => 12, 'pk_medium' => 13, 'pk_campaign' => 14, 'pk_keyword' => 15, 'pk_cid' => 16, 'pk_content' => 17, 'fb_action_ids' => 18, 'fb_action_types' => 19, 'fb_source' => 20, 'fbclid' => 21, 'campaignid' => 22, 'adgroupid' => 23, 'adid' => 24, 'gclid' => 25, 'age-verified' => 26, 'ao_noptimize' => 27, 'usqp' => 28, 'cn-reloaded' => 29, '_ga' => 30, 'sscid' => 31, 'gclsrc' => 32, '_gl' => 33, 'mc_cid' => 34, 'mc_eid' => 35, '_bta_tid' => 36, '_bta_c' => 37, 'trk_contact' => 38, 'trk_msg' => 39, 'trk_module' => 40, 'trk_sid' => 41, 'gdfms' => 42, 'gdftrk' => 43, 'gdffi' => 44, '_ke' => 45, 'redirect_log_mongo_id' => 46, 'redirect_mongo_id' => 47, 'sb_referer_host' => 48, 'mkwid' => 49, 'pcrid' => 50, 'ef_id' => 51, 's_kwcid' => 52, 'msclkid' => 53, 'dm_i' => 54, 'epik' => 55, 'pp' => 56, 'gbraid' => 57, 'wbraid' => 58, ); } else { // @phpstan-ignore-next-line $config_keys = $this->config->get_config('cache_ignored_parameters'); } // Remove some parameters. $params = array_diff_key( $this->get, $config_keys ); if ($params) { ksort($params); } return $params; } /** * @param string $name * * @return string */ public function getServerInput($name) { if (!isset($this->server[$name])) { return ''; } return $this->server[$name]; } /** * @return array */ public function getXrayData() { return $this->getData(); } /** * @return $this */ public function clean() { $this->data = array(); return $this; } } } PKM ]Xcxray-profiler-collector.phpnu[data; } /** * @param array $data * * @return void */ public function setData($data) { $this->data = $data; } /** * @return array */ abstract public function getXrayData(); /** * @return self */ abstract public function clean(); } } PKM ]sg g .xray-profiler-collector-blocking-resources.phpnu[data = [ 'css' => 0, ]; } private function __clone() { } /** * @return self */ public static function instance() { if (is_null(self::$instance)) { self::$instance = new self(); self::$instance->clean(); } return self::$instance; } /** * Filter the output buffer contents. * * @param string $buffer Contents of the output buffer. * * @return string */ public function startOutputBuffering($buffer) { if (empty($buffer)) { $this->empty_buffer_occurred++; return $buffer; } $this->scanForBlockingCss($buffer); return $buffer; } /** * Flush the output buffer. * * @return void */ public function stopOutputBuffering() { if (ob_get_contents()) { ob_end_flush(); } } /** * Looks for blocking CSS resources in given HTML code. * * The number of found resources is added to a local counter. * * @param string $html * * @return void */ private function scanForBlockingCss($html) { $parser = new CssResourceParser(); $parser->parse($html); $this->css_resource_count += $parser->getCount(); } /** * @return array */ public function getData() { $value = $this->css_resource_count; if (0 === $value && $this->empty_buffer_occurred > 0) { $value = $this->empty_buffer_occurred * -1; } return [ 'css' => $value, ]; } /** * {@inheritDoc} */ public function getXrayData() { return $this->getData(); } /** * {@inheritDoc} */ public function clean() { $this->css_resource_count = 0; $this->empty_buffer_occurred = 0; $this->data = []; return $this; } } } PKM ]6NN&xray-profiler-collector-shortcodes.phpnu[> */ public $tag_id = array(); /** * @var array> */ private $parsed_handlers = array(); /** * @var self|null */ private static $instance = null; private function __construct() { } private function __clone() { } /** * @return self */ public static function instance() { if (is_null(self::$instance)) { self::$instance = new self(); self::$instance->clean(); } return self::$instance; } /** * @return int */ public function getNextId() { return $this->next_id; } /** * @return int */ public function incrNextId() { return $this->next_id++; } /** * @param string $tag * @param int $id * @return void */ public function setTagId($tag, $id) { $this->tag_id[$tag][] = $id; } /** * @param string $tag * @param bool $replace * @return int */ public function popTagId($tag, $replace = true) { $id = 0; if (array_key_exists($tag, $this->tag_id)) { $ids = $this->tag_id[$tag]; if (!is_null($last = array_pop($ids))) { $id = $last; } if ($replace === true) { $this->tag_id[$tag] = $ids; } } return $id; } /** * @param string $tag * * @return array|null */ public function getParsedHandlers($tag) { if (array_key_exists($tag, $this->parsed_handlers)) { return $this->parsed_handlers[$tag]; } return null; } /** * @param string $tag * @param array $data * * @return void */ public function setParsedHandlers($tag, $data) { $this->parsed_handlers[$tag] = $data; } /** * @param string $tag * @param int $id * * @return array|null * [ * 'shortcode_id' => (int) * 'handler' => (string) * 'name' => (string) * 'plugin' => (string) * 'duration' => (int) * 'attrs_json' => (string) * 'timer_start' => (float) *] */ public function getShortcode($tag, $id) { $data = $this->getData(); if (array_key_exists($tag, $data) && array_key_exists($id, $data[$tag])) { return $data[$tag][$id]; } return null; } /** * @param string $tag * @param int $id * @param array $data * * @return void */ public function setShortcode($tag, $id, $data) { $shortcodes = $this->getData(); if (!array_key_exists($tag, $shortcodes)) { $shortcodes[$tag] = array(); } $shortcodes[$tag][$id] = $data; $this->setData($shortcodes); } /** * @param array|string $attr * * @return array> */ public function prepareAttributes($attr) { $attrs = array(); if (is_array($attr) && !empty($attr)) { foreach ($attr as $key => $val) { $attrs[] = array( 'type' => 'key', 'key' => $key, 'val' => $this->redactAttributeValue($key, $val), ); } } elseif (is_string($attr) && !empty($attr)) { $attrs[] = array( 'type' => 'string', 'key' => '', 'val' => $this->redactAttributeValue('', $attr), ); } return $attrs; } /** * Benign attribute names that are NEVER redacted, regardless of any * secret-looking substring they may contain (e.g. "author" contains * "auth"). Checked first so the secret-token substring match below can * be unanchored without re-introducing collisions on presentational * attributes. * * @var array */ private static $benign_attr_keys = array( 'author', 'id', 'ids', 'src', 'url', 'href', 'link', 'class', 'align', 'size', 'width', 'height', 'title', 'alt', 'name', 'slug', 'type', 'color', 'style', 'target', 'rel', 'caption', 'label', 'tag', 'category', 'date', // Common presentational keys that collide with a secret-token // substring (keyword/keywords -> "key") -- exempt so the substring // match below does not over-redact ordinary shortcode telemetry. 'keyword', 'keywords', ); /** * Secret-looking key tokens. Matched as case-insensitive SUBSTRINGS of * the (non-allowlisted) attribute name, so glued/camelCase secret keys * with no separators (secretkey, accesskey, apitoken, authtoken, * passphrase, passkey, userpass, consumerkey, encryptionkey, hmacsig, * SecretAccessKey, clientsecret, privatekey, ...) are caught alongside * separated variants (api_key, auth_token). Substring matching is * deliberate: under-redacting a glued secret name (data exposure) is * worse than over-redacting a rare presentational name. The benign * allowlist above exempts the common presentational keys that would * otherwise collide (author, keyword, ...). * * @var array */ private static $secret_key_tokens = array( 'secret', 'password', 'passwd', 'pass', 'token', 'apikey', 'api_key', 'api', 'key', 'auth', 'credential', 'bearer', 'dsn', 'privatekey', 'accesskey', 'signature', 'sig', ); /** * Redact secret-looking shortcode attribute values before they are * serialized into attrs_json and exported off-box to telemetry. * Attribute names and overall structure are preserved; only values * flagged by a non-allowlisted secret-looking key name (substring * match), an email address, or a credentialed URL are replaced with a * placeholder. Allowlisted presentational keys (id/src/url/author/...) * are always kept. Retained values are capped at 256 chars as a * backstop; non-scalars are left to the JSON encoder. * * @param int|string $key * @param mixed $val * * @return mixed */ private function redactAttributeValue($key, $val) { if (!is_string($val)) { return $val; } $key_str = is_string($key) ? $key : ''; $key_lc = strtolower($key_str); // Benign-key allowlist: presentational attributes are never // redacted, which resolves the author/auth substring collision // without anchoring the secret-token match below. $is_benign = $key_lc !== '' && in_array($key_lc, self::$benign_attr_keys, true); if (!$is_benign && $key_lc !== '') { // Secret-looking key names: substring match so glued/camelCase // keys (secretkey, accesskey, apitoken, passphrase, passkey, // userpass, SecretAccessKey, ...) are caught, not just separated // variants. The benign allowlist above exempts the common // presentational keys that would otherwise collide (keyword/...). foreach (self::$secret_key_tokens as $token) { if (strpos($key_lc, $token) !== false) { return '[REDACTED]'; } } } // Value-shape rules apply even to benign-but-non-allowlisted keys, // catching secrets hiding under an innocuous attribute name. // Email address. if (preg_match('/[^\s@]+@[^\s@]+\.[^\s@]+/', $val)) { return '[REDACTED]'; } // URL embedding credentials (scheme://user:pass@host). if (preg_match('#[a-z][a-z0-9+.-]*://[^/\s:@]+:[^/\s@]+@#i', $val)) { return '[REDACTED]'; } // No bare value-length/entropy redaction: it masks public asset // paths, slug ids and long URLs. Glued secret keys are already // covered by the substring key match above, so a length heuristic // would only re-introduce over-redaction of public URLs/paths. // Backstop: cap retained value length to limit accidental leakage. if (strlen($val) > 256) { return substr($val, 0, 256) . '...[truncated]'; } return $val; } /** * @param string $tag * @param object|callable $fn * * @return array */ public function parseHandler($tag, $fn) { if ($cache = $this->getParsedHandlers($tag)) { return $cache; } $handler = ''; $plugin = ''; if ( class_exists('ReflectionClass') && class_exists('ReflectionObject') && class_exists('ReflectionFunction') ) { try { $parse = array( 'path' => '', 'handler' => '', ); if (is_array($fn)) { // Class::method $parse = $this->parseHandlerArray($fn); } elseif (is_object($fn)) { // Object/Closure/Invoke $parse = $this->parseHandlerObject($fn); } elseif (is_string($fn)) { // Function string $parse = $this->parseHandlerString($fn); } $path = $parse['path']; $handler = $parse['handler']; if (!empty($path)) { $plugin = $this->pluginOrThemeName($path); } if (empty($handler)) { xray_profiler_log( E_USER_NOTICE, "Can't parse handler: " . print_r($fn, true), __FILE__, __LINE__ ); } } catch (Exception $e) { $message = "Catch Reflection error Exception: " . $e->getMessage() . ', with handler: ' . print_r($fn, true); xray_profiler_log(E_USER_WARNING, $message, $e->getFile(), $e->getLine()); } } else { xray_profiler_log(E_USER_NOTICE, "Can't parse handler, Reflection doesn't exists", __FILE__, __LINE__); } $result = array( 'handler' => $handler, 'plugin' => $plugin, ); $this->setParsedHandlers($tag, $result); return $result; } /** * @param array $fn * * @return array * @throws ReflectionException */ public function parseHandlerArray($fn) { $path = ''; $handler = ''; $fn = array_values($fn); if (!empty($fn)) { if (is_object($fn[0])) { $parse = $this->parseHandlerObject($fn[0]); } elseif (is_string($fn[0])) { $parse = $this->parseHandlerString($fn[0]); } if (!empty($parse['handler'])) { $path = $parse['path']; $handler = $parse['handler']; if (array_key_exists(1, $fn) && is_string($fn[1])) { $handler .= '::' . $fn[1]; } } } return array( 'path' => $path, 'handler' => $handler, ); } /** * @param object $fn * * @return array * @throws ReflectionException */ public function parseHandlerObject($fn) { $ref = new ReflectionObject($fn); $name = $ref->getName(); $path = ''; $handler = ''; if (!empty($name)) { $handler = $name; $file = $ref->getFileName(); if (!empty($file)) { $path = $file; } if ($name == 'Closure' && $fn instanceof Closure) { $ref = new ReflectionFunction($fn); $name = $ref->getName(); if (!empty($name)) { $file = $ref->getFileName(); if (!empty($file)) { $path = $file; } } } } return array( 'path' => $path, 'handler' => $handler, ); } /** * @param string $fn * * @return array */ public function parseHandlerString($fn) { $path = ''; $handler = ''; $class = $fn; $ref = null; if (strpos($fn, '::') !== false) { $parts = explode('::', $fn); $class = array_shift($parts); } if (class_exists($class)) { $ref = new ReflectionClass($class); } elseif (function_exists($class)) { $ref = new ReflectionFunction($class); } if ($ref) { $handler = $fn; $name = $ref->getName(); if (! empty($name)) { $file = $ref->getFileName(); if (! empty($file)) { $path = $file; } } } return array( 'path' => $path, 'handler' => $handler, ); } /** * @param string $path * * @return string */ public function pluginOrThemeName($path) { $name = ''; $pattern = '/wp-content\/(mu-plugins\/|plugins\/|themes\/)(.*?)(\/|.php)/is'; preg_match($pattern, $path, $matches); if (!empty($matches) && array_key_exists(2, $matches)) { if (strpos($matches[1], 'themes') === 0) { $name = 'Theme: '; } $name .= $matches[2]; } return $name; } /** * @param false|string $return * @param string $tag * @param array|string $attr * @param array $m * * @return false|string */ public function preDoShortcodeTagEarly($return, $tag, $attr, $m) { $this->incrNextId(); $id = $this->getNextId(); $this->setTagId($tag, $id); $attrs = $this->prepareAttributes($attr); $parseHandler = $this->parseHandler($tag, $GLOBALS['shortcode_tags'][$tag]); $handler = $parseHandler['handler']; $plugin = $parseHandler['plugin']; if (empty($attrs) || !($attrs_json = json_encode($attrs))) { $attrs_json = 'null'; } $data = [ 'shortcode_id' => $id, 'handler' => empty($handler) ? 'Unknown' : $handler, 'name' => $tag, 'plugin' => empty($plugin) ? 'Unknown' : $plugin, 'duration' => 0, 'attrs_json' => $attrs_json, 'timer_start' => microtime(true), ]; $this->setShortcode($tag, $id, $data); return $return; } /** * @param false|string $return * @param string $tag * @param array|string $attr * @param array $m * * @return false|string */ public function preDoShortcodeTagLate($return, $tag, $attr, $m) { if ($return !== false) { $this->popTagId($tag); } return $return; } /** * @param false|string $output * @param string $tag * @param array|string $attr * @param array $m * * @return false|string */ public function doShortcodeTagLate($output, $tag, $attr, $m) { $timer_end = microtime(true); $id = $this->popTagId($tag); $shortcode = $this->getShortcode($tag, $id); if (empty($shortcode)) { xray_profiler_log( E_USER_NOTICE, 'Can\'t find shortcode ' . $tag . ' id: ' . $id . ' in ' . __METHOD__, __FILE__, __LINE__ ); } else { $timer_start = floatval($shortcode['timer_start']); $diff = $timer_end - $timer_start; $duration = number_format($diff * 1000000, 0, '', ''); $shortcode['duration'] = $duration; unset($shortcode['timer_start']); $tag = $shortcode['name'] . ''; $this->setShortcode($tag, $id, $shortcode); } return $output; } /** * @return array */ public function getXrayData() { $shortcodes = $this->data; $items = array(); foreach ($shortcodes as $iterations) { $items = array_merge($items, $iterations); } usort($items, function ($a, $b) { if ($a['duration'] == $b['duration']) { return 0; } return ($a['duration'] < $b['duration']) ? 1 : -1; }); foreach ($items as &$item) { if (array_key_exists('timer_start', $item)) { unset($item['timer_start']); } } return array_slice($items, 0, 20); } /** * @return $this */ public function clean() { $this->data = array(); $this->next_id = 0; $this->tag_id = array(); $this->parsed_handlers = array(); return $this; } } } PKO]/ Dates.pynu[PKO]ΎMMVec.pynu[PKO]j%&&H$Dbm.pynu[PKO]E *Range.pyonu[PKO] :Dbm.pycnu[PKO](  DREADMEnu[PKO]u+&& 'GComplex.pynu[PKO]1 1 CnRev.pycnu[PKO]nL6 6 yRange.pynu[PKO]FI&'&' Complex.pyonu[PKO]E zRange.pycnu[PKO]:6  Vec.pyonu[PKO]FI&'&' Complex.pycnu[PKO]cAC<5(5( Jbitvec.pyonu[PKO](( bitvec.pynu[PKO]cAC<5(5( Abitvec.pycnu[PKO]w `jDates.pycnu[PKO]w ?Dates.pyonu[PKO]:6  Vec.pycnu[PKO]IYRev.pynu[PKO] Dbm.pyonu[PKO]1 1 Rev.pyonu[PKM ]ధoHoH xray-profiler-log.phpnu[PKM ]R%xray-profiler-css-resource-parser.phpnu[PKM ]G~P P %xray-profiler-web-vitals-injector.phpnu[PKM ]sdMM(l+xray-profiler-collector-cacheability.phpnu[PKM ]Xcyxray-profiler-collector.phpnu[PKM ]sg g .r}xray-profiler-collector-blocking-resources.phpnu[PKM ]6NN&7xray-profiler-collector-shortcodes.phpnu[PKb