bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def _if_modified_since_request_handler(self, REQUEST, RESPONSE): # HTTP If-Modified-Since header handling: return True if # we can handle this request by returning a 304 response header=REQUEST.get_header('If-Modified-Since', None) if header is not None: header=header.split( ';')[0] # Some proxies seem to send invalid date strings for this # header. If the date string is not valid, we ignore it # rather than raise an error to be generally consistent # with common servers such as Apache (which can usually # understand the screwy date string as a lucky side effect # of the way they parse it). # This happens to be what RFC2616 tells us to do in the face of an # invalid date. try: mod_since=long(DateTime(header).timeTime()) except: mod_since=None if mod_since is not None: if self._p_mtime: last_mod = long(self._p_mtime) else: last_mod = long(0) if last_mod > 0 and last_mod <= mod_since: # Set header values since apache caching will return # Content-Length of 0 in response if size is not set here RESPONSE.setHeader('Last-Modified', rfc1123_date(self._p_mtime)) RESPONSE.setHeader('Content-Type', self.content_type) RESPONSE.setHeader('Content-Length', self.size) RESPONSE.setHeader('Accept-Ranges', 'bytes') RESPONSE.setStatus(304) return True
def _if_modified_since_request_handler(self, REQUEST, RESPONSE): # HTTP If-Modified-Since header handling: return True if # we can handle this request by returning a 304 response header=REQUEST.get_header('If-Modified-Since', None) if header is not None: header=header.split( ';')[0] # Some proxies seem to send invalid date strings for this # header. If the date string is not valid, we ignore it # rather than raise an error to be generally consistent # with common servers such as Apache (which can usually # understand the screwy date string as a lucky side effect # of the way they parse it). # This happens to be what RFC2616 tells us to do in the face of an # invalid date. try:mod_since=long(DateTime(header).timeTime()) except: mod_since=None if mod_since is not None: if self._p_mtime: last_mod = long(self._p_mtime) else: last_mod = long(0) if last_mod > 0 and last_mod <= mod_since: # Set header values since apache caching will return # Content-Length of 0 in response if size is not set here RESPONSE.setHeader('Last-Modified', rfc1123_date(self._p_mtime)) RESPONSE.setHeader('Content-Type', self.content_type) RESPONSE.setHeader('Content-Length', self.size) RESPONSE.setHeader('Accept-Ranges', 'bytes') RESPONSE.setStatus(304) return True
1,800
def _if_modified_since_request_handler(self, REQUEST, RESPONSE): # HTTP If-Modified-Since header handling: return True if # we can handle this request by returning a 304 response header=REQUEST.get_header('If-Modified-Since', None) if header is not None: header=header.split( ';')[0] # Some proxies seem to send invalid date strings for this # header. If the date string is not valid, we ignore it # rather than raise an error to be generally consistent # with common servers such as Apache (which can usually # understand the screwy date string as a lucky side effect # of the way they parse it). # This happens to be what RFC2616 tells us to do in the face of an # invalid date. try: mod_since=long(DateTime(header).timeTime()) except: mod_since=None if mod_since is not None: if self._p_mtime: last_mod = long(self._p_mtime) else: last_mod = long(0) if last_mod > 0 and last_mod <= mod_since: # Set header values since apache caching will return # Content-Length of 0 in response if size is not set here RESPONSE.setHeader('Last-Modified', rfc1123_date(self._p_mtime)) RESPONSE.setHeader('Content-Type', self.content_type) RESPONSE.setHeader('Content-Length', self.size) RESPONSE.setHeader('Accept-Ranges', 'bytes') RESPONSE.setStatus(304) return True
def _if_modified_since_request_handler(self, REQUEST, RESPONSE): # HTTP If-Modified-Since header handling: return True if # we can handle this request by returning a 304 response header=REQUEST.get_header('If-Modified-Since', None) if header is not None: header=header.split( ';')[0] # Some proxies seem to send invalid date strings for this # header. If the date string is not valid, we ignore it # rather than raise an error to be generally consistent # with common servers such as Apache (which can usually # understand the screwy date string as a lucky side effect # of the way they parse it). # This happens to be what RFC2616 tells us to do in the face of an # invalid date. try: mod_since=long(DateTime(header).timeTime()) except: mod_since=None if mod_since is not None: if self._p_mtime: last_mod = long(self._p_mtime) else: last_mod = long(0) if last_mod > 0 and last_mod <= mod_since: # Set header values since apache caching will return # Content-Length of 0 in response if size is not set here RESPONSE.setHeader('Last-Modified', rfc1123_date(self._p_mtime)) RESPONSE.setHeader('Content-Type', self.content_type) RESPONSE.setHeader('Accept-Ranges', 'bytes') RESPONSE.setStatus(304) return True
1,801
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,802
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,803
def field2int(v): try: v=v.read() except: v=str(v) return string.atoi(v)
def field2int(v): try: v=v.read() except: v=str(v) if v: return string.atoi(v) raise ValueError, 'Empty entry when integer expected'
1,804
def field2float(v): try: v=v.read() except: v=str(v) return string.atof(v)
def field2float(v): try: v=v.read() except: v=str(v) if v: return string.atof(v) raise ValueError, 'Empty entry when floating-point number expected'
1,805
def field2long(v): try: v=v.read() except: v=str(v) return string.atol(v)
def field2long(v): try: v=v.read() except: v=str(v) if v: return string.atol(v) raise ValueError, 'Empty entry when integer expected'
1,806
def uniqueValues( self, name=None, withLengths=0 ): """ Return a list of unique values for 'name'.
def uniqueValues( self, name=None, withLengths=0 ): """ Return a list of unique values for 'name'.
1,807
def MOVE(self, REQUEST, RESPONSE): """Move a resource to a new location.""" self.dav__init(REQUEST, RESPONSE) raise 'Forbidden', 'This resource cannot be moved.'
def MOVE(self, REQUEST, RESPONSE): """Move a resource to a new location.""" self.dav__init(REQUEST, RESPONSE) raise 'Forbidden', 'This resource cannot be moved.'
1,808
def set_locale(val): try: import locale except: raise SystemExit, ( 'The locale module could not be imported.\n' 'To use localization options, you must ensure\n' 'that the locale module is compiled into your\n' 'Python installation.' ) try: locale.setlocale(locale.LC_ALL, val) except: raise SystemExit, ( 'The specified locale is not supported by your system.\n' 'See your operating system documentation for more\n' 'information on locale support.' )
def set_locale(val): try: import locale except: raise SystemExit, ( 'The locale module could not be imported.\n' 'To use localization options, you must ensure\n' 'that the locale module is compiled into your\n' 'Python installation.' ) try: locale.setlocale(locale.LC_ALL, val) except: raise SystemExit, ( 'The specified locale is not supported by your system.\n' 'See your operating system documentation for more\n' 'information on locale support.' )
1,809
def logBadRefresh(productid): exc = sys.exc_info() try: LOG('Refresh', ERROR, 'Exception while refreshing %s' % productid, error=exc) if hasattr(exc[0], '__name__'): error_type = exc[0].__name__ else: error_type = str(exc[0]) error_value = str(exc[1]) info = format_exception(exc[0], exc[1], exc[2], limit=200) refresh_exc_info[productid] = (error_type, error_value, info) finally: exc = None
def logBadRefresh(productid): exc = sys.exc_info() try: LOG('Refresh', ERROR, 'Exception while refreshing %s' % productid, error=exc) if hasattr(exc[0], '__name__'): error_type = exc[0].__name__ else: error_type = str(exc[0]) error_value = str(exc[1]) info = ''.join(format_exception(exc[0], exc[1], exc[2], limit=200)) refresh_exc_info[productid] = (error_type, error_value, info) finally: exc = None
1,810
def setBase(self,base): 'Set the base URL for the returned document.' if base[-1:] != '/': base=base+'/' self.base=base self.insertBase()
def setBase(self,base): 'Set the base URL for the returned document.' if base[-1:] != '/': base=base+'/' self.base=base self.insertBase()
1,811
def setBase(self,base): 'Set the base URL for the returned document.' if base[-1:] != '/': base=base+'/' self.base=base self.insertBase()
def setBase(self,base): 'Set the base URL for the returned document.' if base[-1:] != '/': base=base+'/' self.base=base self.insertBase()
1,812
def insertBase(self, base_re_search=regex.compile('\(<base[\0- ]+[^>]+>\)', regex.casefold).search ): # Only insert a base tag if content appears to be html. if self.headers.get('content-type', '')[:9] != 'text/html': return
def insertBase(self, base_re_search=regex.compile('\(<base[\0- ]+[^>]+>\)', regex.casefold).search ): # Only insert a base tag if content appears to be html. content_type = self.headers.get('content-type', '')[:9] if content_type and (content_type != 'text/html'): return
1,813
def getOwner(self, info=0): """Get the owner
def getOwner(self, info=0, aq_get=aq_get, None=None, UnownableOwner=UnownableOwner, getSecurityManager=getSecurityManager, ): """Get the owner
1,814
def getOwner(self, info=0): """Get the owner
def getOwner(self, info=0): """Get the owner
1,815
def testStrftimeUnicode(self): dt = DateTime('2002-05-02T08:00:00+00:00') self.assertEqual(dt.strftime(u'Le %d/%m/%Y \xe0 %Hh%M'), u'Le 02/05/2002 \xe0 10h00')
def testStrftimeUnicode(self): dt = DateTime('2002-05-02T08:00:00+00:00') self.assertEqual(dt.strftime(u'Le %d/%m/%Y \xe0 %Hh%M'), u'Le 02/05/2002 \xe0 10h00')
1,816
def createInObjectManager(self, id, REQUEST, RESPONSE=None): """ Create Z instance. If called with a RESPONSE, the RESPONSE will be redirected to the management screen of the new instance's parent Folder. Otherwise, the instance will be returned. """ i=mapply(self._zclass_, (), REQUEST) if not hasattr(i, 'id') or not i.id: i.id=id
def createInObjectManager(self, id, REQUEST, RESPONSE=None): """ Create Z instance. If called with a RESPONSE, the RESPONSE will be redirected to the management screen of the new instance's parent Folder. Otherwise, the instance will be returned. """ i=mapply(self._zclass_, (), REQUEST) if not hasattr(i, 'id') or not i.id: i.id=id
1,817
def structured_text(v, name='(Unknown name)', md={}): global StructuredText if StructuredText is None: from StructuredText import html_with_references return str(html_with_references(str(v),level=3,header=0))
def structured_text(v, name='(Unknown name)', md={}): global StructuredText if StructuredText is None: from StructuredText.StructuredText import HTML return HTML(str(v),level=3,header=0)
1,818
def setAddNotificationTarget(self, f): # We should assert that the callback function 'f' implements # the TransientNotification interface print "setting addNotificationTarget to %s" % f self._addCallback = f
def setAddNotificationTarget(self, f): # We should assert that the callback function 'f' implements # the TransientNotification interface self._addCallback = f
1,819
def setDelNotificationTarget(self, f): # We should assert that the callback function 'f' implements # the TransientNotification interface print "setting delNotificationTarget to %s" % f self._delCallback = f
def setDelNotificationTarget(self, f): # We should assert that the callback function 'f' implements # the TransientNotification interface self._delCallback = f
1,820
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif rawdata.startswith("<!--", i): # <!-- k = self.parse_comment(i) elif rawdata.startswith("<?", i): # <? k = self.parse_pi(i) elif rawdata.startswith("<!", i): # <! k = self.parse_declaration(i) elif (i + 1) < n: self.handle_data("<") k = i + 1 else: break if k < 0: if end: self.error("EOF in middle of construct") break i = self.updatepos(i, k) elif rawdata[i:i+2] == "&#": match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue else: break elif rawdata[i] == '&': match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: # match.group() will contain at least 2 chars rest = rawdata[i:] if end and match.group() == rest: self.error("EOF in middle of entity or char ref") # incomplete break elif (i + 1) < n: # not the end of the buffer, and can't be confused # with some other construct self.handle_data("&") i = self.updatepos(i, i + 1) else: break else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif _contains_at(rawdata, "<!--", i): # <!-- k = self.parse_comment(i) elif rawdata.startswith("<?", i): # <? k = self.parse_pi(i) elif rawdata.startswith("<!", i): # <! k = self.parse_declaration(i) elif (i + 1) < n: self.handle_data("<") k = i + 1 else: break if k < 0: if end: self.error("EOF in middle of construct") break i = self.updatepos(i, k) elif rawdata[i:i+2] == "&#": match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue else: break elif rawdata[i] == '&': match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: # match.group() will contain at least 2 chars rest = rawdata[i:] if end and match.group() == rest: self.error("EOF in middle of entity or char ref") # incomplete break elif (i + 1) < n: # not the end of the buffer, and can't be confused # with some other construct self.handle_data("&") i = self.updatepos(i, i + 1) else: break else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
1,821
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif rawdata.startswith("<!--", i): # <!-- k = self.parse_comment(i) elif rawdata.startswith("<?", i): # <? k = self.parse_pi(i) elif rawdata.startswith("<!", i): # <! k = self.parse_declaration(i) elif (i + 1) < n: self.handle_data("<") k = i + 1 else: break if k < 0: if end: self.error("EOF in middle of construct") break i = self.updatepos(i, k) elif rawdata[i:i+2] == "&#": match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue else: break elif rawdata[i] == '&': match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: # match.group() will contain at least 2 chars rest = rawdata[i:] if end and match.group() == rest: self.error("EOF in middle of entity or char ref") # incomplete break elif (i + 1) < n: # not the end of the buffer, and can't be confused # with some other construct self.handle_data("&") i = self.updatepos(i, i + 1) else: break else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif rawdata.startswith("<!--", i): # <!-- k = self.parse_comment(i) elif _contains_at(rawdata, "<?", i): # <? k = self.parse_pi(i) elif rawdata.startswith("<!", i): # <! k = self.parse_declaration(i) elif (i + 1) < n: self.handle_data("<") k = i + 1 else: break if k < 0: if end: self.error("EOF in middle of construct") break i = self.updatepos(i, k) elif rawdata[i:i+2] == "&#": match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue else: break elif rawdata[i] == '&': match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: # match.group() will contain at least 2 chars rest = rawdata[i:] if end and match.group() == rest: self.error("EOF in middle of entity or char ref") # incomplete break elif (i + 1) < n: # not the end of the buffer, and can't be confused # with some other construct self.handle_data("&") i = self.updatepos(i, i + 1) else: break else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
1,822
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif rawdata.startswith("<!--", i): # <!-- k = self.parse_comment(i) elif rawdata.startswith("<?", i): # <? k = self.parse_pi(i) elif rawdata.startswith("<!", i): # <! k = self.parse_declaration(i) elif (i + 1) < n: self.handle_data("<") k = i + 1 else: break if k < 0: if end: self.error("EOF in middle of construct") break i = self.updatepos(i, k) elif rawdata[i:i+2] == "&#": match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue else: break elif rawdata[i] == '&': match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: # match.group() will contain at least 2 chars rest = rawdata[i:] if end and match.group() == rest: self.error("EOF in middle of entity or char ref") # incomplete break elif (i + 1) < n: # not the end of the buffer, and can't be confused # with some other construct self.handle_data("&") i = self.updatepos(i, i + 1) else: break else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif rawdata.startswith("<!--", i): # <!-- k = self.parse_comment(i) elif rawdata.startswith("<?", i): # <? k = self.parse_pi(i) elif _contains_at(rawdata, "<?", i): # <! k = self.parse_declaration(i) elif (i + 1) < n: self.handle_data("<") k = i + 1 else: break if k < 0: if end: self.error("EOF in middle of construct") break i = self.updatepos(i, k) elif rawdata[i:i+2] == "&#": match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue else: break elif rawdata[i] == '&': match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: # match.group() will contain at least 2 chars rest = rawdata[i:] if end and match.group() == rest: self.error("EOF in middle of entity or char ref") # incomplete break elif (i + 1) < n: # not the end of the buffer, and can't be confused # with some other construct self.handle_data("&") i = self.updatepos(i, i + 1) else: break else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
1,823
def __str__(self): L1 = self.__dict__.items() L1.sort() return join(map(lambda item: "%s: %s" %item, L1), ", ")
def __str__(self): L1 = self.__dict__.items() L1.sort() return join(map(lambda item: "%s: %s" %item, L1), ", ")
1,824
def __str__(self): L1 = self.__dict__.items() L1.sort() return join(map(lambda item: "%s: %s" %item, L1), ", ")
def __str__(self): L1 = self.__dict__.items() L1.sort() return join(map(lambda item: "%s: %s" %item, L1), ", ")
1,825
def initializeProduct(productp, name, home, app): # Initialize a levered product products=app.Control_Panel.Products if hasattr(productp, 'import_error_'): ie=productp.import_error_ else: ie=None try: fver=strip(open(home+'/version.txt').read()) except: fver='' old=None try: if ihasattr(products,name): old=getattr(products, name) if (ihasattr(old,'version') and old.version==fver and hasattr(old, 'import_error_') and old.import_error_==ie): return except: pass try: f=CompressedInputFile(open(home+'/product.dat','rb'),name+' shshsh') meta=cPickle.Unpickler(f).load() product=Globals.Bobobase._jar.import_file(f) product._objects=meta['_objects'] except: f=fver and (" (%s)" % fver) product=Product(name, 'Installed product %s%s' % (name,f)) if old is not None: products._delObject(name) products._setObject(name, product) product.__of__(products)._postCopy(products) product.manage_options=Folder.manage_options product.icon='p_/InstalledProduct_icon' product.version=fver product._distribution=None product.manage_distribution=None product.thisIsAnInstalledProduct=1 if ie: product.import_error_=ie product.title='Broken product %s' % name product.icon='p_/BrokenProduct_icon' product.manage_options=( {'label':'Traceback', 'action':'manage_traceback'}, ) if os.path.exists(os.path.join(home, 'README.txt')): product.manage_options=product.manage_options+( {'label':'README', 'action':'manage_readme'}, )
def initializeProduct(productp, name, home, app): # Initialize a levered product products=app.Control_Panel.Products if hasattr(productp, '__import_error__'): ie=productp.__import_error__ else: ie=None try: fver=strip(open(home+'/version.txt').read()) except: fver='' old=None try: if ihasattr(products,name): old=getattr(products, name) if (ihasattr(old,'version') and old.version==fver and hasattr(old, 'import_error_') and old.import_error_==ie): return except: pass try: f=CompressedInputFile(open(home+'/product.dat','rb'),name+' shshsh') meta=cPickle.Unpickler(f).load() product=Globals.Bobobase._jar.import_file(f) product._objects=meta['_objects'] except: f=fver and (" (%s)" % fver) product=Product(name, 'Installed product %s%s' % (name,f)) if old is not None: products._delObject(name) products._setObject(name, product) product.__of__(products)._postCopy(products) product.manage_options=Folder.manage_options product.icon='p_/InstalledProduct_icon' product.version=fver product._distribution=None product.manage_distribution=None product.thisIsAnInstalledProduct=1 if ie: product.import_error_=ie product.title='Broken product %s' % name product.icon='p_/BrokenProduct_icon' product.manage_options=( {'label':'Traceback', 'action':'manage_traceback'}, ) if os.path.exists(os.path.join(home, 'README.txt')): product.manage_options=product.manage_options+( {'label':'README', 'action':'manage_readme'}, )
1,826
def initializeProduct(productp, name, home, app): # Initialize a levered product products=app.Control_Panel.Products if hasattr(productp, 'import_error_'): ie=productp.import_error_ else: ie=None try: fver=strip(open(home+'/version.txt').read()) except: fver='' old=None try: if ihasattr(products,name): old=getattr(products, name) if (ihasattr(old,'version') and old.version==fver and hasattr(old, 'import_error_') and old.import_error_==ie): return except: pass try: f=CompressedInputFile(open(home+'/product.dat','rb'),name+' shshsh') meta=cPickle.Unpickler(f).load() product=Globals.Bobobase._jar.import_file(f) product._objects=meta['_objects'] except: f=fver and (" (%s)" % fver) product=Product(name, 'Installed product %s%s' % (name,f)) if old is not None: products._delObject(name) products._setObject(name, product) product.__of__(products)._postCopy(products) product.manage_options=Folder.manage_options product.icon='p_/InstalledProduct_icon' product.version=fver product._distribution=None product.manage_distribution=None product.thisIsAnInstalledProduct=1 if ie: product.import_error_=ie product.title='Broken product %s' % name product.icon='p_/BrokenProduct_icon' product.manage_options=( {'label':'Traceback', 'action':'manage_traceback'}, ) if os.path.exists(os.path.join(home, 'README.txt')): product.manage_options=product.manage_options+( {'label':'README', 'action':'manage_readme'}, )
def initializeProduct(productp, name, home, app): # Initialize a levered product products=app.Control_Panel.Products if hasattr(productp, 'import_error_'): ie=productp.import_error_ else: ie=None try: fver=strip(open(home+'/version.txt').read()) except: fver='' old=None try: if ihasattr(products,name): old=getattr(products, name) if (ihasattr(old,'version') and old.version==fver and hasattr(old, 'import_error_') and old.import_error_==ie): return old except: pass try: f=CompressedInputFile(open(home+'/product.dat','rb'),name+' shshsh') meta=cPickle.Unpickler(f).load() product=Globals.Bobobase._jar.import_file(f) product._objects=meta['_objects'] except: f=fver and (" (%s)" % fver) product=Product(name, 'Installed product %s%s' % (name,f)) if old is not None: products._delObject(name) products._setObject(name, product) product.__of__(products)._postCopy(products) product.manage_options=Folder.manage_options product.icon='p_/InstalledProduct_icon' product.version=fver product._distribution=None product.manage_distribution=None product.thisIsAnInstalledProduct=1 if ie: product.import_error_=ie product.title='Broken product %s' % name product.icon='p_/BrokenProduct_icon' product.manage_options=( {'label':'Traceback', 'action':'manage_traceback'}, ) if os.path.exists(os.path.join(home, 'README.txt')): product.manage_options=product.manage_options+( {'label':'README', 'action':'manage_readme'}, )
1,827
def initializeProduct(productp, name, home, app): # Initialize a levered product products=app.Control_Panel.Products if hasattr(productp, 'import_error_'): ie=productp.import_error_ else: ie=None try: fver=strip(open(home+'/version.txt').read()) except: fver='' old=None try: if ihasattr(products,name): old=getattr(products, name) if (ihasattr(old,'version') and old.version==fver and hasattr(old, 'import_error_') and old.import_error_==ie): return except: pass try: f=CompressedInputFile(open(home+'/product.dat','rb'),name+' shshsh') meta=cPickle.Unpickler(f).load() product=Globals.Bobobase._jar.import_file(f) product._objects=meta['_objects'] except: f=fver and (" (%s)" % fver) product=Product(name, 'Installed product %s%s' % (name,f)) if old is not None: products._delObject(name) products._setObject(name, product) product.__of__(products)._postCopy(products) product.manage_options=Folder.manage_options product.icon='p_/InstalledProduct_icon' product.version=fver product._distribution=None product.manage_distribution=None product.thisIsAnInstalledProduct=1 if ie: product.import_error_=ie product.title='Broken product %s' % name product.icon='p_/BrokenProduct_icon' product.manage_options=( {'label':'Traceback', 'action':'manage_traceback'}, ) if os.path.exists(os.path.join(home, 'README.txt')): product.manage_options=product.manage_options+( {'label':'README', 'action':'manage_readme'}, )
def return product initializeProduct(productp, return product name, return product home, return product app): return product # return product Initialize return product a return product levered return product product return product return product products=app.Control_Panel.Products return product return product if return product hasattr(productp, return product 'import_error_'): return product ie=productp.import_error_ return product else: return product ie=None return product return product try: return product fver=strip(open(home+'/version.txt').read()) return product except: return product fver='' return product old=None return product try: return product if return product ihasattr(products,name): return product old=getattr(products, return product name) return product if return product (ihasattr(old,'version') return product and return product old.version==fver return product and return product hasattr(old, return product 'import_error_') return product and return product old.import_error_==ie): return product return return product except: return product pass return product return product try: return product f=CompressedInputFile(open(home+'/product.dat','rb'),name+' return product shshsh') return product meta=cPickle.Unpickler(f).load() return product product=Globals.Bobobase._jar.import_file(f) return product product._objects=meta['_objects'] return product except: return product f=fver return product and return product (" return product (%s)" return product % return product fver) return product product=Product(name, return product 'Installed return product product return product %s%s' return product % return product (name,f)) return product return product if return product old return product is return product not return product None: return product products._delObject(name) return product products._setObject(name, return product product) return product product.__of__(products)._postCopy(products) return product product.manage_options=Folder.manage_options return product product.icon='p_/InstalledProduct_icon' return product product.version=fver return product product._distribution=None return product product.manage_distribution=None return product product.thisIsAnInstalledProduct=1 return product return product if return product ie: return product product.import_error_=ie return product product.title='Broken return product product return product %s' return product % return product name return product product.icon='p_/BrokenProduct_icon' return product product.manage_options=( return product {'label':'Traceback', return product 'action':'manage_traceback'}, return product ) return product return product if return product os.path.exists(os.path.join(home, return product 'README.txt')): return product product.manage_options=product.manage_options+( return product {'label':'README', return product 'action':'manage_readme'}, return product ) return product return product
1,828
def marshal_long(name, val): return ('%s:long=%s' % (name, val))[:-1]
def marshal_long(name, val): value = '%s:long=%s' % (name, val) if value[-1] == 'L': value = value[:-1] return value
1,829
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None, simple_type={type(''):0, type(1):0, type(1.0):0}.has_key, ): "Render a tree as a table" have_arg=args.has_key exp=0 if level >= 0: urlattr=args['url'] if urlattr and hasattr(self, urlattr): tpUrl=getattr(self, urlattr) if not simple_type(type(tpUrl)): tpUrl=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 idattr=args['id'] output=data.append items=None if (have_arg('assume_children') and args['assume_children'] and substate is not state): # We should not compute children unless we have to. # See if we've been asked to expand our children. for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break if not exp: items=1 if items is None: validate=md.validate if have_arg('branches') and hasattr(self, args['branches']): if validate is None or not hasattr(self, 'aq_acquire'): items=getattr(self, args['branches']) else: items=self.aq_acquire(args['branches'],validate,md) items=items() elif have_arg('branches_expr'): items=args['branches_expr'](md) if not items and have_arg('leaves'): items=1 if items and items != 1: if validate is not None: unauth=[] index=0 for i in items: try: v=validate(items,items,index,i,md) except: v=0 if not v: unauth.append(index) index=index+1 if unauth: if have_arg('skip_unauthorized') and args['skip_unauthorized']: items=list(items) unauth.reverse() for i in unauth: del items[i] else: raise ValidationError, unauth if have_arg('sort'): # 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) sub=None 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) #################################### script=md['SCRIPT_NAME'] if exp: treeData['tree-item-expanded']=1 output('<A NAME="%s">' '<A HREF="%s?tree-c=%s#%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A>' % (id, root_url, s, id, script)) else: output('<A NAME="%s">' '<A HREF="%s?tree-e=%s#%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A>' % (id, root_url, s, id, 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" ALIGN="LEFT">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(render_blocks(section, 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 md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, 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 if have_arg('leaves'): doc=args['leaves'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,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>', )) finally: md._pop(1) elif have_arg('expand'): doc=args['expand'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,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>', )) finally: md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, idattr): id=getattr(item, idattr) if not simple_type(type(id)): id=id() 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 md._push(InstanceDict(item,md)) try: data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) finally: md._pop() 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 md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, 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, simple_type={type(''):0, type(1):0, type(1.0):0}.has_key, ): "Render a tree as a table" have_arg=args.has_key exp=0 if level >= 0: urlattr=args['url'] if urlattr and hasattr(self, urlattr): tpUrl=getattr(self, urlattr) if not simple_type(type(tpUrl)): tpUrl=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 idattr=args['id'] output=data.append items=None if (have_arg('assume_children') and args['assume_children'] and substate is not state): # We should not compute children unless we have to. # See if we've been asked to expand our children. for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break if not exp: items=1 if items is None: validate=md.validate if have_arg('branches') and hasattr(self, args['branches']): if validate is None or not hasattr(self, 'aq_acquire'): items=getattr(self, args['branches']) else: items=self.aq_acquire(args['branches'],validate,md) items=items() elif have_arg('branches_expr'): items=args['branches_expr'](md) if not items and have_arg('leaves'): items=1 if items and items != 1: if validate is not None: unauth=[] index=0 for i in items: try: v=validate(items,items,index,i,md) except: v=0 if not v: unauth.append(index) index=index+1 if unauth: if have_arg('skip_unauthorized') and args['skip_unauthorized']: items=list(items) unauth.reverse() for i in unauth: del items[i] else: raise ValidationError, unauth if have_arg('sort'): # 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) sub=None 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) #################################### script=md['SCRIPT_NAME'] if exp: treeData['tree-item-expanded']=1 output('<A NAME="%s">' '<A HREF="%s?tree-c=%s#%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A></A>' % (id, root_url, s, id, script)) else: output('<A NAME="%s">' '<A HREF="%s?tree-e=%s#%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A>' % (id, root_url, s, id, 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" ALIGN="LEFT">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(render_blocks(section, 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 md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, 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 if have_arg('leaves'): doc=args['leaves'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,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>', )) finally: md._pop(1) elif have_arg('expand'): doc=args['expand'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,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>', )) finally: md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, idattr): id=getattr(item, idattr) if not simple_type(type(id)): id=id() 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 md._push(InstanceDict(item,md)) try: data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) finally: md._pop() 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 md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, 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,830
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None, simple_type={type(''):0, type(1):0, type(1.0):0}.has_key, ): "Render a tree as a table" have_arg=args.has_key exp=0 if level >= 0: urlattr=args['url'] if urlattr and hasattr(self, urlattr): tpUrl=getattr(self, urlattr) if not simple_type(type(tpUrl)): tpUrl=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 idattr=args['id'] output=data.append items=None if (have_arg('assume_children') and args['assume_children'] and substate is not state): # We should not compute children unless we have to. # See if we've been asked to expand our children. for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break if not exp: items=1 if items is None: validate=md.validate if have_arg('branches') and hasattr(self, args['branches']): if validate is None or not hasattr(self, 'aq_acquire'): items=getattr(self, args['branches']) else: items=self.aq_acquire(args['branches'],validate,md) items=items() elif have_arg('branches_expr'): items=args['branches_expr'](md) if not items and have_arg('leaves'): items=1 if items and items != 1: if validate is not None: unauth=[] index=0 for i in items: try: v=validate(items,items,index,i,md) except: v=0 if not v: unauth.append(index) index=index+1 if unauth: if have_arg('skip_unauthorized') and args['skip_unauthorized']: items=list(items) unauth.reverse() for i in unauth: del items[i] else: raise ValidationError, unauth if have_arg('sort'): # 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) sub=None 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) #################################### script=md['SCRIPT_NAME'] if exp: treeData['tree-item-expanded']=1 output('<A NAME="%s">' '<A HREF="%s?tree-c=%s#%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A>' % (id, root_url, s, id, script)) else: output('<A NAME="%s">' '<A HREF="%s?tree-e=%s#%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A>' % (id, root_url, s, id, 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" ALIGN="LEFT">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(render_blocks(section, 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 md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, 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 if have_arg('leaves'): doc=args['leaves'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,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>', )) finally: md._pop(1) elif have_arg('expand'): doc=args['expand'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,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>', )) finally: md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, idattr): id=getattr(item, idattr) if not simple_type(type(id)): id=id() 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 md._push(InstanceDict(item,md)) try: data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) finally: md._pop() 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 md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, 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, simple_type={type(''):0, type(1):0, type(1.0):0}.has_key, ): "Render a tree as a table" have_arg=args.has_key exp=0 if level >= 0: urlattr=args['url'] if urlattr and hasattr(self, urlattr): tpUrl=getattr(self, urlattr) if not simple_type(type(tpUrl)): tpUrl=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 idattr=args['id'] output=data.append items=None if (have_arg('assume_children') and args['assume_children'] and substate is not state): # We should not compute children unless we have to. # See if we've been asked to expand our children. for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break if not exp: items=1 if items is None: validate=md.validate if have_arg('branches') and hasattr(self, args['branches']): if validate is None or not hasattr(self, 'aq_acquire'): items=getattr(self, args['branches']) else: items=self.aq_acquire(args['branches'],validate,md) items=items() elif have_arg('branches_expr'): items=args['branches_expr'](md) if not items and have_arg('leaves'): items=1 if items and items != 1: if validate is not None: unauth=[] index=0 for i in items: try: v=validate(items,items,index,i,md) except: v=0 if not v: unauth.append(index) index=index+1 if unauth: if have_arg('skip_unauthorized') and args['skip_unauthorized']: items=list(items) unauth.reverse() for i in unauth: del items[i] else: raise ValidationError, unauth if have_arg('sort'): # 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) sub=None 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) #################################### script=md['SCRIPT_NAME'] if exp: treeData['tree-item-expanded']=1 output('<A NAME="%s">' '<A HREF="%s?tree-c=%s#%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A>' % (id, root_url, s, id, script)) else: output('<A NAME="%s">' '<A HREF="%s?tree-e=%s#%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A></A>' % (id, root_url, s, id, 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" ALIGN="LEFT">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(render_blocks(section, 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 md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, 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 if have_arg('leaves'): doc=args['leaves'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,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>', )) finally: md._pop(1) elif have_arg('expand'): doc=args['expand'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,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>', )) finally: md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, idattr): id=getattr(item, idattr) if not simple_type(type(id)): id=id() 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 md._push(InstanceDict(item,md)) try: data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) finally: md._pop() 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 md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, 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,831
def doc_table(self, paragraph, expr = re.compile(r'\s*\|[-]+\|').match): text = paragraph.getColorizableTexts()[0] m = expr(text) subs = paragraph.getSubparagraphs() if not (m): return None rows = [] spans = [] ROWS = [] COLS = [] indexes = [] ignore = [] TDdivider = re.compile("[\-]+").match THdivider = re.compile("[\=]+").match col = re.compile('\|').search innertable = re.compile('\|([-]+|[=]+)\|').search text = strip(text) rows = split(text,'\n') foo = "" for row in range(len(rows)): rows[row] = strip(rows[row]) # have indexes store if a row is a divider # or a cell part for index in range(len(rows)): tmpstr = rows[index][1:len(rows[index])-1] if TDdivider(tmpstr): indexes.append("TDdivider") elif THdivider(tmpstr): indexes.append("THdivider") else: indexes.append("cell")
def doc_table(self, paragraph, expr = re.compile(r'\s*\|[-]+\|').match): text = paragraph.getColorizableTexts()[0] m = expr(text) subs = paragraph.getSubparagraphs() if not (m): return None rows = [] spans = [] ROWS = [] COLS = [] indexes = [] ignore = [] TDdivider = re.compile("[\-]+").match THdivider = re.compile("[\=]+").match col = re.compile('\|').search innertable = re.compile('\|([-]+|[=]+)\|').search text = strip(text) rows = split(text,'\n') foo = "" for row in range(len(rows)): rows[row] = strip(rows[row]) # have indexes store if a row is a divider # or a cell part for index in range(len(rows)): tmpstr = rows[index][1:len(rows[index])-1] if TDdivider(tmpstr): indexes.append("TDdivider") elif THdivider(tmpstr): indexes.append("THdivider") else: indexes.append("cell")
1,832
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None, simple_type={type(''):0, type(1):0, type(1.0):0}.has_key, ): "Render a tree as a table" have_arg=args.has_key exp=0 if level >= 0: urlattr=args['url'] if urlattr and hasattr(self, urlattr): tpUrl=getattr(self, urlattr) if not simple_type(type(tpUrl)): tpUrl=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 idattr=args['id'] output=data.append items=None if (have_arg('assume_children') and args['assume_children'] and substate is not state): # We should not compute children unless we have to. # See if we've been asked to expand our children. for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break if not exp: items=1 if items is None: validate=md.validate if have_arg('branches') and hasattr(self, args['branches']): if validate is None or not hasattr(self, 'aq_acquire'): items=getattr(self, args['branches']) else: items=self.aq_acquire(args['branches'],validate,md) items=items() elif have_arg('branches_expr'): items=args['branches_expr'](md) if not items and have_arg('leaves'): items=1 if items and items != 1: if validate is not None: unauth=[] index=0 for i in items: try: v=validate(items,items,index,i,md) except: v=0 if not v: unauth.append(index) index=index+1 if unauth: if have_arg('skip_unauthorized') and args['skip_unauthorized']: items=list(items) unauth.reverse() for i in unauth: del items[i] else: raise ValidationError, unauth if have_arg('sort'): # 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] if have_arg('reverse'): items.reverse() diff.append(id) sub=None 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) #################################### script=md['SCRIPT_NAME'] if exp: treeData['tree-item-expanded']=1 output('<A NAME="%s">' '<A HREF="%s?tree-c=%s#%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A></A>' % (id, root_url, s, id, script)) else: output('<A NAME="%s">' '<A HREF="%s?tree-e=%s#%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A></A>' % (id, root_url, s, id, 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" ALIGN="LEFT">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(render_blocks(section, 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 md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, 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 if have_arg('leaves'): doc=args['leaves'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,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>', )) finally: md._pop(1) elif have_arg('expand'): doc=args['expand'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,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>', )) finally: md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, idattr): id=getattr(item, idattr) if not simple_type(type(id)): id=id() elif hasattr(item, '_p_oid'): id=oid(item) else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 md._push(InstanceDict(item,md)) try: data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) finally: md._pop() 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 md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, 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, simple_type={type(''):0, type(1):0, type(1.0):0}.has_key, ): "Render a tree as a table" have_arg=args.has_key exp=0 if level >= 0: urlattr=args['url'] if urlattr and hasattr(self, urlattr): tpUrl=getattr(self, urlattr) if not simple_type(type(tpUrl)): tpUrl=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 idattr=args['id'] output=data.append items=None if (have_arg('assume_children') and args['assume_children'] and substate is not state): # We should not compute children unless we have to. # See if we've been asked to expand our children. for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break if not exp: items=1 if items is None: validate=md.validate if have_arg('branches') and hasattr(self, args['branches']): if validate is None or not hasattr(self, 'aq_acquire'): items=getattr(self, args['branches']) else: items=self.aq_acquire(args['branches'],validate,md) items=items() elif have_arg('branches_expr'): items=args['branches_expr'](md) if not items and have_arg('leaves'): items=1 if items and items != 1: if validate is not None: unauth=[] index=0 for i in items: try: v=validate(items,items,index,i,md) except: v=0 if not v: unauth.append(index) index=index+1 if unauth: if have_arg('skip_unauthorized') and args['skip_unauthorized']: items=list(items) unauth.reverse() for i in unauth: del items[i] else: raise ValidationError, unauth if have_arg('sort'): # 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] if have_arg('reverse'): items=self.reverse_items(items) diff.append(id) sub=None 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) #################################### script=md['SCRIPT_NAME'] if exp: treeData['tree-item-expanded']=1 output('<A NAME="%s">' '<A HREF="%s?tree-c=%s#%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A></A>' % (id, root_url, s, id, script)) else: output('<A NAME="%s">' '<A HREF="%s?tree-e=%s#%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A></A>' % (id, root_url, s, id, 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" ALIGN="LEFT">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(render_blocks(section, 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 md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, 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 if have_arg('leaves'): doc=args['leaves'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,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>', )) finally: md._pop(1) elif have_arg('expand'): doc=args['expand'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,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>', )) finally: md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, idattr): id=getattr(item, idattr) if not simple_type(type(id)): id=id() elif hasattr(item, '_p_oid'): id=oid(item) else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 md._push(InstanceDict(item,md)) try: data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) finally: md._pop() 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 md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, 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,833
def manage_edit(self, title, base, path, REQUEST=None): '''Set the title, base, and path''' self.__init__(title, base, path) if REQUEST: return MessageDialog(title='SiteRoot changed.', message='The title is now "%s"<br>' 'The base is now "%s"<br>' 'The path is now "%s"<br>' % map(escape, (title, base, path)), action='%s/manage_main' % REQUEST['URL1'])
def manage_edit(self, title, base, path, REQUEST=None): '''Set the title, base, and path''' self.__init__(title, base, path) if REQUEST: return MessageDialog(title='SiteRoot changed.', message='SiteRoot changed.', action='%s/manage_main' % REQUEST['URL1'])
1,834
def set_locale(val): try: import locale except: raise SystemExit, ( 'The locale module could not be imported.\n' \ 'To use localization options, you must ensure\n' \ 'that the locale module is compiled into your\n' \ 'Python installation.' ) try: locale.setlocale(locale.LC_ALL, val) except: raise SystemExit, ( 'The specified locale is not supported by your system.\n' \ 'See your operating system documentation for more\n' \ 'information on locale support.' )
def set_locale(val): try: import locale except: raise SystemExit, ( 'The locale module could not be imported.\n' \ 'To use localization options, you must ensure\n' \ 'that the locale module is compiled into your\n' \ 'Python installation.' ) try: locale.setlocale(locale.LC_ALL, val) except: raise SystemExit, ( 'The specified locale is not supported by your system.\n' \ 'See your operating system documentation for more\n' \ 'information on locale support.' )
1,835
def set_locale(val): try: import locale except: raise SystemExit, ( 'The locale module could not be imported.\n' \ 'To use localization options, you must ensure\n' \ 'that the locale module is compiled into your\n' \ 'Python installation.' ) try: locale.setlocale(locale.LC_ALL, val) except: raise SystemExit, ( 'The specified locale is not supported by your system.\n' \ 'See your operating system documentation for more\n' \ 'information on locale support.' )
def set_locale(val): try: import locale except: raise SystemExit, ( 'The locale module could not be imported.\n' \ 'To use localization options, you must ensure\n' \ 'that the locale module is compiled into your\n' \ 'Python installation.' ) try: locale.setlocale(locale.LC_ALL, val) except: raise SystemExit, ( 'The specified locale is not supported by your system.\n' \ 'See your operating system documentation for more\n' \ 'information on locale support.' )
1,836
def set_locale(val): try: import locale except: raise SystemExit, ( 'The locale module could not be imported.\n' \ 'To use localization options, you must ensure\n' \ 'that the locale module is compiled into your\n' \ 'Python installation.' ) try: locale.setlocale(locale.LC_ALL, val) except: raise SystemExit, ( 'The specified locale is not supported by your system.\n' \ 'See your operating system documentation for more\n' \ 'information on locale support.' )
def set_locale(val): try: import locale except: raise SystemExit, ( 'The locale module could not be imported.\n' \ 'To use localization options, you must ensure\n' \ 'that the locale module is compiled into your\n' \ 'Python installation.' ) try: locale.setlocale(locale.LC_ALL, val) except: raise SystemExit, ( 'The specified locale is not supported by your system.\n' \ 'See your operating system documentation for more\n' \ 'information on locale support.' )
1,837
def manage_addLocalRoles(self, userid, roles, REQUEST=None): """Set local roles for a user.""" if not roles: raise ValueError, 'One or more roles must be given!' dict=self.__ac_local_roles__ or {} local_roles = dict.get(userid, []) for r in roles: if r not in local_roles: local_roles.append(r) dict[userid] = local_roles self.__ac_local_roles__=dict if REQUEST is not None: stat='Your changes have been saved.' return self.manage_listLocalRoles(self, REQUEST, stat=stat)
def manage_addLocalRoles(self, userid, roles, REQUEST=None): """Set local roles for a user.""" if not roles: raise ValueError, 'One or more roles must be given!' dict=self.__ac_local_roles__ or {} local_roles = list(dict.get(userid, [])) for r in roles: if r not in local_roles: local_roles.append(r) dict[userid] = local_roles self.__ac_local_roles__=dict if REQUEST is not None: stat='Your changes have been saved.' return self.manage_listLocalRoles(self, REQUEST, stat=stat)
1,838
def StructuredText(paragraphs, paragraph_delimiter=re.compile('\n\s*\n')): """ StructuredText accepts paragraphs, which is a list of lines to be parsed. StructuredText creates a structure which mimics the structure of the paragraphs. Structure => [paragraph,[sub-paragraphs]] """ currentlevel = 0 currentindent = 0 levels = {0:0} level = 0 # which header are we under struct = [] # the structure to be returned run = struct paragraphs = filter( strip, paragraph_delimiter.split(expandtabs('\n\n'+paragraphs+'\n\n')) ) if not paragraphs: return StructuredTextDocument() ind = [] # structure based on indention levels for paragraph in paragraphs: ind.append([indention(paragraph), paragraph]) currentindent = indention(paragraphs[0]) levels[0] = currentindent ############################################################# # updated # ############################################################# for indent,paragraph in ind : if indent == 0: level = level + 1 currentlevel = 0 currentindent = 0 levels = {0:0} struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) elif indent > currentindent: currentlevel = currentlevel + 1 currentindent = indent levels[currentlevel] = indent run = insert(struct,level,currentlevel) run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) elif indent < currentindent: result = findlevel(levels,indent) if result > 0: currentlevel = result currentindent = indent if not level: struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) else: run = insert(struct,level,currentlevel) run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) else: if insert(struct,level,currentlevel): run = insert(struct,level,currentlevel) else: run = struct currentindet = indent run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) return StructuredTextDocument(struct)
def StructuredText(paragraphs, delimiter=re.compile(para_delim)): """ StructuredText accepts paragraphs, which is a list of lines to be parsed. StructuredText creates a structure which mimics the structure of the paragraphs. Structure => [paragraph,[sub-paragraphs]] """ currentlevel = 0 currentindent = 0 levels = {0:0} level = 0 # which header are we under struct = [] # the structure to be returned run = struct paragraphs = filter( strip, paragraph_delimiter.split(expandtabs('\n\n'+paragraphs+'\n\n')) ) if not paragraphs: return StructuredTextDocument() ind = [] # structure based on indention levels for paragraph in paragraphs: ind.append([indention(paragraph), paragraph]) currentindent = indention(paragraphs[0]) levels[0] = currentindent ############################################################# # updated # ############################################################# for indent,paragraph in ind : if indent == 0: level = level + 1 currentlevel = 0 currentindent = 0 levels = {0:0} struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) elif indent > currentindent: currentlevel = currentlevel + 1 currentindent = indent levels[currentlevel] = indent run = insert(struct,level,currentlevel) run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) elif indent < currentindent: result = findlevel(levels,indent) if result > 0: currentlevel = result currentindent = indent if not level: struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) else: run = insert(struct,level,currentlevel) run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) else: if insert(struct,level,currentlevel): run = insert(struct,level,currentlevel) else: run = struct currentindet = indent run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) return StructuredTextDocument(struct)
1,839
def StructuredText(paragraphs, paragraph_delimiter=re.compile('\n\s*\n')): """ StructuredText accepts paragraphs, which is a list of lines to be parsed. StructuredText creates a structure which mimics the structure of the paragraphs. Structure => [paragraph,[sub-paragraphs]] """ currentlevel = 0 currentindent = 0 levels = {0:0} level = 0 # which header are we under struct = [] # the structure to be returned run = struct paragraphs = filter( strip, paragraph_delimiter.split(expandtabs('\n\n'+paragraphs+'\n\n')) ) if not paragraphs: return StructuredTextDocument() ind = [] # structure based on indention levels for paragraph in paragraphs: ind.append([indention(paragraph), paragraph]) currentindent = indention(paragraphs[0]) levels[0] = currentindent ############################################################# # updated # ############################################################# for indent,paragraph in ind : if indent == 0: level = level + 1 currentlevel = 0 currentindent = 0 levels = {0:0} struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) elif indent > currentindent: currentlevel = currentlevel + 1 currentindent = indent levels[currentlevel] = indent run = insert(struct,level,currentlevel) run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) elif indent < currentindent: result = findlevel(levels,indent) if result > 0: currentlevel = result currentindent = indent if not level: struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) else: run = insert(struct,level,currentlevel) run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) else: if insert(struct,level,currentlevel): run = insert(struct,level,currentlevel) else: run = struct currentindet = indent run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) return StructuredTextDocument(struct)
def StructuredText(paragraphs, paragraph_delimiter=re.compile('\n\s*\n')): """ StructuredText accepts paragraphs, which is a list of lines to be parsed. StructuredText creates a structure which mimics the structure of the paragraphs. Structure => [paragraph,[sub-paragraphs]] """ currentlevel = 0 currentindent = 0 levels = {0:0} level = 0 # which header are we under struct = [] # the structure to be returned run = struct paragraphs = expandtabs(paragraphs) paragraphs = '%s%s%s' % ('\n\n', paragraphs, '\n\n') paragraphs = delimiter.split(paragraphs) paragraphs = filter(strip, paragraphs) if not paragraphs: return StructuredTextDocument() ind = [] # structure based on indention levels for paragraph in paragraphs: ind.append([indention(paragraph), paragraph]) currentindent = indention(paragraphs[0]) levels[0] = currentindent ############################################################# # updated # ############################################################# for indent,paragraph in ind : if indent == 0: level = level + 1 currentlevel = 0 currentindent = 0 levels = {0:0} struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) elif indent > currentindent: currentlevel = currentlevel + 1 currentindent = indent levels[currentlevel] = indent run = insert(struct,level,currentlevel) run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) elif indent < currentindent: result = findlevel(levels,indent) if result > 0: currentlevel = result currentindent = indent if not level: struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) else: run = insert(struct,level,currentlevel) run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) else: if insert(struct,level,currentlevel): run = insert(struct,level,currentlevel) else: run = struct currentindet = indent run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) return StructuredTextDocument(struct)
1,840
def query(s, index, default_operator = Or, ws = (string.whitespace,)): # First replace any occurences of " and not " with " andnot " s = regsub.gsub('[%s]+and[%s]*not[%s]+' % (ws * 3), ' andnot ', s) q = parse(s) q = parse2(q, default_operator) return evaluate(q, index)
def query(s, index, default_operator = Or, ws = (string.whitespace,)): # First replace any occurences of " and not " with " andnot " s = ts_regex.gsub('[%s]+and[%s]*not[%s]+' % (ws * 3), ' andnot ', s) q = parse(s) q = parse2(q, default_operator) return evaluate(q, index)
1,841
def parens(s, parens_regex = regex.compile("(\|)")): '''Find the beginning and end of the first set of parentheses''' if (parens_regex.search(s) < 0): return None if (parens_regex.group(0) == ")"): raise QueryError, "Mismatched parentheses" open = parens_regex.regs[0][0] + 1 start = parens_regex.regs[0][1] p = 1 while (parens_regex.search(s, start) >= 0): if (parens_regex.group(0) == ")"): p = p - 1 else: p = p + 1 start = parens_regex.regs[0][1] if (p == 0): return (open, parens_regex.regs[0][0]) raise QueryError, "Mismatched parentheses"
def parens(s, parens_re = regex.compile('(\|)').search): index=open_index=paren_count = 0 while 1: index = parens_re(s, index) if index < 0 : break if s[index] == '(': paren_count = paren_count + 1 if open_index == 0 : open_index = index + 1 else: paren_count = paren_count - 1 if paren_count == 0: return open_index, index else: index = index + 1 if paren_count == 0: return None else: raise QueryError, "Mismatched parentheses"
1,842
def quotes(s, ws = (string.whitespace,)): # split up quoted regions splitted = regsub.split(s, '[%s]*\"[%s]*' % (ws * 2)) split=string.split if (len(splitted) > 1): if ((len(splitted) % 2) == 0): raise QueryError, "Mismatched quotes" for i in range(1,len(splitted),2): # split the quoted region into words splitted[i] = filter(None, split(splitted[i])) # put the Proxmity operator in between quoted words for j in range(1, len(splitted[i])): splitted[i][j : j] = [ Near ] for i in range(len(splitted)-1,-1,-2): # split the non-quoted region into words splitted[i:i+1] = filter(None, split(splitted[i])) splitted = filter(None, splitted) else: # No quotes, so just split the string into words splitted = filter(None, split(s)) return splitted
def quotes(s, ws = (string.whitespace,)): # split up quoted regions splitted = ts_regex.split(s, '[%s]*\"[%s]*' % (ws * 2)) split=string.split if (len(splitted) > 1): if ((len(splitted) % 2) == 0): raise QueryError, "Mismatched quotes" for i in range(1,len(splitted),2): # split the quoted region into words splitted[i] = filter(None, split(splitted[i])) # put the Proxmity operator in between quoted words for j in range(1, len(splitted[i])): splitted[i][j : j] = [ Near ] for i in range(len(splitted)-1,-1,-2): # split the non-quoted region into words splitted[i:i+1] = filter(None, split(splitted[i])) splitted = filter(None, splitted) else: # No quotes, so just split the string into words splitted = filter(None, split(s)) return splitted
1,843
def emit(self, record): try: self.buffer.append(record) msg = self.format(record) self.stream.write("%s\n" % msg) self.flush() except: self.handleError()
def emit(self, record): try: self.buffer.append(record) msg = self.format(record) self.stream.write("%s\n" % msg) self.flush() except: self.handleError()
1,844
def traverse(self, path, response=None): """Traverse the object space
def traverse(self, path, response=None): """Traverse the object space
1,845
def traverse(self, path, response=None): """Traverse the object space
def traverse(self, path, response=None): """Traverse the object space
1,846
def __init__(self, id, title, bases): """Build a Zope class
def __init__(self, id, title, bases): """Build a Zope class
1,847
#def manage_workspace(self, URL1):
#def manage_workspace(self, URL1):
1,848
def __init__(self,id,title,file, precondition='',content_type='application/octet-stream'): try: headers=file.headers except: headers=None if headers is None: if not content_type: raise 'BadValue', 'No content type specified' self.content_type=content_type self.data=Pdata(file) else: if headers.has_key('content-type'): self.content_type=headers['content-type'] else: if not content_type: raise 'BadValue', 'No content type specified' self.content_type=content_type self.data=Pdata(file.read()) self.__name__=id self.title=title if precondition: self.precondition=precondition self.size=len(self.data)
def __init__(self,id,title,file,content_type='application/octet-stream', precondition=''): try: headers=file.headers except: headers=None if headers is None: if not content_type: raise 'BadValue', 'No content type specified' self.content_type=content_type self.data=Pdata(file) else: if headers.has_key('content-type'): self.content_type=headers['content-type'] else: if not content_type: raise 'BadValue', 'No content type specified' self.content_type=content_type self.data=Pdata(file.read()) self.__name__=id self.title=title if precondition: self.precondition=precondition self.size=len(self.data)
1,849
def detailedusage(): details = usage(0) pname = sys.argv[0] details = details + """
def detailedusage(): details = usage(0) pname = sys.argv[0] details = details + """
1,850
def detailedusage(): details = usage(0) pname = sys.argv[0] details = details + """
def detailedusage(): details = usage(0) pname = sys.argv[0] details = details + """
1,851
def numObjects(self): """ return the number of indexed objects""" try: return self._length() except AttributeError: # backward compatibility l = len(self._unindex) self._length = Length(l) return l
def numObjects(self): """ return the number of indexed objects""" try: return self._length() except AttributeError: # backward compatibility l = len(self._unindex) self._length = Length(l) return l
1,852
def handle_read (self): self.recv (8192) try: self.lock.acquire() for thunk in self.thunks: try: thunk() except: (file, fun, line), t, v, tbinfo = asyncore.compact_traceback() print 'exception in trigger thunk: (%s:%s %s)' % (t, v, tbinfo) self.thunks = [] finally: self.lock.release()
def handle_read (self): self.recv (8192) try: self.lock.acquire() for thunk in self.thunks: try: thunk() except: (file, fun, line), t, v, tbinfo = asyncore.compact_traceback() print 'exception in trigger thunk: (%s:%s %s)' % (t, v, tbinfo) self.thunks = [] finally: self.lock.release()
1,853
def __init__ (self): a = socket.socket (socket.AF_INET, socket.SOCK_STREAM) w = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # set TCP_NODELAY to true to avoid buffering w.setsockopt(socket.IPPROTO_TCP, 1, 1) # tricky: get a pair of connected sockets host='127.0.0.1' port=19999 while 1: try: self.address=(host, port) a.bind(self.address) break except: if port <= 19950: raise BindError, 'Cannot bind trigger!' port=port - 1 a.listen (1) w.setblocking (0) try: w.connect (self.address) except: pass r, addr = a.accept() a.close() w.setblocking (1) self.trigger = w asyncore.dispatcher.__init__ (self, r) self.lock = thread.allocate_lock() self.thunks = [] self._trigger_connected = 0
def __init__ (self): a = socket.socket (socket.AF_INET, socket.SOCK_STREAM) w = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # set TCP_NODELAY to true to avoid buffering w.setsockopt(socket.IPPROTO_TCP, 1, 1) # tricky: get a pair of connected sockets host='127.0.0.1' port=19999 while 1: try: self.address=(host, port) a.bind(self.address) break except: if port <= 19950: raise BindError, 'Cannot bind trigger!' port=port - 1 a.listen (1) w.setblocking (0) try: w.connect (self.address) except: pass r, addr = a.accept() a.close() w.setblocking (1) self.trigger = w asyncore.dispatcher.__init__ (self, r) self.lock = thread.allocate_lock() self.thunks = [] self._trigger_connected = 0
1,854
def __init__ (self): a = socket.socket (socket.AF_INET, socket.SOCK_STREAM) w = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # set TCP_NODELAY to true to avoid buffering w.setsockopt(socket.IPPROTO_TCP, 1, 1) # tricky: get a pair of connected sockets host='127.0.0.1' port=19999 while 1: try: self.address=(host, port) a.bind(self.address) break except: if port <= 19950: raise BindError, 'Cannot bind trigger!' port=port - 1 a.listen (1) w.setblocking (0) try: w.connect (self.address) except: pass r, addr = a.accept() a.close() w.setblocking (1) self.trigger = w asyncore.dispatcher.__init__ (self, r) self.lock = thread.allocate_lock() self.thunks = [] self._trigger_connected = 0
def __init__ (self): a = socket.socket (socket.AF_INET, socket.SOCK_STREAM) w = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # set TCP_NODELAY to true to avoid buffering w.setsockopt(socket.IPPROTO_TCP, 1, 1) # tricky: get a pair of connected sockets host='127.0.0.1' port=19999 while 1: count += 1 a = socket.socket() a.bind(("127.0.0.1", 0)) connect_address = a.getsockname() a.listen(1) try: w.connect(connect_address) break except socket.error, detail: if detail[0] != errno.WSAEADDRINUSE: raise if count >= 10: a.close() w.close() raise BindError("Cannot bind trigger!") a.close() r, addr = a.accept() a.close() w.setblocking (1) self.trigger = w asyncore.dispatcher.__init__ (self, r) self.lock = thread.allocate_lock() self.thunks = [] self._trigger_connected = 0
1,855
def __init__ (self): a = socket.socket (socket.AF_INET, socket.SOCK_STREAM) w = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # set TCP_NODELAY to true to avoid buffering w.setsockopt(socket.IPPROTO_TCP, 1, 1) # tricky: get a pair of connected sockets host='127.0.0.1' port=19999 while 1: try: self.address=(host, port) a.bind(self.address) break except: if port <= 19950: raise BindError, 'Cannot bind trigger!' port=port - 1 a.listen (1) w.setblocking (0) try: w.connect (self.address) except: pass r, addr = a.accept() a.close() w.setblocking (1) self.trigger = w asyncore.dispatcher.__init__ (self, r) self.lock = thread.allocate_lock() self.thunks = [] self._trigger_connected = 0
def __init__ (self): a = socket.socket (socket.AF_INET, socket.SOCK_STREAM) w = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # set TCP_NODELAY to true to avoid buffering w.setsockopt(socket.IPPROTO_TCP, 1, 1) # tricky: get a pair of connected sockets host='127.0.0.1' port=19999 while 1: try: self.address=(host, port) a.bind(self.address) break except: if port <= 19950: raise BindError, 'Cannot bind trigger!' port=port - 1 a.listen (1) w.setblocking (0) try: w.connect (self.address) except: pass r, addr = a.accept() a.close() self.trigger = w asyncore.dispatcher.__init__ (self, r) self.lock = thread.allocate_lock() self.thunks = [] self._trigger_connected = 0
1,856
def __init__ (self): a = socket.socket (socket.AF_INET, socket.SOCK_STREAM) w = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # set TCP_NODELAY to true to avoid buffering w.setsockopt(socket.IPPROTO_TCP, 1, 1) # tricky: get a pair of connected sockets host='127.0.0.1' port=19999 while 1: try: self.address=(host, port) a.bind(self.address) break except: if port <= 19950: raise BindError, 'Cannot bind trigger!' port=port - 1 a.listen (1) w.setblocking (0) try: w.connect (self.address) except: pass r, addr = a.accept() a.close() w.setblocking (1) self.trigger = w asyncore.dispatcher.__init__ (self, r) self.lock = thread.allocate_lock() self.thunks = [] self._trigger_connected = 0
def__init__(self):a=socket.socket(socket.AF_INET,socket.SOCK_STREAM)w=socket.socket(socket.AF_INET,socket.SOCK_STREAM)#setTCP_NODELAYtotruetoavoidbufferingw.setsockopt(socket.IPPROTO_TCP,1,1)#tricky:getapairofconnectedsocketshost='127.0.0.1'port=19999while1:try:self.address=(host,port)a.bind(self.address)breakexcept:ifport<=19950:raiseBindError,'Cannotbindtrigger!'port=port-1a.listen(1)w.setblocking(0)try:w.connect(self.address)except:passr,addr=a.accept()a.close()w.setblocking(1)self.trigger=wasyncore.dispatcher.__init__(self,r)self.lock=thread.allocate_lock()self.thunks=[]self._trigger_connected=0
1,857
def __repr__ (self): return '<select-trigger (loopback) at %x>' % id(self)
def __repr__(self): return '<select-trigger (loopback) at %x>' % id(self)
1,858
def readable (self): return 1
def readable(self): return 1
1,859
def writable (self): return 0
def writable(self): return 0
1,860
def handle_connect (self): pass
def handle_connect(self): pass
1,861
def pull_trigger (self, thunk=None): if thunk: try: self.lock.acquire() self.thunks.append (thunk) finally: self.lock.release() self.trigger.send ('x')
def pull_trigger(self, thunk=None): if thunk: try: self.lock.acquire() self.thunks.append (thunk) finally: self.lock.release() self.trigger.send ('x')
1,862
def handle_read (self): self.recv (8192) try: self.lock.acquire() for thunk in self.thunks: try: thunk() except: (file, fun, line), t, v, tbinfo = asyncore.compact_traceback() print 'exception in trigger thunk: (%s:%s %s)' % (t, v, tbinfo) self.thunks = [] finally: self.lock.release()
def handle_read(self): self.recv(8192) try: self.lock.acquire() for thunk in self.thunks: try: thunk() except: (file, fun, line), t, v, tbinfo = asyncore.compact_traceback() print 'exception in trigger thunk: (%s:%s %s)' % (t, v, tbinfo) self.thunks = [] finally: self.lock.release()
1,863
def testPublicFuncWithWrongAuth(self): """ testing PublicFunc"""
def testPublicFuncWithWrongAuth(self): """ testing PublicFunc"""
1,864
def testProtectedFunc(self): """ testing PrivateFunc"""
def testProtectedFunc(self): """ testing PrivateFunc"""
1,865
def _request(self,*args,**kw):
def _request(self,*args,**kw):
1,866
def _request(self,*args,**kw):
def _request(self,*args,**kw):
1,867
def __init__(self, aStructuredString, level=0, paragraph_divider=regex.compile('\(\n *\)+\n'), ): '''Convert a structured text string into a structured text object.
def __init__(self, aStructuredString, level=0, paragraph_divider=regex.compile('\(\n *\)+\n'), ): '''Convert a structured text string into a structured text object.
1,868
def __init__(self, aStructuredString, level=0, paragraph_divider=regex.compile('\(\n *\)+\n'), ): '''Convert a structured text string into a structured text object.
def __init__(self, aStructuredString, level=0, paragraph_divider=regex.compile('\(\n *\)+\n'), ): '''Convert a structured text string into a structured text object.
1,869
def oct12(i): i=oct(i) return '0'*(11-len(i))+i+' '
def oct12(i): i=oct(i) v = '0'*(11-len(i))+i+' ' if len(v) > 12: left = v[:-12] for c in left: if c != '0': raise ValueError, 'value too large for oct12' return v[-12:] return v
1,870
def manage_addFile(self,id,file,title='',precondition='', content_type='', REQUEST=None): """Add a new File object. Creates a new File object 'id' with the contents of 'file'""" id, title = cookId(id, title, file) self=self.this() # First, we create the image without data: self._setObject(id, File(id,title,'',content_type, precondition)) # And commit to a sub-transaction: if Globals.DatabaseVersion=='3': get_transaction().commit(1) # Now we "upload" the data. By commiting the add first, the # object can use a database trick to make the upload more efficient. self._getOb(id).manage_upload(file) if REQUEST is not None: return self.manage_main(self,REQUEST)
def manage_addFile(self,id,file,title='',precondition='', content_type='', REQUEST=None): """Add a new File object. Creates a new File object 'id' with the contents of 'file'""" id, title = cookId(id, title, file) self=self.this() # First, we create the image without data: self._setObject(id, File(id,title,'',content_type, precondition)) # And commit to a sub-transaction: if Globals.DatabaseVersion=='3': get_transaction().commit(1) # Now we "upload" the data. By commiting the add first, the # object can use a database trick to make the upload more efficient. self._getOb(id).manage_upload(file) if REQUEST is not None: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
1,871
def __init__(self, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, environ=os.environ): self.environ=environ fp=None try: if environ['REQUEST_METHOD'] != 'GET': fp=stdin except: pass
def __init__(self, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, environ=os.environ): self.environ=environ fp=None try: if environ['REQUEST_METHOD'] != 'GET': fp=stdin except: pass
1,872
def getEntryForObject(self, documentId, default=None): """Takes a document ID and returns all the information we have on that specific object.""" if default is None: return self._unindex.get(documentId, default) else: return self._unindex.get(documentId)
def getEntryForObject(self, documentId, default=MV): """Takes a document ID and returns all the information we have on that specific object.""" if default is None: return self._unindex.get(documentId, default) else: return self._unindex.get(documentId)
1,873
def getEntryForObject(self, documentId, default=None): """Takes a document ID and returns all the information we have on that specific object.""" if default is None: return self._unindex.get(documentId, default) else: return self._unindex.get(documentId)
def getEntryForObject(self, documentId, default=None): """Takes a document ID and returns all the information we have on that specific object.""" if default is not MV: return self._unindex.get(documentId, default) else: return self._unindex.get(documentId)
1,874
def _cached_result(self, DB__, query, compressed=0):
def _cached_result(self, DB__, query, compressed=0):
1,875
def cb_isCopyable(self): pass # for now, we don't allow ZClasses to be copied.
def cb_isCopyable(self): pass # for now, we don't allow ZClasses to be copied.
1,876
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,877
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,878
def main(): # The "main" program for this module pass
def main(): # The "main" program for this module pass
1,879
def field2lines(v): try: v=v.read() except: v=str(v) return string.split(v,'\n')
def field2lines(v, crlf=regex.compile('\r\n\|\n\r')): try: v=v.read() except: v=str(v) return string.split(v,'\n')
1,880
def __call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw): """Call the database method
def __call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw): """Call the database method
1,881
def __init__(self,*args, **kw): """Return a new date-time object
def __init__(self,*args, **kw): """Return a new date-time object
1,882
def getLastChild(self): """The last child of this node. If ther is no such node this returns None.""" return None
def getLastChild(self): """The last child of this node. If ther is no such node this returns None.""" return None
1,883
def parseAttributeReplacements(arg): dict = {} for part in splitParts(arg): m = _attr_re.match(part) if not m: print "Bad syntax in z:attributes:", `part` continue name, expr = m.group(1, 2) if dict.has_key(name): print "Duplicate attribute name in z:attributes:", `part` continue dict[name] = expr return dict
def parseAttributeReplacements(arg): dict = {} for part in splitParts(arg): m = _attr_re.match(part) if not m: print "Bad syntax in attributes:", `part` continue name, expr = m.group(1, 2) if dict.has_key(name): print "Duplicate attribute name in z:attributes:", `part` continue dict[name] = expr return dict
1,884
def parseAttributeReplacements(arg): dict = {} for part in splitParts(arg): m = _attr_re.match(part) if not m: print "Bad syntax in z:attributes:", `part` continue name, expr = m.group(1, 2) if dict.has_key(name): print "Duplicate attribute name in z:attributes:", `part` continue dict[name] = expr return dict
def parseAttributeReplacements(arg): dict = {} for part in splitParts(arg): m = _attr_re.match(part) if not m: print "Bad syntax in z:attributes:", `part` continue name, expr = m.group(1, 2) if dict.has_key(name): print "Duplicate attribute name in attributes:", `part` continue dict[name] = expr return dict
1,885
def parseSubstitution(arg): m = _subst_re.match(arg) if not m: print "Bad syntax in z:insert/replace:", `arg` return None, None key, expr = m.group(1, 2) if not key: key = "text" return key, expr
def parseSubstitution(arg): m = _subst_re.match(arg) if not m: print "Bad syntax in insert/replace:", `arg` return None, None key, expr = m.group(1, 2) if not key: key = "text" return key, expr
1,886
def splitParts(arg): # Break in pieces at undoubled semicolons and # change double semicolons to singles: import string arg = string.replace(arg, ";;", "\0") parts = string.split(arg, ';') parts = map(lambda s, repl=string.replace: repl(s, "\0", ";;"), parts) if len(parts) > 1 and not string.strip(parts[-1]): del parts[-1] # It ended in a semicolon return parts
def splitParts(arg): # Break in pieces at undoubled semicolons and # change double semicolons to singles: import string arg = string.replace(arg, ";;", "\0") parts = string.split(arg, ';') parts = map(lambda s, repl=string.replace: repl(s, "\0", ";"), parts) if len(parts) > 1 and not string.strip(parts[-1]): del parts[-1] # It ended in a semicolon return parts
1,887
def __init__(self, program, macros, engine, stream=None, debug=0, wrap=60, metal=1, tal=1, showtal=-1, strictinsert=1, stackLimit=100): self.program = program self.macros = macros self.engine = engine self.TALESError = engine.getTALESError() self.Default = engine.getDefault() self.stream = stream or sys.stdout self.debug = debug self.wrap = wrap self.metal = metal self.tal = tal assert showtal in (-1, 0, 1) if showtal == -1: showtal = (not tal) self.showtal = showtal self.strictinsert = strictinsert self.stackLimit = stackLimit self.html = 0 self.endsep = "/>" self.macroStack = [] self.definingMacro = None self.position = None, None # (lineno, offset) self.col = 0 self.level = 0 self.scopeLevel = 0
def __init__(self, program, macros, engine, stream=None, debug=0, wrap=60, metal=1, tal=1, showtal=-1, strictinsert=1, stackLimit=100): self.program = program self.macros = macros self.engine = engine self.TALESError = engine.getTALESError() self.Default = engine.getDefault() self.stream = stream or sys.stdout self.debug = debug self.wrap = wrap self.metal = metal self.tal = tal assert showtal in (-1, 0, 1) if showtal == -1: showtal = (not tal) self.showtal = showtal self.strictinsert = strictinsert self.stackLimit = stackLimit self.html = 0 self.endsep = "/>" self.macroStack = [] self.position = None, None # (lineno, offset) self.col = 0 self.level = 0 self.scopeLevel = 0
1,888
def attrAction(self, item): name, value = item[:2] try: action = self.actionIndex[item[2]] except KeyError: raise TALError, ('Error in TAL program', self.position) if not self.showtal and action > 1: return 0, name, value ok = 1 if action <= 1 and self.tal: if self.html and string.lower(name) in BOOLEAN_HTML_ATTRS: evalue = self.engine.evaluateBoolean(item[3]) if evalue is self.Default: if action == 1: # Cancelled insert ok = 0 elif not evalue: ok = 0 else: value = None else: evalue = self.engine.evaluateText(item[3]) if evalue is self.Default: if action == 1: # Cancelled insert ok = 0 else: value = evalue if value is None: ok = 0 elif action == 2 and self.macroStack: i = string.rfind(name, ":") + 1 prefix, suffix = name[:i], name[i:] if suffix == "define-macro": if len(self.macroStack) == 1: macroName, slots = self.macroStack[-1] name = prefix + "use-macro" value = macroName else: ok = 0 if suffix == "fill-slot": macroName, slots = self.macroStack[0] if not slots.has_key(value): ok = 0 if suffix == "define-slot" and not self.definingMacro: name = prefix + "fill-slot" elif action == 1: # Unexecuted insert ok = 0 return ok, name, value
def attrAction(self, item): name, value = item[:2] try: action = self.actionIndex[item[2]] except KeyError: raise TALError, ('Error in TAL program', self.position) if not self.showtal and action > 1: return 0, name, value ok = 1 if action <= 1 and self.tal: if self.html and string.lower(name) in BOOLEAN_HTML_ATTRS: evalue = self.engine.evaluateBoolean(item[3]) if evalue is self.Default: if action == 1: # Cancelled insert ok = 0 elif not evalue: ok = 0 else: value = None else: evalue = self.engine.evaluateText(item[3]) if evalue is self.Default: if action == 1: # Cancelled insert ok = 0 else: value = evalue if value is None: ok = 0 elif action == 2 and self.metal: i = string.rfind(name, ":") + 1 prefix, suffix = name[:i], name[i:] if suffix == "define-macro": if len(self.macroStack) == 1: macroName, slots = self.macroStack[-1] name = prefix + "use-macro" value = macroName else: ok = 0 if suffix == "fill-slot": macroName, slots = self.macroStack[0] if not slots.has_key(value): ok = 0 if suffix == "define-slot" and not self.definingMacro: name = prefix + "fill-slot" elif action == 1: # Unexecuted insert ok = 0 return ok, name, value
1,889
def attrAction(self, item): name, value = item[:2] try: action = self.actionIndex[item[2]] except KeyError: raise TALError, ('Error in TAL program', self.position) if not self.showtal and action > 1: return 0, name, value ok = 1 if action <= 1 and self.tal: if self.html and string.lower(name) in BOOLEAN_HTML_ATTRS: evalue = self.engine.evaluateBoolean(item[3]) if evalue is self.Default: if action == 1: # Cancelled insert ok = 0 elif not evalue: ok = 0 else: value = None else: evalue = self.engine.evaluateText(item[3]) if evalue is self.Default: if action == 1: # Cancelled insert ok = 0 else: value = evalue if value is None: ok = 0 elif action == 2 and self.macroStack: i = string.rfind(name, ":") + 1 prefix, suffix = name[:i], name[i:] if suffix == "define-macro": if len(self.macroStack) == 1: macroName, slots = self.macroStack[-1] name = prefix + "use-macro" value = macroName else: ok = 0 if suffix == "fill-slot": macroName, slots = self.macroStack[0] if not slots.has_key(value): ok = 0 if suffix == "define-slot" and not self.definingMacro: name = prefix + "fill-slot" elif action == 1: # Unexecuted insert ok = 0 return ok, name, value
def attrAction(self, item): name, value = item[:2] try: action = self.actionIndex[item[2]] except KeyError: raise TALError, ('Error in TAL program', self.position) if not self.showtal and action > 1: return 0, name, value ok = 1 if action <= 1 and self.tal: if self.html and string.lower(name) in BOOLEAN_HTML_ATTRS: evalue = self.engine.evaluateBoolean(item[3]) if evalue is self.Default: if action == 1: # Cancelled insert ok = 0 elif not evalue: ok = 0 else: value = None else: evalue = self.engine.evaluateText(item[3]) if evalue is self.Default: if action == 1: # Cancelled insert ok = 0 else: value = evalue if value is None: ok = 0 elif action == 2 and self.macroStack: i = string.rfind(name, ":") + 1 prefix, suffix = name[:i], name[i:] if suffix == "define-macro": if what == "use-macro": name = prefix + "use-macro" value = macroName else: ok = 0 if suffix == "fill-slot": macroName, slots = self.macroStack[0] if not slots.has_key(value): ok = 0 if suffix == "define-slot" and not self.definingMacro: name = prefix + "fill-slot" elif action == 1: # Unexecuted insert ok = 0 return ok, name, value
1,890
def attrAction(self, item): name, value = item[:2] try: action = self.actionIndex[item[2]] except KeyError: raise TALError, ('Error in TAL program', self.position) if not self.showtal and action > 1: return 0, name, value ok = 1 if action <= 1 and self.tal: if self.html and string.lower(name) in BOOLEAN_HTML_ATTRS: evalue = self.engine.evaluateBoolean(item[3]) if evalue is self.Default: if action == 1: # Cancelled insert ok = 0 elif not evalue: ok = 0 else: value = None else: evalue = self.engine.evaluateText(item[3]) if evalue is self.Default: if action == 1: # Cancelled insert ok = 0 else: value = evalue if value is None: ok = 0 elif action == 2 and self.macroStack: i = string.rfind(name, ":") + 1 prefix, suffix = name[:i], name[i:] if suffix == "define-macro": if len(self.macroStack) == 1: macroName, slots = self.macroStack[-1] name = prefix + "use-macro" value = macroName else: ok = 0 if suffix == "fill-slot": macroName, slots = self.macroStack[0] if not slots.has_key(value): ok = 0 if suffix == "define-slot" and not self.definingMacro: name = prefix + "fill-slot" elif action == 1: # Unexecuted insert ok = 0 return ok, name, value
def attrAction(self, item): name, value = item[:2] try: action = self.actionIndex[item[2]] except KeyError: raise TALError, ('Error in TAL program', self.position) if not self.showtal and action > 1: return 0, name, value ok = 1 if action <= 1 and self.tal: if self.html and string.lower(name) in BOOLEAN_HTML_ATTRS: evalue = self.engine.evaluateBoolean(item[3]) if evalue is self.Default: if action == 1: # Cancelled insert ok = 0 elif not evalue: ok = 0 else: value = None else: evalue = self.engine.evaluateText(item[3]) if evalue is self.Default: if action == 1: # Cancelled insert ok = 0 else: value = evalue if value is None: ok = 0 elif action == 2 and self.macroStack: i = string.rfind(name, ":") + 1 prefix, suffix = name[:i], name[i:] if suffix == "define-macro": if len(self.macroStack) == 1: macroName, slots = self.macroStack[-1] name = prefix + "use-macro" value = macroName else: assert what == "define-macro" i = self.macroContext("use-macro") if i >= 0: j = self.macroContext("define-slot") if j > i: name = prefix + "use-macro" else: ok = 0 elif suffix == "define-slot": assert what == "define-slot" if self.macroContext("use-macro") >= 0: name = prefix + "fill-slot" elif action == 1: # Unexecuted insert ok = 0 return ok, name, value
1,891
## def dumpMacroStack(self, prefix, suffix, value):
## def dumpMacroStack(self, prefix, suffix, value):
1,892
def do_defineMacro(self, macroName, macro): save = self.definingMacro self.definingMacro = macroName self.interpret(macro) self.definingMacro = save
def do_defineMacro(self, macroName, macro): if not self.metal: self.interpret(macro) return self.pushMacro("define-macro", macroName, None) self.interpret(macro) self.definingMacro = save
1,893
def do_defineMacro(self, macroName, macro): save = self.definingMacro self.definingMacro = macroName self.interpret(macro) self.definingMacro = save
def do_defineMacro(self, macroName, macro): save = self.definingMacro self.definingMacro = macroName self.interpret(macro) self.definingMacro = save
1,894
def do_useMacro(self, macroName, macroExpr, compiledSlots, block): if not self.metal: self.interpret(block) return macro = self.engine.evaluateMacro(macroExpr) if macro is self.Default: self.interpret(block) return if not isCurrentVersion(macro): raise METALError("macro %s has incompatible version %s" % (`macroName`, `getProgramVersion(macro)`), self.position) mode = getProgramMode(macro) if mode != (self.html and "html" or "xml"): raise METALError("macro %s has incompatible mode %s" % (`macroName`, `mode`), self.position) if len(self.macroStack) >= self.stackLimit: raise METALError("macro nesting limit (%d) exceeded " "by macro %s" % (self.stackLimit, `macroName`)) self.macroStack.append((macroName, compiledSlots)) self.interpret(macro) self.macroStack.pop()
def do_useMacro(self, macroName, macroExpr, compiledSlots, block): if not self.metal: self.interpret(block) return macro = self.engine.evaluateMacro(macroExpr) if macro is self.Default: self.interpret(block) return if not isCurrentVersion(macro): raise METALError("macro %s has incompatible version %s" % (`macroName`, `getProgramVersion(macro)`), self.position) mode = getProgramMode(macro) if mode != (self.html and "html" or "xml"): raise METALError("macro %s has incompatible mode %s" % (`macroName`, `mode`), self.position) self.pushMacro("use-macro", macroName, compiledSlots) self.interpret(macro) self.macroStack.pop()
1,895
def do_useMacro(self, macroName, macroExpr, compiledSlots, block): if not self.metal: self.interpret(block) return macro = self.engine.evaluateMacro(macroExpr) if macro is self.Default: self.interpret(block) return if not isCurrentVersion(macro): raise METALError("macro %s has incompatible version %s" % (`macroName`, `getProgramVersion(macro)`), self.position) mode = getProgramMode(macro) if mode != (self.html and "html" or "xml"): raise METALError("macro %s has incompatible mode %s" % (`macroName`, `mode`), self.position) if len(self.macroStack) >= self.stackLimit: raise METALError("macro nesting limit (%d) exceeded " "by macro %s" % (self.stackLimit, `macroName`)) self.macroStack.append((macroName, compiledSlots)) self.interpret(macro) self.macroStack.pop()
def do_useMacro(self, macroName, macroExpr, compiledSlots, block): if not self.metal: self.interpret(block) return macro = self.engine.evaluateMacro(macroExpr) if macro is self.Default: self.interpret(block) return if not isCurrentVersion(macro): raise METALError("macro %s has incompatible version %s" % (`macroName`, `getProgramVersion(macro)`), self.position) mode = getProgramMode(macro) if mode != (self.html and "html" or "xml"): raise METALError("macro %s has incompatible mode %s" % (`macroName`, `mode`), self.position) if len(self.macroStack) >= self.stackLimit: raise METALError("macro nesting limit (%d) exceeded " "by macro %s" % (self.stackLimit, `macroName`)) self.macroStack.append((macroName, compiledSlots)) self.interpret(macro) self.macroStack.pop()
1,896
def do_defineSlot(self, slotName, block): slot = None for macroName, slots in self.macroStack: slot = slots.get(slotName) or slot if slot: self.interpret(slot) else: self.interpret(block)
def do_defineSlot(self, slotName, block): slot = None for what, macroName, slots in self.macroStack: if what == "use-macro" and slots is not None: slot = slots.get(slotName, slot) self.pushMacro("define-slot", slotName, None) if slot: self.interpret(slot) else: self.interpret(block)
1,897
def raise_standardErrorMessage( self, client=None, REQUEST={}, error_type=None, error_value=None, tb=None, error_tb=None, error_message='', tagSearch=ts_regex.compile('[a-zA-Z]>').search):
def raise_standardErrorMessage( self, client=None, REQUEST={}, error_type=None, error_value=None, tb=None, error_tb=None, error_message='', tagSearch=ts_regex.compile('[a-zA-Z]>').search):
1,898
def testHybrid(self): '''Test hybrid path expressions''' ec = self.ec assert ec.evaluate('x | python:1+1') == 2
def testHybrid(self): '''Test hybrid path expressions''' ec = self.ec assert ec.evaluate('x | python:1+1') == 2
1,899