rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
def dump_string(self, value):
def dump_string(self, value, escape=escape):
def dump_string(self, value): self.write("<value><string>%s</string></value>\n" % escape(value))
def dump_unicode(self, value):
def dump_unicode(self, value, escape=escape):
def dump_unicode(self, value): value = value.encode(self.encoding) self.write("<value><string>%s</string></value>\n" % escape(value))
def container(self, value):
def opencontainer(self, value):
def container(self, value): if value: i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive data structures" self.memo[i] = None
self.container(value)
self.opencontainer(value)
def dump_array(self, value): self.container(value) write = self.write write("<value><array><data>\n") for v in value: self.__dump(v) write("</data></array></value>\n")
self.__dump(v)
dump(v)
def dump_array(self, value): self.container(value) write = self.write write("<value><array><data>\n") for v in value: self.__dump(v) write("</data></array></value>\n")
def dump_struct(self, value): self.container(value)
def dump_struct(self, value, escape=escape): self.opencontainer(value)
def dump_struct(self, value): self.container(value) write = self.write write("<value><struct>\n") for k, v in value.items(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) self.__dump(v) write("</member>\n") write("</struct></value>\n")
self.__dump(v)
dump(v)
def dump_struct(self, value): self.container(value) write = self.write write("<value><struct>\n") for k, v in value.items(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) self.__dump(v) write("</member>\n") write("</struct></value>\n")
self._encoding = encoding or "utf-8"
self._encoding = encoding
def xml(self, encoding, standalone): self._encoding = encoding or "utf-8" # FIXME: assert standalone == 1 ???
if tag in ("array", "struct"):
if tag == "array" or tag == "struct":
def start(self, tag, attrs): # prepare to handle this element if tag in ("array", "struct"): self._marks.append(len(self._stack)) self._data = [] self._value = (tag == "value")
dispatch = {} def end(self, tag):
def end(self, tag, join=string.join):
def data(self, text): self._data.append(text)
return f(self)
return f(self, join(self._data, "")) def end_dispatch(self, tag, data): try: f = self.dispatch[tag] except KeyError: pass else: return f(self, data)
def end(self, tag): # call the appropriate end tag handler try: f = self.dispatch[tag] except KeyError: pass # unknown tag ? else: return f(self)
def end_boolean(self, join=string.join): value = join(self._data, "") if value == "0":
dispatch = {} def end_boolean(self, data): if data == "0":
def end_boolean(self, join=string.join): value = join(self._data, "") if value == "0": self.append(False) elif value == "1": self.append(True) else: raise TypeError, "bad boolean value" self._value = 0
elif value == "1":
elif data == "1":
def end_boolean(self, join=string.join): value = join(self._data, "") if value == "0": self.append(False) elif value == "1": self.append(True) else: raise TypeError, "bad boolean value" self._value = 0
def end_int(self, join=string.join): self.append(int(join(self._data, "")))
def end_int(self, data): self.append(int(data))
def end_int(self, join=string.join): self.append(int(join(self._data, ""))) self._value = 0
def end_double(self, join=string.join): self.append(float(join(self._data, "")))
def end_double(self, data): self.append(float(data))
def end_double(self, join=string.join): self.append(float(join(self._data, ""))) self._value = 0
def end_string(self, join=string.join): data = join(self._data, "")
def end_string(self, data):
def end_string(self, join=string.join): data = join(self._data, "") if self._encoding: data = _decode(data, self._encoding) self.append(data) self._value = 0
self.append(data)
self.append(_stringify(data))
def end_string(self, join=string.join): data = join(self._data, "") if self._encoding: data = _decode(data, self._encoding) self.append(data) self._value = 0
def end_array(self):
def end_array(self, data):
def end_array(self): mark = self._marks[-1] del self._marks[-1] # map arrays to Python lists self._stack[mark:] = [self._stack[mark:]] self._value = 0
def end_struct(self):
def end_struct(self, data):
def end_struct(self): mark = self._marks[-1] del self._marks[-1] # map structs to Python dictionaries dict = {} items = self._stack[mark:] for i in range(0, len(items), 2): dict[items[i]] = items[i+1] self._stack[mark:] = [dict] self._value = 0
dict[items[i]] = items[i+1]
dict[_stringify(items[i])] = items[i+1]
def end_struct(self): mark = self._marks[-1] del self._marks[-1] # map structs to Python dictionaries dict = {} items = self._stack[mark:] for i in range(0, len(items), 2): dict[items[i]] = items[i+1] self._stack[mark:] = [dict] self._value = 0
def end_base64(self, join=string.join):
def end_base64(self, data):
def end_base64(self, join=string.join): value = Binary() value.decode(join(self._data, "")) self.append(value) self._value = 0
value.decode(join(self._data, ""))
value.decode(data)
def end_base64(self, join=string.join): value = Binary() value.decode(join(self._data, "")) self.append(value) self._value = 0
def end_dateTime(self, join=string.join):
def end_dateTime(self, data):
def end_dateTime(self, join=string.join): value = DateTime() value.decode(join(self._data, "")) self.append(value)
value.decode(join(self._data, ""))
value.decode(data)
def end_dateTime(self, join=string.join): value = DateTime() value.decode(join(self._data, "")) self.append(value)
def end_value(self):
def end_value(self, data):
def end_value(self): # if we stumble upon an value element with no internal # elements, treat it as a string element if self._value: self.end_string()
self.end_string()
self.end_string(data)
def end_value(self): # if we stumble upon an value element with no internal # elements, treat it as a string element if self._value: self.end_string()
def end_params(self):
def end_params(self, data):
def end_params(self): self._type = "params"
def end_fault(self):
def end_fault(self, data):
def end_fault(self): self._type = "fault"
def end_methodName(self, join=string.join): data = join(self._data, "")
def end_methodName(self, data):
def end_methodName(self, join=string.join): data = join(self._data, "") if self._encoding: data = _decode(data, self._encoding) self._methodname = data
target = Unmarshaller() if FastParser: return FastParser(target), target return SlowParser(target), target
if FastParser and FastUnmarshaller: target = FastUnmarshaller(True, False, binary, datetime) parser = FastParser(target) else: target = Unmarshaller() if FastParser: parser = FastParser(target) elif SgmlopParser: parser = SgmlopParser(target) elif ExpatParser: parser = ExpatParser(target) else: parser = SlowParser(target) return parser, target
def getparser(): """getparser() -> parser, unmarshaller Create an instance of the fastest available parser, and attach it to an unmarshalling object. Return both objects. """ target = Unmarshaller() if FastParser: return FastParser(target), target return SlowParser(target), target
Convert a tuple or a fault object to an XML-RPC request (or response, if the methodsresponse option is used). In addition to the data object, the following options can be given as keyword arguments:
Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). In addition to the data object, the following options can be given as keyword arguments:
def dumps(params, methodname=None, methodresponse=None, encoding=None): """data [,options] -> marshalled data Convert a tuple or a fault object to an XML-RPC request (or response, if the methodsresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet encoding: the packet encoding (default is UTF-8) All 8-bit strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, as necessary. """ assert type(params) == TupleType or isinstance(params, Fault),\ "argument must be tuple or Fault instance" if not encoding: encoding = "utf-8" m = Marshaller(encoding) data = m.dumps(params) if encoding != "utf-8": xmlheader = "<?xml version='1.0' encoding=%s?>\n" % repr(encoding) else: xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default # standard XML-RPC wrappings if methodname: # a method call if not isinstance(methodname, StringType): methodname = methodname.encode(encoding) data = ( xmlheader, "<methodCall>\n" "<methodName>", methodname, "</methodName>\n", data, "</methodCall>\n" ) elif methodresponse or isinstance(params, Fault): # a method response data = ( xmlheader, "<methodResponse>\n", data, "</methodResponse>\n" ) else: return data # return as is return string.join(data, "")
methodresponse: true to create a methodResponse packet
methodresponse: true to create a methodResponse packet. If this option is used with a tuple, the tuple must be a singleton (i.e. it can contain only one element).
def dumps(params, methodname=None, methodresponse=None, encoding=None): """data [,options] -> marshalled data Convert a tuple or a fault object to an XML-RPC request (or response, if the methodsresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet encoding: the packet encoding (default is UTF-8) All 8-bit strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, as necessary. """ assert type(params) == TupleType or isinstance(params, Fault),\ "argument must be tuple or Fault instance" if not encoding: encoding = "utf-8" m = Marshaller(encoding) data = m.dumps(params) if encoding != "utf-8": xmlheader = "<?xml version='1.0' encoding=%s?>\n" % repr(encoding) else: xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default # standard XML-RPC wrappings if methodname: # a method call if not isinstance(methodname, StringType): methodname = methodname.encode(encoding) data = ( xmlheader, "<methodCall>\n" "<methodName>", methodname, "</methodName>\n", data, "</methodCall>\n" ) elif methodresponse or isinstance(params, Fault): # a method response data = ( xmlheader, "<methodResponse>\n", data, "</methodResponse>\n" ) else: return data # return as is return string.join(data, "")
as necessary.
where necessary.
def dumps(params, methodname=None, methodresponse=None, encoding=None): """data [,options] -> marshalled data Convert a tuple or a fault object to an XML-RPC request (or response, if the methodsresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet encoding: the packet encoding (default is UTF-8) All 8-bit strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, as necessary. """ assert type(params) == TupleType or isinstance(params, Fault),\ "argument must be tuple or Fault instance" if not encoding: encoding = "utf-8" m = Marshaller(encoding) data = m.dumps(params) if encoding != "utf-8": xmlheader = "<?xml version='1.0' encoding=%s?>\n" % repr(encoding) else: xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default # standard XML-RPC wrappings if methodname: # a method call if not isinstance(methodname, StringType): methodname = methodname.encode(encoding) data = ( xmlheader, "<methodCall>\n" "<methodName>", methodname, "</methodName>\n", data, "</methodCall>\n" ) elif methodresponse or isinstance(params, Fault): # a method response data = ( xmlheader, "<methodResponse>\n", data, "</methodResponse>\n" ) else: return data # return as is return string.join(data, "")
assert type(params) == TupleType or isinstance(params, Fault),\
assert isinstance(params, TupleType) or isinstance(params, Fault),\
def dumps(params, methodname=None, methodresponse=None, encoding=None): """data [,options] -> marshalled data Convert a tuple or a fault object to an XML-RPC request (or response, if the methodsresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet encoding: the packet encoding (default is UTF-8) All 8-bit strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, as necessary. """ assert type(params) == TupleType or isinstance(params, Fault),\ "argument must be tuple or Fault instance" if not encoding: encoding = "utf-8" m = Marshaller(encoding) data = m.dumps(params) if encoding != "utf-8": xmlheader = "<?xml version='1.0' encoding=%s?>\n" % repr(encoding) else: xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default # standard XML-RPC wrappings if methodname: # a method call if not isinstance(methodname, StringType): methodname = methodname.encode(encoding) data = ( xmlheader, "<methodCall>\n" "<methodName>", methodname, "</methodName>\n", data, "</methodCall>\n" ) elif methodresponse or isinstance(params, Fault): # a method response data = ( xmlheader, "<methodResponse>\n", data, "</methodResponse>\n" ) else: return data # return as is return string.join(data, "")
elif methodresponse or isinstance(params, Fault):
elif methodresponse:
def dumps(params, methodname=None, methodresponse=None, encoding=None): """data [,options] -> marshalled data Convert a tuple or a fault object to an XML-RPC request (or response, if the methodsresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet encoding: the packet encoding (default is UTF-8) All 8-bit strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, as necessary. """ assert type(params) == TupleType or isinstance(params, Fault),\ "argument must be tuple or Fault instance" if not encoding: encoding = "utf-8" m = Marshaller(encoding) data = m.dumps(params) if encoding != "utf-8": xmlheader = "<?xml version='1.0' encoding=%s?>\n" % repr(encoding) else: xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default # standard XML-RPC wrappings if methodname: # a method call if not isinstance(methodname, StringType): methodname = methodname.encode(encoding) data = ( xmlheader, "<methodCall>\n" "<methodName>", methodname, "</methodName>\n", data, "</methodCall>\n" ) elif methodresponse or isinstance(params, Fault): # a method response data = ( xmlheader, "<methodResponse>\n", data, "</methodResponse>\n" ) else: return data # return as is return string.join(data, "")
p, u = getparser()
p, u = self.getparser()
def parse_response(self, f): # read response from input file, and parse it
class Server:
class ServerProxy:
def send_host(self, connection, host): if isinstance(host, TupleType): host, x509 = host connection.putheader("Host", host)
"<Server proxy for %s%s>" %
"<ServerProxy for %s%s>" %
def __repr__(self): return ( "<Server proxy for %s%s>" % (self.__host, self.__handler) )
server = Server("http://betty.userland.com")
server = ServerProxy("http://betty.userland.com")
def __getattr__(self, name): # magic method dispatcher return _Method(self.__request, name)
name=mo.group(1) value={'default':mo.group(2)} l=len(mo.group(0))
name=mo.group(2) value={'default':mo.group(3)} l=len(mo.group(1))
def parse(text, result=None, keys=None, unparmre=re.compile( r'([\000- ]*([^\000- ="]+))'), parmre=re.compile( r'([\000- ]*([^\000- ="]+)=([^\000- ="]+))'), qparmre=re.compile( r'([\000- ]*([^\000- ="]+)="([^"]*)")'), ): if result is None: result = {} keys=[] __traceback_info__=text mo = parmre.match(text) if mo: name=mo.group(1) value={'default':mo.group(2)} l=len(mo.group(0)) else: mo = qparmre.match(text) if mo: name=mo.group(0) value={'default':mo.group(2)} l=len(mo.group(0)) else: mo = unparmre.match(text) if ts_results: name=mo.group(1) l=len(mo.group(0)) value={} else: if not text or not strip(text): return Args(result,keys) raise InvalidParameter, text lt=string.find(name,':') if lt > 0: value['type']=name[lt+1:] name=name[:lt] result[name]=value keys.append(name) return parse(text[l:],result,keys)
name=mo.group(0) value={'default':mo.group(2)} l=len(mo.group(0))
name=mo.group(1) value={'default':mo.group(3)} l=len(mo.group(2))
def parse(text, result=None, keys=None, unparmre=re.compile( r'([\000- ]*([^\000- ="]+))'), parmre=re.compile( r'([\000- ]*([^\000- ="]+)=([^\000- ="]+))'), qparmre=re.compile( r'([\000- ]*([^\000- ="]+)="([^"]*)")'), ): if result is None: result = {} keys=[] __traceback_info__=text mo = parmre.match(text) if mo: name=mo.group(1) value={'default':mo.group(2)} l=len(mo.group(0)) else: mo = qparmre.match(text) if mo: name=mo.group(0) value={'default':mo.group(2)} l=len(mo.group(0)) else: mo = unparmre.match(text) if ts_results: name=mo.group(1) l=len(mo.group(0)) value={} else: if not text or not strip(text): return Args(result,keys) raise InvalidParameter, text lt=string.find(name,':') if lt > 0: value['type']=name[lt+1:] name=name[:lt] result[name]=value keys.append(name) return parse(text[l:],result,keys)
name=mo.group(1) l=len(mo.group(0))
name=mo.group(2) l=len(mo.group(1))
def parse(text, result=None, keys=None, unparmre=re.compile( r'([\000- ]*([^\000- ="]+))'), parmre=re.compile( r'([\000- ]*([^\000- ="]+)=([^\000- ="]+))'), qparmre=re.compile( r'([\000- ]*([^\000- ="]+)="([^"]*)")'), ): if result is None: result = {} keys=[] __traceback_info__=text mo = parmre.match(text) if mo: name=mo.group(1) value={'default':mo.group(2)} l=len(mo.group(0)) else: mo = qparmre.match(text) if mo: name=mo.group(0) value={'default':mo.group(2)} l=len(mo.group(0)) else: mo = unparmre.match(text) if ts_results: name=mo.group(1) l=len(mo.group(0)) value={} else: if not text or not strip(text): return Args(result,keys) raise InvalidParameter, text lt=string.find(name,':') if lt > 0: value['type']=name[lt+1:] name=name[:lt] result[name]=value keys.append(name) return parse(text[l:],result,keys)
self._tmp.write(oid+pack(">I", len(data))) self._tmp.write(data)
try: self._tmp.write(oid+pack(">i", len(data))) self._tmp.write(data) except IOError: raise OutOfTempSpaceError, self._tempdir
def store(self, oid, serial, data, version, transaction): if transaction is not self._transaction: raise POSException.StorageTransactionError(self, transaction)
s=tmp.tell()
oidlen=8 intlen=4 fsize=tmp.tell()
def _finish(self, tid, u, d, e): txn = self._env.txn_begin() try: zeros={} referenceCount=self._referenceCount referenceCount_get=referenceCount.get referenceCount_put=referenceCount.put oreferences=self._oreferences oreferences_put=oreferences.put serial_put=self._index.put opickle_put=self._opickle.put serial=self._serial tmp=self._tmp s=tmp.tell() tmp.seek(0) read=tmp.read l=0 while l < s: oid, ldata = unpack(">8sI", read(12)) data=read(ldata)
while l < s: oid, ldata = unpack(">8sI", read(12))
while l < fsize: sdata = read(oidlen+intlen) oid, ldata = unpack(">%ssi" % oidlen, sdata)
def _finish(self, tid, u, d, e): txn = self._env.txn_begin() try: zeros={} referenceCount=self._referenceCount referenceCount_get=referenceCount.get referenceCount_put=referenceCount.put oreferences=self._oreferences oreferences_put=oreferences.put serial_put=self._index.put opickle_put=self._opickle.put serial=self._serial tmp=self._tmp s=tmp.tell() tmp.seek(0) read=tmp.read l=0 while l < s: oid, ldata = unpack(">8sI", read(12)) data=read(ldata)
referenceCount_put(oid, '\0\0\0\0', txn) zeros[oid]=1
referenceCount_put(oid, '\0'*intlen, txn)
def _finish(self, tid, u, d, e): txn = self._env.txn_begin() try: zeros={} referenceCount=self._referenceCount referenceCount_get=referenceCount.get referenceCount_put=referenceCount.put oreferences=self._oreferences oreferences_put=oreferences.put serial_put=self._index.put opickle_put=self._opickle.put serial=self._serial tmp=self._tmp s=tmp.tell() tmp.seek(0) read=tmp.read l=0 while l < s: oid, ldata = unpack(">8sI", read(12)) data=read(ldata)
raise "Bad reference count, %s" % (rc+1)
raise ReferenceCountError, ( "Oid %s had refcount %s" % (`roid`,rc) )
def _finish(self, tid, u, d, e): txn = self._env.txn_begin() try: zeros={} referenceCount=self._referenceCount referenceCount_get=referenceCount.get referenceCount_put=referenceCount.put oreferences=self._oreferences oreferences_put=oreferences.put serial_put=self._index.put opickle_put=self._opickle.put serial=self._serial tmp=self._tmp s=tmp.tell() tmp.seek(0) read=tmp.read l=0 while l < s: oid, ldata = unpack(">8sI", read(12)) data=read(ldata)
referenceCount_put(roid, '\0\0\0\1', txn)
referenceCount_put(roid, pack(">i", 1), txn)
def _finish(self, tid, u, d, e): txn = self._env.txn_begin() try: zeros={} referenceCount=self._referenceCount referenceCount_get=referenceCount.get referenceCount_put=referenceCount.put oreferences=self._oreferences oreferences_put=oreferences.put serial_put=self._index.put opickle_put=self._opickle.put serial=self._serial tmp=self._tmp s=tmp.tell() tmp.seek(0) read=tmp.read l=0 while l < s: oid, ldata = unpack(">8sI", read(12)) data=read(ldata)
l=l+ldata+12 if ldata > s: raise 'Temporary file corrupted'
l=l+ldata+oidlen+intlen if ldata > fsize: raise TemporaryLogCorruptedError
def _finish(self, tid, u, d, e): txn = self._env.txn_begin() try: zeros={} referenceCount=self._referenceCount referenceCount_get=referenceCount.get referenceCount_put=referenceCount.put oreferences=self._oreferences oreferences_put=oreferences.put serial_put=self._index.put opickle_put=self._opickle.put serial=self._serial tmp=self._tmp s=tmp.tell() tmp.seek(0) read=tmp.read l=0 while l < s: oid, ldata = unpack(">8sI", read(12)) data=read(ldata)
if s > 999999: tmp.truncate()
if fsize > MAXTEMPFSIZE: tmp.truncate()
def _finish(self, tid, u, d, e): txn = self._env.txn_begin() try: zeros={} referenceCount=self._referenceCount referenceCount_get=referenceCount.get referenceCount_put=referenceCount.put oreferences=self._oreferences oreferences_put=oreferences.put serial_put=self._index.put opickle_put=self._opickle.put serial=self._serial tmp=self._tmp s=tmp.tell() tmp.seek(0) read=tmp.read l=0 while l < s: oid, ldata = unpack(">8sI", read(12)) data=read(ldata)
raise "Bad reference count, %s" % (rc+1)
raise ReferenceCountError, ( "Oid %s had refcount %s" % (`roid`,rc) )
def _takeOutGarbage(self, oid, txn): # take out the garbage. referenceCount=self._referenceCount referenceCount.delete(oid, txn) self._opickle.delete(oid, txn) self._current.delete(oid, txn)
pass finally: self._lock_release()
try: txn = self._env.txn_begin() rindex={} referenced=rindex.has_key rootl=['\0\0\0\0\0\0\0\0'] while rootl: oid=rootl.pop() if referenced(oid): continue p = self._opickle[oid] referencesf(p, rootl) rindex[oid] = None for oid in self._index.keys(): if not referenced(oid): self._takeOutGarbage(oid, txn) except: txn.abort() raise else: txn.commit() finally: self._lock_release()
def pack(self, t, referencesf): self._lock_acquire() try: pass # TBD finally: self._lock_release()
if published is None: raise
if published is None: raise t, v, traceback
def zpublisher_exception_hook(published, REQUEST, t, v, traceback): try: if isinstance(t, StringType): if t.lower() in ('unauthorized', 'redirect'): raise else: if t is SystemExit: raise if issubclass(t, ConflictError): # First, we need to close the current connection. We'll # do this by releasing the hold on it. There should be # some sane protocol for this, but for now we'll use # brute force: global conflict_errors conflict_errors = conflict_errors + 1 method_name = REQUEST.get('PATH_INFO', '') err = ('ZODB conflict error at %s ' '(%s conflicts since startup at %s)') LOG(err % (method_name, conflict_errors, startup_time), INFO, '') LOG('Conflict traceback', BLATHER, '', error=sys.exc_info()) raise ZPublisher.Retry(t, v, traceback) if t is ZPublisher.Retry: v.reraise() try: log = aq_acquire(published, '__error_log__', containment=1) except AttributeError: error_log_url = '' else: error_log_url = log.raising((t, v, traceback)) if (getattr(REQUEST.get('RESPONSE', None), '_error_format', '') !='text/html'): raise if (published is None or published is app or type(published) is ListType): # At least get the top-level object published=app.__bobo_traverse__(REQUEST).__of__( RequestContainer(REQUEST)) get_transaction().begin() # Just to be sure. published=getattr(published, 'im_self', published) while 1: f=getattr(published, 'raise_standardErrorMessage', None) if f is None: published=getattr(published, 'aq_parent', None) if published is None: raise else: break client=published while 1: if getattr(client, 'standard_error_message', None) is not None: break client=getattr(client, 'aq_parent', None) if client is None: raise if REQUEST.get('AUTHENTICATED_USER', None) is None: REQUEST['AUTHENTICATED_USER']=AccessControl.User.nobody try: f(client, REQUEST, t, v, traceback, error_log_url=error_log_url) except TypeError: # Pre 2.6 call signature f(client, REQUEST, t, v, traceback) finally: traceback=None
if client is None: raise
if client is None: raise t, v, traceback
def zpublisher_exception_hook(published, REQUEST, t, v, traceback): try: if isinstance(t, StringType): if t.lower() in ('unauthorized', 'redirect'): raise else: if t is SystemExit: raise if issubclass(t, ConflictError): # First, we need to close the current connection. We'll # do this by releasing the hold on it. There should be # some sane protocol for this, but for now we'll use # brute force: global conflict_errors conflict_errors = conflict_errors + 1 method_name = REQUEST.get('PATH_INFO', '') err = ('ZODB conflict error at %s ' '(%s conflicts since startup at %s)') LOG(err % (method_name, conflict_errors, startup_time), INFO, '') LOG('Conflict traceback', BLATHER, '', error=sys.exc_info()) raise ZPublisher.Retry(t, v, traceback) if t is ZPublisher.Retry: v.reraise() try: log = aq_acquire(published, '__error_log__', containment=1) except AttributeError: error_log_url = '' else: error_log_url = log.raising((t, v, traceback)) if (getattr(REQUEST.get('RESPONSE', None), '_error_format', '') !='text/html'): raise if (published is None or published is app or type(published) is ListType): # At least get the top-level object published=app.__bobo_traverse__(REQUEST).__of__( RequestContainer(REQUEST)) get_transaction().begin() # Just to be sure. published=getattr(published, 'im_self', published) while 1: f=getattr(published, 'raise_standardErrorMessage', None) if f is None: published=getattr(published, 'aq_parent', None) if published is None: raise else: break client=published while 1: if getattr(client, 'standard_error_message', None) is not None: break client=getattr(client, 'aq_parent', None) if client is None: raise if REQUEST.get('AUTHENTICATED_USER', None) is None: REQUEST['AUTHENTICATED_USER']=AccessControl.User.nobody try: f(client, REQUEST, t, v, traceback, error_log_url=error_log_url) except TypeError: # Pre 2.6 call signature f(client, REQUEST, t, v, traceback) finally: traceback=None
v = str(v)
vstr = str(v)
def exception(self, fatal=0, info=None, absuri_match=None, tag_search=None): # Fetch our exception info. t is type, v is value and tb is the # traceback object. if type(info) is type(()) and len(info)==3: t,v,tb = info else: t,v,tb = sys.exc_info()
v = re.sub(pat, " ", v)
vstr = re.sub(pat, " ", vstr)
def exception(self, fatal=0, info=None, absuri_match=None, tag_search=None): # Fetch our exception info. t is type, v is value and tb is the # traceback object. if type(info) is type(()) and len(info)==3: t,v,tb = info else: t,v,tb = sys.exc_info()
value = '\n' + ''.join(format_exception(t, v, tb))
value = '\n' + ''.join(format_exception(t, vstr, tb))
def exception(self, fatal=0, info=None, absuri_match=None, tag_search=None): # Fetch our exception info. t is type, v is value and tb is the # traceback object. if type(info) is type(()) and len(info)==3: t,v,tb = info else: t,v,tb = sys.exc_info()
value = '%s - %s' % (t, v)
value = '%s - %s' % (t, vstr)
def exception(self, fatal=0, info=None, absuri_match=None, tag_search=None): # Fetch our exception info. t is type, v is value and tb is the # traceback object. if type(info) is type(()) and len(info)==3: t,v,tb = info else: t,v,tb = sys.exc_info()
print ' '*level, sym_name[ast[0]]
print ' '*level, sym_name[ast[0]], '(%s)' % ast[0]
def pret(ast, level=0): if ISTERMINAL(ast[0]): print ' '*level, ast[1] else: print ' '*level, sym_name[ast[0]] for a in ast[1:]: pret(a,level+1)
ast[1:]=[multi_munge(ast[1:])]
keep_going=1 while keep_going: keep_going=0 start=2 for i in range(start,len(ast)-1): if ast[i][0]==STAR: ast[i-1:i+2]=[multi_munge(ast[i-1:i+2])] keep_going=1 break for a in ast[1:]: munge(a)
def munge(ast): if ISTERMINAL(ast[0]): return else: if ast[0]==term and len(ast) > 2: ast[1:]=[multi_munge(ast[1:])] elif ast[0]==power: keep_going=1 while keep_going: keep_going=0 start=2 for i in range(start,len(ast)): a=ast[i] if a[0]==trailer: if a[1][0]==DOT: ast[:i+1]=dot_munge(ast,i) keep_going=1 start=3 break if a[1][0]==LSQB: if (a[2][0] != subscriptlist or a[2][1][0] != subscript): raise ParseError, ( 'Unexpected form after left square brace') slist=a[2] if len(slist)==2: # One subscript, check for range and ... sub=slist[1] if sub[1][0]==DOT: raise ParseError, ( 'ellipses are not supported') l=len(sub) if l < 3 and sub[1][0] != COLON: ast[:i+1]=item_munge(ast, i) elif l < 5: ast[:i+1]=slice_munge(ast, i) else: raise ParseError, 'Invalid slice' else: ast[:i+1]=item_munge(ast, i) keep_going=1 start=3 break for a in ast[1:]: munge(a) else: for a in ast[1:]: munge(a) return ast
("a*b*c", "__guarded_mul__(_vars, a, b, c)"),
("a*b*c", "__guarded_mul__(_vars, __guarded_mul__(_vars, a, b), c)" ),
def spam(): # Regression test import traceback ok=1 for expr1, expr2 in ( ("a*b", "__guarded_mul__(_vars, a, b)"), ("a*b*c", "__guarded_mul__(_vars, a, b, c)"), ("a.b", "__guarded_getattr__(_vars, a, 'b')"), ("a[b]", "__guarded_getitem__(_vars, a, b)"), ("a[b,c]", "__guarded_getitem__(_vars, a, b, c)"), ("a[b:c]", "__guarded_getslice__(_vars, a, b, c)"), ("a[:c]", "__guarded_getslice__(_vars, a, 0, c)"), ("a[b:]", "__guarded_getslice__(_vars, a, b)"), ("a[:]", "__guarded_getslice__(_vars, a)"), ): l1=munge(astl(expr1)) l2=astl(expr2) try: c1=compileast(sequence2ast(l1)) except: traceback.print_exc c1=None c2=compileast(sequence2ast(l2)) if c1 !=c2: ok=0 print 'test failed', expr1, expr2 print print l1 print print l2 print ast=parser.sequence2ast(l1) c=parser.compileast(ast) if ok: print 'all tests succeeded'
item.reverse() item = item[0] item=getattr(item,attr)
item = getattr(item[-1], attr)
def processInputs( self, # "static" variables that we want to be local for speed SEQUENCE=1, DEFAULT=2, RECORD=4, RECORDS=8, REC=12, # RECORD|RECORDS EMPTY=16, CONVERTED=32, hasattr=hasattr, getattr=getattr, setattr=setattr, search_type=re.compile('(:[a-zA-Z][a-zA-Z0-9_]+|\\.[xy])$').search, ): """Process request inputs
if flags&RECORDS: reclist = mapping_object[key] reclist.reverse() x=reclist[0] reclist.reverse() if not hasattr(x,attr): if flags&SEQUENCE: item=[item] reclist.remove(x) setattr(x,attr,item) reclist.append(x) mapping_object[key] = reclist else: if flags&SEQUENCE: reclist.remove(x) y = getattr(x, attr) y.append(item) setattr(x, attr, y) reclist.append(x) mapping_object[key] = reclist else: n=record() setattr(n,attr,item) reclist.append(n) mapping_object[key]=reclist elif flags&RECORD: b=mapping_object[key] if flags&SEQUENCE: item=[item] if not hasattr(b,attr): setattr(b,attr,item) else: setattr(b,attr,getattr(b,attr)+item) else: setattr(b,attr,item) else: found=mapping_object[key] if type(found) is lt: found.append(item) else: found=[found,item] mapping_object[key]=found
if flags&RECORDS: reclist = mapping_object[key] x = reclist[-1] if not hasattr(x,attr): if flags&SEQUENCE: item=[item] reclist.remove(x) setattr(x,attr,item) reclist.append(x) mapping_object[key] = reclist else: if flags&SEQUENCE: reclist.remove(x) y = getattr(x, attr) y.append(item) setattr(x, attr, y) reclist.append(x) mapping_object[key] = reclist else: n=record() setattr(n,attr,item) reclist.append(n) mapping_object[key]=reclist elif flags&RECORD: b=mapping_object[key] if flags&SEQUENCE: item=[item] if not hasattr(b,attr): setattr(b,attr,item) else: setattr(b,attr,getattr(b,attr)+item) else: setattr(b,attr,item) else: found=mapping_object[key] if type(found) is lt: found.append(item) else: found=[found,item] mapping_object[key]=found
def processInputs( self, # "static" variables that we want to be local for speed SEQUENCE=1, DEFAULT=2, RECORD=4, RECORDS=8, REC=12, # RECORD|RECORDS EMPTY=16, CONVERTED=32, hasattr=hasattr, getattr=getattr, setattr=setattr, search_type=re.compile('(:[a-zA-Z][a-zA-Z0-9_]+|\\.[xy])$').search, ): """Process request inputs
if (isCGI_NAME(key) or key[:5] == 'HTTP_') and \ (not hide_key(key)): keys[key] = 1
if (isCGI_NAME(key) or key[:5] == 'HTTP_') and (not hide_key(key)): keys[key] = 1
def keys(self): keys = {} keys.update(self.common) keys.update(self._lazies)
ob=ob.__of__(self)
def manage_clone(self, ob, id, REQUEST=None): """Clone an object, creating a new object with the given id.""" if not ob.cb_isCopyable(): raise CopyError, eNotSupported % absattr(ob.id) try: self._checkId(id) except: raise CopyError, MessageDialog( title='Invalid Id', message=sys.exc_value, action ='manage_main') self._verifyObjectPaste(ob, REQUEST) try: ob._notifyOfCopyTo(self, op=0) except: raise CopyError, MessageDialog( title='Rename Error', message=sys.exc_value, action ='manage_main') ob=ob._getCopy(self) ob._setId(id) self._setObject(id, ob) #ob=ob.__of__(self) #ob._postCopy(self, op=0) return ob
if request['PATH_INFO'][-1] != '/':
pathinfo=request.get('PATH_INFO','') if pathinfo and pathinfo[-1] != '/':
def dav__init(self, request, response): # By the spec, we are not supposed to accept /foo for a # collection, we are supposed to redirect to /foo/. if request['PATH_INFO'][-1] != '/': raise 'Moved Permanently', request['URL1']+'/' response.setHeader('Connection', 'close', 1) response.setHeader('Date', rfc1123_date(), 1) response.setHeader('DAV', '1', 1)
self._getOb(id).manage_upload(file)
if file: self._getOb(id).manage_upload(file)
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=str(id) title=str(title) content_type=str(content_type) precondition=str(precondition) id, title = cookId(id, title, file) self=self.this() # First, we create the file without data: self._setObject(id, File(id,title,'',content_type, precondition)) # Now we "upload" the data. By doing this in two steps, we # can use a database trick to make the upload more efficient. self._getOb(id).manage_upload(file) if content_type: self._getOb(id).content_type=content_type if REQUEST is not None: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
self._getOb(id).manage_upload(file)
if file: self._getOb(id).manage_upload(file)
def manage_addImage(self, id, file, title='', precondition='', content_type='', REQUEST=None): """ Add a new Image object. Creates a new Image object 'id' with the contents of 'file'. """ id=str(id) title=str(title) content_type=str(content_type) precondition=str(precondition) id, title = cookId(id, title, file) self=self.this() # First, we create the image without data: self._setObject(id, Image(id,title,'',content_type, precondition)) # Now we "upload" the data. By doing this in two steps, we # can use a database trick to make the upload more efficient. self._getOb(id).manage_upload(file) if content_type: self._getOb(id).content_type=content_type if REQUEST is not None: try: url=self.DestinationURL() except: url=REQUEST['URL1'] REQUEST.RESPONSE.redirect('%s/manage_main' % url) return id
attempt = crypt(attempt, reference[7:9])
attempt = crypt.crypt(attempt, reference[7:9])
def pw_validate(reference, attempt): """Validate the provided password string, which uses LDAP-style encoding notation. Reference is the correct password, attempt is clear text password attempt.""" result = 0 if upper(reference[:5]) == '{SHA}': attempt = binascii.b2a_base64(sha.new(attempt).digest())[:-1] result = reference[5:] == attempt elif upper(reference[:7]) == '{CRYPT}' and crypt is not None: #if crypt is None, it's not compiled in and everything will fail attempt = crypt(attempt, reference[7:9]) result = reference[7:] == attempt else: result = reference == attempt return result
'<hr><strong>SQL used:</strong><br>\n<pre>\n%s\n</pre>/n<hr>\n'
'<hr><strong>SQL used:</strong><br>\n<pre>\n%s\n</pre>\n<hr>\n'
def manage_test(self, REQUEST):
RESPONSE.setStatus(304) return RESPONSE
response.setStatus(304) return response
def _init_headers(self, request, response): # Attempt to handle If-Modified-Since headers. ms=request.get_header('If-Modified-Since', None) if ms is not None: ms=split(ms, ';')[0] ms=DateTime(ms).timeTime() if self.lmt > ms: RESPONSE.setStatus(304) return RESPONSE response.setHeader('Content-Type', self.content_type) response.setHeader('Last-Modified', self.lmh)
$Id: Publish.py,v 1.5 1996/07/08 20:34:11 jfulton Exp $"""
$Id: Publish.py,v 1.6 1996/07/10 22:53:54 jfulton Exp $"""
def taste(spam): "a favorable reviewer" return spam,'yum yum, I like ' + spam
__version__='$Revision: 1.5 $'[11:-2]
__version__='$Revision: 1.6 $'[11:-2]
def taste(spam): "a favorable reviewer" return spam,'yum yum, I like ' + spam
import Realm
def validate(self,groups,realm=None):
return realm.validate(self.env("HTTP_AUTHORIZATION"),groups)
user=realm.validate(self.env("HTTP_AUTHORIZATION"),groups) self.request['AUTHENTICATED_USER']=user
def validate(self,groups,realm=None):
else: uid=string.join(uid(), '/')
else: uid='/'.join(uid())
def catalog_object(self, obj, uid=None, idxs=[]): """ wrapper around catalog """
string.find(ob.PrincipiaSearchSource(), obj_searchterm) >= 0
ob.PrincipiaSearchSource().find(obj_searchterm) >= 0
def ZopeFindAndApply(self, obj, obj_ids=None, obj_metatypes=None, obj_searchterm=None, obj_expr=None, obj_mtime=None, obj_mspec=None, obj_permission=None, obj_roles=None, search_sub=0, REQUEST=None, result=None, pre='', apply_func=None, apply_path=''): """Zope Find interface and apply
if string.find(path, script) != 0:
if path.find(script) != 0:
def resolve_url(self, path, REQUEST): """ Attempt to resolve a url into an object in the Zope namespace. The url may be absolute or a catalog path style url. If no object is found, None is returned. No exceptions are raised. """ script=REQUEST.script if string.find(path, script) != 0: path='%s/%s' % (script, path) try: return REQUEST.resolve_url(path) except: pass
ppath = string.join(ob.getPhysicalPath(), '/')
ppath = '/'.join(ob.getPhysicalPath())
def manage_normalize_paths(self, REQUEST): """Ensure that all catalog paths are full physical paths
def loadmail(dest, name, mbox, printstat=0, max=99999999):
def loadmail(dest, name, mbox, printstat=0, max=-1):
def loadmail(dest, name, mbox, printstat=0, max=99999999): try: import Products.BTreeFolder.BTreeFolder except: dest.manage_addFolder(name) else: Products.BTreeFolder.BTreeFolder.manage_addBTreeFolder(dest, name) dest=getattr(dest, name) f=open(mbox) mb=mailbox.UnixMailbox(f) i=0 message=mb.next() while message: if i > max: break if i%100 == 0 and printstat: sys.stdout.write("\t%s\t%s\t\r" % (i, f.tell())) sys.stdout.flush() if i and (i%5000 == 0): get_transaction().commit() dest._p_jar._cache.invalidate(None) dest._p_jar._cache.minimize() loadmessage(dest, message, i) i=i+1 message=mb.next() dest.number_of_messages=i get_transaction().commit()
if i > max: break
if max >= 0 and i > max: break
def loadmail(dest, name, mbox, printstat=0, max=99999999): try: import Products.BTreeFolder.BTreeFolder except: dest.manage_addFolder(name) else: Products.BTreeFolder.BTreeFolder.manage_addBTreeFolder(dest, name) dest=getattr(dest, name) f=open(mbox) mb=mailbox.UnixMailbox(f) i=0 message=mb.next() while message: if i > max: break if i%100 == 0 and printstat: sys.stdout.write("\t%s\t%s\t\r" % (i, f.tell())) sys.stdout.flush() if i and (i%5000 == 0): get_transaction().commit() dest._p_jar._cache.invalidate(None) dest._p_jar._cache.minimize() loadmessage(dest, message, i) i=i+1 message=mb.next() dest.number_of_messages=i get_transaction().commit()
sys.stdout.write("\t%s\t%s\t\r" % (i, f.tell()))
fmt = "\t%s\t%s\t\r" if os.environ.get('TERM') == 'emacs': fmt = "\t%s\t%s\t\n" sys.stdout.write(fmt % (i, f.tell()))
def loadmail(dest, name, mbox, printstat=0, max=99999999): try: import Products.BTreeFolder.BTreeFolder except: dest.manage_addFolder(name) else: Products.BTreeFolder.BTreeFolder.manage_addBTreeFolder(dest, name) dest=getattr(dest, name) f=open(mbox) mb=mailbox.UnixMailbox(f) i=0 message=mb.next() while message: if i > max: break if i%100 == 0 and printstat: sys.stdout.write("\t%s\t%s\t\r" % (i, f.tell())) sys.stdout.flush() if i and (i%5000 == 0): get_transaction().commit() dest._p_jar._cache.invalidate(None) dest._p_jar._cache.minimize() loadmessage(dest, message, i) i=i+1 message=mb.next() dest.number_of_messages=i get_transaction().commit()
dest._p_jar._cache.invalidate(None)
def loadmail(dest, name, mbox, printstat=0, max=99999999): try: import Products.BTreeFolder.BTreeFolder except: dest.manage_addFolder(name) else: Products.BTreeFolder.BTreeFolder.manage_addBTreeFolder(dest, name) dest=getattr(dest, name) f=open(mbox) mb=mailbox.UnixMailbox(f) i=0 message=mb.next() while message: if i > max: break if i%100 == 0 and printstat: sys.stdout.write("\t%s\t%s\t\r" % (i, f.tell())) sys.stdout.flush() if i and (i%5000 == 0): get_transaction().commit() dest._p_jar._cache.invalidate(None) dest._p_jar._cache.minimize() loadmessage(dest, message, i) i=i+1 message=mb.next() dest.number_of_messages=i get_transaction().commit()
max=atoi(sys.argv[3])
if len(sys.argv) > 3: max = atoi(sys.argv[3]) else: max = -1
def base(): try: os.unlink('../../var/Data.fs') except: pass import Zope app=Zope.app() max=atoi(sys.argv[3]) print do(Zope.DB, loadmail, (app, 'mail', sys.argv[2], 1, max)) Zope.DB.close()
m,(huh,l,c,src) = v
def name_param(params,tag='',expr=0, attr='name', default_unnamed=1): used=params.has_key __traceback_info__=params, tag, expr, attr #if expr and used('expr') and used('') and not used(params['']): # # Fix up something like: <!--#in expr="whatever" mapping--> # params[params['']]=default_unnamed # del params[''] if used(''): v=params[''] if v[:1]=='"' and v[-1:]=='"' and len(v) > 1: # expr shorthand if used(attr): raise ParseError, ('%s and expr given' % attr, tag) if expr: if used('expr'): raise ParseError, ('two exprs given', tag) v=v[1:-1] try: expr=Eval(v, expr_globals) except SyntaxError, v: m,(huh,l,c,src) = v raise ParseError, ( '<strong>Expression (Python) Syntax error</strong>:' '\n<pre>\n%s\n</pre>\n' % v[0], tag) return v, expr else: raise ParseError, ( 'The "..." shorthand for expr was used in a tag ' 'that doesn\'t support expr attributes.', tag) else: # name shorthand if used(attr): raise ParseError, ('Two %s values were given' % attr, tag) if expr: if used('expr'): # raise 'Waaaaaa', 'waaa' raise ParseError, ('%s and expr given' % attr, tag) return params[''],None return params[''] elif used(attr): if expr: if used('expr'): raise ParseError, ('%s and expr given' % attr, tag) return params[attr],None return params[attr] elif expr and used('expr'): name=params['expr'] expr=Eval(name, expr_globals) return name, expr raise ParseError, ('No %s given' % attr, tag)
def __setstate__(self, v): ApplicationManager.inheritedAttribute('__setstate__')(self, v) if not hasattr(self, 'Products'): self.Products=ProductFolder()
def __init__(self): self.Products=ProductFolder()
return """The implementation of %(method)s violates it's contract
return """The implementation of %(method)s violates its contract
def __str__(self): return """The implementation of %(method)s violates it's contract because %(mess)s. """ % self.__dict__
return self.__class__(self._year,self._month,self._day,0,0,1,self._tz)
return self.__class__(self._year,self._month,self._day,0,0,0,self._tz)
def earliestTime(self): """Return a new DateTime object that represents the earliest possible time (in whole seconds) that still falls within the current object\'s day, in the object\'s timezone context""" return self.__class__(self._year,self._month,self._day,0,0,1,self._tz)
result=custom_default_report(self.id, result)
r=custom_default_report(self.id, result)
def manage_test(self, REQUEST):
result=(
r=(
def manage_test(self, REQUEST):
% result)
% r)
def manage_test(self, REQUEST):
expr=VSEval.Eval(name, __mul__=VSEval.careful_mul, __getattr__=None)
expr=VSEval.Eval(name, __mul__=VSEval.careful_mul, __getattr__=careful_getattr, validate=validate)
def name_param(params,tag='',expr=0): used=params.has_key if used(''): if used('name'): raise ParseError, _tm('Two names were given', tag) if expr: if used('expr'): raise ParseError, _tm('name and expr given', tag) return params[''],None return params[''] elif used('name'): if expr: if used('expr'): raise ParseError, _tm('name and expr given', tag) return params['name'],None return params['name'] elif expr and used('expr'): name=params['expr'] expr=VSEval.Eval(name, __mul__=VSEval.careful_mul, __getattr__=None) return name, expr raise ParseError, ('No name given', tag)
('Invalid parameter name, %s <!--%s--> <!--u-->' % (name, text)), tag)
'Invalid parameter name, "%s"' % name, tag)
def parse_params(text, result=None, tag='', unparmre=regex.compile( '\([\0- ]*\([^\0- =\"]+\)\)'), parmre=regex.compile( '\([\0- ]*\([^\0- =\"]+\)=\([^\0- =\"]+\)\)'), qparmre=regex.compile( '\([\0- ]*\([^\0- =\"]+\)="\([^"]*\)\"\)'), **parms): """Parse tag parameters The format of tag parameters consists of 1 or more parameter specifications separated by whitespace. Each specification consists of an unnamed and unquoted value, a valueless name, or a name-value pair. A name-value pair consists of a name and a quoted or unquoted value separated by an '='. The input parameter, text, gives the text to be parsed. The keyword parameters give valid parameter names and default values. If a specification is not a name-value pair and it is not the first specification that is not a name-value pair and it is a valid parameter name, then it is treated as a name-value pair with a value as given in the keyword argument. Otherwise, if it is not a name-value pair, it is treated as an unnamed value. The data are parsed into a dictionary mapping names to values. Unnamed values are mapped from the name '""'. Only one value may be given for a name and there may be only one unnamed value. """ result=result or {} if parmre.match(text) >= 0: name=lower(parmre.group(2)) value=parmre.group(3) l=len(parmre.group(1)) elif qparmre.match(text) >= 0: name=lower(qparmre.group(2)) value=qparmre.group(3) l=len(qparmre.group(1)) elif unparmre.match(text) >= 0: name=unparmre.group(2) l=len(unparmre.group(1)) if result.has_key(''): if parms.has_key(name): result[name]=parms[name] else: raise ParseError, ( ('Invalid parameter name, %s <!--%s--> <!--u-->' % (name, text)), tag) else: result['']=name return apply(parse_params,(text[l:],result),parms) else: if not text or not strip(text): return result raise InvalidParameter, text if not parms.has_key(name): raise ParseError, ( ('Invalid parameter name, %s <!--%s-->' % (name, text)), tag) result[name]=value text=strip(text[l:]) if text: return apply(parse_params,(text,result),parms) else: return result
('Invalid parameter name, %s <!--%s-->' % (name, text)), tag)
'Invalid parameter name, "%s"' % name, tag)
def parse_params(text, result=None, tag='', unparmre=regex.compile( '\([\0- ]*\([^\0- =\"]+\)\)'), parmre=regex.compile( '\([\0- ]*\([^\0- =\"]+\)=\([^\0- =\"]+\)\)'), qparmre=regex.compile( '\([\0- ]*\([^\0- =\"]+\)="\([^"]*\)\"\)'), **parms): """Parse tag parameters The format of tag parameters consists of 1 or more parameter specifications separated by whitespace. Each specification consists of an unnamed and unquoted value, a valueless name, or a name-value pair. A name-value pair consists of a name and a quoted or unquoted value separated by an '='. The input parameter, text, gives the text to be parsed. The keyword parameters give valid parameter names and default values. If a specification is not a name-value pair and it is not the first specification that is not a name-value pair and it is a valid parameter name, then it is treated as a name-value pair with a value as given in the keyword argument. Otherwise, if it is not a name-value pair, it is treated as an unnamed value. The data are parsed into a dictionary mapping names to values. Unnamed values are mapped from the name '""'. Only one value may be given for a name and there may be only one unnamed value. """ result=result or {} if parmre.match(text) >= 0: name=lower(parmre.group(2)) value=parmre.group(3) l=len(parmre.group(1)) elif qparmre.match(text) >= 0: name=lower(qparmre.group(2)) value=qparmre.group(3) l=len(qparmre.group(1)) elif unparmre.match(text) >= 0: name=unparmre.group(2) l=len(unparmre.group(1)) if result.has_key(''): if parms.has_key(name): result[name]=parms[name] else: raise ParseError, ( ('Invalid parameter name, %s <!--%s--> <!--u-->' % (name, text)), tag) else: result['']=name return apply(parse_params,(text[l:],result),parms) else: if not text or not strip(text): return result raise InvalidParameter, text if not parms.has_key(name): raise ParseError, ( ('Invalid parameter name, %s <!--%s-->' % (name, text)), tag) result[name]=value text=strip(text[l:]) if text: return apply(parse_params,(text,result),parms) else: return result
long(ms * 1000.0) - long(EPOCH * 1000.0)
long(round(ms * 1000.0)) - long(EPOCH * 1000.0)
def _calcIndependentSecondEtc(tz, x, ms): # Derive the timezone-independent second from the timezone # dependent second. fsetAtEpoch = _tzoffset(tz, 0.0) nearTime = x - fsetAtEpoch - long(EPOCH) + 86400L + ms # nearTime is now within an hour of being correct. # Recalculate t according to DST. fset = long(_tzoffset(tz, nearTime)) x_adjusted = x - fset + ms d = x_adjusted / 86400.0 t = x_adjusted - long(EPOCH) + 86400L millis = (x + 86400 - fset) * 1000 + \ long(ms * 1000.0) - long(EPOCH * 1000.0) s = d - math.floor(d) return s,d,t,millis
if(h+mn+s): if (s-int(s))> 0.0001: try: subsec = ('%g' % s).split('.')[1] return '%4.4d/%2.2d/%2.2d %2.2d:%2.2d:%2.2d.%s %s' % ( y,m,d,h,mn,s,subsec,t) except: pass return '%4.4d/%2.2d/%2.2d %2.2d:%2.2d:%2.2d %s' % ( y,m,d,h,mn,s,t)
if h == mn == s == 0: return '%4.4d/%2.2d/%2.2d' % (y, m, d) elif s == int(s):
def __str__(self): """Convert a DateTime to a string.""" y,m,d =self._year,self._month,self._day h,mn,s,t=self._hour,self._minute,self._second,self._tz if(h+mn+s): if (s-int(s))> 0.0001: try: # For the seconds, print two digits # before the decimal point. subsec = ('%g' % s).split('.')[1] return '%4.4d/%2.2d/%2.2d %2.2d:%2.2d:%2.2d.%s %s' % ( y,m,d,h,mn,s,subsec,t) except: # Didn't produce the decimal point as expected. # Just fall through. pass return '%4.4d/%2.2d/%2.2d %2.2d:%2.2d:%2.2d %s' % ( y,m,d,h,mn,s,t) return '%4.4d/%2.2d/%2.2d %2.2d:%2.2d:%2.2d %s' % ( y,m,d,h,mn,s,t) else: return '%4.4d/%2.2d/%2.2d' % (y,m,d)
y,m,d,h,mn,s,t) else: return '%4.4d/%2.2d/%2.2d' % (y,m,d)
y, m, d, h, mn, s, t) else: return '%4.4d/%2.2d/%2.2d %2.2d:%2.2d:%06.3f %s' % ( y, m, d, h, mn, s, t)
def __str__(self): """Convert a DateTime to a string.""" y,m,d =self._year,self._month,self._day h,mn,s,t=self._hour,self._minute,self._second,self._tz if(h+mn+s): if (s-int(s))> 0.0001: try: # For the seconds, print two digits # before the decimal point. subsec = ('%g' % s).split('.')[1] return '%4.4d/%2.2d/%2.2d %2.2d:%2.2d:%2.2d.%s %s' % ( y,m,d,h,mn,s,subsec,t) except: # Didn't produce the decimal point as expected. # Just fall through. pass return '%4.4d/%2.2d/%2.2d %2.2d:%2.2d:%2.2d %s' % ( y,m,d,h,mn,s,t) return '%4.4d/%2.2d/%2.2d %2.2d:%2.2d:%2.2d %s' % ( y,m,d,h,mn,s,t) else: return '%4.4d/%2.2d/%2.2d' % (y,m,d)
self.validate = security.DTMLValidate
self.__dict__['validate'] = security.DTMLValidate
def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw): """Render the document given a client object, REQUEST mapping, Response, and key word arguments."""
del self.validate
del self.__dict__['validate']
def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw): """Render the document given a client object, REQUEST mapping, Response, and key word arguments."""
$Id: Publish.py,v 1.41 1997/04/11 22:46:26 jim Exp $"""
$Id: Publish.py,v 1.42 1997/04/23 20:04:46 brian Exp $"""
def taste(spam): "a favorable reviewer" return spam,'yum yum, I like ' + spam