rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
initial_value = range(0, 10)
initial_value = range(0, 5)
def test_set_slice(self): initial_value = range(0, 10)
for i in xrange(-12, 12): for j in xrange(-12, 12): for k in xrange(-12, 12): self._list_op_test(initial_value, make_op_func(i, j, k, []), True) self._list_op_test(initial_value, make_op_func(i, j, k, range(0,2)), True) self._list_op_test(initial_value, make_op_func(i, j, k, range(0,4)), True) self._list_op_test(initia...
for i in [None] + range(-7, 7): for j in [None] + range(-7, 7): for k in [None] + range(-7, 7): self._list_op_test(initial_value, make_op_func(i, j, k, []), 'set_slice [%s:%s:%s]=[]' % (i,j,k)) self._list_op_test(initial_value, make_op_func(i, j, k, range(0,2)), 'set_slice [%s:%s:%s]=range(0,2)' % (i,j,k)) self._list_o...
def _f(xs): xs[i:j:k] = v
self._list_op_test(initial_value, make_op_func(i), True)
self._list_op_test(initial_value, make_op_func(i), 'del_integer [%d]' % (i,))
def _f(xs): del xs[index]
initial_value = range(0,10)
initial_value = range(0,5)
def test_del_slice(self): initial_value = range(0,10)
for i in xrange(-12, 12): for j in xrange(-12, 12): for k in xrange(-12, 12): self._list_op_test(initial_value, make_op_func(i, j, k), True)
for i in [None] + range(-7, 7): for j in [None] + range(-7, 7): for k in [None] + range(-7, 7): self._list_op_test(initial_value, make_op_func(i, j, k), 'del_slice [%s:%s:%s]' % (i,j,k))
def _f(xs): del xs[i:j:k]
return self._jffi_type.size
return self._jffi_type.size()
def size(self): return self._jffi_type.size
return type._jffi_type.size
return type._jffi_type.size()
def sizeof(type): if hasattr(type, '_jffi_type'): return type._jffi_type.size else: raise TypeError("this type has no size")
return type._jffi_type.alignment
return type._jffi_type.alignment()
def alignment(type): return type._jffi_type.alignment
output = ByteArrayOutputStream() serializer = ObjectOutputStream(output) serializer.writeObject(date_list) serializer.close() input = ByteArrayInputStream(output.toByteArray()) unserializer = ObjectInputStream(input) self.assertEqual(date_list, unserializer.readObject())
self.assertEqual(date_list, roundtrip_serialization(date_list)) def test_java_serialization_pycode(self): def universal_answer(): return 42 serialized_code = roundtrip_serialization(universal_answer.func_code) self.assertEqual(eval(serialized_code), universal_answer()) class CopyTest(unittest.TestCase): def test_...
def test_java_serialization(self): date_list = [Date(), Date()] output = ByteArrayOutputStream() serializer = ObjectOutputStream(output) serializer.writeObject(date_list) serializer.close()
self._cont_handler.characters(String(char, start, len).getBytes('utf-8').tostring().decode('utf-8'))
self._cont_handler.characters(unicode(String(char, start, len)))
def characters(self, char, start, len): self._cont_handler.characters(String(char, start, len).getBytes('utf-8').tostring().decode('utf-8'))
self._cont_handler.ignorableWhitespace(String(char, start, len).getBytes('utf-8').tostring().decode('utf-8'))
self._cont_handler.ignorableWhitespace(unicode(String(char, start, len)))
def ignorableWhitespace(self, char, start, len): self._cont_handler.ignorableWhitespace(String(char, start, len).getBytes('utf-8').tostring().decode('utf-8'))
from javatests import JOverload
def extract_ov_meths(jcl,envl_class): meths = java.lang.Class.getDeclaredMethods(jcl) names = [ m.name for m in meths] meth_dict = {} for name in names: if name.startswith('ov_') and not meth_dict.has_key(name): meth_dict[name] = envl_class(name,[ m for m in meths if m.name == name ]) return meth_dict
import sys
def printout(meth_dict,lbl,rng,args): for i in rng: print meth_dict['ov_%s%s' % (lbl,i)](jo,args)
test_support.run_unittest(OverloadedDispatchTests)
test_support.run_unittest(OverloadedDispatchTests, VarargsDispatchTests, ComplexOverloadingTests)
def printout(meth_dict,lbl,rng,args): for i in rng: print meth_dict['ov_%s%s' % (lbl,i)](jo,args)
if isinstance(source, str):
if isinstance(source, basestring):
def __init__(self, source): if isinstance(source, str): javasax.InputSource.__init__(self, source) elif hasattr(source, "read"):#file like object f = source javasax.InputSource.__init__(self, FilelikeInputStream(f)) if hasattr(f, "name"): self.setSystemId(f.name) else:#xml.sax.xmlreader.InputSource object #Use byte str...
test_support.run_unittest(ReferencesTestCase)
test_support.run_unittest(ReferencesTestCase, ArgsTestCase)
def test_main(): test_support.run_unittest(ReferencesTestCase)
"thread.LockType should exist"
def test_lock_type(self): "thread.LockType should exist" t = thread.LockType self.assertEquals(t, type(thread.allocate_lock()), "thread.LockType has wrong value")
print "Content handler is %s" % self._cont_handler.__class__
def comment(self, char, start, len): print "Content handler is %s" % self._cont_handler.__class__ self._cont_handler.comment(unicode(String(char, start, len)))
self._logger.warning('TCP/IP connection lost.')
self._logger.debug('TCP/IP connection lost.')
def on_disconnected(self): self._logger.warning('TCP/IP connection lost.')
self._log(logging.WARNING, 'Request to queue message during or after thread shutdown denied.')
self._log(logging.DEBUG, 'Request to queue message during or after thread shutdown denied.')
def send(self, destination=None, message='', headers=None, **keyword_headers): """Add message to local queue for sending to MSG server. @param destination: An MSG topic or queue, e.g. /topic/dashboard.test. @param message: A string or dictionary of key-value pairs. @param headers: A dictionary of headers. @param keywo...
self._log(logging.WARNING, 'Exception on disconnect.', exc_info=True)
self._log(logging.DEBUG, 'Exception on disconnect.', exc_info=True)
def _disconnect(self): """Disconnects (quietly) from MSG server if not already disconnected.""" cx = self._cx if cx is not None: self._log(logging.DEBUG, 'Disconnecting') self._cx = None if cx.is_connected(): try: cx.disconnect() except Exception: self._log(logging.WARNING, 'Exception on disconnect.', exc_info=True) se...
self._log(logging.WARNING, 'Exception on connect/send.', exc_info=True)
self._log(logging.DEBUG, 'Exception on connect/send.', exc_info=True)
def run(self): """Send messages, connecting as necessary and disconnecting after idle_timeout seconds. """ # indicates time in seconds since last connect/send attempt idle_time = 0 # indicates time in seconds before next connect/send attempt backoff_time = 0 # run unless should_stop and (queue empty or backing off) whi...
query = cursor.execute( self.querystring + " where tracks.filesize = " + size )
query = cursor.execute( self.querystring + " where tracks.filesize = " + str(size) )
def findSongBySize(self, size): cursor = self.db.cursor() query = cursor.execute( self.querystring + " where tracks.filesize = " + size ) results = cursor.fetchall() return self.rowsToSongs( results )
if match == None: self.ambiguousMatches = self.ambiguousMatches + 1
def correlateSong( self, song, confirm, fastAndLoose, promptForDisambiguate ): match = None matches = self.parser.findSongBySize( song.size ); matchcount = len(matches) # no results if matchcount == 0: print "\t no matches found" self.zeroMatches = self.zeroMatches + 1 # full match elif matchcount == 1: match = match...
foo = raw_input( 'press <enter> to continue')
foo = raw_input( 'press <enter> to continue, Ctrl-C to cancel')
def correlateSong( self, song, confirm, fastAndLoose, promptForDisambiguate ): match = None matches = self.parser.findSongBySize( song.size ); matchcount = len(matches) # no results if matchcount == 0: print "\t no matches found" self.zeroMatches = self.zeroMatches + 1 # full match elif matchcount == 1: match = match...
def __init__(self, location)
def __init__(self, location):
def __init__(self, location) self.doc = libxml2.parseFile( location ) self.xpathContext = doc.xpathNewContext() return
return getPlaylistFiles('Library')
return self.getPlaylistFiles('Library')
def getSongs(self): return getPlaylistFiles('Library')
self.rating = WMPSong.getItemInfo("UserRating")
try: self.rating = int(WMPSong.getItemInfo("UserRating")) except ValueError: print WMPSong.getItemInfo("UserRating") print "\t junk" self.rating = 0
def __init__(self, WMPSong): self.wmpNode = WMPSong self.artist = WMPSong.getItemInfo("WM/AlbumArtist") self.album = WMPSong.getItemInfo("WM/AlbumTitle") self.title = WMPSong.name self.size = WMPSong.getItemInfo("FileSize") self.rating = WMPSong.getItemInfo("UserRating") self.playcount = WMPSong.getItemInfo("UserPlayco...
print "iTunesToRhythm <path to ItunesMusicLibrary.xml> <path to rhythmdb.xml>
print "iTunesToRhythm <path to ItunesMusicLibrary.xml> <path to rhythmdb.xml>"
def showUsage(self): print "iTunesToRhythm <path to ItunesMusicLibrary.xml> <path to rhythmdb.xml>
newRatingKeyNode.setContent("rating")
newRatingKeyNode.setContent("Rating")
def setRating( self, rating): ratingValueNodes = self.xmlNode.xpathEval("integer[preceding-sibling::* = 'Rating'][1]") if len( ratingValueNodes ) == 0: newRatingKeyNode= libxml2.newNode("key") newRatingKeyNode.setContent("rating") ratingValueNode = libxml2.newNode("integer") newRatingKeyNode.addSibling( ratingValueNo...
self.wmpNode.setItemInfo("UserPlaycount", rating)
self.wmpNode.setItemInfo("UserPlaycount", playcount)
def setPlaycount(self, playcount): self.wmpNode.setItemInfo("UserPlaycount", rating)
return UploadedFLVFile(flvfile)
return UploadedFLVFile(mp4file)
def clean(self, data, initial=None): """Checks that the file is valid video and converts it to FLV format""" f = super(VideoUploadToFLVField, self).clean(data, initial) if f is None: return None elif not data and initial: return initial
flvfile = tmpname+".mp4"
mp4file = tmpname+".mp4"
def clean(self, data, initial=None): """Checks that the file is valid video and converts it to FLV format""" f = super(VideoUploadToFLVField, self).clean(data, initial) if f is None: return None elif not data and initial: return initial
if not os.path.exists(os.path.join(settings.MEDIA_ROOT, videourl)): videourl = None
def word(request, viewname, keyword, n, flavour='dictionary'): """View of a single keyword that may have more than one sign""" n = int(n) if request.GET.has_key('feedbackmessage'): feedbackmessage = request.GET['feedbackmessage'] else: feedbackmessage = False word = get_object_or_404(Keyword, text=keyword) # returns...
b = ffmpeg(sourcefile, targetfile, options=convert_options)
b = ffmpeg(sourcefile, targetfile, options=FFMPEG_OPTIONS)
def convert_video(sourcefile, targetfile): """convert a video to h264 format""" format = probe_format(sourcefile) if format == "h264": # just do a copy of the file shutil.copy(sourcefile, targetfile) else: # convert the video b = ffmpeg(sourcefile, targetfile, options=convert_options) format = probe_format(targetfil...
raise ComponentLookupError(u"Cannot URL encode %s of type %s" % (name, field.value_type.__class__,))
raise ComponentLookupError(u"Cannot URL encode value type for %s of type %s : %s" % (name, field.__class__, field.value_type.__class__,))
def encode(data, schema, ignore=()): """Given a data dictionary with key/value pairs and schema, return an encoded query string. This is similar to urllib.urlencode(), but field names will include the appropriate field type converters, e.g. an int field will be encoded as fieldname:int=123. Fields not found in the data...
value_type_converter = IFieldTypeConverter(field, None)
value_type_converter = IFieldTypeConverter(field.value_type, None)
def encode(data, schema, ignore=()): """Given a data dictionary with key/value pairs and schema, return an encoded query string. This is similar to urllib.urlencode(), but field names will include the appropriate field type converters, e.g. an int field will be encoded as fieldname:int=123. Fields not found in the data...
encoded_name = "%s:%s:%s" % (name, value_type_converter, converter.token,)
encoded_name = "%s:%s:%s" % (name, value_type_converter.token, converter.token,)
def encode(data, schema, ignore=()): """Given a data dictionary with key/value pairs and schema, return an encoded query string. This is similar to urllib.urlencode(), but field names will include the appropriate field type converters, e.g. an int field will be encoded as fieldname:int=123. Fields not found in the data...
Please also inform the Biopython developers by sending an email to biopython-dev@biopython.org to inform us about this missing DTD, so that we can include it with the next release of Biopython.
Please also inform the Biopython developers about this missing DTD, by reporting a bug on http://bugzilla.open-bio.org/ or sign up to our mailing list and emailing us, so that we can include it with the next release of Biopython.
def externalEntityRefHandler(self, context, base, systemId, publicId): """The purpose of this function is to load the DTD locally, instead of downloading it from the URL specified in the XML. Using the local DTD results in much faster parsing. If the DTD is not found locally, we try to download it. In practice, this ma...
pseudo_initial = asarray(pseudo_initial)
pseudo_initial = numpy.asarray(pseudo_initial)
def train_bw(states, alphabet, training_data, pseudo_initial=None, pseudo_transition=None, pseudo_emission=None, update_fn=None, ): """train_bw(states, alphabet, training_data[, pseudo_initial] [, pseudo_transition][, pseudo_emission][, update_fn]) -> MarkovModel Train a MarkovModel using the Baum-Welch algorithm. st...
pseudo_transition = asarray(pseudo_transition)
pseudo_transition = numpy.asarray(pseudo_transition)
def train_bw(states, alphabet, training_data, pseudo_initial=None, pseudo_transition=None, pseudo_emission=None, update_fn=None, ): """train_bw(states, alphabet, training_data[, pseudo_initial] [, pseudo_transition][, pseudo_emission][, update_fn]) -> MarkovModel Train a MarkovModel using the Baum-Welch algorithm. st...
pseudo_emission = asarray(pseudo_emission)
pseudo_emission = numpy.asarray(pseudo_emission)
def train_bw(states, alphabet, training_data, pseudo_initial=None, pseudo_transition=None, pseudo_emission=None, update_fn=None, ): """train_bw(states, alphabet, training_data[, pseudo_initial] [, pseudo_transition][, pseudo_emission][, update_fn]) -> MarkovModel Train a MarkovModel using the Baum-Welch algorithm. st...
pseudo_initial = asarray(pseudo_initial)
pseudo_initial = numpy.asarray(pseudo_initial)
def train_visible(states, alphabet, training_data, pseudo_initial=None, pseudo_transition=None, pseudo_emission=None): """train_visible(states, alphabet, training_data[, pseudo_initial] [, pseudo_transition][, pseudo_emission]) -> MarkovModel Train a visible MarkovModel using maximum likelihoood estimates for each of ...
pseudo_transition = asarray(pseudo_transition)
pseudo_transition = numpy.asarray(pseudo_transition)
def train_visible(states, alphabet, training_data, pseudo_initial=None, pseudo_transition=None, pseudo_emission=None): """train_visible(states, alphabet, training_data[, pseudo_initial] [, pseudo_transition][, pseudo_emission]) -> MarkovModel Train a visible MarkovModel using maximum likelihoood estimates for each of ...
pseudo_emission = asarray(pseudo_emission)
pseudo_emission = numpy.asarray(pseudo_emission)
def train_visible(states, alphabet, training_data, pseudo_initial=None, pseudo_transition=None, pseudo_emission=None): """train_visible(states, alphabet, training_data[, pseudo_initial] [, pseudo_transition][, pseudo_emission]) -> MarkovModel Train a visible MarkovModel using maximum likelihoood estimates for each of ...
child.stdin.close()
def emboss_translate(sequence, table=None, frame=None): """Call transeq, returns protein sequence as string.""" #TODO - Support transeq in Bio.Emboss.Applications? #(doesn't seem worthwhile as Biopython can do translations) if not sequence: raise ValueError(sequence) #Setup, cline = exes["transeq"] if len(sequence) ...
"HUM":"MAM",
"HUM":"PRI",
def _get_data_division(self, record): try: division = record.annotations["data_file_division"] except KeyError: division = "UNK" if division in ["PRI", "ROD", "MAM", "VRT", "INV", "PLN", "BCT", "VRL", "PHG", "SYN", "UNA", "EST", "PAT", "STS", "GSS", "HTG", "HTC", "ENV", "CON"]: #Good, already GenBank style # PRI - p...
self._write_single_line("ID", "%s; %s; ; %s; ; ; %i BP." \ % (accession, version, mol_type, len(record)))
self._write_single_line("ID", "%s; %s; ; %s; ; %s; %i BP." \ % (accession, version, mol_type, division, len(record)))
def _write_the_first_lines(self, record): """Write the ID and AC lines.""" if "." in record.id and record.id.rsplit(".", 1)[1].isdigit(): version = "SV " + record.id.rsplit(".", 1)[1] accession = self._get_annotation_str(record, "accession", record.id.rsplit(".", 1)[0], just_first=True) else : version = "" accession = ...
return StringIO.StringIO(results)
return StringIO(results)
def qblast(program, database, sequence, auto_format=None,composition_based_statistics=None, db_genetic_code=None,endpoints=None,entrez_query='(none)', expect=10.0,filter=None,gapcosts=None,genetic_code=None, hitlist_size=50,i_thresh=None,layout=None,lcase_mask=None, matrix_name=None,nucl_penalty=None,nucl_reward=None, ...
records = list(SeqIO.parse(handle=open(t_filename,"r"), format=t_format))
records = list(SeqIO.parse(handle=open(t_filename,mode), format=t_format))
def check_simple_write_read(records, indent=" "): #print indent+"Checking we can write and then read back these records" for format in test_write_read_alignment_formats: if format not in possible_unknown_seq_formats \ and isinstance(records[0].seq, UnknownSeq) \ and len(records[0].seq) > 100: #Skipping for speed. Some...
seq_iterator = SeqIO.parse(handle=open(t_filename,"r"), format=t_format)
seq_iterator = SeqIO.parse(handle=open(t_filename,mode), format=t_format)
def check_simple_write_read(records, indent=" "): #print indent+"Checking we can write and then read back these records" for format in test_write_read_alignment_formats: if format not in possible_unknown_seq_formats \ and isinstance(records[0].seq, UnknownSeq) \ and len(records[0].seq) > 100: #Skipping for speed. Some...
for record in SeqIO.parse(open(t_filename),t_format,given_alpha):
for record in SeqIO.parse(open(t_filename,mode),t_format,given_alpha):
def check_simple_write_read(records, indent=" "): #print indent+"Checking we can write and then read back these records" for format in test_write_read_alignment_formats: if format not in possible_unknown_seq_formats \ and isinstance(records[0].seq, UnknownSeq) \ and len(records[0].seq) > 100: #Skipping for speed. Some...
record = SeqIO.read(open(t_filename),t_format,given_alpha)
record = SeqIO.read(open(t_filename,mode),t_format,given_alpha)
def check_simple_write_read(records, indent=" "): #print indent+"Checking we can write and then read back these records" for format in test_write_read_alignment_formats: if format not in possible_unknown_seq_formats \ and isinstance(records[0].seq, UnknownSeq) \ and len(records[0].seq) > 100: #Skipping for speed. Some...
print SeqIO.parse(open(t_filename),t_format,given_alpha).next()
print SeqIO.parse(open(t_filename,mode),t_format,given_alpha).next()
def check_simple_write_read(records, indent=" "): #print indent+"Checking we can write and then read back these records" for format in test_write_read_alignment_formats: if format not in possible_unknown_seq_formats \ and isinstance(records[0].seq, UnknownSeq) \ and len(records[0].seq) > 100: #Skipping for speed. Some...
handle=open(t_filename,"r"), format=t_format))
handle=open(t_filename,mode), format=t_format))
def check_simple_write_read(records, indent=" "): #print indent+"Checking we can write and then read back these records" for format in test_write_read_alignment_formats: if format not in possible_unknown_seq_formats \ and isinstance(records[0].seq, UnknownSeq) \ and len(records[0].seq) > 100: #Skipping for speed. Some...
def test_convert_to_phylip32(self): """Convert FASTA to PHYLIP 3.2 format.""" self.conversion(11, "phy", "phylip")
def test_convert_to_phylip32(self): """Convert FASTA to PHYLIP 3.2 format.""" self.conversion(11, "phy", "phylip")
feature_key = line[2:self.FEATURE_QUALIFIER_INDENT].strip() feature_lines = [line[self.FEATURE_QUALIFIER_INDENT:]]
if line[self.FEATURE_QUALIFIER_INDENT]!=" " \ and " " in line[self.FEATURE_QUALIFIER_INDENT:]: feature_key, line = line[2:].strip().split(None,1) feature_lines = [line] import warnings warnings.warn("Overindented %s feature?" % feature_key) else: feature_key = line[2:self.FEATURE_QUALIFIER_INDENT].strip() feature_li...
def parse_features(self, skip=False): """Return list of tuples for the features (if present)
confidence = property(_get_confidence, _set_confidence)
def _del_confidence(self): self.confidences = [] confidence = property(_get_confidence, _set_confidence, _del_confidence)
def _set_confidence(self, value): if isinstance(value, float) or isinstance(value, int): value = Confidence(value) elif not isinstance(value, Confidence): raise ValueError("value must be a number or Confidence instance") if len(self.confidences) == 0: self.confidences.append(value) elif len(self.confidences) == 1: self...
print X.pi()
print X.isoelectric_point()
def secondary_structure_fraction (self): if not self.amino_acids_percent: self.get_amino_acids_percent() Helix = self.amino_acids_percent['V'] + self.amino_acids_percent['I'] + self.amino_acids_percent['Y'] + self.amino_acids_percent['F'] + self.amino_acids_percent['W'] + self.amino_acids_percent['L'] Turn = self.amino...
answer.append(ref)
answer.dbxrefs.append(ref)
def __add__(self, other): """Add another sequence or string to this sequence.
mode = "r"
def write_read(filename, in_format, out_format): if in_format in BINARY_FORMATS: mode = "rb" handle = BytesIO() else : mode = "r" handle = StringIO() records = list(SeqIO.parse(open(filename, mode),in_format)) #Write it out... SeqIO.write(records, handle, out_format) handle.seek(0) #Now load it back and check it agrees...
records = list(SeqIO.parse(open(filename, mode),in_format))
def write_read(filename, in_format, out_format): if in_format in BINARY_FORMATS: mode = "rb" handle = BytesIO() else : mode = "r" handle = StringIO() records = list(SeqIO.parse(open(filename, mode),in_format)) #Write it out... SeqIO.write(records, handle, out_format) handle.seek(0) #Now load it back and check it agrees...
raise TypeError("Need a file handle, not a string (i.e. not a filename)")
raise TypeError(\ "Need a file handle, not a string (i.e. not a filename)")
def write(alignments, handle, format): """Write complete set of alignments to a file. Arguments: - sequences - A list (or iterator) of Alignment objects - handle - File handle object to write to - format - lower case string describing the file format to write. You should close the handle after calling this func...
raise TypeError("Need an Alignment list/iterator, not just a single Alignment")
raise TypeError(\ "Need an Alignment list/iterator, not just a single Alignment")
def write(alignments, handle, format): """Write complete set of alignments to a file. Arguments: - sequences - A list (or iterator) of Alignment objects - handle - File handle object to write to - format - lower case string describing the file format to write. You should close the handle after calling this func...
raise TypeError("Expect a list or iterator of Alignment objects.")
raise TypeError(\ "Expect a list or iterator of Alignment objects.")
def write(alignments, handle, format): """Write complete set of alignments to a file. Arguments: - sequences - A list (or iterator) of Alignment objects - handle - File handle object to write to - format - lower case string describing the file format to write. You should close the handle after calling this func...
raise TypeError("Need a file handle, not a string (i.e. not a filename)")
raise TypeError(\ "Need a file handle, not a string (i.e. not a filename)")
def parse(handle, format, seq_count=None, alphabet=None): """Turns a sequence file into an iterator returning Alignment objects. Arguments: - handle - handle to the file. - format - string describing the file format. - alphabet - optional Alphabet object, useful when the sequence type cannot be automatically in...
print "Extra: " + ",".join(sorted(extra)) print "Missing: " + ",".join(sorted(missing)) self.assertEqual(len(extra), 0, \ "Wrapper has extra: " + ", ".join(sorted(extra))) self.assertEqual(len(missing), 0, \ "Wrapper is missing: " + ", ".join(sorted(missing)))
raise MissingExternalDependencyError("BLAST+ and Biopython out of sync. " "Your version of the NCBI BLAST+ tool %s does not match what we " "are expecting. Please update your copy of Biopython, or report " "this issue if you are already using the latest version. " "(Exta args: %s; Missing: %s)" \ % (exe_name, ",".join(...
def check(self, exe_name, wrapper) : global exe_names exe = exe_names[exe_name] cline = wrapper(exe, h=True)
is_require=True),
is_required=True),
def __init__(self, cmd="iep", **kwargs): self.parameters = [ _Option(["-sequence","sequence"], "Protein sequence(s) filename", filename=True, is_require=True), _Option(["-amino","amino"], "Amino acid"), _Option(["-lysinemodified","lysinemodified"], ""), #TODO _Option(["-disulphides","disulphides"], ""), #TODO _Option([...
_Switch(["--6merpair", "6merpair"], ["input"],
_Switch(["--6merpair", "6merpair", "sixmerpair"], ["input"],
def __init__(self, cmd="mafft", **kwargs): BLOSUM_MATRICES = ["30","45","62","80"] self.parameters = \ [ #**** Algorithm **** #Automatically selects an appropriate strategy from L-INS-i, FFT-NS- #i and FFT-NS-2, according to data size. Default: off (always FFT-NS-2) _Switch(["--auto", "auto"], ["input"], "Automatically...
You can specify the returned record's features as a list of SeqFeature objects, True to keep that of the parent, or False to omit them. The default is to keep the original features (with the strand and locations adjusted). You can specify the returned record's annotations and letter_annotations as dictionaries, True t...
You can specify the returned record's features with a list of SeqFeature objects, or True to keep that of the parent, or False to omit them. The default is to keep the original features (with the strand and locations adjusted). You can also specify both the returned record's annotations and letter_annotations as dicti...
def reverse_complement(self, id=False, name=False, description=False, features=True, annotations=False, letter_annotations=True, dbxrefs=False): """Returns new SeqRecord with reverse complement sequence.
Notice that the per-letter-annotations have also been reversed, although this may not be appropriate for all possible per-letter-annotation.
Notice that the per-letter-annotations have also been reversed, although this may not be appropriate for all cases.
def reverse_complement(self, id=False, name=False, description=False, features=True, annotations=False, letter_annotations=True, dbxrefs=False): """Returns new SeqRecord with reverse complement sequence.
Note trying to reverse complement a protein SeqRecord raises an exception:
Note that if the SeqFeature annotation includes any strand specific information (e.g. base changes for a SNP), this information is not ammended, and would need correction after the reverse complement. Note trying to reverse complement a protein SeqRecord raises an exception:
def reverse_complement(self, id=False, name=False, description=False, features=True, annotations=False, letter_annotations=True, dbxrefs=False): """Returns new SeqRecord with reverse complement sequence.
def _validate(self): if self.remote and self.in_pssm: raise ValueError("The remote option cannot be used with in_pssm") if self.query and self.in_pssm: raise ValueError("The query option cannot be used with in_pssm") _Ncbiblast2SeqCommandline._validate(self)
def _validate(self): if self.remote and self.in_pssm: raise ValueError("The remote option cannot be used with in_pssm") if self.query and self.in_pssm: raise ValueError("The query option cannot be used with in_pssm") _Ncbiblast2SeqCommandline._validate(self)
return Seq(self.data[i:j], self.alphabet)
return Seq.Seq(self.data[i:j], self.alphabet)
def __getslice__(self, i, j): i = max(i, 0); j = max(j, 0) return Seq(self.data[i:j], self.alphabet)
raise ValueError("Expected frequency letters %s" + " do not match observed %s" % (e_freq_table.keys(), obs_freq.keys() - [gap_char]))
raise ValueError("Expected frequency letters %s " "do not match observed %s" \ % (e_freq_table.keys(), obs_freq.keys() - [gap_char]))
def _get_column_info_content(self, obs_freq, e_freq_table, log_base, random_expected): """Calculate the information content for a column.
raise ValueError("Alphabet type is unsupported: %s" % alphabet.letters)
raise ValueError(\ "Alphabet type is unsupported: %s" % genome_alphabet.letters)
def random_population(genome_alphabet, genome_size, num_organisms, fitness_calculator): """Generate a population of individuals with randomly set genomes. Arguments: o genome_alphabet -- An Alphabet object describing all of the possible letters that could potentially be in the genome of an organism. o genome_size --...
if child is not None: return child.text and construct(child.text) or None
if child is not None and child.text: return construct(child.text)
def get_child_text(parent, tag, construct=unicode): """Find a child node by tag; pass its text through a constructor. Returns None if no matching child is found. """ child = parent.find(_ns(tag)) if child is not None: return child.text and construct(child.text) or None
"Returns a list of strings."""
def _split_multi_line(self, text, max_len): "Returns a list of strings.""" #TODO - Do the line spliting while preserving white space? text = text.strip() if len(text) <= max_len: return [text]
if max([len(w) for w in words]) > max_len: raise ValueError("Text cannot be broken into len %i lines!:\n%s" % (max_len, repr(text)))
def _split_multi_line(self, text, max_len): "Returns a list of strings.""" #TODO - Do the line spliting while preserving white space? text = text.strip() if len(text) <= max_len: return [text]
assert len(text) <= max_len
def _split_multi_line(self, text, max_len): "Returns a list of strings.""" #TODO - Do the line spliting while preserving white space? text = text.strip() if len(text) <= max_len: return [text]
assert len(text) <= self.MAX_WIDTH - self.HEADER_WIDTH, \ "Annotation %s too long for %s line" % (repr(text), tag)
if len(text) > self.MAX_WIDTH - self.HEADER_WIDTH: import warnings warnings.warn("Annotation %r too long for %s line" % (text, tag))
def _write_single_line(self, tag, text): "Used in the the 'header' of each GenBank record.""" assert len(tag) < self.HEADER_WIDTH assert len(text) <= self.MAX_WIDTH - self.HEADER_WIDTH, \ "Annotation %s too long for %s line" % (repr(text), tag) self.handle.write("%s%s\n" % (tag.ljust(self.HEADER_WIDTH), text.replace("\...
record = None if record is not None: records3.append(record) else:
def check_simple_write_read(records, indent=" "): #print indent+"Checking we can write and then read back these records" for format in test_write_read_alignment_formats: if format not in possible_unknown_seq_formats \ and isinstance(records[0].seq, UnknownSeq) \ and len(records[0].seq) > 100: #Skipping for speed. Some...
assert record is not None, "Should raise StopIteration not return None" records3.append(record)
def check_simple_write_read(records, indent=" "): #print indent+"Checking we can write and then read back these records" for format in test_write_read_alignment_formats: if format not in possible_unknown_seq_formats \ and isinstance(records[0].seq, UnknownSeq) \ and len(records[0].seq) > 100: #Skipping for speed. Some...
elif isinstance(filename, file):
elif hasattr(filename, 'write'):
def write_nexus_data(self, filename=None, matrix=None, exclude=[], delete=[],\ blocksize=None, interleave=False, interleave_by_partition=False,\ comment=None,omit_NEXUS=False,append_sets=True,mrbayes=False,\ codons_block=True): """Writes a nexus file with data and sets block to a file or handle.
cur_feature = self._cur_feature if location_line.startswith("complement("): assert location_line.endswith(")") location_line = location_line[11:-1] cur_feature.strand = -1 if _re_simple_location.match(location_line): s, e = location_line.split("..") cur_feature.location = SeqFeature.FeatureLocation(_pos(s,-1), _p...
def location(self, content): """Parse out location information from the location string.
self._set_location_info(parse_info, self._cur_feature)
self._set_location_info(parse_info, cur_feature)
def location(self, content): """Parse out location information from the location string.
self.assertTrue(key in ids)
self.assertTrue(key in keys)
def check_dict_methods(self, rec_dict, keys, ids): self.assertEqual(set(keys), set(rec_dict.keys())) #This is redundant, I just want to make sure len works: self.assertEqual(len(keys), len(rec_dict)) #Make sure boolean evaluation works self.assertEqual(bool(keys), bool(rec_dict)) for key,id in zip(keys, ids): self.asse...
_Option(["-input","-primers","primers","input"], ["input", "file"],
_Option(["-infile","-primers","primers","infile"], ["input", "file"],
def __init__(self, cmd="primersearch", **kwargs): self.parameters = \ [_Option(["-seqall","-sequences","sequences","seqall"], ["input"], None, 1, "Sequence to look for the primer pairs in."), #When this wrapper was written primersearch used -sequences #as the argument name. Since at least EMBOSS 5.0 (and #perhaps earli...
raise "Vector: x is not a list/tuple/array of 3 numbers"
raise ValueError("Vector: x is not a " "list/tuple/array of 3 numbers")
def __init__(self, x, y=None, z=None): if y is None and z is None: # Array, list, tuple... if len(x)!=3: raise "Vector: x is not a list/tuple/array of 3 numbers" self._ar=numpy.array(x, 'd') else: # Three numbers self._ar=numpy.array((x, y, z), 'd')
report_pops(num_pops)
if report_pops: report_pops(num_pops)
def init_pop(): my_pop = [] for i in range(num_loci): my_pop.append({}) return my_pop
assert data.count("-")==1 consumer.reference_bases("(bases " + data.replace("-", " to ") + ")")
parts = [bases.replace("-"," to ").strip() for bases in data.split(",")] consumer.reference_bases("(bases %s)" % "; ".join(parts))
def _feed_header_lines(self, consumer, lines): EMBL_INDENT = self.HEADER_WIDTH EMBL_SPACER = " " * EMBL_INDENT consumer_dict = { 'AC' : 'accession', 'SV' : 'version', # SV line removed in June 2006, now part of ID line 'DE' : 'definition', #'RN' : 'reference_num', #'RC' : reference comment... TODO #'RP' : 'reference_b...
raise NexusError('Unknown partition: '+interleave_by_partition)
raise NexusError('Unknown partition: %r' % interleave_by_partition)
def write_nexus_data(self, filename=None, matrix=None, exclude=[], delete=[],\ blocksize=None, interleave=False, interleave_by_partition=False,\ comment=None,omit_NEXUS=False,append_sets=True,mrbayes=False,\ codons_block=True): """Writes a nexus file with data and sets block to a file or handle.
if sys.version_info == 3:
if sys.version_info[0] == 3:
def test_convert(self): """Convert a tree between all supported formats.""" mem_file_1 = StringIO() mem_file_3 = StringIO() if sys.version_info == 3: from io import BytesIO mem_file_2 = BytesIO() else: mem_file_2 = StringIO() Phylo.convert(EX_NEWICK, 'newick', mem_file_1, 'nexus') mem_file_1.seek(0) Phylo.convert(mem_f...
if hasattr(n2, 'weight') and n2.weight is not None: graph[n1][n2]['weight'] = n2.weight elif hasattr(n1, 'weight') and n1.weight is not None: graph[n1][n2]['weight'] = n1.weight n2.weight = n1.weight
if hasattr(n2, 'width') and n2.width is not None: graph[n1][n2]['width'] = n2.width elif hasattr(n1, 'width') and n1.width is not None: graph[n1][n2]['width'] = n1.width n2.width = n1.width
def add_edge(graph, n1, n2): # NB (1/2010): the networkx API congealed recently # Ubuntu Lucid uses v0.99, newest is v1.0.1, let's support both if networkx.__version__ >= '1.0': graph.add_edge(n1, n2, weight=str(n2.branch_length or 1.0)) # Copy branch color value as hex, if available if hasattr(n2, 'color') and n2.colo...
len_adjusted -= len( self._start_line )
len_adjusted = len(self._start_line)
def read_block( self, len_expected ):
len_adjusted = len_adjusted - len_filtered_text
len_adjusted -= len_filtered_text
def read_block( self, len_expected ):
for clade in self.clades:
for clade in self.root.clades:
def is_preterminal(self): """True if all direct descendents are terminal.""" if self.root.is_terminal(): return False for clade in self.clades: if not clade.is_terminal(): return False return True
class MotifTestsBasic(unittest.TestCase):
class MotifTestPWM(unittest.TestCase):
def test_mast_parser_3(self): """Test if Motif can parse MAST output files (third test) """ from Bio.Alphabet import IUPAC from Bio.Motif.Parsers import MAST handle = open("Motif/mast.protein.tcm.txt") record = MAST.read(handle) self.assertEqual(record.version, "3.0") self.assertEqual(record.database, "farntrans5.s") s...
self.assertAlmostEqual(markov_model.p_emission[0][0], 0.666667, 4) self.assertAlmostEqual(markov_model.p_emission[0][1], 0.111111, 4) self.assertAlmostEqual(markov_model.p_emission[0][2], 0.111111, 4) self.assertAlmostEqual(markov_model.p_emission[0][3], 0.111111, 4) self.assertAlmostEqual(markov_model.p_emission[1][0]...
self.assertAlmostEqual(markov_model.p_emission[0][0], 0.666667, places=4) self.assertAlmostEqual(markov_model.p_emission[0][1], 0.111111, places=4) self.assertAlmostEqual(markov_model.p_emission[0][2], 0.111111, places=4) self.assertAlmostEqual(markov_model.p_emission[0][3], 0.111111, places=4) self.assertAlmostEqual(m...
def test_train_visible(self): states = ["0", "1", "2", "3"] alphabet = ["A", "C", "G", "T"] training_data = [ ("AACCCGGGTTTTTTT", "001112223333333"), ("ACCGTTTTTTT", "01123333333"), ("ACGGGTTTTTT", "01222333333"), ("ACCGTTTTTTTT", "011233333333"), ] markov_model = MarkovModel.train_visible(states, alphabet, training_da...
self.assertAlmostEqual(markov_model.p_initial[0], 1.0, 4) self.assertAlmostEqual(markov_model.p_initial[1], 0.0, 4)
self.assertAlmostEqual(markov_model.p_initial[0], 1.0, places=4) self.assertAlmostEqual(markov_model.p_initial[1], 0.0, places=4)
def test_baum_welch(self): states = ["CP", "IP"] alphabet = ["cola", "ice_t", "lem"] outputs = [ (2, 1, 0) ] p_initial = [1.0, 0.0000001] p_transition = [[0.7, 0.3], [0.5, 0.5]] p_emission = [[0.6, 0.1, 0.3], [0.1, 0.7, 0.2]] N, M = len(states), len(alphabet) x = MarkovModel._baum_welch(N, M, outputs, p_initial=p_initi...