bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def allowed(self, object, object_roles=None): """Check whether the user has access to object, assuming that object.__roles__ is the given roles.""" if object_roles is None or 'Anonymous' in object_roles: return 1 usr_roles=self.getRolesInContext(object) for role in object_roles: if role in usr_roles: # The user apparently has one of the necessary # roles, but first make sure the object exists # in the context of the parent of the acl_users # folder. ufolder = getattr(self, 'aq_parent', None) ucontext = getattr(ufolder, 'aq_parent', None) if ucontext is not None: if object is None: # This is a strange rule, though # it doesn't cause any security holes. SDH return 1 if not hasattr(object, 'aq_inContextOf'): if hasattr(object, 'im_self'): # This is a method. Grab its self. object=object.im_self if not hasattr(object, 'aq_inContextOf'): # object is not wrapped, therefore we # can't determine context. # Fail the access attempt. Otherwise # this would be a security hole. return None if not object.aq_inContextOf(ucontext, 1): if 'Shared' in object_roles: # Damn, old role setting. Waaa object_roles=self._shared_roles(object) if 'Anonymous' in roles: return 1 return None # Note that if self were not wrapped, it would # not be possible to determine the user's context # and this method would return 1. # However, as long as user folders always return # wrapped user objects, this is safe. return 1
def allowed(self, object, object_roles=None): """Check whether the user has access to object, assuming that object.__roles__ is the given roles.""" if object_roles is None or 'Anonymous' in object_roles: return 1 usr_roles=self.getRolesInContext(object) for role in object_roles: if role in usr_roles: # The user apparently has one of the necessary # roles, but first make sure the object exists # in the context of the parent of the acl_users # folder. ufolder = getattr(self, 'aq_parent', None) ucontext = getattr(ufolder, 'aq_parent', None) if ucontext is not None: if object is None: # This is a strange rule, though # it doesn't cause any security holes. SDH return 1 if not hasattr(object, 'aq_inContextOf'): if hasattr(object, 'im_self'): # This is a method. Grab its self. object=object.im_self if not hasattr(object, 'aq_inContextOf'): # object is not wrapped, therefore we # can't determine context. # Fail the access attempt. Otherwise # this would be a security hole. return None if not object.aq_inContextOf(ucontext, 1): if 'Shared' in object_roles: # Damn, old role setting. Waaa object_roles=self._shared_roles(object) if 'Anonymous' in roles: return 1 return None # Note that if self were not wrapped, it would # not be possible to determine the user's context # and this method would return 1. # However, as long as user folders always return # wrapped user objects, this is safe. return 1
3,100
def allowed(self, object, object_roles=None): """Check whether the user has access to object, assuming that object.__roles__ is the given roles.""" if object_roles is None or 'Anonymous' in object_roles: return 1 usr_roles=self.getRolesInContext(object) for role in object_roles: if role in usr_roles: # The user apparently has one of the necessary # roles, but first make sure the object exists # in the context of the parent of the acl_users # folder. ufolder = getattr(self, 'aq_parent', None) ucontext = getattr(ufolder, 'aq_parent', None) if ucontext is not None: if object is None: # This is a strange rule, though # it doesn't cause any security holes. SDH return 1 if not hasattr(object, 'aq_inContextOf'): if hasattr(object, 'im_self'): # This is a method. Grab its self. object=object.im_self if not hasattr(object, 'aq_inContextOf'): # object is not wrapped, therefore we # can't determine context. # Fail the access attempt. Otherwise # this would be a security hole. return None if not object.aq_inContextOf(ucontext, 1): if 'Shared' in object_roles: # Damn, old role setting. Waaa object_roles=self._shared_roles(object) if 'Anonymous' in roles: return 1 return None # Note that if self were not wrapped, it would # not be possible to determine the user's context # and this method would return 1. # However, as long as user folders always return # wrapped user objects, this is safe. return 1
def allowed(self, object, object_roles=None): """Check whether the user has access to object, assuming that object.__roles__ is the given roles.""" if object_roles is None or 'Anonymous' in object_roles: return 1 usr_roles=self.getRolesInContext(object) for role in object_roles: if role in usr_roles: # The user apparently has one of the necessary # roles, but first make sure the object exists # in the context of the parent of the acl_users # folder. ufolder = getattr(self, 'aq_parent', None) ucontext = getattr(ufolder, 'aq_parent', None) if ucontext is not None: if object is None: # This is a strange rule, though # it doesn't cause any security holes. SDH return 1 if not hasattr(object, 'aq_inContextOf'): if hasattr(object, 'im_self'): # This is a method. Grab its self. object=object.im_self if not hasattr(object, 'aq_inContextOf'): # object is not wrapped, therefore we # can't determine context. # Fail the access attempt. Otherwise # this would be a security hole. return None if not object.aq_inContextOf(ucontext, 1): if 'Shared' in object_roles: # Damn, old role setting. Waaa object_roles=self._shared_roles(object) if 'Anonymous' in roles: return 1 return None # Note that if self were not wrapped, it would # not be possible to determine the user's context # and this method would return 1. # However, as long as user folders always return # wrapped user objects, this is safe. return 1
3,101
def manage_cutObjects(self, ids=None, REQUEST=None): """Put a reference to the objects named in ids in the clip board""" if ids is None and REQUEST is not None: return eNoItemsSpecified elif ids is None: raise ValueError, 'ids must be specified'
def manage_cutObjects(self, ids=None, REQUEST=None): """Put a reference to the objects named in ids in the clip board""" if ids is None and REQUEST is not None: return eNoItemsSpecified elif ids is None: raise ValueError, 'ids must be specified'
3,102
def manage_copyObjects(self, ids=None, REQUEST=None, RESPONSE=None): """Put a reference to the objects named in ids in the clip board""" if ids is None and REQUEST is not None: return eNoItemsSpecified elif ids is None: raise ValueError, 'ids must be specified'
def manage_copyObjects(self, ids=None, REQUEST=None, RESPONSE=None): """Put a reference to the objects named in ids in the clip board""" if ids is None and REQUEST is not None: return eNoItemsSpecified elif ids is None: raise ValueError, 'ids must be specified'
3,103
def _booleanInput(self,n,t,v):
def _booleanInput(self,n,t,v):
3,104
def _booleanInput(self,n,t,v):
def _booleanInput(self,n,t,v):
3,105
def _textInput(self,n,t,v): return ('<TEXTAREA NAME="%s" ROWS="10" COLS="50">%s</TEXTAREA>'
def _textInput(self,n,t,v): return ('<TEXTAREA NAME="%s" ROWS="10" COLS="50">%s</TEXTAREA>'
3,106
def manage_addZGadflyConnection( self, id, title, connection, check=None, REQUEST=None): " " return getDA().manage_addZGadflyConnection( self, id, title, connection, check, REQUEST)
def manage_addZGadflyConnection( self, id, title, connection, check=None, REQUEST=None): " " return getDA().manage_addZGadflyConnection( self, id, title, connection, check, REQUEST)
3,107
def write(self, text): assert type(text) is type('') if text[:len(self._error_start)] == self._error_start: errend = find(text, '-->') if errend >= 0: text = text[errend + 4:] if self._text != text: self._text = text self._cook()
def write(self, text): assert type(text) is type('') if text[:len(self._error_start)] == self._error_start: errend = text.find('-->') if errend >= 0: text = text[errend + 4:] if self._text != text: self._text = text self._cook()
3,108
def install_products(): # 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,'lib/python/Products') isdir=os.path.isdir exists=os.path.exists DictType=type({}) meta_types=list(Folder.Folder.dynamic_meta_types) product_names=os.listdir(product_dir) product_names.sort() 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')): continue product=getattr(__import__("Products.%s" % product_name), product_name) 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'] if (not meta_type.has_key('prefix') and not regex.match('[^a-zA-Z0-9_]', name)): meta_type['prefix']=lower(name) if meta_type.has_key('prefix'): prefix=meta_type['prefix'] def productNames(self, name=name): t=[] for i in self.objectMap(): if i['meta_type']==name: t.append(i['name']) return t setattr(Folder.Folder, "%sNames" % prefix , productNames) def productValues(self, name=name): t=[] for i in self.objectMap(): if i['meta_type']==name: t.append(getattr(self,i['name'])) return t setattr(Folder.Folder, "%sValues" % prefix , productValues) def productItems(self, name=name): t=[] for i in self.objectMap(): if i['meta_type']=='Image': n=i['name'] t.append((n,getattr(self,n))) return t setattr(Folder.Folder, "%sItems" % prefix , productItems) for name,method in pgetattr(product, 'methods', {}).items(): setattr(Folder.Folder, name, method) misc_=pgetattr(product, 'misc_', {}) if type(misc_) is DictType: misc_=Misc_(product_name, misc_) Application.misc_.__dict__[product_name]=misc_ Folder.Folder.dynamic_meta_types=tuple(meta_types)
def install_products(): # 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,'lib/python/Products') isdir=os.path.isdir exists=os.path.exists DictType=type({}) meta_types=list(Folder.Folder.dynamic_meta_types) product_names=os.listdir(product_dir) product_names.sort() 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=getattr(__import__("Products.%s" % product_name), product_name) 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'] if (not meta_type.has_key('prefix') and not regex.match('[^a-zA-Z0-9_]', name)): meta_type['prefix']=lower(name) if meta_type.has_key('prefix'): prefix=meta_type['prefix'] def productNames(self, name=name): t=[] for i in self.objectMap(): if i['meta_type']==name: t.append(i['name']) return t setattr(Folder.Folder, "%sNames" % prefix , productNames) def productValues(self, name=name): t=[] for i in self.objectMap(): if i['meta_type']==name: t.append(getattr(self,i['name'])) return t setattr(Folder.Folder, "%sValues" % prefix , productValues) def productItems(self, name=name): t=[] for i in self.objectMap(): if i['meta_type']=='Image': n=i['name'] t.append((n,getattr(self,n))) return t setattr(Folder.Folder, "%sItems" % prefix , productItems) for name,method in pgetattr(product, 'methods', {}).items(): setattr(Folder.Folder, name, method) misc_=pgetattr(product, 'misc_', {}) if type(misc_) is DictType: misc_=Misc_(product_name, misc_) Application.misc_.__dict__[product_name]=misc_ Folder.Folder.dynamic_meta_types=tuple(meta_types)
3,109
def get_env(self, req): env = self._ENV.copy() (path, params, query, fragment) = req.split_uri() if params: path = path + params # undo medusa bug while path and path[0] == '/': path = path[1:] if '%' in path: path = unquote(path) if query: # ZPublisher doesn't want the leading '?' query = query[1:] env['PATH_INFO']= '/' + path env['PATH_TRANSLATED']= os.path.normpath( os.path.join(os.getcwd(), env['PATH_INFO'])) if query: env['QUERY_STRING'] = query env['channel.creation_time']=time.time() for header in req.header: key,value = header.split(":",1) key = key.upper() value = value.strip() key = 'HTTP_%s' % ("_".join(key.split( "-"))) if value: env[key]=value return env
def get_env(self, req): env = self._ENV.copy() (path, params, query, fragment) = req.split_uri() if params: path = path + params # undo medusa bug while path and path[0] == '/': path = path[1:] if '%' in path: path = unquote(path) if query: # ZPublisher doesn't want the leading '?' query = query[1:] env['PATH_INFO']= '/' + path env['PATH_TRANSLATED']= posixpath.normpath( posixpath.join(os.getcwd(), env['PATH_INFO'])) if query: env['QUERY_STRING'] = query env['channel.creation_time']=time.time() for header in req.header: key,value = header.split(":",1) key = key.upper() value = value.strip() key = 'HTTP_%s' % ("_".join(key.split( "-"))) if value: env[key]=value return env
3,110
def _prep_version_data(): global _version_string, _zope_version if _version_string is None: v = sys.version_info pyver = "python %d.%d.%d, %s" % (v[0], v[1], v[2], sys.platform) cfg = getConfiguration() fn = os.path.join(cfg.softwarehome, 'version.txt') expr = re.compile( r'(?P<product>[A-Za-z0-9]+) +(?P<major>[0-9]+)' '\.(?P<minor>[0-9]+)\.(?P<micro>[0-9]+)' '(?P<status>[A-Za-z]+)?(?P<release>[0-9]+)?') try: s = open(fn).read() except IOError: ss = 'unreleased version' _zope_version = (-1, -1, -1, '', -1) else: ss = re.sub("\(.*?\)\?","",s) dict = expr.match(s).groupdict() _zope_version = ( int(dict.get('major') or -1), int(dict.get('minor') or -1), int(dict.get('micro') or -1), dict.get('status') or '', int(dict.get('release') or -1), ) _version_string = "%s, %s" % (ss, pyver)
def _prep_version_data(): global _version_string, _zope_version if _version_string is None: v = sys.version_info pyver = "python %d.%d.%d, %s" % (v[0], v[1], v[2], sys.platform) cfg = getConfiguration() fn = os.path.join(cfg.softwarehome, 'version.txt') expr = re.compile( r'(?P<product>[A-Za-z0-9]+) +(?P<major>[0-9]+)' '\.(?P<minor>[0-9]+)\.(?P<micro>[0-9]+)' '(?P<status>[A-Za-z]+)?(?P<release>[0-9]+)?') try: s = open(fn).read().strip() except IOError: ss = 'unreleased version' _zope_version = (-1, -1, -1, '', -1) else: ss = re.sub("\(.*?\)\?","",s) dict = expr.match(s).groupdict() _zope_version = ( int(dict.get('major') or -1), int(dict.get('minor') or -1), int(dict.get('micro') or -1), dict.get('status') or '', int(dict.get('release') or -1), ) _version_string = "%s, %s" % (ss, pyver)
3,111
def do_useMacro(self, macroName, compiledSlots): doc, localName = self.engine.findMacroDocument(macroName) if not doc: # Local macro macro = self.macros[localName] else: # External macro macroDict = macroIndexer(doc) if not macroDict.has_key(localName): print "Macro", macroName, "not found" return macroNode = macroDict[localName] macro, dummy = TALCompiler(macroNode)() save = self.slots, self.inMacro self.slots = compiledSlots self.inMacro = 1 self.interpret(macro) self.slots, self.inMacro = save
def do_useMacro(self, macroName, compiledSlots): doc, localName = self.engine.findMacroDocument(macroName) if not doc: # Local macro macro = self.macros[localName] else: # External macro macroDict = macroIndexer(doc) if not macroDict.has_key(localName): print "Macro", macroName, "not found" return macroNode = macroDict[localName] macro, dummy = TALCompiler(macroNode)() save = self.slots, self.inMacro self.slots = compiledSlots self.inMacro = 1 self.interpret(macro) self.slots, self.inMacro = save
3,112
def _edit_widget_for_type(self, t, id, p): if t in ('int', 'long', 'float', 'date', 'string'): if t=='string': q=' html_quote' else: q='' return (''' <input name="%s:%s" size="35" value="<!--#var %s%s-->">''' % (id, t, id, q) ) if t=='boolean': return (''' <input type="checkbox" name="%s:boolean" size="35" <!--#if %s-->CHECKED<!--#/if-->>''' % (id, id) ) if t=='tokens': return (''' <input type="text" name="%s:tokens" size="35" value="<!--#in %s--><!--#var sequence-item--> <!--#endin-->">''' % (id, id) ) if t=='text': return (''' <textarea name="%s:text" rows="6" cols="35"><!--#var %s --></textarea>''' % (id, id) ) if t=='lines': return (''' <textarea name="%s:lines" rows="6" cols="35"><!--#in %s --><!--#var sequence-item-->\n<!--#/in--></textarea>''' % (id, id) ) if t=='selection': return (''' <!--#if "_.has_key('%(select_variable)s')"--> <select name="<!--#var %(id)s-->"> <!--#in %(select_variable)s--> <option <!--#if "_['sequence-item']==%(id)s"--> SELECTED<!--#/if--> ><!--#var sequence-item--></option> <!--#/in--> </select> <!--#else--> No value for %(select_variable)s <!--#/if-->''' % p )
def _edit_widget_for_type(self, t, id, p): if t in ('int', 'long', 'float', 'date', 'string'): if t=='string': q=' html_quote' else: q='' return (''' <input name="%s:%s" size="35" value="<!--#var %s%s-->">''' % (id, t, id, q) ) if t=='boolean': return (''' <input type="checkbox" name="%s:boolean" size="35" <!--#if %s-->CHECKED<!--#/if-->>''' % (id, id) ) if t=='tokens': return (''' <input type="text" name="%s:tokens" size="35" value="<!--#in %s--><!--#var sequence-item--> <!--#endin-->">''' % (id, id) ) if t=='text': return (''' <textarea name="%s:text" rows="6" cols="35"><!--#var %s --></textarea>''' % (id, id) ) if t=='lines': return (''' <textarea name="%s:lines" rows="6" cols="35"><!--#in %s --><!--#var sequence-item-->\n<!--#/in--></textarea>''' % (id, id) ) if t=='selection': return (''' <!--#if "_.has_key('%(select_variable)s')"--> <select name="<!--#var %(id)s-->"> <!--#in %(select_variable)s--> <option <!--#if "_['sequence-item']==%(id)s"--> SELECTED<!--#/if--> ><!--#var sequence-item--></option> <!--#/in--> </select> <!--#else--> No value for %(select_variable)s <!--#/if-->''' % p )
3,113
def main(args): usage_msg="""Usage: python testrunner.py options If run without options, testrunner will display this usage message. If you want to run all test suites found in all subdirectories of the current working directory, use the -a option. options: -a Run all tests found in all subdirectories of the current working directory. This is the default if no options are specified. -m Run all tests in a single, giant suite (consolidates error reporting). [default] -M Run each test file's suite separately (noisier output, may help in isolating global effects later). -p Add 'lib/python' to the Python search path. [default] -P *Don't* add 'lib/python' to the Python search path. -d dirpath Run all tests found in the directory specified by dirpath, and recursively in all its subdirectories. The dirpath should be a full system path. -f filepath Run the test suite found in the file specified. The filepath should be a fully qualified path to the file to be run. -v level Set the Verbosity level to level. Newer versions of unittest.py allow more options than older ones. Allowed values are: 0 - Silent 1 - Quiet (produces a dot for each succesful test) 2 - Verbose (default - produces a line of output for each test) -q Run tests without producing verbose output. The tests are normally run in verbose mode, which produces a line of output for each test that includes the name of the test and whether it succeeded. Running with -q is the same as running with -v1. -o filename Output test results to the specified file rather than to stderr. -h Display usage information. """ pathname=None filename=None test_all=None verbosity = VERBOSE mega_suite = 1 set_python_path = 1 options, arg=getopt.getopt(args, 'amPhd:f:v:qMo:') if not options: err_exit(usage_msg) for name, value in options: name=name[1:] if name == 'a': test_all=1 elif name == 'm': mega_suite = 1 elif name == 'M': mega_suite = 0 elif name == 'p': set_python_path = 1 elif name == 'P': set_python_path = 0 elif name == 'd': pathname=string.strip(value) elif name == 'f': filename=string.strip(value) elif name == 'h': err_exit(usage_msg, 0) elif name == 'v': verbosity = int(value) elif name == 'q': verbosity = 1 elif name == 'o': f = open(value,'w') sys.stderr = f else: err_exit(usage_msg) os.path.walk(os.curdir, remove_stale_bytecode, None) testrunner = TestRunner( os.getcwd() , verbosity=verbosity , mega_suite=mega_suite) if set_python_path: script = sys.argv[0] script_dir = os.path.split( os.path.abspath( script ) )[0] zope_dir = os.path.abspath( os.path.join( script_dir, '..' ) ) sw_home = os.path.join( zope_dir, 'lib', 'python' ) if verbosity > 1: testrunner.report( "Adding %s to sys.path." % sw_home ) sys.path.insert( 0, sw_home ) os.environ['SOFTWARE_HOME'] = sw_home try: # Try to set up the testing environment (esp. INSTANCE_HOME, # so we use the right custom_zodb.py.) import Testing except ImportError: pass if test_all: testrunner.runAllTests() elif pathname: testrunner.runPath(pathname) elif filename: testrunner.runFile(filename) ## Report overall errors / failures if there were any fails = reduce(lambda x, y: x + len(y.failures), testrunner.results, 0) errs = reduce(lambda x, y: x + len(y.errors), testrunner.results, 0) if fails or errs: msg = '=' * 70 msg += "\nOVERALL FAILED (" if fails: msg += "total failures=%d" % fails if errs: if fails: msg += ", " msg += "total errors=%d" % errs msg += ")" err_exit(msg, 1) sys.exit(0)
def main(args): usage_msg="""Usage: python testrunner.py options If run without options, testrunner will display this usage message. If you want to run all test suites found in all subdirectories of the current working directory, use the -a option. options: -a Run all tests found in all subdirectories of the current working directory. -m Run all tests in a single, giant suite (consolidates error reporting). [default] -M Run each test file's suite separately (noisier output, may help in isolating global effects later). -p Add 'lib/python' to the Python search path. [default] -P *Don't* add 'lib/python' to the Python search path. -d dirpath Run all tests found in the directory specified by dirpath, and recursively in all its subdirectories. The dirpath should be a full system path. -f filepath Run the test suite found in the file specified. The filepath should be a fully qualified path to the file to be run. -v level Set the Verbosity level to level. Newer versions of unittest.py allow more options than older ones. Allowed values are: 0 - Silent 1 - Quiet (produces a dot for each succesful test) 2 - Verbose (default - produces a line of output for each test) -q Run tests without producing verbose output. The tests are normally run in verbose mode, which produces a line of output for each test that includes the name of the test and whether it succeeded. Running with -q is the same as running with -v1. -o filename Output test results to the specified file rather than to stderr. -h Display usage information. """ pathname=None filename=None test_all=None verbosity = VERBOSE mega_suite = 1 set_python_path = 1 options, arg=getopt.getopt(args, 'amPhd:f:v:qMo:') if not options: err_exit(usage_msg) for name, value in options: name=name[1:] if name == 'a': test_all=1 elif name == 'm': mega_suite = 1 elif name == 'M': mega_suite = 0 elif name == 'p': set_python_path = 1 elif name == 'P': set_python_path = 0 elif name == 'd': pathname=string.strip(value) elif name == 'f': filename=string.strip(value) elif name == 'h': err_exit(usage_msg, 0) elif name == 'v': verbosity = int(value) elif name == 'q': verbosity = 1 elif name == 'o': f = open(value,'w') sys.stderr = f else: err_exit(usage_msg) os.path.walk(os.curdir, remove_stale_bytecode, None) testrunner = TestRunner( os.getcwd() , verbosity=verbosity , mega_suite=mega_suite) if set_python_path: script = sys.argv[0] script_dir = os.path.split( os.path.abspath( script ) )[0] zope_dir = os.path.abspath( os.path.join( script_dir, '..' ) ) sw_home = os.path.join( zope_dir, 'lib', 'python' ) if verbosity > 1: testrunner.report( "Adding %s to sys.path." % sw_home ) sys.path.insert( 0, sw_home ) os.environ['SOFTWARE_HOME'] = sw_home try: # Try to set up the testing environment (esp. INSTANCE_HOME, # so we use the right custom_zodb.py.) import Testing except ImportError: pass if test_all: testrunner.runAllTests() elif pathname: testrunner.runPath(pathname) elif filename: testrunner.runFile(filename) ## Report overall errors / failures if there were any fails = reduce(lambda x, y: x + len(y.failures), testrunner.results, 0) errs = reduce(lambda x, y: x + len(y.errors), testrunner.results, 0) if fails or errs: msg = '=' * 70 msg += "\nOVERALL FAILED (" if fails: msg += "total failures=%d" % fails if errs: if fails: msg += ", " msg += "total errors=%d" % errs msg += ")" err_exit(msg, 1) sys.exit(0)
3,114
def manage_renameObject(self, id, new_id, REQUEST=None): """Rename a particular sub-object""" try: self._checkId(new_id) except: raise CopyError, MessageDialog( title='Invalid Id', message=sys.exc_info()[1], action ='manage_main') ob=self._getOb(id) if not ob.cb_isMoveable(): raise CopyError, eNotSupported % id self._verifyObjectPaste(ob) try: ob._notifyOfCopyTo(self, op=1) except: raise CopyError, MessageDialog( title='Rename Error', message=sys.exc_info()[1], action ='manage_main') ob = aq_base(ob) ob._setId(new_id) # Note - because a rename always keeps the same context, we # can just leave the ownership info unchanged. self._setObject(new_id, ob, set_owner=0) self._delObject(id)
def manage_renameObject(self, id, new_id, REQUEST=None): """Rename a particular sub-object""" try: self._checkId(new_id) except: raise CopyError, MessageDialog( title='Invalid Id', message=sys.exc_info()[1], action ='manage_main') ob=self._getOb(id) if not ob.cb_isMoveable(): raise CopyError, eNotSupported % id self._verifyObjectPaste(ob) try: ob._notifyOfCopyTo(self, op=1) except: raise CopyError, MessageDialog( title='Rename Error', message=sys.exc_info()[1], action ='manage_main') ob = aq_base(ob) ob._setId(new_id) # Note - because a rename always keeps the same context, we # can just leave the ownership info unchanged. self._setObject(new_id, ob, set_owner=0) self._delObject(id)
3,115
def hasSessionData(self): """ """ key = self.getBrowserIdManager().getToken(create=0) if key: if self._hasSessionDataObject(key): return 1
def hasSessionData(self): """ """ key = self.getBrowserIdManager().getToken(create=0) if key: if self._hasSessionDataObject(key): return 1
3,116
def taste(spam): "a favorable reviewer" return spam,'yum yum, I like ' + spam
def taste(spam): "a favorable reviewer" return spam,'yum yum, I like ' + spam
3,117
def taste(spam): "a favorable reviewer" return spam,'yum yum, I like ' + spam
def taste(spam): "a favorable reviewer" return spam,'yum yum, I like ' + spam
3,118
def publish(self, module_name, published='web_objects',
def publish(self, module_name, published='web_objects',
3,119
def publish(self, module_name, published='web_objects',
def publish(self, module_name, published='web_objects',
3,120
def function_with_empty_signature(): pass
def try: transaction=get_transaction() transaction.begin() except: transaction=None function_with_empty_signature(): try: transaction=get_transaction() transaction.begin() except: transaction=None pass
3,121
def flatten_field(v,converter): if type(v) is types.ListType: if len(v) > 1: return map(flatten_field,v) v=v[0] try: if v.file: v=v.file else: v=v.value except: pass if converter: v=converter(v) return v
def flatten_field(v,converter=None): if type(v) is types.ListType: if len(v) > 1: return map(flatten_field,v) v=v[0] try: if v.file: v=v.file else: v=v.value except: pass if converter: v=converter(v) return v
3,122
def __getitem__(self,key):
def __getitem__(self,key):
3,123
def __init__(self,
def __init__(self,
3,124
def __init__(self,
def __init__(self,
3,125
def add(self, id, title='', smtp_host=None, localhost='localhost', smtp_port=25, timeout=1.0, REQUEST=None): ' add a MailHost into the system ' id=str(id) title=str(title) if smtp_host is not None: smtp_host=str(smtp_host) if type(smtp_port) is not type(1): smtp_port=string.atoi(smtp_port) i=MailHost() #create new mail host i.id=id #give it id i.title=title #title i._init(smtp_host=smtp_host, smtp_port=smtp_port) self=self.this() self._setObject(id,i) #register it if REQUEST is not None: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
def add(self, id, title='', smtp_host=None, localhost='localhost', smtp_port=25, timeout=1.0, REQUEST=None): ' add a MailHost into the system ' id=str(id) title=str(title) if smtp_host is not None: smtp_host=str(smtp_host) if type(smtp_port) is not type(1): smtp_port=string.atoi(smtp_port) i=MailHost() #create new mail host i.id=id #give it id i.title=title #title i._init(smtp_host=smtp_host, smtp_port=smtp_port) self=self.this() self._setObject(id,i) #register it if REQUEST is not None: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
3,126
def __init__(self, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, environ=os.environ): self.environ=environ fp=None try: if environ['REQUEST_METHOD'] != 'GET': fp=stdin except: pass
def __init__(self, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, environ=os.environ): self.environ=environ fp=None try: if environ['REQUEST_METHOD'] != 'GET': fp=stdin except: pass
3,127
def emitDefines(self, defines): for part in splitParts(defines): m = re.match( r"\s*(?:(global|local)\s+)?(%s)\s+(.*)" % NAME_RE, part) if not m: if not string.strip(part): break # extra space after semi raise TALError("invalid z:define syntax: " + `part`) scope, name, expr = m.group(1, 2, 3) scope = scope or "local" cexpr = self.compileExpression(expr) if scope == "local": self.emit("setLocal", name, cexpr) else: self.emit("setGlobal", name, cexpr)
def emitDefines(self, defines): for part in splitParts(defines): m = re.match( r"\s*(?:(global|local)\s+)?(%s)\s+(.*)" % NAME_RE, part) if not m: if not string.strip(part): break # extra space after semi raise TALError("invalid z:define syntax: " + `part`) scope, name, expr = m.group(1, 2, 3) scope = scope or "local" cexpr = self.compileExpression(expr) if scope == "local": self.emit("setLocal", name, cexpr) else: self.emit("setGlobal", name, cexpr)
3,128
def emitRepeat(self, arg): m = re.match("\s*(%s)\s+(.*)" % NAME_RE, arg) if not m: raise TALError("invalid z:repeat syntax: " + `repeat`) name, expr = m.group(1, 2) cexpr = self.compileExpression(expr) program = self.popProgram() self.emit("loop", name, cexpr, program)
def emitRepeat(self, arg): m = re.match("\s*(%s)\s+(.*)" % NAME_RE, arg) if not m: raise TALError("invalid repeat syntax: " + `repeat`) name, expr = m.group(1, 2) cexpr = self.compileExpression(expr) program = self.popProgram() self.emit("loop", name, cexpr, program)
3,129
def emitSubstitution(self, arg, attrDict={}): key, expr = parseSubstitution(arg) if not key: raise TALError("Bad syntax in z:insert/z:replace: " + `arg`) cexpr = self.compileExpression(expr) program = self.popProgram() if key == "text": self.emit("insertText", cexpr, program) else: assert key == "structure" self.emit("insertStructure", cexpr, attrDict, program)
def emitSubstitution(self, arg, attrDict={}): key, expr = parseSubstitution(arg) if not key: raise TALError("Bad syntax in insert/replace: " + `arg`) cexpr = self.compileExpression(expr) program = self.popProgram() if key == "text": self.emit("insertText", cexpr, program) else: assert key == "structure" self.emit("insertStructure", cexpr, attrDict, program)
3,130
def initialize(app): # Initialize the application # Initialize the cache: app.Control_Panel.initialize_cache() # The following items marked b/c are backward compatibility hacks # which make sure that expected system objects are added to the # bobobase. This is required because the bobobase in use may pre- # date the introduction of certain system objects such as those # which provide Lever support. # b/c: Ensure that Control Panel exists. if not hasattr(app, 'Control_Panel'): cpl=ApplicationManager() cpl._init() app._setObject('Control_Panel', cpl) get_transaction().note('Added Control_Panel') get_transaction().commit() # b/c: Ensure that a ProductFolder exists. if not hasattr(app.Control_Panel.aq_base, 'Products'): app.Control_Panel.Products=App.Product.ProductFolder() get_transaction().note('Added Control_Panel.Products') get_transaction().commit() # Ensure that a temp folder exists if not hasattr(app, 'temp_folder'): from Products.TemporaryFolder.TemporaryFolder import \ MountedTemporaryFolder tf = MountedTemporaryFolder('temp_folder','Temporary Folder') app._setObject('temp_folder', tf) get_transaction().note('Added temp_folder') get_transaction().commit() del tf # Ensure that there is a transient container in the temp folder tf = app.temp_folder if not hasattr(tf, 'session_data'): env_has = os.environ.get from Products.Transience.Transience import TransientObjectContainer addnotify = env_has('ZSESSION_ADD_NOTIFY', None) delnotify = env_has('ZSESSION_DEL_NOTIFY', None) default_limit = 1000 limit = env_has('ZSESSION_OBJECT_LIMIT', default_limit) try: limit=int(limit) if limit != default_limit: LOG('Zope Default Object Creation', INFO, ('using ZSESSION_OBJECT_LIMIT-specified max objects ' 'value of %s' % limit)) except ValueError: LOG('Zope Default Object Creation', WARNING, ('Noninteger value %s specified for ZSESSION_OBJECT_LIMIT, ' 'defaulting to %s' % (limit, default_limit))) limit = default_limit if addnotify and app.unrestrictedTraverse(addnotify, None) is None: LOG('Zope Default Object Creation', WARNING, ('failed to use nonexistent "%s" script as ' 'ZSESSION_ADD_NOTIFY' % addnotify)) addnotify=None elif addnotify: LOG('Zope Default Object Creation', INFO, 'using %s as add notification script' % addnotify) if delnotify and app.unrestrictedTraverse(delnotify, None) is None: LOG('Zope Default Object Creation', WARNING, ('failed to use nonexistent "%s" script as ' 'ZSESSION_DEL_NOTIFY' % delnotify)) delnotify=None elif delnotify: LOG('Zope Default Object Creation', INFO, 'using %s as delete notification script' % delnotify) toc = TransientObjectContainer('session_data', 'Session Data Container', addNotification = addnotify, delNotification = delnotify, limit=limit) timeout_spec = env_has('ZSESSION_TIMEOUT_MINS', '') if timeout_spec: try: timeout_spec = int(timeout_spec) except ValueError: LOG('Zope Default Object Creation', WARNING, ('"%s" is an illegal value for ZSESSION_TIMEOUT_MINS, ' 'using default timeout instead.' % timeout_spec)) else: LOG('Zope Default Object Creation', INFO, ('using ZSESSION_TIMEOUT_MINS-specified session timeout ' 'value of %s' % timeout_spec)) toc = TransientObjectContainer('session_data', 'Session Data Container', timeout_mins = timeout_spec, addNotification=addnotify, delNotification = delnotify, limit=limit) tf._setObject('session_data', toc) tf_reserved = getattr(tf, '_reserved_names', ()) if 'session_data' not in tf_reserved: tf._reserved_names = tf_reserved + ('session_data',) get_transaction().note('Added session_data to temp_folder') get_transaction().commit() del toc del addnotify del delnotify del timeout_spec del env_has del tf # Ensure that a browser ID manager exists if not hasattr(app, 'browser_id_manager'): from Products.Sessions.BrowserIdManager import BrowserIdManager bid = BrowserIdManager('browser_id_manager', 'Browser Id Manager') app._setObject('browser_id_manager', bid) get_transaction().note('Added browser_id_manager') get_transaction().commit() del bid # Ensure that a session data manager exists if not hasattr(app, 'session_data_manager'): from Products.Sessions.SessionDataManager import SessionDataManager sdm = SessionDataManager('session_data_manager', title='Session Data Manager', path='/temp_folder/session_data', requestName='SESSION') app._setObject('session_data_manager', sdm) get_transaction().note('Added session_data_manager') get_transaction().commit() del sdm # Ensure that there's an Examples folder with examples. # However, make sure that if the examples have been added already # and then deleted that we don't add them again. if not hasattr(app, 'Examples') and not \ hasattr(app, '_Zope25_examples_have_been_added'):
def initialize(app): # Initialize the application # Initialize the cache: app.Control_Panel.initialize_cache() # The following items marked b/c are backward compatibility hacks # which make sure that expected system objects are added to the # bobobase. This is required because the bobobase in use may pre- # date the introduction of certain system objects such as those # which provide Lever support. # b/c: Ensure that Control Panel exists. if not hasattr(app, 'Control_Panel'): cpl=ApplicationManager() cpl._init() app._setObject('Control_Panel', cpl) get_transaction().note('Added Control_Panel') get_transaction().commit() # b/c: Ensure that a ProductFolder exists. if not hasattr(app.Control_Panel.aq_base, 'Products'): app.Control_Panel.Products=App.Product.ProductFolder() get_transaction().note('Added Control_Panel.Products') get_transaction().commit() # Ensure that a temp folder exists if not hasattr(app, 'temp_folder'): from Products.TemporaryFolder.TemporaryFolder import \ MountedTemporaryFolder tf = MountedTemporaryFolder('temp_folder','Temporary Folder') app._setObject('temp_folder', tf) get_transaction().note('Added temp_folder') get_transaction().commit() del tf # Ensure that there is a transient container in the temp folder tf = app.temp_folder if not hasattr(tf, 'session_data'): env_has = os.environ.get from Products.Transience.Transience import TransientObjectContainer addnotify = env_has('ZSESSION_ADD_NOTIFY', None) delnotify = env_has('ZSESSION_DEL_NOTIFY', None) default_limit = 1000 limit = env_has('ZSESSION_OBJECT_LIMIT', default_limit) try: limit=int(limit) if limit != default_limit: LOG('Zope Default Object Creation', INFO, ('using ZSESSION_OBJECT_LIMIT-specified max objects ' 'value of %s' % limit)) except ValueError: LOG('Zope Default Object Creation', WARNING, ('Noninteger value %s specified for ZSESSION_OBJECT_LIMIT, ' 'defaulting to %s' % (limit, default_limit))) limit = default_limit if addnotify and app.unrestrictedTraverse(addnotify, None) is None: LOG('Zope Default Object Creation', WARNING, ('failed to use nonexistent "%s" script as ' 'ZSESSION_ADD_NOTIFY' % addnotify)) addnotify=None elif addnotify: LOG('Zope Default Object Creation', INFO, 'using %s as add notification script' % addnotify) if delnotify and app.unrestrictedTraverse(delnotify, None) is None: LOG('Zope Default Object Creation', WARNING, ('failed to use nonexistent "%s" script as ' 'ZSESSION_DEL_NOTIFY' % delnotify)) delnotify=None elif delnotify: LOG('Zope Default Object Creation', INFO, 'using %s as delete notification script' % delnotify) toc = TransientObjectContainer('session_data', 'Session Data Container', addNotification = addnotify, delNotification = delnotify, limit=limit) timeout_spec = env_has('ZSESSION_TIMEOUT_MINS', '') if timeout_spec: try: timeout_spec = int(timeout_spec) except ValueError: LOG('Zope Default Object Creation', WARNING, ('"%s" is an illegal value for ZSESSION_TIMEOUT_MINS, ' 'using default timeout instead.' % timeout_spec)) else: LOG('Zope Default Object Creation', INFO, ('using ZSESSION_TIMEOUT_MINS-specified session timeout ' 'value of %s' % timeout_spec)) toc = TransientObjectContainer('session_data', 'Session Data Container', timeout_mins = timeout_spec, addNotification=addnotify, delNotification = delnotify, limit=limit) tf._setObject('session_data', toc) tf_reserved = getattr(tf, '_reserved_names', ()) if 'session_data' not in tf_reserved: tf._reserved_names = tf_reserved + ('session_data',) get_transaction().note('Added session_data to temp_folder') get_transaction().commit() del toc del addnotify del delnotify del timeout_spec del env_has del tf # Ensure that a browser ID manager exists if not hasattr(app, 'browser_id_manager'): from Products.Sessions.BrowserIdManager import BrowserIdManager bid = BrowserIdManager('browser_id_manager', 'Browser Id Manager') app._setObject('browser_id_manager', bid) get_transaction().note('Added browser_id_manager') get_transaction().commit() del bid # Ensure that a session data manager exists if not hasattr(app, 'session_data_manager'): from Products.Sessions.SessionDataManager import SessionDataManager sdm = SessionDataManager('session_data_manager', title='Session Data Manager', path='/temp_folder/session_data', requestName='SESSION') app._setObject('session_data_manager', sdm) get_transaction().note('Added session_data_manager') get_transaction().commit() del sdm # Ensure that there's an Examples folder with examples. # However, make sure that if the examples have been added already # and then deleted that we don't add them again. if not hasattr(app, 'Examples') and not \ hasattr(app, '_Zope25_examples_have_been_added'):
3,131
def initialize(app): # Initialize the application # Initialize the cache: app.Control_Panel.initialize_cache() # The following items marked b/c are backward compatibility hacks # which make sure that expected system objects are added to the # bobobase. This is required because the bobobase in use may pre- # date the introduction of certain system objects such as those # which provide Lever support. # b/c: Ensure that Control Panel exists. if not hasattr(app, 'Control_Panel'): cpl=ApplicationManager() cpl._init() app._setObject('Control_Panel', cpl) get_transaction().note('Added Control_Panel') get_transaction().commit() # b/c: Ensure that a ProductFolder exists. if not hasattr(app.Control_Panel.aq_base, 'Products'): app.Control_Panel.Products=App.Product.ProductFolder() get_transaction().note('Added Control_Panel.Products') get_transaction().commit() # Ensure that a temp folder exists if not hasattr(app, 'temp_folder'): from Products.TemporaryFolder.TemporaryFolder import \ MountedTemporaryFolder tf = MountedTemporaryFolder('temp_folder','Temporary Folder') app._setObject('temp_folder', tf) get_transaction().note('Added temp_folder') get_transaction().commit() del tf # Ensure that there is a transient container in the temp folder tf = app.temp_folder if not hasattr(tf, 'session_data'): env_has = os.environ.get from Products.Transience.Transience import TransientObjectContainer addnotify = env_has('ZSESSION_ADD_NOTIFY', None) delnotify = env_has('ZSESSION_DEL_NOTIFY', None) default_limit = 1000 limit = env_has('ZSESSION_OBJECT_LIMIT', default_limit) try: limit=int(limit) if limit != default_limit: LOG('Zope Default Object Creation', INFO, ('using ZSESSION_OBJECT_LIMIT-specified max objects ' 'value of %s' % limit)) except ValueError: LOG('Zope Default Object Creation', WARNING, ('Noninteger value %s specified for ZSESSION_OBJECT_LIMIT, ' 'defaulting to %s' % (limit, default_limit))) limit = default_limit if addnotify and app.unrestrictedTraverse(addnotify, None) is None: LOG('Zope Default Object Creation', WARNING, ('failed to use nonexistent "%s" script as ' 'ZSESSION_ADD_NOTIFY' % addnotify)) addnotify=None elif addnotify: LOG('Zope Default Object Creation', INFO, 'using %s as add notification script' % addnotify) if delnotify and app.unrestrictedTraverse(delnotify, None) is None: LOG('Zope Default Object Creation', WARNING, ('failed to use nonexistent "%s" script as ' 'ZSESSION_DEL_NOTIFY' % delnotify)) delnotify=None elif delnotify: LOG('Zope Default Object Creation', INFO, 'using %s as delete notification script' % delnotify) toc = TransientObjectContainer('session_data', 'Session Data Container', addNotification = addnotify, delNotification = delnotify, limit=limit) timeout_spec = env_has('ZSESSION_TIMEOUT_MINS', '') if timeout_spec: try: timeout_spec = int(timeout_spec) except ValueError: LOG('Zope Default Object Creation', WARNING, ('"%s" is an illegal value for ZSESSION_TIMEOUT_MINS, ' 'using default timeout instead.' % timeout_spec)) else: LOG('Zope Default Object Creation', INFO, ('using ZSESSION_TIMEOUT_MINS-specified session timeout ' 'value of %s' % timeout_spec)) toc = TransientObjectContainer('session_data', 'Session Data Container', timeout_mins = timeout_spec, addNotification=addnotify, delNotification = delnotify, limit=limit) tf._setObject('session_data', toc) tf_reserved = getattr(tf, '_reserved_names', ()) if 'session_data' not in tf_reserved: tf._reserved_names = tf_reserved + ('session_data',) get_transaction().note('Added session_data to temp_folder') get_transaction().commit() del toc del addnotify del delnotify del timeout_spec del env_has del tf # Ensure that a browser ID manager exists if not hasattr(app, 'browser_id_manager'): from Products.Sessions.BrowserIdManager import BrowserIdManager bid = BrowserIdManager('browser_id_manager', 'Browser Id Manager') app._setObject('browser_id_manager', bid) get_transaction().note('Added browser_id_manager') get_transaction().commit() del bid # Ensure that a session data manager exists if not hasattr(app, 'session_data_manager'): from Products.Sessions.SessionDataManager import SessionDataManager sdm = SessionDataManager('session_data_manager', title='Session Data Manager', path='/temp_folder/session_data', requestName='SESSION') app._setObject('session_data_manager', sdm) get_transaction().note('Added session_data_manager') get_transaction().commit() del sdm # Ensure that there's an Examples folder with examples. # However, make sure that if the examples have been added already # and then deleted that we don't add them again. if not hasattr(app, 'Examples') and not \ hasattr(app, '_Zope25_examples_have_been_added'):
def initialize(app): # Initialize the application # Initialize the cache: app.Control_Panel.initialize_cache() # The following items marked b/c are backward compatibility hacks # which make sure that expected system objects are added to the # bobobase. This is required because the bobobase in use may pre- # date the introduction of certain system objects such as those # which provide Lever support. # b/c: Ensure that Control Panel exists. if not hasattr(app, 'Control_Panel'): cpl=ApplicationManager() cpl._init() app._setObject('Control_Panel', cpl) get_transaction().note('Added Control_Panel') get_transaction().commit() # b/c: Ensure that a ProductFolder exists. if not hasattr(app.Control_Panel.aq_base, 'Products'): app.Control_Panel.Products=App.Product.ProductFolder() get_transaction().note('Added Control_Panel.Products') get_transaction().commit() # Ensure that a temp folder exists if not hasattr(app, 'temp_folder'): from Products.TemporaryFolder.TemporaryFolder import \ MountedTemporaryFolder tf = MountedTemporaryFolder('temp_folder','Temporary Folder') app._setObject('temp_folder', tf) get_transaction().note('Added temp_folder') get_transaction().commit() del tf # Ensure that there is a transient container in the temp folder tf = app.temp_folder if not hasattr(tf, 'session_data'): env_has = os.environ.get from Products.Transience.Transience import TransientObjectContainer addnotify = env_has('ZSESSION_ADD_NOTIFY', None) delnotify = env_has('ZSESSION_DEL_NOTIFY', None) default_limit = 1000 limit = env_has('ZSESSION_OBJECT_LIMIT', default_limit) try: limit=int(limit) if limit != default_limit: LOG('Zope Default Object Creation', INFO, ('using ZSESSION_OBJECT_LIMIT-specified max objects ' 'value of %s' % limit)) except ValueError: LOG('Zope Default Object Creation', WARNING, ('Noninteger value %s specified for ZSESSION_OBJECT_LIMIT, ' 'defaulting to %s' % (limit, default_limit))) limit = default_limit if addnotify and app.unrestrictedTraverse(addnotify, None) is None: LOG('Zope Default Object Creation', WARNING, ('failed to use nonexistent "%s" script as ' 'ZSESSION_ADD_NOTIFY' % addnotify)) addnotify=None elif addnotify: LOG('Zope Default Object Creation', INFO, 'using %s as add notification script' % addnotify) if delnotify and app.unrestrictedTraverse(delnotify, None) is None: LOG('Zope Default Object Creation', WARNING, ('failed to use nonexistent "%s" script as ' 'ZSESSION_DEL_NOTIFY' % delnotify)) delnotify=None elif delnotify: LOG('Zope Default Object Creation', INFO, 'using %s as delete notification script' % delnotify) toc = TransientObjectContainer('session_data', 'Session Data Container', addNotification = addnotify, delNotification = delnotify, limit=limit) timeout_spec = env_has('ZSESSION_TIMEOUT_MINS', '') if timeout_spec: try: timeout_spec = int(timeout_spec) except ValueError: LOG('Zope Default Object Creation', WARNING, ('"%s" is an illegal value for ZSESSION_TIMEOUT_MINS, ' 'using default timeout instead.' % timeout_spec)) else: LOG('Zope Default Object Creation', INFO, ('using ZSESSION_TIMEOUT_MINS-specified session timeout ' 'value of %s' % timeout_spec)) toc = TransientObjectContainer('session_data', 'Session Data Container', timeout_mins = timeout_spec, addNotification=addnotify, delNotification = delnotify, limit=limit) tf._setObject('session_data', toc) tf_reserved = getattr(tf, '_reserved_names', ()) if 'session_data' not in tf_reserved: tf._reserved_names = tf_reserved + ('session_data',) get_transaction().note('Added session_data to temp_folder') get_transaction().commit() del toc del addnotify del delnotify del timeout_spec del env_has del tf # Ensure that a browser ID manager exists if not hasattr(app, 'browser_id_manager'): from Products.Sessions.BrowserIdManager import BrowserIdManager bid = BrowserIdManager('browser_id_manager', 'Browser Id Manager') app._setObject('browser_id_manager', bid) get_transaction().note('Added browser_id_manager') get_transaction().commit() del bid # Ensure that a session data manager exists if not hasattr(app, 'session_data_manager'): from Products.Sessions.SessionDataManager import SessionDataManager sdm = SessionDataManager('session_data_manager', title='Session Data Manager', path='/temp_folder/session_data', requestName='SESSION') app._setObject('session_data_manager', sdm) get_transaction().note('Added session_data_manager') get_transaction().commit() del sdm # Ensure that there's an Examples folder with examples. # However, make sure that if the examples have been added already # and then deleted that we don't add them again. if not hasattr(app, 'Examples') and not \ hasattr(app, '_Zope25_examples_have_been_added'):
3,132
def delRoles(self, roles):
def delRoles(self, roles):
3,133
def __init__(self,name,data,obj):
def __init__(self,name,data,obj):
3,134
def marshal_long(n,f): return ('%s:long=%s' % (n,f))[:-1]
def marshal_long(n,f): value = '%s:long=%s' % (n, f) if value[-1] == 'L': value = value[:-1] return value
3,135
def tpValues(self): # Return a list of subobjects, used by tree tag. r=[] if hasattr(aq_base(self), 'tree_ids'): tree_ids=self.tree_ids try: tree_ids=list(tree_ids) except TypeError: pass if hasattr(tree_ids, 'sort'): tree_ids.sort() for id in tree_ids: if hasattr(self, id): r.append(self._getOb(id)) else: obj_ids=self.objectIds() obj_ids.sort() for id in obj_ids: o=self._getOb(id) if hasattr(o, 'isPrincipiaFolderish') and \ o.isPrincipiaFolderish: r.append(o) return r
def tpValues(self): # Return a list of subobjects, used by tree tag. r=[] if hasattr(aq_base(self), 'tree_ids'): tree_ids=self.tree_ids try: tree_ids=list(tree_ids) except TypeError: pass if hasattr(tree_ids, 'sort'): tree_ids.sort() for id in tree_ids: if hasattr(self, id): r.append(self._getOb(id)) else: obj_ids=self.objectIds() obj_ids.sort() for id in obj_ids: o=self._getOb(id) if hasattr(aq_base(o), 'isPrincipiaFolderish') and \ o.isPrincipiaFolderish: r.append(o) return r
3,136
def manage_FTPlist(self, REQUEST): """Directory listing for FTP. """ out=()
def manage_FTPlist(self, REQUEST): """Directory listing for FTP. """ out=()
3,137
def manage_FTPlist(self, REQUEST): """Directory listing for FTP. """ out=()
def manage_FTPlist(self, REQUEST): """Directory listing for FTP. """ out=()
3,138
def manage_FTPlist(self, REQUEST): """Directory listing for FTP. """ out=()
def manage_FTPlist(self, REQUEST): """Directory listing for FTP. """ out=()
3,139
def manage_FTPlist(self, REQUEST): """Directory listing for FTP. """ out=()
def manage_FTPlist(self, REQUEST): """Directory listing for FTP. """ out=()
3,140
def findChildren(obj,dirname=''): """ recursive walk through the object hierarchy to find all children of an object (ajung) """ lst =[] for name,child in obj.objectItems(): if child.meta_type=="Folder": lst.extend(findChildren(child,dirname+ obj.id + '/')) else: lst.append( (dirname + obj.id + "/" + name,child) ) return lst
def findChildren(obj,dirname=''): """ recursive walk through the object hierarchy to find all children of an object (ajung) """ lst = [] for name, child in obj.objectItems(): if hasattr(aq_base(child), 'isPrincipiaFolderish') and child.isPrincipiaFolderish: lst.extend(findChildren(child, dirname + obj.id + '/')) else: lst.append( (dirname + obj.id + "/" + name,child) ) return lst
3,141
def findChildren(obj,dirname=''): """ recursive walk through the object hierarchy to find all children of an object (ajung) """ lst =[] for name,child in obj.objectItems(): if child.meta_type=="Folder": lst.extend(findChildren(child,dirname+ obj.id + '/')) else: lst.append( (dirname + obj.id + "/" + name,child) ) return lst
def findChildren(obj,dirname=''): """ recursive walk through the object hierarchy to find all children of an object (ajung) """ lst =[] for name,child in obj.objectItems(): if child.meta_type=="Folder": lst.extend(findChildren(child,dirname+ obj.id + '/')) else: lst.append((dirname + obj.id + "/" + name, child)) return lst
3,142
def _cookie_list(self): cookie_list=[] for name, attrs in self.cookies.items():
def _cookie_list(self): cookie_list=[] for name, attrs in self.cookies.items():
3,143
def apply(self, classobj): """Apply security information to the given class object.""" dict = classobj.__dict__
def apply(self, classobj): """Apply security information to the given class object.""" dict = classobj.__dict__
3,144
def emitStartTag(self, node): self.emit("startTag", node.nodeName, getAttributeList(node))
def emitStartTag(self, node): self.emit("startTag", node.nodeName, getAttributeList(node))
3,145
def emitStartEndTag(self, node): self.emit("startEndTag", node.nodeName, getAttributeList(node))
def emitStartEndTag(self, node): self.emit("startEndTag", node.nodeName, getAttributeList(node))
3,146
def visitElement(self, node): if not node.hasAttributes(): self.emitElement(node) return macroName = node.getAttributeNS(ZOPE_METAL_NS, "use-macro") if macroName: slotDict = slotIndexer(node) compiledSlots = {} if slotDict: # Compile the slots for slotName, slotNode in slotDict.items(): self.pushProgram() self.visitElement(slotNode) compiledSlots[slotName] = self.popProgram() self.emit("useMacro", macroName, compiledSlots) return macroName = node.getAttributeNS(ZOPE_METAL_NS, "define-macro") if macroName: # Save macro definitions if self.macros.has_key(macroName): print "Warning: duplicate macro definition for", macroName self.pushProgram() self.compileElement(node) macro = self.popProgram() self.macros[macroName] = macro self.emit("defineMacro", macroName, macro) return slotName = node.getAttributeNS(ZOPE_METAL_NS, "define-slot") if slotName: self.pushProgram() self.compileElement(node) block = self.popProgram() self.emit("defineSlot", slotName, block) return slotName = node.getAttributeNS(ZOPE_METAL_NS, "use-slot") if slotName: self.pushProgram() self.compileElement(node) block = self.popProgram() self.emit("useSlot", slotName, block) return self.compileElement(node)
def visitElement(self, node): if not node.hasAttributes(): self.emitElement(node) else: self.expandElement(node) self.popNS() def expandElement(self, node): macroName = node.getAttributeNS(ZOPE_METAL_NS, "use-macro") if macroName: slotDict = slotIndexer(node) compiledSlots = {} if slotDict: # Compile the slots for slotName, slotNode in slotDict.items(): self.pushProgram() self.visitElement(slotNode) compiledSlots[slotName] = self.popProgram() self.emit("useMacro", macroName, compiledSlots) else: self.expandElement(node) self.popNS() def expandElement(self, node): macroName = node.getAttributeNS(ZOPE_METAL_NS, "define-macro") if macroName: # Save macro definitions if self.macros.has_key(macroName): print "Warning: duplicate macro definition for", macroName self.pushProgram() self.compileElement(node) macro = self.popProgram() self.macros[macroName] = macro self.emit("defineMacro", macroName, macro) else: self.expandElement(node) self.popNS() def expandElement(self, node): slotName = node.getAttributeNS(ZOPE_METAL_NS, "define-slot") if slotName: self.pushProgram() self.compileElement(node) block = self.popProgram() self.emit("defineSlot", slotName, block) else: self.expandElement(node) self.popNS() def expandElement(self, node): slotName = node.getAttributeNS(ZOPE_METAL_NS, "use-slot") if slotName: self.pushProgram() self.compileElement(node) block = self.popProgram() self.emit("useSlot", slotName, block) else: self.expandElement(node) self.popNS() def expandElement(self, node): self.compileElement(node)
3,147
def testVariables(self): '''Test variables''' ctxt = self.getContext() c = ctxt.vars ctxt.beginScope() ctxt.setLocal('v1', 1) ctxt.setLocal('v2', 2)
def testVariables(self): '''Test variables''' ctxt = self.getContext() ctxt.beginScope() ctxt.setLocal('v1', 1) ctxt.setLocal('v2', 2)
3,148
def setUp(self): self._old = __builtins__.__dict__.get('INSTANCE_HOME') __builtins__.INSTANCE_HOME = os.path.split( Products.ExternalMethod.tests.__file__)[0]
def setUp(self): self._old = builtinsdict.get('INSTANCE_HOME') builtinsdict['INSTANCE_HOME'] = os.path.split( Products.ExternalMethod.tests.__file__)[0]
3,149
def tearDown(self): if self._old is None: del __builtins__.INSTANCE_HOME else: __builtins__.INSTANCE_HOME = self._old
def tearDown(self): if self._old is None: del builtinsdict['INSTANCE_HOME'] else: __builtins__.INSTANCE_HOME = self._old
3,150
def tearDown(self): if self._old is None: del __builtins__.INSTANCE_HOME else: __builtins__.INSTANCE_HOME = self._old
def tearDown(self): if self._old is None: del __builtins__.INSTANCE_HOME else: __builtins__.INSTANCE_HOME = self._old
3,151
def __init__(self,
def __init__(self,
3,152
def load_binput(self): i = mloads('i' + self.read(1) + '\000\000\000') last = self.stack[-1] if getattr(last, 'id', last) is not last: last.id = self.idprefix + `i`
def load_binput(self): i = mloads('i' + self.read(1) + '\000\000\000') last = self.stack[-1] if getattr(last, 'id', last) is last: last.id = self.idprefix + `i`
3,153
def load_long_binput(self): i = mloads('i' + self.read(4)) last = self.stack[-1] if getattr(last, 'id', last) is not last: last.id = self.idprefix + `i`
def load_long_binput(self): i = mloads('i' + self.read(4)) last = self.stack[-1] if getattr(last, 'id', last) is last: last.id = self.idprefix + `i`
3,154
def save_persis(self, tag, data): v=data[2] if self.binary: v=v+'Q' else: v='P'+v return v
def save_persis(self, tag, data): v=data[2] if self.binary: v=v+'Q' else: v='P'+v return v
3,155
def save_persis(self, tag, data): v=data[2] if self.binary: v=v+'Q' else: v='P'+v return v
def save_persis(self, tag, data): v=data[2] if self.binary: v=v+'Q' else: v='P'+v return v
3,156
def read_file(name): f = open(os.path.join(here, name), 'rb') res = f.read() f.close() return res
def read_file(name): f = open(os.path.join(here, name), 'rb') res = f.read() f.close() return res
3,157
def __getitem__(self,key):
def __getitem__(self,key):
3,158
def careful_mul(env, *factors): s=None r=1 for factor in factors: try: l=len(factor) s=1 except: l=factor if s and (l*r) > 1000: raise TypeError, 'Illegal sequence repeat' r=r*factor return r
def careful_mul(env, *factors): s=None for factor in factors: try: l=len(factor) s=1 except: l=factor if s and (l*r) > 1000: raise TypeError, 'Illegal sequence repeat' r=r*factor return r
3,159
def careful_mul(env, *factors): s=None r=1 for factor in factors: try: l=len(factor) s=1 except: l=factor if s and (l*r) > 1000: raise TypeError, 'Illegal sequence repeat' r=r*factor return r
def careful_mul(env, *factors): s=None r=1 for factor in factors: try: l=len(factor) s=1 except TypeError: c=c*factor if s and c > 1000: raise TypeError, \ 'Illegal sequence repeat (too many repetitions: %d)' % c r=r*factor return r
3,160
def careful_mul(env, *factors): s=None r=1 for factor in factors: try: l=len(factor) s=1 except: l=factor if s and (l*r) > 1000: raise TypeError, 'Illegal sequence repeat' r=r*factor return r
defcareful_mul(env,*factors):s=Noner=1forfactorinfactors:try:l=len(factor)s=1except:l=factorifsand(l*r)>1000:raiseTypeError,'Illegalsequencerepeat'r=r*factorreturnr
3,161
def dav__propstat(self, name, propstat=propstat, propdesc=propdesc, join=string.join): # DAV helper method - return a propstat element indicating # property name and value for the requested property. xml_id=self.xml_namespace() propdict=self._propdict() if not propdict.has_key(name): prop=' <n:%s/>' % name error=propdesc % ('The property %s does not exist.' % name) return propstat % (xml_id, prop, '404 Not Found', error) else: item=propdict[name] name, type=item['id'], item.get('type','string') value=self.getProperty(name) if type=='tokens': value=join(value, ' ') elif type=='lines': value=join(value, '\n') # allow for xml properties attrs=item.get('meta', {}).get('__xml_attrs__', None) if attrs is not None: attrs=map(lambda n: ' %s="%s"' % n, attrs.items()) attrs=join(attrs, '') else: # quote non-xml items here? attrs='' prop=' <n:%s%s>%s</n:%s>' % (name, attrs, value, name) return propstat % (xml_id, prop, '200 OK', '')
def dav__propstat(self, name, result, propstat=propstat, propdesc=propdesc, join=string.join): xml_id=self.xml_namespace() propdict=self._propdict() if not propdict.has_key(name): prop='<n:%s xmlns:n="%s"/>\n' % (name, xml_id) code='404 Not Found' if not result.has_key(code): result[code]=[prop] else: result[code].append(prop) return else: item=propdict[name] name, type=item['id'], item.get('type','string') value=self.getProperty(name) if type=='tokens': value=join(value, ' ') elif type=='lines': value=join(value, '\n') attrs=item.get('meta', {}).get('__xml_attrs__', None) if attrs is not None: attrs=map(lambda n: ' %s="%s"' % n, attrs.items()) attrs=join(attrs, '') else: attrs='' prop='<n:%s%s xmlns:n="%s">%s</n:%s>\n' % ( name, attrs, xml_id, value, name) code='200 OK' if not result.has_key(code): result[code]=[prop] else: result[code].append(prop) return def odav__propstat(self, name, propstat=propstat, propdesc=propdesc, join=string.join): # DAV helper method - return a propstat element indicating # property name and value for the requested property. xml_id=self.xml_namespace() propdict=self._propdict() if not propdict.has_key(name): prop=' <n:%s/>' % name error=propdesc % ('The property %s does not exist.' % name) return propstat % (xml_id, prop, '404 Not Found', error) else: item=propdict[name] name, type=item['id'], item.get('type','string') value=self.getProperty(name) if type=='tokens': value=join(value, ' ') elif type=='lines': value=join(value, '\n') # allow for xml properties attrs=item.get('meta', {}).get('__xml_attrs__', None) if attrs is not None: attrs=map(lambda n: ' %s="%s"' % n, attrs.items()) attrs=join(attrs, '') else: # quote non-xml items here? attrs='' prop=' <n:%s%s>%s</n:%s>' % (name, attrs, value, name) return propstat % (xml_id, prop, '200 OK', '')
3,162
def __getitem__(self,index): if index==self._index: return self._row parent=self._parent fields=self._class(self._data[index], parent) self._index=index self._row=fields if parent is None: return fields return fields.__of__(parent)
def __getitem__(self,index): if index==self._index: return self._row parent=self._parent fields=self._class(self._data[index], parent) self._index=index self._row=fields if parent is None: return fields return fields.__of__(parent)
3,163
def evaluate(self, expression): m = re.match(r"(?s)(%s):(.*)\Z" % NAME_RE, expression) if m: type, expr = m.group(1, 2) else: type = "var" expr = expression if type == "str": return expr if type == "local": return self.locals[string.strip(expr)] if type == "global": return self.globals[string.strip(expr)] if type == "var": expr = string.strip(expr) if self.locals.has_key(expr): return self.locals[expr] else: return self.globals[expr] if type == "python": return eval(expr, self.globals, self.locals) raise TALESError("unrecognized expression: " + `expression`)
def evaluate(self, expression): m = re.match(r"(?s)(%s):(.*)\Z" % NAME_RE, expression) if m: type, expr = m.group(1, 2) else: type = "path" expr = expression if type == "str": return expr if type == "local": return self.locals[string.strip(expr)] if type == "global": return self.globals[string.strip(expr)] if type == "var": expr = string.strip(expr) if self.locals.has_key(expr): return self.locals[expr] else: return self.globals[expr] if type == "python": return eval(expr, self.globals, self.locals) raise TALESError("unrecognized expression: " + `expression`)
3,164
def evaluate(self, expression): m = re.match(r"(?s)(%s):(.*)\Z" % NAME_RE, expression) if m: type, expr = m.group(1, 2) else: type = "var" expr = expression if type == "str": return expr if type == "local": return self.locals[string.strip(expr)] if type == "global": return self.globals[string.strip(expr)] if type == "var": expr = string.strip(expr) if self.locals.has_key(expr): return self.locals[expr] else: return self.globals[expr] if type == "python": return eval(expr, self.globals, self.locals) raise TALESError("unrecognized expression: " + `expression`)
def evaluate(self, expression): m = re.match(r"(?s)(%s):(.*)\Z" % NAME_RE, expression) if m: type, expr = m.group(1, 2) else: type = "var" expr = expression if type in ("string", "str"): return expr if type == "local": return self.locals[string.strip(expr)] if type == "global": return self.globals[string.strip(expr)] if type == "var": expr = string.strip(expr) if self.locals.has_key(expr): return self.locals[expr] else: return self.globals[expr] if type == "python": return eval(expr, self.globals, self.locals) raise TALESError("unrecognized expression: " + `expression`)
3,165
def evaluate(self, expression): m = re.match(r"(?s)(%s):(.*)\Z" % NAME_RE, expression) if m: type, expr = m.group(1, 2) else: type = "var" expr = expression if type == "str": return expr if type == "local": return self.locals[string.strip(expr)] if type == "global": return self.globals[string.strip(expr)] if type == "var": expr = string.strip(expr) if self.locals.has_key(expr): return self.locals[expr] else: return self.globals[expr] if type == "python": return eval(expr, self.globals, self.locals) raise TALESError("unrecognized expression: " + `expression`)
def evaluate(self, expression): m = re.match(r"(?s)(%s):(.*)\Z" % NAME_RE, expression) if m: type, expr = m.group(1, 2) else: type = "var" expr = expression if type == "str": return expr if type in ("path", "var", "global", "local"): expr = string.strip(expr) if self.locals.has_key(expr): return self.locals[expr] else: return self.globals[expr] if type == "python": return eval(expr, self.globals, self.locals) raise TALESError("unrecognized expression: " + `expression`)
3,166
def evaluate(self, expression): m = re.match(r"(?s)(%s):(.*)\Z" % NAME_RE, expression) if m: type, expr = m.group(1, 2) else: type = "var" expr = expression if type == "str": return expr if type == "local": return self.locals[string.strip(expr)] if type == "global": return self.globals[string.strip(expr)] if type == "var": expr = string.strip(expr) if self.locals.has_key(expr): return self.locals[expr] else: return self.globals[expr] if type == "python": return eval(expr, self.globals, self.locals) raise TALESError("unrecognized expression: " + `expression`)
def evaluate(self, expression): m = re.match(r"(?s)(%s):(.*)\Z" % NAME_RE, expression) if m: type, expr = m.group(1, 2) else: type = "var" expr = expression if type == "str": return expr if type == "local": return self.locals[string.strip(expr)] if type == "global": return self.globals[string.strip(expr)] if type == "var": expr = string.strip(expr) if self.locals.has_key(expr): return self.locals[expr] else: raise TALESError("unknown variable: %s", expr) if type == "not": v = self.evaluate(expr) return not v if type == "exists": return self.locals.has_key(expr) or self.globals.has_key(expr) if type == "python": return eval(expr, self.globals, self.locals) raise TALESError("unrecognized expression: " + `expression`)
3,167
def evaluate(self, expression): m = re.match(r"(?s)(%s):(.*)\Z" % NAME_RE, expression) if m: type, expr = m.group(1, 2) else: type = "var" expr = expression if type == "str": return expr if type == "local": return self.locals[string.strip(expr)] if type == "global": return self.globals[string.strip(expr)] if type == "var": expr = string.strip(expr) if self.locals.has_key(expr): return self.locals[expr] else: return self.globals[expr] if type == "python": return eval(expr, self.globals, self.locals) raise TALESError("unrecognized expression: " + `expression`)
def evaluate(self, expression): m = re.match(r"(?s)(%s):(.*)\Z" % NAME_RE, expression) if m: type, expr = m.group(1, 2) else: type = "var" expr = expression if type == "str": return expr if type == "local": return self.locals[string.strip(expr)] if type == "global": return self.globals[string.strip(expr)] if type == "var": expr = string.strip(expr) if self.locals.has_key(expr): return self.locals[expr] else: return self.globals[expr] if type == "python": try: return eval(expr, self.globals, self.locals) except: t, v, tb = info = sys.exc_info() raise TALESError("evaluation error in %s" % `expr`, info=sys.exc_info()) raise TALESError("unrecognized expression: " + `expression`)
3,168
def _getMountRoot(self, root): sdc = root.get('folder', None) if sdc is None: sdc = root['folder'] = OFS.Folder.Folder() self._populate(sdc, root)
def _getMountRoot(self, root): sdc = root.get('folder', None) if sdc is None: sdc = root['folder'] = Folder() self._populate(sdc, root)
3,169
def db_size(self): if Globals.DatabaseVersion=='2': s=os.stat(self.db_name())[6] else: s=self._p_jar.db().getSize() if s >= 1048576.0: return '%.1fM' % (s/1048576.0) return '%.1fK' % (s/1024.0)
def db_size(self): if Globals.DatabaseVersion=='2': s=os.stat(self.db_name())[6] else: s=self._p_jar.db().getSize() if s >= 1048576.0: return '%.1fM' % (s/1048576.0) return '%.1fK' % (s/1024.0)
3,170
def rcsnapshot(self): self._v_rcs=self.refdict() self._v_rst=DateTime()
def rcsnapshot(self): self._v_rcs=self.refdict() self._v_rst=DateTime()
3,171
def rcdate(self): return self._v_rst
def rcdate(self): return self._v_rst
3,172
def rcdeltas(self): if self._v_rcs is None: self.rcsnapshot() nc=self.refdict() rc=self._v_rcs rd=[] for n, c in nc.items(): prev=rc[n] if c > prev: rd.append( (c - prev, (c, prev, n)) ) rd.sort() rd.reverse()
def rcdeltas(self): if _v_rcs is None: self.rcsnapshot() nc=self.refdict() rc=self._v_rcs rd=[] for n, c in nc.items(): prev=rc[n] if c > prev: rd.append( (c - prev, (c, prev, n)) ) rd.sort() rd.reverse()
3,173
def rcdeltas(self): if self._v_rcs is None: self.rcsnapshot() nc=self.refdict() rc=self._v_rcs rd=[] for n, c in nc.items(): prev=rc[n] if c > prev: rd.append( (c - prev, (c, prev, n)) ) rd.sort() rd.reverse()
def rcdeltas(self): if self._v_rcs is None: self.rcsnapshot() nc=self.refdict() rc=_v_rcs rd=[] for n, c in nc.items(): prev=rc[n] if c > prev: rd.append( (c - prev, (c, prev, n)) ) rd.sort() rd.reverse()
3,174
def manage_addZClass(self, id, title='', baseclasses=[], meta_type='', CreateFactory=0, REQUEST=None): """Add a Z Class """ bases=[] for b in baseclasses: if Products.meta_classes.has_key(b): bases.append(Products.meta_classes[b]) else: base=find_class(self, b) bases.append(base) Z=ZClass(id,title,bases) if meta_type: Z._zclass_.meta_type=meta_type self._setObject(id, Z) if CreateFactory and meta_type: self.manage_addDTMLMethod( id+'_addForm', id+' constructor input form', addFormDefault % {'id': id, 'meta_type': meta_type}, ) self.manage_addDTMLMethod( id+'_add', id+' constructor', addDefault % {'id': id}, ) self.manage_addPrincipiaFactory( id+'_factory', id+' factory', meta_type, id+'_addForm', ) if REQUEST is not None: return self.manage_main(self,REQUEST)
def manage_addZClass(self, id, title='', baseclasses=[], meta_type='', CreateAFactory=0, REQUEST=None): """Add a Z Class """ bases=[] for b in baseclasses: if Products.meta_classes.has_key(b): bases.append(Products.meta_classes[b]) else: base=find_class(self, b) bases.append(base) Z=ZClass(id,title,bases) if meta_type: Z._zclass_.meta_type=meta_type self._setObject(id, Z) if CreateFactory and meta_type: self.manage_addDTMLMethod( id+'_addForm', id+' constructor input form', addFormDefault % {'id': id, 'meta_type': meta_type}, ) self.manage_addDTMLMethod( id+'_add', id+' constructor', addDefault % {'id': id}, ) self.manage_addPrincipiaFactory( id+'_factory', id+' factory', meta_type, id+'_addForm', ) if REQUEST is not None: return self.manage_main(self,REQUEST)
3,175
def __init__(self, stdin, environ, response, clean=0, # "static" variables that we want to be local for speed SEQUENCE=1, DEFAULT=2, RECORD=4, RECORDS=8, REC=12, # RECORD|RECORDS EMPTY=16, CONVERTED=32, hasattr=hasattr, getattr=getattr, setattr=setattr, search_type=regex.compile( ':[a-zA-Z][a-zA-Z0-9_]+$' ).search, rfind=string.rfind, ): # Avoid the overhead of scrubbing the environment in the # case of request cloning for traversal purposes. If the # clean flag is set, we know we can use the passed in # environ dict directly.
def __init__(self, stdin, environ, response, clean=0, # "static" variables that we want to be local for speed SEQUENCE=1, DEFAULT=2, RECORD=4, RECORDS=8, REC=12, # RECORD|RECORDS EMPTY=16, CONVERTED=32, hasattr=hasattr, getattr=getattr, setattr=setattr, search_type=regex.compile( ':[a-zA-Z][a-zA-Z0-9_]+$' ).search, rfind=string.rfind, ): # Avoid the overhead of scrubbing the environment in the # case of request cloning for traversal purposes. If the # clean flag is set, we know we can use the passed in # environ dict directly.
3,176
def near(self, x, distance = 1): '''\ near(rl, distance = 1) Returns a ResultList containing documents which contain''' result = self.__class__() for key, v in self.items(): try: value = x[key] except KeyError: value = None if value is None: continue
def near(self, x, distance = 1): '''\ near(rl, distance = 1) Returns a ResultList containing documents which contain''' result = self.__class__() for key, v in self.items(): try: value = x[key] except KeyError: value = None if value is None: continue
3,177
def render(self, md): args=self.args have_arg=args.has_key name=self.__name__
def render(self, md): args=self.args have_arg=args.has_key name=self.__name__
3,178
def render(self, md): args=self.args have_arg=args.has_key name=self.__name__
def render(self, md): args=self.args have_arg=args.has_key name=self.__name__
3,179
def render(self, md): args=self.args have_arg=args.has_key name=self.__name__
def render(self, md): args=self.args have_arg=args.has_key name=self.__name__
3,180
def tpValues(self):
def tpValues(self):
3,181
def manage_edit(self, title, module, function, REQUEST=None): """Change the external method
def manage_edit(self, title, module, function, REQUEST=None): """Change the external method
3,182
def redirect(self, location, status=302): """Cause a redirection without raising an error""" self.setStatus(status) self.setHeader('Location', location)
def redirect(self, location, status=302, lock=0): """Cause a redirection without raising an error""" self.setStatus(status) self.setHeader('Location', location)
3,183
def redirect(self, location, status=302): """Cause a redirection without raising an error""" self.setStatus(status) self.setHeader('Location', location)
def redirect(self, location, status=302): """Cause a redirection without raising an error""" self.setStatus(status) self.setHeader('Location', location)
3,184
def new_version(self, _intending=regex.compile("[.]?[0-9]+$").search, ): # Return a new version number based on the existing version. v=str(self.version) if not v: return '1.0' if _intending(v) < 0: return v l=rfind(v,'.') return v[:l+1]+str(1+atoi(v[l+1:]))
def new_version(self, _intending=regex.compile("[.]?[0-9]+$").search, ): # Return a new version number based on the existing version. v=str(self.version) if not v: return '1.0' if _intending(v) < 0: return v l=rfind(v,'.') return v[:l+1]+str(1+atoi(v[l+1:]))
3,185
def manage_addPropertySheet(self, id, ns): """ """ md={'xmlns':ns} ps=PropertySheet(id, md) self.addPropertySheet(ps) return 'OK'
def manage_addPropertySheet(self, id, ns, REQUEST=None): """ """ md={'xmlns':ns} ps=PropertySheet(id, md) self.addPropertySheet(ps) return 'OK'
3,186
def manage_addPropertySheet(self, id, ns): """ """ md={'xmlns':ns} ps=PropertySheet(id, md) self.addPropertySheet(ps) return 'OK'
def manage_addPropertySheet(self, id, ns): """ """ md={'xmlns':ns} ps= self.PropertySheetClass(id, md) self.addPropertySheet(ps) return 'OK'
3,187
def manage_addPropertySheet(self, id, ns): """ """ md={'xmlns':ns} ps=PropertySheet(id, md) self.addPropertySheet(ps) return 'OK'
def manage_addPropertySheet(self, id, ns): """ """ md={'xmlns':ns} ps=PropertySheet(id, md) self.addPropertySheet(ps) return 'OK'
3,188
def manage_options(self): """Return a manage option data structure for me instance """ try: r=self.REQUEST except: r=None if r is None: pre='../' else: pre=r['URL'] for i in (1,2): l=pre.rfind('/') if l >= 0: pre=pre[:l] pre=pre+'/'
def manage_options(self): """Return a manage option data structure for me instance """ try: r=self.REQUEST except: r=None if r is None: pre='../' else: pre=r['URLPATH0'] for i in (1,2): l=pre.rfind('/') if l >= 0: pre=pre[:l] pre=pre+'/'
3,189
def test_dont_break_getPhysicalPath(self): # see http://www.zope.org/Collectors/Zope/2057 item = SimpleItem() self.assertEqual(item.getPhysicalPath(), ('',)) self.assertEqual(item.getPhysicalPath(), makerequest(item).getPhysicalPath())
def test_dont_break_getPhysicalPath(self): # see http://www.zope.org/Collectors/Zope/2057 item = SimpleItem() self.assertEqual(item.getPhysicalPath(), ('',)) self.assertEqual(item.getPhysicalPath(), makerequest(item).getPhysicalPath())
3,190
def __init__(self, smtpHost, smtpPort, localHost="localhost", timeout=1): self.conn = socket(AF_INET, SOCK_STREAM) self.conn.connect(smtpHost, smtpPort) self.timeout=timeout self.fd=self.conn.fileno() self.conn.send("helo "+localHost+"\r\n") while 1: if not self._check(): break
def __init__(self, smtpHost, smtpPort, localHost="localhost", timeout=1): self.conn = socket(AF_INET, SOCK_STREAM) self.conn.connect(smtpHost, smtpPort) self.timeout=timeout self.fd=self.conn.fileno() self.conn.send("helo "+localHost+"\015\012") while 1: if not self._check(): break
3,191
def _check(self, lev='250'): line = self.getLine() if not line: return 0 #can't check an empty line, eh? try: code=string.atoi(line[:3]) except: raise smtpError, "Cannot convert line from SMTP: %s" % line
def _check(self, lev='250'): line = self.getLine() if not line: return 0 #can't check an empty line, eh? try: code=string.atoi(line[:3]) except: raise smtpError, "Cannot convert line from SMTP: %s" % line
3,192
def send(self, mfrom, mto, subj='No Subject', body='Blank Message'): self.conn.send("mail from:<%s>\n" % mfrom) self._check() if type(mto) in [types.ListType, types.TupleType]: for person in mto: self.conn.send("rcpt to:<%s>\n" % person) self._check() else: self.conn.send("rcpt to:<%s>\n" % mto) self._check() self.conn.send("data\n") self._check() self.conn.send(body) self.conn.send("\n.\n") self._check('354')
def send(self, mfrom, mto, subj='No Subject', body='Blank Message'): self.conn.send("mail from:<%s>\015\012" % mfrom) self._check() if type(mto) in [types.ListType, types.TupleType]: for person in mto: self.conn.send("rcpt to:<%s>\n" % person) self._check() else: self.conn.send("rcpt to:<%s>\n" % mto) self._check() self.conn.send("data\n") self._check() self.conn.send(body) self.conn.send("\n.\n") self._check('354')
3,193
def send(self, mfrom, mto, subj='No Subject', body='Blank Message'): self.conn.send("mail from:<%s>\n" % mfrom) self._check() if type(mto) in [types.ListType, types.TupleType]: for person in mto: self.conn.send("rcpt to:<%s>\n" % person) self._check() else: self.conn.send("rcpt to:<%s>\n" % mto) self._check() self.conn.send("data\n") self._check() self.conn.send(body) self.conn.send("\n.\n") self._check('354')
def send(self, mfrom, mto, subj='No Subject', body='Blank Message'): self.conn.send("mail from:<%s>\n" % mfrom) self._check() if type(mto) in [types.ListType, types.TupleType]: for person in mto: self.conn.send("rcpt to:<%s>\015\012" % person) self._check() else: self.conn.send("rcpt to:<%s>\n" % mto) self._check() self.conn.send("data\n") self._check() self.conn.send(body) self.conn.send("\n.\n") self._check('354')
3,194
def send(self, mfrom, mto, subj='No Subject', body='Blank Message'): self.conn.send("mail from:<%s>\n" % mfrom) self._check() if type(mto) in [types.ListType, types.TupleType]: for person in mto: self.conn.send("rcpt to:<%s>\n" % person) self._check() else: self.conn.send("rcpt to:<%s>\n" % mto) self._check() self.conn.send("data\n") self._check() self.conn.send(body) self.conn.send("\n.\n") self._check('354')
def send(self, mfrom, mto, subj='No Subject', body='Blank Message'): self.conn.send("mail from:<%s>\n" % mfrom) self._check() if type(mto) in [types.ListType, types.TupleType]: for person in mto: self.conn.send("rcpt to:<%s>\n" % person) self._check() else: self.conn.send("rcpt to:<%s>\015\012" % mto) self._check() self.conn.send("data\n") self._check() self.conn.send(body) self.conn.send("\n.\n") self._check('354')
3,195
def send(self, mfrom, mto, subj='No Subject', body='Blank Message'): self.conn.send("mail from:<%s>\n" % mfrom) self._check() if type(mto) in [types.ListType, types.TupleType]: for person in mto: self.conn.send("rcpt to:<%s>\n" % person) self._check() else: self.conn.send("rcpt to:<%s>\n" % mto) self._check() self.conn.send("data\n") self._check() self.conn.send(body) self.conn.send("\n.\n") self._check('354')
def send(self, mfrom, mto, subj='No Subject', body='Blank Message'): self.conn.send("mail from:<%s>\n" % mfrom) self._check() if type(mto) in [types.ListType, types.TupleType]: for person in mto: self.conn.send("rcpt to:<%s>\n" % person) self._check() else: self.conn.send("rcpt to:<%s>\n" % mto) self._check() self.conn.send("data\015\012") self._check() self.conn.send(body) self.conn.send("\n.\n") self._check('354')
3,196
def send(self, mfrom, mto, subj='No Subject', body='Blank Message'): self.conn.send("mail from:<%s>\n" % mfrom) self._check() if type(mto) in [types.ListType, types.TupleType]: for person in mto: self.conn.send("rcpt to:<%s>\n" % person) self._check() else: self.conn.send("rcpt to:<%s>\n" % mto) self._check() self.conn.send("data\n") self._check() self.conn.send(body) self.conn.send("\n.\n") self._check('354')
def send(self, mfrom, mto, subj='No Subject', body='Blank Message'): self.conn.send("mail from:<%s>\n" % mfrom) self._check() if type(mto) in [types.ListType, types.TupleType]: for person in mto: self.conn.send("rcpt to:<%s>\n" % person) self._check() else: self.conn.send("rcpt to:<%s>\n" % mto) self._check() self.conn.send("data\n") self._check() self.conn.send(body) self.conn.send("\015\012.\015\012") self._check('354')
3,197
def _close(self): self.conn.send("quit\n") self.conn.close()
def _close(self): self.conn.send("quit\015\012") self.conn.close()
3,198
def main(): user, password = 'superuser', '123' opts, args = getopt.getopt(sys.argv[1:], 'p:u:v9') global verbose global old for o, v in opts: if o=='-p': d, f = os.path.split(v) if f=='ZPublisher': sys.path.insert(0,d) else: sys.path.insert(0,v) elif o=='-u': v = string.split(v,':') user, password = v[0], string.join(v[1:],':') elif o=='-v': verbose=1 elif o=='-9': old=1 if not args: print sys.argv[0]+usage sys.exit(1) url=args[0] files=args[1:] import ZPublisher.Client global ServerError ServerError=ZPublisher.Client.ServerError object=ZPublisher.Client.Object(url, username=user, password=password) for f in files: upload_file(object, f)
def main(): user, password = 'superuser', '123' opts, args = getopt.getopt(sys.argv[1:], 'p:u:DIv9') global verbose global old for o, v in opts: if o=='-p': d, f = os.path.split(v) if f=='ZPublisher': sys.path.insert(0,d) else: sys.path.insert(0,v) elif o=='-u': v = string.split(v,':') user, password = v[0], string.join(v[1:],':') elif o=='-v': verbose=1 elif o=='-9': old=1 if not args: print sys.argv[0]+usage sys.exit(1) url=args[0] files=args[1:] import ZPublisher.Client global ServerError ServerError=ZPublisher.Client.ServerError object=ZPublisher.Client.Object(url, username=user, password=password) for f in files: upload_file(object, f)
3,199