desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return the server software version string.'
def version_string(self):
return ((self.server_version + ' ') + self.sys_version)
'Return the current date and time formatted for a message header.'
def date_time_string(self, timestamp=None):
if (timestamp is None): timestamp = time.time() (year, month, day, hh, mm, ss, wd, y, z) = time.gmtime(timestamp) s = ('%s, %02d %3s %4d %02d:%02d:%02d GMT' % (self.weekdayname[wd], day, self.monthname[month], year, hh, mm, ss)) return s
'Return the current time formatted for logging.'
def log_date_time_string(self):
now = time.time() (year, month, day, hh, mm, ss, x, y, z) = time.localtime(now) s = ('%02d/%3s/%04d %02d:%02d:%02d' % (day, self.monthname[month], year, hh, mm, ss)) return s
'Return the client address formatted for logging. This version looks up the full hostname using gethostbyaddr(), and tries to find a name that contains at least one dot.'
def address_string(self):
(host, port) = self.client_address[:2] return socket.getfqdn(host)
'dup() -> socket object Return a new socket object connected to the same system resource.'
def dup(self):
return _socketobject(_sock=self._sock)
'makefile([mode[, bufsize]]) -> file object Return a regular file object corresponding to the socket. The mode and bufsize arguments are as for the built-in open() function.'
def makefile(self, mode='r', bufsize=(-1)):
return _fileobject(self._sock, mode, bufsize)
'Return the file descriptor of the log reader\'s log file.'
def fileno(self):
return self._reader.fileno()
'This method is called for each additional ADD_INFO record. This can be overridden by applications that want to receive these events. The default implementation does not need to be called by alternate implementations. The initial set of ADD_INFO records do not pass through this mechanism; this is only needed to receive notification when new values are added. Subclasses can inspect self._info after calling LogReader.__init__().'
def addinfo(self, key, value):
pass
'Close the logfile and terminate the profiler.'
def close(self):
self._prof.close()
'Return the file descriptor of the profiler\'s log file.'
def fileno(self):
return self._prof.fileno()
'Start the profiler.'
def start(self):
self._prof.start()
'Stop the profiler.'
def stop(self):
self._prof.stop()
'Add an arbitrary labelled value to the profile log.'
def addinfo(self, key, value):
self._prof.addinfo(key, value)
'Profile an exec-compatible string in the script environment. The globals from the __main__ module are used as both the globals and locals for the script.'
def run(self, cmd):
import __main__ dict = __main__.__dict__ return self.runctx(cmd, dict, dict)
'Evaluate an exec-compatible string in a specific environment. The string is compiled before profiling begins.'
def runctx(self, cmd, globals, locals):
code = compile(cmd, '<string>', 'exec') self._prof.runcode(code, globals, locals) return self
'Profile a single call of a callable. Additional positional and keyword arguments may be passed along; the result of the call is returned, and exceptions are allowed to propagate cleanly, while ensuring that profiling is disabled on the way out.'
def runcall(self, func, *args, **kw):
return self._prof.runcall(func, args, kw)
'Dummy implementation of acquire(). For blocking calls, self.locked_status is automatically set to True and returned appropriately based on value of ``waitflag``. If it is non-blocking, then the value is actually checked and not set if it is already acquired. This is all done so that threading.Condition\'s assert statements aren\'t triggered and throw a little fit.'
def acquire(self, waitflag=None):
if ((waitflag is None) or waitflag): self.locked_status = True return True elif (not self.locked_status): self.locked_status = True return True else: return False
'Release the dummy lock.'
def release(self):
if (not self.locked_status): raise error self.locked_status = False return True
'Instantiate a line-oriented interpreter framework. The optional argument \'completekey\' is the readline name of a completion key; it defaults to the Tab key. If completekey is not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alternate input and output file objects; if not specified, sys.stdin and sys.stdout are used.'
def __init__(self, completekey='tab', stdin=None, stdout=None):
import sys if (stdin is not None): self.stdin = stdin else: self.stdin = sys.stdin if (stdout is not None): self.stdout = stdout else: self.stdout = sys.stdout self.cmdqueue = [] self.completekey = completekey
'Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument.'
def cmdloop(self, intro=None):
self.preloop() if (self.use_rawinput and self.completekey): try: import readline self.old_completer = readline.get_completer() readline.set_completer(self.complete) readline.parse_and_bind((self.completekey + ': complete')) except ImportError: pass try: if (intro is not None): self.intro = intro if self.intro: self.stdout.write((str(self.intro) + '\n')) stop = None while (not stop): if self.cmdqueue: line = self.cmdqueue.pop(0) elif self.use_rawinput: try: line = raw_input(self.prompt) except EOFError: line = 'EOF' else: self.stdout.write(self.prompt) self.stdout.flush() line = self.stdin.readline() if (not len(line)): line = 'EOF' else: line = line.rstrip('\r\n') line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) self.postloop() finally: if (self.use_rawinput and self.completekey): try: import readline readline.set_completer(self.old_completer) except ImportError: pass
'Hook method executed just before the command line is interpreted, but after the input prompt is generated and issued.'
def precmd(self, line):
return line
'Hook method executed just after a command dispatch is finished.'
def postcmd(self, stop, line):
return stop
'Hook method executed once when the cmdloop() method is called.'
def preloop(self):
pass
'Hook method executed once when the cmdloop() method is about to return.'
def postloop(self):
pass
'Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). \'command\' and \'args\' may be None if the line couldn\'t be parsed.'
def parseline(self, line):
line = line.strip() if (not line): return (None, None, line) elif (line[0] == '?'): line = ('help ' + line[1:]) elif (line[0] == '!'): if hasattr(self, 'do_shell'): line = ('shell ' + line[1:]) else: return (None, None, line) (i, n) = (0, len(line)) while ((i < n) and (line[i] in self.identchars)): i = (i + 1) (cmd, arg) = (line[:i], line[i:].strip()) return (cmd, arg, line)
'Interpret the argument as though it had been typed in response to the prompt. This may be overridden, but should not normally need to be; see the precmd() and postcmd() methods for useful execution hooks. The return value is a flag indicating whether interpretation of commands by the interpreter should stop.'
def onecmd(self, line):
(cmd, arg, line) = self.parseline(line) if (not line): return self.emptyline() if (cmd is None): return self.default(line) self.lastcmd = line if (line == 'EOF'): self.lastcmd = '' if (cmd == ''): return self.default(line) else: try: func = getattr(self, ('do_' + cmd)) except AttributeError: return self.default(line) return func(arg)
'Called when an empty line is entered in response to the prompt. If this method is not overridden, it repeats the last nonempty command entered.'
def emptyline(self):
if self.lastcmd: return self.onecmd(self.lastcmd)
'Called on an input line when the command prefix is not recognized. If this method is not overridden, it prints an error message and returns.'
def default(self, line):
self.stdout.write(('*** Unknown syntax: %s\n' % line))
'Method called to complete an input line when no command-specific complete_*() method is available. By default, it returns an empty list.'
def completedefault(self, *ignored):
return []
'Return the next possible completion for \'text\'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions.'
def complete(self, text, state):
if (state == 0): import readline origline = readline.get_line_buffer() line = origline.lstrip() stripped = (len(origline) - len(line)) begidx = (readline.get_begidx() - stripped) endidx = (readline.get_endidx() - stripped) if (begidx > 0): (cmd, args, foo) = self.parseline(line) if (cmd == ''): compfunc = self.completedefault else: try: compfunc = getattr(self, ('complete_' + cmd)) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
'List available commands with "help" or detailed help with "help cmd".'
def do_help(self, arg):
if arg: try: func = getattr(self, ('help_' + arg)) except AttributeError: try: doc = getattr(self, ('do_' + arg)).__doc__ if doc: self.stdout.write(('%s\n' % str(doc))) return except AttributeError: pass self.stdout.write(('%s\n' % str((self.nohelp % (arg,))))) return func() else: names = self.get_names() cmds_doc = [] cmds_undoc = [] help = {} for name in names: if (name[:5] == 'help_'): help[name[5:]] = 1 names.sort() prevname = '' for name in names: if (name[:3] == 'do_'): if (name == prevname): continue prevname = name cmd = name[3:] if (cmd in help): cmds_doc.append(cmd) del help[cmd] elif getattr(self, name).__doc__: cmds_doc.append(cmd) else: cmds_undoc.append(cmd) self.stdout.write(('%s\n' % str(self.doc_leader))) self.print_topics(self.doc_header, cmds_doc, 15, 80) self.print_topics(self.misc_header, help.keys(), 15, 80) self.print_topics(self.undoc_header, cmds_undoc, 15, 80)
'Display a list of strings as a compact set of columns. Each column is only as wide as necessary. Columns are separated by two spaces (one was not legible enough).'
def columnize(self, list, displaywidth=80):
if (not list): self.stdout.write('<empty>\n') return nonstrings = [i for i in range(len(list)) if (not isinstance(list[i], str))] if nonstrings: raise TypeError, ('list[i] not a string for i in %s' % ', '.join(map(str, nonstrings))) size = len(list) if (size == 1): self.stdout.write(('%s\n' % str(list[0]))) return for nrows in range(1, len(list)): ncols = (((size + nrows) - 1) // nrows) colwidths = [] totwidth = (-2) for col in range(ncols): colwidth = 0 for row in range(nrows): i = (row + (nrows * col)) if (i >= size): break x = list[i] colwidth = max(colwidth, len(x)) colwidths.append(colwidth) totwidth += (colwidth + 2) if (totwidth > displaywidth): break if (totwidth <= displaywidth): break else: nrows = len(list) ncols = 1 colwidths = [0] for row in range(nrows): texts = [] for col in range(ncols): i = (row + (nrows * col)) if (i >= size): x = '' else: x = list[i] texts.append(x) while (texts and (not texts[(-1)])): del texts[(-1)] for col in range(len(texts)): texts[col] = texts[col].ljust(colwidths[col]) self.stdout.write(('%s\n' % str(' '.join(texts))))
'Deprecated. Use the readPlist() function instead.'
def fromFile(cls, pathOrFile):
rootObject = readPlist(pathOrFile) plist = cls() plist.update(rootObject) return plist
'Deprecated. Use the writePlist() function instead.'
def write(self, pathOrFile):
writePlist(self, pathOrFile)
'Send user name, return response (should indicate password required).'
def user(self, user):
return self._shortcmd(('USER %s' % user))
'Send password, return response (response includes message count, mailbox size). NB: mailbox is locked by server from here to \'quit()\''
def pass_(self, pswd):
return self._shortcmd(('PASS %s' % pswd))
'Get mailbox status. Result is tuple of 2 ints (message count, mailbox size)'
def stat(self):
retval = self._shortcmd('STAT') rets = retval.split() if self._debugging: print '*stat*', repr(rets) numMessages = int(rets[1]) sizeMessages = int(rets[2]) return (numMessages, sizeMessages)
'Request listing, return result. Result without a message number argument is in form [\'response\', [\'mesg_num octets\', ...], octets]. Result when a message number argument is given is a single response: the "scan listing" for that message.'
def list(self, which=None):
if (which is not None): return self._shortcmd(('LIST %s' % which)) return self._longcmd('LIST')
'Retrieve whole message number \'which\'. Result is in form [\'response\', [\'line\', ...], octets].'
def retr(self, which):
return self._longcmd(('RETR %s' % which))
'Delete message number \'which\'. Result is \'response\'.'
def dele(self, which):
return self._shortcmd(('DELE %s' % which))
'Does nothing. One supposes the response indicates the server is alive.'
def noop(self):
return self._shortcmd('NOOP')
'Unmark all messages marked for deletion.'
def rset(self):
return self._shortcmd('RSET')
'Signoff: commit changes on server, unlock mailbox, close connection.'
def quit(self):
try: resp = self._shortcmd('QUIT') except error_proto as val: resp = val self.file.close() self.sock.close() del self.file, self.sock return resp
'Not sure what this does.'
def rpop(self, user):
return self._shortcmd(('RPOP %s' % user))
'Authorisation - only possible if server has supplied a timestamp in initial greeting. Args: user - mailbox user; secret - secret shared between client and server. NB: mailbox is locked by server from here to \'quit()\''
def apop(self, user, secret):
m = self.timestamp.match(self.welcome) if (not m): raise error_proto('-ERR APOP not supported by server') import hashlib digest = hashlib.md5((m.group(1) + secret)).digest() digest = ''.join(map((lambda x: ('%02x' % ord(x))), digest)) return self._shortcmd(('APOP %s %s' % (user, digest)))
'Retrieve message header of message number \'which\' and first \'howmuch\' lines of message body. Result is in form [\'response\', [\'line\', ...], octets].'
def top(self, which, howmuch):
return self._longcmd(('TOP %s %s' % (which, howmuch)))
'Return message digest (unique id) list. If \'which\', result contains unique id for that message in the form \'response mesgnum uid\', otherwise result is the list [\'response\', [\'mesgnum uid\', ...], octets]'
def uidl(self, which=None):
if (which is not None): return self._shortcmd(('UIDL %s' % which)) return self._longcmd('UIDL')
'Set the input delimiter. Can be a fixed string of any length, an integer, or None'
def set_terminator(self, term):
self.terminator = term
'predicate for inclusion in the readable for select()'
def readable(self):
return 1
'predicate for inclusion in the writable for select()'
def writable(self):
return (self.producer_fifo or (not self.connected))
'automatically close this channel once the outgoing queue is empty'
def close_when_done(self):
self.producer_fifo.append(None)
'This virtual directory is a root directory if parent and name are blank'
def is_root(self):
(parent, name) = self.split_path() return ((not parent) and (not name))
'Format this parameter suitable for IIS'
def __str__(self):
items = [self.Extension, self.Module, self.Flags] if self.Verbs: items.append(self.Verbs) items = [str(item) for item in items] return ','.join(items)
'Overridden by the sub-class to handle connection requests. This class creates a thread-pool using a Windows completion port, and dispatches requests via this port. Sub-classes can generally implement each connection request using blocking reads and writes, and the thread-pool will still provide decent response to the end user. The sub-class can set a max_workers attribute (default is 20). Note that this generally does *not* mean 20 threads will all be concurrently running, via the magic of Windows completion ports. There is no default implementation - sub-classes must implement this.'
def Dispatch(self, ecb):
raise NotImplementedError('sub-classes should override Dispatch')
'Handles errors in the Dispatch method. When a Dispatch method call fails, this method is called to handle the exception. The default implementation formats the traceback in the browser.'
def HandleDispatchError(self, ecb):
ecb.HttpStatusCode = isapicon.HSE_STATUS_ERROR (exc_typ, exc_val, exc_tb) = sys.exc_info() limit = None try: import cgi ecb.SendResponseHeaders('200 OK', 'Content-type: text/html\r\n\r\n', False) print >>ecb print >>ecb, '<H3>Traceback (most recent call last):</H3>' list = (traceback.format_tb(exc_tb, limit) + traceback.format_exception_only(exc_typ, exc_val)) print >>ecb, ('<PRE>%s<B>%s</B></PRE>' % (cgi.escape(''.join(list[:(-1)])), cgi.escape(list[(-1)]))) except ExtensionError: pass except: print 'FAILED to render the error message!' traceback.print_exc() print 'ORIGINAL extension error:' traceback.print_exception(exc_typ, exc_val, exc_tb) finally: exc_tb = None ecb.DoneWithSession()
'Called by the ISAPI framework to get the extension version The default implementation uses the classes docstring to set the extension description.'
def GetExtensionVersion(self, vi):
if (vi is not None): vi.ExtensionDesc = self.__doc__
'Called by the ISAPI framework for each extension request. sub-classes must provide an implementation for this method.'
def HttpExtensionProc(self, control_block):
raise NotImplementedError('sub-classes should override HttpExtensionProc')
'Called by the ISAPI framework as the extension terminates.'
def TerminateExtension(self, status):
pass
'Called by the ISAPI framework to get the extension version The default implementation uses the classes docstring to set the extension description, and uses the classes filter_flags attribute to set the ISAPI filter flags - you must specify filter_flags in your class.'
def GetFilterVersion(self, fv):
if (self.filter_flags is None): raise RuntimeError('You must specify the filter flags') if (fv is not None): fv.Flags = self.filter_flags fv.FilterDesc = self.__doc__
'Called by the ISAPI framework for each filter request. sub-classes must provide an implementation for this method.'
def HttpFilterProc(self, fc):
raise NotImplementedError('sub-classes should override HttpExtensionProc')
'Called by the ISAPI framework as the filter terminates.'
def TerminateFilter(self, status):
pass
'Evaluate an expression.'
def Eval(self, exp):
if (type(exp) not in [str, unicode]): raise Exception(desc='Must be a string', scode=winerror.DISP_E_TYPEMISMATCH) return eval(str(exp), self.dict)
'Execute a statement.'
def Exec(self, exp):
if (type(exp) not in [str, unicode]): raise Exception(desc='Must be a string', scode=winerror.DISP_E_TYPEMISMATCH) exec str(exp) in self.dict
'Return the template used to create this dialog'
def GetTemplate(self):
w = 272 h = 192 style = (((FRAMEDLG_STD | win32con.WS_VISIBLE) | win32con.DS_SETFONT) | win32con.WS_MINIMIZEBOX) template = [['Type Library Browser', (0, 0, w, h), style, None, (8, 'Helv')]] template.append([130, '&Type', (-1), (10, 10, 62, 9), (SS_STD | win32con.SS_LEFT)]) template.append([131, None, self.IDC_TYPELIST, (10, 20, 80, 80), LBS_STD]) template.append([130, '&Members', (-1), (100, 10, 62, 9), (SS_STD | win32con.SS_LEFT)]) template.append([131, None, self.IDC_MEMBERLIST, (100, 20, 80, 80), LBS_STD]) template.append([130, '&Parameters', (-1), (190, 10, 62, 9), (SS_STD | win32con.SS_LEFT)]) template.append([131, None, self.IDC_PARAMLIST, (190, 20, 75, 80), LBS_STD]) lvStyle = (((((SS_STD | commctrl.LVS_REPORT) | commctrl.LVS_AUTOARRANGE) | commctrl.LVS_ALIGNLEFT) | win32con.WS_BORDER) | win32con.WS_TABSTOP) template.append(['SysListView32', '', self.IDC_LISTVIEW, (10, 110, 255, 65), lvStyle]) return template
'Compare for sorting'
def __cmp__(self, other):
ret = cmp(self.order, other.order) if ((ret == 0) and self.doc): ret = cmp(self.doc[0], other.doc[0]) return ret
'Called when the process starts.'
def Starting(self, tlb_desc):
self.tlb_desc = tlb_desc
'Generate a single child. May force a few children to be built as we generate deps'
def generate_child(self, child, dir):
self.generate_type = GEN_DEMAND_CHILD la = self.typelib.GetLibAttr() lcid = la[1] clsid = la[0] major = la[3] minor = la[4] self.base_mod_name = (('win32com.gen_py.' + str(clsid)[1:(-1)]) + ('x%sx%sx%s' % (lcid, major, minor))) try: oleItems = {} vtableItems = {} infos = self.CollectOleItemInfosFromType() found = 0 for type_info_tuple in infos: (info, infotype, doc, attr) = type_info_tuple if (infotype == pythoncom.TKIND_COCLASS): (coClassItem, child_infos) = self._Build_CoClass(type_info_tuple) found = (build.MakePublicAttributeName(doc[0]) == child) if (not found): for (info, info_type, refType, doc, refAttr, flags) in child_infos: if (build.MakePublicAttributeName(doc[0]) == child): found = 1 break if found: oleItems[coClassItem.clsid] = coClassItem self._Build_CoClassChildren(coClassItem, child_infos, oleItems, vtableItems) break if (not found): for type_info_tuple in infos: (info, infotype, doc, attr) = type_info_tuple if (infotype in [pythoncom.TKIND_INTERFACE, pythoncom.TKIND_DISPATCH]): if (build.MakePublicAttributeName(doc[0]) == child): found = 1 (oleItem, vtableItem) = self._Build_Interface(type_info_tuple) oleItems[clsid] = oleItem if (vtableItem is not None): vtableItems[clsid] = vtableItem assert found, ("Cant find the '%s' interface in the CoClasses, or the interfaces" % (child,)) items = {} for (key, value) in oleItems.iteritems(): items[key] = (value, None) for (key, value) in vtableItems.iteritems(): existing = items.get(key, None) if (existing is not None): new_val = (existing[0], value) else: new_val = (None, value) items[key] = new_val self.progress.SetDescription('Generating...', len(items)) for (oleitem, vtableitem) in items.itervalues(): an_item = (oleitem or vtableitem) assert (not self.file), 'already have a file?' out_name = (os.path.join(dir, an_item.python_name) + '.py') worked = False self.file = self.open_writer(out_name) try: if (oleitem is not None): self.do_gen_child_item(oleitem) if (vtableitem is not None): self.do_gen_child_item(vtableitem) self.progress.Tick() worked = True finally: self.finish_writer(out_name, self.file, worked) self.file = None finally: self.progress.Finished()
'Return tuple counting in/outs/OPTS. Sum of result may not be len(argTuple), as some args may be in/out.'
def CountInOutOptArgs(self, argTuple):
ins = out = opts = 0 for argCheck in argTuple: inOut = argCheck[1] if (inOut == 0): ins = (ins + 1) out = (out + 1) else: if (inOut & pythoncom.PARAMFLAG_FIN): ins = (ins + 1) if (inOut & pythoncom.PARAMFLAG_FOPT): opts = (opts + 1) if (inOut & pythoncom.PARAMFLAG_FOUT): out = (out + 1) return (ins, out, opts)
'Provide \'default dispatch\' COM functionality - allow instance to be called'
def __call__(self, *args):
if self._olerepr_.defaultDispatchName: (invkind, dispid) = self._find_dispatch_type_(self._olerepr_.defaultDispatchName) else: (invkind, dispid) = ((pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET), pythoncom.DISPID_VALUE) if (invkind is not None): allArgs = ((dispid, LCID, invkind, 1) + args) return self._get_good_object_(self._oleobj_.Invoke(*allArgs), self._olerepr_.defaultDispatchName, None) raise TypeError('This dispatch object does not define a default method')
'Given an object (usually the retval from a method), make it a good object to return. Basically checks if it is a COM object, and wraps it up. Also handles the fact that a retval may be a tuple of retvals'
def _get_good_object_(self, ob, userName=None, ReturnCLSID=None):
if (ob is None): return None elif isinstance(ob, tuple): return tuple(map((lambda o, s=self, oun=userName, rc=ReturnCLSID: s._get_good_single_object_(o, oun, rc)), ob)) else: return self._get_good_single_object_(ob)
'Make a method object - Assumes in olerepr funcmap'
def _make_method_(self, name):
methodName = build.MakePublicAttributeName(name) methodCodeList = self._olerepr_.MakeFuncMethod(self._olerepr_.mapFuncs[name], methodName, 0) methodCode = '\n'.join(methodCodeList) try: codeObject = compile(methodCode, ('<COMObject %s>' % self._username_), 'exec') tempNameSpace = {} globNameSpace = globals().copy() globNameSpace['Dispatch'] = win32com.client.Dispatch exec codeObject in globNameSpace, tempNameSpace name = methodName fn = self._builtMethods_[name] = tempNameSpace[name] newMeth = MakeMethod(fn, self, self.__class__) return newMeth except: debug_print('Error building OLE definition for code ', methodCode) traceback.print_exc() return None
'Cleanup object - like a close - to force cleanup when you dont want to rely on Python\'s reference counting.'
def _Release_(self):
for childCont in self._mapCachedItems_.itervalues(): childCont._Release_() self._mapCachedItems_ = {} if self._oleobj_: self._oleobj_.Release() self.__dict__['_oleobj_'] = None if self._olerepr_: self.__dict__['_olerepr_'] = None self._enum_ = None
'Call the named method as a procedure, rather than function. Mainly used by Word.Basic, which whinges about such things.'
def _proc_(self, name, *args):
try: item = self._olerepr_.mapFuncs[name] dispId = item.dispid return self._get_good_object_(self._oleobj_.Invoke(*((dispId, LCID, item.desc[4], 0) + args))) except KeyError: raise AttributeError(name)
'Debug routine - dumps what it knows about an object.'
def _print_details_(self):
print 'AxDispatch container', self._username_ try: print 'Methods:' for method in self._olerepr_.mapFuncs.iterkeys(): print ' DCTB ', method print 'Props:' for (prop, entry) in self._olerepr_.propMap.iteritems(): print (' DCTB %s = 0x%x - %s' % (prop, entry.dispid, repr(entry))) print 'Get Props:' for (prop, entry) in self._olerepr_.propMapGet.iteritems(): print (' DCTB %s = 0x%x - %s' % (prop, entry.dispid, repr(entry))) print 'Put Props:' for (prop, entry) in self._olerepr_.propMapPut.iteritems(): print (' DCTB %s = 0x%x - %s' % (prop, entry.dispid, repr(entry))) except: traceback.print_exc()
'Flag these attribute names as being methods. Some objects do not correctly differentiate methods and properties, leading to problems when calling these methods. Specifically, trying to say: ob.SomeFunc() may yield an exception "None object is not callable" In this case, an attempt to fetch the *property*has worked and returned None, rather than indicating it is really a method. Calling: ob._FlagAsMethod("SomeFunc") should then allow this to work.'
def _FlagAsMethod(self, *methodNames):
for name in methodNames: details = build.MapEntry(self.__AttrToID__(name), (name,)) self._olerepr_.mapFuncs[name] = details
'Create a decimal point instance. >>> Decimal(\'3.14\') # string input Decimal("3.14") >>> Decimal((0, (3, 1, 4), -2)) # tuple input (sign, digit_tuple, exponent) Decimal("3.14") >>> Decimal(314) # int or long Decimal("314") >>> Decimal(Decimal(314)) # another decimal instance Decimal("314")'
def __new__(cls, value='0', context=None):
self = object.__new__(cls) self._is_special = False if isinstance(value, _WorkRep): self._sign = value.sign self._int = tuple(map(int, str(value.int))) self._exp = int(value.exp) return self if isinstance(value, Decimal): self._exp = value._exp self._sign = value._sign self._int = value._int self._is_special = value._is_special return self if isinstance(value, (int, long)): if (value >= 0): self._sign = 0 else: self._sign = 1 self._exp = 0 self._int = tuple(map(int, str(abs(value)))) return self if isinstance(value, (list, tuple)): if (len(value) != 3): raise ValueError, 'Invalid arguments' if (value[0] not in (0, 1)): raise ValueError, 'Invalid sign' for digit in value[1]: if ((not isinstance(digit, (int, long))) or (digit < 0)): raise ValueError, 'The second value in the tuple must be composed of non negative integer elements.' self._sign = value[0] self._int = tuple(value[1]) if (value[2] in ('F', 'n', 'N')): self._exp = value[2] self._is_special = True else: self._exp = int(value[2]) return self if isinstance(value, float): raise TypeError(('Cannot convert float to Decimal. ' + 'First convert the float to a string')) if (context is None): context = getcontext() if isinstance(value, basestring): if _isinfinity(value): self._exp = 'F' self._int = (0,) self._is_special = True if (_isinfinity(value) == 1): self._sign = 0 else: self._sign = 1 return self if _isnan(value): (sig, sign, diag) = _isnan(value) self._is_special = True if (len(diag) > context.prec): (self._sign, self._int, self._exp) = context._raise_error(ConversionSyntax) return self if (sig == 1): self._exp = 'n' else: self._exp = 'N' self._sign = sign self._int = tuple(map(int, diag)) return self try: (self._sign, self._int, self._exp) = _string2exact(value) except ValueError: self._is_special = True (self._sign, self._int, self._exp) = context._raise_error(ConversionSyntax) return self raise TypeError(('Cannot convert %r to Decimal' % value))
'Returns whether the number is not actually one. 0 if a number 1 if NaN 2 if sNaN'
def _isnan(self):
if self._is_special: exp = self._exp if (exp == 'n'): return 1 elif (exp == 'N'): return 2 return 0
'Returns whether the number is infinite 0 if finite or not a number 1 if +INF -1 if -INF'
def _isinfinity(self):
if (self._exp == 'F'): if self._sign: return (-1) return 1 return 0
'Returns whether the number is not actually one. if self, other are sNaN, signal if self, other are NaN return nan return 0 Done before operations.'
def _check_nans(self, other=None, context=None):
self_is_nan = self._isnan() if (other is None): other_is_nan = False else: other_is_nan = other._isnan() if (self_is_nan or other_is_nan): if (context is None): context = getcontext() if (self_is_nan == 2): return context._raise_error(InvalidOperation, 'sNaN', 1, self) if (other_is_nan == 2): return context._raise_error(InvalidOperation, 'sNaN', 1, other) if self_is_nan: return self return other return 0
'Is the number non-zero? 0 if self == 0 1 if self != 0'
def __nonzero__(self):
if self._is_special: return 1 return (sum(self._int) != 0)
'Compares one to another. -1 => a < b 0 => a = b 1 => a > b NaN => one is NaN Like __cmp__, but returns Decimal instances.'
def compare(self, other, context=None):
other = _convert_other(other) if (self._is_special or (other and other._is_special)): ans = self._check_nans(other, context) if ans: return ans return Decimal(self.__cmp__(other, context))
'x.__hash__() <==> hash(x)'
def __hash__(self):
if self._is_special: if self._isnan(): raise TypeError('Cannot hash a NaN value.') return hash(str(self)) i = int(self) if (self == Decimal(i)): return hash(i) assert self.__nonzero__() return hash(str(self.normalize()))
'Represents the number as a triple tuple. To show the internals exactly as they are.'
def as_tuple(self):
return (self._sign, self._int, self._exp)
'Represents the number as an instance of Decimal.'
def __repr__(self):
return ('Decimal("%s")' % str(self))
'Return string representation of the number in scientific notation. Captures all of the information in the underlying representation.'
def __str__(self, eng=0, context=None):
if self._isnan(): minus = ('-' * self._sign) if (self._int == (0,)): info = '' else: info = ''.join(map(str, self._int)) if (self._isnan() == 2): return ((minus + 'sNaN') + info) return ((minus + 'NaN') + info) if self._isinfinity(): minus = ('-' * self._sign) return (minus + 'Infinity') if (context is None): context = getcontext() tmp = map(str, self._int) numdigits = len(self._int) leftdigits = (self._exp + numdigits) if (eng and (not self)): if ((self._exp < 0) and (self._exp >= (-6))): s = ((('-' * self._sign) + '0.') + ('0' * abs(self._exp))) return s exp = ((((self._exp - 1) // 3) + 1) * 3) if (exp != self._exp): s = ('0.' + ('0' * (exp - self._exp))) else: s = '0' if (exp != 0): if context.capitals: s += 'E' else: s += 'e' if (exp > 0): s += '+' s += str(exp) s = (('-' * self._sign) + s) return s if eng: dotplace = (((leftdigits - 1) % 3) + 1) adjexp = ((leftdigits - 1) - ((leftdigits - 1) % 3)) else: adjexp = (leftdigits - 1) dotplace = 1 if (self._exp == 0): pass elif ((self._exp < 0) and (adjexp >= 0)): tmp.insert(leftdigits, '.') elif ((self._exp < 0) and (adjexp >= (-6))): tmp[0:0] = (['0'] * int((- leftdigits))) tmp.insert(0, '0.') else: if (numdigits > dotplace): tmp.insert(dotplace, '.') elif (numdigits < dotplace): tmp.extend((['0'] * (dotplace - numdigits))) if adjexp: if (not context.capitals): tmp.append('e') else: tmp.append('E') if (adjexp > 0): tmp.append('+') tmp.append(str(adjexp)) if eng: while (tmp[0:1] == ['0']): tmp[0:1] = [] if ((len(tmp) == 0) or (tmp[0] == '.') or (tmp[0].lower() == 'e')): tmp[0:0] = ['0'] if self._sign: tmp.insert(0, '-') return ''.join(tmp)
'Convert to engineering-type string. Engineering notation has an exponent which is a multiple of 3, so there are up to 3 digits left of the decimal place. Same rules for when in exponential and when as a value as in __str__.'
def to_eng_string(self, context=None):
return self.__str__(eng=1, context=context)
'Returns a copy with the sign switched. Rounds, if it has reason.'
def __neg__(self, context=None):
if self._is_special: ans = self._check_nans(context=context) if ans: return ans if (not self): sign = 0 elif self._sign: sign = 0 else: sign = 1 if (context is None): context = getcontext() if (context._rounding_decision == ALWAYS_ROUND): return Decimal((sign, self._int, self._exp))._fix(context) return Decimal((sign, self._int, self._exp))
'Returns a copy, unless it is a sNaN. Rounds the number (if more then precision digits)'
def __pos__(self, context=None):
if self._is_special: ans = self._check_nans(context=context) if ans: return ans sign = self._sign if (not self): sign = 0 if (context is None): context = getcontext() if (context._rounding_decision == ALWAYS_ROUND): ans = self._fix(context) else: ans = Decimal(self) ans._sign = sign return ans
'Returns the absolute value of self. If the second argument is 0, do not round.'
def __abs__(self, round=1, context=None):
if self._is_special: ans = self._check_nans(context=context) if ans: return ans if (not round): if (context is None): context = getcontext() context = context._shallow_copy() context._set_rounding_decision(NEVER_ROUND) if self._sign: ans = self.__neg__(context=context) else: ans = self.__pos__(context=context) return ans
'Returns self + other. -INF + INF (or the reverse) cause InvalidOperation errors.'
def __add__(self, other, context=None):
other = _convert_other(other) if (context is None): context = getcontext() if (self._is_special or other._is_special): ans = self._check_nans(other, context) if ans: return ans if self._isinfinity(): if ((self._sign != other._sign) and other._isinfinity()): return context._raise_error(InvalidOperation, '-INF + INF') return Decimal(self) if other._isinfinity(): return Decimal(other) shouldround = (context._rounding_decision == ALWAYS_ROUND) exp = min(self._exp, other._exp) negativezero = 0 if ((context.rounding == ROUND_FLOOR) and (self._sign != other._sign)): negativezero = 1 if ((not self) and (not other)): sign = min(self._sign, other._sign) if negativezero: sign = 1 return Decimal((sign, (0,), exp)) if (not self): exp = max(exp, ((other._exp - context.prec) - 1)) ans = other._rescale(exp, watchexp=0, context=context) if shouldround: ans = ans._fix(context) return ans if (not other): exp = max(exp, ((self._exp - context.prec) - 1)) ans = self._rescale(exp, watchexp=0, context=context) if shouldround: ans = ans._fix(context) return ans op1 = _WorkRep(self) op2 = _WorkRep(other) (op1, op2) = _normalize(op1, op2, shouldround, context.prec) result = _WorkRep() if (op1.sign != op2.sign): if (op1.int == op2.int): if (exp < context.Etiny()): exp = context.Etiny() context._raise_error(Clamped) return Decimal((negativezero, (0,), exp)) if (op1.int < op2.int): (op1, op2) = (op2, op1) if (op1.sign == 1): result.sign = 1 (op1.sign, op2.sign) = (op2.sign, op1.sign) else: result.sign = 0 elif (op1.sign == 1): result.sign = 1 (op1.sign, op2.sign) = (0, 0) else: result.sign = 0 if (op2.sign == 0): result.int = (op1.int + op2.int) else: result.int = (op1.int - op2.int) result.exp = op1.exp ans = Decimal(result) if shouldround: ans = ans._fix(context) return ans
'Return self + (-other)'
def __sub__(self, other, context=None):
other = _convert_other(other) if (self._is_special or other._is_special): ans = self._check_nans(other, context=context) if ans: return ans tmp = Decimal(other) tmp._sign = (1 - tmp._sign) return self.__add__(tmp, context=context)
'Return other + (-self)'
def __rsub__(self, other, context=None):
other = _convert_other(other) tmp = Decimal(self) tmp._sign = (1 - tmp._sign) return other.__add__(tmp, context=context)
'Special case of add, adding 1eExponent Since it is common, (rounding, for example) this adds (sign)*one E self._exp to the number more efficiently than add. For example: Decimal(\'5.624e10\')._increment() == Decimal(\'5.625e10\')'
def _increment(self, round=1, context=None):
if self._is_special: ans = self._check_nans(context=context) if ans: return ans return Decimal(self) L = list(self._int) L[(-1)] += 1 spot = (len(L) - 1) while (L[spot] == 10): L[spot] = 0 if (spot == 0): L[0:0] = [1] break L[(spot - 1)] += 1 spot -= 1 ans = Decimal((self._sign, L, self._exp)) if (context is None): context = getcontext() if (round and (context._rounding_decision == ALWAYS_ROUND)): ans = ans._fix(context) return ans
'Return self * other. (+-) INF * 0 (or its reverse) raise InvalidOperation.'
def __mul__(self, other, context=None):
other = _convert_other(other) if (context is None): context = getcontext() resultsign = (self._sign ^ other._sign) if (self._is_special or other._is_special): ans = self._check_nans(other, context) if ans: return ans if self._isinfinity(): if (not other): return context._raise_error(InvalidOperation, '(+-)INF * 0') return Infsign[resultsign] if other._isinfinity(): if (not self): return context._raise_error(InvalidOperation, '0 * (+-)INF') return Infsign[resultsign] resultexp = (self._exp + other._exp) shouldround = (context._rounding_decision == ALWAYS_ROUND) if ((not self) or (not other)): ans = Decimal((resultsign, (0,), resultexp)) if shouldround: ans = ans._fix(context) return ans if (self._int == (1,)): ans = Decimal((resultsign, other._int, resultexp)) if shouldround: ans = ans._fix(context) return ans if (other._int == (1,)): ans = Decimal((resultsign, self._int, resultexp)) if shouldround: ans = ans._fix(context) return ans op1 = _WorkRep(self) op2 = _WorkRep(other) ans = Decimal((resultsign, map(int, str((op1.int * op2.int))), resultexp)) if shouldround: ans = ans._fix(context) return ans
'Return self / other.'
def __div__(self, other, context=None):
return self._divide(other, context=context)
'Return a / b, to context.prec precision. divmod: 0 => true division 1 => (a //b, a%b) 2 => a //b 3 => a%b Actually, if divmod is 2 or 3 a tuple is returned, but errors for computing the other value are not raised.'
def _divide(self, other, divmod=0, context=None):
other = _convert_other(other) if (context is None): context = getcontext() sign = (self._sign ^ other._sign) if (self._is_special or other._is_special): ans = self._check_nans(other, context) if ans: if divmod: return (ans, ans) return ans if (self._isinfinity() and other._isinfinity()): if divmod: return (context._raise_error(InvalidOperation, '(+-)INF // (+-)INF'), context._raise_error(InvalidOperation, '(+-)INF % (+-)INF')) return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') if self._isinfinity(): if (divmod == 1): return (Infsign[sign], context._raise_error(InvalidOperation, 'INF % x')) elif (divmod == 2): return (Infsign[sign], NaN) elif (divmod == 3): return (Infsign[sign], context._raise_error(InvalidOperation, 'INF % x')) return Infsign[sign] if other._isinfinity(): if divmod: return (Decimal((sign, (0,), 0)), Decimal(self)) context._raise_error(Clamped, 'Division by infinity') return Decimal((sign, (0,), context.Etiny())) if ((not self) and (not other)): if divmod: return context._raise_error(DivisionUndefined, '0 / 0', 1) return context._raise_error(DivisionUndefined, '0 / 0') if (not self): if divmod: otherside = Decimal(self) otherside._exp = min(self._exp, other._exp) return (Decimal((sign, (0,), 0)), otherside) exp = (self._exp - other._exp) if (exp < context.Etiny()): exp = context.Etiny() context._raise_error(Clamped, '0e-x / y') if (exp > context.Emax): exp = context.Emax context._raise_error(Clamped, '0e+x / y') return Decimal((sign, (0,), exp)) if (not other): if divmod: return context._raise_error(DivisionByZero, 'divmod(x,0)', sign, 1) return context._raise_error(DivisionByZero, 'x / 0', sign) shouldround = (context._rounding_decision == ALWAYS_ROUND) if (divmod and (self.__abs__(0, context) < other.__abs__(0, context))): if ((divmod == 1) or (divmod == 3)): exp = min(self._exp, other._exp) ans2 = self._rescale(exp, context=context, watchexp=0) if shouldround: ans2 = ans2._fix(context) return (Decimal((sign, (0,), 0)), ans2) elif (divmod == 2): return (Decimal((sign, (0,), 0)), Decimal(self)) op1 = _WorkRep(self) op2 = _WorkRep(other) (op1, op2, adjust) = _adjust_coefficients(op1, op2) res = _WorkRep((sign, 0, (op1.exp - op2.exp))) if (divmod and (res.exp > (context.prec + 1))): return context._raise_error(DivisionImpossible) prec_limit = (10 ** context.prec) while 1: while (op2.int <= op1.int): res.int += 1 op1.int -= op2.int if ((res.exp == 0) and divmod): if ((res.int >= prec_limit) and shouldround): return context._raise_error(DivisionImpossible) otherside = Decimal(op1) frozen = context._ignore_all_flags() exp = min(self._exp, other._exp) otherside = otherside._rescale(exp, context=context, watchexp=0) context._regard_flags(*frozen) if shouldround: otherside = otherside._fix(context) return (Decimal(res), otherside) if ((op1.int == 0) and (adjust >= 0) and (not divmod)): break if ((res.int >= prec_limit) and shouldround): if divmod: return context._raise_error(DivisionImpossible) shouldround = 1 if (op1.int != 0): res.int *= 10 res.int += 1 res.exp -= 1 break res.int *= 10 res.exp -= 1 adjust += 1 op1.int *= 10 op1.exp -= 1 if ((res.exp == 0) and divmod and (op2.int > op1.int)): if ((res.int >= prec_limit) and shouldround): return context._raise_error(DivisionImpossible) otherside = Decimal(op1) frozen = context._ignore_all_flags() exp = min(self._exp, other._exp) otherside = otherside._rescale(exp, context=context) context._regard_flags(*frozen) return (Decimal(res), otherside) ans = Decimal(res) if shouldround: ans = ans._fix(context) return ans
'Swaps self/other and returns __div__.'
def __rdiv__(self, other, context=None):
other = _convert_other(other) return other.__div__(self, context=context)
'(self // other, self % other)'
def __divmod__(self, other, context=None):
return self._divide(other, 1, context)
'Swaps self/other and returns __divmod__.'
def __rdivmod__(self, other, context=None):
other = _convert_other(other) return other.__divmod__(self, context=context)
'self % other'
def __mod__(self, other, context=None):
other = _convert_other(other) if (self._is_special or other._is_special): ans = self._check_nans(other, context) if ans: return ans if (self and (not other)): return context._raise_error(InvalidOperation, 'x % 0') return self._divide(other, 3, context)[1]