rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
def refmac5_prep(xyzin, tlsin, xyzout, tlsout):
def refmac5_prep(xyzin, tlsin_list, xyzout, tlsout):
def refmac5_prep(xyzin, tlsin, xyzout, tlsout): """Use TLS model + Uiso for each atom. Output xyzout with the residual Uiso only. """ os.umask(022) ## load structure struct = LoadStructure(fil = xyzin) ## load and construct TLS groups tls_group_list = [] tls_file = TLSFile() tls_file.set_file_format(TLSFileFormatTL...
tls_file = TLSFile() tls_file.set_file_format(TLSFileFormatTLSOUT()) tls_file.load(open(tlsin, "r")) for tls_desc in tls_file.tls_desc_list: tls_group = tls_desc.construct_tls_group_with_atoms(struct) fit_tls_group(tls_group) tls_group.tls_desc = tls_desc tls_group_list.append(tls_group)
for tlsin in tlsin_list: tls_file = TLSFile() tls_file.set_file_format(TLSFileFormatTLSOUT()) tls_file.load(open(tlsin, "r")) for tls_desc in tls_file.tls_desc_list: tls_group = tls_desc.construct_tls_group_with_atoms(struct) tls_group.tls_desc = tls_desc tls_group_list.append(tls_group)
def refmac5_prep(xyzin, tlsin, xyzout, tlsout): """Use TLS model + Uiso for each atom. Output xyzout with the residual Uiso only. """ os.umask(022) ## load structure struct = LoadStructure(fil = xyzin) ## load and construct TLS groups tls_group_list = [] tls_file = TLSFile() tls_file.set_file_format(TLSFileFormatTL...
if atm.sig_position:
if atm.sig_position != None:
def atom_common(arec1, arec2): arec2["serial"] = arec1["serial"] arec2["chainID"] = arec1["chainID"] arec2["resName"] = arec1["resName"] arec2["resSeq"] = arec1["resSeq"] arec2["iCode"] = arec1["iCode"] arec2["name"] = arec1["name"] arec2["altLoc"] = arec1["altLoc"] arec2["element"] = arec1["element"] arec2["ch...
if atm.U:
if atm.U != None:
def atom_common(arec1, arec2): arec2["serial"] = arec1["serial"] arec2["chainID"] = arec1["chainID"] arec2["resName"] = arec1["resName"] arec2["resSeq"] = arec1["resSeq"] arec2["iCode"] = arec1["iCode"] arec2["name"] = arec1["name"] arec2["altLoc"] = arec1["altLoc"] arec2["element"] = arec1["element"] arec2["ch...
if atm.sig_U: siguij_rec = siguij()
if atm.sig_U != None: siguij_rec = SIGUIJ()
def atom_common(arec1, arec2): arec2["serial"] = arec1["serial"] arec2["chainID"] = arec1["chainID"] arec2["resName"] = arec1["resName"] arec2["resSeq"] = arec1["resSeq"] arec2["iCode"] = arec1["iCode"] arec2["name"] = arec1["name"] arec2["altLoc"] = arec1["altLoc"] arec2["element"] = arec1["element"] arec2["ch...
self.segmentations = []
self.configurations = []
def __init__(self): ## bars are 15 pixels heigh self.pheight = ALIGN_HEIGHT ## spacing pixels between stacked bars self.spacing = ALIGN_SPACING ## background color self.bg_color = rgb_f2i((1.0, 1.0, 1.0)) self.frag_list = [] self.segmentations = []
self.segmentations.append(tls_seg_desc)
self.configurations.append(tls_seg_desc)
def add_tls_segmentation(self, chainopt, ntls): """Add a TLS optimization to the alignment plot. """ tlsopt = chainopt["tlsopt"][ntls] ## get the list of TLS segments for the specified number of ## segments (ntls) tls_seg_desc = {} self.segmentations.append(tls_seg_desc) tls_seg_desc["chainopt"] = chainopt tls_seg_des...
if len(self.frag_list)==0 or len(self.segmentations)==0:
if len(self.frag_list)==0 or len(self.configurations)==0:
def plot(self, path): """Plot and write the png plot image to the specified path. """ if len(self.frag_list)==0 or len(self.segmentations)==0: return False nfrag = len(self.frag_list) target_width = 500 fw = int(round(float(ALIGN_TARGET_WIDTH) / nfrag)) fwidth = max(1, fw)
num_plots = len(self.segmentations)
num_plots = len(self.configurations)
def plot(self, path): """Plot and write the png plot image to the specified path. """ if len(self.frag_list)==0 or len(self.segmentations)==0: return False nfrag = len(self.frag_list) target_width = 500 fw = int(round(float(ALIGN_TARGET_WIDTH) / nfrag)) fwidth = max(1, fw)
for i in range(len(self.segmentations)): tls_seg_desc = self.segmentations[i]
for i in range(len(self.configurations)): tls_seg_desc = self.configurations[i]
def plot(self, path): """Plot and write the png plot image to the specified path. """ if len(self.frag_list)==0 or len(self.segmentations)==0: return False nfrag = len(self.frag_list) target_width = 500 fw = int(round(float(ALIGN_TARGET_WIDTH) / nfrag)) fwidth = max(1, fw)
if const.MAINCHAIN_ATOM_DICT.has_key(atom.name) is False:
if const.MAINCHAIN_ATOM_DICT.has_key(atm.name) is False:
def calc_include_atom(atm, reject_messages = False): """Filter out atoms from the model which will cause problems or cont contribute to the TLS analysis. """ if atm.position == None: return False if atm.occupancy < 0.1: if reject_messages == True: console.stdoutln("calc_include_atom(%s): rejected because of low occupa...
self.term_alpha = 0.75
self.term_alpha = 0.5
def __init__(self): self.visible = True self.width = 0 self.height = 0 self.zplane = 5000.0
print "lsq_fit_segment centroid = ", centroid
def lsq_fit_segment(self, frag_id1, frag_id2): """Performs a LSQ fit of TLS parameters for the protein segment starting with fragment index ifrag_start to (and including) the fragment ifrag_end. """ ## all return values here fit_info = {} ## calculate the start/end indexes of the start fragment ## and end fragment so ...
name = atm_map["name"] fragment_id = atm_map["fragment_id"] chain_id = atm_map["chain_id"]
name = atm_map.get("name", "") fragment_id = atm_map.get("fragment_id", "") chain_id = atm_map.get("chain_id", "")
def load_atom(self, atm_map): """Called repeatedly by the implementation of read_atoms to load all the data for a single atom. The data is contained in the atm_map argument, and is not well documented at this point. Look at this function and you'll figure it out. """ ## XXX -- I presently do not support more than one...
atm_id = (name, alt_loc, fragment_id, chain_id)
def load_atom(self, atm_map): """Called repeatedly by the implementation of read_atoms to load all the data for a single atom. The data is contained in the atm_map argument, and is not well documented at this point. Look at this function and you'll figure it out. """ ## XXX -- I presently do not support more than one...
atm_id = (name, alt_loc, fragment_id, chain_id)
def load_atom(self, atm_map): """Called repeatedly by the implementation of read_atoms to load all the data for a single atom. The data is contained in the atm_map argument, and is not well documented at this point. Look at this function and you'll figure it out. """ ## XXX -- I presently do not support more than one...
debug("duplicate atom "+str(atm_id)) return
old_name = name i = 2 while self.atom_cache.has_key(atm_id): name = "%s%d" % (old_name, i) atm_id = (name, alt_loc, fragment_id, chain_id) i += 1
def load_atom(self, atm_map): """Called repeatedly by the implementation of read_atoms to load all the data for a single atom. The data is contained in the atm_map argument, and is not well documented at this point. Look at this function and you'll figure it out. """ ## XXX -- I presently do not support more than one...
stdout, stdin, stderr = popen2.popen3( (self.render_program_path, "-png", self.render_png_path, "-gamma", "1.5"), 32768*4)
pobj = popen2.Popen4([self.render_program_path, "-png", self.render_png_path, "-gamma", "1.5"], 32768) stdin = pobj.tochild
def close(self): for fil in self.fils: fil.close()
else: stdout.read() stdout.close() stderr.read() stderr.close()
elif pobj is not None: pobj.wait()
def close(self): for fil in self.fils: fil.close()
atom.calc_anisotropy() atom.calc_anisotropy3()
try: atom.calc_anisotropy() except ZeroDivisionError: pass try: atom.calc_anisotropy3() except ZeroDivisionError: pass
def atom_test(atom, stats): """Tests the mmLib.Structure.Atom object. """ stats["atom_count"] += 1 stats["testing"] = atom len(atom) alt_loc = atom.get_structure().get_default_alt_loc() atom.get_fragment() atom.get_chain() atom.get_model() atom.get_structure() visited_atm_list = [] for atm in atom.iter_alt_loc(...
try: frag1 = self.segment[0] frag2 = self.segment[-1] except IndexError: return "AlphaHelix(%s %d)" % (self.helix_id, self.helix_class) return "AlphaHelix(%s %s %s...%s)" % ( self.helix_id, self.helix_class, str(frag1), str(frag2))
return "AlphaHelix(%s %s %s:%s...%s:%s)" % ( self.helix_id, self.helix_class, self.chain_id1, self.fragment_id1, self.chain_id2, self.fragment_id2)
def __str__(self): try: frag1 = self.segment[0] frag2 = self.segment[-1] except IndexError: return "AlphaHelix(%s %d)" % (self.helix_id, self.helix_class)
if ref_tf>tls_tf: aatm.temp_factor = ((add_Uiso) + ref_tf - tls_tf)*U2B
if ref_tf > tls_tf: aatm.temp_factor = ((add_Uiso) + ref_tf - tls_tf)*Constants.U2B
def refmac5_prep(xyzin, tlsin_list, xyzout, tlsout): """Use TLS model + Uiso for each atom. Output xyzout with the residual Uiso only. """ os.umask(022) ## load structure struct = FileLoader.LoadStructure(fil = xyzin) ## load and construct TLS groups tls_group_list = [] tls_file = TLS.TLSFile() tls_file.set_file_fo...
aatm.temp_factor = (add_Uiso) * U2B
aatm.temp_factor = (add_Uiso) * Constants.U2B
def refmac5_prep(xyzin, tlsin_list, xyzout, tlsout): """Use TLS model + Uiso for each atom. Output xyzout with the residual Uiso only. """ os.umask(022) ## load structure struct = FileLoader.LoadStructure(fil = xyzin) ## load and construct TLS groups tls_group_list = [] tls_file = TLS.TLSFile() tls_file.set_file_fo...
outbase = string.join(listx, "_")
outbase ="_".join(listx)
def html_page(self): job_id = check_job_id(self.form) title = 'Input Files for Refmac5 TLS Refinement' x = '' x += self.html_head(title) x += self.html_title(title)
usage: idle.py [-c command] [-d] [-e] [-s] [-t title] [arg] ... -c command run this command -d enable debugger -e edit mode; arguments are files to be edited -s run $IDLESTARTUP or $PYTHONSTARTUP before anything else -t title set title of shell window When neither -c nor -e is used, and...
usage: idle.py [-c command] [-d] [-i] [-r script] [-s] [-t title] [arg] ... idle file(s) (without options) edit the file(s) -c cmd run the command in a shell -d enable the debugger -i open an interactive shell -i file(s) open a shell and also an editor window for each file -r script run a file...
def isatty(self): return 1
opts, args = getopt.getopt(argv, "c:deist:")
opts, args = getopt.getopt(argv, "c:dir:st:")
def main(self, argv, noshell): cmd = None edit = 0 debug = 0 startup = 0 try: opts, args = getopt.getopt(argv, "c:deist:") except getopt.error, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.stderr.write(usage_msg) sys.exit(2) for o, a in opts: noshell = 0 if o == '-c': cmd = a if o == '-d': debug = 1 if o == '-...
if o == '-e': edit = 1
if o == '-i': interactive = 1 if o == '-r': script = a
def main(self, argv, noshell): cmd = None edit = 0 debug = 0 startup = 0 try: opts, args = getopt.getopt(argv, "c:deist:") except getopt.error, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.stderr.write(usage_msg) sys.exit(2) for o, a in opts: noshell = 0 if o == '-c': cmd = a if o == '-d': debug = 1 if o == '-...
elif not edit and args and args[0] != "-": interp.execfile(args[0])
elif script: if os.path.isfile(script): interp.execfile(script) else: print "No script file: ", script
def main(self, argv, noshell): cmd = None edit = 0 debug = 0 startup = 0 try: opts, args = getopt.getopt(argv, "c:deist:") except getopt.error, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.stderr.write(usage_msg) sys.exit(2) for o, a in opts: noshell = 0 if o == '-c': cmd = a if o == '-d': debug = 1 if o == '-...
def testNtoH(self): for func in socket.htonl, socket.ntohl: for i in (0, 1, ~0xffff, 2L): self.assertEqual(i, func(func(i))) biglong = 2**32L - 1 swapped = func(biglong) self.assert_(swapped == biglong or swapped == -1) self.assertRaises(OverflowError, func, 2L**34)
def testNtoHL(self): sizes = {socket.htonl: 32, socket.ntohl: 32, socket.htons: 16, socket.ntohs: 16} for func, size in sizes.items(): mask = (1L<<size) - 1 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210): self.assertEqual(i & mask, func(func(i&mask)) & mask) swapped = func(mask) self.assertEqual(swapped...
def testNtoH(self): for func in socket.htonl, socket.ntohl: for i in (0, 1, ~0xffff, 2L): self.assertEqual(i, func(func(i)))
line = line.lstrip()
def _ascii_split(self, s, charset, firstline): # Attempt to split the line at the highest-level syntactic break # possible. Note that we don't have a lot of smarts about field # syntax; we just try to break on semi-colons, then whitespace. rtn = [] lines = s.splitlines() while lines: line = lines.pop(0) if firstline: ...
sentence_end = ".?!"
sentence_end_re = re.compile(r'[%s]' r'[\.\!\?]' r'[\"\']?' % string.lowercase)
def islower (c): return c in string.lowercase
punct = self.sentence_end
pat = self.sentence_end_re
def _fix_sentence_endings (self, chunks): """_fix_sentence_endings(chunks : [string])
if (chunks[i][-1] in punct and chunks[i+1] == " " and islower(chunks[i][-2])):
if chunks[i+1] == " " and pat.search(chunks[i]):
def _fix_sentence_endings (self, chunks): """_fix_sentence_endings(chunks : [string])
dump(vars(values), write)
dump({'faultCode': values.faultCode, 'faultString': values.faultString}, write)
def dumps(self, values): out = [] write = out.append dump = self.__dump if isinstance(values, Fault): # fault instance write("<fault>\n") dump(vars(values), write) write("</fault>\n") else: # parameter block # FIXME: the xml-rpc specification allows us to leave out # the entire <params> block if there are no parameters...
print "self.bdist_dir = %s" % self.bdist_dir print "self.format = %s" % self.format
def run (self):
args = args + to
if to[0] == '-to': to = to[1:] args = args + ('-to',) + tuple(to)
def put(self, data, to=None): args = (self.name, 'put', data) if to: args = args + to apply(self.tk.call, args)
p = subprocess.Popen([sys.executable, "-c", "import os; os.abort()"])
old_limit = self._suppress_core_files() try: p = subprocess.Popen([sys.executable, "-c", "import os; os.abort()"]) finally: self._unsuppress_core_files(old_limit)
def test_run_abort(self): # returncode handles signal termination p = subprocess.Popen([sys.executable, "-c", "import os; os.abort()"]) p.wait() self.assertEqual(-p.returncode, signal.SIGABRT)
self._tk.deletecommand(cbname)
self._master.deletecommand(cbname)
def trace_vdelete(self, mode, cbname): self._tk.call("trace", "vdelete", self._name, mode, cbname) self._tk.deletecommand(cbname)
self._preprocess(body, headers, lang)
self._preprocess(body, headers, include_dirs, lang)
def try_cpp (self, body=None, headers=None, include_dirs=None, lang="c"): """Construct a source file from 'body' (a string containing lines of C/C++ code) and 'headers' (a list of header files to include) and run it through the preprocessor. Return true if the preprocessor succeeded, false if there were any errors. ('...
(src, out) = self._preprocess(body, headers, lang)
(src, out) = self._preprocess(body, headers, include_dirs, lang)
def search_cpp (self, pattern, body=None, headers=None, include_dirs=None, lang="c"): """Construct a source file (just like 'try_cpp()'), run it through the preprocessor, and return true if any line of the output matches 'pattern'. 'pattern' should either be a compiled regex object or a string containing a regex. If ...
if pattern.search(pattern):
if pattern.search(line):
def search_cpp (self, pattern, body=None, headers=None, include_dirs=None, lang="c"): """Construct a source file (just like 'try_cpp()'), run it through the preprocessor, and return true if any line of the output matches 'pattern'. 'pattern' should either be a compiled regex object or a string containing a regex. If ...
self._compile(body, headers, lang)
self._compile(body, headers, include_dirs, lang)
def try_compile (self, body, headers=None, include_dirs=None, lang="c"): """Try to compile a source file built from 'body' and 'headers'. Return true on success, false otherwise. """ from distutils.ccompiler import CompileError self._check_compiler() try: self._compile(body, headers, lang) ok = 1 except CompileError: o...
exts.append( Extension('audioop', ['audioop.c']) )
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
Note that decimal places (from zero) is usually not the same
Note that decimal places (from zero) are usually not the same
def failUnlessAlmostEqual(self, first, second, places=7, msg=None): """Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero.
import unittest
def loadTestsFromName(self, name, module=None): """Return a suite of all tests cases given a string specifier.
issubclass(obj, unittest.TestCase)):
issubclass(obj, TestCase)):
def loadTestsFromName(self, name, module=None): """Return a suite of all tests cases given a string specifier.
elif isinstance(obj, unittest.TestSuite):
elif isinstance(obj, TestSuite):
def loadTestsFromName(self, name, module=None): """Return a suite of all tests cases given a string specifier.
if not isinstance(test, (unittest.TestCase, unittest.TestSuite)):
if not isinstance(test, (TestCase, TestSuite)):
def loadTestsFromName(self, name, module=None): """Return a suite of all tests cases given a string specifier.
timeTaken = float(stopTime - startTime)
timeTaken = stopTime - startTime
def run(self, test): "Run the given test case or test suite." result = self._makeResult() startTime = time.time() test(result) stopTime = time.time() timeTaken = float(stopTime - startTime) result.printErrors() self.stream.writeln(result.separator2) run = result.testsRun self.stream.writeln("Ran %d test%s in %.3fs" % (...
def cmp(f1, f2, shallow=1, use_statcache=0):
def cmp(f1, f2, shallow=1, use_statcache=None):
def cmp(f1, f2, shallow=1, use_statcache=0): """Compare two files. Arguments: f1 -- First file name f2 -- Second file name shallow -- Just check stat signature (do not read the files). defaults to 1. use_statcache -- obsolete argument. Return value: True if the files are the same, False otherwise. This function...
def cmpfiles(a, b, common, shallow=1, use_statcache=0):
def cmpfiles(a, b, common, shallow=1, use_statcache=None):
def cmpfiles(a, b, common, shallow=1, use_statcache=0): """Compare common files in two directories. a, b -- directory names common -- list of file names found in both directories shallow -- if true, do comparison based solely on stat() information use_statcache -- obsolete argument Returns a tuple of three lists: fil...
raise getopt.error, 'need exactly two args'
raise getopt.GetoptError('need exactly two args', None)
def demo(): import sys import getopt options, args = getopt.getopt(sys.argv[1:], 'r') if len(args) != 2: raise getopt.error, 'need exactly two args' dd = dircmp(args[0], args[1]) if ('-r', '') in options: dd.report_full_closure() else: dd.report()
if self.optmize > 0:
if self.optimize > 0:
def _bytecode_filenames (self, py_filenames): bytecode_files = [] for py_file in py_filenames: if self.compile: bytecode_files.append(py_file + "c") if self.optmize > 0: bytecode_files.append(py_file + "o")
tmp_file.close()
_sync_close(tmp_file)
def add(self, message): """Add message and return assigned key.""" tmp_file = self._create_tmp() try: self._dump_message(message, tmp_file) finally: tmp_file.close() if isinstance(message, MaildirMessage): subdir = message.get_subdir() suffix = self.colon + message.get_info() if suffix == self.colon: suffix = '' else: ...
new_file.close()
_sync_close(new_file)
def flush(self): """Write any pending changes to disk.""" if not self._pending: return self._lookup() new_file = _create_temporary(self._path) try: new_toc = {} self._pre_mailbox_hook(new_file) for key in sorted(self._toc.keys()): start, stop = self._toc[key] self._file.seek(start) self._pre_message_hook(new_file) new_...
f.close()
_sync_close(f)
def add(self, message): """Add message and return assigned key.""" keys = self.keys() if len(keys) == 0: new_key = 1 else: new_key = max(keys) + 1 new_path = os.path.join(self._path, str(new_key)) f = _create_carefully(new_path) try: if self._locked: _lock_file(f) try: self._dump_message(message, f) if isinstance(messa...
f.close()
_sync_close(f)
def __setitem__(self, key, message): """Replace the keyed message; raise KeyError if it doesn't exist.""" path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') except IOError, e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise try: if self._locked: _lock_file(f) tr...
self._file.close()
_sync_close(self._file)
def unlock(self): """Unlock the mailbox if it is locked.""" if self._locked: _unlock_file(self._file) self._file.close() del self._file self._locked = False
f.close()
_sync_close(f)
def set_sequences(self, sequences): """Set sequences using the given name-to-key-list dictionary.""" f = open(os.path.join(self._path, '.mh_sequences'), 'r+') try: os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC)) for name, keys in sequences.iteritems(): if len(keys) == 0: continue f.write('%s:' % name) prev = None c...
status = []
status = [self.__class__.__module__+"."+self.__class__.__name__]
def __repr__ (self): try: status = [] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: if type(self.addr) == types.TupleType: status.append ('%s:%d' % self.addr) else: status.append (self.addr) return '<%s %s at %x>' % (self.__class__.__name__, ...
return '<%s %s at %x>' % (self.__class__.__name__, ' '.join (status), id (self))
return '<%s at %
def __repr__ (self): try: status = [] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: if type(self.addr) == types.TupleType: status.append ('%s:%d' % self.addr) else: status.append (self.addr) return '<%s %s at %x>' % (self.__class__.__name__, ...
register("gnome", None, BackgroundBrowser(commd))
register("gnome", None, BackgroundBrowser(commd.split()))
def register_X_browsers(): # The default Gnome browser if _iscommand("gconftool-2"): # get the web browser string from gconftool gc = 'gconftool-2 -g /desktop/gnome/url-handlers/http/command 2>/dev/null' out = os.popen(gc) commd = out.read().strip() retncode = out.close() # if successful, register it if retncode is No...
path = list (path)
path = list (package)
def get_package_dir (self, package): """Return the directory, relative to the top of the source distribution, where package 'package' should be found (at least according to the 'package_dir' option, if any)."""
return apply (os.path.join, path)
if path: return apply (os.path.join, path) else: return ''
def get_package_dir (self, package): """Return the directory, relative to the top of the source distribution, where package 'package' should be found (at least according to the 'package_dir' option, if any)."""
return apply (os.path.join, tail)
if tail: return apply (os.path.join, tail) else: return ''
def get_package_dir (self, package): """Return the directory, relative to the top of the source distribution, where package 'package' should be found (at least according to the 'package_dir' option, if any)."""
if package != "":
if package:
def check_package (self, package, package_dir):
outfile_path = package
outfile_path = list (package)
def build_module (self, module, module_file, package):
imclass = object.im_class
def docroutine(self, object, name=None, mod=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" realname = object.__name__ name = name or realname anchor = (cl and cl.__name__ or '') + '-' + name note = '' skipdocs = 0 if inspect.ismethod(object): if cl: i...
note = (object.im_self and ' method of %s instance' + object.im_self.__class__ or ' unbound %s method' % object.im_class.__name__)
inst = object.im_self note = (inst and ' method of %s instance' % classname(inst.__class__, mod) or ' unbound %s method' % classname(imclass, mod))
def docroutine(self, object, name=None, mod=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" realname = object.__name__ name = name or realname anchor = (cl and cl.__name__ or '') + '-' + name note = '' skipdocs = 0 if inspect.ismethod(object): if cl: i...
note = (object.im_self and ' method of %s instance' + object.im_self.__class__ or ' unbound %s method' % classname(imclass, mod))
inst = object.im_self note = (inst and ' method of %s instance' % classname(inst.__class__, mod) or ' unbound %s method' % classname(imclass, mod))
def docroutine(self, object, name=None, mod=None, cl=None): """Produce text documentation for a function or method object.""" realname = object.__name__ name = name or realname note = '' skipdocs = 0 if inspect.ismethod(object): imclass = object.im_class if cl: if imclass is not cl: note = ' from ' + classname(imclass,...
args=(key, self.update, self.done)).start()
args=(self.update, key, self.done)).start()
def search(self, event=None): key = self.search_ent.get() self.stop_btn.pack(side='right') self.stop_btn.config(state='normal') self.search_lbl.config(text='Searching for "%s"...' % key) self.search_ent.forget() self.search_lbl.pack(side='left') self.result_lst.delete(0, 'end') self.goto_btn.config(state='disabled') se...
- excample: the Example object that failed
- example: the Example object that failed
def output_difference(self, example, got, optionflags): """ Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`. """ want = example.want # If <BLANKLINE>s are bein...
def QueueTaskDoneTest(q)
def QueueTaskDoneTest(q):
def QueueTaskDoneTest(q) try: q.task_done() except ValueError: pass else: raise TestFailed("Did not detect task count going negative")
while url[-1] in ');:,.?\'"':
while url[-1] in '();:,.?\'"<>':
def translate(text, pre=0): global translate_prog if not translate_prog: url = '\(http\|ftp\|https\)://[^ \t\r\n]*' email = '\<[-a-zA-Z0-9._]+@[-a-zA-Z0-9._]+' translate_prog = prog = regex.compile(url + '\|' + email) else: prog = translate_prog i = 0 list = [] while 1: j = prog.search(text, i) if j < 0: break list.app...
i = i + len(url)
def translate(text, pre=0): global translate_prog if not translate_prog: url = '\(http\|ftp\|https\)://[^ \t\r\n]*' email = '\<[-a-zA-Z0-9._]+@[-a-zA-Z0-9._]+' translate_prog = prog = regex.compile(url + '\|' + email) else: prog = translate_prog i = 0 list = [] while 1: j = prog.search(text, i) if j < 0: break list.app...
test('isupper', u'\u1FFc', 0)
if sys.platform[:4] != 'java': test('isupper', u'\u1FFc', 0)
def test_fixup(s): s2 = u'\ud800\udc01' test_lecmp(s, s2) s2 = u'\ud900\udc01' test_lecmp(s, s2) s2 = u'\uda00\udc01' test_lecmp(s, s2) s2 = u'\udb00\udc01' test_lecmp(s, s2) s2 = u'\ud800\udd01' test_lecmp(s, s2) s2 = u'\ud900\udd01' test_lecmp(s, s2) s2 = u'\uda00\udd01' test_lecmp(s, s2) s2 = u'\udb00\udd01' test_le...
value = u"%r, %r" % (u"abc", "abc") if value != u"u'abc', 'abc'": print '*** formatting failed for "%s"' % 'u"%r, %r" % (u"abc", "abc")'
if sys.platform[:4] != 'java': value = u"%r, %r" % (u"abc", "abc") if value != u"u'abc', 'abc'": print '*** formatting failed for "%s"' % 'u"%r, %r" % (u"abc", "abc")'
def test_fixup(s): s2 = u'\ud800\udc01' test_lecmp(s, s2) s2 = u'\ud900\udc01' test_lecmp(s, s2) s2 = u'\uda00\udc01' test_lecmp(s, s2) s2 = u'\udb00\udc01' test_lecmp(s, s2) s2 = u'\ud800\udd01' test_lecmp(s, s2) s2 = u'\ud900\udd01' test_lecmp(s, s2) s2 = u'\uda00\udd01' test_lecmp(s, s2) s2 = u'\udb00\udd01' test_le...
value = u"%(x)s, %()s" % {'x':u"abc", u''.encode('utf-8'):"def"}
if sys.platform[:4] != 'java': value = u"%(x)s, %()s" % {'x':u"abc", u''.encode('utf-8'):"def"} else: value = u"%(x)s, %()s" % {'x':u"abc", u'':"def"}
def test_fixup(s): s2 = u'\ud800\udc01' test_lecmp(s, s2) s2 = u'\ud900\udc01' test_lecmp(s, s2) s2 = u'\uda00\udc01' test_lecmp(s, s2) s2 = u'\udb00\udc01' test_lecmp(s, s2) s2 = u'\ud800\udd01' test_lecmp(s, s2) s2 = u'\ud900\udd01' test_lecmp(s, s2) s2 = u'\uda00\udd01' test_lecmp(s, s2) s2 = u'\udb00\udd01' test_le...
self.assert_(reuse == 0, "Error performing getsockopt.")
self.failIf(reuse != 0, "initial mode is reuse")
def testGetSockOpt(self): """Testing getsockopt().""" # We know a socket should start without reuse==0 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) self.assert_(reuse == 0, "Error performing getsockopt.")
self.assert_(reuse == 1, "Error performing setsockopt.")
self.failIf(reuse == 0, "failed to set reuse mode")
def testSetSockOpt(self): """Testing setsockopt().""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) self.assert_(reuse == 1, "Error performing setsockopt.")
timeout = int(timeout*1000)
if timeout is not None: timeout = int(timeout*1000)
def poll2 (timeout=0.0, map=None): import poll if map is None: map=socket_map # timeout is in milliseconds timeout = int(timeout*1000) if map: l = [] for fd, obj in map.items(): flags = 0 if obj.readable(): flags = poll.POLLIN if obj.writable(): flags = flags | poll.POLLOUT if flags: l.append ((fd, flags)) r = poll.pol...
timeout = int(timeout*1000)
if timeout is not None: timeout = int(timeout*1000)
def poll3 (timeout=0.0, map=None): # Use the poll() support added to the select module in Python 2.0 if map is None: map=socket_map # timeout is in milliseconds timeout = int(timeout*1000) pollster = select.poll() if map: for fd, obj in map.items(): flags = 0 if obj.readable(): flags = select.POLLIN if obj.writable(): ...
... t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ") ... ... for x in t:
>>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ") >>> >>> for x in t:
>>> def inorder(t):
test_support.run_unittest(UTF16Test)
suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(UTF16Test)) suite.addTest(unittest.makeSuite(EscapeDecodeTest)) test_support.run_suite(suite)
def test_main(): test_support.run_unittest(UTF16Test)
if len(error_302_dict)>10 or req.error_302_dict.has_key(newurl):
if len(req.error_302_dict)>10 or \ req.error_302_dict.has_key(newurl):
def http_error_302(self, req, fp, code, msg, headers): if headers.has_key('location'): newurl = headers['location'] elif headers.has_key('uri'): newurl = headers['uri'] else: return nil = fp.read() fp.close()
completions.
completions. (For class instances, class members are are also considered.)
def attr_matches(self, text): """Compute matches when text contains a dot.
words = dir(eval(expr, __main__.__dict__))
object = eval(expr, __main__.__dict__) words = dir(object) if hasattr(object,'__class__'): words.append('__class__') words = words + get_class_members(object.__class__)
def attr_matches(self, text): """Compute matches when text contains a dot.
child = TreeNode(self.canvas, self, item)
child = self.__class__(self.canvas, self, item)
def draw(self, x, y): # XXX This hard-codes too many geometry constants! self.x, self.y = x, y self.drawicon() self.drawtext() if self.state != 'expanded': return y+17 # draw children if not self.children: sublist = self.item._GetSubList() if not sublist: # _IsExpandable() was mistaken; that's allowed return y+17 for i...
element = _encode(element)
def beginElement(self, element): self.stack.append(element) element = _encode(element) self.writeln("<%s>" % element) self.indentLevel += 1
element = _encode(element)
def simpleElement(self, element, value=None): if value: element = _encode(element) value = _encode(value) self.writeln("<%s>%s</%s>" % (element, value, element)) else: self.writeln("<%s/>" % element)
Foo="Doodah", aList=["A", "B", 12, 32.1, [1, 2, 3]], aFloat = 0.1, anInt = 728, aDict=Dict( aString="<hello & hi there!>", SomeUnicodeValue=u'M\xe4ssig, Ma\xdf', someTrueValue=True, someFalseValue=False, ), someData = Data("hello there!"), someMoreData = Data("hello there! " * 10), aDate = Date(time.mktime(time.gmtime(...
aString="Doodah", aList=["A", "B", 12, 32.1, [1, 2, 3]], aFloat = 0.1, anInt = 728, aDict=Dict( anotherString="<hello & hi there!>", aUnicodeValue=u'M\xe4ssig, Ma\xdf', aTrueValue=True, aFalseValue=False, ), someData = Data("<binary gunk>"), someMoreData = Data("<lots of binary gunk>" * 10), aDate = Date(time.mktime(ti...
def __repr__(self): if self: return "True" else: return "False"
self.library_dirs.append(os.path.join(sys.exec_prefix, 'PC', 'VC6'))
self.library_dirs.append(os.path.join(sys.exec_prefix, 'PCBuild'))
def finalize_options (self): from distutils import sysconfig
skip_msg = "byte-compilation of %s skipped" % f
skip_msg = "skipping byte-compilation of %s" % f
def run (self):
def __init__(self, display=1, logdir=None, context=5, file=None):
def __init__(self, display=1, logdir=None, context=5, file=None, format="html"):
def __init__(self, display=1, logdir=None, context=5, file=None): self.display = display # send tracebacks to browser if true self.logdir = logdir # log tracebacks to files if not None self.context = context # number of source code lines per frame self.file = file or sys.stdout # place to ...
self.file.write(reset())
if self.format == "html": self.file.write(reset()) formatter = (self.format=="html") and html or text plain = False
def handle(self, info=None): info = info or sys.exc_info() self.file.write(reset())
text, doc = 0, html(info, self.context)
doc = formatter(info, self.context)
def handle(self, info=None): info = info or sys.exc_info() self.file.write(reset())
text, doc = 1, ''.join(traceback.format_exception(*info))
doc = ''.join(traceback.format_exception(*info)) plain = True
def handle(self, info=None): info = info or sys.exc_info() self.file.write(reset())
if text:
if plain:
def handle(self, info=None): info = info or sys.exc_info() self.file.write(reset())
(fd, path) = tempfile.mkstemp(suffix=['.html', '.txt'][text], dir=self.logdir)
suffix = ['.html', '.txt'][self.format=="html"] (fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir)
def handle(self, info=None): info = info or sys.exc_info() self.file.write(reset())
from UserDict import DictMixin class SeqDict(DictMixin):
class SeqDict(UserDict.DictMixin):
def display(self): print self