bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def __sub__(self,other): """Either a DateTime or a number may be subtracted from a DateTime, however, a DateTime may not be subtracted from a number.""" if hasattr(other, '_d'): my_t = self._t + _tzoffset(self._tz, self._t) ob_t = other._t + _tzoffset(other._tz, other._t) return (my_t - ob_t) / 86400.0 else: return self.__add__(-(other))
def __sub__(self,other): """Either a DateTime or a number may be subtracted from a DateTime, however, a DateTime may not be subtracted from a number.""" if hasattr(other, '_d'): if 0: my_t = self._t + _tzoffset(self._tz, self._t) ob_t = other._t + _tzoffset(other._tz, other._t) return (my_t - ob_t) / 86400.0 return self._d - other._d else: return self.__add__(-(other))
1,900
def tag(height=None, width=None, alt=None, scale=0, xscale=0, yscale=0, **args): """ This method returns a string which contains an HTML IMG tag reference to the image.
def tag(height=None, width=None, alt=None, scale=0, xscale=0, yscale=0, **args): """ This method returns a string which contains an HTML IMG tag reference to the image.
1,901
def install_tempfolder_and_sdc(self): app = self.getApp() from Products.ZODBMountPoint.MountedObject import manage_addMounts,\ MountedObject from Products.ZODBMountPoint.MountedObject import getConfiguration as \ getDBTabConfiguration
def install_tempfolder_and_sdc(self): app = self.getApp() from Products.ZODBMountPoint.MountedObject import manage_addMounts,\ MountedObject from Products.ZODBMountPoint.MountedObject import getConfiguration as \ getDBTabConfiguration
1,902
def index_object(self, i, obj, tupleType=type(()), dictType=type({}), callable=callable): """Recompute index data for data with ids >= start. if 'obj' is passed in, it is indexed instead of _data[i]"""
def index_object(self, i, obj, tupleType=type(()), dictType=type({}), callable=callable): """Recompute index data for data with ids >= start. if 'obj' is passed in, it is indexed instead of _data[i]"""
1,903
def _updateProperty(self, id, value): # Update the value of an existing property. If value is a string, # an attempt will be made to convert the value to the type of the # existing property. if not self.hasProperty(id): raise 'Bad Request', 'The property %s does not exist.' % id if type(value)==type(''): proptype=self.propertyInfo(id).get('type', 'string') if type_converters.has_key(proptype): value=type_converters[proptype](value) setattr(self.v_self(), id, value)
def _updateProperty(self, id, value, meta=None): # Update the value of an existing property. If value is a string, # an attempt will be made to convert the value to the type of the # existing property. if not self.hasProperty(id): raise 'Bad Request', 'The property %s does not exist.' % id if type(value)==type(''): proptype=self.propertyInfo(id).get('type', 'string') if type_converters.has_key(proptype): value=type_converters[proptype](value) setattr(self.v_self(), id, value)
1,904
def _updateProperty(self, id, value): # Update the value of an existing property. If value is a string, # an attempt will be made to convert the value to the type of the # existing property. if not self.hasProperty(id): raise 'Bad Request', 'The property %s does not exist.' % id if type(value)==type(''): proptype=self.propertyInfo(id).get('type', 'string') if type_converters.has_key(proptype): value=type_converters[proptype](value) setattr(self.v_self(), id, value)
def _updateProperty(self, id, value): # Update the value of an existing property. If value is a string, # an attempt will be made to convert the value to the type of the # existing property. if not self.hasProperty(id): raise 'Bad Request', 'The property %s does not exist.' % id if type(value)==type(''): proptype=self.propertyInfo(id).get('type', 'string') if type_converters.has_key(proptype): value=type_converters[proptype](value) setattr(self.v_self(), id, value)
1,905
def getRolesInContext(self, object): """Return the list of roles assigned to the user, including local roles assigned in context of the passed in object.""" name=self.getUserName() roles=self.getRoles() local={} object=getattr(object, 'aq_inner', object) while 1: local_roles = getattr(object, '__ac_local_roles__', None) if local_roles: if callable(local_roles): local_roles=local_roles() dict=local_roles or {} for r in dict.get(name, []): local[r]=1 inner = getattr(object, 'aq_inner', object) parent = getattr(inner, 'aq_parent', None) if parent: object = parent continue if hasattr(object, 'im_self'): object=object.im_self object=getattr(object, 'aq_inner', object) continue break roles=list(roles) + local.keys() return roles
def getRolesInContext(self, object): """Return the list of roles assigned to the user, including local roles assigned in context of the passed in object.""" name=self.getUserName() roles=self.getRoles() local={} object=getattr(object, 'aq_inner', object) while 1: local_roles = getattr(object, '__ac_local_roles__', None) if local_roles: if callable(local_roles): local_roles=local_roles() dict=local_roles or {} for r in dict.get(name, []): local[r]=1 inner = getattr(object, 'aq_inner', object) parent = getattr(inner, 'aq_parent', None) if parent is not None: object = parent continue if hasattr(object, 'im_self'): object=object.im_self object=getattr(object, 'aq_inner', object) continue break roles=list(roles) + local.keys() return roles
1,906
def __setstate__(self, state): Globals.Persistent.__setstate__(self, state) if self.connection_string: try: self.connect(self.connection_string) except: logger.error('Error connecting to relational database.', exc_info=exc_info())
def __setstate__(self, state): Globals.Persistent.__setstate__(self, state) if self.connection_string: try: self.connect(self.connection_string) except: logger.error('Error connecting to relational database.', exc_info=exc_info())
1,907
def manage_close_connection(self, REQUEST=None): " " try: if hasattr(self,'_v_database_connection'): self._v_database_connection.close() except: logger.error('Error closing relational database connection.', error=exc_info()) self._v_connected='' if REQUEST is not None: return self.manage_main(self, REQUEST)
def manage_close_connection(self, REQUEST=None): " " try: if hasattr(self,'_v_database_connection'): self._v_database_connection.close() except: logger.error('Error closing relational database connection.', exc_info=True) self._v_connected='' if REQUEST is not None: return self.manage_main(self, REQUEST)
1,908
def manage_edit(self, meta_type='', icon='', file='', REQUEST=None): """Set basic item properties. """ klass=self.aq_inner.aq_parent.aq_parent._zclass_ if meta_type: self.setClassAttr('meta_type', meta_type) if file: # and hasattr(file, 'content_type'): if hasattr(klass, 'ziconImage'): klass.ziconImage.manage_upload(file) else: self.setClassAttr('ziconImage', OFS.Image.Image('ziconImage','',file)) if not icon: self.setClassAttr('icon', REQUEST['URL1']+'/ziconImage')
def manage_edit(self, meta_type='', icon='', file='', REQUEST=None): """Set basic item properties. """ if meta_type: self.setClassAttr('meta_type', meta_type) if file: # and hasattr(file, 'content_type'): if hasattr(klass, 'ziconImage'): klass.ziconImage.manage_upload(file) else: self.setClassAttr('ziconImage', OFS.Image.Image('ziconImage','',file)) if not icon: self.setClassAttr('icon', REQUEST['URL1']+'/ziconImage')
1,909
def manage_edit(self, meta_type='', icon='', file='', REQUEST=None): """Set basic item properties. """ klass=self.aq_inner.aq_parent.aq_parent._zclass_ if meta_type: self.setClassAttr('meta_type', meta_type) if file: # and hasattr(file, 'content_type'): if hasattr(klass, 'ziconImage'): klass.ziconImage.manage_upload(file) else: self.setClassAttr('ziconImage', OFS.Image.Image('ziconImage','',file)) if not icon: self.setClassAttr('icon', REQUEST['URL1']+'/ziconImage')
def manage_edit(self, meta_type='', icon='', file='', REQUEST=None): """Set basic item properties. """ klass=self.aq_inner.aq_parent.aq_parent._zclass_ if meta_type: self.setClassAttr('meta_type', meta_type) if file: # and hasattr(file, 'content_type'): __traceback_info__=file image=self.getClassAttr('ziconImage', None) if image is None: self.setClassAttr('ziconImage', OFS.Image.Image('ziconImage','',file)) if not icon: self.setClassAttr('icon', REQUEST['URL1']+'/ziconImage')
1,910
def manage_edit(self, meta_type='', icon='', file='', REQUEST=None): """Set basic item properties. """ klass=self.aq_inner.aq_parent.aq_parent._zclass_ if meta_type: self.setClassAttr('meta_type', meta_type) if file: # and hasattr(file, 'content_type'): if hasattr(klass, 'ziconImage'): klass.ziconImage.manage_upload(file) else: self.setClassAttr('ziconImage', OFS.Image.Image('ziconImage','',file)) if not icon: self.setClassAttr('icon', REQUEST['URL1']+'/ziconImage')
def manage_edit(self, meta_type='', icon='', file='', REQUEST=None): """Set basic item properties. """ klass=self.aq_inner.aq_parent.aq_parent._zclass_ if meta_type: self.setClassAttr('meta_type', meta_type) if file: # and hasattr(file, 'content_type'): if hasattr(klass, 'ziconImage'): klass.ziconImage.manage_upload(file) else: self.setClassAttr('ziconImage', OFS.Image.Image('ziconImage','',file)) if not icon: self.setClassAttr('icon', REQUEST['URL1']+'/ziconImage')
1,911
def manage_edit(self, meta_type='', icon='', file='', REQUEST=None): """Set basic item properties. """ klass=self.aq_inner.aq_parent.aq_parent._zclass_ if meta_type: self.setClassAttr('meta_type', meta_type) if file: # and hasattr(file, 'content_type'): if hasattr(klass, 'ziconImage'): klass.ziconImage.manage_upload(file) else: self.setClassAttr('ziconImage', OFS.Image.Image('ziconImage','',file)) if not icon: self.setClassAttr('icon', REQUEST['URL1']+'/ziconImage')
def manage_edit(self, meta_type='', icon='', file='', REQUEST=None): """Set basic item properties. """ klass=self.aq_inner.aq_parent.aq_parent._zclass_ if meta_type: self.setClassAttr('meta_type', meta_type) if file: # and hasattr(file, 'content_type'): if hasattr(klass, 'ziconImage'): klass.ziconImage.manage_upload(file) else: self.setClassAttr('ziconImage', OFS.Image.Image('ziconImage','',file)) if not icon: self.setClassAttr('icon', REQUEST['URL1']+'/ziconImage')
1,912
def __of__(self, parent): return _ziconImage()
def __of__(self, parent): return _ziconImage()
1,913
def icon_(self): icon=self.aq_inner.aq_parent.aq_parent._zclass_.icon
def icon_(self): icon=self.aq_inner.aq_parent.aq_parent._zclass_.icon
1,914
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
1,915
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
1,916
def __init__(self,
def __init__(self,
1,917
def manage_profile_stats(self, sort='time', limit=200): """Return profile data if available""" stats=getattr(sys, '_ps_', None) if stats is None: return None output=StringIO() stdout=sys.stdout sys.stdout=output stats.strip_dirs().sort_stats(sort).print_stats(limit) sys.stdout.flush() sys.stdout=stdout return output.getvalue()
def manage_profile_stats(self, sort='time', limit=200, stripDirs=1, mode='stats'): """Return profile data if available""" stats=getattr(sys, '_ps_', None) if stats is None: return None output=StringIO() stdout=sys.stdout sys.stdout=output stats.strip_dirs().sort_stats(sort).print_stats(limit) sys.stdout.flush() sys.stdout=stdout return output.getvalue()
1,918
def manage_profile_stats(self, sort='time', limit=200): """Return profile data if available""" stats=getattr(sys, '_ps_', None) if stats is None: return None output=StringIO() stdout=sys.stdout sys.stdout=output stats.strip_dirs().sort_stats(sort).print_stats(limit) sys.stdout.flush() sys.stdout=stdout return output.getvalue()
def manage_profile_stats(self, sort='time', limit=200): """Return profile data if available""" stats=getattr(sys, '_ps_', None) if stats is None: return None output=StringIO() stdout=sys.stdout sys.stdout=output getattr(stats,'print_%s' % mode)(limit) sys.stdout.flush() sys.stdout=stdout return output.getvalue()
1,919
def root_config(section): from ZConfig import ConfigurationError here = os.path.dirname(os.path.abspath(__file__)) swhome = os.path.dirname(os.path.dirname(here)) section.softwarehome = swhome section.zopehome = os.path.dirname(os.path.dirname(swhome)) if section.cgi_environment is None: section.cgi_environment = {} if section.clienthome is None: section.clienthome = os.path.join(section.instancehome, "var") # set up defaults for pid_filename and lock_filename if they're # not in the config if section.pid_filename is None: section.pid_filename = os.path.join(section.clienthome, 'Z2.pid') if section.lock_filename is None: section.lock_filename = os.path.join(section.clienthome, 'Z2.lock') if not section.databases: section.databases = getDefaultDatabaseFactories(section) mount_factories = {} # { name -> factory} mount_points = {} # { virtual path -> name } dup_err = ('Invalid configuration: ZODB databases named "%s" and "%s" are ' 'both configured to use the same mount point, named "%s"') for database in section.databases: points = database.getVirtualMountPaths() name = database.config.getSectionName() mount_factories[name] = database for point in points: if mount_points.has_key(point): raise ConfigurationError(dup_err % (mount_points[point], name, point)) mount_points[point] = name from DBTab.DBTab import DBTab section.dbtab = DBTab(mount_factories, mount_points) return section
def root_config(section): from ZConfig import ConfigurationError here = os.path.dirname(os.path.abspath(__file__)) swhome = os.path.dirname(os.path.dirname(here)) section.softwarehome = swhome section.zopehome = os.path.dirname(os.path.dirname(swhome)) if section.cgi_environment is None: section.cgi_environment = {} if section.clienthome is None: section.clienthome = os.path.join(section.instancehome, "var") # set up defaults for pid_filename and lock_filename if they're # not in the config if section.pid_filename is None: section.pid_filename = os.path.join(section.clienthome, 'Z2.pid') if section.lock_filename is None: section.lock_filename = os.path.join(section.clienthome, 'Z2.lock') if not section.databases: section.databases = getDefaultDatabaseFactories(section) mount_factories = {} # { name -> factory} mount_points = {} # { virtual path -> name } dup_err = ('Invalid configuration: ZODB databases named "%s" and "%s" are ' 'both configured to use the same mount point, named "%s"') for database in section.databases: points = database.getVirtualMountPaths() name = database.config.getSectionName() mount_factories[name] = database for point in points: if mount_points.has_key(point): raise ConfigurationError(dup_err % (mount_points[point], name, point)) mount_points[point] = name from DBTab.DBTab import DBTab section.dbtab = DBTab(mount_factories, mount_points) return section
1,920
def open(self): DB = self.createDB() if self.config.connection_class: # set the connection class DB.klass = self.config.connection_class print DB, DB.klass if self.config.class_factory is not None: DB.setClassFactory(self.config.class_factory) from ZODB.ActivityMonitor import ActivityMonitor DB.setActivityMonitor(ActivityMonitor()) return DB
def open(self): DB = self.createDB() if self.config.connection_class: # set the connection class DB.klass = self.config.connection_class if self.config.class_factory is not None: DB.setClassFactory(self.config.class_factory) from ZODB.ActivityMonitor import ActivityMonitor DB.setActivityMonitor(ActivityMonitor()) return DB
1,921
def getSectionName(self): return self.name
def getSectionName(self): return self.name
1,922
def getSectionName(self): return self.name
def getSectionName(self): return self.name
1,923
def manage_addImage(self,id,file,title='',REQUEST=None): """ Add a new Image object. Creates a new Image object 'id' with the contents of 'file'. """ id, title = cookId(id, title, file) self._setObject(id, Image(id,title,file)) if REQUEST is not None: return self.manage_main(self,REQUEST) return id
def manage_addImage(self,id,file,title='',REQUEST=None): """ Add a new Image object. Creates a new Image object 'id' with the contents of 'file'. """ id, title = cookId(id, title, file) self._setObject(id, Image(id,title,file)) if REQUEST is not None: return self.manage_main(self,REQUEST) return id
1,924
def tabs_path_default(self, REQUEST, # Static var unquote=urllib.unquote, ): steps = REQUEST._steps[:-1] script = REQUEST['BASEPATH1'] linkpat = '<a href="%s/manage_workspace">%s</a>' out = [] url = linkpat % (script, '&nbsp;/') if not steps: return url last = steps.pop() for step in steps: script = '%s/%s' % (script, step) out.append(linkpat % (script, unquote(step))) out.append(unquote(last)) return '%s&nbsp;%s' % (url, join(out,'&nbsp;/&nbsp;'))
def tabs_path_default(self, REQUEST, # Static var unquote=urllib.unquote, ): steps = REQUEST._steps[:-1] script = REQUEST['BASEPATH1'] linkpat = '<a href="%s/manage_workspace">%s</a>' out = [] url = linkpat % (script, '&nbsp;/') if not steps: return url last = steps.pop() for step in steps: script = '%s/%s' % (script, step) out.append(linkpat % (script, unquote(step))) out.append(unquote(last)) return '%s&nbsp;%s' % (url, join(out,'&nbsp;/&nbsp;'))
1,925
def removeForwardIndexEntry(self, entry, documentId): """Take the entry provided and remove any reference to documentId in its entry in the index. """ indexRow = self._index.get(entry, _marker) if indexRow is not _marker: try: indexRow.remove(documentId) if not indexRow: del self._index[entry] self._length.change(-1)
def removeForwardIndexEntry(self, entry, documentId): """Take the entry provided and remove any reference to documentId in its entry in the index. """ indexRow = self._index.get(entry, _marker) if indexRow is not _marker: try: indexRow.remove(documentId) if not indexRow: try: del self._index[entry] except KeyError: pass if isinstance(self.__len__, BTrees.Length.Length): self._length = self.__len__ del self.__len__ self._length.change(-1)
1,926
def insertForwardIndexEntry(self, entry, documentId): """Take the entry provided and put it in the correct place in the forward index.
def insertForwardIndexEntry(self, entry, documentId): """Take the entry provided and put it in the correct place in the forward index.
1,927
def _get__roles__(self): return getattr(self.aq_parent, '%s__roles__' % self.__name__)
def _get__roles__(self): return getattr(self.aq_parent, '%s__roles__' % self.__name__)
1,928
def parseString(self, s): from cStringIO import cStringIO self.ParseStream(cStringIO(s))
def parseString(self, s): from cStringIO import cStringIO self.ParseStream(cStringIO(s))
1,929
def _exec(self, bound_names, args, kw): """Call a Page Template""" bound_names['options'] = kw
def _exec(self, bound_names, args, kw): """Call a Page Template""" bound_names['options'] = kw
1,930
def __getitem__(self,key):
def __getitem__(self,key):
1,931
def test_structure_replace_with_messageid_and_i18nname(self): program, macros = self._compile( '<div i18n:translate="" >' '<span tal:replace="structure foo" i18n:name="foo_name"/>' '</div>') self._check(program, '<div>FOOVALUE</div>\n')
def test_structure_replace_with_messageid_and_i18nname(self): program, macros = self._compile( '<div i18n:translate="" >' '<span tal:replace="structure foo" i18n:name="foo_name"' ' i18n:translate=""/>' '</div>') self._check(program, '<div>FOOVALUE</div>\n')
1,932
def test_complex_replace_with_messageid_and_i18nname(self): program, macros = self._compile( '<div i18n:translate="" >' '<em i18n:name="foo_name">' '<span tal:replace="foo"/>' '</em>' '</div>') self._check(program, '<div>FOOVALUE</div>\n')
def test_complex_replace_with_messageid_and_i18nname(self): program, macros = self._compile( '<div i18n:translate="" >' '<em i18n:name="foo_name" tal:omit-tag="">' '<span tal:replace="foo"/>' '</em>' '</div>') self._check(program, '<div>FOOVALUE</div>\n')
1,933
def test_translate_static_text_as_dynamic_from_bytecode(self): program = [('version', '1.5'),
def test_translate_static_text_as_dynamic_from_bytecode(self): program = [('version', '1.5'),
1,934
def _getCollectingTranslationDomain(self): class CollectingTranslationService(DummyTranslationService): data = []
def _getCollectingTranslationDomain(self): class CollectingTranslationService(DummyTranslationService): data = []
1,935
def test_for_correct_msgids(self): xlatdmn = self._getCollectingTranslationDomain() result = StringIO() program, macros = self._compile( '<div i18n:translate="">This is text for ' '<span i18n:translate="" tal:content="bar" ' 'i18n:name="bar_name"/>.</div>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = list(xlatdmn.data) msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual('BaRvAlUe', msgids[0][0]) self.assertEqual('This is text for ${bar_name}.', msgids[1][0]) self.assertEqual({'bar_name': '<span>BARVALUE</span>'}, msgids[1][1]) self.assertEqual( '<div>THIS IS TEXT FOR <span>BARVALUE</span>.</div>\n', result.getvalue())
def test_for_correct_msgids(self): self.engine.translationDomain.clearMsgids() result = StringIO() program, macros = self._compile( '<div i18n:translate="">This is text for ' '<span i18n:translate="" tal:content="bar" ' 'i18n:name="bar_name"/>.</div>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = list(xlatdmn.data) msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual('BaRvAlUe', msgids[0][0]) self.assertEqual('This is text for ${bar_name}.', msgids[1][0]) self.assertEqual({'bar_name': '<span>BARVALUE</span>'}, msgids[1][1]) self.assertEqual( '<div>THIS IS TEXT FOR <span>BARVALUE</span>.</div>\n', result.getvalue())
1,936
def test_for_correct_msgids(self): xlatdmn = self._getCollectingTranslationDomain() result = StringIO() program, macros = self._compile( '<div i18n:translate="">This is text for ' '<span i18n:translate="" tal:content="bar" ' 'i18n:name="bar_name"/>.</div>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = list(xlatdmn.data) msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual('BaRvAlUe', msgids[0][0]) self.assertEqual('This is text for ${bar_name}.', msgids[1][0]) self.assertEqual({'bar_name': '<span>BARVALUE</span>'}, msgids[1][1]) self.assertEqual( '<div>THIS IS TEXT FOR <span>BARVALUE</span>.</div>\n', result.getvalue())
def test_for_correct_msgids(self): xlatdmn = self._getCollectingTranslationDomain() result = StringIO() program, macros = self._compile( '<div i18n:translate="">This is text for ' '<span i18n:translate="" tal:content="bar" ' 'i18n:name="bar_name"/>.</div>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = self.engine.translationDomain.getMsgids('default') msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual('BaRvAlUe', msgids[0][0]) self.assertEqual('This is text for ${bar_name}.', msgids[1][0]) self.assertEqual({'bar_name': '<span>BARVALUE</span>'}, msgids[1][1]) self.assertEqual( '<div>THIS IS TEXT FOR <span>BARVALUE</span>.</div>\n', result.getvalue())
1,937
def test_for_raw_msgids(self): # Test for Issue 314: i18n:translate removes line breaks from # <pre>...</pre> contents # HTML mode xlatdmn = self._getCollectingTranslationDomain() result = StringIO() program, macros = self._compile( '<div i18n:translate=""> This is text\n' ' \tfor\n div. </div>' '<pre i18n:translate=""> This is text\n' ' <b>\tfor</b>\n pre. </pre>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = list(xlatdmn.data) msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual(' This is text\n <b>\tfor</b>\n pre. ', msgids[0][0]) self.assertEqual('This is text for div.', msgids[1][0]) self.assertEqual( '<div>THIS IS TEXT FOR DIV.</div>' '<pre> THIS IS TEXT\n <B>\tFOR</B>\n PRE. </pre>\n', result.getvalue())
def test_for_raw_msgids(self): # Test for Issue 314: i18n:translate removes line breaks from # <pre>...</pre> contents # HTML mode self.engine.translationDomain.clearMsgids() result = StringIO() program, macros = self._compile( '<div i18n:translate=""> This is text\n' ' \tfor\n div. </div>' '<pre i18n:translate=""> This is text\n' ' <b>\tfor</b>\n pre. </pre>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = list(xlatdmn.data) msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual(' This is text\n <b>\tfor</b>\n pre. ', msgids[0][0]) self.assertEqual('This is text for div.', msgids[1][0]) self.assertEqual( '<div>THIS IS TEXT FOR DIV.</div>' '<pre> THIS IS TEXT\n <B>\tFOR</B>\n PRE. </pre>\n', result.getvalue())
1,938
def test_for_raw_msgids(self): # Test for Issue 314: i18n:translate removes line breaks from # <pre>...</pre> contents # HTML mode xlatdmn = self._getCollectingTranslationDomain() result = StringIO() program, macros = self._compile( '<div i18n:translate=""> This is text\n' ' \tfor\n div. </div>' '<pre i18n:translate=""> This is text\n' ' <b>\tfor</b>\n pre. </pre>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = list(xlatdmn.data) msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual(' This is text\n <b>\tfor</b>\n pre. ', msgids[0][0]) self.assertEqual('This is text for div.', msgids[1][0]) self.assertEqual( '<div>THIS IS TEXT FOR DIV.</div>' '<pre> THIS IS TEXT\n <B>\tFOR</B>\n PRE. </pre>\n', result.getvalue())
def test_for_raw_msgids(self): # Test for Issue 314: i18n:translate removes line breaks from # <pre>...</pre> contents # HTML mode xlatdmn = self._getCollectingTranslationDomain() result = StringIO() program, macros = self._compile( '<div i18n:translate=""> This is text\n' ' \tfor\n div. </div>' '<pre i18n:translate=""> This is text\n' ' <b>\tfor</b>\n pre. </pre>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = self.engine.translationDomain.getMsgids('default') msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual(' This is text\n <b>\tfor</b>\n pre. ', msgids[0][0]) self.assertEqual('This is text for div.', msgids[1][0]) self.assertEqual( '<div>THIS IS TEXT FOR DIV.</div>' '<pre> THIS IS TEXT\n <B>\tFOR</B>\n PRE. </pre>\n', result.getvalue())
1,939
def test_for_raw_msgids(self): # Test for Issue 314: i18n:translate removes line breaks from # <pre>...</pre> contents # HTML mode xlatdmn = self._getCollectingTranslationDomain() result = StringIO() program, macros = self._compile( '<div i18n:translate=""> This is text\n' ' \tfor\n div. </div>' '<pre i18n:translate=""> This is text\n' ' <b>\tfor</b>\n pre. </pre>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = list(xlatdmn.data) msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual(' This is text\n <b>\tfor</b>\n pre. ', msgids[0][0]) self.assertEqual('This is text for div.', msgids[1][0]) self.assertEqual( '<div>THIS IS TEXT FOR DIV.</div>' '<pre> THIS IS TEXT\n <B>\tFOR</B>\n PRE. </pre>\n', result.getvalue())
def test_for_raw_msgids(self): # Test for Issue 314: i18n:translate removes line breaks from # <pre>...</pre> contents # HTML mode self.engine.translationDomain.clearMsgids() result = StringIO() program, macros = self._compile( '<div i18n:translate=""> This is text\n' ' \tfor\n div. </div>' '<pre i18n:translate=""> This is text\n' ' <b>\tfor</b>\n pre. </pre>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = list(xlatdmn.data) msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual(' This is text\n <b>\tfor</b>\n pre. ', msgids[0][0]) self.assertEqual('This is text for div.', msgids[1][0]) self.assertEqual( '<div>THIS IS TEXT FOR DIV.</div>' '<pre> THIS IS TEXT\n <B>\tFOR</B>\n PRE. </pre>\n', result.getvalue())
1,940
def test_for_raw_msgids(self): # Test for Issue 314: i18n:translate removes line breaks from # <pre>...</pre> contents # HTML mode xlatdmn = self._getCollectingTranslationDomain() result = StringIO() program, macros = self._compile( '<div i18n:translate=""> This is text\n' ' \tfor\n div. </div>' '<pre i18n:translate=""> This is text\n' ' <b>\tfor</b>\n pre. </pre>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = list(xlatdmn.data) msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual(' This is text\n <b>\tfor</b>\n pre. ', msgids[0][0]) self.assertEqual('This is text for div.', msgids[1][0]) self.assertEqual( '<div>THIS IS TEXT FOR DIV.</div>' '<pre> THIS IS TEXT\n <B>\tFOR</B>\n PRE. </pre>\n', result.getvalue())
def test_for_raw_msgids(self): # Test for Issue 314: i18n:translate removes line breaks from # <pre>...</pre> contents # HTML mode xlatdmn = self._getCollectingTranslationDomain() result = StringIO() program, macros = self._compile( '<div i18n:translate=""> This is text\n' ' \tfor\n div. </div>' '<pre i18n:translate=""> This is text\n' ' <b>\tfor</b>\n pre. </pre>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = self.engine.translationDomain.getMsgids('default') msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual(' This is text\n <b>\tfor</b>\n pre. ', msgids[0][0]) self.assertEqual('This is text for div.', msgids[1][0]) self.assertEqual( '<div>THIS IS TEXT FOR DIV.</div>' '<pre> THIS IS TEXT\n <B>\tFOR</B>\n PRE. </pre>\n', result.getvalue())
1,941
def test_raw_msgids_and_i18ntranslate_i18nname(self): xlatdmn = self._getCollectingTranslationDomain() result = StringIO() program, macros = self._compile( '<div i18n:translate=""> This is text\n \tfor\n' '<pre tal:content="raw" i18n:name="raw"' ' i18n:translate=""></pre>.</div>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = list(xlatdmn.data) msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual(' \tRaW\n ', msgids[0][0]) self.assertEqual('This is text for ${raw}.', msgids[1][0]) self.assertEqual({'raw': '<pre> \tRAW\n </pre>'}, msgids[1][1]) self.assertEqual( u'<div>THIS IS TEXT FOR <pre> \tRAW\n </pre>.</div>\n', result.getvalue())
def test_raw_msgids_and_i18ntranslate_i18nname(self): self.engine.translationDomain.clearMsgids() result = StringIO() program, macros = self._compile( '<div i18n:translate=""> This is text\n \tfor\n' '<pre tal:content="raw" i18n:name="raw"' ' i18n:translate=""></pre>.</div>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = list(xlatdmn.data) msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual(' \tRaW\n ', msgids[0][0]) self.assertEqual('This is text for ${raw}.', msgids[1][0]) self.assertEqual({'raw': '<pre> \tRAW\n </pre>'}, msgids[1][1]) self.assertEqual( u'<div>THIS IS TEXT FOR <pre> \tRAW\n </pre>.</div>\n', result.getvalue())
1,942
def test_raw_msgids_and_i18ntranslate_i18nname(self): xlatdmn = self._getCollectingTranslationDomain() result = StringIO() program, macros = self._compile( '<div i18n:translate=""> This is text\n \tfor\n' '<pre tal:content="raw" i18n:name="raw"' ' i18n:translate=""></pre>.</div>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = list(xlatdmn.data) msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual(' \tRaW\n ', msgids[0][0]) self.assertEqual('This is text for ${raw}.', msgids[1][0]) self.assertEqual({'raw': '<pre> \tRAW\n </pre>'}, msgids[1][1]) self.assertEqual( u'<div>THIS IS TEXT FOR <pre> \tRAW\n </pre>.</div>\n', result.getvalue())
def test_raw_msgids_and_i18ntranslate_i18nname(self): xlatdmn = self._getCollectingTranslationDomain() result = StringIO() program, macros = self._compile( '<div i18n:translate=""> This is text\n \tfor\n' '<pre tal:content="raw" i18n:name="raw"' ' i18n:translate=""></pre>.</div>') self.interpreter = TALInterpreter(program, {}, self.engine, stream=result) self.interpreter() msgids = self.engine.translationDomain.getMsgids('default') msgids.sort() self.assertEqual(2, len(msgids)) self.assertEqual(' \tRaW\n ', msgids[0][0]) self.assertEqual('This is text for ${raw}.', msgids[1][0]) self.assertEqual({'raw': '<pre> \tRAW\n </pre>'}, msgids[1][1]) self.assertEqual( u'<div>THIS IS TEXT FOR <pre> \tRAW\n </pre>.</div>\n', result.getvalue())
1,943
def test_unicode_mixed_unknown_encoding(self): # This test assumes that sys.getdefaultencoding is ascii... text = u"foo ${bar}" mapping = {u'bar': 'd\xe9j\xe0'} expected = u"foo d\\xe9j\\xe0" self.assertEqual(interpolate(text, mapping), expected)
def test_unicode_mixed_unknown_encoding(self): # This test assumes that sys.getdefaultencoding is ascii... text = u"foo ${bar}" mapping = {u'bar': 'd\xe9j\xe0'} expected = u"foo d\\xe9j\\xe0" self.assertEqual(interpolate(text, mapping), expected)
1,944
def __init__(self, basepath): # initialize python path self.basepath=path=basepath pjoin=os.path.join if sys.platform == 'win32': sys.path.insert(0, pjoin(path, 'lib/python')) sys.path.insert(1, pjoin(path, 'bin/lib')) sys.path.insert(2, pjoin(path, 'bin/lib/plat-win')) sys.path.insert(3, pjoin(path, 'bin/lib/win32')) sys.path.insert(4, pjoin(path, 'bin/lib/win32/lib')) sys.path.insert(5, path) else: sys.path.insert(0, pjoin(path, 'lib/python')) sys.path.insert(1, path)
def __init__(self, basepath, verbosity=VERBOSE): # initialize python path self.basepath=path=basepath pjoin=os.path.join if sys.platform == 'win32': sys.path.insert(0, pjoin(path, 'lib/python')) sys.path.insert(1, pjoin(path, 'bin/lib')) sys.path.insert(2, pjoin(path, 'bin/lib/plat-win')) sys.path.insert(3, pjoin(path, 'bin/lib/win32')) sys.path.insert(4, pjoin(path, 'bin/lib/win32/lib')) sys.path.insert(5, path) else: sys.path.insert(0, pjoin(path, 'lib/python')) sys.path.insert(1, path)
1,945
def smellsLikeATest(self, filepath, find=string.find): file = open(filepath, 'r') text = file.read() file.close() return ((find(text, 'unittest') > -1) or (find(text, 'framework.py') > -1))
def smellsLikeATest(self, filepath, find=string.find): file = open(filepath, 'r') text = file.read() file.close() return ((find(text, 'unittest') > -1) or (find(text, 'framework.py') > -1))
1,946
def runSuite(self, suite): runner=unittest.TextTestRunner(verbosity=VERBOSE) runner.run(suite)
def runSuite(self, suite): runner=unittest.TextTestRunner(verbosity=self.verbosity) runner.run(suite)
1,947
def runPath(self, pathname): """Run all tests found in the directory named by pathname and all subdirectories.""" if not os.path.isabs(pathname): pathname = os.path.join(self.basepath, pathname) names=os.listdir(pathname) for name in names: fname, ext=os.path.splitext(name) if name[:4]=='test' and name[-3:]=='.py' and \ name != 'testrunner.py': filepath=os.path.join(pathname, name) if self.smellsLikeATest(filepath): self.runFile(filepath) for name in names: fullpath=os.path.join(pathname, name) if os.path.isdir(fullpath): self.runPath(fullpath)
def runPath(self, pathname): """Run all tests found in the directory named by pathname and all subdirectories.""" if not os.path.isabs(pathname): pathname = os.path.join(self.basepath, pathname) names=os.listdir(pathname) for name in names: fullpath=os.path.join(pathname, name) if os.path.isdir(fullpath): self.runPath(fullpath)
1,948
def runFile(self, filename): """Run the test suite defined by filename.""" working_dir = os.getcwd() dirname, name = os.path.split(filename) if dirname: os.chdir(dirname) self.report('Running: %s' % filename) try: suite=self.getSuiteFromFile(filename) except: traceback.print_exc() suite=None if suite is None: self.report('No test suite found in file:\n%s' % filename) return self.runSuite(suite) os.chdir(working_dir)
def runFile(self, filename): """Run the test suite defined by filename.""" working_dir = os.getcwd() dirname, name = os.path.split(filename) if dirname: os.chdir(dirname) self.report('Running: %s' % filename) try: suite=self.getSuiteFromFile(name) except: traceback.print_exc() suite=None if suite is None: self.report('No test suite found in file:\n%s' % filename) return self.runSuite(suite) os.chdir(working_dir)
1,949
def runFile(self, filename): """Run the test suite defined by filename.""" working_dir = os.getcwd() dirname, name = os.path.split(filename) if dirname: os.chdir(dirname) self.report('Running: %s' % filename) try: suite=self.getSuiteFromFile(filename) except: traceback.print_exc() suite=None if suite is None: self.report('No test suite found in file:\n%s' % filename) return self.runSuite(suite) os.chdir(working_dir)
def runFile(self, filename): """Run the test suite defined by filename.""" working_dir = os.getcwd() dirname, name = os.path.split(filename) if dirname: os.chdir(dirname) self.report('Running: %s' % filename) try: suite=self.getSuiteFromFile(filename) except: traceback.print_exc() suite=None if suite is not None: self.runSuite(suite) else: self.report('No test suite found in file:\n%s\n' % filename) os.chdir(working_dir)
1,950
def runFile(self, filename): """Run the test suite defined by filename.""" working_dir = os.getcwd() dirname, name = os.path.split(filename) if dirname: os.chdir(dirname) self.report('Running: %s' % filename) try: suite=self.getSuiteFromFile(filename) except: traceback.print_exc() suite=None if suite is None: self.report('No test suite found in file:\n%s' % filename) return self.runSuite(suite) os.chdir(working_dir)
def runFile(self, filename): """Run the test suite defined by filename.""" working_dir = os.getcwd() dirname, name = os.path.split(filename) if dirname: os.chdir(dirname) self.report('Running: %s' % filename) try:suite=self.getSuiteFromFile(filename) except: traceback.print_exc() suite=None if suite is None: self.report('No test suite found in file:\n%s' % filename) return self.runSuite(suite) os.chdir(working_dir)
1,951
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. -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. -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. Quiet mode prints a period as each test runs. -h Display usage information. """ pathname=None filename=None test_all=None options, arg=getopt.getopt(args, 'ahd:f:q') if not options: err_exit(usage_msg) for name, value in options: name=name[1:] if name == 'a': test_all=1 elif name == 'd': pathname=string.strip(value) elif name == 'f': filename=string.strip(value) elif name == 'h': err_exit(usage_msg, 0) elif name == 'q': global VERBOSE VERBOSE = 1 else: err_exit(usage_msg) testrunner=TestRunner(os.getcwd()) if test_all: testrunner.runAllTests() elif pathname: testrunner.runPath(pathname) elif filename: testrunner.runFile(filename) 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. This is the default if no options are specified. -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. -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. -h Display usage information. """ pathname=None filename=None test_all=None options, arg=getopt.getopt(args, 'ahd:f:q') if not options: err_exit(usage_msg) for name, value in options: name=name[1:] if name == 'a': test_all=1 elif name == 'd': pathname=string.strip(value) elif name == 'f': filename=string.strip(value) elif name == 'h': err_exit(usage_msg, 0) elif name == 'q': global VERBOSE VERBOSE = 1 else: err_exit(usage_msg) testrunner=TestRunner(os.getcwd()) if test_all: testrunner.runAllTests() elif pathname: testrunner.runPath(pathname) elif filename: testrunner.runFile(filename) sys.exit(0)
1,952
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. -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. -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. Quiet mode prints a period as each test runs. -h Display usage information. """ pathname=None filename=None test_all=None options, arg=getopt.getopt(args, 'ahd:f:q') if not options: err_exit(usage_msg) for name, value in options: name=name[1:] if name == 'a': test_all=1 elif name == 'd': pathname=string.strip(value) elif name == 'f': filename=string.strip(value) elif name == 'h': err_exit(usage_msg, 0) elif name == 'q': global VERBOSE VERBOSE = 1 else: err_exit(usage_msg) testrunner=TestRunner(os.getcwd()) if test_all: testrunner.runAllTests() elif pathname: testrunner.runPath(pathname) elif filename: testrunner.runFile(filename) 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. This is the default if no options are specified. -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. -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. Quiet mode prints a period as each test runs. -h Display usage information. """ pathname=None filename=None test_all=None verbosity = VERBOSE options, arg=getopt.getopt(args, 'ahd:f:v:q') if not options: err_exit(usage_msg) for name, value in options: name=name[1:] if name == 'a': test_all=1 elif name == 'd': pathname=string.strip(value) elif name == 'f': filename=string.strip(value) elif name == 'h': err_exit(usage_msg, 0) elif name == 'q': global VERBOSE VERBOSE = 1 else: err_exit(usage_msg) testrunner=TestRunner(os.getcwd()) if test_all: testrunner.runAllTests() elif pathname: testrunner.runPath(pathname) elif filename: testrunner.runFile(filename) sys.exit(0)
1,953
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. -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. -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. Quiet mode prints a period as each test runs. -h Display usage information. """ pathname=None filename=None test_all=None options, arg=getopt.getopt(args, 'ahd:f:q') if not options: err_exit(usage_msg) for name, value in options: name=name[1:] if name == 'a': test_all=1 elif name == 'd': pathname=string.strip(value) elif name == 'f': filename=string.strip(value) elif name == 'h': err_exit(usage_msg, 0) elif name == 'q': global VERBOSE VERBOSE = 1 else: err_exit(usage_msg) testrunner=TestRunner(os.getcwd()) if test_all: testrunner.runAllTests() elif pathname: testrunner.runPath(pathname) elif filename: testrunner.runFile(filename) 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. This is the default if no options are specified. -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. -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. Quiet mode prints a period as each test runs. -h Display usage information. """ pathname=None filename=None test_all=None options, arg=getopt.getopt(args, 'ahd:f:q') if not options: err_exit(usage_msg) for name, value in options: name=name[1:] if name == 'a': test_all=1 elif name == 'd': pathname=string.strip(value) elif name == 'f': filename=string.strip(value) elif name == 'h': err_exit(usage_msg, 0) elif name == 'q': verbosity = 1 else: err_exit(usage_msg) testrunner=TestRunner(os.getcwd()) if test_all: testrunner.runAllTests() elif pathname: testrunner.runPath(pathname) elif filename: testrunner.runFile(filename) sys.exit(0)
1,954
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. -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. -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. Quiet mode prints a period as each test runs. -h Display usage information. """ pathname=None filename=None test_all=None options, arg=getopt.getopt(args, 'ahd:f:q') if not options: err_exit(usage_msg) for name, value in options: name=name[1:] if name == 'a': test_all=1 elif name == 'd': pathname=string.strip(value) elif name == 'f': filename=string.strip(value) elif name == 'h': err_exit(usage_msg, 0) elif name == 'q': global VERBOSE VERBOSE = 1 else: err_exit(usage_msg) testrunner=TestRunner(os.getcwd()) if test_all: testrunner.runAllTests() elif pathname: testrunner.runPath(pathname) elif filename: testrunner.runFile(filename) 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. This is the default if no options are specified. -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. -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. Quiet mode prints a period as each test runs. -h Display usage information. """ pathname=None filename=None test_all=None options, arg=getopt.getopt(args, 'ahd:f:q') if not options: err_exit(usage_msg) for name, value in options: name=name[1:] if name == 'a': test_all=1 elif name == 'd': pathname=string.strip(value) elif name == 'f': filename=string.strip(value) elif name == 'h': err_exit(usage_msg, 0) elif name == 'q': global VERBOSE VERBOSE = 1 else: err_exit(usage_msg) testrunner = TestRunner(os.getcwd(), verbosity=verbosity) if test_all: testrunner.runAllTests() elif pathname: testrunner.runPath(pathname) elif filename: testrunner.runFile(filename) sys.exit(0)
1,955
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('')
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('')
1,956
def url(self, ftype=urllib.splittype, fhost=urllib.splithost): """Return a SCRIPT_NAME-based url for an object.""" if hasattr(self, 'DestinationURL') and \ callable(self.DestinationURL): url='%s/%s' % (self.DestinationURL(), self.id) else: url=self.absolute_url() type, uri=ftype(url) host, uri=fhost(uri) script_name=self.REQUEST['SCRIPT_NAME'] __traceback_info__=(`uri`, `script_name`) if script_name: uri=filter(None, string.split(uri, script_name))[0] uri=uri or '/' if uri[0]=='/': uri=uri[1:] return uri
def url(self, ftype=urllib.splittype, fhost=urllib.splithost): """Return a SCRIPT_NAME-based url for an object.""" if hasattr(self, 'DestinationURL') and \ callable(self.DestinationURL): url='%s/%s' % (self.DestinationURL(), self.id) else: url=self.absolute_url() type, uri=ftype(url) host, uri=fhost(uri) script_name=self.REQUEST['SCRIPT_NAME'] __traceback_info__=(`uri`, `script_name`) if script_name: uri=filter(None, string.split(uri, script_name))[0] uri=uri or '/' if uri[0]=='/': uri=uri[1:] return uri
1,957
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None): "Render a tree as a table" have_arg=args.has_key if level >= 0: tpUrl=self.tpURL() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 exp=0 sub=None output=data.append script=md['SCRIPT_NAME'] try: items=getattr(self, args['branches'])() except: items=None if not items and have_arg('leaves'): items=1 if (args.has_key('sort')) and (items is not None) and (items != 1): # Faster/less mem in-place sort if type(items)==type(()): items=list(items) sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] diff.append(id) if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] s=translate(s, tplus) #################################### if exp: treeData['tree-item-expanded']=1 output('<A HREF="%s?tree-c=%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A>' % (root_url,s, script)) else: output('<A HREF="%s?tree-e=%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A>' % (root_url,s, script)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(section(self, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): if md.has_key(args['header']): output(md.getitem(args['header'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['leaves'],0)( self,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) md._pop(1) elif have_arg('expand'): treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['expand'],0)(self,md)) md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, 'tpId'): id=item.tpId() elif hasattr(item, '_p_oid'): id=item._p_oid else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): if md.has_key(args['footer']): output(md.getitem(args['footer'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None): "Render a tree as a table" have_arg=args.has_key if level >= 0: tpUrl=self.tpURL() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 exp=0 sub=None output=data.append script=md['SCRIPT_NAME'] try: items=getattr(self, args['branches'])() except: items=None if not items and have_arg('leaves'): items=1 if (args.has_key('sort')) and (items is not None) and (items != 1): # Faster/less mem in-place sort if type(items)==type(()): items=list(items) sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] diff.append(id) if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] s=translate(s, tplus) #################################### if exp: treeData['tree-item-expanded']=1 output('<A HREF="%s?tree-c=%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A>' % (root_url,s, script)) else: output('<A HREF="%s?tree-e=%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A>' % (root_url,s, script)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(section(self, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): doc=args['header'] if hasattr(self, doc): doc=getattr(self, doc) elif md.has_key(doc): doc=md.getitem(args['header'],0) else: doc=None if doc is not None: output(doc( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['leaves'],0)( self,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) md._pop(1) elif have_arg('expand'): treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['expand'],0)(self,md)) md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, 'tpId'): id=item.tpId() elif hasattr(item, '_p_oid'): id=item._p_oid else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): if md.has_key(args['footer']): output(md.getitem(args['footer'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data
1,958
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None): "Render a tree as a table" have_arg=args.has_key if level >= 0: tpUrl=self.tpURL() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 exp=0 sub=None output=data.append script=md['SCRIPT_NAME'] try: items=getattr(self, args['branches'])() except: items=None if not items and have_arg('leaves'): items=1 if (args.has_key('sort')) and (items is not None) and (items != 1): # Faster/less mem in-place sort if type(items)==type(()): items=list(items) sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] diff.append(id) if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] s=translate(s, tplus) #################################### if exp: treeData['tree-item-expanded']=1 output('<A HREF="%s?tree-c=%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A>' % (root_url,s, script)) else: output('<A HREF="%s?tree-e=%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A>' % (root_url,s, script)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(section(self, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): if md.has_key(args['header']): output(md.getitem(args['header'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['leaves'],0)( self,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) md._pop(1) elif have_arg('expand'): treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['expand'],0)(self,md)) md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, 'tpId'): id=item.tpId() elif hasattr(item, '_p_oid'): id=item._p_oid else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): if md.has_key(args['footer']): output(md.getitem(args['footer'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None): "Render a tree as a table" have_arg=args.has_key if level >= 0: tpUrl=self.tpURL() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 exp=0 sub=None output=data.append script=md['SCRIPT_NAME'] try: items=getattr(self, args['branches'])() except: items=None if not items and have_arg('leaves'): items=1 if (args.has_key('sort')) and (items is not None) and (items != 1): # Faster/less mem in-place sort if type(items)==type(()): items=list(items) sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] diff.append(id) if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] s=translate(s, tplus) #################################### if exp: treeData['tree-item-expanded']=1 output('<A HREF="%s?tree-c=%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A>' % (root_url,s, script)) else: output('<A HREF="%s?tree-e=%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A>' % (root_url,s, script)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(section(self, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): if md.has_key(args['header']): output(md.getitem(args['header'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves doc=args['leaves'] if hasattr(self, doc): doc=getattr(self, doc) elif md.has_key(doc): doc=md.getitem(args['header'],0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(doc( self,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) md._pop(1) elif have_arg('expand'): treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['expand'],0)(self,md)) md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, 'tpId'): id=item.tpId() elif hasattr(item, '_p_oid'): id=item._p_oid else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): if md.has_key(args['footer']): output(md.getitem(args['footer'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data
1,959
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None): "Render a tree as a table" have_arg=args.has_key if level >= 0: tpUrl=self.tpURL() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 exp=0 sub=None output=data.append script=md['SCRIPT_NAME'] try: items=getattr(self, args['branches'])() except: items=None if not items and have_arg('leaves'): items=1 if (args.has_key('sort')) and (items is not None) and (items != 1): # Faster/less mem in-place sort if type(items)==type(()): items=list(items) sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] diff.append(id) if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] s=translate(s, tplus) #################################### if exp: treeData['tree-item-expanded']=1 output('<A HREF="%s?tree-c=%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A>' % (root_url,s, script)) else: output('<A HREF="%s?tree-e=%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A>' % (root_url,s, script)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(section(self, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): if md.has_key(args['header']): output(md.getitem(args['header'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['leaves'],0)( self,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) md._pop(1) elif have_arg('expand'): treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['expand'],0)(self,md)) md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, 'tpId'): id=item.tpId() elif hasattr(item, '_p_oid'): id=item._p_oid else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): if md.has_key(args['footer']): output(md.getitem(args['footer'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None): "Render a tree as a table" have_arg=args.has_key if level >= 0: tpUrl=self.tpURL() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 exp=0 sub=None output=data.append script=md['SCRIPT_NAME'] try: items=getattr(self, args['branches'])() except: items=None if not items and have_arg('leaves'): items=1 if (args.has_key('sort')) and (items is not None) and (items != 1): # Faster/less mem in-place sort if type(items)==type(()): items=list(items) sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] diff.append(id) if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] s=translate(s, tplus) #################################### if exp: treeData['tree-item-expanded']=1 output('<A HREF="%s?tree-c=%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A>' % (root_url,s, script)) else: output('<A HREF="%s?tree-e=%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A>' % (root_url,s, script)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(section(self, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): if md.has_key(args['header']): output(md.getitem(args['header'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['leaves'],0)( self,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) md._pop(1) elif have_arg('expand'): treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['expand'],0)(self,md)) md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, 'tpId'): id=item.tpId() elif hasattr(item, '_p_oid'): id=item._p_oid else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): doc=args['footer'] if hasattr(self, doc): doc=getattr(self, doc) elif md.has_key(doc): doc=md.getitem(args['header'],0) else: doc=None if doc is not None: output(doc( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data
1,960
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
1,961
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
1,962
def insert_code(self, rcode, at = None): opn = self.opn # rcode is passed as a (callables, args) pair rcode = map(apply, rcode[0], rcode[1]) if at is None: at = opn self.code[at:at]=rcode self.opn = opn + len(rcode) return rcode
def insert_code(self, rcode, at = None): opn = self.opn # rcode is passed as a (callables, args) pair rcode = map(apply, rcode[0], rcode[1]) if at is None: at = opn self.code[at + 1:at + 1] = [self.code[at]] self.code[at + 1:at + 1] = rcode del self.code[at] self.opn = opn + len(rcode) return rcode
1,963
def query(self, pattern): """ """ result = [] for x in self.lexicon.get(pattern): if self.globbing: result.append(self.lexicon._inverseLex[x]) else: result.append(pattern)
def query(self, pattern): """ """ result = [] for x in self.lexicon.get(pattern): if self.globbing: result.append(self.lexicon._inverseLex[x]) else: result.append(pattern)
1,964
def unindex_object(self, i, tt=type(()) ): """ carefully unindex document with integer id 'i' from the text index and do not fail if it does not exist """ index = self._index unindex = self._unindex val = unindex.get(i, None) if val is not None: for n in val: v = index.get(n, None) if type(v) is tt: del index[n] elif v is not None: try: del index[n][i] except (KeyError, IndexError, TypeError): LOG('UnTextIndex', PROBLEM, 'unindex_object tried to unindex nonexistent' ' document %s' % str(i)) del unindex[i] self._index = index self._unindex = unindex
def unindex_object(self, i, tt=type(()) ): """ carefully unindex document with integer id 'i' from the text index and do not fail if it does not exist """ index = self._index unindex = self._unindex val = unindex.get(i, None) if val is not None: for n in val: v = index.get(n, None) if type(v) is tt: del index[n] elif v is not None: try: del index[n][i] except (KeyError, IndexError, TypeError): LOG('UnTextIndex', ERROR, 'unindex_object tried to unindex nonexistent' ' document %s' % str(i)) del unindex[i] self._index = index self._unindex = unindex
1,965
def and_not(self, x): '''Return items in the reciever that are not in the argument''' result = self.__class__() for key,v in self.items(): try: x[key] except KeyError: result[key] = v return result
def and_not(self, x): '''Return items in the receiver that are not in the argument''' result = self.__class__() for key,v in self.items(): try: x[key] except KeyError: result[key] = v return result
1,966
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 positions = v[1] + value[1] positions.sort() positionsr = [] rel = pow(v[0] * value[0], 0.5) pl = positions[0] rl = -1 for i in range(1, len(positions)): p = positions[i] d = p - pl if d > 0 and d <= distance: if pl != rl: positionsr.append(pl) positionsr.append(p) rl = p pl = p if (len(positionsr)): result[key] = positionsr return result
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 positions = v[1] + value[1] positions.sort() positionsr = [] rel = pow(v[0] * value[0], 0.5) pl = positions[0] rl = -1 for i in range(1, len(positions)): p = positions[i] d = p - pl if d > 0 and d <= distance: if pl != rl: positionsr.append(pl) positionsr.append(p) rl = p pl = p if (len(positionsr)): result[key] = score,positionsr return result
1,967
def unlock(self, token, **kw): """Remove the lock identified by token from the resource and all other resources included in the lock. If all resources which have been locked under the submitted lock token can not be unlocked the unlock method will fail.""" headers=self.__get_headers(kw) token='<opaquelocktoken:%s>' % str(token) headers['Lock-Token']=token return self.__snd_request('UNLOCK', self.uri, headers, body)
def unlock(self, token, **kw): """Remove the lock identified by token from the resource and all other resources included in the lock. If all resources which have been locked under the submitted lock token can not be unlocked the unlock method will fail.""" headers=self.__get_headers(kw) token='<opaquelocktoken:%s>' % str(token) headers['Lock-Token']=token return self.__snd_request('UNLOCK', self.uri, headers, body)
1,968
def __getitem__(self, index, ttype=type(())): """ Returns instances of self._v_brains, or whatever is passed into self.useBrains. """ if type(index) is ttype: normalized_score, score, key = index r=self._v_result_class(self.data[key]).__of__(self.aq_parent) r.data_record_id_ = key r.data_record_score_ = score r.data_record_normalized_score_ = normalized_score else: r=self._v_result_class(self.data[index]).__of__(self.aq_parent) r.data_record_id_ = index r.data_record_score__ = 1 r.data_record_normalized_score_ = 1 return r
def __getitem__(self, index, ttype=type(())): """ Returns instances of self._v_brains, or whatever is passed into self.useBrains. """ if type(index) is ttype: normalized_score, score, key = index r=self._v_result_class(self.data[key]).__of__(self.aq_parent) r.data_record_id_ = key r.data_record_score_ = score r.data_record_normalized_score_ = normalized_score else: r=self._v_result_class(self.data[index]).__of__(self.aq_parent) r.data_record_id_ = index r.data_record_score_ = 1 r.data_record_normalized_score_ = 1 return r
1,969
def encodeUrl(self, url, create=1): """ encode a URL with the browser id as a postfixed query string element """ bid = self.getBrowserId(create) if bid is None: raise BrowserIdManagerErr, 'There is no current browser id.' name = self.getBrowserIdName() if '?' in url: return '%s&%s=%s' % (url, name, bid) else: return '%s?%s=%s' % (url, name, bid)
def encodeUrl(self, url, create=1): """ encode a URL with the browser id as a postfixed query string element """ bid = self.getBrowserId(create) if bid is None: raise BrowserIdManagerErr, 'There is no current browser id.' name = self.getBrowserIdName() if '?' in url: return '%s&amp;%s=%s' % (url, name, bid) else: return '%s?%s=%s' % (url, name, bid)
1,970
def objectIds(self,t=None): # Return a list of subobject ids
def objectIds(self, spec=None): # Return a list of subobject ids
1,971
def objectIds(self,t=None): # Return a list of subobject ids
def objectIds(self,t=None): # Return a list of subobject ids
1,972
def objectValues(self,t=None): # Return a list of the actual subobjects
def objectValues(self, spec=None): # Return a list of the actual subobjects
1,973
def objectValues(self,t=None): # Return a list of the actual subobjects
def objectValues(self,t=None): # Return a list of the actual subobjects
1,974
def objectItems(self,t=None): # Return a list of (id, subobject) tuples
def objectItems(self, spec=None): # Return a list of (id, subobject) tuples
1,975
def objectItems(self,t=None): # Return a list of (id, subobject) tuples
def objectItems(self,t=None): # Return a list of (id, subobject) tuples
1,976
def copyskel(sourcedir, targetdir, uid, gid, **replacements): """ This is an independent function because we'd like to import and call it from mkzopeinstance """ # Create the top of the instance: if not os.path.exists(targetdir): os.makedirs(targetdir) # This is fairly ugly. The chdir() makes path manipulation in the # walk() callback a little easier (less magical), so we'll live # with it. pwd = os.getcwd() os.chdir(sourcedir) try: try: os.path.walk(os.curdir, copydir, (targetdir, replacements, uid, gid)) finally: os.chdir(pwd) except (IOError, OSError), msg: print >>sys.stderr, msg sys.exit(1)
def copyskel(sourcedir, targetdir, uid, gid, **replacements): """ This is an independent function because we'd like to import and call it from mkzopeinstance """ # Create the top of the instance: if not os.path.exists(targetdir): os.makedirs(targetdir) # This is fairly ugly. The chdir() makes path manipulation in the # walk() callback a little easier (less magical), so we'll live # with it. pwd = os.getcwd() os.chdir(sourcedir) try: try: os.path.walk(os.curdir, copydir, (targetdir, replacements, uid, gid)) finally: os.chdir(pwd) except (IOError, OSError), msg: print >>sys.stderr, msg sys.exit(1)
1,977
def copydir((targetdir, replacements, uid, gid), sourcedir, names): # Don't recurse into CVS directories: for name in names[:]: if os.path.normcase(name) == CVS: names.remove(name) elif os.path.isfile(os.path.join(sourcedir, name)): # Copy the file: sn, ext = os.path.splitext(name) if os.path.normcase(ext) == ".in": dst = os.path.join(targetdir, sourcedir, sn) if os.path.exists(dst): continue copyin(os.path.join(sourcedir, name), dst, replacements, uid, gid) if uid is not None: os.chown(dst, uid, gid) else: src = os.path.join(sourcedir, name) dst = os.path.join(targetdir, src) if os.path.exists(dst): continue shutil.copyfile(src, dst) shutil.copymode(src, dst) if uid is not None: os.chown(dst, uid, gid) else: # Directory: dn = os.path.join(targetdir, sourcedir, name) if not os.path.exists(dn): os.mkdir(dn) shutil.copymode(os.path.join(sourcedir, name), dn) if uid is not None: os.chown(dn, uid, gid)
def copydir((targetdir, replacements, uid, gid), sourcedir, names): # Don't recurse into CVS directories: for name in names[:]: if os.path.normcase(name) in CVS_DIRS: names.remove(name) elif os.path.isfile(os.path.join(sourcedir, name)): # Copy the file: sn, ext = os.path.splitext(name) if os.path.normcase(ext) == ".in": dst = os.path.join(targetdir, sourcedir, sn) if os.path.exists(dst): continue copyin(os.path.join(sourcedir, name), dst, replacements, uid, gid) if uid is not None: os.chown(dst, uid, gid) else: src = os.path.join(sourcedir, name) dst = os.path.join(targetdir, src) if os.path.exists(dst): continue shutil.copyfile(src, dst) shutil.copymode(src, dst) if uid is not None: os.chown(dst, uid, gid) else: # Directory: dn = os.path.join(targetdir, sourcedir, name) if not os.path.exists(dn): os.mkdir(dn) shutil.copymode(os.path.join(sourcedir, name), dn) if uid is not None: os.chown(dn, uid, gid)
1,978
def refuse_to_unpickle(self): raise pickle.UnpicklingError, 'Refused'
def refuse_to_unpickle(self): raise pickle.UnpicklingError, 'Refused'
1,979
def refuse_to_unpickle(self): raise pickle.UnpicklingError, 'Refused'
def refuse_to_unpickle(self): raise pickle.UnpicklingError, 'Refused'
1,980
def _test(): _should_fail('hello',0) _should_succeed('hello') _should_succeed(1) _should_succeed(1L) _should_succeed(1.0) _should_succeed((1,2,3)) _should_succeed([1,2,3]) _should_succeed({1:2,3:4}) _should_fail(open) _should_fail(_junk_class) _should_fail(_junk_class())
def _test(): _should_succeed('hello') _should_succeed(1) _should_succeed(1L) _should_succeed(1.0) _should_succeed((1,2,3)) _should_succeed([1,2,3]) _should_succeed({1:2,3:4}) _should_fail(open) _should_fail(_junk_class) _should_fail(_junk_class())
1,981
def tabs_path_info(self, script, path, # Static vars quote=urllib.quote, ): out=[] while path[:1]=='/': path=path[1:] while path[-1:]=='/': path=path[:-1] while script[:1]=='/': script=script[1:] while script[-1:]=='/': script=script[:-1] path=split(path,'/')[:-1] if script: path=[script]+path if not path: return '' script='' last=path[-1] del path[-1] for p in path: script="%s/%s" % (script, quote(p)) out.append('<a href="%s/manage_workspace">%s</a>' % (script, p)) out.append(last) return join(out, '/')
def tabs_path_info(self, script, path, # Static vars quote=urllib.quote, ): out=[] while path[:1]=='/': path=path[1:] while path[-1:]=='/': path=path[:-1] while script[:1]=='/': script=script[1:] while script[-1:]=='/': script=script[:-1] path=split(path,'/')[:-1] if script: path=[script]+path if not path: return '' script='' last=path[-1] del path[-1] for p in path: script="%s/%s" % (script, quote(p)) out.append('<a href="%s/manage_workspace">%s</a>' % (script, p)) out.append(last) return join(out, '/')
1,982
def manage_zmi_logout(self, REQUEST, RESPONSE): """Logout current user""" p = getattr(REQUEST, '_logout_path', None) if p is not None: return apply(self.restrictedTraverse(p))
def manage_zmi_logout(self, REQUEST, RESPONSE): """Logout current user""" p = getattr(REQUEST, '_logout_path', None) if p is not None: return apply(self.restrictedTraverse(p))
1,983
def get_module_info(module_name, modules={}, acquire=_l.acquire, release=_l.release, ): if modules.has_key(module_name): return modules[module_name] if module_name[-4:]=='.cgi': module_name=module_name[:-4] acquire() tb=None try: try: module=__import__(module_name, globals(), globals(), ('__doc__',)) realm=module_name # Let the app specify a realm if hasattr(module,'__bobo_realm__'): realm=module.__bobo_realm__ elif os.environ.has_key('BOBO_REALM'): realm=request.environ['BOBO_REALM'] else: realm=module_name # Check for debug mode if hasattr(module,'__bobo_debug_mode__'): debug_mode=not not module.__bobo_debug_mode__ elif os.environ.has_key('BOBO_DEBUG_MODE'): debug_mode=lower(os.environ['BOBO_DEBUG_MODE']) if debug_mode=='y' or debug_mode=='yes': debug_mode=1 else: try: debug_mode=atoi(debug_mode) except: debug_mode=None else: debug_mode=None # Check whether tracebacks should be hidden: if hasattr(module,'__bobo_hide_tracebacks__'): hide_tracebacks=not not module.__bobo_hide_tracebacks__ elif os.environ.has_key('BOBO_HIDE_TRACEBACKS'): hide_tracebacks=lower(os.environ['BOBO_HIDE_TRACEBACKS']) if hide_tracebacks=='y' or hide_tracebacks=='yes': hide_tracebacks=1 else: try: hide_tracebacks=atoi(hide_tracebacks) except: hide_tracebacks=None else: hide_tracebacks=None # Reset response handling of tracebacks, if necessary: if debug_mode or not hide_tracebacks: def hack_response(): import Response Response._tbopen = '<PRE>' Response._tbclose = '</PRE>' hack_response() if hasattr(module,'__bobo_before__'): bobo_before=module.__bobo_before__ else: bobo_before=None if hasattr(module,'__bobo_after__'): bobo_after=module.__bobo_after__ else: bobo_after=None # Get request data from outermost environment: if hasattr(module,'__request_data__'): request_params=module.__request_data__ else: request_params=None # Get initial group data: inherited_groups=[] if hasattr(module,'__allow_groups__'): groups=module.__allow_groups__ inherited_groups.append(groups) else: groups=None web_objects=None roles=UNSPECIFIED_ROLES if hasattr(module,'bobo_application'): object=module.bobo_application if hasattr(object,'__allow_groups__'): groups=object.__allow_groups__ inherited_groups.append(groups) else: groups=None if hasattr(object,'__roles__'): roles=object.__roles__ else: if hasattr(module,'web_objects'): web_objects=module.web_objects object=web_objects else: object=module published=web_objects try: doc=module.__doc__ except: if web_objects is not None: doc=' ' else: doc=None info= (bobo_before, bobo_after, request_params, inherited_groups, groups, roles, object, doc, published, realm, module_name, debug_mode) modules[module_name]=modules[module_name+'.cgi']=info return info except: if hasattr(sys, 'exc_info'): t,v,tb=sys.exc_info() else: t, v, tb = sys.exc_type, sys.exc_value, sys.exc_traceback v=str(v) raise ImportError, (t, v), tb finally: tb=None release()
def get_module_info(module_name, modules={}, acquire=_l.acquire, release=_l.release, ): if modules.has_key(module_name): return modules[module_name] if module_name[-4:]=='.cgi': module_name=module_name[:-4] acquire() tb=None try: try: module=__import__(module_name, globals(), globals(), ('__doc__',)) realm=module_name # Let the app specify a realm if hasattr(module,'__bobo_realm__'): realm=module.__bobo_realm__ elif os.environ.has_key('BOBO_REALM'): realm=request.environ['BOBO_REALM'] else: realm=module_name # Check for debug mode if hasattr(module,'__bobo_debug_mode__'): debug_mode=not not module.__bobo_debug_mode__ elif os.environ.has_key('BOBO_DEBUG_MODE'): debug_mode=lower(os.environ['BOBO_DEBUG_MODE']) if debug_mode=='y' or debug_mode=='yes': debug_mode=1 else: try: debug_mode=atoi(debug_mode) except: debug_mode=None else: debug_mode=None # Check whether tracebacks should be hidden: if hasattr(module,'__bobo_hide_tracebacks__'): hide_tracebacks=not not module.__bobo_hide_tracebacks__ elif os.environ.has_key('BOBO_HIDE_TRACEBACKS'): hide_tracebacks=lower(os.environ['BOBO_HIDE_TRACEBACKS']) if hide_tracebacks=='y' or hide_tracebacks=='yes': hide_tracebacks=1 else: try: hide_tracebacks=atoi(hide_tracebacks) except: hide_tracebacks=None else: hide_tracebacks=1 # Reset response handling of tracebacks, if necessary: if debug_mode or not hide_tracebacks: def hack_response(): import Response Response._tbopen = '<PRE>' Response._tbclose = '</PRE>' hack_response() if hasattr(module,'__bobo_before__'): bobo_before=module.__bobo_before__ else: bobo_before=None if hasattr(module,'__bobo_after__'): bobo_after=module.__bobo_after__ else: bobo_after=None # Get request data from outermost environment: if hasattr(module,'__request_data__'): request_params=module.__request_data__ else: request_params=None # Get initial group data: inherited_groups=[] if hasattr(module,'__allow_groups__'): groups=module.__allow_groups__ inherited_groups.append(groups) else: groups=None web_objects=None roles=UNSPECIFIED_ROLES if hasattr(module,'bobo_application'): object=module.bobo_application if hasattr(object,'__allow_groups__'): groups=object.__allow_groups__ inherited_groups.append(groups) else: groups=None if hasattr(object,'__roles__'): roles=object.__roles__ else: if hasattr(module,'web_objects'): web_objects=module.web_objects object=web_objects else: object=module published=web_objects try: doc=module.__doc__ except: if web_objects is not None: doc=' ' else: doc=None info= (bobo_before, bobo_after, request_params, inherited_groups, groups, roles, object, doc, published, realm, module_name, debug_mode) modules[module_name]=modules[module_name+'.cgi']=info return info except: if hasattr(sys, 'exc_info'): t,v,tb=sys.exc_info() else: t, v, tb = sys.exc_type, sys.exc_value, sys.exc_traceback v=str(v) raise ImportError, (t, v), tb finally: tb=None release()
1,984
def PUT(self, REQUEST, RESPONSE): """ Handle HTTP PUT requests """ self.dav__init(REQUEST, RESPONSE) self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1) ## XXX this should be unicode or we must pass an encoding self.pt_edit(REQUEST.get('BODY', '')) RESPONSE.setStatus(204) return RESPONSE
def PUT(self, REQUEST, RESPONSE): """ Handle HTTP PUT requests """ self.dav__init(REQUEST, RESPONSE) self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1) ## XXX this should be unicode or we must pass an encodingtext = REQUEST.get('BODY', '') content_type = guess_type('', text) self.pt_edit(text, content_type, self.output_encoding) RESPONSE.setStatus(204) return RESPONSE
1,985
def manage_FTPget(self): "Get source for FTP download" self.REQUEST.RESPONSE.setHeader('Content-Type', self.content_type) return self.read()
def manage_FTPget(self): "Get source for FTP download" self.REQUEST.RESPONSE.setHeader('Content-Type', self.content_type) return self.read()
1,986
def item_munge(ast, i): # Munge an item access into a function call name=ast[i][2][1] args=[arglist] append=args.append a=(factor, (power, (atom, (NAME, '_vars')))) a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, a))))))))))) append(a) append([COMMA,',']) a=ast[:i] a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, (factor, a)))))))))))) append(a) append([COMMA,',']) for sub in ast[2][2][1:]: if sub[0]==COMMA: append(sub) else: if len(sub) != 2: raise ParseError, 'Invalid slice in subscript' append([argument, sub[1]]) return [power, [atom, [NAME, '__guarded_getitem__']], [trailer, [LPAR, '('], args, [RPAR, ')'], ] ]
def item_munge(ast, i): # Munge an item access into a function call name=ast[i][2][1] args=[arglist] append=args.append a=(factor, (power, (atom, (NAME, '_vars')))) a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, a))))))))))) append(a) append([COMMA,',']) a=ast[:i] a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, (factor, a)))))))))))) append(a) append([COMMA,',']) for sub in ast[i][2][1:]: if sub[0]==COMMA: append(sub) else: if len(sub) != 2: raise ParseError, 'Invalid slice in subscript' append([argument, sub[1]]) return [power, [atom, [NAME, '__guarded_getitem__']], [trailer, [LPAR, '('], args, [RPAR, ')'], ] ]
1,987
def dot_munge(ast, i): # Munge an attribute access into a function call name=ast[i][2][1] args=[arglist] append=args.append a=(factor, (power, (atom, (NAME, '_vars')))) a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, a))))))))))) append(a) append([COMMA,',']) a=ast[:i] a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, (factor, a)))))))))))) append(a) append([COMMA,',']) a=(factor, (power, (atom, (STRING, `name`)))) a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, a))))))))))) append(a) return [power, [atom, [NAME, '__guarded_getattr__']], [trailer, [LPAR, '('], args, [RPAR, ')'], ] ]
def dot_munge(ast, i): # Munge an attribute access into a function call name=ast[i][2][1] args=[arglist] append=args.append a=(factor, (power, (atom, (NAME, '_vars')))) a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, a))))))))))) append(a) append([COMMA,',']) a=ast[:i] a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, (factor, a)))))))))))) append(a) append([COMMA,',']) a=(factor, (power, (atom, (STRING, `name`)))) a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, a))))))))))) append(a) return [power, [atom, [NAME, '__guarded_getattr__']], [trailer, [LPAR, '('], args, [RPAR, ')']], ]
1,988
def spam(): # Regression test import traceback ok=1 for expr1, expr2 in ( ("a*b", "__guarded_mul__(_vars, a, b)"), ("a*b*c", "__guarded_mul__(_vars, __guarded_mul__(_vars, a, b), c)" ), ("a.b", "__guarded_getattr__(_vars, a, 'b')"), ("a[b]", "__guarded_getitem__(_vars, a, b)"), ("a[b,c]", "__guarded_getitem__(_vars, a, b, c)"), ("a[b:c]", "__guarded_getslice__(_vars, a, b, c)"), ("a[:c]", "__guarded_getslice__(_vars, a, 0, c)"), ("a[b:]", "__guarded_getslice__(_vars, a, b)"), ("a[:]", "__guarded_getslice__(_vars, a)"), ("_vars['sequence-index'] % 2", "__guarded_getitem__(_vars, _vars, 'sequence-index') % 2" ), ): l1=munge(astl(expr1)) l2=astl(expr2) try: c1=compileast(sequence2ast(l1)) except: traceback.print_exc c1=None c2=compileast(sequence2ast(l2)) if c1 !=c2: ok=0 print 'test failed', expr1, expr2 print print l1 print print l2 print ast=parser.sequence2ast(l1) c=parser.compileast(ast) if ok: print 'all tests succeeded'
defspam():#Regressiontestimporttracebackok=1forexpr1,expr2in(("a*b", "__guarded_mul__(_vars,a,b)"),("a*b*c","__guarded_mul__(_vars,__guarded_mul__(_vars,a,b),c)"),("a.b", "__guarded_getattr__(_vars,a,'b')"),("a[b]", "__guarded_getitem__(_vars,a,b)"),("a[b,c]", "__guarded_getitem__(_vars,a,b,c)"),("a[b:c]", "__guarded_getslice__(_vars,a,b,c)"),("a[:c]", "__guarded_getslice__(_vars,a,0,c)"),("a[b:]", "__guarded_getslice__(_vars,a,b)"),("a[:]", "__guarded_getslice__(_vars,a)"),("_vars['sequence-index']%2","__guarded_getitem__(_vars,_vars,'sequence-index')%2"),):l1=munge(astl(expr1))l2=astl(expr2)try:c1=compileast(sequence2ast(l1))except:traceback.print_excc1=Nonec2=compileast(sequence2ast(l2))ifc1!=c2:ok=0print'testfailed',expr1,expr2printprintl1printprintl2printast=parser.sequence2ast(l1)c=parser.compileast(ast)ifok:print'alltestssucceeded'
1,989
def unindex_object(self, i): """ Unindex the object with integer id 'i' """ index = self._index unindex = self._unindex
def unindex_object(self, i): """ Unindex the object with integer id 'i' """ index = self._index unindex = self._unindex
1,990
def install_product(app, product_dir, product_name, meta_types, folder_permissions, raise_exc=0, log_exc=1): path_join=os.path.join isdir=os.path.isdir exists=os.path.exists DictType=type({}) global_dict=globals() silly=('__doc__',) if 1: # Preserve indentation for diff :-) package_dir=path_join(product_dir, product_name) __traceback_info__=product_name if not isdir(package_dir): return if not exists(path_join(package_dir, '__init__.py')): if not exists(path_join(package_dir, '__init__.pyc')): return try: product=__import__("Products.%s" % product_name, global_dict, global_dict, silly) # Install items into the misc_ namespace, used by products # and the framework itself to store common static resources # like icon images. misc_=pgetattr(product, 'misc_', {}) if misc_: if type(misc_) is DictType: misc_=Misc_(product_name, misc_) Application.misc_.__dict__[product_name]=misc_ # Here we create a ProductContext object which contains # information about the product and provides an interface # for registering things like classes and help topics that # should be associated with that product. Products are # expected to implement a method named 'initialize' in # their __init__.py that takes the ProductContext as an # argument. productObject=App.Product.initializeProduct( product, product_name, package_dir, app) context=ProductContext(productObject, app, product) # Look for an 'initialize' method in the product. If it does # not exist, then this is an old product that has never been # updated. In that case, we will analyze the product and # build up enough information to do initialization manually. initmethod=pgetattr(product, 'initialize', None) if initmethod is not None: initmethod(context) # Support old-style product metadata. Older products may # define attributes to name their permissions, meta_types, # constructors, etc. permissions={} new_permissions={} for p in pgetattr(product, '__ac_permissions__', ()): permission, names, default = ( tuple(p)+('Manager',))[:3] 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', ()): # Modern product initialization via a ProductContext # adds 'product' and 'permission' keys to the meta_type # mapping. We have to add these here for old products. pname=permissions.get(meta_type['action'], None) if pname is not None: meta_type['permission']=pname meta_type['product']=productObject.id meta_types.append(meta_type) for name,method in pgetattr( product, 'methods', {}).items(): if not hasattr(Folder, name): setattr(Folder, name, method) if name[-9:]!='__roles__': # not 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.Folder.__dict__['__ac_permissions__']=tuple( list(Folder.Folder.__ac_permissions__)+new_permissions) if (os.environ.get('ZEO_CLIENT') and not os.environ.get('FORCE_PRODUCT_LOAD')): # we don't want to install products from clients # (unless FORCE_PRODUCT_LOAD is defined). get_transaction().abort() else: get_transaction().note('Installed product '+product_name) get_transaction().commit() except: if log_exc: LOG('Zope',ERROR,'Couldn\'t install %s' % product_name, error=sys.exc_info()) get_transaction().abort() if raise_exc: raise
def install_product(app, product_dir, product_name, meta_types, folder_permissions, raise_exc=0, log_exc=1): path_join=os.path.join isdir=os.path.isdir exists=os.path.exists DictType=type({}) global_dict=globals() silly=('__doc__',) if 1: # Preserve indentation for diff :-) package_dir=path_join(product_dir, product_name) __traceback_info__=product_name if not isdir(package_dir): return if not exists(path_join(package_dir, '__init__.py')): if not exists(path_join(package_dir, '__init__.pyc')): return try: product=__import__("Products.%s" % product_name, global_dict, global_dict, silly) # Install items into the misc_ namespace, used by products # and the framework itself to store common static resources # like icon images. misc_=pgetattr(product, 'misc_', {}) if misc_: if type(misc_) is DictType: misc_=Misc_(product_name, misc_) Application.misc_.__dict__[product_name]=misc_ # Here we create a ProductContext object which contains # information about the product and provides an interface # for registering things like classes and help topics that # should be associated with that product. Products are # expected to implement a method named 'initialize' in # their __init__.py that takes the ProductContext as an # argument. productObject=App.Product.initializeProduct( product, product_name, package_dir, app) context=ProductContext(productObject, app, product) # Look for an 'initialize' method in the product. If it does # not exist, then this is an old product that has never been # updated. In that case, we will analyze the product and # build up enough information to do initialization manually. initmethod=pgetattr(product, 'initialize', None) if initmethod is not None: initmethod(context) # Support old-style product metadata. Older products may # define attributes to name their permissions, meta_types, # constructors, etc. permissions={} new_permissions={} for p in pgetattr(product, '__ac_permissions__', ()): permission, names, default = ( tuple(p)+('Manager',))[:3] 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', ()): # Modern product initialization via a ProductContext # adds 'product' and 'permission' keys to the meta_type # mapping. We have to add these here for old products. pname=permissions.get(meta_type['action'], None) if pname is not None: meta_type['permission']=pname meta_type['product']=productObject.id meta_types.append(meta_type) for name,method in pgetattr( product, 'methods', {}).items(): if not hasattr(Folder.Folder, name): setattr(Folder.Folder, name, method) if name[-9:]!='__roles__': # not 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.Folder.__dict__['__ac_permissions__']=tuple( list(Folder.Folder.__ac_permissions__)+new_permissions) if (os.environ.get('ZEO_CLIENT') and not os.environ.get('FORCE_PRODUCT_LOAD')): # we don't want to install products from clients # (unless FORCE_PRODUCT_LOAD is defined). get_transaction().abort() else: get_transaction().note('Installed product '+product_name) get_transaction().commit() except: if log_exc: LOG('Zope',ERROR,'Couldn\'t install %s' % product_name, error=sys.exc_info()) get_transaction().abort() if raise_exc: raise
1,991
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None): "Render a tree as a table" have_arg=args.has_key tpUrl=self.tpURL() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 exp=0 sub=None output=data.append try: items=getattr(self, args['branches'])() except: items=None if not items and have_arg('leaves'): items=1 if (args.has_key('sort')) and (items is not None) and (items != 1): # Faster/less mem in-place sort sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] diff.append(id) if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] #################################### if exp: treeData['tree-item-expanded']=1 output('<A HREF="%s?tree-c=%s">%s</A>' % (root_url,s, icoMinus)) else: output('<A HREF="%s?tree-e=%s">%s</A>' % (root_url,s, icoPlus)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(section(self, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): if md.has_key(args['header']): output(md.getitem(args['header'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['leaves'],0)( self,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) md._pop(1) elif have_arg('expand'): treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['expand'],0)(self,md)) md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, 'tpId'): id=item.tpId() elif hasattr(item, '_p_oid'): id=item._p_oid else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): if md.has_key(args['footer']): output(md.getitem(args['footer'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None): "Render a tree as a table" have_arg=args.has_key if level >= 0: tpUrl=self.tpURL() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 exp=0 sub=None output=data.append try: items=getattr(self, args['branches'])() except: items=None if not items and have_arg('leaves'): items=1 if (args.has_key('sort')) and (items is not None) and (items != 1): # Faster/less mem in-place sort sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] diff.append(id) if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] #################################### if exp: treeData['tree-item-expanded']=1 output('<A HREF="%s?tree-c=%s">%s</A>' % (root_url,s, icoMinus)) else: output('<A HREF="%s?tree-e=%s">%s</A>' % (root_url,s, icoPlus)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(section(self, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): if md.has_key(args['header']): output(md.getitem(args['header'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['leaves'],0)( self,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) md._pop(1) elif have_arg('expand'): treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['expand'],0)(self,md)) md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, 'tpId'): id=item.tpId() elif hasattr(item, '_p_oid'): id=item._p_oid else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): if md.has_key(args['footer']): output(md.getitem(args['footer'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data
1,992
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
def decapitate(html, RESPONSE=None, header_re=ts_regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
1,993
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=ts_regex.compile('\([ \t]+\)'), name_re=ts_regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
1,994
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): ts_results = header_re.match_group(html, (1,3)) if not ts_results: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
1,995
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = ts_results[1] headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
1,996
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] continue ts_results = space_re.match_group(headers[i], (1,)) if ts_results: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
1,997
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(ts_results[1]):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
1,998
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] continue i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
1,999