rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
if validate(None, self, None, o, None): | if validate(None, self, None, o): | def filtered_manage_options(self, REQUEST=None): |
if type(path) is type(''): path = path.split( '/') | if isinstance(path, StringType) or isinstance(path, UnicodeType): path = path.split('/') | def setVirtualRoot(self, path, hard=0): """ Treat the current publishing object as a VirtualRoot """ other = self.other if type(path) is type(''): path = path.split( '/') self._script[:] = map(quote, filter(None, path)) del self._steps[:] parents = other['PARENTS'] if hard: del parents[:-1] other['VirtualRootPhysicalPath'] = parents[-1].getPhysicalPath() self._resetURLS() |
print path | def getPhysicalPath(self): '''Returns a path (an immutable sequence of strings) that can be used to access this object again later, for example in a copy/paste operation. getPhysicalRoot() and getPhysicalPath() are designed to operate together. ''' path = (self.id,) p = getattr(self,'aq_inner', None) if p is not None: path = p.aq_parent.getPhysicalPath() + path print path return path |
|
except AttributeError, KeyError: k = None | except (AttributeError, KeyError): k = None | def sort(sequence, sort=(), _=None, mapping=0): """ - sequence is a sequence of objects to be sorted - sort is a sequence of tuples (key,func,direction) that define the sort order: - key is the name of an attribute to sort the objects by - func is the name of a comparison function. This parameter is optional allowed values: - "cmp" -- the standard comparison function (default) - "nocase" -- case-insensitive comparison - "strcoll" or "locale" -- locale-aware string comparison - "strcoll_nocase" or "locale_nocase" -- locale-aware case-insensitive string comparison - "xxx" -- a user-defined comparison function - direction -- defines the sort direction for the key (optional). (allowed values: "asc" (default) , "desc") """ need_sortfunc = 0 if sort: for s in sort: if len(s) > 1: # extended sort if there is reference to... # ...comparison function or sort order, even if they are "cmp" and "asc" need_sortfunc = 1 break sortfields = sort # multi sort = key1,key2 multsort = len(sortfields) > 1 # flag: is multiple sort if need_sortfunc: # prepare the list of functions and sort order multipliers sf_list = make_sortfunctions(sortfields, _) # clean the mess a bit if multsort: # More than one sort key. sortfields = map(lambda x: x[0], sf_list) else: sort = sf_list[0][0] elif sort: if multsort: # More than one sort key. sortfields = map(lambda x: x[0], sort) else: sort = sort[0][0] isort=not sort s=[] for client in sequence: k = None if type(client)==TupleType and len(client)==2: if isort: k=client[0] v=client[1] else: if isort: k=client v=client if sort: if multsort: # More than one sort key. k = [] for sk in sortfields: try: if mapping: akey = v[sk] else: akey = getattr(v, sk) except (AttributeError, KeyError): akey = None if not basic_type(akey): try: akey = akey() except: pass k.append(akey) else: # One sort key. try: if mapping: k = v[sort] else: k = getattr(v, sort) except AttributeError, KeyError: k = None if not basic_type(type(k)): try: k = k() except: pass s.append((k,client)) if need_sortfunc: by = SortBy(multsort, sf_list) s.sort(by) else: s.sort() sequence=[] for k, client in s: sequence.append(client) return sequence |
'extra' -- a record-style object that keeps additional index-related parameters 'caller' -- reference to the calling object (usually | 'extra' -- a mapping object that keeps additional index-related parameters - subitem 'indexed_attrs' can be string with comma separated attribute names or a list 'caller' -- reference to the calling object (usually | def __init__( self, id, ignore_ex=None, call_methods=None, extra=None, caller=None): """Create an unindex |
try: self.indexed_attrs = extra.indexed_attrs.split(',') self.indexed_attrs = [ attr.strip() for attr in self.indexed_attrs if attr ] if len(self.indexed_attrs) == 0: self.indexed_attrs = [ self.id ] except: self.indexed_attrs = [ self.id ] | try: ia=extra['indexed_attrs'] if type(ia) in StringTypes: self.indexed_attrs = ia.split(',') else: self.indexed_attrs = list(ia) self.indexed_attrs = [ attr.strip() for attr in self.indexed_attrs if attr ] or [self.id] except: self.indexed_attrs = [ self.id ] | def __init__( self, id, ignore_ex=None, call_methods=None, extra=None, caller=None): """Create an unindex |
self._setupBindings(bindmap) self._makeFunction() | self.ZBindings_edit(bindmap) else: self._makeFunction() | def write(self, text): """ Change the Script by parsing a read()-style source text. """ self._validateProxy() mdata = self._metadata_map() bindmap = self.getBindingAssignments().getAssignedNames() bup = 0 |
if validate is None: return getattr(inst, name) | if validate is None: return v | def careful_getattr(md, inst, name): if name[:1]!='_': validate=md.validate if validate is None: return getattr(inst, name) if hasattr(inst,'aq_acquire'): return inst.aq_acquire(name, validate, md) v=getattr(inst, name) if validate(inst,inst,name,v,md): return v raise ValidationError, name |
v=getattr(inst, name) | def careful_getattr(md, inst, name): if name[:1]!='_': validate=md.validate if validate is None: return getattr(inst, name) if hasattr(inst,'aq_acquire'): return inst.aq_acquire(name, validate, md) v=getattr(inst, name) if validate(inst,inst,name,v,md): return v raise ValidationError, name |
|
try: if name[:1]!='_': validate=md.validate if validate is None: return hasattr(inst, name) if hasattr(inst,'aq_acquire'): inst.aq_acquire(name, validate, md) return 1 v=getattr(inst, name) if validate(inst,inst,name,v,md): return 1 except: pass | v=getattr(inst, name, _marker) if v is not _marker: try: if name[:1]!='_': validate=md.validate if validate is None: return 1 if hasattr(inst,'aq_acquire'): inst.aq_acquire(name, validate, md) return 1 if validate(inst,inst,name,v,md): return 1 except: pass | def careful_hasattr(md, inst, name): try: if name[:1]!='_': validate=md.validate if validate is None: return hasattr(inst, name) if hasattr(inst,'aq_acquire'): inst.aq_acquire(name, validate, md) return 1 v=getattr(inst, name) if validate(inst,inst,name,v,md): return 1 except: pass return 0 |
addentry(word,srckey,(freq, positions)) | addentry(word,srckey,(freq, tuple(positions))) | def index(self, isrc, srckey): '''\ index(src, srckey) |
if (key[0] == '"'): | if ((key is not None) and (key[0] == '"')): | def __getitem__(self, key): '''\ Get the ResultList objects for the inverted key, key. The key may be a regular expression, in which case a regular expression match is done. The key may be a string, in which case an case-insensitive match is done. ''' index = self._index_object synstop = self.synstop List = self.list_class |
import jim; jim.debug() | def open_bobobase(): # Open the application database Bobobase=Globals.Bobobase=Globals.PickleDictionary(Globals.BobobaseName) product_dir=os.path.join(SOFTWARE_HOME,'lib/python/Products') __traceback_info__=sys.path try: app=Bobobase['Application'] except KeyError: app=Application() app._init() Bobobase['Application']=app get_transaction().commit() # Backward compatibility if not hasattr(app, 'Control_Panel'): cpl=ApplicationManager() cpl._init() app._setObject('Control_Panel', cpl) get_transaction().commit() if not hasattr(app, 'standard_error_message'): import Document Document.manage_addDocument( app, 'standard_error_message', 'Standard Error Message', _standard_error_msg) get_transaction().commit() import jim; jim.debug() install_products(app) get_transaction().commit() return Bobobase |
|
return self._unindex(id) | return self._unindex[id] | def keyForDocument(self, id): return self._unindex(id) |
return absattr(self.v_self().title_or_id()) | return absattr(xml_escape(self.v_self().title_or_id())) | def dav__displayname(self): return absattr(self.v_self().title_or_id()) |
r=LazyCat(map(lambda i: i[1], r), len(r)) | r=map(lambda i: i[1], r) r=LazyCat(r, reduce(lambda x,y: x+len(y), r, 0)) | def searchResults(self, REQUEST=None, used=None, **kw): # Get search arguments: if REQUEST is None and not kw: try: REQUEST=self.REQUEST except AttributeError: pass if kw: if REQUEST: m=MultiMapping() m.push(REQUEST) m.push(kw) kw=m elif REQUEST: kw=REQUEST |
if self.cache_time_ > 0 and self.self.max_cache_ > 0: | if self.cache_time_ > 0 and self.max_cache_ > 0: | def __call__(self, REQUEST=None, __ick__=None, src__=0, **kw): """Call the database method |
def _print_traceback(self, msg, err, test, errlist): if self.showAll or self.dots or self._progress: self.stream.writeln("\n") | def _handle_problem(self, err, test, errlist): if self._debug: raise err[0], err[1], err[2] if errlist is self.errors: prefix = 'Error' else: prefix = 'Failure' tb = "".join(traceback.format_exception(*err)) if self._progress: self.stream.writeln("\r") self.stream.writeln("%s in test %s" % (prefix,test)) self.stream.writeln(tb) | def _print_traceback(self, msg, err, test, errlist): if self.showAll or self.dots or self._progress: self.stream.writeln("\n") self._lastWidth = 0 |
tb = "".join(traceback.format_exception(*err)) self.stream.writeln(msg) self.stream.writeln(tb) errlist.append((test, tb)) | elif self.showAll: self._lastWidth = 0 self.stream.writeln(prefix.upper()) elif self.dots: self.stream.write(prefix[0]) if not self._progress: errlist.append((test, tb)) | def _print_traceback(self, msg, err, test, errlist): if self.showAll or self.dots or self._progress: self.stream.writeln("\n") self._lastWidth = 0 |
if self._progress: self.stream.write("\r") if self._debug: raise err[0], err[1], err[2] self._print_traceback("Error in test %s" % test, err, test, self.errors) | self._handle_problem(err, test, self.errors) | def addError(self, test, err): if self._progress: self.stream.write("\r") if self._debug: raise err[0], err[1], err[2] self._print_traceback("Error in test %s" % test, err, test, self.errors) |
if self._progress: self.stream.write("\r") if self._debug: raise err[0], err[1], err[2] self._print_traceback("Failure in test %s" % test, err, test, self.failures) | self._handle_problem(err, test, self.failures) | def addFailure(self, test, err): if self._progress: self.stream.write("\r") if self._debug: raise err[0], err[1], err[2] self._print_traceback("Failure in test %s" % test, err, test, self.failures) |
f=f.read() | title, head, body = parse_html(f) | def upload_html(object, f): dir, name = os.path.split(f) f=open(f) # There is a Document bugs that causes file uploads to fail. # Waaa. This will be fixed in 1.10.2. f=f.read() if old: call(object.manage_addDocument, id=name, file=f) else: call(object.manage_addDTMLDocument, id=name, file=f) |
call(object.manage_addDocument, id=name, file=f) | call(object.manage_addDocument, id=name, file=body) | def upload_html(object, f): dir, name = os.path.split(f) f=open(f) # There is a Document bugs that causes file uploads to fail. # Waaa. This will be fixed in 1.10.2. f=f.read() if old: call(object.manage_addDocument, id=name, file=f) else: call(object.manage_addDTMLDocument, id=name, file=f) |
call(object.manage_addDTMLDocument, id=name, file=f) | call(object.manage_addDTMLDocument, id=name, title=title, file=body) if head: object=object.__class__(object.url+'/'+name, username=object.username, password=object.password) call(object.manage_addProperty, id="loadsite-head", type="text", value=head) | def upload_html(object, f): dir, name = os.path.split(f) f=open(f) # There is a Document bugs that causes file uploads to fail. # Waaa. This will be fixed in 1.10.2. f=f.read() if old: call(object.manage_addDocument, id=name, file=f) else: call(object.manage_addDTMLDocument, id=name, file=f) |
os.system("xterm -e %s &" % cmd) | os.system("xterm -e sh -c '%s | less' &" % cmd) | def specialcommand(self, line, results, first): assert line.startswith("/") line = line[1:] if not line: n = first else: try: n = int(line) - 1 except: print "Huh?" return if n < 0 or n >= len(results): print "Out of range" return docid, score = results[n] path = self.docpaths[docid] i = path.rfind("/") assert i > 0 folder = path[:i] n = path[i+1:] cmd = "show +%s %s" % (folder, n) if os.getenv("DISPLAY"): os.system("xterm -e %s &" % cmd) else: os.system(cmd) |
qw = max(1, self.index.query_weight(text)) factor = 100.0 / qw / 1024 | qw = self.index.query_weight(text) | def formatresults(self, text, results, maxlines=MAXLINES, lo=0, hi=sys.maxint): stop = self.stopdict.has_key words = [w for w in re.findall(r"\w+\*?", text.lower()) if not stop(w)] pattern = r"\b(" + "|".join(words) + r")\b" pattern = pattern.replace("*", ".*") # glob -> re syntax prog = re.compile(pattern, re.IGNORECASE) print '='*70 rank = lo qw = max(1, self.index.query_weight(text)) factor = 100.0 / qw / 1024 for docid, score in results[lo:hi]: rank += 1 path = self.docpaths[docid] score = min(100, int(score * factor)) print "Rank: %d Score: %d%% File: %s" % (rank, score, path) path = os.path.join(self.mh.getpath(), path) fp = open(path) msg = mhlib.Message("<folder>", 0, fp) for header in "From", "To", "Cc", "Bcc", "Subject", "Date": h = msg.getheader(header) if h: print "%-8s %s" % (header+":", h) text = self.getmessagetext(msg) if text: print nleft = maxlines for part in text: for line in part.splitlines(): if prog.search(line): print line nleft -= 1 if nleft <= 0: break if nleft <= 0: break print '-'*70 |
score = min(100, int(score * factor)) | score = 100.0*score/qw | def formatresults(self, text, results, maxlines=MAXLINES, lo=0, hi=sys.maxint): stop = self.stopdict.has_key words = [w for w in re.findall(r"\w+\*?", text.lower()) if not stop(w)] pattern = r"\b(" + "|".join(words) + r")\b" pattern = pattern.replace("*", ".*") # glob -> re syntax prog = re.compile(pattern, re.IGNORECASE) print '='*70 rank = lo qw = max(1, self.index.query_weight(text)) factor = 100.0 / qw / 1024 for docid, score in results[lo:hi]: rank += 1 path = self.docpaths[docid] score = min(100, int(score * factor)) print "Rank: %d Score: %d%% File: %s" % (rank, score, path) path = os.path.join(self.mh.getpath(), path) fp = open(path) msg = mhlib.Message("<folder>", 0, fp) for header in "From", "To", "Cc", "Bcc", "Subject", "Date": h = msg.getheader(header) if h: print "%-8s %s" % (header+":", h) text = self.getmessagetext(msg) if text: print nleft = maxlines for part in text: for line in part.splitlines(): if prog.search(line): print line nleft -= 1 if nleft <= 0: break if nleft <= 0: break print '-'*70 |
ob=aq_base(self._getCopy(parent)) | self.manage_changeOwnershipType(explicit=1) self._notifyOfCopyTo(parent, op=1) ob = aq_base(self._getCopy(parent)) | def MOVE(self, REQUEST, RESPONSE): """Move a resource to a new location. Though we may later try to make a move appear seamless across namespaces (e.g. from Zope to Apache), MOVE is currently only supported within the Zope namespace.""" self.dav__init(REQUEST, RESPONSE) self.dav__validate(self, 'DELETE', REQUEST) if not hasattr(aq_base(self), 'cb_isMoveable') or \ not self.cb_isMoveable(): raise MethodNotAllowed, 'This object may not be moved.' |
App.Product.initializeProduct(product_name, package_dir, app) | App.Product.initializeProduct(product, product_name, package_dir, app) | def install_products(app): # Install a list of products into the basic folder class, so # that all folders know about top-level objects, aka products path_join=os.path.join product_dir=path_join(SOFTWARE_HOME,'Products') isdir=os.path.isdir exists=os.path.exists DictType=type({}) from Folder import Folder folder_permissions={} for p in Folder.__ac_permissions__: permission, names = p[:2] folder_permissions[permission]=names meta_types=list(Folder.dynamic_meta_types) product_names=os.listdir(product_dir) product_names.sort() global_dict=globals() silly=('__doc__',) for product_name in product_names: package_dir=path_join(product_dir, product_name) if not isdir(package_dir): continue if not exists(path_join(package_dir, '__init__.py')): if not exists(path_join(package_dir, '__init__.pyc')): continue product=__import__("Products.%s" % product_name, global_dict, global_dict, silly) permissions={} new_permissions={} for permission, names in pgetattr(product, '__ac_permissions__', ()): if names: for name in names: permissions[name]=permission elif not folder_permissions.has_key(permission): new_permissions[permission]=() for meta_type in pgetattr(product, 'meta_types', ()): if product_name=='OFSP': meta_types.insert(0,meta_type) else: meta_types.append(meta_type) name=meta_type['name'] for name,method in pgetattr(product, 'methods', {}).items(): if not hasattr(Folder, name): setattr(Folder, name, method) if name[-9:]=='__roles__': continue # Just setting roles if (permissions.has_key(name) and not folder_permissions.has_key(permissions[name])): permission=permissions[name] if new_permissions.has_key(permission): new_permissions[permission].append(name) else: new_permissions[permission]=[name] if new_permissions: new_permissions=new_permissions.items() for permission, names in new_permissions: folder_permissions[permission]=names new_permissions.sort() Folder.__dict__['__ac_permissions__']=tuple( list(Folder.__ac_permissions__)+new_permissions) misc_=pgetattr(product, 'misc_', {}) if type(misc_) is DictType: misc_=Misc_(product_name, misc_) Application.misc_.__dict__[product_name]=misc_ # Set up dynamic project information. App.Product.initializeProduct(product_name, package_dir, app) Folder.dynamic_meta_types=tuple(meta_types) Globals.default__class_init__(Folder) |
def lcd(e): _k1_='\357\261\390\247\357\362\306\216\226' _k2_='\157\161\090\147\157\122\106\016\126' rot=rotor.newrotor(_k2_, 13) dat=rot.decrypt(e) del rot dat=list(dat) dat.reverse() dat=join(dat,'') dat=marshal.loads(dat) if type(dat) != type([]): rot=rotor.newrotor(_k1_, 13) dat=rot.decrypt(e) del rot dat=list(dat) dat.reverse() dat=join(dat,'') dat=marshal.loads(dat) if type(dat) != type([]): return None return dat | def install_products(app): # Install a list of products into the basic folder class, so # that all folders know about top-level objects, aka products path_join=os.path.join product_dir=path_join(SOFTWARE_HOME,'Products') isdir=os.path.isdir exists=os.path.exists DictType=type({}) from Folder import Folder folder_permissions={} for p in Folder.__ac_permissions__: permission, names = p[:2] folder_permissions[permission]=names meta_types=list(Folder.dynamic_meta_types) product_names=os.listdir(product_dir) product_names.sort() global_dict=globals() silly=('__doc__',) for product_name in product_names: package_dir=path_join(product_dir, product_name) if not isdir(package_dir): continue if not exists(path_join(package_dir, '__init__.py')): if not exists(path_join(package_dir, '__init__.pyc')): continue product=__import__("Products.%s" % product_name, global_dict, global_dict, silly) permissions={} new_permissions={} for permission, names in pgetattr(product, '__ac_permissions__', ()): if names: for name in names: permissions[name]=permission elif not folder_permissions.has_key(permission): new_permissions[permission]=() for meta_type in pgetattr(product, 'meta_types', ()): if product_name=='OFSP': meta_types.insert(0,meta_type) else: meta_types.append(meta_type) name=meta_type['name'] for name,method in pgetattr(product, 'methods', {}).items(): if not hasattr(Folder, name): setattr(Folder, name, method) if name[-9:]=='__roles__': continue # Just setting roles if (permissions.has_key(name) and not folder_permissions.has_key(permissions[name])): permission=permissions[name] if new_permissions.has_key(permission): new_permissions[permission].append(name) else: new_permissions[permission]=[name] if new_permissions: new_permissions=new_permissions.items() for permission, names in new_permissions: folder_permissions[permission]=names new_permissions.sort() Folder.__dict__['__ac_permissions__']=tuple( list(Folder.__ac_permissions__)+new_permissions) misc_=pgetattr(product, 'misc_', {}) if type(misc_) is DictType: misc_=Misc_(product_name, misc_) Application.misc_.__dict__[product_name]=misc_ # Set up dynamic project information. App.Product.initializeProduct(product_name, package_dir, app) Folder.dynamic_meta_types=tuple(meta_types) Globals.default__class_init__(Folder) |
|
{'label':'View', 'action':'view_image_or_file'}, | {'label':'View', 'action':''}, | def manage_addFile(self,id,file,title='',precondition='',REQUEST=None): """Add a new File object. Creates a new file object 'id' with the contents of 'file'""" self._setObject(id, File(id,title,file,precondition)) if REQUEST is not None: return self.manage_main(self,REQUEST) |
parmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)=\([^\0- =\"]+\)' '\([\0- ]*[;,]\)?[\0- ]*\)' ), | def parse_cookie(text, result=None, parmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)=\([^\0- =\"]+\)' '\([\0- ]*[;,]\)?[\0- ]*\)' ), qparmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)="\([^"]*\)\"' '\([\0- ]*[;,]\)?[\0- ]*\)' ), ): if result is None: result={} if parmre.match(text) >= 0: name=parmre.group(2) value=parmre.group(3) l=len(parmre.group(1)) elif qparmre.match(text) >= 0: name=qparmre.group(2) value=qparmre.group(3) l=len(qparmre.group(1)) else: if not text or not strip(text): return result raise "InvalidParameter", text result[name]=value return apply(parse_cookie,(text[l:],result)) |
|
if parmre.match(text) >= 0: | if qparmre.match(text) >= 0: name=qparmre.group(2) value=qparmre.group(3) l=len(qparmre.group(1)) elif parmre.match(text) >= 0: | def parse_cookie(text, result=None, parmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)=\([^\0- =\"]+\)' '\([\0- ]*[;,]\)?[\0- ]*\)' ), qparmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)="\([^"]*\)\"' '\([\0- ]*[;,]\)?[\0- ]*\)' ), ): if result is None: result={} if parmre.match(text) >= 0: name=parmre.group(2) value=parmre.group(3) l=len(parmre.group(1)) elif qparmre.match(text) >= 0: name=qparmre.group(2) value=qparmre.group(3) l=len(qparmre.group(1)) else: if not text or not strip(text): return result raise "InvalidParameter", text result[name]=value return apply(parse_cookie,(text[l:],result)) |
elif qparmre.match(text) >= 0: name=qparmre.group(2) value=qparmre.group(3) l=len(qparmre.group(1)) | def parse_cookie(text, result=None, parmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)=\([^\0- =\"]+\)' '\([\0- ]*[;,]\)?[\0- ]*\)' ), qparmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)="\([^"]*\)\"' '\([\0- ]*[;,]\)?[\0- ]*\)' ), ): if result is None: result={} if parmre.match(text) >= 0: name=parmre.group(2) value=parmre.group(3) l=len(parmre.group(1)) elif qparmre.match(text) >= 0: name=qparmre.group(2) value=qparmre.group(3) l=len(qparmre.group(1)) else: if not text or not strip(text): return result raise "InvalidParameter", text result[name]=value return apply(parse_cookie,(text[l:],result)) |
|
def convertSet(s, IITreeSet=IITreeSet): | def convertSet(s, IITreeSet=IITreeSet, IntType=type(0), type=type, len=len, doneTypes = (IntType, IITreeSet)): if type(s) in doneTypes: return s | def convertSet(s, IITreeSet=IITreeSet): if len(s) == 1: try: return s[0] # convert to int except: pass # This is just an optimization. return IITreeSet(s) |
self.__len__=BTrees.Length.Length() | self.__len__=BTrees.Length.Length(len(_index)) | def convertSet(s, IITreeSet=IITreeSet): if len(s) == 1: try: return s[0] # convert to int except: pass # This is just an optimization. return IITreeSet(s) |
auth_user=REQUEST.get('AUTHENTICATED_USER', None) if auth_user is not None: verify_watermark(auth_user) | if REQUEST.has_key('AUTHENTICATED_USER'): verify_watermark(REQUEST['AUTHENTICATED_USER']) | def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw): """Render the document given a client object, REQUEST mapping, Response, and key word arguments.""" kw['document_id'] =self.id kw['document_title']=self.title |
query += '\nDBConnId: %s' % self.connection_hook | query = query + ('\nDBConnId: %s' % self.connection_hook, ) | def _cached_result(self, DB__, query): pure_query = query # we need to munge the incoming query key in the cache # so that the same request to a different db is returned query += '\nDBConnId: %s' % self.connection_hook # Try to fetch from cache if hasattr(self,'_v_cache'): cache=self._v_cache else: cache=self._v_cache={}, Bucket() cache, tcache = cache max_cache=self.max_cache_ now=time() t=now-self.cache_time_ if len(cache) > max_cache / 2: keys=tcache.keys() keys.reverse() while keys and (len(keys) > max_cache or keys[-1] < t): key=keys[-1] q=tcache[key] del tcache[key] if int(cache[q][0]) == key: del cache[q] del keys[-1] |
self.REQUEST.RESPONSE.setHeader('Content-Length', self.size) | RESPONSE.setHeader('Content-Length', self.size) | def manage_FTPget(self): """Return body for ftp.""" if self.ZCacheable_isCachingEnabled(): result = self.ZCacheable_get(default=None) if result is not None: # We will always get None from RAMCacheManager but we will get # something implementing the IStreamIterator interface # from FileCacheManager. # the content-length is required here by HTTPResponse, even # though FTP doesn't use it. self.REQUEST.RESPONSE.setHeader('Content-Length', self.size) return result return str(self.data) |
return str(self.data) | data = self.data if type(data) is type(''): RESPONSE.setBase(None) return data while data is not None: RESPONSE.write(data.data) data = data.next return '' | def manage_FTPget(self): """Return body for ftp.""" if self.ZCacheable_isCachingEnabled(): result = self.ZCacheable_get(default=None) if result is not None: # We will always get None from RAMCacheManager but we will get # something implementing the IStreamIterator interface # from FileCacheManager. # the content-length is required here by HTTPResponse, even # though FTP doesn't use it. self.REQUEST.RESPONSE.setHeader('Content-Length', self.size) return result return str(self.data) |
if stid <> tid: | if stid == tid: data = self._pickles.get(oid+stid, txn=txn) assert data is not None self._update(deltas, data, 1) else: | def _docommit(self, txn, tid): self._pending.put(self._serial, COMMIT, txn) deltas = {} co = cs = None try: co = self._oids.cursor(txn=txn) cs = self._serials.cursor(txn=txn) rec = co.first() while rec: oid = rec[0] rec = co.next() # Remove from the serials table all entries with key oid where # the serial is not tid. These are the old revisions of the # object. At the same time, we want to collect the oids of # the objects referred to by this revision's pickle, so that # later we can decref those reference counts. srec = cs.set(oid) while srec: soid, stid = srec if soid <> oid: break if stid <> tid: cs.delete() data = self._pickles.get(oid+stid, txn=txn) assert data is not None self._update(deltas, data, -1) self._pickles.delete(oid+stid, txn=txn) srec = cs.next_dup() # Now add incref deltas for all objects referenced by the new # revision of this object. data = self._pickles.get(oid+tid, txn=txn) assert data is not None self._update(deltas, data, 1) finally: # There's a small window of opportunity for leaking a cursor here, # if co.close() were to fail. In practice this shouldn't happen. if co: co.close() if cs: cs.close() # We're done with this table self._oids.truncate(txn) self._pending.truncate(txn) # Now, to finish up, we need apply the refcount deltas to the # refcounts table, and do recursive collection of all refcount == 0 # objects. while deltas: deltas = self._update_refcounts(deltas, txn) |
self._pending.truncate(txn) | def _docommit(self, txn, tid): self._pending.put(self._serial, COMMIT, txn) deltas = {} co = cs = None try: co = self._oids.cursor(txn=txn) cs = self._serials.cursor(txn=txn) rec = co.first() while rec: oid = rec[0] rec = co.next() # Remove from the serials table all entries with key oid where # the serial is not tid. These are the old revisions of the # object. At the same time, we want to collect the oids of # the objects referred to by this revision's pickle, so that # later we can decref those reference counts. srec = cs.set(oid) while srec: soid, stid = srec if soid <> oid: break if stid <> tid: cs.delete() data = self._pickles.get(oid+stid, txn=txn) assert data is not None self._update(deltas, data, -1) self._pickles.delete(oid+stid, txn=txn) srec = cs.next_dup() # Now add incref deltas for all objects referenced by the new # revision of this object. data = self._pickles.get(oid+tid, txn=txn) assert data is not None self._update(deltas, data, 1) finally: # There's a small window of opportunity for leaking a cursor here, # if co.close() were to fail. In practice this shouldn't happen. if co: co.close() if cs: cs.close() # We're done with this table self._oids.truncate(txn) self._pending.truncate(txn) # Now, to finish up, we need apply the refcount deltas to the # refcounts table, and do recursive collection of all refcount == 0 # objects. while deltas: deltas = self._update_refcounts(deltas, txn) |
|
def setBase(self,base): | def setBase(self,base, URL): | def setBase(self,base): |
def insertBase(self): | def host(self,base): return base[:string.find(base,'/',string.find(base,'//'))] def insertBase(self, base_re=regex.compile('\(<base[\0- ]+\([^>]+\)>\)', regex.casefold) ): | def insertBase(self): |
e=end_of_header_re.search(body) if e >= 0 and base_re.search(body) < 0: self.body=('%s\t<base href="%s">\n%s' % (body[:e],self.base,body[e:])) | if body: e=end_of_header_re.search(body) if e >= 0: b=base_re.search(body) if b < 0: self.body=('%s\t<base href="%s">\n%s' % (body[:e],self.base,body[e:])) elif self.URL: href=base_re.group(2) base='' if href[:1]=='/': base=self.host(self.base)+href elif href[:1]=='.': base=self.URL while href[:1]=='.': if href[:2]=='./' or href=='.': href=href[2:] elif href[:3]=='../' or href=='..': href=href[3:] base=base[:string.rfind(base,'/')] else: break if base: self.body=("%s<base %s>%s" % (body[:b],base, body[b+len(base_re.group(1)):])) | def insertBase(self): |
(regex.compile('"'), '"e;'))): | (regex.compile('"'), '"'))): | def quoteHTML(self,text, |
def format_exception(self,etype,value,tb,limit=None): import traceback result=['Traceback (innermost last):'] if limit is None: if hasattr(sys, 'tracebacklimit'): limit = sys.tracebacklimit n = 0 while tb is not None and (limit is None or n < limit): f = tb.tb_frame lineno = tb.tb_lineno co = f.f_code filename = co.co_filename name = co.co_name locals=f.f_locals result.append(' File %s, line %d, in %s' % (filename,lineno,name)) try: result.append(' (Object: %s)' % locals[co.co_varnames[0]].__name__) except: pass try: result.append(' (Info: %s)' % str(locals['__traceback_info__'])) except: pass tb = tb.tb_next n = n+1 result.append(string.joinfields( traceback.format_exception_only(etype, value), ' ')) return result | def quoteHTML(self,text, |
|
import traceback tb=string.joinfields(traceback.format_exception(t,v,tb,200),'\n') | tb=self.format_exception(t,v,tb,200) tb=string.joinfields(tb,'\n') | def _traceback(self,t,v,tb): |
def exception(self): | def exception(self, fatal=0): | def exception(self): |
heading=('<tr>\n%s\n</tr>' % | heading=('<tr>\n%s </tr>' % | def custom_default_report(id, result, action='', no_table=0, goofy=regex.compile('[^a-zA-Z0-9_]').search ): columns=result._searchable_result_columns() __traceback_info__=columns heading=('<tr>\n%s\n</tr>' % string.joinfields( map(lambda c: ' <th>%s</th>\n' % nicify(c['name']), columns), '' ) ) if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ', ' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '' if no_table: tr='<p>', '</p>' else: tr, _tr = '<tr>', '</tr>' row=[] for c in columns: n=c['name'] if goofy(n) >= 0: n='expr="_vars[\'%s]"' % (`'"'+n`[2:]) row.append(' %s<!--#var %s%s-->%s\n' % (td,n,c['type']!='s' and ' null=""' or '',_td)) row=('%s\n%s\n%s' % (tr,string.joinfields(row,delim), _tr)) return custom_default_report_src( id=id,heading=heading,row=row,action=action,no_table=no_table) |
if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ', ' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '' if no_table: tr='<p>', '</p>' else: tr, _tr = '<tr>', '</tr>' | if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ',\n' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '\n' | def custom_default_report(id, result, action='', no_table=0, goofy=regex.compile('[^a-zA-Z0-9_]').search ): columns=result._searchable_result_columns() __traceback_info__=columns heading=('<tr>\n%s\n</tr>' % string.joinfields( map(lambda c: ' <th>%s</th>\n' % nicify(c['name']), columns), '' ) ) if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ', ' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '' if no_table: tr='<p>', '</p>' else: tr, _tr = '<tr>', '</tr>' row=[] for c in columns: n=c['name'] if goofy(n) >= 0: n='expr="_vars[\'%s]"' % (`'"'+n`[2:]) row.append(' %s<!--#var %s%s-->%s\n' % (td,n,c['type']!='s' and ' null=""' or '',_td)) row=('%s\n%s\n%s' % (tr,string.joinfields(row,delim), _tr)) return custom_default_report_src( id=id,heading=heading,row=row,action=action,no_table=no_table) |
if isinstance(s, HTML): | try: _isinstance=isinstance(s, HTML) except TypeError: _isinstance=None if _isinstance: | def raise_standardErrorMessage( self, client=None, REQUEST={}, error_type=None, error_value=None, tb=None, error_tb=None, error_message='', tagSearch=re.compile(r'[a-zA-Z]>').search): |
if xdelta and width==None: width = int(width) * xdelta if ydelta and height==None: height = int(height) * ydelta | if xdelta and width != None: width = str(int(width) * xdelta) if ydelta and height != None: height = str(int(height) * ydelta) | def tag(self, height=None, width=None, alt=None, scale=0, xscale=0, yscale=0, **args): """ Generate an HTML IMG tag for this image, with customization. Arguments to self.tag() can be any valid attributes of an IMG tag. 'src' will always be an absolute pathname, to prevent redundant downloading of images. Defaults are applied intelligently for 'height', 'width', and 'alt'. If specified, the 'scale', 'xscale', and 'yscale' keyword arguments will be used to automatically adjust the output height and width values of the image tag. """ if height is None: height=self.height if width is None: width=self.width |
t = type(value) if not isinstance(t, StringType): if not isinstance(t, TupleType): | if not isinstance(value, StringType): if not isinstance(value, TupleType): | def __init__(self, value=0): t = type(value) if not isinstance(t, StringType): if not isinstance(t, TupleType): if value == 0: value = time.time() value = time.localtime(value) value = time.strftime("%Y%m%dT%H:%M:%S", value) self.value = value |
self.col = self.col + align | self.col = align | def do_startTag(self, name, attrList, end=">"): if not attrList: s = "<%s%s" % (name, end) self.do_rawtextOffset(s, len(s)) return _len = len self._stream_write("<" + name) self.col = self.col + _len(name) + 1 align = self.col + 1 + _len(name) if align >= self.wrap/2: align = 4 # Avoid a narrow column far to the right for item in attrList: if _len(item) == 2: name, value = item else: ok, name, value = self.attrAction(item) if not ok: continue if value is None: s = name else: s = "%s=%s" % (name, quote(value)) if (self.wrap and self.col >= align and self.col + 1 + _len(s) > self.wrap): self._stream_write("\n" + " "*align) self.col = self.col + align else: s = " " + s self._stream_write(s) if "\n" in s: self.col = _len(s) - (rfind(s, "\n") + 1) else: self.col = self.col + _len(s) self._stream_write(end) self.col = self.col + _len(end) |
try: query=apply(self.template, (p,), argdata) | try: try: query=apply(self.template, (p,), argdata) except TypeError, msg: msg = str(msg) if find(msg,'client'): raise NameError("'client' may not be used as an " + "argument name in this context") else: raise | def __call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw): """Call the database method |
return ', '.join(users, ', ') | return ', '.join(users) | def creator(self): """Return a sequence of user names who have the local Owner role on an object. The name creator is used for this method to conform to Dublin Core.""" users=[] for user, roles in self.get_local_roles(): if 'Owner' in roles: users.append(user) return ', '.join(users, ', ') |
REQURE_PYEXPAT = 1 | REQUIRE_PYEXPAT = 1 | def main(): # below assumes this script is in the BASE_DIR/inst directory global PREFIX BASE_DIR=os.path.abspath(os.path.dirname(os.path.dirname(sys.argv[0]))) BUILD_BASE=os.path.join(os.getcwd(), 'build-base') PYTHON=sys.executable MAKEFILE=open(os.path.join(BASE_DIR, 'inst', IN_MAKEFILE)).read() REQUIRE_LF_ENABLED = 1 REQUIRE_ZLIB = 1 REQURE_PYEXPAT = 1 INSTALL_FLAGS = '' DISTUTILS_OPTS = '' try: longopts = ['help', 'ignore-largefile', 'ignore-zlib', 'ignore-pyexpat', 'prefix=', 'build-base=', 'optimize', 'no-compile', 'quiet'] opts, args = getopt.getopt(sys.argv[1:], 'h', longopts) except getopt.GetoptError, v: print v usage() sys.exit(1) for o, a in opts: if o in ('-h', '--help'): usage() sys.exit() if o == '--prefix': PREFIX=os.path.abspath(os.path.expanduser(a)) if o == '--ignore-largefile': REQUIRE_LF_ENABLED=0 if o == '--ignore-zlib': REQUIRE_ZLIB=0 if o == '--ignore-pyexpat': REQUIRE_PYEXPAT=0 if o == '--optimize': INSTALL_FLAGS = '--optimize=1 --no-compile' if o == '--no-compile': INSTALL_FLAGS = '--no-compile' if o == '--build-base': BUILD_BASE = a if o == '--quiet': DISTUTILS_OPTS = '-q' global QUIET QUIET = 1 if REQUIRE_LF_ENABLED: test_largefile() if REQUIRE_ZLIB: test_zlib() if REQUIRE_PYEXPAT: test_pyexpat() out(' - Zope top-level binary directory will be %s.' % PREFIX) if INSTALL_FLAGS: out(' - Distutils install flags will be "%s"' % INSTALL_FLAGS) idata = { '<<PYTHON>>':PYTHON, '<<PREFIX>>':PREFIX, '<<BASE_DIR>>':BASE_DIR, '<<BUILD_BASE>>':BUILD_BASE, '<<INSTALL_FLAGS>>':INSTALL_FLAGS, '<<ZOPE_MAJOR_VERSION>>':versions.ZOPE_MAJOR_VERSION, '<<ZOPE_MINOR_VERSION>>':versions.ZOPE_MINOR_VERSION, '<<VERSION_RELEASE_TAG>>':versions.VERSION_RELEASE_TAG, '<<DISTUTILS_OPTS>>':DISTUTILS_OPTS, } for k,v in idata.items(): MAKEFILE = MAKEFILE.replace(k, v) f = open(os.path.join(os.getcwd(), 'makefile'), 'w') f.write(MAKEFILE) out(' - Makefile written.') out('') out(' Next, run %s.' % MAKE_COMMAND) out('') |
if type(body) == InstanceType: | if type(body) == types.InstanceType: | def setBody(self, body, title='', is_error=0, bogus_str_search=None): if isinstance(body, xmlrpclib.Fault): # Convert Fault object to XML-RPC response. body=xmlrpclib.dumps(body, methodresponse=1) else: if type(body) == InstanceType: # Avoid disclosing private members. Private members are # by convention named with a leading underscore char. orig = body.__dict__ dict = {} for key in orig.keys(): if key[:1] != '_': dict[key] = orig[key] body = dict |
parent=request['PARENTS'][0] | parents=request.get('PARENTS', []) if not parents: parent=self.aq_parent else: parent=parents[0] | def validate(self,request,auth='',roles=None): parent=request['PARENTS'][0] |
setDefaultRoles__roles__=ACCESS_PRIVATE def setDefaultRoles(self, permission_name, roles): | setPermissionDefault__roles__=ACCESS_PRIVATE def setPermissionDefault(self, permission_name, roles): | def declareObjectProtected(self, permission_name): """Declare the object to be associated with a permission.""" self._setaccess((), permission_name) |
method when executed. | method when executed. Raises a ValueError if the instance does not have a method with the specified name. | def __init__(self, methodName='runTest'): """Create an instance of the class that will use the named test method when executed. """ try: self.__testMethod = getattr(self,methodName) except AttributeError: raise ValueError,"no such test method: %s" % methodName |
raise ValueError,"no such test method: %s" % methodName | raise ValueError, "no such test method in %s: %s" % \ (self.__class__, methodName) | def __init__(self, methodName='runTest'): """Create an instance of the class that will use the named test method when executed. """ try: self.__testMethod = getattr(self,methodName) except AttributeError: raise ValueError,"no such test method: %s" % methodName |
return "%s.%s" % (self.__class__, self.__testMethod.__name__) | return "%s (%s)" % (self.__testMethod.__name__, self.__class__) | def __str__(self): return "%s.%s" % (self.__class__, self.__testMethod.__name__) |
raise AssertionError, (hasattr(excClass,'__name__') and excClass.__name__ or str(excClass)) | if hasattr(excClass,'__name__'): excName = excClass.__name__ else: excName = str(excClass) raise AssertionError, excName | def assertRaises(self, excClass, callableObj, *args, **kwargs): """Assert that an exception of class excClass is thrown by callableObj when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. """ try: apply(callableObj, args, kwargs) except excClass: return else: raise AssertionError, (hasattr(excClass,'__name__') and excClass.__name__ or str(excClass)) |
def __str__(self): | def __repr__(self): | def __str__(self): return "<%s tests=%s>" % (self.__class__, self._tests) |
__repr__ = __str__ | __str__ = __repr__ | def __str__(self): return "<%s tests=%s>" % (self.__class__, self._tests) |
class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): TestCase.__init__(self) self.__setUpFunc = setUp self.__tearDownFunc = tearDown self.__testFunc = testFunc self.__description = description def setUp(self): if self.__setUpFunc is not None: self.__setUpFunc() def tearDown(self): if self.__tearDownFunc is not None: self.__tearDownFunc() def runTest(self): self.__testFunc() def id(self): return self.__testFunc.__name__ def __str__(self): return "%s (%s)" % (self.__class__, self.__testFunc.__name__) def __repr__(self): return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) def shortDescription(self): if self.__description is not None: return self.__description doc = self.__testFunc.__doc__ return doc and string.strip(string.split(doc, "\n")[0]) or None def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) def createTestInstance(name, module=None): """Finds tests by their name, optionally only within the given module. Return the newly-constructed test, ready to run. If the name contains a ':' then the portion of the name after the colon is used to find a specific test case within the test case class named before the colon. Examples: findTest('examples.listtests.suite') -- returns result of calling 'suite' findTest('examples.listtests.ListTestCase:checkAppend') -- returns result of calling ListTestCase('checkAppend') findTest('examples.listtests.ListTestCase:check-') -- returns result of calling makeSuite(ListTestCase, prefix="check") """ spec = string.split(name, ':') if len(spec) > 2: raise ValueError, "illegal test name: %s" % name if len(spec) == 1: testName = spec[0] caseName = None else: testName, caseName = spec parts = string.split(testName, '.') if module is None: if len(parts) < 2: raise ValueError, "incomplete test name: %s" % name constructor = __import__(string.join(parts[:-1],'.')) parts = parts[1:] else: constructor = module for part in parts: constructor = getattr(constructor, part) if not callable(constructor): raise ValueError, "%s is not a callable object" % constructor if caseName: if caseName[-1] == '-': prefix = caseName[:-1] if not prefix: raise ValueError, "prefix too short: %s" % name test = makeSuite(constructor, prefix=prefix) else: test = constructor(caseName) else: test = constructor() if not hasattr(test,"countTestCases"): raise TypeError, \ "object %s found with spec %s is not a test" % (test, name) return test | def __call__(self, result): for test in self._tests: if result.shouldStop: break test(result) return result |
|
self.write(os.linesep) | self.write(self.linesep) | def writeln(self, *args): if args: apply(self.write, args) self.write(os.linesep) |
class _TextTestResult(TestResult): | class _JUnitTextTestResult(TestResult): | def writeln(self, *args): if args: apply(self.write, args) self.write(os.linesep) |
self.printNumberedErrors('error',self.errors) | self.printNumberedErrors("error",self.errors) | def printErrors(self): self.printNumberedErrors('error',self.errors) |
self.printNumberedErrors('failure',self.failures) | self.printNumberedErrors("failure",self.failures) | def printFailures(self): self.printNumberedErrors('failure',self.failures) |
class TextTestRunner: | class JUnitTextTestRunner: | def printResult(self): self.printHeader() self.printErrors() self.printFailures() |
Uses TextTestResult. | The display format approximates that of JUnit's 'textui' test runner. This test runner may be removed in a future version of PyUnit. | def printResult(self): self.printHeader() self.printErrors() self.printFailures() |
result = _TextTestResult(self.stream) | "Run the given test case or test suite." result = _JUnitTextTestResult(self.stream) | def run(self, test): """Run the given test case or test suite. """ result = _TextTestResult(self.stream) startTime = time.time() test(result) stopTime = time.time() self.stream.writeln() self.stream.writeln("Time: %.3fs" % float(stopTime - startTime)) result.printResult() return result |
def createTestInstance(name): """Looks up and calls a callable object by its string name, which should include its module name, e.g. 'widgettests.WidgetTestSuite'. """ if '.' not in name: raise ValueError,"Incomplete name; expected 'package.suiteobj'" dotPos = string.rfind(name,'.') last = name[dotPos+1:] if not len(last): raise ValueError,"Malformed classname" pkg = name[:dotPos] try: testCreator = getattr(__import__(pkg,globals(),locals(),[last]),last) except AttributeError, e: raise ImportError, \ "No object '%s' found in package '%s'" % (last,pkg) if not callable(testCreator): raise ValueError, "'%s' is not callable" % name try: test = testCreator() except: raise TypeError, \ "Error making a test instance by calling '%s'" % testCreator if not hasattr(test,"countTestCases"): raise TypeError, \ "Calling '%s' returned '%s', which is not a test case or suite" \ % (name,test) return test def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) | class _VerboseTextTestResult(TestResult): """A test result class that can print formatted text results to a stream. Used by VerboseTextTestRunner. """ def __init__(self, stream, descriptions): TestResult.__init__(self) self.stream = stream self.lastFailure = None self.descriptions = descriptions def startTest(self, test): TestResult.startTest(self, test) if self.descriptions: self.stream.write(test.shortDescription() or str(test)) else: self.stream.write(str(test)) self.stream.write(" ... ") def stopTest(self, test): TestResult.stopTest(self, test) if self.lastFailure is not test: self.stream.writeln("ok") def addError(self, test, err): TestResult.addError(self, test, err) self._printError("ERROR", test, err) self.lastFailure = test if err[0] is KeyboardInterrupt: self.shouldStop = 1 def addFailure(self, test, err): TestResult.addFailure(self, test, err) self._printError("FAIL", test, err) self.lastFailure = test def _printError(self, flavour, test, err): errLines = [] separator1 = "\t" + '=' * 70 separator2 = "\t" + '-' * 70 if not self.lastFailure is test: self.stream.writeln() self.stream.writeln(separator1) self.stream.writeln("\t%s" % flavour) self.stream.writeln(separator2) for line in apply(traceback.format_exception, err): for l in string.split(line,"\n")[:-1]: self.stream.writeln("\t%s" % l) self.stream.writeln(separator1) class VerboseTextTestRunner: """A test runner class that displays results in textual form. It prints out the names of tests as they are run, errors as they occur, and a summary of the results at the end of the test run. """ def __init__(self, stream=sys.stderr, descriptions=1): self.stream = _WritelnDecorator(stream) self.descriptions = descriptions def run(self, test): "Run the given test case or test suite." result = _VerboseTextTestResult(self.stream, self.descriptions) startTime = time.time() test(result) stopTime = time.time() timeTaken = float(stopTime - startTime) self.stream.writeln("-" * 78) run = result.testsRun self.stream.writeln("Ran %d test%s in %.3fs" % (run, run > 1 and "s" or "", timeTaken)) self.stream.writeln() if not result.wasSuccessful(): self.stream.write("FAILED (") failed, errored = map(len, (result.failures, result.errors)) if failed: self.stream.write("failures=%d" % failed) if errored: if failed: self.stream.write(", ") self.stream.write("errors=%d" % errored) self.stream.writeln(")") else: self.stream.writeln("OK") return result TextTestRunner = VerboseTextTestRunner class TestProgram: """A command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. """ USAGE = """\ Usage: %(progName)s [-h|--help] [test[:(casename|prefix-)]] [...] Examples: %(progName)s - run default set of tests %(progName)s MyTestSuite - run suite 'MyTestSuite' %(progName)s MyTestCase:checkSomething - run MyTestCase.checkSomething %(progName)s MyTestCase:check- - run all 'check*' test methods in MyTestCase """ def __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=None): if type(module) == type(''): self.module = __import__(module) for part in string.split(module,'.')[1:]: self.module = getattr(self.module, part) else: self.module = module if argv is None: argv = sys.argv self.defaultTest = defaultTest self.testRunner = testRunner self.progName = os.path.basename(argv[0]) self.parseArgs(argv) self.createTests() self.runTests() def usageExit(self, msg=None): if msg: print msg print self.USAGE % self.__dict__ sys.exit(2) def parseArgs(self, argv): import getopt try: options, args = getopt.getopt(argv[1:], 'hH', ['help']) opts = {} for opt, value in options: if opt in ('-h','-H','--help'): self.usageExit() if len(args) == 0 and self.defaultTest is None: raise getopt.error, "No default test is defined." if len(args) > 0: self.testNames = args else: self.testNames = (self.defaultTest,) except getopt.error, msg: self.usageExit(msg) def createTests(self): tests = [] for testName in self.testNames: tests.append(createTestInstance(testName, self.module)) self.test = TestSuite(tests) def runTests(self): if self.testRunner is None: self.testRunner = TextTestRunner() result = self.testRunner.run(self.test) sys.exit(not result.wasSuccessful()) main = TestProgram | def createTestInstance(name): """Looks up and calls a callable object by its string name, which should include its module name, e.g. 'widgettests.WidgetTestSuite'. """ if '.' not in name: raise ValueError,"Incomplete name; expected 'package.suiteobj'" dotPos = string.rfind(name,'.') last = name[dotPos+1:] if not len(last): raise ValueError,"Malformed classname" pkg = name[:dotPos] try: testCreator = getattr(__import__(pkg,globals(),locals(),[last]),last) except AttributeError, e: raise ImportError, \ "No object '%s' found in package '%s'" % (last,pkg) if not callable(testCreator): raise ValueError, "'%s' is not callable" % name try: test = testCreator() except: raise TypeError, \ "Error making a test instance by calling '%s'" % testCreator if not hasattr(test,"countTestCases"): raise TypeError, \ "Calling '%s' returned '%s', which is not a test case or suite" \ % (name,test) return test |
if len(sys.argv) == 2 and sys.argv[1] not in ('-help','-h','--help'): testClass = createTestInstance(sys.argv[1]) result = TextTestRunner().run(testClass) if result.wasSuccessful(): sys.exit(0) else: sys.exit(1) else: print "usage:", sys.argv[0], "package1.YourTestSuite" sys.exit(2) | main(module=None) | def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) |
def cache_detail(self): try: db=self._p_jar.db() except: detail={} for oid, ob in Globals.Bobobase._jar.cache.items(): if hasattr(ob, '__class__'): ob=ob.__class__ decor='' else: decor=' class' c="%s.%s%s" % (ob.__module__ or '', ob.__name__, decor) if detail.has_key(c): detail[c]=detail[c]+1 else: detail[c]=1 detail=detail.items() else: detail=db.cacheDetail() detail=map(lambda d: (("%s.%s" % (d[0].__module__, d[0].__name__)), d[1]), detail.items()) detail.sort() return detail def cache_extreme_detail(self): try: db=self._p_jar.db() except: detail=[] rc=sys.getrefcount db=Globals.Bobobase._jar.db for oid, ob in Globals.Bobobase._jar.cache.items(): id=oid if hasattr(ob, '__class__'): if hasattr(ob,'__dict__'): d=ob.__dict__ if d.has_key('id'): id="%s (%s)" % (oid, d['id']) elif d.has_key('__name__'): id="%s (%s)" % (oid, d['__name__']) ob=ob.__class__ decor='' else: decor=' class' detail.append({ 'oid': id, 'klass': "%s.%s%s" % (ob.__module__, ob.__name__, decor), 'rc': rc(ob)-4, 'references': db.objectReferencesIn(oid), }) | def cache_detail(self, REQUEST=None): """ Returns the name of the classes of the objects in the cache and the number of objects in the cache for each class. """ db=self._p_jar.db() detail = db.cacheDetail() if REQUEST is not None: REQUEST.RESPONSE.setHeader('Content-Type', 'text/plain') return string.join(map(lambda (name, count): '%6d %s' % (count, name), detail), '\n') else: | def cache_detail(self): try: db=self._p_jar.db() except: # BoboPOS2 detail={} for oid, ob in Globals.Bobobase._jar.cache.items(): if hasattr(ob, '__class__'): ob=ob.__class__ decor='' else: decor=' class' c="%s.%s%s" % (ob.__module__ or '', ob.__name__, decor) if detail.has_key(c): detail[c]=detail[c]+1 else: detail[c]=1 detail=detail.items() else: # ZODB 3 detail=db.cacheDetail() detail=map(lambda d: (("%s.%s" % (d[0].__module__, d[0].__name__)), d[1]), detail.items()) |
else: return db.cacheExtremeDetail() | def cache_extreme_detail(self, REQUEST=None): """ Returns information about each object in the cache. """ db=self._p_jar.db() detail = db.cacheExtremeDetail() if REQUEST is not None: lst = map(lambda dict: ((dict['conn_no'], dict['oid']), dict), detail) lst.sort() res = [ ' 'and class.', ' for sortkey, dict in lst: id = dict.get('id', None) if id: idinfo = ' (%s)' % id else: idinfo = '' s = dict['state'] if s == 0: state = 'L' elif s == 1: state = 'C' else: state = 'G' res.append('%d %-34s %6d %s %s%s' % ( dict['conn_no'], `dict['oid']`, dict['rc'], state, dict['klass'], idinfo)) REQUEST.RESPONSE.setHeader('Content-Type', 'text/plain') return string.join(res, '\n') else: return detail | def cache_extreme_detail(self): try: db=self._p_jar.db() except: # BoboPOS2 detail=[] rc=sys.getrefcount db=Globals.Bobobase._jar.db for oid, ob in Globals.Bobobase._jar.cache.items(): id=oid |
getattr(self, id).write(file) | self._getOb(id).write(file) | def manage_addPythonScript(self, id, REQUEST=None): """Add a Python script to a folder. """ id = str(id) id = self._setObject(id, PythonScript(id)) if REQUEST is not None: file = REQUEST.form.get('file', None) if file: if type(file) is not type(''): file = file.read() getattr(self, id).write(file) try: u = self.DestinationURL() except: u = REQUEST['URL1'] REQUEST.RESPONSE.redirect('%s/%s/manage_main' % (u, quote(id))) return '' |
content_type='application/octet-stream' | type='application/octet-stream' | def PUT(self, REQUEST, RESPONSE): """Adds a document, image or file to the folder when a PUT request is received.""" name=self.id type=REQUEST.get_header('content-type', None) body=REQUEST.get('BODY', '') if type is None: type, enc=mimetypes.guess_type(name) if type is None: if content_types.find_binary(body) >= 0: content_type='application/octet-stream' else: type=content_types.text_type(body) type=lower(type) if type in ('text/html', 'text/xml', 'text/plain'): self.__parent__.manage_addDTMLDocument(name, '', body) elif type[:6]=='image/': ob=Image(name, '', body, content_type=type) self.__parent__._setObject(name, ob) else: ob=File(name, '', body, content_type=type) self.__parent__._setObject(name, ob) RESPONSE.setStatus(201) RESPONSE.setBody('') return RESPONSE |
self.extends.append(names[2], url) | self.extends.append((names[2], url)) | def __init__(self, klass): # Creates an APIDoc instance given a python class. # the class describes the API; it contains # methods, arguments and doc strings. # # The name of the API is deduced from the name # of the class. # # The base APIs are deduced from the __extends__ # attribute. self.name=klass.__name__ self.doc=trim_doc_string(klass.__doc__) if hasattr(klass,'__extends__'): self.extends=[] for base in klass.__extends__: names=string.split(base, '.') url="%s/Help/%s.py#%s" % (names[0], names[1], names[2]) self.extends.append(names[2], url) # Get info on methods and attributes, ignore special items self.attributes=[] self.methods=[] for k,v in klass.__dict__.items(): if k not in ('__extends__', '__doc__'): if type(v)==types.FunctionType: self.methods.append(MethodDoc(v)) else: self.attributes.append(AttributeDoc(k, v)) |
r=db().undoLog() | r=db().undoLog(first_transaction, last_transaction) | def undoable_transactions(self, AUTHENTICATION_PATH=None, first_transaction=None, last_transaction=None, PrincipiaUndoBatchSize=None): |
for d in r: r['time']=DateTime(r['time']) | for d in r: d['time']=DateTime(d['time']) | def undoable_transactions(self, AUTHENTICATION_PATH=None, first_transaction=None, last_transaction=None, PrincipiaUndoBatchSize=None): |
self.__attrs=attrs | def __init__(self, name, bases=(), attrs=None, __doc__=None): """Create a new interface """ for b in bases: if not isinstance(b, Interface): raise TypeError, 'Expected base interfaces' self.__bases__=bases self.__name__=name |
|
if __doc__ is not None: self.__doc__=__doc__ | if __doc__ is not None: self.__doc__=__doc__ else: self.__doc__ = "" | def __init__(self, name, bases=(), attrs=None, __doc__=None): """Create a new interface """ for b in bases: if not isinstance(b, Interface): raise TypeError, 'Expected base interfaces' self.__bases__=bases self.__name__=name |
for k, v in self.__dict__.items(): | for k, v in self.__attrs.items(): | def __d(self, dict): |
dtpref_cols='50', dtpref_rows='20'): | dtpref_cols='100%', dtpref_rows='20'): | def pt_changePrefs(self, REQUEST, height=None, width=None, dtpref_cols='50', dtpref_rows='20'): """Change editing preferences.""" # The <textarea> can have dimensions expressed in percentages; # strip the percent sign so int() below won't fail if dtpref_cols[-1:] == "%": dtpref_cols = dtpref_cols[:-1] or '50' if dtpref_rows[-1:] == "%": dtpref_rows = dtpref_rows[:-1] or '20' szchh = {'Taller': 1, 'Shorter': -1, None: 0} szchw = {'Wider': 5, 'Narrower': -5, None: 0} try: rows = int(height) except: rows = max(1, int(dtpref_rows) + szchh.get(height, 0)) try: cols = int(width) except: cols = max(40, int(dtpref_cols) + szchw.get(width, 0)) e = (DateTime('GMT') + 365).rfc822() setc = REQUEST['RESPONSE'].setCookie setc('dtpref_rows', str(rows), path='/', expires=e) setc('dtpref_cols', str(cols), path='/', expires=e) REQUEST.form.update({'dtpref_cols': cols, 'dtpref_rows': rows}) return self.manage_main() |
if dtpref_cols[-1:] == "%": dtpref_cols = dtpref_cols[:-1] or '50' if dtpref_rows[-1:] == "%": dtpref_rows = dtpref_rows[:-1] or '20' | def pt_changePrefs(self, REQUEST, height=None, width=None, dtpref_cols='50', dtpref_rows='20'): """Change editing preferences.""" # The <textarea> can have dimensions expressed in percentages; # strip the percent sign so int() below won't fail if dtpref_cols[-1:] == "%": dtpref_cols = dtpref_cols[:-1] or '50' if dtpref_rows[-1:] == "%": dtpref_rows = dtpref_rows[:-1] or '20' szchh = {'Taller': 1, 'Shorter': -1, None: 0} szchw = {'Wider': 5, 'Narrower': -5, None: 0} try: rows = int(height) except: rows = max(1, int(dtpref_rows) + szchh.get(height, 0)) try: cols = int(width) except: cols = max(40, int(dtpref_cols) + szchw.get(width, 0)) e = (DateTime('GMT') + 365).rfc822() setc = REQUEST['RESPONSE'].setCookie setc('dtpref_rows', str(rows), path='/', expires=e) setc('dtpref_cols', str(cols), path='/', expires=e) REQUEST.form.update({'dtpref_cols': cols, 'dtpref_rows': rows}) return self.manage_main() |
|
try: cols = int(width) except: cols = max(40, int(dtpref_cols) + szchw.get(width, 0)) | def pt_changePrefs(self, REQUEST, height=None, width=None, dtpref_cols='50', dtpref_rows='20'): """Change editing preferences.""" # The <textarea> can have dimensions expressed in percentages; # strip the percent sign so int() below won't fail if dtpref_cols[-1:] == "%": dtpref_cols = dtpref_cols[:-1] or '50' if dtpref_rows[-1:] == "%": dtpref_rows = dtpref_rows[:-1] or '20' szchh = {'Taller': 1, 'Shorter': -1, None: 0} szchw = {'Wider': 5, 'Narrower': -5, None: 0} try: rows = int(height) except: rows = max(1, int(dtpref_rows) + szchh.get(height, 0)) try: cols = int(width) except: cols = max(40, int(dtpref_cols) + szchw.get(width, 0)) e = (DateTime('GMT') + 365).rfc822() setc = REQUEST['RESPONSE'].setCookie setc('dtpref_rows', str(rows), path='/', expires=e) setc('dtpref_cols', str(cols), path='/', expires=e) REQUEST.form.update({'dtpref_cols': cols, 'dtpref_rows': rows}) return self.manage_main() |
|
if file and (type(file) is type('') or hasattr(file, 'content-type')): | if file and (type(file) is type('') or file.filename): | def manage_edit(self, meta_type='', icon='', file='', REQUEST=None): """Set basic item properties. """ if meta_type: self.setClassAttr('meta_type', meta_type) |
db_name = ApplicationManager.db_name db_size = ApplicationManager.db_size manage_pack = ApplicationManager.manage_pack | db_name = ApplicationManager.db_name.im_func db_size = ApplicationManager.db_size.im_func manage_pack = ApplicationManager.manage_pack.im_func | def objectIds(self, spec=None): """ this is a patch for pre-2.4 Zope installations. Such installations don't have an entry for the WebDAV LockManager introduced in 2.4. """ |
return folder._getOb(i.id) | id = i.getId() return folder._getOb(id) | def createInObjectManager(self, id, REQUEST, RESPONSE=None): """ Create Z instance. If called with a RESPONSE, the RESPONSE will be redirected to the management screen of the new instance's parent Folder. Otherwise, the instance will be returned. """ i=mapply(self._zclass_, (), REQUEST) try: i._setId(id) except AttributeError: i.id=id folder=durl=None if hasattr(self, 'Destination'): d=self.Destination if d.im_self.__class__ is FactoryDispatcher: folder=d() if folder is None: folder=self.aq_parent if not hasattr(folder,'_setObject'): folder=folder.aq_parent |
result[name]=value | if not already_have(name): result[name]=value | def parse_cookie(text, result=None, qparmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)="\([^"]*\)\"' '\([\0- ]*[;,]\)?[\0- ]*\)' ), parmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)=\([^\0;-=\"]*\)' '\([\0- ]*[;,]\)?[\0- ]*\)' ), ): if result is None: result={} if qparmre.match(text) >= 0: # Match quoted correct cookies name=qparmre.group(2) value=qparmre.group(3) l=len(qparmre.group(1)) elif parmre.match(text) >= 0: # Match evil MSIE cookies ;) name=parmre.group(2) value=parmre.group(3) l=len(parmre.group(1)) else: if not text or not strip(text): return result raise "InvalidParameter", text result[name]=value return apply(parse_cookie,(text[l:],result)) |
transaction.savepoint() | transaction.savepoint(optimistic=True) | def _read_data(self, file): |
lg = logger.syslog_logger((addr, int(port)) | lg = logger.syslog_logger((addr, int(port))) | def set_locale(val): try: import locale except: raise SystemExit, ( 'The locale module could not be imported.\n' 'To use localization options, you must ensure\n' 'that the locale module is compiled into your\n' 'Python installation.' ) try: locale.setlocale(locale.LC_ALL, val) except: raise SystemExit, ( 'The specified locale is not supported by your system.\n' 'See your operating system documentation for more\n' 'information on locale support.' ) |
for name in os.listdir(ed): suffix='' if name[:lpp]==pp: path=os.path.join(ed, name) try: f=open(path) data=f.read() f.close() if name[-3:]=='.py': data=rot.encrypt(zlib.compress(data)) suffix='p' except: data=None if data: ar.add("%sExtensions/%s%s" % (prefix,name[lpp:],suffix), data) | if os.path.exists(ed): for name in os.listdir(ed): suffix='' if name[:lpp]==pp: path=os.path.join(ed, name) try: f=open(path) data=f.read() f.close() if name[-3:]=='.py': data=rot.encrypt(zlib.compress(data)) suffix='p' except: data=None if data: ar.add("%sExtensions/%s%s" % (prefix,name[lpp:],suffix), data) | def _distribution(self): # Return a distribution if self.__dict__.has_key('manage_options'): raise TypeError, 'This product is <b>not</b> redistributable.' |
except Except: | except AttributeError: | def index_object(self, documentId, obj, threshold=None): """ index an object 'obj' with integer id 'i' |
finished=[] idx=0 while(idx < len(items)): name, ob = items[idx] | finished_dict={} finished = finished_dict.has_key while items: name, ob = items.pop() | def fixupZClassDependencies(self, rebuild=0): # Note that callers should not catch exceptions from this method # to ensure that the transaction gets aborted if the registry # cannot be rebuilt for some reason. Returns true if any ZClasses # were registered as a result of the call or the registry was # rebuilt. jar=self._p_jar result=0 |
if base in finished: idx=idx+1 | if finished(id(base)): | def fixupZClassDependencies(self, rebuild=0): # Note that callers should not catch exceptions from this method # to ensure that the transaction gets aborted if the registry # cannot be rebuilt for some reason. Returns true if any ZClasses # were registered as a result of the call or the registry was # rebuilt. jar=self._p_jar result=0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.