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(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) ## set the extra Uiso for each atom for tls_group in tls_group_list: ## minimal/maximal amount of Uiso which has to be added ## to the group's atoms to to make Uiso == Uiso_tls min_Uiso = 0.0 max_Uiso = 0.0 n = 0 sum_diff2 = 0.0 for atm, Utls in tls_group.iter_atm_Utls(): for aatm in atm.iter_alt_loc(): tls_tf = trace(Utls)/3.0 ref_tf = trace(aatm.get_U())/3.0 n += 1 sum_diff2 += (tls_tf - ref_tf)**2 if ref_tf>tls_tf: max_Uiso = max(ref_tf - tls_tf, max_Uiso) else: min_Uiso = max(tls_tf - ref_tf, min_Uiso) msd = sum_diff2 / n rmsd = math.sqrt(msd) ## report the percentage of atoms with Uiso within the RMSD ntotal = 0 nrmsd = 0 for atm, Utls in tls_group.iter_atm_Utls(): for aatm in atm.iter_alt_loc(): tls_tf = trace(Utls)/3.0 ref_tf = trace(aatm.get_U())/3.0 ntotal += 1 deviation = math.sqrt((tls_tf - ref_tf)**2) if deviation<=rmsd: nrmsd += 1 ## reduce the TLS group T tensor by min_Uiso so that ## a PDB file can be written out where all atoms ## Uiso == Uiso_tls ## we must rotate the T tensor to its primary axes before ## subtracting min_Uiso magnitude from it (T_eval, TR) = eigenvectors(tls_group.T) T = matrixmultiply(TR, matrixmultiply(tls_group.T, transpose(TR))) assert allclose(T[0,1], 0.0) assert allclose(T[0,2], 0.0) assert allclose(T[1,2], 0.0) T[0,0] = T[0,0] - min_Uiso T[1,1] = T[1,1] - min_Uiso T[2,2] = T[2,2] - min_Uiso ## now take half of the smallest principal component of T and ## move it into the individual atomic temperature factors min_T = min(T[0,0], min(T[1,1], T[2,2])) sub_T = min_T * 0.80 add_Uiso = min_T - sub_T T[0,0] = T[0,0] - sub_T T[1,1] = T[1,1] - sub_T T[2,2] = T[2,2] - sub_T ## rotate T back to original orientation tls_group.T = matrixmultiply(transpose(TR), matrixmultiply(T, TR)) ## reset the TLS tensor values in the TLSDesc object so they can be ## saved tls_group.tls_desc.set_tls_group(tls_group) ## set atm.temp_factor for atm, Utls in tls_group.iter_atm_Utls(): for aatm in atm.iter_alt_loc(): tls_tf = trace(Utls)/3.0 ref_tf = trace(aatm.get_U())/3.0 if ref_tf>tls_tf: aatm.temp_factor = ((add_Uiso) + ref_tf - tls_tf)*U2B aatm.U = None else: aatm.temp_factor = (add_Uiso) * U2B aatm.U = None SaveStructure(fil=xyzout, struct=struct) tls_file.save(open(tlsout, "w")) |
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(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) ## set the extra Uiso for each atom for tls_group in tls_group_list: ## minimal/maximal amount of Uiso which has to be added ## to the group's atoms to to make Uiso == Uiso_tls min_Uiso = 0.0 max_Uiso = 0.0 n = 0 sum_diff2 = 0.0 for atm, Utls in tls_group.iter_atm_Utls(): for aatm in atm.iter_alt_loc(): tls_tf = trace(Utls)/3.0 ref_tf = trace(aatm.get_U())/3.0 n += 1 sum_diff2 += (tls_tf - ref_tf)**2 if ref_tf>tls_tf: max_Uiso = max(ref_tf - tls_tf, max_Uiso) else: min_Uiso = max(tls_tf - ref_tf, min_Uiso) msd = sum_diff2 / n rmsd = math.sqrt(msd) ## report the percentage of atoms with Uiso within the RMSD ntotal = 0 nrmsd = 0 for atm, Utls in tls_group.iter_atm_Utls(): for aatm in atm.iter_alt_loc(): tls_tf = trace(Utls)/3.0 ref_tf = trace(aatm.get_U())/3.0 ntotal += 1 deviation = math.sqrt((tls_tf - ref_tf)**2) if deviation<=rmsd: nrmsd += 1 ## reduce the TLS group T tensor by min_Uiso so that ## a PDB file can be written out where all atoms ## Uiso == Uiso_tls ## we must rotate the T tensor to its primary axes before ## subtracting min_Uiso magnitude from it (T_eval, TR) = eigenvectors(tls_group.T) T = matrixmultiply(TR, matrixmultiply(tls_group.T, transpose(TR))) assert allclose(T[0,1], 0.0) assert allclose(T[0,2], 0.0) assert allclose(T[1,2], 0.0) T[0,0] = T[0,0] - min_Uiso T[1,1] = T[1,1] - min_Uiso T[2,2] = T[2,2] - min_Uiso ## now take half of the smallest principal component of T and ## move it into the individual atomic temperature factors min_T = min(T[0,0], min(T[1,1], T[2,2])) sub_T = min_T * 0.80 add_Uiso = min_T - sub_T T[0,0] = T[0,0] - sub_T T[1,1] = T[1,1] - sub_T T[2,2] = T[2,2] - sub_T ## rotate T back to original orientation tls_group.T = matrixmultiply(transpose(TR), matrixmultiply(T, TR)) ## reset the TLS tensor values in the TLSDesc object so they can be ## saved tls_group.tls_desc.set_tls_group(tls_group) ## set atm.temp_factor for atm, Utls in tls_group.iter_atm_Utls(): for aatm in atm.iter_alt_loc(): tls_tf = trace(Utls)/3.0 ref_tf = trace(aatm.get_U())/3.0 if ref_tf>tls_tf: aatm.temp_factor = ((add_Uiso) + ref_tf - tls_tf)*U2B aatm.U = None else: aatm.temp_factor = (add_Uiso) * U2B aatm.U = None SaveStructure(fil=xyzout, struct=struct) tls_file.save(open(tlsout, "w")) |
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["charge"] = arec1["charge"] |
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["charge"] = arec1["charge"] |
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["charge"] = arec1["charge"] |
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_desc["ntls"] = ntls tls_seg_desc["tlsopt"] = tlsopt ## update the master fragment_list self.__update_frag_list(chainopt["chain"], tlsopt) |
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 occupancy" % (atm)) return False if numpy.trace(atm.get_U()) <= const.TSMALL: if reject_messages == True: console.stdoutln("calc_include_atom(%s): rejected because of small Uiso magnitude " % (atm)) return False elif conf.globalconf.include_atoms == "MAINCHAIN": if const.MAINCHAIN_ATOM_DICT.has_key(atom.name) is False: if reject_messages == True: console.stdoutln("calc_include_atom(%s): rejected non-mainchain atom" % (atm)) return False return True |
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 the A matrix and b vector can be sliced ## in the correct placees |
|
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 NMR ## style MODEL; this is first on the list for the ## next version if atm_map.has_key("model_num") and atm_map["model_num"] > 1: debug("NMR-style multi-models not supported yet") return ## /XXX |
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 NMR ## style MODEL; this is first on the list for the ## next version if atm_map.has_key("model_num") and atm_map["model_num"] > 1: debug("NMR-style multi-models not supported yet") return ## /XXX |
|
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 NMR ## style MODEL; this is first on the list for the ## next version if atm_map.has_key("model_num") and atm_map["model_num"] > 1: debug("NMR-style multi-models not supported yet") return ## /XXX |
|
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 NMR ## style MODEL; this is first on the list for the ## next version if atm_map.has_key("model_num") and atm_map["model_num"] > 1: debug("NMR-style multi-models not supported yet") return ## /XXX |
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(): assert isinstance(atm, Atom) assert atm in atom assert atm not in visited_atm_list visited_atm_list.append(atm) assert atm[atom.alt_loc] == atom assert atm.get_fragment() == atom.get_fragment() assert atm.get_chain() == atom.get_chain() assert atm.get_structure() == atom.get_structure() assert atm.name == atom.name assert atm.res_name == atom.res_name assert atm.fragment_id == atom.fragment_id assert atm.chain_id == atom.chain_id atom.calc_anisotropy() atom.calc_anisotropy3() |
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_format(TLS.TLSFileFormatTLSOUT()) tls_file_format = TLS.TLSFileFormatTLSOUT() for tlsin in tlsin_list: tls_desc_list = tls_file_format.load(open(tlsin, "r")) for tls_desc in tls_desc_list: tls_file.tls_desc_list.append(tls_desc) tls_group = tls_desc.construct_tls_group_with_atoms(struct) tls_group.tls_desc = tls_desc tls_group_list.append(tls_group) ## set the extra Uiso for each atom for tls_group in tls_group_list: ## minimal/maximal amount of Uiso which has to be added ## to the group's atoms to to make Uiso == Uiso_tls min_Uiso = 0.0 max_Uiso = 0.0 n = 0 sum_diff2 = 0.0 for atm, Utls in tls_group.iter_atm_Utls(): for aatm in atm.iter_alt_loc(): tls_tf = numpy.trace(Utls)/3.0 ref_tf = numpy.trace(aatm.get_U())/3.0 n += 1 sum_diff2 += (tls_tf - ref_tf)**2 if ref_tf>tls_tf: max_Uiso = max(ref_tf - tls_tf, max_Uiso) else: min_Uiso = max(tls_tf - ref_tf, min_Uiso) msd = sum_diff2 / n rmsd = math.sqrt(msd) ## report the percentage of atoms with Uiso within the RMSD ntotal = 0 nrmsd = 0 for atm, Utls in tls_group.iter_atm_Utls(): for aatm in atm.iter_alt_loc(): tls_tf = numpy.trace(Utls)/3.0 ref_tf = numpy.trace(aatm.get_U())/3.0 ntotal += 1 deviation = math.sqrt((tls_tf - ref_tf)**2) if deviation <= rmsd: nrmsd += 1 ## reduce the TLS group T tensor by min_Uiso so that ## a PDB file can be written out where all atoms ## Uiso == Uiso_tls ## we must rotate the T tensor to its primary axes before ## subtracting min_Uiso magnitude from it (T_eval, TR) = numpy.linalg.eigenvectors(tls_group.T) T = numpy.matrixmultiply(TR, numpy.matrixmultiply(tls_group.T, numpy.transpose(TR))) assert numpy.allclose(T[0,1], 0.0) assert numpy.allclose(T[0,2], 0.0) assert numpy.allclose(T[1,2], 0.0) T[0,0] = T[0,0] - min_Uiso T[1,1] = T[1,1] - min_Uiso T[2,2] = T[2,2] - min_Uiso ## now take half of the smallest principal component of T and ## move it into the individual atomic temperature factors min_T = min(T[0,0], min(T[1,1], T[2,2])) sub_T = min_T * 0.80 add_Uiso = min_T - sub_T T[0,0] = T[0,0] - sub_T T[1,1] = T[1,1] - sub_T T[2,2] = T[2,2] - sub_T ## rotate T back to original orientation tls_group.T = numpy.matrixmultiply(numpy.transpose(TR), numpy.matrixmultiply(T, TR)) ## reset the TLS tensor values in the TLSDesc object so they can be saved tls_group.tls_desc.set_tls_group(tls_group) ## set atm.temp_factor for atm, Utls in tls_group.iter_atm_Utls(): for aatm in atm.iter_alt_loc(): tls_tf = numpy.trace(Utls)/3.0 ref_tf = numpy.trace(aatm.get_U())/3.0 if ref_tf>tls_tf: aatm.temp_factor = ((add_Uiso) + ref_tf - tls_tf)*U2B aatm.U = None else: aatm.temp_factor = (add_Uiso) * U2B aatm.U = None FileLoader.SaveStructure(fil=xyzout, struct=struct) tls_file.save(open(tlsout, "w")) |
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_format(TLS.TLSFileFormatTLSOUT()) tls_file_format = TLS.TLSFileFormatTLSOUT() for tlsin in tlsin_list: tls_desc_list = tls_file_format.load(open(tlsin, "r")) for tls_desc in tls_desc_list: tls_file.tls_desc_list.append(tls_desc) tls_group = tls_desc.construct_tls_group_with_atoms(struct) tls_group.tls_desc = tls_desc tls_group_list.append(tls_group) ## set the extra Uiso for each atom for tls_group in tls_group_list: ## minimal/maximal amount of Uiso which has to be added ## to the group's atoms to to make Uiso == Uiso_tls min_Uiso = 0.0 max_Uiso = 0.0 n = 0 sum_diff2 = 0.0 for atm, Utls in tls_group.iter_atm_Utls(): for aatm in atm.iter_alt_loc(): tls_tf = numpy.trace(Utls)/3.0 ref_tf = numpy.trace(aatm.get_U())/3.0 n += 1 sum_diff2 += (tls_tf - ref_tf)**2 if ref_tf>tls_tf: max_Uiso = max(ref_tf - tls_tf, max_Uiso) else: min_Uiso = max(tls_tf - ref_tf, min_Uiso) msd = sum_diff2 / n rmsd = math.sqrt(msd) ## report the percentage of atoms with Uiso within the RMSD ntotal = 0 nrmsd = 0 for atm, Utls in tls_group.iter_atm_Utls(): for aatm in atm.iter_alt_loc(): tls_tf = numpy.trace(Utls)/3.0 ref_tf = numpy.trace(aatm.get_U())/3.0 ntotal += 1 deviation = math.sqrt((tls_tf - ref_tf)**2) if deviation <= rmsd: nrmsd += 1 ## reduce the TLS group T tensor by min_Uiso so that ## a PDB file can be written out where all atoms ## Uiso == Uiso_tls ## we must rotate the T tensor to its primary axes before ## subtracting min_Uiso magnitude from it (T_eval, TR) = numpy.linalg.eigenvectors(tls_group.T) T = numpy.matrixmultiply(TR, numpy.matrixmultiply(tls_group.T, numpy.transpose(TR))) assert numpy.allclose(T[0,1], 0.0) assert numpy.allclose(T[0,2], 0.0) assert numpy.allclose(T[1,2], 0.0) T[0,0] = T[0,0] - min_Uiso T[1,1] = T[1,1] - min_Uiso T[2,2] = T[2,2] - min_Uiso ## now take half of the smallest principal component of T and ## move it into the individual atomic temperature factors min_T = min(T[0,0], min(T[1,1], T[2,2])) sub_T = min_T * 0.80 add_Uiso = min_T - sub_T T[0,0] = T[0,0] - sub_T T[1,1] = T[1,1] - sub_T T[2,2] = T[2,2] - sub_T ## rotate T back to original orientation tls_group.T = numpy.matrixmultiply(numpy.transpose(TR), numpy.matrixmultiply(T, TR)) ## reset the TLS tensor values in the TLSDesc object so they can be saved tls_group.tls_desc.set_tls_group(tls_group) ## set atm.temp_factor for atm, Utls in tls_group.iter_atm_Utls(): for aatm in atm.iter_alt_loc(): tls_tf = numpy.trace(Utls)/3.0 ref_tf = numpy.trace(aatm.get_U())/3.0 if ref_tf>tls_tf: aatm.temp_factor = ((add_Uiso) + ref_tf - tls_tf)*U2B aatm.U = None else: aatm.temp_factor = (add_Uiso) * U2B aatm.U = None FileLoader.SaveStructure(fil=xyzout, struct=struct) tls_file.save(open(tlsout, "w")) |
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 there are arguments, and the first argument is not '-', the first argument is run as a script. Remaining arguments are arguments to the script or to the command run by -c. | 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 as a script in a shell -s run $IDLESTARTUP or $PYTHONSTARTUP before anything else -t title set title of shell window Remaining arguments are applied to the command (-c) or script (-r). | 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 == '-e': edit = 1 if o == '-s': startup = 1 if o == '-t': PyShell.shell_title = a if noshell: edit=1 for i in range(len(sys.path)): sys.path[i] = os.path.abspath(sys.path[i]) pathx = [] if edit: for filename in args: pathx.append(os.path.dirname(filename)) elif args and args[0] != "-": pathx.append(os.path.dirname(args[0])) else: pathx.append(os.curdir) for dir in pathx: dir = os.path.abspath(dir) if not dir in sys.path: sys.path.insert(0, dir) |
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 == '-e': edit = 1 if o == '-s': startup = 1 if o == '-t': PyShell.shell_title = a if noshell: edit=1 for i in range(len(sys.path)): sys.path[i] = os.path.abspath(sys.path[i]) pathx = [] if edit: for filename in args: pathx.append(os.path.dirname(filename)) elif args and args[0] != "-": pathx.append(os.path.dirname(args[0])) else: pathx.append(os.curdir) for dir in pathx: dir = os.path.abspath(dir) if not dir in sys.path: sys.path.insert(0, dir) |
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 == '-e': edit = 1 if o == '-s': startup = 1 if o == '-t': PyShell.shell_title = a if noshell: edit=1 for i in range(len(sys.path)): sys.path[i] = os.path.abspath(sys.path[i]) pathx = [] if edit: for filename in args: pathx.append(os.path.dirname(filename)) elif args and args[0] != "-": pathx.append(os.path.dirname(args[0])) else: pathx.append(os.curdir) for dir in pathx: dir = os.path.abspath(dir) if not dir in sys.path: sys.path.insert(0, dir) |
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 & mask, mask) self.assertRaises(OverflowError, func, 1L<<34) | 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: maxlinelen = self._firstlinelen firstline = 0 else: line = line.lstrip() maxlinelen = self._maxlinelen # Short lines can remain unchanged if len(line.replace('\t', SPACE8)) <= maxlinelen: rtn.append(line) else: oldlen = len(line) # Try to break the line on semicolons, but if that doesn't # work, try to split on folding whitespace. while len(line) > maxlinelen: i = line.rfind(';', 0, maxlinelen) if i < 0: break rtn.append(line[:i] + ';') line = line[i+1:] # Is the remaining stuff still longer than maxlinelen? if len(line) <= maxlinelen: # Splitting on semis worked rtn.append(line) continue # Splitting on semis didn't finish the job. If it did any # work at all, stick the remaining junk on the front of the # `lines' sequence and let the next pass do its thing. if len(line) <> oldlen: lines.insert(0, line) continue # Otherwise, splitting on semis didn't help at all. parts = re.split(r'(\s+)', line) if len(parts) == 1 or (len(parts) == 3 and parts[0].endswith(':')): # This line can't be split on whitespace. There's now # little we can do to get this into maxlinelen. BAW: # We're still potentially breaking the RFC by possibly # allowing lines longer than the absolute maximum of 998 # characters. For now, let it slide. # # len(parts) will be 1 if this line has no `Field: ' # prefix, otherwise it will be len(3). rtn.append(line) continue # There is whitespace we can split on. first = parts.pop(0) sublines = [first] acc = len(first) while parts: len0 = len(parts[0]) len1 = len(parts[1]) if acc + len0 + len1 <= maxlinelen: sublines.append(parts.pop(0)) sublines.append(parts.pop(0)) acc += len0 + len1 else: # Split it here, but don't forget to ignore the # next whitespace-only part if first <> '': rtn.append(EMPTYSTRING.join(sublines)) del parts[0] first = parts.pop(0) sublines = [first] acc = len(first) rtn.append(EMPTYSTRING.join(sublines)) return [(chunk, charset) for chunk in rtn] |
|
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. # however, changing this may break older code (including # old versions of xmlrpclib.py), so this is better left as # is for now. See @XMLRPC3 for more information. /F write("<params>\n") for v in values: write("<param>\n") dump(v, write) write("</param>\n") write("</params>\n") result = string.join(out, "") return result |
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. ('body' probably isn't of much use, but what the heck.) """ from distutils.ccompiler import CompileError self._check_compiler() ok = 1 try: self._preprocess(body, headers, lang) except CompileError: ok = 0 |
(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 both 'body' and 'headers' are None, preprocesses an empty file -- which can be useful to determine the symbols the preprocessor and compiler set by default. """ |
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 both 'body' and 'headers' are None, preprocesses an empty file -- which can be useful to determine the symbols the preprocessor and compiler set by default. """ |
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: ok = 0 |
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" % (run, run != 1 and "s" or "", timeTaken)) self.stream.writeln() if not result.wasSuccessful(): self.stream.write("FAILED (") failed, errored = map(len, (result.failures, result.errors)) if failed: self.stream.write("failures=%d" % failed) if errored: if failed: self.stream.write(", ") self.stream.write("errors=%d" % errored) self.stream.writeln(")") else: self.stream.writeln("OK") return result |
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 uses a cache for past comparisons and the results, with a cache invalidation mechanism relying on stale signatures. """ s1 = _sig(os.stat(f1)) s2 = _sig(os.stat(f2)) if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG: return False if shallow and s1 == s2: return True if s1[1] != s2[1]: return False result = _cache.get((f1, f2)) if result and (s1, s2) == result[:2]: return result[2] outcome = _do_cmp(f1, f2) _cache[f1, f2] = s1, s2, outcome return outcome |
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: files that compare equal files that are different filenames that aren't regular files. """ res = ([], [], []) for x in common: ax = os.path.join(a, x) bx = os.path.join(b, x) res[_cmp(ax, bx, shallow)].append(x) return res |
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: subdir = 'new' suffix = '' uniq = os.path.basename(tmp_file.name).split(self.colon)[0] dest = os.path.join(self._path, subdir, uniq + suffix) os.rename(tmp_file.name, dest) if isinstance(message, MaildirMessage): os.utime(dest, (os.path.getatime(dest), message.get_date())) return uniq |
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_start = new_file.tell() while True: buffer = self._file.read(min(4096, stop - self._file.tell())) if buffer == '': break new_file.write(buffer) new_toc[key] = (new_start, new_file.tell()) self._post_message_hook(new_file) except: new_file.close() os.remove(new_file.name) raise new_file.close() self._file.close() try: os.rename(new_file.name, self._path) except OSError, e: if e.errno == errno.EEXIST or \ (os.name == 'os2' and e.errno == errno.EACCES): os.remove(self._path) os.rename(new_file.name, self._path) else: raise self._file = open(self._path, 'rb+') self._toc = new_toc self._pending = False if self._locked: _lock_file(self._file, dotlock=False) |
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(message, MHMessage): self._dump_sequences(message, new_key) finally: if self._locked: _unlock_file(f) finally: f.close() return new_key |
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) try: os.close(os.open(path, os.O_WRONLY | os.O_TRUNC)) self._dump_message(message, f) if isinstance(message, MHMessage): self._dump_sequences(message, key) finally: if self._locked: _unlock_file(f) finally: f.close() |
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 completing = False for key in sorted(set(keys)): if key - 1 == prev: if not completing: completing = True f.write('-') elif completing: completing = False f.write('%s %s' % (prev, key)) else: f.write(' %s' % key) prev = key if completing: f.write(str(prev) + '\n') else: f.write('\n') finally: f.close() |
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__, ' '.join (status), id (self)) except: pass |
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__, ' '.join (status), id (self)) except: pass |
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 None and commd: register("gnome", None, BackgroundBrowser(commd)) # First, the Mozilla/Netscape browsers for browser in ("mozilla-firefox", "firefox", "mozilla-firebird", "firebird", "seamonkey", "mozilla", "netscape"): if _iscommand(browser): register(browser, None, Mozilla(browser)) # Konqueror/kfm, the KDE browser. if _iscommand("kfm"): register("kfm", Konqueror, Konqueror("kfm")) elif _iscommand("konqueror"): register("konqueror", Konqueror, Konqueror("konqueror")) # Gnome's Galeon and Epiphany for browser in ("galeon", "epiphany"): if _iscommand(browser): register(browser, None, Galeon(browser)) # Skipstone, another Gtk/Mozilla based browser if _iscommand("skipstone"): register("skipstone", None, BackgroundBrowser("skipstone")) # Opera, quite popular if _iscommand("opera"): register("opera", None, Opera("opera")) # Next, Mosaic -- old but still in use. if _iscommand("mosaic"): register("mosaic", None, BackgroundBrowser("mosaic")) # Grail, the Python browser. Does anybody still use it? if _iscommand("grail"): register("grail", Grail, None) |
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: imclass = object.im_class if imclass is not cl: url = '%s.html#%s-%s' % ( imclass.__module__, imclass.__name__, name) note = ' from <a href="%s">%s</a>' % ( url, classname(imclass, mod)) skipdocs = 1 else: note = (object.im_self and ' method of %s instance' + object.im_self.__class__ or ' unbound %s method' % object.im_class.__name__) object = object.im_func |
|
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: imclass = object.im_class if imclass is not cl: url = '%s.html#%s-%s' % ( imclass.__module__, imclass.__name__, name) note = ' from <a href="%s">%s</a>' % ( url, classname(imclass, mod)) skipdocs = 1 else: note = (object.im_self and ' method of %s instance' + object.im_self.__class__ or ' unbound %s method' % object.im_class.__name__) object = object.im_func |
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, mod) skipdocs = 1 else: note = (object.im_self and ' method of %s instance' + object.im_self.__class__ or ' unbound %s method' % classname(imclass, mod)) object = object.im_func |
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') self.expand() |
- 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 being used, then replace blank lines # with <BLANKLINE> in the actual output string. if not (optionflags & DONT_ACCEPT_BLANKLINE): got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got) |
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.append(escape(text[i:j])) i = j url = prog.group(0) while url[-1] in ');:,.?\'"': url = url[:-1] url = escape(url) if not pre or (pre and PROCESS_PREFORMAT): if ':' in url: repl = '<A HREF="%s">%s</A>' % (url, url) else: repl = '<A HREF="mailto:%s"><%s></A>' % (url, url) else: repl = url list.append(repl) i = i + len(url) j = len(text) list.append(escape(text[i:j])) return string.join(list, '') |
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.append(escape(text[i:j])) i = j url = prog.group(0) while url[-1] in ');:,.?\'"': url = url[:-1] url = escape(url) if not pre or (pre and PROCESS_PREFORMAT): if ':' in url: repl = '<A HREF="%s">%s</A>' % (url, url) else: repl = '<A HREF="mailto:%s"><%s></A>' % (url, url) else: repl = url list.append(repl) i = i + len(url) j = len(text) list.append(escape(text[i:j])) return string.join(list, '') |
|
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_lecmp(s, s2) s2 = u'\ud800\ude01' test_lecmp(s, s2) s2 = u'\ud900\ude01' test_lecmp(s, s2) s2 = u'\uda00\ude01' test_lecmp(s, s2) s2 = u'\udb00\ude01' test_lecmp(s, s2) s2 = u'\ud800\udfff' test_lecmp(s, s2) s2 = u'\ud900\udfff' test_lecmp(s, s2) s2 = u'\uda00\udfff' test_lecmp(s, s2) s2 = u'\udb00\udfff' test_lecmp(s, s2) |
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_lecmp(s, s2) s2 = u'\ud800\ude01' test_lecmp(s, s2) s2 = u'\ud900\ude01' test_lecmp(s, s2) s2 = u'\uda00\ude01' test_lecmp(s, s2) s2 = u'\udb00\ude01' test_lecmp(s, s2) s2 = u'\ud800\udfff' test_lecmp(s, s2) s2 = u'\ud900\udfff' test_lecmp(s, s2) s2 = u'\uda00\udfff' test_lecmp(s, s2) s2 = u'\udb00\udfff' test_lecmp(s, s2) |
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_lecmp(s, s2) s2 = u'\ud800\ude01' test_lecmp(s, s2) s2 = u'\ud900\ude01' test_lecmp(s, s2) s2 = u'\uda00\ude01' test_lecmp(s, s2) s2 = u'\udb00\ude01' test_lecmp(s, s2) s2 = u'\ud800\udfff' test_lecmp(s, s2) s2 = u'\ud900\udfff' test_lecmp(s, s2) s2 = u'\uda00\udfff' test_lecmp(s, s2) s2 = u'\udb00\udfff' test_lecmp(s, s2) |
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.poll (l, timeout) for fd, flags in r: try: obj = map[fd] try: if (flags & poll.POLLIN): obj.handle_read_event() if (flags & poll.POLLOUT): obj.handle_write_event() except ExitNow: raise ExitNow except: obj.handle_error() except KeyError: pass |
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(): flags = flags | select.POLLOUT if flags: pollster.register(fd, flags) r = pollster.poll (timeout) for fd, flags in r: try: obj = map[fd] try: if (flags & select.POLLIN): obj.handle_read_event() if (flags & select.POLLOUT): obj.handle_write_event() except ExitNow: raise ExitNow except: obj.handle_error() except KeyError: pass |
... 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 item in sublist: child = TreeNode(self.canvas, self, item) self.children.append(child) cx = x+20 cy = y+17 cylast = 0 for child in self.children: cylast = cy self.canvas.create_line(x+9, cy+7, cx, cy+7, fill="gray50") cy = child.draw(cx, cy) if child.item._IsExpandable(): if child.state == 'expanded': iconname = "minusnode" callback = child.collapse else: iconname = "plusnode" callback = child.expand image = self.geticonimage(iconname) id = self.canvas.create_image(x+9, cylast+7, image=image) # XXX This leaks bindings until canvas is deleted: self.canvas.tag_bind(id, "<1>", callback) self.canvas.tag_bind(id, "<Double-1>", lambda x: None) id = self.canvas.create_line(x+9, y+10, x+9, cylast+7, ##stipple="gray50", # XXX Seems broken in Tk 8.0.x fill="gray50") self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2 return cy |
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(time.gmtime())), | 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 send the output |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.