repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
klavinslab/coral
coral/sequence/_dna.py
DNA.ape
def ape(self, ape_path=None): '''Open in ApE if `ApE` is in your command line path.''' # TODO: simplify - make ApE look in PATH only cmd = 'ApE' if ape_path is None: # Check for ApE in PATH ape_executables = [] for path in os.environ['PATH'].split(os.pathsep): exepath = os.path.join(path, cmd) ape_executables.append(os.access(exepath, os.X_OK)) if not any(ape_executables): raise Exception('Ape not in PATH. Use ape_path kwarg.') else: cmd = ape_path # Check whether ApE exists in PATH tmp = tempfile.mkdtemp() if self.name is not None and self.name: filename = os.path.join(tmp, '{}.ape'.format(self.name)) else: filename = os.path.join(tmp, 'tmp.ape') coral.seqio.write_dna(self, filename) process = subprocess.Popen([cmd, filename]) # Block until window is closed try: process.wait() shutil.rmtree(tmp) except KeyboardInterrupt: shutil.rmtree(tmp)
python
def ape(self, ape_path=None): '''Open in ApE if `ApE` is in your command line path.''' # TODO: simplify - make ApE look in PATH only cmd = 'ApE' if ape_path is None: # Check for ApE in PATH ape_executables = [] for path in os.environ['PATH'].split(os.pathsep): exepath = os.path.join(path, cmd) ape_executables.append(os.access(exepath, os.X_OK)) if not any(ape_executables): raise Exception('Ape not in PATH. Use ape_path kwarg.') else: cmd = ape_path # Check whether ApE exists in PATH tmp = tempfile.mkdtemp() if self.name is not None and self.name: filename = os.path.join(tmp, '{}.ape'.format(self.name)) else: filename = os.path.join(tmp, 'tmp.ape') coral.seqio.write_dna(self, filename) process = subprocess.Popen([cmd, filename]) # Block until window is closed try: process.wait() shutil.rmtree(tmp) except KeyboardInterrupt: shutil.rmtree(tmp)
[ "def", "ape", "(", "self", ",", "ape_path", "=", "None", ")", ":", "# TODO: simplify - make ApE look in PATH only", "cmd", "=", "'ApE'", "if", "ape_path", "is", "None", ":", "# Check for ApE in PATH", "ape_executables", "=", "[", "]", "for", "path", "in", "os", ".", "environ", "[", "'PATH'", "]", ".", "split", "(", "os", ".", "pathsep", ")", ":", "exepath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "cmd", ")", "ape_executables", ".", "append", "(", "os", ".", "access", "(", "exepath", ",", "os", ".", "X_OK", ")", ")", "if", "not", "any", "(", "ape_executables", ")", ":", "raise", "Exception", "(", "'Ape not in PATH. Use ape_path kwarg.'", ")", "else", ":", "cmd", "=", "ape_path", "# Check whether ApE exists in PATH", "tmp", "=", "tempfile", ".", "mkdtemp", "(", ")", "if", "self", ".", "name", "is", "not", "None", "and", "self", ".", "name", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "tmp", ",", "'{}.ape'", ".", "format", "(", "self", ".", "name", ")", ")", "else", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "tmp", ",", "'tmp.ape'", ")", "coral", ".", "seqio", ".", "write_dna", "(", "self", ",", "filename", ")", "process", "=", "subprocess", ".", "Popen", "(", "[", "cmd", ",", "filename", "]", ")", "# Block until window is closed", "try", ":", "process", ".", "wait", "(", ")", "shutil", ".", "rmtree", "(", "tmp", ")", "except", "KeyboardInterrupt", ":", "shutil", ".", "rmtree", "(", "tmp", ")" ]
Open in ApE if `ApE` is in your command line path.
[ "Open", "in", "ApE", "if", "ApE", "is", "in", "your", "command", "line", "path", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L84-L111
klavinslab/coral
coral/sequence/_dna.py
DNA.copy
def copy(self): '''Create a copy of the current instance. :returns: A safely-editable copy of the current sequence. :rtype: coral.DNA ''' # Significant performance improvements by skipping alphabet check features_copy = [feature.copy() for feature in self.features] copy = type(self)(self.top.seq, circular=self.circular, features=features_copy, name=self.name, bottom=self.bottom.seq, run_checks=False) return copy
python
def copy(self): '''Create a copy of the current instance. :returns: A safely-editable copy of the current sequence. :rtype: coral.DNA ''' # Significant performance improvements by skipping alphabet check features_copy = [feature.copy() for feature in self.features] copy = type(self)(self.top.seq, circular=self.circular, features=features_copy, name=self.name, bottom=self.bottom.seq, run_checks=False) return copy
[ "def", "copy", "(", "self", ")", ":", "# Significant performance improvements by skipping alphabet check", "features_copy", "=", "[", "feature", ".", "copy", "(", ")", "for", "feature", "in", "self", ".", "features", "]", "copy", "=", "type", "(", "self", ")", "(", "self", ".", "top", ".", "seq", ",", "circular", "=", "self", ".", "circular", ",", "features", "=", "features_copy", ",", "name", "=", "self", ".", "name", ",", "bottom", "=", "self", ".", "bottom", ".", "seq", ",", "run_checks", "=", "False", ")", "return", "copy" ]
Create a copy of the current instance. :returns: A safely-editable copy of the current sequence. :rtype: coral.DNA
[ "Create", "a", "copy", "of", "the", "current", "instance", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L113-L125
klavinslab/coral
coral/sequence/_dna.py
DNA.circularize
def circularize(self): '''Circularize linear DNA. :returns: A circularized version of the current sequence. :rtype: coral.DNA ''' if self.top[-1].seq == '-' and self.bottom[0].seq == '-': raise ValueError('Cannot circularize - termini disconnected.') if self.bottom[-1].seq == '-' and self.top[0].seq == '-': raise ValueError('Cannot circularize - termini disconnected.') copy = self.copy() copy.circular = True copy.top.circular = True copy.bottom.circular = True return copy
python
def circularize(self): '''Circularize linear DNA. :returns: A circularized version of the current sequence. :rtype: coral.DNA ''' if self.top[-1].seq == '-' and self.bottom[0].seq == '-': raise ValueError('Cannot circularize - termini disconnected.') if self.bottom[-1].seq == '-' and self.top[0].seq == '-': raise ValueError('Cannot circularize - termini disconnected.') copy = self.copy() copy.circular = True copy.top.circular = True copy.bottom.circular = True return copy
[ "def", "circularize", "(", "self", ")", ":", "if", "self", ".", "top", "[", "-", "1", "]", ".", "seq", "==", "'-'", "and", "self", ".", "bottom", "[", "0", "]", ".", "seq", "==", "'-'", ":", "raise", "ValueError", "(", "'Cannot circularize - termini disconnected.'", ")", "if", "self", ".", "bottom", "[", "-", "1", "]", ".", "seq", "==", "'-'", "and", "self", ".", "top", "[", "0", "]", ".", "seq", "==", "'-'", ":", "raise", "ValueError", "(", "'Cannot circularize - termini disconnected.'", ")", "copy", "=", "self", ".", "copy", "(", ")", "copy", ".", "circular", "=", "True", "copy", ".", "top", ".", "circular", "=", "True", "copy", ".", "bottom", ".", "circular", "=", "True", "return", "copy" ]
Circularize linear DNA. :returns: A circularized version of the current sequence. :rtype: coral.DNA
[ "Circularize", "linear", "DNA", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L127-L143
klavinslab/coral
coral/sequence/_dna.py
DNA.display
def display(self): '''Display a visualization of the sequence in an IPython notebook.''' try: from IPython.display import HTML import uuid except ImportError: raise IPythonDisplayImportError sequence_json = self.json() d3cdn = '//d3js.org/d3.v3.min.js' div_id = 'sequence_{}'.format(uuid.uuid1()) cur_dir = os.path.abspath(os.path.dirname(__file__)) d3_plasmid_path = os.path.join(cur_dir, 'd3-plasmid.js') with open(d3_plasmid_path) as f: d3_plasmid_js = f.read() html = '<div id={div_id}></div>'.format(div_id=div_id) js_databind = ''' <script> require([\'{d3_cdn}\'], function(lib) {{ window.data = {data};'''.format(div_id=div_id, d3_cdn=d3cdn, data=sequence_json) js_viz = ''' d3sequence(window.data, \'{div_id}\') }}); </script> '''.format(div_id=div_id) return HTML(html + js_databind + d3_plasmid_js + js_viz)
python
def display(self): '''Display a visualization of the sequence in an IPython notebook.''' try: from IPython.display import HTML import uuid except ImportError: raise IPythonDisplayImportError sequence_json = self.json() d3cdn = '//d3js.org/d3.v3.min.js' div_id = 'sequence_{}'.format(uuid.uuid1()) cur_dir = os.path.abspath(os.path.dirname(__file__)) d3_plasmid_path = os.path.join(cur_dir, 'd3-plasmid.js') with open(d3_plasmid_path) as f: d3_plasmid_js = f.read() html = '<div id={div_id}></div>'.format(div_id=div_id) js_databind = ''' <script> require([\'{d3_cdn}\'], function(lib) {{ window.data = {data};'''.format(div_id=div_id, d3_cdn=d3cdn, data=sequence_json) js_viz = ''' d3sequence(window.data, \'{div_id}\') }}); </script> '''.format(div_id=div_id) return HTML(html + js_databind + d3_plasmid_js + js_viz)
[ "def", "display", "(", "self", ")", ":", "try", ":", "from", "IPython", ".", "display", "import", "HTML", "import", "uuid", "except", "ImportError", ":", "raise", "IPythonDisplayImportError", "sequence_json", "=", "self", ".", "json", "(", ")", "d3cdn", "=", "'//d3js.org/d3.v3.min.js'", "div_id", "=", "'sequence_{}'", ".", "format", "(", "uuid", ".", "uuid1", "(", ")", ")", "cur_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "d3_plasmid_path", "=", "os", ".", "path", ".", "join", "(", "cur_dir", ",", "'d3-plasmid.js'", ")", "with", "open", "(", "d3_plasmid_path", ")", "as", "f", ":", "d3_plasmid_js", "=", "f", ".", "read", "(", ")", "html", "=", "'<div id={div_id}></div>'", ".", "format", "(", "div_id", "=", "div_id", ")", "js_databind", "=", "'''\n <script>\n require([\\'{d3_cdn}\\'], function(lib) {{\n window.data = {data};'''", ".", "format", "(", "div_id", "=", "div_id", ",", "d3_cdn", "=", "d3cdn", ",", "data", "=", "sequence_json", ")", "js_viz", "=", "'''\n d3sequence(window.data, \\'{div_id}\\')\n }});\n </script>\n '''", ".", "format", "(", "div_id", "=", "div_id", ")", "return", "HTML", "(", "html", "+", "js_databind", "+", "d3_plasmid_js", "+", "js_viz", ")" ]
Display a visualization of the sequence in an IPython notebook.
[ "Display", "a", "visualization", "of", "the", "sequence", "in", "an", "IPython", "notebook", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L145-L176
klavinslab/coral
coral/sequence/_dna.py
DNA.excise
def excise(self, feature): '''Removes feature from circular plasmid and linearizes. Automatically reorients at the base just after the feature. This operation is complementary to the .extract() method. :param feature_name: The feature to remove. :type feature_name: coral.Feature ''' rotated = self.rotate_to_feature(feature) excised = rotated[feature.stop - feature.start:] return excised
python
def excise(self, feature): '''Removes feature from circular plasmid and linearizes. Automatically reorients at the base just after the feature. This operation is complementary to the .extract() method. :param feature_name: The feature to remove. :type feature_name: coral.Feature ''' rotated = self.rotate_to_feature(feature) excised = rotated[feature.stop - feature.start:] return excised
[ "def", "excise", "(", "self", ",", "feature", ")", ":", "rotated", "=", "self", ".", "rotate_to_feature", "(", "feature", ")", "excised", "=", "rotated", "[", "feature", ".", "stop", "-", "feature", ".", "start", ":", "]", "return", "excised" ]
Removes feature from circular plasmid and linearizes. Automatically reorients at the base just after the feature. This operation is complementary to the .extract() method. :param feature_name: The feature to remove. :type feature_name: coral.Feature
[ "Removes", "feature", "from", "circular", "plasmid", "and", "linearizes", ".", "Automatically", "reorients", "at", "the", "base", "just", "after", "the", "feature", ".", "This", "operation", "is", "complementary", "to", "the", ".", "extract", "()", "method", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L202-L214
klavinslab/coral
coral/sequence/_dna.py
DNA.extract
def extract(self, feature, remove_subfeatures=False): '''Extract a feature from the sequence. This operation is complementary to the .excise() method. :param feature: Feature object. :type feature: coral.sequence.Feature :param remove_subfeatures: Remove all features in the extracted sequence aside from the input feature. :type remove_subfeatures: bool :returns: A subsequence from start to stop of the feature. ''' extracted = self[feature.start:feature.stop] # Turn gaps into Ns or Xs for gap in feature.gaps: for i in range(*gap): extracted[i] = self._any_char if remove_subfeatures: # Keep only the feature specified extracted.features = [feature] # Update feature locations # copy them for feature in extracted.features: feature.move(-feature.start) return extracted
python
def extract(self, feature, remove_subfeatures=False): '''Extract a feature from the sequence. This operation is complementary to the .excise() method. :param feature: Feature object. :type feature: coral.sequence.Feature :param remove_subfeatures: Remove all features in the extracted sequence aside from the input feature. :type remove_subfeatures: bool :returns: A subsequence from start to stop of the feature. ''' extracted = self[feature.start:feature.stop] # Turn gaps into Ns or Xs for gap in feature.gaps: for i in range(*gap): extracted[i] = self._any_char if remove_subfeatures: # Keep only the feature specified extracted.features = [feature] # Update feature locations # copy them for feature in extracted.features: feature.move(-feature.start) return extracted
[ "def", "extract", "(", "self", ",", "feature", ",", "remove_subfeatures", "=", "False", ")", ":", "extracted", "=", "self", "[", "feature", ".", "start", ":", "feature", ".", "stop", "]", "# Turn gaps into Ns or Xs", "for", "gap", "in", "feature", ".", "gaps", ":", "for", "i", "in", "range", "(", "*", "gap", ")", ":", "extracted", "[", "i", "]", "=", "self", ".", "_any_char", "if", "remove_subfeatures", ":", "# Keep only the feature specified", "extracted", ".", "features", "=", "[", "feature", "]", "# Update feature locations", "# copy them", "for", "feature", "in", "extracted", ".", "features", ":", "feature", ".", "move", "(", "-", "feature", ".", "start", ")", "return", "extracted" ]
Extract a feature from the sequence. This operation is complementary to the .excise() method. :param feature: Feature object. :type feature: coral.sequence.Feature :param remove_subfeatures: Remove all features in the extracted sequence aside from the input feature. :type remove_subfeatures: bool :returns: A subsequence from start to stop of the feature.
[ "Extract", "a", "feature", "from", "the", "sequence", ".", "This", "operation", "is", "complementary", "to", "the", ".", "excise", "()", "method", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L216-L240
klavinslab/coral
coral/sequence/_dna.py
DNA.flip
def flip(self): '''Flip the DNA - swap the top and bottom strands. :returns: Flipped DNA (bottom strand is now top strand, etc.). :rtype: coral.DNA ''' copy = self.copy() copy.top, copy.bottom = copy.bottom, copy.top copy.features = [_flip_feature(f, len(self)) for f in copy.features] return copy
python
def flip(self): '''Flip the DNA - swap the top and bottom strands. :returns: Flipped DNA (bottom strand is now top strand, etc.). :rtype: coral.DNA ''' copy = self.copy() copy.top, copy.bottom = copy.bottom, copy.top copy.features = [_flip_feature(f, len(self)) for f in copy.features] return copy
[ "def", "flip", "(", "self", ")", ":", "copy", "=", "self", ".", "copy", "(", ")", "copy", ".", "top", ",", "copy", ".", "bottom", "=", "copy", ".", "bottom", ",", "copy", ".", "top", "copy", ".", "features", "=", "[", "_flip_feature", "(", "f", ",", "len", "(", "self", ")", ")", "for", "f", "in", "copy", ".", "features", "]", "return", "copy" ]
Flip the DNA - swap the top and bottom strands. :returns: Flipped DNA (bottom strand is now top strand, etc.). :rtype: coral.DNA
[ "Flip", "the", "DNA", "-", "swap", "the", "top", "and", "bottom", "strands", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L242-L252
klavinslab/coral
coral/sequence/_dna.py
DNA.linearize
def linearize(self, index=0): '''Linearize circular DNA at an index. :param index: index at which to linearize. :type index: int :returns: A linearized version of the current sequence. :rtype: coral.DNA :raises: ValueError if the input is linear DNA. ''' if not self.circular: raise ValueError('Cannot relinearize linear DNA.') copy = self.copy() # Snip at the index if index: return copy[index:] + copy[:index] copy.circular = False copy.top.circular = False copy.bottom.circular = False return copy
python
def linearize(self, index=0): '''Linearize circular DNA at an index. :param index: index at which to linearize. :type index: int :returns: A linearized version of the current sequence. :rtype: coral.DNA :raises: ValueError if the input is linear DNA. ''' if not self.circular: raise ValueError('Cannot relinearize linear DNA.') copy = self.copy() # Snip at the index if index: return copy[index:] + copy[:index] copy.circular = False copy.top.circular = False copy.bottom.circular = False return copy
[ "def", "linearize", "(", "self", ",", "index", "=", "0", ")", ":", "if", "not", "self", ".", "circular", ":", "raise", "ValueError", "(", "'Cannot relinearize linear DNA.'", ")", "copy", "=", "self", ".", "copy", "(", ")", "# Snip at the index", "if", "index", ":", "return", "copy", "[", "index", ":", "]", "+", "copy", "[", ":", "index", "]", "copy", ".", "circular", "=", "False", "copy", ".", "top", ".", "circular", "=", "False", "copy", ".", "bottom", ".", "circular", "=", "False", "return", "copy" ]
Linearize circular DNA at an index. :param index: index at which to linearize. :type index: int :returns: A linearized version of the current sequence. :rtype: coral.DNA :raises: ValueError if the input is linear DNA.
[ "Linearize", "circular", "DNA", "at", "an", "index", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L275-L295
klavinslab/coral
coral/sequence/_dna.py
DNA.locate
def locate(self, pattern): '''Find sequences matching a pattern. For a circular sequence, the search extends over the origin. :param pattern: str or NucleicAcidSequence for which to find matches. :type pattern: str or coral.DNA :returns: A list of top and bottom strand indices of matches. :rtype: list of lists of indices (ints) :raises: ValueError if the pattern is longer than either the input sequence (for linear DNA) or twice as long as the input sequence (for circular DNA). ''' top_matches = self.top.locate(pattern) bottom_matches = self.bottom.locate(pattern) return [top_matches, bottom_matches]
python
def locate(self, pattern): '''Find sequences matching a pattern. For a circular sequence, the search extends over the origin. :param pattern: str or NucleicAcidSequence for which to find matches. :type pattern: str or coral.DNA :returns: A list of top and bottom strand indices of matches. :rtype: list of lists of indices (ints) :raises: ValueError if the pattern is longer than either the input sequence (for linear DNA) or twice as long as the input sequence (for circular DNA). ''' top_matches = self.top.locate(pattern) bottom_matches = self.bottom.locate(pattern) return [top_matches, bottom_matches]
[ "def", "locate", "(", "self", ",", "pattern", ")", ":", "top_matches", "=", "self", ".", "top", ".", "locate", "(", "pattern", ")", "bottom_matches", "=", "self", ".", "bottom", ".", "locate", "(", "pattern", ")", "return", "[", "top_matches", ",", "bottom_matches", "]" ]
Find sequences matching a pattern. For a circular sequence, the search extends over the origin. :param pattern: str or NucleicAcidSequence for which to find matches. :type pattern: str or coral.DNA :returns: A list of top and bottom strand indices of matches. :rtype: list of lists of indices (ints) :raises: ValueError if the pattern is longer than either the input sequence (for linear DNA) or twice as long as the input sequence (for circular DNA).
[ "Find", "sequences", "matching", "a", "pattern", ".", "For", "a", "circular", "sequence", "the", "search", "extends", "over", "the", "origin", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L297-L313
klavinslab/coral
coral/sequence/_dna.py
DNA.rotate
def rotate(self, n): '''Rotate Sequence by n bases. :param n: Number of bases to rotate. :type n: int :returns: The current sequence reoriented at `index`. :rtype: coral.DNA :raises: ValueError if applied to linear sequence or `index` is negative. ''' if not self.circular and n != 0: raise ValueError('Cannot rotate linear DNA') else: copy = self.copy() copy.top = self.top.rotate(n) copy.bottom = self.bottom.rotate(-n) copy.features = [] for feature in self.features: feature_copy = feature.copy() feature_copy.move(n) # Adjust the start/stop if we move over the origin feature_copy.start = feature_copy.start % len(self) feature_copy.stop = feature_copy.stop % len(self) copy.features.append(feature_copy) return copy.circularize()
python
def rotate(self, n): '''Rotate Sequence by n bases. :param n: Number of bases to rotate. :type n: int :returns: The current sequence reoriented at `index`. :rtype: coral.DNA :raises: ValueError if applied to linear sequence or `index` is negative. ''' if not self.circular and n != 0: raise ValueError('Cannot rotate linear DNA') else: copy = self.copy() copy.top = self.top.rotate(n) copy.bottom = self.bottom.rotate(-n) copy.features = [] for feature in self.features: feature_copy = feature.copy() feature_copy.move(n) # Adjust the start/stop if we move over the origin feature_copy.start = feature_copy.start % len(self) feature_copy.stop = feature_copy.stop % len(self) copy.features.append(feature_copy) return copy.circularize()
[ "def", "rotate", "(", "self", ",", "n", ")", ":", "if", "not", "self", ".", "circular", "and", "n", "!=", "0", ":", "raise", "ValueError", "(", "'Cannot rotate linear DNA'", ")", "else", ":", "copy", "=", "self", ".", "copy", "(", ")", "copy", ".", "top", "=", "self", ".", "top", ".", "rotate", "(", "n", ")", "copy", ".", "bottom", "=", "self", ".", "bottom", ".", "rotate", "(", "-", "n", ")", "copy", ".", "features", "=", "[", "]", "for", "feature", "in", "self", ".", "features", ":", "feature_copy", "=", "feature", ".", "copy", "(", ")", "feature_copy", ".", "move", "(", "n", ")", "# Adjust the start/stop if we move over the origin", "feature_copy", ".", "start", "=", "feature_copy", ".", "start", "%", "len", "(", "self", ")", "feature_copy", ".", "stop", "=", "feature_copy", ".", "stop", "%", "len", "(", "self", ")", "copy", ".", "features", ".", "append", "(", "feature_copy", ")", "return", "copy", ".", "circularize", "(", ")" ]
Rotate Sequence by n bases. :param n: Number of bases to rotate. :type n: int :returns: The current sequence reoriented at `index`. :rtype: coral.DNA :raises: ValueError if applied to linear sequence or `index` is negative.
[ "Rotate", "Sequence", "by", "n", "bases", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L324-L350
klavinslab/coral
coral/sequence/_dna.py
DNA.reverse_complement
def reverse_complement(self): '''Reverse complement the DNA. :returns: A reverse-complemented instance of the current sequence. :rtype: coral.DNA ''' copy = self.copy() # Note: if sequence is double-stranded, swapping strand is basically # (but not entirely) the same thing - gaps affect accuracy. copy.top = self.top.reverse_complement() copy.bottom = self.bottom.reverse_complement() # Remove all features - the reverse complement isn't flip! copy.features = [] return copy
python
def reverse_complement(self): '''Reverse complement the DNA. :returns: A reverse-complemented instance of the current sequence. :rtype: coral.DNA ''' copy = self.copy() # Note: if sequence is double-stranded, swapping strand is basically # (but not entirely) the same thing - gaps affect accuracy. copy.top = self.top.reverse_complement() copy.bottom = self.bottom.reverse_complement() # Remove all features - the reverse complement isn't flip! copy.features = [] return copy
[ "def", "reverse_complement", "(", "self", ")", ":", "copy", "=", "self", ".", "copy", "(", ")", "# Note: if sequence is double-stranded, swapping strand is basically", "# (but not entirely) the same thing - gaps affect accuracy.", "copy", ".", "top", "=", "self", ".", "top", ".", "reverse_complement", "(", ")", "copy", ".", "bottom", "=", "self", ".", "bottom", ".", "reverse_complement", "(", ")", "# Remove all features - the reverse complement isn't flip!", "copy", ".", "features", "=", "[", "]", "return", "copy" ]
Reverse complement the DNA. :returns: A reverse-complemented instance of the current sequence. :rtype: coral.DNA
[ "Reverse", "complement", "the", "DNA", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L379-L395
klavinslab/coral
coral/sequence/_dna.py
DNA.select_features
def select_features(self, term, by='name', fuzzy=False): '''Select features from the features list based on feature name, gene, or locus tag. :param term: Search term. :type term: str :param by: Feature attribute to search by. Options are 'name', 'gene', and 'locus_tag'. :type by: str :param fuzzy: If True, search becomes case-insensitive and will also find substrings - e.g. if fuzzy search is enabled, a search for 'gfp' would return a hit for a feature named 'GFP_seq'. :type fuzzy: bool :returns: A list of features matched by the search. :rtype: list ''' features = [] if fuzzy: fuzzy_term = term.lower() for feature in self.features: if fuzzy_term in feature.__getattribute__(by).lower(): features.append(feature) else: for feature in self.features: if feature.__getattribute__(by) == term: features.append(feature) return features
python
def select_features(self, term, by='name', fuzzy=False): '''Select features from the features list based on feature name, gene, or locus tag. :param term: Search term. :type term: str :param by: Feature attribute to search by. Options are 'name', 'gene', and 'locus_tag'. :type by: str :param fuzzy: If True, search becomes case-insensitive and will also find substrings - e.g. if fuzzy search is enabled, a search for 'gfp' would return a hit for a feature named 'GFP_seq'. :type fuzzy: bool :returns: A list of features matched by the search. :rtype: list ''' features = [] if fuzzy: fuzzy_term = term.lower() for feature in self.features: if fuzzy_term in feature.__getattribute__(by).lower(): features.append(feature) else: for feature in self.features: if feature.__getattribute__(by) == term: features.append(feature) return features
[ "def", "select_features", "(", "self", ",", "term", ",", "by", "=", "'name'", ",", "fuzzy", "=", "False", ")", ":", "features", "=", "[", "]", "if", "fuzzy", ":", "fuzzy_term", "=", "term", ".", "lower", "(", ")", "for", "feature", "in", "self", ".", "features", ":", "if", "fuzzy_term", "in", "feature", ".", "__getattribute__", "(", "by", ")", ".", "lower", "(", ")", ":", "features", ".", "append", "(", "feature", ")", "else", ":", "for", "feature", "in", "self", ".", "features", ":", "if", "feature", ".", "__getattribute__", "(", "by", ")", "==", "term", ":", "features", ".", "append", "(", "feature", ")", "return", "features" ]
Select features from the features list based on feature name, gene, or locus tag. :param term: Search term. :type term: str :param by: Feature attribute to search by. Options are 'name', 'gene', and 'locus_tag'. :type by: str :param fuzzy: If True, search becomes case-insensitive and will also find substrings - e.g. if fuzzy search is enabled, a search for 'gfp' would return a hit for a feature named 'GFP_seq'. :type fuzzy: bool :returns: A list of features matched by the search. :rtype: list
[ "Select", "features", "from", "the", "features", "list", "based", "on", "feature", "name", "gene", "or", "locus", "tag", ".", ":", "param", "term", ":", "Search", "term", ".", ":", "type", "term", ":", "str", ":", "param", "by", ":", "Feature", "attribute", "to", "search", "by", ".", "Options", "are", "name", "gene", "and", "locus_tag", ".", ":", "type", "by", ":", "str", ":", "param", "fuzzy", ":", "If", "True", "search", "becomes", "case", "-", "insensitive", "and", "will", "also", "find", "substrings", "-", "e", ".", "g", ".", "if", "fuzzy", "search", "is", "enabled", "a", "search", "for", "gfp", "would", "return", "a", "hit", "for", "a", "feature", "named", "GFP_seq", ".", ":", "type", "fuzzy", ":", "bool", ":", "returns", ":", "A", "list", "of", "features", "matched", "by", "the", "search", ".", ":", "rtype", ":", "list" ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L397-L424
klavinslab/coral
coral/sequence/_dna.py
DNA.to_feature
def to_feature(self, name=None, feature_type='misc_feature'): '''Create a feature from the current object. :param name: Name for the new feature. Must be specified if the DNA instance has no .name attribute. :type name: str :param feature_type: The type of feature (genbank standard). :type feature_type: str ''' if name is None: if not self.name: raise ValueError('name attribute missing from DNA instance' ' and arguments') name = self.name return Feature(name, start=0, stop=len(self), feature_type=feature_type)
python
def to_feature(self, name=None, feature_type='misc_feature'): '''Create a feature from the current object. :param name: Name for the new feature. Must be specified if the DNA instance has no .name attribute. :type name: str :param feature_type: The type of feature (genbank standard). :type feature_type: str ''' if name is None: if not self.name: raise ValueError('name attribute missing from DNA instance' ' and arguments') name = self.name return Feature(name, start=0, stop=len(self), feature_type=feature_type)
[ "def", "to_feature", "(", "self", ",", "name", "=", "None", ",", "feature_type", "=", "'misc_feature'", ")", ":", "if", "name", "is", "None", ":", "if", "not", "self", ".", "name", ":", "raise", "ValueError", "(", "'name attribute missing from DNA instance'", "' and arguments'", ")", "name", "=", "self", ".", "name", "return", "Feature", "(", "name", ",", "start", "=", "0", ",", "stop", "=", "len", "(", "self", ")", ",", "feature_type", "=", "feature_type", ")" ]
Create a feature from the current object. :param name: Name for the new feature. Must be specified if the DNA instance has no .name attribute. :type name: str :param feature_type: The type of feature (genbank standard). :type feature_type: str
[ "Create", "a", "feature", "from", "the", "current", "object", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L436-L452
klavinslab/coral
coral/sequence/_dna.py
RestrictionSite.cuts_outside
def cuts_outside(self): '''Report whether the enzyme cuts outside its recognition site. Cutting at the very end of the site returns True. :returns: Whether the enzyme will cut outside its recognition site. :rtype: bool ''' for index in self.cut_site: if index < 0 or index > len(self.recognition_site) + 1: return True return False
python
def cuts_outside(self): '''Report whether the enzyme cuts outside its recognition site. Cutting at the very end of the site returns True. :returns: Whether the enzyme will cut outside its recognition site. :rtype: bool ''' for index in self.cut_site: if index < 0 or index > len(self.recognition_site) + 1: return True return False
[ "def", "cuts_outside", "(", "self", ")", ":", "for", "index", "in", "self", ".", "cut_site", ":", "if", "index", "<", "0", "or", "index", ">", "len", "(", "self", ".", "recognition_site", ")", "+", "1", ":", "return", "True", "return", "False" ]
Report whether the enzyme cuts outside its recognition site. Cutting at the very end of the site returns True. :returns: Whether the enzyme will cut outside its recognition site. :rtype: bool
[ "Report", "whether", "the", "enzyme", "cuts", "outside", "its", "recognition", "site", ".", "Cutting", "at", "the", "very", "end", "of", "the", "site", "returns", "True", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L787-L798
klavinslab/coral
coral/sequence/_dna.py
Primer.copy
def copy(self): '''Generate a Primer copy. :returns: A safely-editable copy of the current primer. :rtype: coral.DNA ''' return type(self)(self.anneal, self.tm, overhang=self.overhang, name=self.name, note=self.note)
python
def copy(self): '''Generate a Primer copy. :returns: A safely-editable copy of the current primer. :rtype: coral.DNA ''' return type(self)(self.anneal, self.tm, overhang=self.overhang, name=self.name, note=self.note)
[ "def", "copy", "(", "self", ")", ":", "return", "type", "(", "self", ")", "(", "self", ".", "anneal", ",", "self", ".", "tm", ",", "overhang", "=", "self", ".", "overhang", ",", "name", "=", "self", ".", "name", ",", "note", "=", "self", ".", "note", ")" ]
Generate a Primer copy. :returns: A safely-editable copy of the current primer. :rtype: coral.DNA
[ "Generate", "a", "Primer", "copy", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L886-L894
klavinslab/coral
coral/analysis/_sequence/melting_temp.py
tm
def tm(seq, dna_conc=50, salt_conc=50, parameters='cloning'): '''Calculate nearest-neighbor melting temperature (Tm). :param seq: Sequence for which to calculate the tm. :type seq: coral.DNA :param dna_conc: DNA concentration in nM. :type dna_conc: float :param salt_conc: Salt concentration in mM. :type salt_conc: float :param parameters: Nearest-neighbor parameter set. Available options: 'breslauer': Breslauer86 parameters 'sugimoto': Sugimoto96 parameters 'santalucia96': SantaLucia96 parameters 'santalucia98': SantaLucia98 parameters 'cloning': breslauer without corrections 'cloning_sl98': santalucia98 fit to 'cloning' :type parameters: str :returns: Melting temperature (Tm) in °C. :rtype: float :raises: ValueError if parameter argument is invalid. ''' if parameters == 'breslauer': params = tm_params.BRESLAUER elif parameters == 'sugimoto': params = tm_params.SUGIMOTO elif parameters == 'santalucia96': params = tm_params.SANTALUCIA96 elif parameters == 'santalucia98' or parameters == 'cloning_sl98': params = tm_params.SANTALUCIA98 elif parameters == 'cloning': params = tm_params.CLONING else: raise ValueError('Unsupported parameter set.') # Thermodynamic parameters pars = {'delta_h': params['delta_h'], 'delta_s': params['delta_s']} pars_error = {'delta_h': params['delta_h_err'], 'delta_s': params['delta_s_err']} # Error corrections - done first for use of reverse_complement parameters if parameters == 'breslauer': deltas = breslauer_corrections(seq, pars_error) elif parameters == 'sugimoto': deltas = breslauer_corrections(seq, pars_error) elif parameters == 'santalucia96': deltas = breslauer_corrections(seq, pars_error) elif parameters == 'santalucia98' or parameters == 'cloning_sl98': deltas = santalucia98_corrections(seq, pars_error) elif parameters == 'cloning': deltas = breslauer_corrections(seq, pars_error) deltas[0] += 3.4 deltas[1] += 12.4 # Sum up the nearest-neighbor enthalpy and entropy seq = str(seq).upper() # TODO: catch more cases when alphabets expand if 'N' in seq: raise ValueError('Can\'t calculate Tm of an N base.') new_delt = _pair_deltas(seq, pars) deltas[0] += new_delt[0] deltas[1] += new_delt[1] # Unit corrections salt_conc /= 1e3 dna_conc /= 1e9 deltas[0] *= 1e3 # Universal gas constant (R) R = 1.9872 # Supposedly this is what dnamate does, but the output doesn't match theirs # melt = (-deltas[0] / (-deltas[1] + R * log(dna_conc / 4.0))) + # 16.6 * log(salt_conc) - 273.15 # return melt # Overall equation is supposedly: # sum{dH}/(sum{dS} + R ln(dna_conc/b)) - 273.15 # with salt corrections for the whole term (or for santalucia98, # salt corrections added to the dS term. # So far, implementing this as described does not give results that match # any calculator but Biopython's if parameters == 'breslauer' or parameters == 'cloning': numerator = -deltas[0] # Modified dna_conc denominator denominator = (-deltas[1]) + R * log(dna_conc / 16.0) # Modified Schildkraut-Lifson equation adjustment salt_adjustment = 16.6 * log(salt_conc) / log(10.0) melt = numerator / denominator + salt_adjustment - 273.15 elif parameters == 'santalucia98' or 'cloning_sl98': # TODO: dna_conc should be divided by 2.0 when dna_conc >> template # (like PCR) numerator = -deltas[0] # SantaLucia 98 salt correction salt_adjustment = 0.368 * (len(seq) - 1) * log(salt_conc) denominator = -deltas[1] + salt_adjustment + R * log(dna_conc / 4.0) melt = -deltas[0] / denominator - 273.15 elif parameters == 'santalucia96': # TODO: find a way to test whether the code below matches another # algorithm. It appears to be correct, but need to test it. numerator = -deltas[0] denominator = -deltas[1] + R * log(dna_conc / 4.0) # SantaLucia 96 salt correction salt_adjustment = 12.5 * log10(salt_conc) melt = numerator / denominator + salt_adjustment - 273.15 elif parameters == 'sugimoto': # TODO: the stuff below is untested and probably wrong numerator = -deltas[0] denominator = -deltas[1] + R * log(dna_conc / 4.0) # Sugimoto parameters were fit holding salt concentration constant # Salt correction can be chosen / ignored? Remove sugimoto set since # it's so similar to santalucia98? salt_correction = 16.6 * log10(salt_conc) melt = numerator / denominator + salt_correction - 273.15 if parameters == 'cloning_sl98': # Corrections to make santalucia98 method approximate cloning method. # May be even better for cloning with Phusion than 'cloning' method melt *= 1.27329212575 melt += -2.55585450119 return melt
python
def tm(seq, dna_conc=50, salt_conc=50, parameters='cloning'): '''Calculate nearest-neighbor melting temperature (Tm). :param seq: Sequence for which to calculate the tm. :type seq: coral.DNA :param dna_conc: DNA concentration in nM. :type dna_conc: float :param salt_conc: Salt concentration in mM. :type salt_conc: float :param parameters: Nearest-neighbor parameter set. Available options: 'breslauer': Breslauer86 parameters 'sugimoto': Sugimoto96 parameters 'santalucia96': SantaLucia96 parameters 'santalucia98': SantaLucia98 parameters 'cloning': breslauer without corrections 'cloning_sl98': santalucia98 fit to 'cloning' :type parameters: str :returns: Melting temperature (Tm) in °C. :rtype: float :raises: ValueError if parameter argument is invalid. ''' if parameters == 'breslauer': params = tm_params.BRESLAUER elif parameters == 'sugimoto': params = tm_params.SUGIMOTO elif parameters == 'santalucia96': params = tm_params.SANTALUCIA96 elif parameters == 'santalucia98' or parameters == 'cloning_sl98': params = tm_params.SANTALUCIA98 elif parameters == 'cloning': params = tm_params.CLONING else: raise ValueError('Unsupported parameter set.') # Thermodynamic parameters pars = {'delta_h': params['delta_h'], 'delta_s': params['delta_s']} pars_error = {'delta_h': params['delta_h_err'], 'delta_s': params['delta_s_err']} # Error corrections - done first for use of reverse_complement parameters if parameters == 'breslauer': deltas = breslauer_corrections(seq, pars_error) elif parameters == 'sugimoto': deltas = breslauer_corrections(seq, pars_error) elif parameters == 'santalucia96': deltas = breslauer_corrections(seq, pars_error) elif parameters == 'santalucia98' or parameters == 'cloning_sl98': deltas = santalucia98_corrections(seq, pars_error) elif parameters == 'cloning': deltas = breslauer_corrections(seq, pars_error) deltas[0] += 3.4 deltas[1] += 12.4 # Sum up the nearest-neighbor enthalpy and entropy seq = str(seq).upper() # TODO: catch more cases when alphabets expand if 'N' in seq: raise ValueError('Can\'t calculate Tm of an N base.') new_delt = _pair_deltas(seq, pars) deltas[0] += new_delt[0] deltas[1] += new_delt[1] # Unit corrections salt_conc /= 1e3 dna_conc /= 1e9 deltas[0] *= 1e3 # Universal gas constant (R) R = 1.9872 # Supposedly this is what dnamate does, but the output doesn't match theirs # melt = (-deltas[0] / (-deltas[1] + R * log(dna_conc / 4.0))) + # 16.6 * log(salt_conc) - 273.15 # return melt # Overall equation is supposedly: # sum{dH}/(sum{dS} + R ln(dna_conc/b)) - 273.15 # with salt corrections for the whole term (or for santalucia98, # salt corrections added to the dS term. # So far, implementing this as described does not give results that match # any calculator but Biopython's if parameters == 'breslauer' or parameters == 'cloning': numerator = -deltas[0] # Modified dna_conc denominator denominator = (-deltas[1]) + R * log(dna_conc / 16.0) # Modified Schildkraut-Lifson equation adjustment salt_adjustment = 16.6 * log(salt_conc) / log(10.0) melt = numerator / denominator + salt_adjustment - 273.15 elif parameters == 'santalucia98' or 'cloning_sl98': # TODO: dna_conc should be divided by 2.0 when dna_conc >> template # (like PCR) numerator = -deltas[0] # SantaLucia 98 salt correction salt_adjustment = 0.368 * (len(seq) - 1) * log(salt_conc) denominator = -deltas[1] + salt_adjustment + R * log(dna_conc / 4.0) melt = -deltas[0] / denominator - 273.15 elif parameters == 'santalucia96': # TODO: find a way to test whether the code below matches another # algorithm. It appears to be correct, but need to test it. numerator = -deltas[0] denominator = -deltas[1] + R * log(dna_conc / 4.0) # SantaLucia 96 salt correction salt_adjustment = 12.5 * log10(salt_conc) melt = numerator / denominator + salt_adjustment - 273.15 elif parameters == 'sugimoto': # TODO: the stuff below is untested and probably wrong numerator = -deltas[0] denominator = -deltas[1] + R * log(dna_conc / 4.0) # Sugimoto parameters were fit holding salt concentration constant # Salt correction can be chosen / ignored? Remove sugimoto set since # it's so similar to santalucia98? salt_correction = 16.6 * log10(salt_conc) melt = numerator / denominator + salt_correction - 273.15 if parameters == 'cloning_sl98': # Corrections to make santalucia98 method approximate cloning method. # May be even better for cloning with Phusion than 'cloning' method melt *= 1.27329212575 melt += -2.55585450119 return melt
[ "def", "tm", "(", "seq", ",", "dna_conc", "=", "50", ",", "salt_conc", "=", "50", ",", "parameters", "=", "'cloning'", ")", ":", "if", "parameters", "==", "'breslauer'", ":", "params", "=", "tm_params", ".", "BRESLAUER", "elif", "parameters", "==", "'sugimoto'", ":", "params", "=", "tm_params", ".", "SUGIMOTO", "elif", "parameters", "==", "'santalucia96'", ":", "params", "=", "tm_params", ".", "SANTALUCIA96", "elif", "parameters", "==", "'santalucia98'", "or", "parameters", "==", "'cloning_sl98'", ":", "params", "=", "tm_params", ".", "SANTALUCIA98", "elif", "parameters", "==", "'cloning'", ":", "params", "=", "tm_params", ".", "CLONING", "else", ":", "raise", "ValueError", "(", "'Unsupported parameter set.'", ")", "# Thermodynamic parameters", "pars", "=", "{", "'delta_h'", ":", "params", "[", "'delta_h'", "]", ",", "'delta_s'", ":", "params", "[", "'delta_s'", "]", "}", "pars_error", "=", "{", "'delta_h'", ":", "params", "[", "'delta_h_err'", "]", ",", "'delta_s'", ":", "params", "[", "'delta_s_err'", "]", "}", "# Error corrections - done first for use of reverse_complement parameters", "if", "parameters", "==", "'breslauer'", ":", "deltas", "=", "breslauer_corrections", "(", "seq", ",", "pars_error", ")", "elif", "parameters", "==", "'sugimoto'", ":", "deltas", "=", "breslauer_corrections", "(", "seq", ",", "pars_error", ")", "elif", "parameters", "==", "'santalucia96'", ":", "deltas", "=", "breslauer_corrections", "(", "seq", ",", "pars_error", ")", "elif", "parameters", "==", "'santalucia98'", "or", "parameters", "==", "'cloning_sl98'", ":", "deltas", "=", "santalucia98_corrections", "(", "seq", ",", "pars_error", ")", "elif", "parameters", "==", "'cloning'", ":", "deltas", "=", "breslauer_corrections", "(", "seq", ",", "pars_error", ")", "deltas", "[", "0", "]", "+=", "3.4", "deltas", "[", "1", "]", "+=", "12.4", "# Sum up the nearest-neighbor enthalpy and entropy", "seq", "=", "str", "(", "seq", ")", ".", "upper", "(", ")", "# TODO: catch more cases when alphabets expand", "if", "'N'", "in", "seq", ":", "raise", "ValueError", "(", "'Can\\'t calculate Tm of an N base.'", ")", "new_delt", "=", "_pair_deltas", "(", "seq", ",", "pars", ")", "deltas", "[", "0", "]", "+=", "new_delt", "[", "0", "]", "deltas", "[", "1", "]", "+=", "new_delt", "[", "1", "]", "# Unit corrections", "salt_conc", "/=", "1e3", "dna_conc", "/=", "1e9", "deltas", "[", "0", "]", "*=", "1e3", "# Universal gas constant (R)", "R", "=", "1.9872", "# Supposedly this is what dnamate does, but the output doesn't match theirs", "# melt = (-deltas[0] / (-deltas[1] + R * log(dna_conc / 4.0))) +", "# 16.6 * log(salt_conc) - 273.15", "# return melt", "# Overall equation is supposedly:", "# sum{dH}/(sum{dS} + R ln(dna_conc/b)) - 273.15", "# with salt corrections for the whole term (or for santalucia98,", "# salt corrections added to the dS term.", "# So far, implementing this as described does not give results that match", "# any calculator but Biopython's", "if", "parameters", "==", "'breslauer'", "or", "parameters", "==", "'cloning'", ":", "numerator", "=", "-", "deltas", "[", "0", "]", "# Modified dna_conc denominator", "denominator", "=", "(", "-", "deltas", "[", "1", "]", ")", "+", "R", "*", "log", "(", "dna_conc", "/", "16.0", ")", "# Modified Schildkraut-Lifson equation adjustment", "salt_adjustment", "=", "16.6", "*", "log", "(", "salt_conc", ")", "/", "log", "(", "10.0", ")", "melt", "=", "numerator", "/", "denominator", "+", "salt_adjustment", "-", "273.15", "elif", "parameters", "==", "'santalucia98'", "or", "'cloning_sl98'", ":", "# TODO: dna_conc should be divided by 2.0 when dna_conc >> template", "# (like PCR)", "numerator", "=", "-", "deltas", "[", "0", "]", "# SantaLucia 98 salt correction", "salt_adjustment", "=", "0.368", "*", "(", "len", "(", "seq", ")", "-", "1", ")", "*", "log", "(", "salt_conc", ")", "denominator", "=", "-", "deltas", "[", "1", "]", "+", "salt_adjustment", "+", "R", "*", "log", "(", "dna_conc", "/", "4.0", ")", "melt", "=", "-", "deltas", "[", "0", "]", "/", "denominator", "-", "273.15", "elif", "parameters", "==", "'santalucia96'", ":", "# TODO: find a way to test whether the code below matches another", "# algorithm. It appears to be correct, but need to test it.", "numerator", "=", "-", "deltas", "[", "0", "]", "denominator", "=", "-", "deltas", "[", "1", "]", "+", "R", "*", "log", "(", "dna_conc", "/", "4.0", ")", "# SantaLucia 96 salt correction", "salt_adjustment", "=", "12.5", "*", "log10", "(", "salt_conc", ")", "melt", "=", "numerator", "/", "denominator", "+", "salt_adjustment", "-", "273.15", "elif", "parameters", "==", "'sugimoto'", ":", "# TODO: the stuff below is untested and probably wrong", "numerator", "=", "-", "deltas", "[", "0", "]", "denominator", "=", "-", "deltas", "[", "1", "]", "+", "R", "*", "log", "(", "dna_conc", "/", "4.0", ")", "# Sugimoto parameters were fit holding salt concentration constant", "# Salt correction can be chosen / ignored? Remove sugimoto set since", "# it's so similar to santalucia98?", "salt_correction", "=", "16.6", "*", "log10", "(", "salt_conc", ")", "melt", "=", "numerator", "/", "denominator", "+", "salt_correction", "-", "273.15", "if", "parameters", "==", "'cloning_sl98'", ":", "# Corrections to make santalucia98 method approximate cloning method.", "# May be even better for cloning with Phusion than 'cloning' method", "melt", "*=", "1.27329212575", "melt", "+=", "-", "2.55585450119", "return", "melt" ]
Calculate nearest-neighbor melting temperature (Tm). :param seq: Sequence for which to calculate the tm. :type seq: coral.DNA :param dna_conc: DNA concentration in nM. :type dna_conc: float :param salt_conc: Salt concentration in mM. :type salt_conc: float :param parameters: Nearest-neighbor parameter set. Available options: 'breslauer': Breslauer86 parameters 'sugimoto': Sugimoto96 parameters 'santalucia96': SantaLucia96 parameters 'santalucia98': SantaLucia98 parameters 'cloning': breslauer without corrections 'cloning_sl98': santalucia98 fit to 'cloning' :type parameters: str :returns: Melting temperature (Tm) in °C. :rtype: float :raises: ValueError if parameter argument is invalid.
[ "Calculate", "nearest", "-", "neighbor", "melting", "temperature", "(", "Tm", ")", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequence/melting_temp.py#L22-L144
klavinslab/coral
coral/analysis/_sequence/melting_temp.py
_pair_deltas
def _pair_deltas(seq, pars): '''Add up nearest-neighbor parameters for a given sequence. :param seq: DNA sequence for which to sum nearest neighbors :type seq: str :param pars: parameter set to use :type pars: dict :returns: nearest-neighbor delta_H and delta_S sums. :rtype: tuple of floats ''' delta0 = 0 delta1 = 0 for i in range(len(seq) - 1): curchar = seq[i:i + 2] delta0 += pars['delta_h'][curchar] delta1 += pars['delta_s'][curchar] return delta0, delta1
python
def _pair_deltas(seq, pars): '''Add up nearest-neighbor parameters for a given sequence. :param seq: DNA sequence for which to sum nearest neighbors :type seq: str :param pars: parameter set to use :type pars: dict :returns: nearest-neighbor delta_H and delta_S sums. :rtype: tuple of floats ''' delta0 = 0 delta1 = 0 for i in range(len(seq) - 1): curchar = seq[i:i + 2] delta0 += pars['delta_h'][curchar] delta1 += pars['delta_s'][curchar] return delta0, delta1
[ "def", "_pair_deltas", "(", "seq", ",", "pars", ")", ":", "delta0", "=", "0", "delta1", "=", "0", "for", "i", "in", "range", "(", "len", "(", "seq", ")", "-", "1", ")", ":", "curchar", "=", "seq", "[", "i", ":", "i", "+", "2", "]", "delta0", "+=", "pars", "[", "'delta_h'", "]", "[", "curchar", "]", "delta1", "+=", "pars", "[", "'delta_s'", "]", "[", "curchar", "]", "return", "delta0", ",", "delta1" ]
Add up nearest-neighbor parameters for a given sequence. :param seq: DNA sequence for which to sum nearest neighbors :type seq: str :param pars: parameter set to use :type pars: dict :returns: nearest-neighbor delta_H and delta_S sums. :rtype: tuple of floats
[ "Add", "up", "nearest", "-", "neighbor", "parameters", "for", "a", "given", "sequence", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequence/melting_temp.py#L147-L164
klavinslab/coral
coral/analysis/_sequence/melting_temp.py
breslauer_corrections
def breslauer_corrections(seq, pars_error): '''Sum corrections for Breslauer '84 method. :param seq: sequence for which to calculate corrections. :type seq: str :param pars_error: dictionary of error corrections :type pars_error: dict :returns: Corrected delta_H and delta_S parameters :rtype: list of floats ''' deltas_corr = [0, 0] contains_gc = 'G' in str(seq) or 'C' in str(seq) only_at = str(seq).count('A') + str(seq).count('T') == len(seq) symmetric = seq == seq.reverse_complement() terminal_t = str(seq)[0] == 'T' + str(seq)[-1] == 'T' for i, delta in enumerate(['delta_h', 'delta_s']): if contains_gc: deltas_corr[i] += pars_error[delta]['anyGC'] if only_at: deltas_corr[i] += pars_error[delta]['onlyAT'] if symmetric: deltas_corr[i] += pars_error[delta]['symmetry'] if terminal_t and delta == 'delta_h': deltas_corr[i] += pars_error[delta]['terminalT'] * terminal_t return deltas_corr
python
def breslauer_corrections(seq, pars_error): '''Sum corrections for Breslauer '84 method. :param seq: sequence for which to calculate corrections. :type seq: str :param pars_error: dictionary of error corrections :type pars_error: dict :returns: Corrected delta_H and delta_S parameters :rtype: list of floats ''' deltas_corr = [0, 0] contains_gc = 'G' in str(seq) or 'C' in str(seq) only_at = str(seq).count('A') + str(seq).count('T') == len(seq) symmetric = seq == seq.reverse_complement() terminal_t = str(seq)[0] == 'T' + str(seq)[-1] == 'T' for i, delta in enumerate(['delta_h', 'delta_s']): if contains_gc: deltas_corr[i] += pars_error[delta]['anyGC'] if only_at: deltas_corr[i] += pars_error[delta]['onlyAT'] if symmetric: deltas_corr[i] += pars_error[delta]['symmetry'] if terminal_t and delta == 'delta_h': deltas_corr[i] += pars_error[delta]['terminalT'] * terminal_t return deltas_corr
[ "def", "breslauer_corrections", "(", "seq", ",", "pars_error", ")", ":", "deltas_corr", "=", "[", "0", ",", "0", "]", "contains_gc", "=", "'G'", "in", "str", "(", "seq", ")", "or", "'C'", "in", "str", "(", "seq", ")", "only_at", "=", "str", "(", "seq", ")", ".", "count", "(", "'A'", ")", "+", "str", "(", "seq", ")", ".", "count", "(", "'T'", ")", "==", "len", "(", "seq", ")", "symmetric", "=", "seq", "==", "seq", ".", "reverse_complement", "(", ")", "terminal_t", "=", "str", "(", "seq", ")", "[", "0", "]", "==", "'T'", "+", "str", "(", "seq", ")", "[", "-", "1", "]", "==", "'T'", "for", "i", ",", "delta", "in", "enumerate", "(", "[", "'delta_h'", ",", "'delta_s'", "]", ")", ":", "if", "contains_gc", ":", "deltas_corr", "[", "i", "]", "+=", "pars_error", "[", "delta", "]", "[", "'anyGC'", "]", "if", "only_at", ":", "deltas_corr", "[", "i", "]", "+=", "pars_error", "[", "delta", "]", "[", "'onlyAT'", "]", "if", "symmetric", ":", "deltas_corr", "[", "i", "]", "+=", "pars_error", "[", "delta", "]", "[", "'symmetry'", "]", "if", "terminal_t", "and", "delta", "==", "'delta_h'", ":", "deltas_corr", "[", "i", "]", "+=", "pars_error", "[", "delta", "]", "[", "'terminalT'", "]", "*", "terminal_t", "return", "deltas_corr" ]
Sum corrections for Breslauer '84 method. :param seq: sequence for which to calculate corrections. :type seq: str :param pars_error: dictionary of error corrections :type pars_error: dict :returns: Corrected delta_H and delta_S parameters :rtype: list of floats
[ "Sum", "corrections", "for", "Breslauer", "84", "method", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequence/melting_temp.py#L167-L193
klavinslab/coral
coral/analysis/_sequence/melting_temp.py
santalucia98_corrections
def santalucia98_corrections(seq, pars_error): '''Sum corrections for SantaLucia '98 method (unified parameters). :param seq: sequence for which to calculate corrections. :type seq: str :param pars_error: dictionary of error corrections :type pars_error: dict :returns: Corrected delta_H and delta_S parameters :rtype: list of floats ''' deltas_corr = [0, 0] first = str(seq)[0] last = str(seq)[-1] start_gc = first == 'G' or first == 'C' start_at = first == 'A' or first == 'T' end_gc = last == 'G' or last == 'C' end_at = last == 'A' or last == 'T' init_gc = start_gc + end_gc init_at = start_at + end_at symmetric = seq == seq.reverse_complement() for i, delta in enumerate(['delta_h', 'delta_s']): deltas_corr[i] += init_gc * pars_error[delta]['initGC'] deltas_corr[i] += init_at * pars_error[delta]['initAT'] if symmetric: deltas_corr[i] += pars_error[delta]['symmetry'] return deltas_corr
python
def santalucia98_corrections(seq, pars_error): '''Sum corrections for SantaLucia '98 method (unified parameters). :param seq: sequence for which to calculate corrections. :type seq: str :param pars_error: dictionary of error corrections :type pars_error: dict :returns: Corrected delta_H and delta_S parameters :rtype: list of floats ''' deltas_corr = [0, 0] first = str(seq)[0] last = str(seq)[-1] start_gc = first == 'G' or first == 'C' start_at = first == 'A' or first == 'T' end_gc = last == 'G' or last == 'C' end_at = last == 'A' or last == 'T' init_gc = start_gc + end_gc init_at = start_at + end_at symmetric = seq == seq.reverse_complement() for i, delta in enumerate(['delta_h', 'delta_s']): deltas_corr[i] += init_gc * pars_error[delta]['initGC'] deltas_corr[i] += init_at * pars_error[delta]['initAT'] if symmetric: deltas_corr[i] += pars_error[delta]['symmetry'] return deltas_corr
[ "def", "santalucia98_corrections", "(", "seq", ",", "pars_error", ")", ":", "deltas_corr", "=", "[", "0", ",", "0", "]", "first", "=", "str", "(", "seq", ")", "[", "0", "]", "last", "=", "str", "(", "seq", ")", "[", "-", "1", "]", "start_gc", "=", "first", "==", "'G'", "or", "first", "==", "'C'", "start_at", "=", "first", "==", "'A'", "or", "first", "==", "'T'", "end_gc", "=", "last", "==", "'G'", "or", "last", "==", "'C'", "end_at", "=", "last", "==", "'A'", "or", "last", "==", "'T'", "init_gc", "=", "start_gc", "+", "end_gc", "init_at", "=", "start_at", "+", "end_at", "symmetric", "=", "seq", "==", "seq", ".", "reverse_complement", "(", ")", "for", "i", ",", "delta", "in", "enumerate", "(", "[", "'delta_h'", ",", "'delta_s'", "]", ")", ":", "deltas_corr", "[", "i", "]", "+=", "init_gc", "*", "pars_error", "[", "delta", "]", "[", "'initGC'", "]", "deltas_corr", "[", "i", "]", "+=", "init_at", "*", "pars_error", "[", "delta", "]", "[", "'initAT'", "]", "if", "symmetric", ":", "deltas_corr", "[", "i", "]", "+=", "pars_error", "[", "delta", "]", "[", "'symmetry'", "]", "return", "deltas_corr" ]
Sum corrections for SantaLucia '98 method (unified parameters). :param seq: sequence for which to calculate corrections. :type seq: str :param pars_error: dictionary of error corrections :type pars_error: dict :returns: Corrected delta_H and delta_S parameters :rtype: list of floats
[ "Sum", "corrections", "for", "SantaLucia", "98", "method", "(", "unified", "parameters", ")", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequence/melting_temp.py#L196-L225
klavinslab/coral
coral/analysis/_sequencing/mafft.py
MAFFT
def MAFFT(sequences, gap_open=1.53, gap_extension=0.0, retree=2): '''A Coral wrapper for the MAFFT command line multiple sequence aligner. :param sequences: A list of sequences to align. :type sequences: List of homogeneous sequences (all DNA, or all RNA, etc.) :param gap_open: --op (gap open) penalty in MAFFT cli. :type gap_open: float :param gap_extension: --ep (gap extension) penalty in MAFFT cli. :type gap_extension: float :param retree: Number of times to build the guide tree. :type retree: int ''' arguments = ['mafft'] arguments += ['--op', str(gap_open)] arguments += ['--ep', str(gap_extension)] arguments += ['--retree', str(retree)] arguments.append('input.fasta') tempdir = tempfile.mkdtemp() try: with open(os.path.join(tempdir, 'input.fasta'), 'w') as f: for i, sequence in enumerate(sequences): if hasattr(sequence, 'name'): name = sequence.name else: name = 'sequence{}'.format(i) f.write('>{}\n'.format(name)) f.write(str(sequence) + '\n') process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=open(os.devnull, 'w'), cwd=tempdir) stdout = process.communicate()[0] finally: shutil.rmtree(tempdir) # Process stdout into something downstream process can use records = stdout.split('>') # First line is now blank records.pop(0) aligned_list = [] for record in records: lines = record.split('\n') name = lines.pop(0) aligned_list.append(coral.DNA(''.join(lines))) return aligned_list
python
def MAFFT(sequences, gap_open=1.53, gap_extension=0.0, retree=2): '''A Coral wrapper for the MAFFT command line multiple sequence aligner. :param sequences: A list of sequences to align. :type sequences: List of homogeneous sequences (all DNA, or all RNA, etc.) :param gap_open: --op (gap open) penalty in MAFFT cli. :type gap_open: float :param gap_extension: --ep (gap extension) penalty in MAFFT cli. :type gap_extension: float :param retree: Number of times to build the guide tree. :type retree: int ''' arguments = ['mafft'] arguments += ['--op', str(gap_open)] arguments += ['--ep', str(gap_extension)] arguments += ['--retree', str(retree)] arguments.append('input.fasta') tempdir = tempfile.mkdtemp() try: with open(os.path.join(tempdir, 'input.fasta'), 'w') as f: for i, sequence in enumerate(sequences): if hasattr(sequence, 'name'): name = sequence.name else: name = 'sequence{}'.format(i) f.write('>{}\n'.format(name)) f.write(str(sequence) + '\n') process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=open(os.devnull, 'w'), cwd=tempdir) stdout = process.communicate()[0] finally: shutil.rmtree(tempdir) # Process stdout into something downstream process can use records = stdout.split('>') # First line is now blank records.pop(0) aligned_list = [] for record in records: lines = record.split('\n') name = lines.pop(0) aligned_list.append(coral.DNA(''.join(lines))) return aligned_list
[ "def", "MAFFT", "(", "sequences", ",", "gap_open", "=", "1.53", ",", "gap_extension", "=", "0.0", ",", "retree", "=", "2", ")", ":", "arguments", "=", "[", "'mafft'", "]", "arguments", "+=", "[", "'--op'", ",", "str", "(", "gap_open", ")", "]", "arguments", "+=", "[", "'--ep'", ",", "str", "(", "gap_extension", ")", "]", "arguments", "+=", "[", "'--retree'", ",", "str", "(", "retree", ")", "]", "arguments", ".", "append", "(", "'input.fasta'", ")", "tempdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "try", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "tempdir", ",", "'input.fasta'", ")", ",", "'w'", ")", "as", "f", ":", "for", "i", ",", "sequence", "in", "enumerate", "(", "sequences", ")", ":", "if", "hasattr", "(", "sequence", ",", "'name'", ")", ":", "name", "=", "sequence", ".", "name", "else", ":", "name", "=", "'sequence{}'", ".", "format", "(", "i", ")", "f", ".", "write", "(", "'>{}\\n'", ".", "format", "(", "name", ")", ")", "f", ".", "write", "(", "str", "(", "sequence", ")", "+", "'\\n'", ")", "process", "=", "subprocess", ".", "Popen", "(", "arguments", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "open", "(", "os", ".", "devnull", ",", "'w'", ")", ",", "cwd", "=", "tempdir", ")", "stdout", "=", "process", ".", "communicate", "(", ")", "[", "0", "]", "finally", ":", "shutil", ".", "rmtree", "(", "tempdir", ")", "# Process stdout into something downstream process can use", "records", "=", "stdout", ".", "split", "(", "'>'", ")", "# First line is now blank", "records", ".", "pop", "(", "0", ")", "aligned_list", "=", "[", "]", "for", "record", "in", "records", ":", "lines", "=", "record", ".", "split", "(", "'\\n'", ")", "name", "=", "lines", ".", "pop", "(", "0", ")", "aligned_list", ".", "append", "(", "coral", ".", "DNA", "(", "''", ".", "join", "(", "lines", ")", ")", ")", "return", "aligned_list" ]
A Coral wrapper for the MAFFT command line multiple sequence aligner. :param sequences: A list of sequences to align. :type sequences: List of homogeneous sequences (all DNA, or all RNA, etc.) :param gap_open: --op (gap open) penalty in MAFFT cli. :type gap_open: float :param gap_extension: --ep (gap extension) penalty in MAFFT cli. :type gap_extension: float :param retree: Number of times to build the guide tree. :type retree: int
[ "A", "Coral", "wrapper", "for", "the", "MAFFT", "command", "line", "multiple", "sequence", "aligner", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequencing/mafft.py#L9-L55
klavinslab/coral
coral/analysis/_sequence/repeats.py
repeats
def repeats(seq, size): '''Count times that a sequence of a certain size is repeated. :param seq: Input sequence. :type seq: coral.DNA or coral.RNA :param size: Size of the repeat to count. :type size: int :returns: Occurrences of repeats and how many :rtype: tuple of the matched sequence and how many times it occurs ''' seq = str(seq) n_mers = [seq[i:i + size] for i in range(len(seq) - size + 1)] counted = Counter(n_mers) # No one cares about patterns that appear once, so exclude them found_repeats = [(key, value) for key, value in counted.iteritems() if value > 1] return found_repeats
python
def repeats(seq, size): '''Count times that a sequence of a certain size is repeated. :param seq: Input sequence. :type seq: coral.DNA or coral.RNA :param size: Size of the repeat to count. :type size: int :returns: Occurrences of repeats and how many :rtype: tuple of the matched sequence and how many times it occurs ''' seq = str(seq) n_mers = [seq[i:i + size] for i in range(len(seq) - size + 1)] counted = Counter(n_mers) # No one cares about patterns that appear once, so exclude them found_repeats = [(key, value) for key, value in counted.iteritems() if value > 1] return found_repeats
[ "def", "repeats", "(", "seq", ",", "size", ")", ":", "seq", "=", "str", "(", "seq", ")", "n_mers", "=", "[", "seq", "[", "i", ":", "i", "+", "size", "]", "for", "i", "in", "range", "(", "len", "(", "seq", ")", "-", "size", "+", "1", ")", "]", "counted", "=", "Counter", "(", "n_mers", ")", "# No one cares about patterns that appear once, so exclude them", "found_repeats", "=", "[", "(", "key", ",", "value", ")", "for", "key", ",", "value", "in", "counted", ".", "iteritems", "(", ")", "if", "value", ">", "1", "]", "return", "found_repeats" ]
Count times that a sequence of a certain size is repeated. :param seq: Input sequence. :type seq: coral.DNA or coral.RNA :param size: Size of the repeat to count. :type size: int :returns: Occurrences of repeats and how many :rtype: tuple of the matched sequence and how many times it occurs
[ "Count", "times", "that", "a", "sequence", "of", "a", "certain", "size", "is", "repeated", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequence/repeats.py#L5-L22
klavinslab/coral
coral/reaction/_gibson.py
gibson
def gibson(seq_list, linear=False, homology=10, tm=63.0): '''Simulate a Gibson reaction. :param seq_list: list of DNA sequences to Gibson :type seq_list: list of coral.DNA :param linear: Attempt to produce linear, rather than circular, fragment from input fragments. :type linear: bool :param homology_min: minimum bp of homology allowed :type homology_min: int :param tm: Minimum tm of overlaps :type tm: float :returns: coral.reaction.Gibson instance. :raises: ValueError if any input sequences are circular DNA. ''' # FIXME: Preserve features in overlap # TODO: set a max length? # TODO: add 'expected' keyword argument somewhere to automate # validation # Remove any redundant (identical) sequences seq_list = list(set(seq_list)) for seq in seq_list: if seq.circular: raise ValueError('Input sequences must be linear.') # Copy input list working_list = [s.copy() for s in seq_list] # Attempt to fuse fragments together until only one is left while len(working_list) > 1: working_list = _find_fuse_next(working_list, homology, tm) if not linear: # Fuse the final fragment to itself working_list = _fuse_last(working_list, homology, tm) # Clear features working_list[0].features = [] return _annotate_features(working_list[0], seq_list)
python
def gibson(seq_list, linear=False, homology=10, tm=63.0): '''Simulate a Gibson reaction. :param seq_list: list of DNA sequences to Gibson :type seq_list: list of coral.DNA :param linear: Attempt to produce linear, rather than circular, fragment from input fragments. :type linear: bool :param homology_min: minimum bp of homology allowed :type homology_min: int :param tm: Minimum tm of overlaps :type tm: float :returns: coral.reaction.Gibson instance. :raises: ValueError if any input sequences are circular DNA. ''' # FIXME: Preserve features in overlap # TODO: set a max length? # TODO: add 'expected' keyword argument somewhere to automate # validation # Remove any redundant (identical) sequences seq_list = list(set(seq_list)) for seq in seq_list: if seq.circular: raise ValueError('Input sequences must be linear.') # Copy input list working_list = [s.copy() for s in seq_list] # Attempt to fuse fragments together until only one is left while len(working_list) > 1: working_list = _find_fuse_next(working_list, homology, tm) if not linear: # Fuse the final fragment to itself working_list = _fuse_last(working_list, homology, tm) # Clear features working_list[0].features = [] return _annotate_features(working_list[0], seq_list)
[ "def", "gibson", "(", "seq_list", ",", "linear", "=", "False", ",", "homology", "=", "10", ",", "tm", "=", "63.0", ")", ":", "# FIXME: Preserve features in overlap", "# TODO: set a max length?", "# TODO: add 'expected' keyword argument somewhere to automate", "# validation", "# Remove any redundant (identical) sequences", "seq_list", "=", "list", "(", "set", "(", "seq_list", ")", ")", "for", "seq", "in", "seq_list", ":", "if", "seq", ".", "circular", ":", "raise", "ValueError", "(", "'Input sequences must be linear.'", ")", "# Copy input list", "working_list", "=", "[", "s", ".", "copy", "(", ")", "for", "s", "in", "seq_list", "]", "# Attempt to fuse fragments together until only one is left", "while", "len", "(", "working_list", ")", ">", "1", ":", "working_list", "=", "_find_fuse_next", "(", "working_list", ",", "homology", ",", "tm", ")", "if", "not", "linear", ":", "# Fuse the final fragment to itself", "working_list", "=", "_fuse_last", "(", "working_list", ",", "homology", ",", "tm", ")", "# Clear features", "working_list", "[", "0", "]", ".", "features", "=", "[", "]", "return", "_annotate_features", "(", "working_list", "[", "0", "]", ",", "seq_list", ")" ]
Simulate a Gibson reaction. :param seq_list: list of DNA sequences to Gibson :type seq_list: list of coral.DNA :param linear: Attempt to produce linear, rather than circular, fragment from input fragments. :type linear: bool :param homology_min: minimum bp of homology allowed :type homology_min: int :param tm: Minimum tm of overlaps :type tm: float :returns: coral.reaction.Gibson instance. :raises: ValueError if any input sequences are circular DNA.
[ "Simulate", "a", "Gibson", "reaction", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_gibson.py#L21-L60
klavinslab/coral
coral/reaction/_gibson.py
_find_fuse_next
def _find_fuse_next(working_list, homology, tm): '''Find the next sequence to fuse, and fuse it (or raise exception). :param homology: length of terminal homology in bp :type homology: int :raises: AmbiguousGibsonError if there is more than one way for the fragment ends to combine. GibsonOverlapError if no homology match can be found. ''' # 1. Take the first sequence and find all matches # Get graphs: # a) pattern watson : targets watson # b) pattern watson : targets crick # c) pattern crick: targets watson # d) pattern crick: targets crick pattern = working_list[0] targets = working_list[1:] # Output graph nodes of terminal binders: # (destination, size, strand1, strand2) def graph_strands(strand1, strand2): graph = [] for i, target in enumerate(targets): matchlen = homology_report(pattern, target, strand1, strand2, cutoff=homology, min_tm=tm) if matchlen: graph.append((i, matchlen, strand1, strand2)) return graph graph_ww = graph_strands('w', 'w') graph_wc = graph_strands('w', 'c') graph_cw = graph_strands('c', 'w') graph_cc = graph_strands('c', 'c') graphs_w = graph_ww + graph_wc graphs_c = graph_cw + graph_cc graphs = graphs_w + graphs_c # 2. See if there's more than one result on a strand. # If so, throw an exception. if len(graphs_w) > 1 or len(graphs_c) > 1: raise AmbiguousGibsonError('multiple compatible ends.') if len(graphs_w) == len(graphs_c) == 0: raise GibsonOverlapError('Failed to find compatible Gibson ends.') # 3. There must be one result. Where is it? # If there's one result on each strand, go with the one that matches the # pattern watson strand (will occur first - index 0) match = graphs[0] # 4. Combine pieces together # 4a. Orient pattern sequence if match[2] == 'c': left_side = pattern.reverse_complement() else: left_side = pattern # 4b. Orient target sequence if match[3] == 'w': right_side = working_list.pop(match[0] + 1).reverse_complement() else: right_side = working_list.pop(match[0] + 1) working_list[0] = left_side + right_side[match[1]:] return working_list
python
def _find_fuse_next(working_list, homology, tm): '''Find the next sequence to fuse, and fuse it (or raise exception). :param homology: length of terminal homology in bp :type homology: int :raises: AmbiguousGibsonError if there is more than one way for the fragment ends to combine. GibsonOverlapError if no homology match can be found. ''' # 1. Take the first sequence and find all matches # Get graphs: # a) pattern watson : targets watson # b) pattern watson : targets crick # c) pattern crick: targets watson # d) pattern crick: targets crick pattern = working_list[0] targets = working_list[1:] # Output graph nodes of terminal binders: # (destination, size, strand1, strand2) def graph_strands(strand1, strand2): graph = [] for i, target in enumerate(targets): matchlen = homology_report(pattern, target, strand1, strand2, cutoff=homology, min_tm=tm) if matchlen: graph.append((i, matchlen, strand1, strand2)) return graph graph_ww = graph_strands('w', 'w') graph_wc = graph_strands('w', 'c') graph_cw = graph_strands('c', 'w') graph_cc = graph_strands('c', 'c') graphs_w = graph_ww + graph_wc graphs_c = graph_cw + graph_cc graphs = graphs_w + graphs_c # 2. See if there's more than one result on a strand. # If so, throw an exception. if len(graphs_w) > 1 or len(graphs_c) > 1: raise AmbiguousGibsonError('multiple compatible ends.') if len(graphs_w) == len(graphs_c) == 0: raise GibsonOverlapError('Failed to find compatible Gibson ends.') # 3. There must be one result. Where is it? # If there's one result on each strand, go with the one that matches the # pattern watson strand (will occur first - index 0) match = graphs[0] # 4. Combine pieces together # 4a. Orient pattern sequence if match[2] == 'c': left_side = pattern.reverse_complement() else: left_side = pattern # 4b. Orient target sequence if match[3] == 'w': right_side = working_list.pop(match[0] + 1).reverse_complement() else: right_side = working_list.pop(match[0] + 1) working_list[0] = left_side + right_side[match[1]:] return working_list
[ "def", "_find_fuse_next", "(", "working_list", ",", "homology", ",", "tm", ")", ":", "# 1. Take the first sequence and find all matches", "# Get graphs:", "# a) pattern watson : targets watson", "# b) pattern watson : targets crick", "# c) pattern crick: targets watson", "# d) pattern crick: targets crick", "pattern", "=", "working_list", "[", "0", "]", "targets", "=", "working_list", "[", "1", ":", "]", "# Output graph nodes of terminal binders:", "# (destination, size, strand1, strand2)", "def", "graph_strands", "(", "strand1", ",", "strand2", ")", ":", "graph", "=", "[", "]", "for", "i", ",", "target", "in", "enumerate", "(", "targets", ")", ":", "matchlen", "=", "homology_report", "(", "pattern", ",", "target", ",", "strand1", ",", "strand2", ",", "cutoff", "=", "homology", ",", "min_tm", "=", "tm", ")", "if", "matchlen", ":", "graph", ".", "append", "(", "(", "i", ",", "matchlen", ",", "strand1", ",", "strand2", ")", ")", "return", "graph", "graph_ww", "=", "graph_strands", "(", "'w'", ",", "'w'", ")", "graph_wc", "=", "graph_strands", "(", "'w'", ",", "'c'", ")", "graph_cw", "=", "graph_strands", "(", "'c'", ",", "'w'", ")", "graph_cc", "=", "graph_strands", "(", "'c'", ",", "'c'", ")", "graphs_w", "=", "graph_ww", "+", "graph_wc", "graphs_c", "=", "graph_cw", "+", "graph_cc", "graphs", "=", "graphs_w", "+", "graphs_c", "# 2. See if there's more than one result on a strand.", "# If so, throw an exception.", "if", "len", "(", "graphs_w", ")", ">", "1", "or", "len", "(", "graphs_c", ")", ">", "1", ":", "raise", "AmbiguousGibsonError", "(", "'multiple compatible ends.'", ")", "if", "len", "(", "graphs_w", ")", "==", "len", "(", "graphs_c", ")", "==", "0", ":", "raise", "GibsonOverlapError", "(", "'Failed to find compatible Gibson ends.'", ")", "# 3. There must be one result. Where is it?", "# If there's one result on each strand, go with the one that matches the", "# pattern watson strand (will occur first - index 0)", "match", "=", "graphs", "[", "0", "]", "# 4. Combine pieces together", "# 4a. Orient pattern sequence", "if", "match", "[", "2", "]", "==", "'c'", ":", "left_side", "=", "pattern", ".", "reverse_complement", "(", ")", "else", ":", "left_side", "=", "pattern", "# 4b. Orient target sequence", "if", "match", "[", "3", "]", "==", "'w'", ":", "right_side", "=", "working_list", ".", "pop", "(", "match", "[", "0", "]", "+", "1", ")", ".", "reverse_complement", "(", ")", "else", ":", "right_side", "=", "working_list", ".", "pop", "(", "match", "[", "0", "]", "+", "1", ")", "working_list", "[", "0", "]", "=", "left_side", "+", "right_side", "[", "match", "[", "1", "]", ":", "]", "return", "working_list" ]
Find the next sequence to fuse, and fuse it (or raise exception). :param homology: length of terminal homology in bp :type homology: int :raises: AmbiguousGibsonError if there is more than one way for the fragment ends to combine. GibsonOverlapError if no homology match can be found.
[ "Find", "the", "next", "sequence", "to", "fuse", "and", "fuse", "it", "(", "or", "raise", "exception", ")", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_gibson.py#L87-L150
klavinslab/coral
coral/reaction/_gibson.py
_fuse_last
def _fuse_last(working_list, homology, tm): '''With one sequence left, attempt to fuse it to itself. :param homology: length of terminal homology in bp. :type homology: int :raises: AmbiguousGibsonError if either of the termini are palindromic (would bind self-self). ValueError if the ends are not compatible. ''' # 1. Construct graph on self-self # (destination, size, strand1, strand2) pattern = working_list[0] def graph_strands(strand1, strand2): matchlen = homology_report(pattern, pattern, strand1, strand2, cutoff=homology, min_tm=tm, top_two=True) if matchlen: # Ignore full-sequence matches # HACK: modified homology_report to accept top_two. It should # really just ignore full-length matches for length in matchlen: if length != len(pattern): return (0, length, strand1, strand2) else: return [] # cw is redundant with wc graph_ww = graph_strands('w', 'w') graph_wc = graph_strands('w', 'c') graph_cc = graph_strands('c', 'c') if graph_ww + graph_cc: raise AmbiguousGibsonError('Self-self binding during circularization.') if not graph_wc: raise ValueError('Failed to find compatible ends for circularization.') working_list[0] = working_list[0][:-graph_wc[1]].circularize() return working_list
python
def _fuse_last(working_list, homology, tm): '''With one sequence left, attempt to fuse it to itself. :param homology: length of terminal homology in bp. :type homology: int :raises: AmbiguousGibsonError if either of the termini are palindromic (would bind self-self). ValueError if the ends are not compatible. ''' # 1. Construct graph on self-self # (destination, size, strand1, strand2) pattern = working_list[0] def graph_strands(strand1, strand2): matchlen = homology_report(pattern, pattern, strand1, strand2, cutoff=homology, min_tm=tm, top_two=True) if matchlen: # Ignore full-sequence matches # HACK: modified homology_report to accept top_two. It should # really just ignore full-length matches for length in matchlen: if length != len(pattern): return (0, length, strand1, strand2) else: return [] # cw is redundant with wc graph_ww = graph_strands('w', 'w') graph_wc = graph_strands('w', 'c') graph_cc = graph_strands('c', 'c') if graph_ww + graph_cc: raise AmbiguousGibsonError('Self-self binding during circularization.') if not graph_wc: raise ValueError('Failed to find compatible ends for circularization.') working_list[0] = working_list[0][:-graph_wc[1]].circularize() return working_list
[ "def", "_fuse_last", "(", "working_list", ",", "homology", ",", "tm", ")", ":", "# 1. Construct graph on self-self", "# (destination, size, strand1, strand2)", "pattern", "=", "working_list", "[", "0", "]", "def", "graph_strands", "(", "strand1", ",", "strand2", ")", ":", "matchlen", "=", "homology_report", "(", "pattern", ",", "pattern", ",", "strand1", ",", "strand2", ",", "cutoff", "=", "homology", ",", "min_tm", "=", "tm", ",", "top_two", "=", "True", ")", "if", "matchlen", ":", "# Ignore full-sequence matches", "# HACK: modified homology_report to accept top_two. It should", "# really just ignore full-length matches", "for", "length", "in", "matchlen", ":", "if", "length", "!=", "len", "(", "pattern", ")", ":", "return", "(", "0", ",", "length", ",", "strand1", ",", "strand2", ")", "else", ":", "return", "[", "]", "# cw is redundant with wc", "graph_ww", "=", "graph_strands", "(", "'w'", ",", "'w'", ")", "graph_wc", "=", "graph_strands", "(", "'w'", ",", "'c'", ")", "graph_cc", "=", "graph_strands", "(", "'c'", ",", "'c'", ")", "if", "graph_ww", "+", "graph_cc", ":", "raise", "AmbiguousGibsonError", "(", "'Self-self binding during circularization.'", ")", "if", "not", "graph_wc", ":", "raise", "ValueError", "(", "'Failed to find compatible ends for circularization.'", ")", "working_list", "[", "0", "]", "=", "working_list", "[", "0", "]", "[", ":", "-", "graph_wc", "[", "1", "]", "]", ".", "circularize", "(", ")", "return", "working_list" ]
With one sequence left, attempt to fuse it to itself. :param homology: length of terminal homology in bp. :type homology: int :raises: AmbiguousGibsonError if either of the termini are palindromic (would bind self-self). ValueError if the ends are not compatible.
[ "With", "one", "sequence", "left", "attempt", "to", "fuse", "it", "to", "itself", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_gibson.py#L153-L191
klavinslab/coral
coral/reaction/_gibson.py
homology_report
def homology_report(seq1, seq2, strand1, strand2, cutoff=0, min_tm=63.0, top_two=False, max_size=500): '''Given two sequences (seq1 and seq2), report the size of all perfect matches between the 3' end of the top strand of seq1 and the 3' end of either strand of seq2. In short, in a Gibson reaction, what would bind the desired part of seq1, given a seq2? :param seq1: Sequence for which to test 3\' binding of a single strand to seq2. :type seq1: coral.DNA :param seq2: Sequence for which to test 3\' binding of each strand to seq1. :type seq1: coral.DNA :param strand1: w (watson) or c (crick) - which strand of seq1 is being tested. :type strand1ed: str :param strand2: w (watson) or c (crick) - which strand of seq2 is being tested. :type strand2ed: str :param cutoff: size cutoff for the report - if a match is lower, it's ignored :type cutoff: int :param min_tm: Minimum tm value cutoff - matches below are ignored. :type min_tm: float :param top_two: Return the best two matches :type top_two: bool :param max_size: Maximum overlap size (increases speed) :type max_size: int :returns: List of left and right identities. :rtype: list of ints ''' # Ensure that strand 1 is Watson and strand 2 is Crick if strand1 == 'c': seq1 = seq1.reverse_complement() if strand2 == 'w': seq2 = seq2.reverse_complement() # Generate all same-length 5' ends of seq1 and 3' ends of seq2 within # maximum homology length # TODO: If strings aren't used here, gen_chunks takes forever. Suggests a # need to optimize coral.DNA subsetting seq1_str = str(seq1) seq2_str = str(seq2) def gen_chunks(s1, s2): chunks1 = [seq1_str[-(i + 1):] for i in range(min(len(seq1_str), max_size))] chunks2 = [seq2_str[:(i + 1)] for i in range(min(len(seq2_str), max_size))] return chunks1, chunks2 seq1_chunks, seq2_chunks = gen_chunks(seq1_str, seq2_str) # Check for exact matches from terminal end to terminal end target_matches = [] for i, (s1, s2) in enumerate(zip(seq1_chunks, seq2_chunks)): s1len = len(s1) # Inefficient! (reverse complementing a bunch of times) # Don't calculate tm once base tm has been reached. # TODO: Go through logic here again and make sure the order of checking # makes sense if s1 == s2: logger.debug('Found Match: {}'.format(str(s1))) if s1len >= cutoff: tm = coral.analysis.tm(seq1[-(i + 1):]) logger.debug('Match tm: {} C'.format(tm)) if tm >= min_tm: target_matches.append(s1len) elif tm >= min_tm - 4: msg = 'One overlap had a Tm of {} C.'.format(tm) warnings.warn(msg) target_matches.append(s1len) target_matches.sort() if not top_two: return 0 if not target_matches else target_matches[0] else: return 0 if not target_matches else target_matches[0:2]
python
def homology_report(seq1, seq2, strand1, strand2, cutoff=0, min_tm=63.0, top_two=False, max_size=500): '''Given two sequences (seq1 and seq2), report the size of all perfect matches between the 3' end of the top strand of seq1 and the 3' end of either strand of seq2. In short, in a Gibson reaction, what would bind the desired part of seq1, given a seq2? :param seq1: Sequence for which to test 3\' binding of a single strand to seq2. :type seq1: coral.DNA :param seq2: Sequence for which to test 3\' binding of each strand to seq1. :type seq1: coral.DNA :param strand1: w (watson) or c (crick) - which strand of seq1 is being tested. :type strand1ed: str :param strand2: w (watson) or c (crick) - which strand of seq2 is being tested. :type strand2ed: str :param cutoff: size cutoff for the report - if a match is lower, it's ignored :type cutoff: int :param min_tm: Minimum tm value cutoff - matches below are ignored. :type min_tm: float :param top_two: Return the best two matches :type top_two: bool :param max_size: Maximum overlap size (increases speed) :type max_size: int :returns: List of left and right identities. :rtype: list of ints ''' # Ensure that strand 1 is Watson and strand 2 is Crick if strand1 == 'c': seq1 = seq1.reverse_complement() if strand2 == 'w': seq2 = seq2.reverse_complement() # Generate all same-length 5' ends of seq1 and 3' ends of seq2 within # maximum homology length # TODO: If strings aren't used here, gen_chunks takes forever. Suggests a # need to optimize coral.DNA subsetting seq1_str = str(seq1) seq2_str = str(seq2) def gen_chunks(s1, s2): chunks1 = [seq1_str[-(i + 1):] for i in range(min(len(seq1_str), max_size))] chunks2 = [seq2_str[:(i + 1)] for i in range(min(len(seq2_str), max_size))] return chunks1, chunks2 seq1_chunks, seq2_chunks = gen_chunks(seq1_str, seq2_str) # Check for exact matches from terminal end to terminal end target_matches = [] for i, (s1, s2) in enumerate(zip(seq1_chunks, seq2_chunks)): s1len = len(s1) # Inefficient! (reverse complementing a bunch of times) # Don't calculate tm once base tm has been reached. # TODO: Go through logic here again and make sure the order of checking # makes sense if s1 == s2: logger.debug('Found Match: {}'.format(str(s1))) if s1len >= cutoff: tm = coral.analysis.tm(seq1[-(i + 1):]) logger.debug('Match tm: {} C'.format(tm)) if tm >= min_tm: target_matches.append(s1len) elif tm >= min_tm - 4: msg = 'One overlap had a Tm of {} C.'.format(tm) warnings.warn(msg) target_matches.append(s1len) target_matches.sort() if not top_two: return 0 if not target_matches else target_matches[0] else: return 0 if not target_matches else target_matches[0:2]
[ "def", "homology_report", "(", "seq1", ",", "seq2", ",", "strand1", ",", "strand2", ",", "cutoff", "=", "0", ",", "min_tm", "=", "63.0", ",", "top_two", "=", "False", ",", "max_size", "=", "500", ")", ":", "# Ensure that strand 1 is Watson and strand 2 is Crick", "if", "strand1", "==", "'c'", ":", "seq1", "=", "seq1", ".", "reverse_complement", "(", ")", "if", "strand2", "==", "'w'", ":", "seq2", "=", "seq2", ".", "reverse_complement", "(", ")", "# Generate all same-length 5' ends of seq1 and 3' ends of seq2 within", "# maximum homology length", "# TODO: If strings aren't used here, gen_chunks takes forever. Suggests a", "# need to optimize coral.DNA subsetting", "seq1_str", "=", "str", "(", "seq1", ")", "seq2_str", "=", "str", "(", "seq2", ")", "def", "gen_chunks", "(", "s1", ",", "s2", ")", ":", "chunks1", "=", "[", "seq1_str", "[", "-", "(", "i", "+", "1", ")", ":", "]", "for", "i", "in", "range", "(", "min", "(", "len", "(", "seq1_str", ")", ",", "max_size", ")", ")", "]", "chunks2", "=", "[", "seq2_str", "[", ":", "(", "i", "+", "1", ")", "]", "for", "i", "in", "range", "(", "min", "(", "len", "(", "seq2_str", ")", ",", "max_size", ")", ")", "]", "return", "chunks1", ",", "chunks2", "seq1_chunks", ",", "seq2_chunks", "=", "gen_chunks", "(", "seq1_str", ",", "seq2_str", ")", "# Check for exact matches from terminal end to terminal end", "target_matches", "=", "[", "]", "for", "i", ",", "(", "s1", ",", "s2", ")", "in", "enumerate", "(", "zip", "(", "seq1_chunks", ",", "seq2_chunks", ")", ")", ":", "s1len", "=", "len", "(", "s1", ")", "# Inefficient! (reverse complementing a bunch of times)", "# Don't calculate tm once base tm has been reached.", "# TODO: Go through logic here again and make sure the order of checking", "# makes sense", "if", "s1", "==", "s2", ":", "logger", ".", "debug", "(", "'Found Match: {}'", ".", "format", "(", "str", "(", "s1", ")", ")", ")", "if", "s1len", ">=", "cutoff", ":", "tm", "=", "coral", ".", "analysis", ".", "tm", "(", "seq1", "[", "-", "(", "i", "+", "1", ")", ":", "]", ")", "logger", ".", "debug", "(", "'Match tm: {} C'", ".", "format", "(", "tm", ")", ")", "if", "tm", ">=", "min_tm", ":", "target_matches", ".", "append", "(", "s1len", ")", "elif", "tm", ">=", "min_tm", "-", "4", ":", "msg", "=", "'One overlap had a Tm of {} C.'", ".", "format", "(", "tm", ")", "warnings", ".", "warn", "(", "msg", ")", "target_matches", ".", "append", "(", "s1len", ")", "target_matches", ".", "sort", "(", ")", "if", "not", "top_two", ":", "return", "0", "if", "not", "target_matches", "else", "target_matches", "[", "0", "]", "else", ":", "return", "0", "if", "not", "target_matches", "else", "target_matches", "[", "0", ":", "2", "]" ]
Given two sequences (seq1 and seq2), report the size of all perfect matches between the 3' end of the top strand of seq1 and the 3' end of either strand of seq2. In short, in a Gibson reaction, what would bind the desired part of seq1, given a seq2? :param seq1: Sequence for which to test 3\' binding of a single strand to seq2. :type seq1: coral.DNA :param seq2: Sequence for which to test 3\' binding of each strand to seq1. :type seq1: coral.DNA :param strand1: w (watson) or c (crick) - which strand of seq1 is being tested. :type strand1ed: str :param strand2: w (watson) or c (crick) - which strand of seq2 is being tested. :type strand2ed: str :param cutoff: size cutoff for the report - if a match is lower, it's ignored :type cutoff: int :param min_tm: Minimum tm value cutoff - matches below are ignored. :type min_tm: float :param top_two: Return the best two matches :type top_two: bool :param max_size: Maximum overlap size (increases speed) :type max_size: int :returns: List of left and right identities. :rtype: list of ints
[ "Given", "two", "sequences", "(", "seq1", "and", "seq2", ")", "report", "the", "size", "of", "all", "perfect", "matches", "between", "the", "3", "end", "of", "the", "top", "strand", "of", "seq1", "and", "the", "3", "end", "of", "either", "strand", "of", "seq2", ".", "In", "short", "in", "a", "Gibson", "reaction", "what", "would", "bind", "the", "desired", "part", "of", "seq1", "given", "a", "seq2?" ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_gibson.py#L194-L270
klavinslab/coral
coral/database/_yeast.py
fetch_yeast_locus_sequence
def fetch_yeast_locus_sequence(locus_name, flanking_size=0): '''Acquire a sequence from SGD http://www.yeastgenome.org. :param locus_name: Common name or systematic name for the locus (e.g. ACT1 or YFL039C). :type locus_name: str :param flanking_size: The length of flanking DNA (on each side) to return :type flanking_size: int ''' from intermine.webservice import Service service = Service('http://yeastmine.yeastgenome.org/yeastmine/service') # Get a new query on the class (table) you will be querying: query = service.new_query('Gene') if flanking_size > 0: # The view specifies the output columns # secondaryIdentifier: the systematic name (e.g. YFL039C) # symbol: short name (e.g. ACT1) # length: sequence length # flankingRegions.direction: Upstream or downstream (or both) of locus # flankingRegions.sequence.length: length of the flanking regions # flankingRegions.sequence.residues: sequence of the flanking regions query.add_view('secondaryIdentifier', 'symbol', 'length', 'flankingRegions.direction', 'flankingRegions.sequence.length', 'flankingRegions.sequence.residues') # You can edit the constraint values below query.add_constraint('flankingRegions.direction', '=', 'both', code='A') query.add_constraint('Gene', 'LOOKUP', locus_name, 'S. cerevisiae', code='B') query.add_constraint('flankingRegions.distance', '=', '{:.1f}kb'.format(flanking_size / 1000.), code='C') # Uncomment and edit the code below to specify your own custom logic: query.set_logic('A and B and C') # TODO: What to do when there's more than one result? first_result = query.rows().next() # FIXME: Use logger module instead # print first_result['secondaryIdentifier'] # print first_result['symbol'], row['length'] # print first_result['flankingRegions.direction'] # print first_result['flankingRegions.sequence.length'] # print first_result['flankingRegions.sequence.residues'] seq = coral.DNA(first_result['flankingRegions.sequence.residues']) # TODO: add more metadata elif flanking_size == 0: # The view specifies the output columns query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol', 'name', 'sgdAlias', 'organism.shortName', 'sequence.length', 'sequence.residues', 'description', 'qualifier') query.add_constraint('status', 'IS NULL', code='D') query.add_constraint('status', '=', 'Active', code='C') query.add_constraint('qualifier', 'IS NULL', code='B') query.add_constraint('qualifier', '!=', 'Dubious', code='A') query.add_constraint('Gene', 'LOOKUP', locus_name, 'S. cerevisiae', code='E') # Your custom constraint logic is specified with the code below: query.set_logic('(A or B) and (C or D) and E') first_result = query.rows().next() seq = coral.DNA(first_result['sequence.residues']) else: print 'Problem with the flanking region size....' seq = coral.DNA('') return seq
python
def fetch_yeast_locus_sequence(locus_name, flanking_size=0): '''Acquire a sequence from SGD http://www.yeastgenome.org. :param locus_name: Common name or systematic name for the locus (e.g. ACT1 or YFL039C). :type locus_name: str :param flanking_size: The length of flanking DNA (on each side) to return :type flanking_size: int ''' from intermine.webservice import Service service = Service('http://yeastmine.yeastgenome.org/yeastmine/service') # Get a new query on the class (table) you will be querying: query = service.new_query('Gene') if flanking_size > 0: # The view specifies the output columns # secondaryIdentifier: the systematic name (e.g. YFL039C) # symbol: short name (e.g. ACT1) # length: sequence length # flankingRegions.direction: Upstream or downstream (or both) of locus # flankingRegions.sequence.length: length of the flanking regions # flankingRegions.sequence.residues: sequence of the flanking regions query.add_view('secondaryIdentifier', 'symbol', 'length', 'flankingRegions.direction', 'flankingRegions.sequence.length', 'flankingRegions.sequence.residues') # You can edit the constraint values below query.add_constraint('flankingRegions.direction', '=', 'both', code='A') query.add_constraint('Gene', 'LOOKUP', locus_name, 'S. cerevisiae', code='B') query.add_constraint('flankingRegions.distance', '=', '{:.1f}kb'.format(flanking_size / 1000.), code='C') # Uncomment and edit the code below to specify your own custom logic: query.set_logic('A and B and C') # TODO: What to do when there's more than one result? first_result = query.rows().next() # FIXME: Use logger module instead # print first_result['secondaryIdentifier'] # print first_result['symbol'], row['length'] # print first_result['flankingRegions.direction'] # print first_result['flankingRegions.sequence.length'] # print first_result['flankingRegions.sequence.residues'] seq = coral.DNA(first_result['flankingRegions.sequence.residues']) # TODO: add more metadata elif flanking_size == 0: # The view specifies the output columns query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol', 'name', 'sgdAlias', 'organism.shortName', 'sequence.length', 'sequence.residues', 'description', 'qualifier') query.add_constraint('status', 'IS NULL', code='D') query.add_constraint('status', '=', 'Active', code='C') query.add_constraint('qualifier', 'IS NULL', code='B') query.add_constraint('qualifier', '!=', 'Dubious', code='A') query.add_constraint('Gene', 'LOOKUP', locus_name, 'S. cerevisiae', code='E') # Your custom constraint logic is specified with the code below: query.set_logic('(A or B) and (C or D) and E') first_result = query.rows().next() seq = coral.DNA(first_result['sequence.residues']) else: print 'Problem with the flanking region size....' seq = coral.DNA('') return seq
[ "def", "fetch_yeast_locus_sequence", "(", "locus_name", ",", "flanking_size", "=", "0", ")", ":", "from", "intermine", ".", "webservice", "import", "Service", "service", "=", "Service", "(", "'http://yeastmine.yeastgenome.org/yeastmine/service'", ")", "# Get a new query on the class (table) you will be querying:", "query", "=", "service", ".", "new_query", "(", "'Gene'", ")", "if", "flanking_size", ">", "0", ":", "# The view specifies the output columns", "# secondaryIdentifier: the systematic name (e.g. YFL039C)", "# symbol: short name (e.g. ACT1)", "# length: sequence length", "# flankingRegions.direction: Upstream or downstream (or both) of locus", "# flankingRegions.sequence.length: length of the flanking regions", "# flankingRegions.sequence.residues: sequence of the flanking regions", "query", ".", "add_view", "(", "'secondaryIdentifier'", ",", "'symbol'", ",", "'length'", ",", "'flankingRegions.direction'", ",", "'flankingRegions.sequence.length'", ",", "'flankingRegions.sequence.residues'", ")", "# You can edit the constraint values below", "query", ".", "add_constraint", "(", "'flankingRegions.direction'", ",", "'='", ",", "'both'", ",", "code", "=", "'A'", ")", "query", ".", "add_constraint", "(", "'Gene'", ",", "'LOOKUP'", ",", "locus_name", ",", "'S. cerevisiae'", ",", "code", "=", "'B'", ")", "query", ".", "add_constraint", "(", "'flankingRegions.distance'", ",", "'='", ",", "'{:.1f}kb'", ".", "format", "(", "flanking_size", "/", "1000.", ")", ",", "code", "=", "'C'", ")", "# Uncomment and edit the code below to specify your own custom logic:", "query", ".", "set_logic", "(", "'A and B and C'", ")", "# TODO: What to do when there's more than one result?", "first_result", "=", "query", ".", "rows", "(", ")", ".", "next", "(", ")", "# FIXME: Use logger module instead", "# print first_result['secondaryIdentifier']", "# print first_result['symbol'], row['length']", "# print first_result['flankingRegions.direction']", "# print first_result['flankingRegions.sequence.length']", "# print first_result['flankingRegions.sequence.residues']", "seq", "=", "coral", ".", "DNA", "(", "first_result", "[", "'flankingRegions.sequence.residues'", "]", ")", "# TODO: add more metadata", "elif", "flanking_size", "==", "0", ":", "# The view specifies the output columns", "query", ".", "add_view", "(", "'primaryIdentifier'", ",", "'secondaryIdentifier'", ",", "'symbol'", ",", "'name'", ",", "'sgdAlias'", ",", "'organism.shortName'", ",", "'sequence.length'", ",", "'sequence.residues'", ",", "'description'", ",", "'qualifier'", ")", "query", ".", "add_constraint", "(", "'status'", ",", "'IS NULL'", ",", "code", "=", "'D'", ")", "query", ".", "add_constraint", "(", "'status'", ",", "'='", ",", "'Active'", ",", "code", "=", "'C'", ")", "query", ".", "add_constraint", "(", "'qualifier'", ",", "'IS NULL'", ",", "code", "=", "'B'", ")", "query", ".", "add_constraint", "(", "'qualifier'", ",", "'!='", ",", "'Dubious'", ",", "code", "=", "'A'", ")", "query", ".", "add_constraint", "(", "'Gene'", ",", "'LOOKUP'", ",", "locus_name", ",", "'S. cerevisiae'", ",", "code", "=", "'E'", ")", "# Your custom constraint logic is specified with the code below:", "query", ".", "set_logic", "(", "'(A or B) and (C or D) and E'", ")", "first_result", "=", "query", ".", "rows", "(", ")", ".", "next", "(", ")", "seq", "=", "coral", ".", "DNA", "(", "first_result", "[", "'sequence.residues'", "]", ")", "else", ":", "print", "'Problem with the flanking region size....'", "seq", "=", "coral", ".", "DNA", "(", "''", ")", "return", "seq" ]
Acquire a sequence from SGD http://www.yeastgenome.org. :param locus_name: Common name or systematic name for the locus (e.g. ACT1 or YFL039C). :type locus_name: str :param flanking_size: The length of flanking DNA (on each side) to return :type flanking_size: int
[ "Acquire", "a", "sequence", "from", "SGD", "http", ":", "//", "www", ".", "yeastgenome", ".", "org", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/database/_yeast.py#L6-L83
klavinslab/coral
coral/database/_yeast.py
get_yeast_sequence
def get_yeast_sequence(chromosome, start, end, reverse_complement=False): '''Acquire a sequence from SGD http://www.yeastgenome.org :param chromosome: Yeast chromosome. :type chromosome: int :param start: A biostart. :type start: int :param end: A bioend. :type end: int :param reverse_complement: Get the reverse complement. :type revervse_complement: bool :returns: A DNA sequence. :rtype: coral.DNA ''' import requests if start != end: if reverse_complement: rev_option = '-REV' else: rev_option = '' param_url = '&chr=' + str(chromosome) + '&beg=' + str(start) + \ '&end=' + str(end) + '&rev=' + rev_option url = 'http://www.yeastgenome.org/cgi-bin/getSeq?map=a2map' + \ param_url res = requests.get(url) # ok... sadely, I contacted SGD and they haven;t implemented this so # I have to parse their yeastgenome page, but # it is easy between the raw sequence is between <pre> tags! # warning that's for the first < so we need +5! begin_index = res.text.index('<pre>') end_index = res.text.index('</pre>') sequence = res.text[begin_index + 5:end_index] sequence = sequence.replace('\n', '').replace('\r', '') else: sequence = '' return coral.DNA(sequence)
python
def get_yeast_sequence(chromosome, start, end, reverse_complement=False): '''Acquire a sequence from SGD http://www.yeastgenome.org :param chromosome: Yeast chromosome. :type chromosome: int :param start: A biostart. :type start: int :param end: A bioend. :type end: int :param reverse_complement: Get the reverse complement. :type revervse_complement: bool :returns: A DNA sequence. :rtype: coral.DNA ''' import requests if start != end: if reverse_complement: rev_option = '-REV' else: rev_option = '' param_url = '&chr=' + str(chromosome) + '&beg=' + str(start) + \ '&end=' + str(end) + '&rev=' + rev_option url = 'http://www.yeastgenome.org/cgi-bin/getSeq?map=a2map' + \ param_url res = requests.get(url) # ok... sadely, I contacted SGD and they haven;t implemented this so # I have to parse their yeastgenome page, but # it is easy between the raw sequence is between <pre> tags! # warning that's for the first < so we need +5! begin_index = res.text.index('<pre>') end_index = res.text.index('</pre>') sequence = res.text[begin_index + 5:end_index] sequence = sequence.replace('\n', '').replace('\r', '') else: sequence = '' return coral.DNA(sequence)
[ "def", "get_yeast_sequence", "(", "chromosome", ",", "start", ",", "end", ",", "reverse_complement", "=", "False", ")", ":", "import", "requests", "if", "start", "!=", "end", ":", "if", "reverse_complement", ":", "rev_option", "=", "'-REV'", "else", ":", "rev_option", "=", "''", "param_url", "=", "'&chr='", "+", "str", "(", "chromosome", ")", "+", "'&beg='", "+", "str", "(", "start", ")", "+", "'&end='", "+", "str", "(", "end", ")", "+", "'&rev='", "+", "rev_option", "url", "=", "'http://www.yeastgenome.org/cgi-bin/getSeq?map=a2map'", "+", "param_url", "res", "=", "requests", ".", "get", "(", "url", ")", "# ok... sadely, I contacted SGD and they haven;t implemented this so", "# I have to parse their yeastgenome page, but", "# it is easy between the raw sequence is between <pre> tags!", "# warning that's for the first < so we need +5!", "begin_index", "=", "res", ".", "text", ".", "index", "(", "'<pre>'", ")", "end_index", "=", "res", ".", "text", ".", "index", "(", "'</pre>'", ")", "sequence", "=", "res", ".", "text", "[", "begin_index", "+", "5", ":", "end_index", "]", "sequence", "=", "sequence", ".", "replace", "(", "'\\n'", ",", "''", ")", ".", "replace", "(", "'\\r'", ",", "''", ")", "else", ":", "sequence", "=", "''", "return", "coral", ".", "DNA", "(", "sequence", ")" ]
Acquire a sequence from SGD http://www.yeastgenome.org :param chromosome: Yeast chromosome. :type chromosome: int :param start: A biostart. :type start: int :param end: A bioend. :type end: int :param reverse_complement: Get the reverse complement. :type revervse_complement: bool :returns: A DNA sequence. :rtype: coral.DNA
[ "Acquire", "a", "sequence", "from", "SGD", "http", ":", "//", "www", ".", "yeastgenome", ".", "org", ":", "param", "chromosome", ":", "Yeast", "chromosome", ".", ":", "type", "chromosome", ":", "int", ":", "param", "start", ":", "A", "biostart", ".", ":", "type", "start", ":", "int", ":", "param", "end", ":", "A", "bioend", ".", ":", "type", "end", ":", "int", ":", "param", "reverse_complement", ":", "Get", "the", "reverse", "complement", ".", ":", "type", "revervse_complement", ":", "bool", ":", "returns", ":", "A", "DNA", "sequence", ".", ":", "rtype", ":", "coral", ".", "DNA" ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/database/_yeast.py#L86-L126
klavinslab/coral
coral/database/_yeast.py
get_yeast_gene_location
def get_yeast_gene_location(gene_name): '''Acquire the location of a gene from SGD http://www.yeastgenome.org :param gene_name: Name of the gene. :type gene_name: string :returns location: [int: chromosome, int:biostart, int:bioend, int:strand] :rtype location: list ''' from intermine.webservice import Service service = Service('http://yeastmine.yeastgenome.org/yeastmine/service') # Get a new query on the class (table) you will be querying: query = service.new_query('Gene') # The view specifies the output columns query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol', 'name', 'organism.shortName', 'chromosome.primaryIdentifier', 'chromosomeLocation.start', 'chromosomeLocation.end', 'chromosomeLocation.strand') # Uncomment and edit the line below (the default) to select a custom sort # order: # query.add_sort_order('Gene.primaryIdentifier', 'ASC') # You can edit the constraint values below query.add_constraint('organism.shortName', '=', 'S. cerevisiae', code='B') query.add_constraint('Gene', 'LOOKUP', gene_name, code='A') # Uncomment and edit the code below to specify your own custom logic: # query.set_logic('A and B') chromosomes = {'chrI': 1, 'chrII': 2, 'chrIII': 3, 'chrIV': 4, 'chrV': 5, 'chrVI': 6, 'chrVII': 7, 'chrVIII': 8, 'chrIX': 9, 'chrX': 10, 'chrXI': 11, 'chrXII': 12, 'chrXIII': 13, 'chrXIV': 14, 'chrXV': 15, 'chrXVI': 16} first_result = query.rows().next() return [chromosomes[first_result['chromosome.primaryIdentifier']], first_result['chromosomeLocation.start'], first_result['chromosomeLocation.end'], int(first_result['chromosomeLocation.strand'])]
python
def get_yeast_gene_location(gene_name): '''Acquire the location of a gene from SGD http://www.yeastgenome.org :param gene_name: Name of the gene. :type gene_name: string :returns location: [int: chromosome, int:biostart, int:bioend, int:strand] :rtype location: list ''' from intermine.webservice import Service service = Service('http://yeastmine.yeastgenome.org/yeastmine/service') # Get a new query on the class (table) you will be querying: query = service.new_query('Gene') # The view specifies the output columns query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol', 'name', 'organism.shortName', 'chromosome.primaryIdentifier', 'chromosomeLocation.start', 'chromosomeLocation.end', 'chromosomeLocation.strand') # Uncomment and edit the line below (the default) to select a custom sort # order: # query.add_sort_order('Gene.primaryIdentifier', 'ASC') # You can edit the constraint values below query.add_constraint('organism.shortName', '=', 'S. cerevisiae', code='B') query.add_constraint('Gene', 'LOOKUP', gene_name, code='A') # Uncomment and edit the code below to specify your own custom logic: # query.set_logic('A and B') chromosomes = {'chrI': 1, 'chrII': 2, 'chrIII': 3, 'chrIV': 4, 'chrV': 5, 'chrVI': 6, 'chrVII': 7, 'chrVIII': 8, 'chrIX': 9, 'chrX': 10, 'chrXI': 11, 'chrXII': 12, 'chrXIII': 13, 'chrXIV': 14, 'chrXV': 15, 'chrXVI': 16} first_result = query.rows().next() return [chromosomes[first_result['chromosome.primaryIdentifier']], first_result['chromosomeLocation.start'], first_result['chromosomeLocation.end'], int(first_result['chromosomeLocation.strand'])]
[ "def", "get_yeast_gene_location", "(", "gene_name", ")", ":", "from", "intermine", ".", "webservice", "import", "Service", "service", "=", "Service", "(", "'http://yeastmine.yeastgenome.org/yeastmine/service'", ")", "# Get a new query on the class (table) you will be querying:", "query", "=", "service", ".", "new_query", "(", "'Gene'", ")", "# The view specifies the output columns", "query", ".", "add_view", "(", "'primaryIdentifier'", ",", "'secondaryIdentifier'", ",", "'symbol'", ",", "'name'", ",", "'organism.shortName'", ",", "'chromosome.primaryIdentifier'", ",", "'chromosomeLocation.start'", ",", "'chromosomeLocation.end'", ",", "'chromosomeLocation.strand'", ")", "# Uncomment and edit the line below (the default) to select a custom sort", "# order:", "# query.add_sort_order('Gene.primaryIdentifier', 'ASC')", "# You can edit the constraint values below", "query", ".", "add_constraint", "(", "'organism.shortName'", ",", "'='", ",", "'S. cerevisiae'", ",", "code", "=", "'B'", ")", "query", ".", "add_constraint", "(", "'Gene'", ",", "'LOOKUP'", ",", "gene_name", ",", "code", "=", "'A'", ")", "# Uncomment and edit the code below to specify your own custom logic:", "# query.set_logic('A and B')", "chromosomes", "=", "{", "'chrI'", ":", "1", ",", "'chrII'", ":", "2", ",", "'chrIII'", ":", "3", ",", "'chrIV'", ":", "4", ",", "'chrV'", ":", "5", ",", "'chrVI'", ":", "6", ",", "'chrVII'", ":", "7", ",", "'chrVIII'", ":", "8", ",", "'chrIX'", ":", "9", ",", "'chrX'", ":", "10", ",", "'chrXI'", ":", "11", ",", "'chrXII'", ":", "12", ",", "'chrXIII'", ":", "13", ",", "'chrXIV'", ":", "14", ",", "'chrXV'", ":", "15", ",", "'chrXVI'", ":", "16", "}", "first_result", "=", "query", ".", "rows", "(", ")", ".", "next", "(", ")", "return", "[", "chromosomes", "[", "first_result", "[", "'chromosome.primaryIdentifier'", "]", "]", ",", "first_result", "[", "'chromosomeLocation.start'", "]", ",", "first_result", "[", "'chromosomeLocation.end'", "]", ",", "int", "(", "first_result", "[", "'chromosomeLocation.strand'", "]", ")", "]" ]
Acquire the location of a gene from SGD http://www.yeastgenome.org :param gene_name: Name of the gene. :type gene_name: string :returns location: [int: chromosome, int:biostart, int:bioend, int:strand] :rtype location: list
[ "Acquire", "the", "location", "of", "a", "gene", "from", "SGD", "http", ":", "//", "www", ".", "yeastgenome", ".", "org", ":", "param", "gene_name", ":", "Name", "of", "the", "gene", ".", ":", "type", "gene_name", ":", "string", ":", "returns", "location", ":", "[", "int", ":", "chromosome", "int", ":", "biostart", "int", ":", "bioend", "int", ":", "strand", "]", ":", "rtype", "location", ":", "list" ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/database/_yeast.py#L129-L182
klavinslab/coral
coral/database/_yeast.py
get_gene_id
def get_gene_id(gene_name): '''Retrieve systematic yeast gene name from the common name. :param gene_name: Common name for yeast gene (e.g. ADE2). :type gene_name: str :returns: Systematic name for yeast gene (e.g. YOR128C). :rtype: str ''' from intermine.webservice import Service service = Service('http://yeastmine.yeastgenome.org/yeastmine/service') # Get a new query on the class (table) you will be querying: query = service.new_query('Gene') # The view specifies the output columns query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol', 'name', 'sgdAlias', 'crossReferences.identifier', 'crossReferences.source.name') # Uncomment and edit the line below (the default) to select a custom sort # order: # query.add_sort_order('Gene.primaryIdentifier', 'ASC') # You can edit the constraint values below query.add_constraint('organism.shortName', '=', 'S. cerevisiae', code='B') query.add_constraint('Gene', 'LOOKUP', gene_name, code='A') # Uncomment and edit the code below to specify your own custom logic: # query.set_logic('A and B') for row in query.rows(): gid = row['secondaryIdentifier'] return gid
python
def get_gene_id(gene_name): '''Retrieve systematic yeast gene name from the common name. :param gene_name: Common name for yeast gene (e.g. ADE2). :type gene_name: str :returns: Systematic name for yeast gene (e.g. YOR128C). :rtype: str ''' from intermine.webservice import Service service = Service('http://yeastmine.yeastgenome.org/yeastmine/service') # Get a new query on the class (table) you will be querying: query = service.new_query('Gene') # The view specifies the output columns query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol', 'name', 'sgdAlias', 'crossReferences.identifier', 'crossReferences.source.name') # Uncomment and edit the line below (the default) to select a custom sort # order: # query.add_sort_order('Gene.primaryIdentifier', 'ASC') # You can edit the constraint values below query.add_constraint('organism.shortName', '=', 'S. cerevisiae', code='B') query.add_constraint('Gene', 'LOOKUP', gene_name, code='A') # Uncomment and edit the code below to specify your own custom logic: # query.set_logic('A and B') for row in query.rows(): gid = row['secondaryIdentifier'] return gid
[ "def", "get_gene_id", "(", "gene_name", ")", ":", "from", "intermine", ".", "webservice", "import", "Service", "service", "=", "Service", "(", "'http://yeastmine.yeastgenome.org/yeastmine/service'", ")", "# Get a new query on the class (table) you will be querying:", "query", "=", "service", ".", "new_query", "(", "'Gene'", ")", "# The view specifies the output columns", "query", ".", "add_view", "(", "'primaryIdentifier'", ",", "'secondaryIdentifier'", ",", "'symbol'", ",", "'name'", ",", "'sgdAlias'", ",", "'crossReferences.identifier'", ",", "'crossReferences.source.name'", ")", "# Uncomment and edit the line below (the default) to select a custom sort", "# order:", "# query.add_sort_order('Gene.primaryIdentifier', 'ASC')", "# You can edit the constraint values below", "query", ".", "add_constraint", "(", "'organism.shortName'", ",", "'='", ",", "'S. cerevisiae'", ",", "code", "=", "'B'", ")", "query", ".", "add_constraint", "(", "'Gene'", ",", "'LOOKUP'", ",", "gene_name", ",", "code", "=", "'A'", ")", "# Uncomment and edit the code below to specify your own custom logic:", "# query.set_logic('A and B')", "for", "row", "in", "query", ".", "rows", "(", ")", ":", "gid", "=", "row", "[", "'secondaryIdentifier'", "]", "return", "gid" ]
Retrieve systematic yeast gene name from the common name. :param gene_name: Common name for yeast gene (e.g. ADE2). :type gene_name: str :returns: Systematic name for yeast gene (e.g. YOR128C). :rtype: str
[ "Retrieve", "systematic", "yeast", "gene", "name", "from", "the", "common", "name", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/database/_yeast.py#L185-L219
klavinslab/coral
coral/database/_yeast.py
get_yeast_promoter_ypa
def get_yeast_promoter_ypa(gene_name): '''Retrieve promoter from Yeast Promoter Atlas (http://ypa.csbb.ntu.edu.tw). :param gene_name: Common name for yeast gene. :type gene_name: str :returns: Double-stranded DNA sequence of the promoter. :rtype: coral.DNA ''' import requests loc = get_yeast_gene_location(gene_name) gid = get_gene_id(gene_name) ypa_baseurl = 'http://ypa.csbb.ntu.edu.tw/do' params = {'act': 'download', 'nucle': 'InVitro', 'right': str(loc[2]), 'left': str(loc[1]), 'gene': str(gid), 'chr': str(loc[0])} response = requests.get(ypa_baseurl, params=params) text = response.text # FASTA records are just name-sequence pairs split up by > e.g. # >my_dna_name # GACGATA # TODO: most of this is redundant, as we just want the 2nd record record_split = text.split('>') record_split.pop(0) parsed = [] for record in record_split: parts = record.split('\n') sequence = coral.DNA(''.join(parts[1:])) sequence.name = parts[0] parsed.append(sequence) return parsed[1]
python
def get_yeast_promoter_ypa(gene_name): '''Retrieve promoter from Yeast Promoter Atlas (http://ypa.csbb.ntu.edu.tw). :param gene_name: Common name for yeast gene. :type gene_name: str :returns: Double-stranded DNA sequence of the promoter. :rtype: coral.DNA ''' import requests loc = get_yeast_gene_location(gene_name) gid = get_gene_id(gene_name) ypa_baseurl = 'http://ypa.csbb.ntu.edu.tw/do' params = {'act': 'download', 'nucle': 'InVitro', 'right': str(loc[2]), 'left': str(loc[1]), 'gene': str(gid), 'chr': str(loc[0])} response = requests.get(ypa_baseurl, params=params) text = response.text # FASTA records are just name-sequence pairs split up by > e.g. # >my_dna_name # GACGATA # TODO: most of this is redundant, as we just want the 2nd record record_split = text.split('>') record_split.pop(0) parsed = [] for record in record_split: parts = record.split('\n') sequence = coral.DNA(''.join(parts[1:])) sequence.name = parts[0] parsed.append(sequence) return parsed[1]
[ "def", "get_yeast_promoter_ypa", "(", "gene_name", ")", ":", "import", "requests", "loc", "=", "get_yeast_gene_location", "(", "gene_name", ")", "gid", "=", "get_gene_id", "(", "gene_name", ")", "ypa_baseurl", "=", "'http://ypa.csbb.ntu.edu.tw/do'", "params", "=", "{", "'act'", ":", "'download'", ",", "'nucle'", ":", "'InVitro'", ",", "'right'", ":", "str", "(", "loc", "[", "2", "]", ")", ",", "'left'", ":", "str", "(", "loc", "[", "1", "]", ")", ",", "'gene'", ":", "str", "(", "gid", ")", ",", "'chr'", ":", "str", "(", "loc", "[", "0", "]", ")", "}", "response", "=", "requests", ".", "get", "(", "ypa_baseurl", ",", "params", "=", "params", ")", "text", "=", "response", ".", "text", "# FASTA records are just name-sequence pairs split up by > e.g.", "# >my_dna_name", "# GACGATA", "# TODO: most of this is redundant, as we just want the 2nd record", "record_split", "=", "text", ".", "split", "(", "'>'", ")", "record_split", ".", "pop", "(", "0", ")", "parsed", "=", "[", "]", "for", "record", "in", "record_split", ":", "parts", "=", "record", ".", "split", "(", "'\\n'", ")", "sequence", "=", "coral", ".", "DNA", "(", "''", ".", "join", "(", "parts", "[", "1", ":", "]", ")", ")", "sequence", ".", "name", "=", "parts", "[", "0", "]", "parsed", ".", "append", "(", "sequence", ")", "return", "parsed", "[", "1", "]" ]
Retrieve promoter from Yeast Promoter Atlas (http://ypa.csbb.ntu.edu.tw). :param gene_name: Common name for yeast gene. :type gene_name: str :returns: Double-stranded DNA sequence of the promoter. :rtype: coral.DNA
[ "Retrieve", "promoter", "from", "Yeast", "Promoter", "Atlas", "(", "http", ":", "//", "ypa", ".", "csbb", ".", "ntu", ".", "edu", ".", "tw", ")", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/database/_yeast.py#L222-L259
klavinslab/coral
coral/design/_oligo_synthesis/oligo_assembly.py
_grow_overlaps
def _grow_overlaps(dna, melting_temp, require_even, length_max, overlap_min, min_exception): '''Grows equidistant overlaps until they meet specified constraints. :param dna: Input sequence. :type dna: coral.DNA :param melting_temp: Ideal Tm of the overlaps, in degrees C. :type melting_temp: float :param require_even: Require that the number of oligonucleotides is even. :type require_even: bool :param length_max: Maximum oligo size (e.g. 60bp price point cutoff) range. :type length_range: int :param overlap_min: Minimum overlap size. :type overlap_min: int :param min_exception: In order to meet melting_temp and overlap_min settings, allow overlaps less than overlap_min to continue growing above melting_temp. :type min_exception: bool :returns: Oligos, their overlapping regions, overlap Tms, and overlap indices. :rtype: tuple ''' # TODO: prevent growing overlaps from bumping into each other - # should halt when it happens, give warning, let user decide if they still # want the current construct # Another option would be to start over, moving the starting positions # near the problem region a little farther from each other - this would # put the AT-rich region in the middle of the spanning oligo # Try bare minimum number of oligos oligo_n = len(dna) // length_max + 1 # Adjust number of oligos if even number required if require_even: oligo_increment = 2 if oligo_n % 2 == 1: oligo_n += 1 else: oligo_increment = 1 # Increase oligo number until the minimum oligo_len is less than length_max while float(len(dna)) / oligo_n > length_max: oligo_n += oligo_increment # Loop until all overlaps meet minimum Tm and length tm_met = False len_met = False while(not tm_met or not len_met): # Calculate initial number of overlaps overlap_n = oligo_n - 1 # Place overlaps approximately equidistant over sequence length overlap_interval = float(len(dna)) / oligo_n starts = [int(overlap_interval * (i + 1)) for i in range(overlap_n)] ends = [index + 1 for index in starts] # Fencepost for while loop # Initial overlaps (1 base) and their tms overlaps = [dna[start:end] for start, end in zip(starts, ends)] overlap_tms = [coral.analysis.tm(overlap) for overlap in overlaps] index = overlap_tms.index(min(overlap_tms)) # Initial oligos - includes the 1 base overlaps. # All the oligos are in the same direction - reverse # complementation of every other one happens later oligo_starts = [0] + starts oligo_ends = ends + [len(dna)] oligo_indices = [oligo_starts, oligo_ends] oligos = [dna[start:end] for start, end in zip(*oligo_indices)] # Oligo won't be maxed in first pass. tm_met and len_met will be false maxed = False while not (tm_met and len_met) and not maxed: # Recalculate overlaps and their Tms overlaps = _recalculate_overlaps(dna, overlaps, oligo_indices) # Tm calculation is bottleneck - only recalculate changed overlap overlap_tms[index] = coral.analysis.tm(overlaps[index]) # Find lowest-Tm overlap and its index. index = overlap_tms.index(min(overlap_tms)) # Move overlap at that index oligos = _expand_overlap(dna, oligo_indices, index, oligos, length_max) # Regenerate conditions maxed = any([len(x) == length_max for x in oligos]) tm_met = all([x >= melting_temp for x in overlap_tms]) if min_exception: len_met = True else: len_met = all([len(x) >= overlap_min for x in overlaps]) # TODO: add test for min_exception case (use rob's sequence from # 20130624 with 65C Tm) if min_exception: len_met = all([len(x) >= overlap_min for x in overlaps]) # See if len_met is true - if so do nothing if len_met: break else: while not len_met and not maxed: # Recalculate overlaps and their Tms overlaps = _recalculate_overlaps(dna, overlaps, oligo_indices) # Overlap to increase is the shortest one overlap_lens = [len(overlap) for overlap in overlaps] index = overlap_lens.index(min(overlap_lens)) # Increase left or right oligo oligos = _expand_overlap(dna, oligo_indices, index, oligos, length_max) # Recalculate conditions maxed = any([len(x) == length_max for x in oligos]) len_met = all([len(x) >= overlap_min for x in overlaps]) # Recalculate tms to reflect any changes (some are redundant) overlap_tms[index] = coral.analysis.tm(overlaps[index]) # Outcome could be that len_met happened *or* maxed out # length of one of the oligos. If len_met happened, should be # done so long as tm_met has been satisfied. If maxed happened, # len_met will not have been met, even if tm_met is satisfied, # and script will reattempt with more oligos oligo_n += oligo_increment # Calculate location of overlaps overlap_indices = [(oligo_indices[0][x + 1], oligo_indices[1][x]) for x in range(overlap_n)] return oligos, overlaps, overlap_tms, overlap_indices
python
def _grow_overlaps(dna, melting_temp, require_even, length_max, overlap_min, min_exception): '''Grows equidistant overlaps until they meet specified constraints. :param dna: Input sequence. :type dna: coral.DNA :param melting_temp: Ideal Tm of the overlaps, in degrees C. :type melting_temp: float :param require_even: Require that the number of oligonucleotides is even. :type require_even: bool :param length_max: Maximum oligo size (e.g. 60bp price point cutoff) range. :type length_range: int :param overlap_min: Minimum overlap size. :type overlap_min: int :param min_exception: In order to meet melting_temp and overlap_min settings, allow overlaps less than overlap_min to continue growing above melting_temp. :type min_exception: bool :returns: Oligos, their overlapping regions, overlap Tms, and overlap indices. :rtype: tuple ''' # TODO: prevent growing overlaps from bumping into each other - # should halt when it happens, give warning, let user decide if they still # want the current construct # Another option would be to start over, moving the starting positions # near the problem region a little farther from each other - this would # put the AT-rich region in the middle of the spanning oligo # Try bare minimum number of oligos oligo_n = len(dna) // length_max + 1 # Adjust number of oligos if even number required if require_even: oligo_increment = 2 if oligo_n % 2 == 1: oligo_n += 1 else: oligo_increment = 1 # Increase oligo number until the minimum oligo_len is less than length_max while float(len(dna)) / oligo_n > length_max: oligo_n += oligo_increment # Loop until all overlaps meet minimum Tm and length tm_met = False len_met = False while(not tm_met or not len_met): # Calculate initial number of overlaps overlap_n = oligo_n - 1 # Place overlaps approximately equidistant over sequence length overlap_interval = float(len(dna)) / oligo_n starts = [int(overlap_interval * (i + 1)) for i in range(overlap_n)] ends = [index + 1 for index in starts] # Fencepost for while loop # Initial overlaps (1 base) and their tms overlaps = [dna[start:end] for start, end in zip(starts, ends)] overlap_tms = [coral.analysis.tm(overlap) for overlap in overlaps] index = overlap_tms.index(min(overlap_tms)) # Initial oligos - includes the 1 base overlaps. # All the oligos are in the same direction - reverse # complementation of every other one happens later oligo_starts = [0] + starts oligo_ends = ends + [len(dna)] oligo_indices = [oligo_starts, oligo_ends] oligos = [dna[start:end] for start, end in zip(*oligo_indices)] # Oligo won't be maxed in first pass. tm_met and len_met will be false maxed = False while not (tm_met and len_met) and not maxed: # Recalculate overlaps and their Tms overlaps = _recalculate_overlaps(dna, overlaps, oligo_indices) # Tm calculation is bottleneck - only recalculate changed overlap overlap_tms[index] = coral.analysis.tm(overlaps[index]) # Find lowest-Tm overlap and its index. index = overlap_tms.index(min(overlap_tms)) # Move overlap at that index oligos = _expand_overlap(dna, oligo_indices, index, oligos, length_max) # Regenerate conditions maxed = any([len(x) == length_max for x in oligos]) tm_met = all([x >= melting_temp for x in overlap_tms]) if min_exception: len_met = True else: len_met = all([len(x) >= overlap_min for x in overlaps]) # TODO: add test for min_exception case (use rob's sequence from # 20130624 with 65C Tm) if min_exception: len_met = all([len(x) >= overlap_min for x in overlaps]) # See if len_met is true - if so do nothing if len_met: break else: while not len_met and not maxed: # Recalculate overlaps and their Tms overlaps = _recalculate_overlaps(dna, overlaps, oligo_indices) # Overlap to increase is the shortest one overlap_lens = [len(overlap) for overlap in overlaps] index = overlap_lens.index(min(overlap_lens)) # Increase left or right oligo oligos = _expand_overlap(dna, oligo_indices, index, oligos, length_max) # Recalculate conditions maxed = any([len(x) == length_max for x in oligos]) len_met = all([len(x) >= overlap_min for x in overlaps]) # Recalculate tms to reflect any changes (some are redundant) overlap_tms[index] = coral.analysis.tm(overlaps[index]) # Outcome could be that len_met happened *or* maxed out # length of one of the oligos. If len_met happened, should be # done so long as tm_met has been satisfied. If maxed happened, # len_met will not have been met, even if tm_met is satisfied, # and script will reattempt with more oligos oligo_n += oligo_increment # Calculate location of overlaps overlap_indices = [(oligo_indices[0][x + 1], oligo_indices[1][x]) for x in range(overlap_n)] return oligos, overlaps, overlap_tms, overlap_indices
[ "def", "_grow_overlaps", "(", "dna", ",", "melting_temp", ",", "require_even", ",", "length_max", ",", "overlap_min", ",", "min_exception", ")", ":", "# TODO: prevent growing overlaps from bumping into each other -", "# should halt when it happens, give warning, let user decide if they still", "# want the current construct", "# Another option would be to start over, moving the starting positions", "# near the problem region a little farther from each other - this would", "# put the AT-rich region in the middle of the spanning oligo", "# Try bare minimum number of oligos", "oligo_n", "=", "len", "(", "dna", ")", "//", "length_max", "+", "1", "# Adjust number of oligos if even number required", "if", "require_even", ":", "oligo_increment", "=", "2", "if", "oligo_n", "%", "2", "==", "1", ":", "oligo_n", "+=", "1", "else", ":", "oligo_increment", "=", "1", "# Increase oligo number until the minimum oligo_len is less than length_max", "while", "float", "(", "len", "(", "dna", ")", ")", "/", "oligo_n", ">", "length_max", ":", "oligo_n", "+=", "oligo_increment", "# Loop until all overlaps meet minimum Tm and length", "tm_met", "=", "False", "len_met", "=", "False", "while", "(", "not", "tm_met", "or", "not", "len_met", ")", ":", "# Calculate initial number of overlaps", "overlap_n", "=", "oligo_n", "-", "1", "# Place overlaps approximately equidistant over sequence length", "overlap_interval", "=", "float", "(", "len", "(", "dna", ")", ")", "/", "oligo_n", "starts", "=", "[", "int", "(", "overlap_interval", "*", "(", "i", "+", "1", ")", ")", "for", "i", "in", "range", "(", "overlap_n", ")", "]", "ends", "=", "[", "index", "+", "1", "for", "index", "in", "starts", "]", "# Fencepost for while loop", "# Initial overlaps (1 base) and their tms", "overlaps", "=", "[", "dna", "[", "start", ":", "end", "]", "for", "start", ",", "end", "in", "zip", "(", "starts", ",", "ends", ")", "]", "overlap_tms", "=", "[", "coral", ".", "analysis", ".", "tm", "(", "overlap", ")", "for", "overlap", "in", "overlaps", "]", "index", "=", "overlap_tms", ".", "index", "(", "min", "(", "overlap_tms", ")", ")", "# Initial oligos - includes the 1 base overlaps.", "# All the oligos are in the same direction - reverse", "# complementation of every other one happens later", "oligo_starts", "=", "[", "0", "]", "+", "starts", "oligo_ends", "=", "ends", "+", "[", "len", "(", "dna", ")", "]", "oligo_indices", "=", "[", "oligo_starts", ",", "oligo_ends", "]", "oligos", "=", "[", "dna", "[", "start", ":", "end", "]", "for", "start", ",", "end", "in", "zip", "(", "*", "oligo_indices", ")", "]", "# Oligo won't be maxed in first pass. tm_met and len_met will be false", "maxed", "=", "False", "while", "not", "(", "tm_met", "and", "len_met", ")", "and", "not", "maxed", ":", "# Recalculate overlaps and their Tms", "overlaps", "=", "_recalculate_overlaps", "(", "dna", ",", "overlaps", ",", "oligo_indices", ")", "# Tm calculation is bottleneck - only recalculate changed overlap", "overlap_tms", "[", "index", "]", "=", "coral", ".", "analysis", ".", "tm", "(", "overlaps", "[", "index", "]", ")", "# Find lowest-Tm overlap and its index.", "index", "=", "overlap_tms", ".", "index", "(", "min", "(", "overlap_tms", ")", ")", "# Move overlap at that index", "oligos", "=", "_expand_overlap", "(", "dna", ",", "oligo_indices", ",", "index", ",", "oligos", ",", "length_max", ")", "# Regenerate conditions", "maxed", "=", "any", "(", "[", "len", "(", "x", ")", "==", "length_max", "for", "x", "in", "oligos", "]", ")", "tm_met", "=", "all", "(", "[", "x", ">=", "melting_temp", "for", "x", "in", "overlap_tms", "]", ")", "if", "min_exception", ":", "len_met", "=", "True", "else", ":", "len_met", "=", "all", "(", "[", "len", "(", "x", ")", ">=", "overlap_min", "for", "x", "in", "overlaps", "]", ")", "# TODO: add test for min_exception case (use rob's sequence from", "# 20130624 with 65C Tm)", "if", "min_exception", ":", "len_met", "=", "all", "(", "[", "len", "(", "x", ")", ">=", "overlap_min", "for", "x", "in", "overlaps", "]", ")", "# See if len_met is true - if so do nothing", "if", "len_met", ":", "break", "else", ":", "while", "not", "len_met", "and", "not", "maxed", ":", "# Recalculate overlaps and their Tms", "overlaps", "=", "_recalculate_overlaps", "(", "dna", ",", "overlaps", ",", "oligo_indices", ")", "# Overlap to increase is the shortest one", "overlap_lens", "=", "[", "len", "(", "overlap", ")", "for", "overlap", "in", "overlaps", "]", "index", "=", "overlap_lens", ".", "index", "(", "min", "(", "overlap_lens", ")", ")", "# Increase left or right oligo", "oligos", "=", "_expand_overlap", "(", "dna", ",", "oligo_indices", ",", "index", ",", "oligos", ",", "length_max", ")", "# Recalculate conditions", "maxed", "=", "any", "(", "[", "len", "(", "x", ")", "==", "length_max", "for", "x", "in", "oligos", "]", ")", "len_met", "=", "all", "(", "[", "len", "(", "x", ")", ">=", "overlap_min", "for", "x", "in", "overlaps", "]", ")", "# Recalculate tms to reflect any changes (some are redundant)", "overlap_tms", "[", "index", "]", "=", "coral", ".", "analysis", ".", "tm", "(", "overlaps", "[", "index", "]", ")", "# Outcome could be that len_met happened *or* maxed out", "# length of one of the oligos. If len_met happened, should be", "# done so long as tm_met has been satisfied. If maxed happened,", "# len_met will not have been met, even if tm_met is satisfied,", "# and script will reattempt with more oligos", "oligo_n", "+=", "oligo_increment", "# Calculate location of overlaps", "overlap_indices", "=", "[", "(", "oligo_indices", "[", "0", "]", "[", "x", "+", "1", "]", ",", "oligo_indices", "[", "1", "]", "[", "x", "]", ")", "for", "x", "in", "range", "(", "overlap_n", ")", "]", "return", "oligos", ",", "overlaps", ",", "overlap_tms", ",", "overlap_indices" ]
Grows equidistant overlaps until they meet specified constraints. :param dna: Input sequence. :type dna: coral.DNA :param melting_temp: Ideal Tm of the overlaps, in degrees C. :type melting_temp: float :param require_even: Require that the number of oligonucleotides is even. :type require_even: bool :param length_max: Maximum oligo size (e.g. 60bp price point cutoff) range. :type length_range: int :param overlap_min: Minimum overlap size. :type overlap_min: int :param min_exception: In order to meet melting_temp and overlap_min settings, allow overlaps less than overlap_min to continue growing above melting_temp. :type min_exception: bool :returns: Oligos, their overlapping regions, overlap Tms, and overlap indices. :rtype: tuple
[ "Grows", "equidistant", "overlaps", "until", "they", "meet", "specified", "constraints", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L215-L347
klavinslab/coral
coral/design/_oligo_synthesis/oligo_assembly.py
_recalculate_overlaps
def _recalculate_overlaps(dna, overlaps, oligo_indices): '''Recalculate overlap sequences based on the current overlap indices. :param dna: Sequence being split into oligos. :type dna: coral.DNA :param overlaps: Current overlaps - a list of DNA sequences. :type overlaps: coral.DNA list :param oligo_indices: List of oligo indices (starts and stops). :type oligo_indices: list :returns: Overlap sequences. :rtype: coral.DNA list ''' for i, overlap in enumerate(overlaps): first_index = oligo_indices[0][i + 1] second_index = oligo_indices[1][i] overlap = dna[first_index:second_index] overlaps[i] = overlap return overlaps
python
def _recalculate_overlaps(dna, overlaps, oligo_indices): '''Recalculate overlap sequences based on the current overlap indices. :param dna: Sequence being split into oligos. :type dna: coral.DNA :param overlaps: Current overlaps - a list of DNA sequences. :type overlaps: coral.DNA list :param oligo_indices: List of oligo indices (starts and stops). :type oligo_indices: list :returns: Overlap sequences. :rtype: coral.DNA list ''' for i, overlap in enumerate(overlaps): first_index = oligo_indices[0][i + 1] second_index = oligo_indices[1][i] overlap = dna[first_index:second_index] overlaps[i] = overlap return overlaps
[ "def", "_recalculate_overlaps", "(", "dna", ",", "overlaps", ",", "oligo_indices", ")", ":", "for", "i", ",", "overlap", "in", "enumerate", "(", "overlaps", ")", ":", "first_index", "=", "oligo_indices", "[", "0", "]", "[", "i", "+", "1", "]", "second_index", "=", "oligo_indices", "[", "1", "]", "[", "i", "]", "overlap", "=", "dna", "[", "first_index", ":", "second_index", "]", "overlaps", "[", "i", "]", "=", "overlap", "return", "overlaps" ]
Recalculate overlap sequences based on the current overlap indices. :param dna: Sequence being split into oligos. :type dna: coral.DNA :param overlaps: Current overlaps - a list of DNA sequences. :type overlaps: coral.DNA list :param oligo_indices: List of oligo indices (starts and stops). :type oligo_indices: list :returns: Overlap sequences. :rtype: coral.DNA list
[ "Recalculate", "overlap", "sequences", "based", "on", "the", "current", "overlap", "indices", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L350-L369
klavinslab/coral
coral/design/_oligo_synthesis/oligo_assembly.py
_expand_overlap
def _expand_overlap(dna, oligo_indices, index, oligos, length_max): '''Given an overlap to increase, increases smaller oligo. :param dna: Sequence being split into oligos. :type dna: coral.DNA :param oligo_indices: index of oligo starts and stops :type oligo_indices: list :param index: index of the oligo :type index: int :param left_len: length of left oligo :type left_len: int :param right_len: length of right oligo :type right_len: int :param length_max: length ceiling :type length_max: int :returns: New oligo list with one expanded. :rtype: list ''' left_len = len(oligos[index]) right_len = len(oligos[index + 1]) # If one of the oligos is max size, increase the other one if right_len == length_max: oligo_indices[1] = _adjust_overlap(oligo_indices[1], index, 'right') elif left_len == length_max: oligo_indices[0] = _adjust_overlap(oligo_indices[0], index, 'left') else: if left_len > right_len: oligo_indices[0] = _adjust_overlap(oligo_indices[0], index, 'left') else: oligo_indices[1] = _adjust_overlap(oligo_indices[1], index, 'right') # Recalculate oligos from start and end indices oligos = [dna[start:end] for start, end in zip(*oligo_indices)] return oligos
python
def _expand_overlap(dna, oligo_indices, index, oligos, length_max): '''Given an overlap to increase, increases smaller oligo. :param dna: Sequence being split into oligos. :type dna: coral.DNA :param oligo_indices: index of oligo starts and stops :type oligo_indices: list :param index: index of the oligo :type index: int :param left_len: length of left oligo :type left_len: int :param right_len: length of right oligo :type right_len: int :param length_max: length ceiling :type length_max: int :returns: New oligo list with one expanded. :rtype: list ''' left_len = len(oligos[index]) right_len = len(oligos[index + 1]) # If one of the oligos is max size, increase the other one if right_len == length_max: oligo_indices[1] = _adjust_overlap(oligo_indices[1], index, 'right') elif left_len == length_max: oligo_indices[0] = _adjust_overlap(oligo_indices[0], index, 'left') else: if left_len > right_len: oligo_indices[0] = _adjust_overlap(oligo_indices[0], index, 'left') else: oligo_indices[1] = _adjust_overlap(oligo_indices[1], index, 'right') # Recalculate oligos from start and end indices oligos = [dna[start:end] for start, end in zip(*oligo_indices)] return oligos
[ "def", "_expand_overlap", "(", "dna", ",", "oligo_indices", ",", "index", ",", "oligos", ",", "length_max", ")", ":", "left_len", "=", "len", "(", "oligos", "[", "index", "]", ")", "right_len", "=", "len", "(", "oligos", "[", "index", "+", "1", "]", ")", "# If one of the oligos is max size, increase the other one", "if", "right_len", "==", "length_max", ":", "oligo_indices", "[", "1", "]", "=", "_adjust_overlap", "(", "oligo_indices", "[", "1", "]", ",", "index", ",", "'right'", ")", "elif", "left_len", "==", "length_max", ":", "oligo_indices", "[", "0", "]", "=", "_adjust_overlap", "(", "oligo_indices", "[", "0", "]", ",", "index", ",", "'left'", ")", "else", ":", "if", "left_len", ">", "right_len", ":", "oligo_indices", "[", "0", "]", "=", "_adjust_overlap", "(", "oligo_indices", "[", "0", "]", ",", "index", ",", "'left'", ")", "else", ":", "oligo_indices", "[", "1", "]", "=", "_adjust_overlap", "(", "oligo_indices", "[", "1", "]", ",", "index", ",", "'right'", ")", "# Recalculate oligos from start and end indices", "oligos", "=", "[", "dna", "[", "start", ":", "end", "]", "for", "start", ",", "end", "in", "zip", "(", "*", "oligo_indices", ")", "]", "return", "oligos" ]
Given an overlap to increase, increases smaller oligo. :param dna: Sequence being split into oligos. :type dna: coral.DNA :param oligo_indices: index of oligo starts and stops :type oligo_indices: list :param index: index of the oligo :type index: int :param left_len: length of left oligo :type left_len: int :param right_len: length of right oligo :type right_len: int :param length_max: length ceiling :type length_max: int :returns: New oligo list with one expanded. :rtype: list
[ "Given", "an", "overlap", "to", "increase", "increases", "smaller", "oligo", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L372-L409
klavinslab/coral
coral/design/_oligo_synthesis/oligo_assembly.py
_adjust_overlap
def _adjust_overlap(positions_list, index, direction): '''Increase overlap to the right or left of an index. :param positions_list: list of overlap positions :type positions_list: list :param index: index of the overlap to increase. :type index: int :param direction: which side of the overlap to increase - left or right. :type direction: str :returns: A list of overlap positions (2-element lists) :rtype: list :raises: ValueError if direction isn't \'left\' or \'right\'. ''' if direction == 'left': positions_list[index + 1] -= 1 elif direction == 'right': positions_list[index] += 1 else: raise ValueError('direction must be \'left\' or \'right\'.') return positions_list
python
def _adjust_overlap(positions_list, index, direction): '''Increase overlap to the right or left of an index. :param positions_list: list of overlap positions :type positions_list: list :param index: index of the overlap to increase. :type index: int :param direction: which side of the overlap to increase - left or right. :type direction: str :returns: A list of overlap positions (2-element lists) :rtype: list :raises: ValueError if direction isn't \'left\' or \'right\'. ''' if direction == 'left': positions_list[index + 1] -= 1 elif direction == 'right': positions_list[index] += 1 else: raise ValueError('direction must be \'left\' or \'right\'.') return positions_list
[ "def", "_adjust_overlap", "(", "positions_list", ",", "index", ",", "direction", ")", ":", "if", "direction", "==", "'left'", ":", "positions_list", "[", "index", "+", "1", "]", "-=", "1", "elif", "direction", "==", "'right'", ":", "positions_list", "[", "index", "]", "+=", "1", "else", ":", "raise", "ValueError", "(", "'direction must be \\'left\\' or \\'right\\'.'", ")", "return", "positions_list" ]
Increase overlap to the right or left of an index. :param positions_list: list of overlap positions :type positions_list: list :param index: index of the overlap to increase. :type index: int :param direction: which side of the overlap to increase - left or right. :type direction: str :returns: A list of overlap positions (2-element lists) :rtype: list :raises: ValueError if direction isn't \'left\' or \'right\'.
[ "Increase", "overlap", "to", "the", "right", "or", "left", "of", "an", "index", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L412-L432
klavinslab/coral
coral/design/_oligo_synthesis/oligo_assembly.py
OligoAssembly.design_assembly
def design_assembly(self): '''Design the overlapping oligos. :returns: Assembly oligos, and the sequences, Tms, and indices of their overlapping regions. :rtype: dict ''' # Input parameters needed to design the oligos length_range = self.kwargs['length_range'] oligo_number = self.kwargs['oligo_number'] require_even = self.kwargs['require_even'] melting_temp = self.kwargs['tm'] overlap_min = self.kwargs['overlap_min'] min_exception = self.kwargs['min_exception'] start_5 = self.kwargs['start_5'] if len(self.template) < length_range[0]: # If sequence can be built with just two oligos, do that oligos = [self.template, self.template.reverse_complement()] overlaps = [self.template] overlap_tms = [coral.analysis.tm(self.template)] assembly_dict = {'oligos': oligos, 'overlaps': overlaps, 'overlap_tms': overlap_tms} self.oligos = assembly_dict['oligos'] self.overlaps = assembly_dict['overlaps'] self.overlap_tms = assembly_dict['overlap_tms'] return assembly_dict if oligo_number: # Make first attempt using length_range[1] and see what happens step = 3 # Decrease max range by this amount each iteration length_max = length_range[1] current_oligo_n = oligo_number + 1 oligo_n_met = False above_min_len = length_max > length_range[0] if oligo_n_met or not above_min_len: raise Exception('Failed to design assembly.') while not oligo_n_met and above_min_len: # Starting with low range and going up doesnt work for longer # sequence (overlaps become longer than 80) assembly = _grow_overlaps(self.template, melting_temp, require_even, length_max, overlap_min, min_exception) current_oligo_n = len(assembly[0]) if current_oligo_n > oligo_number: break length_max -= step oligo_n_met = current_oligo_n == oligo_number else: assembly = _grow_overlaps(self.template, melting_temp, require_even, length_range[1], overlap_min, min_exception) oligos, overlaps, overlap_tms, overlap_indices = assembly if start_5: for i in [x for x in range(len(oligos)) if x % 2 == 1]: oligos[i] = oligos[i].reverse_complement() else: for i in [x for x in range(len(oligos)) if x % 2 == 0]: oligos[i] = oligos[i].reverse_complement() # Make single-stranded oligos = [oligo.top for oligo in oligos] assembly_dict = {'oligos': oligos, 'overlaps': overlaps, 'overlap_tms': overlap_tms, 'overlap_indices': overlap_indices} self.oligos = assembly_dict['oligos'] self.overlaps = assembly_dict['overlaps'] self.overlap_tms = assembly_dict['overlap_tms'] self.overlap_indices = assembly_dict['overlap_indices'] for i in range(len(self.overlap_indices) - 1): # TODO: either raise an exception or prevent this from happening # at all current_start = self.overlap_indices[i + 1][0] current_end = self.overlap_indices[i][1] if current_start <= current_end: self.warning = 'warning: overlapping overlaps!' print self.warning self._has_run = True return assembly_dict
python
def design_assembly(self): '''Design the overlapping oligos. :returns: Assembly oligos, and the sequences, Tms, and indices of their overlapping regions. :rtype: dict ''' # Input parameters needed to design the oligos length_range = self.kwargs['length_range'] oligo_number = self.kwargs['oligo_number'] require_even = self.kwargs['require_even'] melting_temp = self.kwargs['tm'] overlap_min = self.kwargs['overlap_min'] min_exception = self.kwargs['min_exception'] start_5 = self.kwargs['start_5'] if len(self.template) < length_range[0]: # If sequence can be built with just two oligos, do that oligos = [self.template, self.template.reverse_complement()] overlaps = [self.template] overlap_tms = [coral.analysis.tm(self.template)] assembly_dict = {'oligos': oligos, 'overlaps': overlaps, 'overlap_tms': overlap_tms} self.oligos = assembly_dict['oligos'] self.overlaps = assembly_dict['overlaps'] self.overlap_tms = assembly_dict['overlap_tms'] return assembly_dict if oligo_number: # Make first attempt using length_range[1] and see what happens step = 3 # Decrease max range by this amount each iteration length_max = length_range[1] current_oligo_n = oligo_number + 1 oligo_n_met = False above_min_len = length_max > length_range[0] if oligo_n_met or not above_min_len: raise Exception('Failed to design assembly.') while not oligo_n_met and above_min_len: # Starting with low range and going up doesnt work for longer # sequence (overlaps become longer than 80) assembly = _grow_overlaps(self.template, melting_temp, require_even, length_max, overlap_min, min_exception) current_oligo_n = len(assembly[0]) if current_oligo_n > oligo_number: break length_max -= step oligo_n_met = current_oligo_n == oligo_number else: assembly = _grow_overlaps(self.template, melting_temp, require_even, length_range[1], overlap_min, min_exception) oligos, overlaps, overlap_tms, overlap_indices = assembly if start_5: for i in [x for x in range(len(oligos)) if x % 2 == 1]: oligos[i] = oligos[i].reverse_complement() else: for i in [x for x in range(len(oligos)) if x % 2 == 0]: oligos[i] = oligos[i].reverse_complement() # Make single-stranded oligos = [oligo.top for oligo in oligos] assembly_dict = {'oligos': oligos, 'overlaps': overlaps, 'overlap_tms': overlap_tms, 'overlap_indices': overlap_indices} self.oligos = assembly_dict['oligos'] self.overlaps = assembly_dict['overlaps'] self.overlap_tms = assembly_dict['overlap_tms'] self.overlap_indices = assembly_dict['overlap_indices'] for i in range(len(self.overlap_indices) - 1): # TODO: either raise an exception or prevent this from happening # at all current_start = self.overlap_indices[i + 1][0] current_end = self.overlap_indices[i][1] if current_start <= current_end: self.warning = 'warning: overlapping overlaps!' print self.warning self._has_run = True return assembly_dict
[ "def", "design_assembly", "(", "self", ")", ":", "# Input parameters needed to design the oligos", "length_range", "=", "self", ".", "kwargs", "[", "'length_range'", "]", "oligo_number", "=", "self", ".", "kwargs", "[", "'oligo_number'", "]", "require_even", "=", "self", ".", "kwargs", "[", "'require_even'", "]", "melting_temp", "=", "self", ".", "kwargs", "[", "'tm'", "]", "overlap_min", "=", "self", ".", "kwargs", "[", "'overlap_min'", "]", "min_exception", "=", "self", ".", "kwargs", "[", "'min_exception'", "]", "start_5", "=", "self", ".", "kwargs", "[", "'start_5'", "]", "if", "len", "(", "self", ".", "template", ")", "<", "length_range", "[", "0", "]", ":", "# If sequence can be built with just two oligos, do that", "oligos", "=", "[", "self", ".", "template", ",", "self", ".", "template", ".", "reverse_complement", "(", ")", "]", "overlaps", "=", "[", "self", ".", "template", "]", "overlap_tms", "=", "[", "coral", ".", "analysis", ".", "tm", "(", "self", ".", "template", ")", "]", "assembly_dict", "=", "{", "'oligos'", ":", "oligos", ",", "'overlaps'", ":", "overlaps", ",", "'overlap_tms'", ":", "overlap_tms", "}", "self", ".", "oligos", "=", "assembly_dict", "[", "'oligos'", "]", "self", ".", "overlaps", "=", "assembly_dict", "[", "'overlaps'", "]", "self", ".", "overlap_tms", "=", "assembly_dict", "[", "'overlap_tms'", "]", "return", "assembly_dict", "if", "oligo_number", ":", "# Make first attempt using length_range[1] and see what happens", "step", "=", "3", "# Decrease max range by this amount each iteration", "length_max", "=", "length_range", "[", "1", "]", "current_oligo_n", "=", "oligo_number", "+", "1", "oligo_n_met", "=", "False", "above_min_len", "=", "length_max", ">", "length_range", "[", "0", "]", "if", "oligo_n_met", "or", "not", "above_min_len", ":", "raise", "Exception", "(", "'Failed to design assembly.'", ")", "while", "not", "oligo_n_met", "and", "above_min_len", ":", "# Starting with low range and going up doesnt work for longer", "# sequence (overlaps become longer than 80)", "assembly", "=", "_grow_overlaps", "(", "self", ".", "template", ",", "melting_temp", ",", "require_even", ",", "length_max", ",", "overlap_min", ",", "min_exception", ")", "current_oligo_n", "=", "len", "(", "assembly", "[", "0", "]", ")", "if", "current_oligo_n", ">", "oligo_number", ":", "break", "length_max", "-=", "step", "oligo_n_met", "=", "current_oligo_n", "==", "oligo_number", "else", ":", "assembly", "=", "_grow_overlaps", "(", "self", ".", "template", ",", "melting_temp", ",", "require_even", ",", "length_range", "[", "1", "]", ",", "overlap_min", ",", "min_exception", ")", "oligos", ",", "overlaps", ",", "overlap_tms", ",", "overlap_indices", "=", "assembly", "if", "start_5", ":", "for", "i", "in", "[", "x", "for", "x", "in", "range", "(", "len", "(", "oligos", ")", ")", "if", "x", "%", "2", "==", "1", "]", ":", "oligos", "[", "i", "]", "=", "oligos", "[", "i", "]", ".", "reverse_complement", "(", ")", "else", ":", "for", "i", "in", "[", "x", "for", "x", "in", "range", "(", "len", "(", "oligos", ")", ")", "if", "x", "%", "2", "==", "0", "]", ":", "oligos", "[", "i", "]", "=", "oligos", "[", "i", "]", ".", "reverse_complement", "(", ")", "# Make single-stranded", "oligos", "=", "[", "oligo", ".", "top", "for", "oligo", "in", "oligos", "]", "assembly_dict", "=", "{", "'oligos'", ":", "oligos", ",", "'overlaps'", ":", "overlaps", ",", "'overlap_tms'", ":", "overlap_tms", ",", "'overlap_indices'", ":", "overlap_indices", "}", "self", ".", "oligos", "=", "assembly_dict", "[", "'oligos'", "]", "self", ".", "overlaps", "=", "assembly_dict", "[", "'overlaps'", "]", "self", ".", "overlap_tms", "=", "assembly_dict", "[", "'overlap_tms'", "]", "self", ".", "overlap_indices", "=", "assembly_dict", "[", "'overlap_indices'", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "overlap_indices", ")", "-", "1", ")", ":", "# TODO: either raise an exception or prevent this from happening", "# at all", "current_start", "=", "self", ".", "overlap_indices", "[", "i", "+", "1", "]", "[", "0", "]", "current_end", "=", "self", ".", "overlap_indices", "[", "i", "]", "[", "1", "]", "if", "current_start", "<=", "current_end", ":", "self", ".", "warning", "=", "'warning: overlapping overlaps!'", "print", "self", ".", "warning", "self", ".", "_has_run", "=", "True", "return", "assembly_dict" ]
Design the overlapping oligos. :returns: Assembly oligos, and the sequences, Tms, and indices of their overlapping regions. :rtype: dict
[ "Design", "the", "overlapping", "oligos", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L57-L145
klavinslab/coral
coral/design/_oligo_synthesis/oligo_assembly.py
OligoAssembly.primers
def primers(self, tm=60): '''Design primers for amplifying the assembled sequence. :param tm: melting temperature (lower than overlaps is best). :type tm: float :returns: Primer list (the output of coral.design.primers). :rtype: list ''' self.primers = coral.design.primers(self.template, tm=tm) return self.primers
python
def primers(self, tm=60): '''Design primers for amplifying the assembled sequence. :param tm: melting temperature (lower than overlaps is best). :type tm: float :returns: Primer list (the output of coral.design.primers). :rtype: list ''' self.primers = coral.design.primers(self.template, tm=tm) return self.primers
[ "def", "primers", "(", "self", ",", "tm", "=", "60", ")", ":", "self", ".", "primers", "=", "coral", ".", "design", ".", "primers", "(", "self", ".", "template", ",", "tm", "=", "tm", ")", "return", "self", ".", "primers" ]
Design primers for amplifying the assembled sequence. :param tm: melting temperature (lower than overlaps is best). :type tm: float :returns: Primer list (the output of coral.design.primers). :rtype: list
[ "Design", "primers", "for", "amplifying", "the", "assembled", "sequence", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L147-L157
klavinslab/coral
coral/design/_oligo_synthesis/oligo_assembly.py
OligoAssembly.write
def write(self, path): '''Write assembly oligos and (if applicable) primers to csv. :param path: path to csv file, including .csv extension. :type path: str ''' with open(path, 'wb') as oligo_file: oligo_writer = csv.writer(oligo_file, delimiter=',', quoting=csv.QUOTE_MINIMAL) oligo_writer.writerow(['name', 'oligo', 'notes']) for i, oligo in enumerate(self.oligos): name = 'oligo {}'.format(i + 1) oligo_len = len(oligo) if i != len(self.oligos) - 1: oligo_tm = self.overlap_tms[i] notes = 'oligo length: {}, '.format(oligo_len) + \ 'overlap Tm: {:.2f}'.format(oligo_tm) else: notes = 'oligo length: {}'.format(oligo_len) oligo_writer.writerow([name, oligo, notes]) if self.primers: for i, (primer, melt) in enumerate(self.primers): oligo_writer.writerow(['primer {}'.format(i + 1), primer, 'Tm: {:.2f}'.format(melt)])
python
def write(self, path): '''Write assembly oligos and (if applicable) primers to csv. :param path: path to csv file, including .csv extension. :type path: str ''' with open(path, 'wb') as oligo_file: oligo_writer = csv.writer(oligo_file, delimiter=',', quoting=csv.QUOTE_MINIMAL) oligo_writer.writerow(['name', 'oligo', 'notes']) for i, oligo in enumerate(self.oligos): name = 'oligo {}'.format(i + 1) oligo_len = len(oligo) if i != len(self.oligos) - 1: oligo_tm = self.overlap_tms[i] notes = 'oligo length: {}, '.format(oligo_len) + \ 'overlap Tm: {:.2f}'.format(oligo_tm) else: notes = 'oligo length: {}'.format(oligo_len) oligo_writer.writerow([name, oligo, notes]) if self.primers: for i, (primer, melt) in enumerate(self.primers): oligo_writer.writerow(['primer {}'.format(i + 1), primer, 'Tm: {:.2f}'.format(melt)])
[ "def", "write", "(", "self", ",", "path", ")", ":", "with", "open", "(", "path", ",", "'wb'", ")", "as", "oligo_file", ":", "oligo_writer", "=", "csv", ".", "writer", "(", "oligo_file", ",", "delimiter", "=", "','", ",", "quoting", "=", "csv", ".", "QUOTE_MINIMAL", ")", "oligo_writer", ".", "writerow", "(", "[", "'name'", ",", "'oligo'", ",", "'notes'", "]", ")", "for", "i", ",", "oligo", "in", "enumerate", "(", "self", ".", "oligos", ")", ":", "name", "=", "'oligo {}'", ".", "format", "(", "i", "+", "1", ")", "oligo_len", "=", "len", "(", "oligo", ")", "if", "i", "!=", "len", "(", "self", ".", "oligos", ")", "-", "1", ":", "oligo_tm", "=", "self", ".", "overlap_tms", "[", "i", "]", "notes", "=", "'oligo length: {}, '", ".", "format", "(", "oligo_len", ")", "+", "'overlap Tm: {:.2f}'", ".", "format", "(", "oligo_tm", ")", "else", ":", "notes", "=", "'oligo length: {}'", ".", "format", "(", "oligo_len", ")", "oligo_writer", ".", "writerow", "(", "[", "name", ",", "oligo", ",", "notes", "]", ")", "if", "self", ".", "primers", ":", "for", "i", ",", "(", "primer", ",", "melt", ")", "in", "enumerate", "(", "self", ".", "primers", ")", ":", "oligo_writer", ".", "writerow", "(", "[", "'primer {}'", ".", "format", "(", "i", "+", "1", ")", ",", "primer", ",", "'Tm: {:.2f}'", ".", "format", "(", "melt", ")", "]", ")" ]
Write assembly oligos and (if applicable) primers to csv. :param path: path to csv file, including .csv extension. :type path: str
[ "Write", "assembly", "oligos", "and", "(", "if", "applicable", ")", "primers", "to", "csv", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L159-L184
klavinslab/coral
coral/design/_oligo_synthesis/oligo_assembly.py
OligoAssembly.write_map
def write_map(self, path): '''Write genbank map that highlights overlaps. :param path: full path to .gb file to write. :type path: str ''' starts = [index[0] for index in self.overlap_indices] features = [] for i, start in enumerate(starts): stop = start + len(self.overlaps[i]) name = 'overlap {}'.format(i + 1) feature_type = 'misc' strand = 0 features.append(coral.Feature(name, start, stop, feature_type, strand=strand)) seq_map = coral.DNA(self.template, features=features) coral.seqio.write_dna(seq_map, path)
python
def write_map(self, path): '''Write genbank map that highlights overlaps. :param path: full path to .gb file to write. :type path: str ''' starts = [index[0] for index in self.overlap_indices] features = [] for i, start in enumerate(starts): stop = start + len(self.overlaps[i]) name = 'overlap {}'.format(i + 1) feature_type = 'misc' strand = 0 features.append(coral.Feature(name, start, stop, feature_type, strand=strand)) seq_map = coral.DNA(self.template, features=features) coral.seqio.write_dna(seq_map, path)
[ "def", "write_map", "(", "self", ",", "path", ")", ":", "starts", "=", "[", "index", "[", "0", "]", "for", "index", "in", "self", ".", "overlap_indices", "]", "features", "=", "[", "]", "for", "i", ",", "start", "in", "enumerate", "(", "starts", ")", ":", "stop", "=", "start", "+", "len", "(", "self", ".", "overlaps", "[", "i", "]", ")", "name", "=", "'overlap {}'", ".", "format", "(", "i", "+", "1", ")", "feature_type", "=", "'misc'", "strand", "=", "0", "features", ".", "append", "(", "coral", ".", "Feature", "(", "name", ",", "start", ",", "stop", ",", "feature_type", ",", "strand", "=", "strand", ")", ")", "seq_map", "=", "coral", ".", "DNA", "(", "self", ".", "template", ",", "features", "=", "features", ")", "coral", ".", "seqio", ".", "write_dna", "(", "seq_map", ",", "path", ")" ]
Write genbank map that highlights overlaps. :param path: full path to .gb file to write. :type path: str
[ "Write", "genbank", "map", "that", "highlights", "overlaps", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L186-L203
klavinslab/coral
coral/reaction/_central_dogma.py
coding_sequence
def coding_sequence(rna): '''Extract coding sequence from an RNA template. :param seq: Sequence from which to extract a coding sequence. :type seq: coral.RNA :param material: Type of sequence ('dna' or 'rna') :type material: str :returns: The first coding sequence (start codon -> stop codon) matched from 5' to 3'. :rtype: coral.RNA :raises: ValueError if rna argument has no start codon. ValueError if rna argument has no stop codon in-frame with the first start codon. ''' if isinstance(rna, coral.DNA): rna = transcribe(rna) codons_left = len(rna) // 3 start_codon = coral.RNA('aug') stop_codons = [coral.RNA('uag'), coral.RNA('uga'), coral.RNA('uaa')] start = None stop = None valid = [None, None] index = 0 while codons_left: codon = rna[index:index + 3] if valid[0] is None: if codon in start_codon: start = index valid[0] = True else: if codon in stop_codons: stop = index + 3 valid[1] = True break index += 3 codons_left -= 1 if valid[0] is None: raise ValueError('Sequence has no start codon.') elif stop is None: raise ValueError('Sequence has no stop codon.') coding_rna = rna[start:stop] return coding_rna
python
def coding_sequence(rna): '''Extract coding sequence from an RNA template. :param seq: Sequence from which to extract a coding sequence. :type seq: coral.RNA :param material: Type of sequence ('dna' or 'rna') :type material: str :returns: The first coding sequence (start codon -> stop codon) matched from 5' to 3'. :rtype: coral.RNA :raises: ValueError if rna argument has no start codon. ValueError if rna argument has no stop codon in-frame with the first start codon. ''' if isinstance(rna, coral.DNA): rna = transcribe(rna) codons_left = len(rna) // 3 start_codon = coral.RNA('aug') stop_codons = [coral.RNA('uag'), coral.RNA('uga'), coral.RNA('uaa')] start = None stop = None valid = [None, None] index = 0 while codons_left: codon = rna[index:index + 3] if valid[0] is None: if codon in start_codon: start = index valid[0] = True else: if codon in stop_codons: stop = index + 3 valid[1] = True break index += 3 codons_left -= 1 if valid[0] is None: raise ValueError('Sequence has no start codon.') elif stop is None: raise ValueError('Sequence has no stop codon.') coding_rna = rna[start:stop] return coding_rna
[ "def", "coding_sequence", "(", "rna", ")", ":", "if", "isinstance", "(", "rna", ",", "coral", ".", "DNA", ")", ":", "rna", "=", "transcribe", "(", "rna", ")", "codons_left", "=", "len", "(", "rna", ")", "//", "3", "start_codon", "=", "coral", ".", "RNA", "(", "'aug'", ")", "stop_codons", "=", "[", "coral", ".", "RNA", "(", "'uag'", ")", ",", "coral", ".", "RNA", "(", "'uga'", ")", ",", "coral", ".", "RNA", "(", "'uaa'", ")", "]", "start", "=", "None", "stop", "=", "None", "valid", "=", "[", "None", ",", "None", "]", "index", "=", "0", "while", "codons_left", ":", "codon", "=", "rna", "[", "index", ":", "index", "+", "3", "]", "if", "valid", "[", "0", "]", "is", "None", ":", "if", "codon", "in", "start_codon", ":", "start", "=", "index", "valid", "[", "0", "]", "=", "True", "else", ":", "if", "codon", "in", "stop_codons", ":", "stop", "=", "index", "+", "3", "valid", "[", "1", "]", "=", "True", "break", "index", "+=", "3", "codons_left", "-=", "1", "if", "valid", "[", "0", "]", "is", "None", ":", "raise", "ValueError", "(", "'Sequence has no start codon.'", ")", "elif", "stop", "is", "None", ":", "raise", "ValueError", "(", "'Sequence has no stop codon.'", ")", "coding_rna", "=", "rna", "[", "start", ":", "stop", "]", "return", "coding_rna" ]
Extract coding sequence from an RNA template. :param seq: Sequence from which to extract a coding sequence. :type seq: coral.RNA :param material: Type of sequence ('dna' or 'rna') :type material: str :returns: The first coding sequence (start codon -> stop codon) matched from 5' to 3'. :rtype: coral.RNA :raises: ValueError if rna argument has no start codon. ValueError if rna argument has no stop codon in-frame with the first start codon.
[ "Extract", "coding", "sequence", "from", "an", "RNA", "template", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_central_dogma.py#L42-L86
klavinslab/coral
coral/database/_rebase.py
Rebase.update
def update(self): '''Update definitions.''' # Download http://rebase.neb.com/rebase/link_withref to tmp self._tmpdir = tempfile.mkdtemp() try: self._rebase_file = self._tmpdir + '/rebase_file' print 'Downloading latest enzyme definitions' url = 'http://rebase.neb.com/rebase/link_withref' header = {'User-Agent': 'Mozilla/5.0'} req = urllib2.Request(url, headers=header) con = urllib2.urlopen(req) with open(self._rebase_file, 'wb') as rebase_file: rebase_file.write(con.read()) # Process into self._enzyme_dict self._process_file() except urllib2.HTTPError, e: print 'HTTP Error: {} {}'.format(e.code, url) print 'Falling back on default enzyme list' self._enzyme_dict = coral.constants.fallback_enzymes except urllib2.URLError, e: print 'URL Error: {} {}'.format(e.reason, url) print 'Falling back on default enzyme list' self._enzyme_dict = coral.constants.fallback_enzymes # Process into RestrictionSite objects? (depends on speed) print 'Processing into RestrictionSite instances.' self.restriction_sites = {} # TODO: make sure all names are unique for key, (site, cuts) in self._enzyme_dict.iteritems(): # Make a site try: r = coral.RestrictionSite(coral.DNA(site), cuts, name=key) # Add it to dict with name as key self.restriction_sites[key] = r except ValueError: # Encountered ambiguous sequence, have to ignore it until # coral.DNA can handle ambiguous DNA pass
python
def update(self): '''Update definitions.''' # Download http://rebase.neb.com/rebase/link_withref to tmp self._tmpdir = tempfile.mkdtemp() try: self._rebase_file = self._tmpdir + '/rebase_file' print 'Downloading latest enzyme definitions' url = 'http://rebase.neb.com/rebase/link_withref' header = {'User-Agent': 'Mozilla/5.0'} req = urllib2.Request(url, headers=header) con = urllib2.urlopen(req) with open(self._rebase_file, 'wb') as rebase_file: rebase_file.write(con.read()) # Process into self._enzyme_dict self._process_file() except urllib2.HTTPError, e: print 'HTTP Error: {} {}'.format(e.code, url) print 'Falling back on default enzyme list' self._enzyme_dict = coral.constants.fallback_enzymes except urllib2.URLError, e: print 'URL Error: {} {}'.format(e.reason, url) print 'Falling back on default enzyme list' self._enzyme_dict = coral.constants.fallback_enzymes # Process into RestrictionSite objects? (depends on speed) print 'Processing into RestrictionSite instances.' self.restriction_sites = {} # TODO: make sure all names are unique for key, (site, cuts) in self._enzyme_dict.iteritems(): # Make a site try: r = coral.RestrictionSite(coral.DNA(site), cuts, name=key) # Add it to dict with name as key self.restriction_sites[key] = r except ValueError: # Encountered ambiguous sequence, have to ignore it until # coral.DNA can handle ambiguous DNA pass
[ "def", "update", "(", "self", ")", ":", "# Download http://rebase.neb.com/rebase/link_withref to tmp", "self", ".", "_tmpdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "try", ":", "self", ".", "_rebase_file", "=", "self", ".", "_tmpdir", "+", "'/rebase_file'", "print", "'Downloading latest enzyme definitions'", "url", "=", "'http://rebase.neb.com/rebase/link_withref'", "header", "=", "{", "'User-Agent'", ":", "'Mozilla/5.0'", "}", "req", "=", "urllib2", ".", "Request", "(", "url", ",", "headers", "=", "header", ")", "con", "=", "urllib2", ".", "urlopen", "(", "req", ")", "with", "open", "(", "self", ".", "_rebase_file", ",", "'wb'", ")", "as", "rebase_file", ":", "rebase_file", ".", "write", "(", "con", ".", "read", "(", ")", ")", "# Process into self._enzyme_dict", "self", ".", "_process_file", "(", ")", "except", "urllib2", ".", "HTTPError", ",", "e", ":", "print", "'HTTP Error: {} {}'", ".", "format", "(", "e", ".", "code", ",", "url", ")", "print", "'Falling back on default enzyme list'", "self", ".", "_enzyme_dict", "=", "coral", ".", "constants", ".", "fallback_enzymes", "except", "urllib2", ".", "URLError", ",", "e", ":", "print", "'URL Error: {} {}'", ".", "format", "(", "e", ".", "reason", ",", "url", ")", "print", "'Falling back on default enzyme list'", "self", ".", "_enzyme_dict", "=", "coral", ".", "constants", ".", "fallback_enzymes", "# Process into RestrictionSite objects? (depends on speed)", "print", "'Processing into RestrictionSite instances.'", "self", ".", "restriction_sites", "=", "{", "}", "# TODO: make sure all names are unique", "for", "key", ",", "(", "site", ",", "cuts", ")", "in", "self", ".", "_enzyme_dict", ".", "iteritems", "(", ")", ":", "# Make a site", "try", ":", "r", "=", "coral", ".", "RestrictionSite", "(", "coral", ".", "DNA", "(", "site", ")", ",", "cuts", ",", "name", "=", "key", ")", "# Add it to dict with name as key", "self", ".", "restriction_sites", "[", "key", "]", "=", "r", "except", "ValueError", ":", "# Encountered ambiguous sequence, have to ignore it until", "# coral.DNA can handle ambiguous DNA", "pass" ]
Update definitions.
[ "Update", "definitions", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/database/_rebase.py#L15-L51
klavinslab/coral
coral/database/_rebase.py
Rebase._process_file
def _process_file(self): '''Process rebase file into dict with name and cut site information.''' print 'Processing file' with open(self._rebase_file, 'r') as f: raw = f.readlines() names = [line.strip()[3:] for line in raw if line.startswith('<1>')] seqs = [line.strip()[3:] for line in raw if line.startswith('<5>')] if len(names) != len(seqs): raise Exception('Found different number of enzyme names and ' 'sequences.') self._enzyme_dict = {} for name, seq in zip(names, seqs): if '?' in seq: # Is unknown sequence, don't keep it pass elif seq.startswith('(') and seq.endswith(')'): # Has four+ cut sites, don't keep it pass elif '^' in seq: # Has reasonable internal cut sites, keep it top_cut = seq.index('^') bottom_cut = len(seq) - top_cut - 1 site = seq.replace('^', '') self._enzyme_dict[name] = (site, (top_cut, bottom_cut)) elif seq.endswith(')'): # Has reasonable external cut sites, keep it # (4-cutter also starts with '(') # separate site and cut locations site, cuts = seq.split('(') cuts = cuts.replace(')', '') top_cut, bottom_cut = [int(x) + len(site) for x in cuts.split('/')] self._enzyme_dict[name] = (site, (top_cut, bottom_cut)) shutil.rmtree(self._tmpdir)
python
def _process_file(self): '''Process rebase file into dict with name and cut site information.''' print 'Processing file' with open(self._rebase_file, 'r') as f: raw = f.readlines() names = [line.strip()[3:] for line in raw if line.startswith('<1>')] seqs = [line.strip()[3:] for line in raw if line.startswith('<5>')] if len(names) != len(seqs): raise Exception('Found different number of enzyme names and ' 'sequences.') self._enzyme_dict = {} for name, seq in zip(names, seqs): if '?' in seq: # Is unknown sequence, don't keep it pass elif seq.startswith('(') and seq.endswith(')'): # Has four+ cut sites, don't keep it pass elif '^' in seq: # Has reasonable internal cut sites, keep it top_cut = seq.index('^') bottom_cut = len(seq) - top_cut - 1 site = seq.replace('^', '') self._enzyme_dict[name] = (site, (top_cut, bottom_cut)) elif seq.endswith(')'): # Has reasonable external cut sites, keep it # (4-cutter also starts with '(') # separate site and cut locations site, cuts = seq.split('(') cuts = cuts.replace(')', '') top_cut, bottom_cut = [int(x) + len(site) for x in cuts.split('/')] self._enzyme_dict[name] = (site, (top_cut, bottom_cut)) shutil.rmtree(self._tmpdir)
[ "def", "_process_file", "(", "self", ")", ":", "print", "'Processing file'", "with", "open", "(", "self", ".", "_rebase_file", ",", "'r'", ")", "as", "f", ":", "raw", "=", "f", ".", "readlines", "(", ")", "names", "=", "[", "line", ".", "strip", "(", ")", "[", "3", ":", "]", "for", "line", "in", "raw", "if", "line", ".", "startswith", "(", "'<1>'", ")", "]", "seqs", "=", "[", "line", ".", "strip", "(", ")", "[", "3", ":", "]", "for", "line", "in", "raw", "if", "line", ".", "startswith", "(", "'<5>'", ")", "]", "if", "len", "(", "names", ")", "!=", "len", "(", "seqs", ")", ":", "raise", "Exception", "(", "'Found different number of enzyme names and '", "'sequences.'", ")", "self", ".", "_enzyme_dict", "=", "{", "}", "for", "name", ",", "seq", "in", "zip", "(", "names", ",", "seqs", ")", ":", "if", "'?'", "in", "seq", ":", "# Is unknown sequence, don't keep it", "pass", "elif", "seq", ".", "startswith", "(", "'('", ")", "and", "seq", ".", "endswith", "(", "')'", ")", ":", "# Has four+ cut sites, don't keep it", "pass", "elif", "'^'", "in", "seq", ":", "# Has reasonable internal cut sites, keep it", "top_cut", "=", "seq", ".", "index", "(", "'^'", ")", "bottom_cut", "=", "len", "(", "seq", ")", "-", "top_cut", "-", "1", "site", "=", "seq", ".", "replace", "(", "'^'", ",", "''", ")", "self", ".", "_enzyme_dict", "[", "name", "]", "=", "(", "site", ",", "(", "top_cut", ",", "bottom_cut", ")", ")", "elif", "seq", ".", "endswith", "(", "')'", ")", ":", "# Has reasonable external cut sites, keep it", "# (4-cutter also starts with '(')", "# separate site and cut locations", "site", ",", "cuts", "=", "seq", ".", "split", "(", "'('", ")", "cuts", "=", "cuts", ".", "replace", "(", "')'", ",", "''", ")", "top_cut", ",", "bottom_cut", "=", "[", "int", "(", "x", ")", "+", "len", "(", "site", ")", "for", "x", "in", "cuts", ".", "split", "(", "'/'", ")", "]", "self", ".", "_enzyme_dict", "[", "name", "]", "=", "(", "site", ",", "(", "top_cut", ",", "bottom_cut", ")", ")", "shutil", ".", "rmtree", "(", "self", ".", "_tmpdir", ")" ]
Process rebase file into dict with name and cut site information.
[ "Process", "rebase", "file", "into", "dict", "with", "name", "and", "cut", "site", "information", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/database/_rebase.py#L69-L102
klavinslab/coral
coral/sequence/_peptide.py
Peptide.copy
def copy(self): '''Create a copy of the current instance. :returns: A safely editable copy of the current sequence. :rtype: coral.Peptide ''' return type(self)(str(self._sequence), features=self.features, run_checks=False)
python
def copy(self): '''Create a copy of the current instance. :returns: A safely editable copy of the current sequence. :rtype: coral.Peptide ''' return type(self)(str(self._sequence), features=self.features, run_checks=False)
[ "def", "copy", "(", "self", ")", ":", "return", "type", "(", "self", ")", "(", "str", "(", "self", ".", "_sequence", ")", ",", "features", "=", "self", ".", "features", ",", "run_checks", "=", "False", ")" ]
Create a copy of the current instance. :returns: A safely editable copy of the current sequence. :rtype: coral.Peptide
[ "Create", "a", "copy", "of", "the", "current", "instance", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_peptide.py#L26-L34
klavinslab/coral
coral/utils/tempdirs.py
tempdir
def tempdir(fun): '''For use as a decorator of instance methods - creates a temporary dir named self._tempdir and then deletes it after the method runs. :param fun: function to decorate :type fun: instance method ''' def wrapper(*args, **kwargs): self = args[0] if os.path.isdir(self._tempdir): shutil.rmtree(self._tempdir) self._tempdir = tempfile.mkdtemp() # If the method raises an exception, delete the temporary dir try: retval = fun(*args, **kwargs) finally: shutil.rmtree(self._tempdir) if os.path.isdir(self._tempdir): shutil.rmtree(self._tempdir) return retval return wrapper
python
def tempdir(fun): '''For use as a decorator of instance methods - creates a temporary dir named self._tempdir and then deletes it after the method runs. :param fun: function to decorate :type fun: instance method ''' def wrapper(*args, **kwargs): self = args[0] if os.path.isdir(self._tempdir): shutil.rmtree(self._tempdir) self._tempdir = tempfile.mkdtemp() # If the method raises an exception, delete the temporary dir try: retval = fun(*args, **kwargs) finally: shutil.rmtree(self._tempdir) if os.path.isdir(self._tempdir): shutil.rmtree(self._tempdir) return retval return wrapper
[ "def", "tempdir", "(", "fun", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "args", "[", "0", "]", "if", "os", ".", "path", ".", "isdir", "(", "self", ".", "_tempdir", ")", ":", "shutil", ".", "rmtree", "(", "self", ".", "_tempdir", ")", "self", ".", "_tempdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "# If the method raises an exception, delete the temporary dir", "try", ":", "retval", "=", "fun", "(", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "shutil", ".", "rmtree", "(", "self", ".", "_tempdir", ")", "if", "os", ".", "path", ".", "isdir", "(", "self", ".", "_tempdir", ")", ":", "shutil", ".", "rmtree", "(", "self", ".", "_tempdir", ")", "return", "retval", "return", "wrapper" ]
For use as a decorator of instance methods - creates a temporary dir named self._tempdir and then deletes it after the method runs. :param fun: function to decorate :type fun: instance method
[ "For", "use", "as", "a", "decorator", "of", "instance", "methods", "-", "creates", "a", "temporary", "dir", "named", "self", ".", "_tempdir", "and", "then", "deletes", "it", "after", "the", "method", "runs", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/utils/tempdirs.py#L9-L30
klavinslab/coral
coral/reaction/utils.py
convert_sequence
def convert_sequence(seq, to_material): '''Translate a DNA sequence into peptide sequence. The following conversions are supported: Transcription (seq is DNA, to_material is 'rna') Reverse transcription (seq is RNA, to_material is 'dna') Translation (seq is RNA, to_material is 'peptide') :param seq: DNA or RNA sequence. :type seq: coral.DNA or coral.RNA :param to_material: material to which to convert ('rna', 'dna', or 'peptide'). :type to_material: str :returns: sequence of type coral.sequence.[material type] ''' if isinstance(seq, coral.DNA) and to_material == 'rna': # Transcribe # Can't transcribe a gap if '-' in seq: raise ValueError('Cannot transcribe gapped DNA') # Convert DNA chars to RNA chars origin = ALPHABETS['dna'][:-1] destination = ALPHABETS['rna'] code = dict(zip(origin, destination)) converted = ''.join([code.get(str(k), str(k)) for k in seq]) # Instantiate RNA object converted = coral.RNA(converted) elif isinstance(seq, coral.RNA): if to_material == 'dna': # Reverse transcribe origin = ALPHABETS['rna'] destination = ALPHABETS['dna'][:-1] code = dict(zip(origin, destination)) converted = ''.join([code.get(str(k), str(k)) for k in seq]) # Instantiate DNA object converted = coral.DNA(converted) elif to_material == 'peptide': # Translate seq_list = list(str(seq)) # Convert to peptide until stop codon is found. converted = [] while True: if len(seq_list) >= 3: base_1 = seq_list.pop(0) base_2 = seq_list.pop(0) base_3 = seq_list.pop(0) codon = ''.join(base_1 + base_2 + base_3).upper() amino_acid = CODONS[codon] # Stop when stop codon is found if amino_acid == '*': break converted.append(amino_acid) else: break converted = ''.join(converted) converted = coral.Peptide(converted) else: msg1 = 'Conversion from ' msg2 = '{0} to {1} is not supported.'.format(seq.__class__.__name__, to_material) raise ValueError(msg1 + msg2) return converted
python
def convert_sequence(seq, to_material): '''Translate a DNA sequence into peptide sequence. The following conversions are supported: Transcription (seq is DNA, to_material is 'rna') Reverse transcription (seq is RNA, to_material is 'dna') Translation (seq is RNA, to_material is 'peptide') :param seq: DNA or RNA sequence. :type seq: coral.DNA or coral.RNA :param to_material: material to which to convert ('rna', 'dna', or 'peptide'). :type to_material: str :returns: sequence of type coral.sequence.[material type] ''' if isinstance(seq, coral.DNA) and to_material == 'rna': # Transcribe # Can't transcribe a gap if '-' in seq: raise ValueError('Cannot transcribe gapped DNA') # Convert DNA chars to RNA chars origin = ALPHABETS['dna'][:-1] destination = ALPHABETS['rna'] code = dict(zip(origin, destination)) converted = ''.join([code.get(str(k), str(k)) for k in seq]) # Instantiate RNA object converted = coral.RNA(converted) elif isinstance(seq, coral.RNA): if to_material == 'dna': # Reverse transcribe origin = ALPHABETS['rna'] destination = ALPHABETS['dna'][:-1] code = dict(zip(origin, destination)) converted = ''.join([code.get(str(k), str(k)) for k in seq]) # Instantiate DNA object converted = coral.DNA(converted) elif to_material == 'peptide': # Translate seq_list = list(str(seq)) # Convert to peptide until stop codon is found. converted = [] while True: if len(seq_list) >= 3: base_1 = seq_list.pop(0) base_2 = seq_list.pop(0) base_3 = seq_list.pop(0) codon = ''.join(base_1 + base_2 + base_3).upper() amino_acid = CODONS[codon] # Stop when stop codon is found if amino_acid == '*': break converted.append(amino_acid) else: break converted = ''.join(converted) converted = coral.Peptide(converted) else: msg1 = 'Conversion from ' msg2 = '{0} to {1} is not supported.'.format(seq.__class__.__name__, to_material) raise ValueError(msg1 + msg2) return converted
[ "def", "convert_sequence", "(", "seq", ",", "to_material", ")", ":", "if", "isinstance", "(", "seq", ",", "coral", ".", "DNA", ")", "and", "to_material", "==", "'rna'", ":", "# Transcribe", "# Can't transcribe a gap", "if", "'-'", "in", "seq", ":", "raise", "ValueError", "(", "'Cannot transcribe gapped DNA'", ")", "# Convert DNA chars to RNA chars", "origin", "=", "ALPHABETS", "[", "'dna'", "]", "[", ":", "-", "1", "]", "destination", "=", "ALPHABETS", "[", "'rna'", "]", "code", "=", "dict", "(", "zip", "(", "origin", ",", "destination", ")", ")", "converted", "=", "''", ".", "join", "(", "[", "code", ".", "get", "(", "str", "(", "k", ")", ",", "str", "(", "k", ")", ")", "for", "k", "in", "seq", "]", ")", "# Instantiate RNA object", "converted", "=", "coral", ".", "RNA", "(", "converted", ")", "elif", "isinstance", "(", "seq", ",", "coral", ".", "RNA", ")", ":", "if", "to_material", "==", "'dna'", ":", "# Reverse transcribe", "origin", "=", "ALPHABETS", "[", "'rna'", "]", "destination", "=", "ALPHABETS", "[", "'dna'", "]", "[", ":", "-", "1", "]", "code", "=", "dict", "(", "zip", "(", "origin", ",", "destination", ")", ")", "converted", "=", "''", ".", "join", "(", "[", "code", ".", "get", "(", "str", "(", "k", ")", ",", "str", "(", "k", ")", ")", "for", "k", "in", "seq", "]", ")", "# Instantiate DNA object", "converted", "=", "coral", ".", "DNA", "(", "converted", ")", "elif", "to_material", "==", "'peptide'", ":", "# Translate", "seq_list", "=", "list", "(", "str", "(", "seq", ")", ")", "# Convert to peptide until stop codon is found.", "converted", "=", "[", "]", "while", "True", ":", "if", "len", "(", "seq_list", ")", ">=", "3", ":", "base_1", "=", "seq_list", ".", "pop", "(", "0", ")", "base_2", "=", "seq_list", ".", "pop", "(", "0", ")", "base_3", "=", "seq_list", ".", "pop", "(", "0", ")", "codon", "=", "''", ".", "join", "(", "base_1", "+", "base_2", "+", "base_3", ")", ".", "upper", "(", ")", "amino_acid", "=", "CODONS", "[", "codon", "]", "# Stop when stop codon is found", "if", "amino_acid", "==", "'*'", ":", "break", "converted", ".", "append", "(", "amino_acid", ")", "else", ":", "break", "converted", "=", "''", ".", "join", "(", "converted", ")", "converted", "=", "coral", ".", "Peptide", "(", "converted", ")", "else", ":", "msg1", "=", "'Conversion from '", "msg2", "=", "'{0} to {1} is not supported.'", ".", "format", "(", "seq", ".", "__class__", ".", "__name__", ",", "to_material", ")", "raise", "ValueError", "(", "msg1", "+", "msg2", ")", "return", "converted" ]
Translate a DNA sequence into peptide sequence. The following conversions are supported: Transcription (seq is DNA, to_material is 'rna') Reverse transcription (seq is RNA, to_material is 'dna') Translation (seq is RNA, to_material is 'peptide') :param seq: DNA or RNA sequence. :type seq: coral.DNA or coral.RNA :param to_material: material to which to convert ('rna', 'dna', or 'peptide'). :type to_material: str :returns: sequence of type coral.sequence.[material type]
[ "Translate", "a", "DNA", "sequence", "into", "peptide", "sequence", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/utils.py#L6-L70
klavinslab/coral
coral/sequence/_nucleicacid.py
NucleicAcid.gc
def gc(self): '''Find the frequency of G and C in the current sequence.''' gc = len([base for base in self.seq if base == 'C' or base == 'G']) return float(gc) / len(self)
python
def gc(self): '''Find the frequency of G and C in the current sequence.''' gc = len([base for base in self.seq if base == 'C' or base == 'G']) return float(gc) / len(self)
[ "def", "gc", "(", "self", ")", ":", "gc", "=", "len", "(", "[", "base", "for", "base", "in", "self", ".", "seq", "if", "base", "==", "'C'", "or", "base", "==", "'G'", "]", ")", "return", "float", "(", "gc", ")", "/", "len", "(", "self", ")" ]
Find the frequency of G and C in the current sequence.
[ "Find", "the", "frequency", "of", "G", "and", "C", "in", "the", "current", "sequence", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_nucleicacid.py#L58-L61
klavinslab/coral
coral/sequence/_nucleicacid.py
NucleicAcid.is_rotation
def is_rotation(self, other): '''Determine whether two sequences are the same, just at different rotations. :param other: The sequence to check for rotational equality. :type other: coral.sequence._sequence.Sequence ''' if len(self) != len(other): return False for i in range(len(self)): if self.rotate(i) == other: return True return False
python
def is_rotation(self, other): '''Determine whether two sequences are the same, just at different rotations. :param other: The sequence to check for rotational equality. :type other: coral.sequence._sequence.Sequence ''' if len(self) != len(other): return False for i in range(len(self)): if self.rotate(i) == other: return True return False
[ "def", "is_rotation", "(", "self", ",", "other", ")", ":", "if", "len", "(", "self", ")", "!=", "len", "(", "other", ")", ":", "return", "False", "for", "i", "in", "range", "(", "len", "(", "self", ")", ")", ":", "if", "self", ".", "rotate", "(", "i", ")", "==", "other", ":", "return", "True", "return", "False" ]
Determine whether two sequences are the same, just at different rotations. :param other: The sequence to check for rotational equality. :type other: coral.sequence._sequence.Sequence
[ "Determine", "whether", "two", "sequences", "are", "the", "same", "just", "at", "different", "rotations", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_nucleicacid.py#L78-L93
klavinslab/coral
coral/sequence/_nucleicacid.py
NucleicAcid.linearize
def linearize(self, index=0): '''Linearize the Sequence at an index. :param index: index at which to linearize. :type index: int :returns: A linearized version of the current sequence. :rtype: coral.sequence._sequence.Sequence :raises: ValueError if the input is a linear sequence. ''' if not self.circular and index != 0: raise ValueError('Cannot relinearize a linear sequence.') copy = self.copy() # Snip at the index if index: return copy[index:] + copy[:index] copy.circular = False return copy
python
def linearize(self, index=0): '''Linearize the Sequence at an index. :param index: index at which to linearize. :type index: int :returns: A linearized version of the current sequence. :rtype: coral.sequence._sequence.Sequence :raises: ValueError if the input is a linear sequence. ''' if not self.circular and index != 0: raise ValueError('Cannot relinearize a linear sequence.') copy = self.copy() # Snip at the index if index: return copy[index:] + copy[:index] copy.circular = False return copy
[ "def", "linearize", "(", "self", ",", "index", "=", "0", ")", ":", "if", "not", "self", ".", "circular", "and", "index", "!=", "0", ":", "raise", "ValueError", "(", "'Cannot relinearize a linear sequence.'", ")", "copy", "=", "self", ".", "copy", "(", ")", "# Snip at the index", "if", "index", ":", "return", "copy", "[", "index", ":", "]", "+", "copy", "[", ":", "index", "]", "copy", ".", "circular", "=", "False", "return", "copy" ]
Linearize the Sequence at an index. :param index: index at which to linearize. :type index: int :returns: A linearized version of the current sequence. :rtype: coral.sequence._sequence.Sequence :raises: ValueError if the input is a linear sequence.
[ "Linearize", "the", "Sequence", "at", "an", "index", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_nucleicacid.py#L95-L113
klavinslab/coral
coral/sequence/_nucleicacid.py
NucleicAcid.locate
def locate(self, pattern): '''Find sequences matching a pattern. :param pattern: Sequence for which to find matches. :type pattern: str :returns: Indices of pattern matches. :rtype: list of ints ''' if self.circular: if len(pattern) >= 2 * len(self): raise ValueError('Search pattern longer than searchable ' + 'sequence.') seq = self + self[:len(pattern) - 1] return super(NucleicAcid, seq).locate(pattern) else: return super(NucleicAcid, self).locate(pattern)
python
def locate(self, pattern): '''Find sequences matching a pattern. :param pattern: Sequence for which to find matches. :type pattern: str :returns: Indices of pattern matches. :rtype: list of ints ''' if self.circular: if len(pattern) >= 2 * len(self): raise ValueError('Search pattern longer than searchable ' + 'sequence.') seq = self + self[:len(pattern) - 1] return super(NucleicAcid, seq).locate(pattern) else: return super(NucleicAcid, self).locate(pattern)
[ "def", "locate", "(", "self", ",", "pattern", ")", ":", "if", "self", ".", "circular", ":", "if", "len", "(", "pattern", ")", ">=", "2", "*", "len", "(", "self", ")", ":", "raise", "ValueError", "(", "'Search pattern longer than searchable '", "+", "'sequence.'", ")", "seq", "=", "self", "+", "self", "[", ":", "len", "(", "pattern", ")", "-", "1", "]", "return", "super", "(", "NucleicAcid", ",", "seq", ")", ".", "locate", "(", "pattern", ")", "else", ":", "return", "super", "(", "NucleicAcid", ",", "self", ")", ".", "locate", "(", "pattern", ")" ]
Find sequences matching a pattern. :param pattern: Sequence for which to find matches. :type pattern: str :returns: Indices of pattern matches. :rtype: list of ints
[ "Find", "sequences", "matching", "a", "pattern", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_nucleicacid.py#L115-L131
klavinslab/coral
coral/sequence/_nucleicacid.py
NucleicAcid.mw
def mw(self): '''Calculate the molecular weight. :returns: The molecular weight of the current sequence in amu. :rtype: float ''' counter = collections.Counter(self.seq.lower()) mw_a = counter['a'] * 313.2 mw_t = counter['t'] * 304.2 mw_g = counter['g'] * 289.2 mw_c = counter['c'] * 329.2 mw_u = counter['u'] * 306.2 if self.material == 'dna': return mw_a + mw_t + mw_g + mw_c + 79.0 else: return mw_a + mw_u + mw_g + mw_c + 159.0
python
def mw(self): '''Calculate the molecular weight. :returns: The molecular weight of the current sequence in amu. :rtype: float ''' counter = collections.Counter(self.seq.lower()) mw_a = counter['a'] * 313.2 mw_t = counter['t'] * 304.2 mw_g = counter['g'] * 289.2 mw_c = counter['c'] * 329.2 mw_u = counter['u'] * 306.2 if self.material == 'dna': return mw_a + mw_t + mw_g + mw_c + 79.0 else: return mw_a + mw_u + mw_g + mw_c + 159.0
[ "def", "mw", "(", "self", ")", ":", "counter", "=", "collections", ".", "Counter", "(", "self", ".", "seq", ".", "lower", "(", ")", ")", "mw_a", "=", "counter", "[", "'a'", "]", "*", "313.2", "mw_t", "=", "counter", "[", "'t'", "]", "*", "304.2", "mw_g", "=", "counter", "[", "'g'", "]", "*", "289.2", "mw_c", "=", "counter", "[", "'c'", "]", "*", "329.2", "mw_u", "=", "counter", "[", "'u'", "]", "*", "306.2", "if", "self", ".", "material", "==", "'dna'", ":", "return", "mw_a", "+", "mw_t", "+", "mw_g", "+", "mw_c", "+", "79.0", "else", ":", "return", "mw_a", "+", "mw_u", "+", "mw_g", "+", "mw_c", "+", "159.0" ]
Calculate the molecular weight. :returns: The molecular weight of the current sequence in amu. :rtype: float
[ "Calculate", "the", "molecular", "weight", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_nucleicacid.py#L133-L150
klavinslab/coral
coral/sequence/_nucleicacid.py
NucleicAcid.rotate
def rotate(self, n): '''Rotate Sequence by n bases. :param n: Number of bases to rotate. :type n: int :returns: The current sequence reoriented at `index`. :rtype: coral.sequence._sequence.Sequence :raises: ValueError if applied to linear sequence or `index` is negative. ''' if not self.circular and n != 0: raise ValueError('Cannot rotate a linear sequence') else: rotated = self[-n:] + self[:-n] return rotated.circularize()
python
def rotate(self, n): '''Rotate Sequence by n bases. :param n: Number of bases to rotate. :type n: int :returns: The current sequence reoriented at `index`. :rtype: coral.sequence._sequence.Sequence :raises: ValueError if applied to linear sequence or `index` is negative. ''' if not self.circular and n != 0: raise ValueError('Cannot rotate a linear sequence') else: rotated = self[-n:] + self[:-n] return rotated.circularize()
[ "def", "rotate", "(", "self", ",", "n", ")", ":", "if", "not", "self", ".", "circular", "and", "n", "!=", "0", ":", "raise", "ValueError", "(", "'Cannot rotate a linear sequence'", ")", "else", ":", "rotated", "=", "self", "[", "-", "n", ":", "]", "+", "self", "[", ":", "-", "n", "]", "return", "rotated", ".", "circularize", "(", ")" ]
Rotate Sequence by n bases. :param n: Number of bases to rotate. :type n: int :returns: The current sequence reoriented at `index`. :rtype: coral.sequence._sequence.Sequence :raises: ValueError if applied to linear sequence or `index` is negative.
[ "Rotate", "Sequence", "by", "n", "bases", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_nucleicacid.py#L152-L167
klavinslab/coral
coral/reaction/_resect.py
five_resect
def five_resect(dna, n_bases): '''Remove bases from 5' end of top strand. :param dna: Sequence to resect. :type dna: coral.DNA :param n_bases: Number of bases cut back. :type n_bases: int :returns: DNA sequence resected at the 5' end by n_bases. :rtype: coral.DNA ''' new_instance = dna.copy() if n_bases >= len(dna): new_instance.top.seq = ''.join(['-' for i in range(len(dna))]) else: new_instance.top.seq = '-' * n_bases + str(dna)[n_bases:] new_instance = _remove_end_gaps(new_instance) return new_instance
python
def five_resect(dna, n_bases): '''Remove bases from 5' end of top strand. :param dna: Sequence to resect. :type dna: coral.DNA :param n_bases: Number of bases cut back. :type n_bases: int :returns: DNA sequence resected at the 5' end by n_bases. :rtype: coral.DNA ''' new_instance = dna.copy() if n_bases >= len(dna): new_instance.top.seq = ''.join(['-' for i in range(len(dna))]) else: new_instance.top.seq = '-' * n_bases + str(dna)[n_bases:] new_instance = _remove_end_gaps(new_instance) return new_instance
[ "def", "five_resect", "(", "dna", ",", "n_bases", ")", ":", "new_instance", "=", "dna", ".", "copy", "(", ")", "if", "n_bases", ">=", "len", "(", "dna", ")", ":", "new_instance", ".", "top", ".", "seq", "=", "''", ".", "join", "(", "[", "'-'", "for", "i", "in", "range", "(", "len", "(", "dna", ")", ")", "]", ")", "else", ":", "new_instance", ".", "top", ".", "seq", "=", "'-'", "*", "n_bases", "+", "str", "(", "dna", ")", "[", "n_bases", ":", "]", "new_instance", "=", "_remove_end_gaps", "(", "new_instance", ")", "return", "new_instance" ]
Remove bases from 5' end of top strand. :param dna: Sequence to resect. :type dna: coral.DNA :param n_bases: Number of bases cut back. :type n_bases: int :returns: DNA sequence resected at the 5' end by n_bases. :rtype: coral.DNA
[ "Remove", "bases", "from", "5", "end", "of", "top", "strand", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_resect.py#L5-L24
klavinslab/coral
coral/reaction/_resect.py
_remove_end_gaps
def _remove_end_gaps(sequence): '''Removes double-stranded gaps from ends of the sequence. :returns: The current sequence with terminal double-strand gaps ('-') removed. :rtype: coral.DNA ''' # Count terminal blank sequences def count_end_gaps(seq): gap = coral.DNA('-') count = 0 for base in seq: if base == gap: count += 1 else: break return count top_left = count_end_gaps(sequence.top) top_right = count_end_gaps(reversed(sequence.top)) bottom_left = count_end_gaps(reversed(sequence.bottom)) bottom_right = count_end_gaps(sequence.bottom) # Trim sequence left_index = min(top_left, bottom_left) right_index = len(sequence) - min(top_right, bottom_right) return sequence[left_index:right_index]
python
def _remove_end_gaps(sequence): '''Removes double-stranded gaps from ends of the sequence. :returns: The current sequence with terminal double-strand gaps ('-') removed. :rtype: coral.DNA ''' # Count terminal blank sequences def count_end_gaps(seq): gap = coral.DNA('-') count = 0 for base in seq: if base == gap: count += 1 else: break return count top_left = count_end_gaps(sequence.top) top_right = count_end_gaps(reversed(sequence.top)) bottom_left = count_end_gaps(reversed(sequence.bottom)) bottom_right = count_end_gaps(sequence.bottom) # Trim sequence left_index = min(top_left, bottom_left) right_index = len(sequence) - min(top_right, bottom_right) return sequence[left_index:right_index]
[ "def", "_remove_end_gaps", "(", "sequence", ")", ":", "# Count terminal blank sequences", "def", "count_end_gaps", "(", "seq", ")", ":", "gap", "=", "coral", ".", "DNA", "(", "'-'", ")", "count", "=", "0", "for", "base", "in", "seq", ":", "if", "base", "==", "gap", ":", "count", "+=", "1", "else", ":", "break", "return", "count", "top_left", "=", "count_end_gaps", "(", "sequence", ".", "top", ")", "top_right", "=", "count_end_gaps", "(", "reversed", "(", "sequence", ".", "top", ")", ")", "bottom_left", "=", "count_end_gaps", "(", "reversed", "(", "sequence", ".", "bottom", ")", ")", "bottom_right", "=", "count_end_gaps", "(", "sequence", ".", "bottom", ")", "# Trim sequence", "left_index", "=", "min", "(", "top_left", ",", "bottom_left", ")", "right_index", "=", "len", "(", "sequence", ")", "-", "min", "(", "top_right", ",", "bottom_right", ")", "return", "sequence", "[", "left_index", ":", "right_index", "]" ]
Removes double-stranded gaps from ends of the sequence. :returns: The current sequence with terminal double-strand gaps ('-') removed. :rtype: coral.DNA
[ "Removes", "double", "-", "stranded", "gaps", "from", "ends", "of", "the", "sequence", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_resect.py#L49-L78
klavinslab/coral
coral/analysis/_sequencing/needle.py
needle
def needle(reference, query, gap_open=-15, gap_extend=0, matrix=submat.DNA_SIMPLE): '''Do a Needleman-Wunsch alignment. :param reference: Reference sequence. :type reference: coral.DNA :param query: Sequence to align against the reference. :type query: coral.DNA :param gapopen: Penalty for opening a gap. :type gapopen: float :param gapextend: Penalty for extending a gap. :type gapextend: float :param matrix: Matrix to use for alignment - options are DNA_simple (for DNA) and BLOSUM62 (for proteins). :type matrix: str :returns: (aligned reference, aligned query, score) :rtype: tuple of two coral.DNA instances and a float ''' # Align using cython Needleman-Wunsch aligned_ref, aligned_res = aligner(str(reference), str(query), gap_open=gap_open, gap_extend=gap_extend, method='global_cfe', matrix=matrix.matrix, alphabet=matrix.alphabet) # Score the alignment score = score_alignment(aligned_ref, aligned_res, gap_open, gap_extend, matrix.matrix, matrix.alphabet) return cr.DNA(aligned_ref), cr.DNA(aligned_res), score
python
def needle(reference, query, gap_open=-15, gap_extend=0, matrix=submat.DNA_SIMPLE): '''Do a Needleman-Wunsch alignment. :param reference: Reference sequence. :type reference: coral.DNA :param query: Sequence to align against the reference. :type query: coral.DNA :param gapopen: Penalty for opening a gap. :type gapopen: float :param gapextend: Penalty for extending a gap. :type gapextend: float :param matrix: Matrix to use for alignment - options are DNA_simple (for DNA) and BLOSUM62 (for proteins). :type matrix: str :returns: (aligned reference, aligned query, score) :rtype: tuple of two coral.DNA instances and a float ''' # Align using cython Needleman-Wunsch aligned_ref, aligned_res = aligner(str(reference), str(query), gap_open=gap_open, gap_extend=gap_extend, method='global_cfe', matrix=matrix.matrix, alphabet=matrix.alphabet) # Score the alignment score = score_alignment(aligned_ref, aligned_res, gap_open, gap_extend, matrix.matrix, matrix.alphabet) return cr.DNA(aligned_ref), cr.DNA(aligned_res), score
[ "def", "needle", "(", "reference", ",", "query", ",", "gap_open", "=", "-", "15", ",", "gap_extend", "=", "0", ",", "matrix", "=", "submat", ".", "DNA_SIMPLE", ")", ":", "# Align using cython Needleman-Wunsch", "aligned_ref", ",", "aligned_res", "=", "aligner", "(", "str", "(", "reference", ")", ",", "str", "(", "query", ")", ",", "gap_open", "=", "gap_open", ",", "gap_extend", "=", "gap_extend", ",", "method", "=", "'global_cfe'", ",", "matrix", "=", "matrix", ".", "matrix", ",", "alphabet", "=", "matrix", ".", "alphabet", ")", "# Score the alignment", "score", "=", "score_alignment", "(", "aligned_ref", ",", "aligned_res", ",", "gap_open", ",", "gap_extend", ",", "matrix", ".", "matrix", ",", "matrix", ".", "alphabet", ")", "return", "cr", ".", "DNA", "(", "aligned_ref", ")", ",", "cr", ".", "DNA", "(", "aligned_res", ")", ",", "score" ]
Do a Needleman-Wunsch alignment. :param reference: Reference sequence. :type reference: coral.DNA :param query: Sequence to align against the reference. :type query: coral.DNA :param gapopen: Penalty for opening a gap. :type gapopen: float :param gapextend: Penalty for extending a gap. :type gapextend: float :param matrix: Matrix to use for alignment - options are DNA_simple (for DNA) and BLOSUM62 (for proteins). :type matrix: str :returns: (aligned reference, aligned query, score) :rtype: tuple of two coral.DNA instances and a float
[ "Do", "a", "Needleman", "-", "Wunsch", "alignment", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequencing/needle.py#L16-L48
klavinslab/coral
coral/analysis/_sequencing/needle.py
needle_msa
def needle_msa(reference, results, gap_open=-15, gap_extend=0, matrix=submat.DNA_SIMPLE): '''Create a multiple sequence alignment based on aligning every result sequence against the reference, then inserting gaps until every aligned reference is identical ''' gap = '-' # Convert alignments to list of strings alignments = [] for result in results: ref_dna, res_dna, score = needle(reference, result, gap_open=gap_open, gap_extend=gap_extend, matrix=matrix) alignments.append([str(ref_dna), str(res_dna), score]) def insert_gap(sequence, position): return sequence[:position] + gap + sequence[position:] i = 0 while True: # Iterate over 'columns' in every reference refs = [alignment[0][i] for alignment in alignments] # If there's a non-unanimous gap, insert gap into alignments gaps = [ref == gap for ref in refs] if any(gaps) and not all(gaps): for alignment in alignments: if alignment[0][i] != gap: alignment[0] = insert_gap(alignment[0], i) alignment[1] = insert_gap(alignment[1], i) # If all references match, we're all done alignment_set = set(alignment[0] for alignment in alignments) if len(alignment_set) == 1: break # If we've reach the end of some, but not all sequences, add end gap lens = [len(alignment[0]) for alignment in alignments] if i + 1 in lens: for alignment in alignments: if len(alignment[0]) == i + 1: alignment[0] = alignment[0] + gap alignment[1] = alignment[1] + gap i += 1 if i > 20: break # Convert into MSA format output_alignment = [cr.DNA(alignments[0][0])] for alignment in alignments: output_alignment.append(cr.DNA(alignment[1])) return output_alignment
python
def needle_msa(reference, results, gap_open=-15, gap_extend=0, matrix=submat.DNA_SIMPLE): '''Create a multiple sequence alignment based on aligning every result sequence against the reference, then inserting gaps until every aligned reference is identical ''' gap = '-' # Convert alignments to list of strings alignments = [] for result in results: ref_dna, res_dna, score = needle(reference, result, gap_open=gap_open, gap_extend=gap_extend, matrix=matrix) alignments.append([str(ref_dna), str(res_dna), score]) def insert_gap(sequence, position): return sequence[:position] + gap + sequence[position:] i = 0 while True: # Iterate over 'columns' in every reference refs = [alignment[0][i] for alignment in alignments] # If there's a non-unanimous gap, insert gap into alignments gaps = [ref == gap for ref in refs] if any(gaps) and not all(gaps): for alignment in alignments: if alignment[0][i] != gap: alignment[0] = insert_gap(alignment[0], i) alignment[1] = insert_gap(alignment[1], i) # If all references match, we're all done alignment_set = set(alignment[0] for alignment in alignments) if len(alignment_set) == 1: break # If we've reach the end of some, but not all sequences, add end gap lens = [len(alignment[0]) for alignment in alignments] if i + 1 in lens: for alignment in alignments: if len(alignment[0]) == i + 1: alignment[0] = alignment[0] + gap alignment[1] = alignment[1] + gap i += 1 if i > 20: break # Convert into MSA format output_alignment = [cr.DNA(alignments[0][0])] for alignment in alignments: output_alignment.append(cr.DNA(alignment[1])) return output_alignment
[ "def", "needle_msa", "(", "reference", ",", "results", ",", "gap_open", "=", "-", "15", ",", "gap_extend", "=", "0", ",", "matrix", "=", "submat", ".", "DNA_SIMPLE", ")", ":", "gap", "=", "'-'", "# Convert alignments to list of strings", "alignments", "=", "[", "]", "for", "result", "in", "results", ":", "ref_dna", ",", "res_dna", ",", "score", "=", "needle", "(", "reference", ",", "result", ",", "gap_open", "=", "gap_open", ",", "gap_extend", "=", "gap_extend", ",", "matrix", "=", "matrix", ")", "alignments", ".", "append", "(", "[", "str", "(", "ref_dna", ")", ",", "str", "(", "res_dna", ")", ",", "score", "]", ")", "def", "insert_gap", "(", "sequence", ",", "position", ")", ":", "return", "sequence", "[", ":", "position", "]", "+", "gap", "+", "sequence", "[", "position", ":", "]", "i", "=", "0", "while", "True", ":", "# Iterate over 'columns' in every reference", "refs", "=", "[", "alignment", "[", "0", "]", "[", "i", "]", "for", "alignment", "in", "alignments", "]", "# If there's a non-unanimous gap, insert gap into alignments", "gaps", "=", "[", "ref", "==", "gap", "for", "ref", "in", "refs", "]", "if", "any", "(", "gaps", ")", "and", "not", "all", "(", "gaps", ")", ":", "for", "alignment", "in", "alignments", ":", "if", "alignment", "[", "0", "]", "[", "i", "]", "!=", "gap", ":", "alignment", "[", "0", "]", "=", "insert_gap", "(", "alignment", "[", "0", "]", ",", "i", ")", "alignment", "[", "1", "]", "=", "insert_gap", "(", "alignment", "[", "1", "]", ",", "i", ")", "# If all references match, we're all done", "alignment_set", "=", "set", "(", "alignment", "[", "0", "]", "for", "alignment", "in", "alignments", ")", "if", "len", "(", "alignment_set", ")", "==", "1", ":", "break", "# If we've reach the end of some, but not all sequences, add end gap", "lens", "=", "[", "len", "(", "alignment", "[", "0", "]", ")", "for", "alignment", "in", "alignments", "]", "if", "i", "+", "1", "in", "lens", ":", "for", "alignment", "in", "alignments", ":", "if", "len", "(", "alignment", "[", "0", "]", ")", "==", "i", "+", "1", ":", "alignment", "[", "0", "]", "=", "alignment", "[", "0", "]", "+", "gap", "alignment", "[", "1", "]", "=", "alignment", "[", "1", "]", "+", "gap", "i", "+=", "1", "if", "i", ">", "20", ":", "break", "# Convert into MSA format", "output_alignment", "=", "[", "cr", ".", "DNA", "(", "alignments", "[", "0", "]", "[", "0", "]", ")", "]", "for", "alignment", "in", "alignments", ":", "output_alignment", ".", "append", "(", "cr", ".", "DNA", "(", "alignment", "[", "1", "]", ")", ")", "return", "output_alignment" ]
Create a multiple sequence alignment based on aligning every result sequence against the reference, then inserting gaps until every aligned reference is identical
[ "Create", "a", "multiple", "sequence", "alignment", "based", "on", "aligning", "every", "result", "sequence", "against", "the", "reference", "then", "inserting", "gaps", "until", "every", "aligned", "reference", "is", "identical" ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequencing/needle.py#L58-L113
klavinslab/coral
coral/analysis/_sequencing/needle.py
needle_multi
def needle_multi(references, queries, gap_open=-15, gap_extend=0, matrix=submat.DNA_SIMPLE): '''Batch process of sequencing split over several cores. Acts just like needle but sequence inputs are lists. :param references: References sequence. :type references: coral.DNA list :param queries: Sequences to align against the reference. :type queries: coral.DNA list :param gap_open: Penalty for opening a gap. :type gap_open: float :param gap_extend: Penalty for extending a gap. :type gap_extend: float :param matrix: Matrix to use for alignment - options are DNA_simple (for DNA) and BLOSUM62 (for proteins). :type matrix: str :returns: a list of the same output as coral.sequence.needle :rtype: list ''' pool = multiprocessing.Pool() try: args_list = [[ref, que, gap_open, gap_extend, matrix] for ref, que in zip(references, queries)] aligned = pool.map(run_needle, args_list) except KeyboardInterrupt: print('Caught KeyboardInterrupt, terminating workers') pool.terminate() pool.join() raise KeyboardInterrupt return aligned
python
def needle_multi(references, queries, gap_open=-15, gap_extend=0, matrix=submat.DNA_SIMPLE): '''Batch process of sequencing split over several cores. Acts just like needle but sequence inputs are lists. :param references: References sequence. :type references: coral.DNA list :param queries: Sequences to align against the reference. :type queries: coral.DNA list :param gap_open: Penalty for opening a gap. :type gap_open: float :param gap_extend: Penalty for extending a gap. :type gap_extend: float :param matrix: Matrix to use for alignment - options are DNA_simple (for DNA) and BLOSUM62 (for proteins). :type matrix: str :returns: a list of the same output as coral.sequence.needle :rtype: list ''' pool = multiprocessing.Pool() try: args_list = [[ref, que, gap_open, gap_extend, matrix] for ref, que in zip(references, queries)] aligned = pool.map(run_needle, args_list) except KeyboardInterrupt: print('Caught KeyboardInterrupt, terminating workers') pool.terminate() pool.join() raise KeyboardInterrupt return aligned
[ "def", "needle_multi", "(", "references", ",", "queries", ",", "gap_open", "=", "-", "15", ",", "gap_extend", "=", "0", ",", "matrix", "=", "submat", ".", "DNA_SIMPLE", ")", ":", "pool", "=", "multiprocessing", ".", "Pool", "(", ")", "try", ":", "args_list", "=", "[", "[", "ref", ",", "que", ",", "gap_open", ",", "gap_extend", ",", "matrix", "]", "for", "ref", ",", "que", "in", "zip", "(", "references", ",", "queries", ")", "]", "aligned", "=", "pool", ".", "map", "(", "run_needle", ",", "args_list", ")", "except", "KeyboardInterrupt", ":", "print", "(", "'Caught KeyboardInterrupt, terminating workers'", ")", "pool", ".", "terminate", "(", ")", "pool", ".", "join", "(", ")", "raise", "KeyboardInterrupt", "return", "aligned" ]
Batch process of sequencing split over several cores. Acts just like needle but sequence inputs are lists. :param references: References sequence. :type references: coral.DNA list :param queries: Sequences to align against the reference. :type queries: coral.DNA list :param gap_open: Penalty for opening a gap. :type gap_open: float :param gap_extend: Penalty for extending a gap. :type gap_extend: float :param matrix: Matrix to use for alignment - options are DNA_simple (for DNA) and BLOSUM62 (for proteins). :type matrix: str :returns: a list of the same output as coral.sequence.needle :rtype: list
[ "Batch", "process", "of", "sequencing", "split", "over", "several", "cores", ".", "Acts", "just", "like", "needle", "but", "sequence", "inputs", "are", "lists", "." ]
train
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequencing/needle.py#L116-L147
WoLpH/python-utils
python_utils/import_.py
import_global
def import_global( name, modules=None, exceptions=DummyException, locals_=None, globals_=None, level=-1): '''Import the requested items into the global scope WARNING! this method _will_ overwrite your global scope If you have a variable named "path" and you call import_global('sys') it will be overwritten with sys.path Args: name (str): the name of the module to import, e.g. sys modules (str): the modules to import, use None for everything exception (Exception): the exception to catch, e.g. ImportError `locals_`: the `locals()` method (in case you need a different scope) `globals_`: the `globals()` method (in case you need a different scope) level (int): the level to import from, this can be used for relative imports ''' frame = None try: # If locals_ or globals_ are not given, autodetect them by inspecting # the current stack if locals_ is None or globals_ is None: import inspect frame = inspect.stack()[1][0] if locals_ is None: locals_ = frame.f_locals if globals_ is None: globals_ = frame.f_globals try: name = name.split('.') # Relative imports are supported (from .spam import eggs) if not name[0]: name = name[1:] level = 1 # raise IOError((name, level)) module = __import__( name=name[0] or '.', globals=globals_, locals=locals_, fromlist=name[1:], level=max(level, 0), ) # Make sure we get the right part of a dotted import (i.e. # spam.eggs should return eggs, not spam) try: for attr in name[1:]: module = getattr(module, attr) except AttributeError: raise ImportError('No module named ' + '.'.join(name)) # If no list of modules is given, autodetect from either __all__ # or a dir() of the module if not modules: modules = getattr(module, '__all__', dir(module)) else: modules = set(modules).intersection(dir(module)) # Add all items in modules to the global scope for k in set(dir(module)).intersection(modules): if k and k[0] != '_': globals_[k] = getattr(module, k) except exceptions as e: return e finally: # Clean up, just to be sure del name, modules, exceptions, locals_, globals_, frame
python
def import_global( name, modules=None, exceptions=DummyException, locals_=None, globals_=None, level=-1): '''Import the requested items into the global scope WARNING! this method _will_ overwrite your global scope If you have a variable named "path" and you call import_global('sys') it will be overwritten with sys.path Args: name (str): the name of the module to import, e.g. sys modules (str): the modules to import, use None for everything exception (Exception): the exception to catch, e.g. ImportError `locals_`: the `locals()` method (in case you need a different scope) `globals_`: the `globals()` method (in case you need a different scope) level (int): the level to import from, this can be used for relative imports ''' frame = None try: # If locals_ or globals_ are not given, autodetect them by inspecting # the current stack if locals_ is None or globals_ is None: import inspect frame = inspect.stack()[1][0] if locals_ is None: locals_ = frame.f_locals if globals_ is None: globals_ = frame.f_globals try: name = name.split('.') # Relative imports are supported (from .spam import eggs) if not name[0]: name = name[1:] level = 1 # raise IOError((name, level)) module = __import__( name=name[0] or '.', globals=globals_, locals=locals_, fromlist=name[1:], level=max(level, 0), ) # Make sure we get the right part of a dotted import (i.e. # spam.eggs should return eggs, not spam) try: for attr in name[1:]: module = getattr(module, attr) except AttributeError: raise ImportError('No module named ' + '.'.join(name)) # If no list of modules is given, autodetect from either __all__ # or a dir() of the module if not modules: modules = getattr(module, '__all__', dir(module)) else: modules = set(modules).intersection(dir(module)) # Add all items in modules to the global scope for k in set(dir(module)).intersection(modules): if k and k[0] != '_': globals_[k] = getattr(module, k) except exceptions as e: return e finally: # Clean up, just to be sure del name, modules, exceptions, locals_, globals_, frame
[ "def", "import_global", "(", "name", ",", "modules", "=", "None", ",", "exceptions", "=", "DummyException", ",", "locals_", "=", "None", ",", "globals_", "=", "None", ",", "level", "=", "-", "1", ")", ":", "frame", "=", "None", "try", ":", "# If locals_ or globals_ are not given, autodetect them by inspecting", "# the current stack", "if", "locals_", "is", "None", "or", "globals_", "is", "None", ":", "import", "inspect", "frame", "=", "inspect", ".", "stack", "(", ")", "[", "1", "]", "[", "0", "]", "if", "locals_", "is", "None", ":", "locals_", "=", "frame", ".", "f_locals", "if", "globals_", "is", "None", ":", "globals_", "=", "frame", ".", "f_globals", "try", ":", "name", "=", "name", ".", "split", "(", "'.'", ")", "# Relative imports are supported (from .spam import eggs)", "if", "not", "name", "[", "0", "]", ":", "name", "=", "name", "[", "1", ":", "]", "level", "=", "1", "# raise IOError((name, level))", "module", "=", "__import__", "(", "name", "=", "name", "[", "0", "]", "or", "'.'", ",", "globals", "=", "globals_", ",", "locals", "=", "locals_", ",", "fromlist", "=", "name", "[", "1", ":", "]", ",", "level", "=", "max", "(", "level", ",", "0", ")", ",", ")", "# Make sure we get the right part of a dotted import (i.e.", "# spam.eggs should return eggs, not spam)", "try", ":", "for", "attr", "in", "name", "[", "1", ":", "]", ":", "module", "=", "getattr", "(", "module", ",", "attr", ")", "except", "AttributeError", ":", "raise", "ImportError", "(", "'No module named '", "+", "'.'", ".", "join", "(", "name", ")", ")", "# If no list of modules is given, autodetect from either __all__", "# or a dir() of the module", "if", "not", "modules", ":", "modules", "=", "getattr", "(", "module", ",", "'__all__'", ",", "dir", "(", "module", ")", ")", "else", ":", "modules", "=", "set", "(", "modules", ")", ".", "intersection", "(", "dir", "(", "module", ")", ")", "# Add all items in modules to the global scope", "for", "k", "in", "set", "(", "dir", "(", "module", ")", ")", ".", "intersection", "(", "modules", ")", ":", "if", "k", "and", "k", "[", "0", "]", "!=", "'_'", ":", "globals_", "[", "k", "]", "=", "getattr", "(", "module", ",", "k", ")", "except", "exceptions", "as", "e", ":", "return", "e", "finally", ":", "# Clean up, just to be sure", "del", "name", ",", "modules", ",", "exceptions", ",", "locals_", ",", "globals_", ",", "frame" ]
Import the requested items into the global scope WARNING! this method _will_ overwrite your global scope If you have a variable named "path" and you call import_global('sys') it will be overwritten with sys.path Args: name (str): the name of the module to import, e.g. sys modules (str): the modules to import, use None for everything exception (Exception): the exception to catch, e.g. ImportError `locals_`: the `locals()` method (in case you need a different scope) `globals_`: the `globals()` method (in case you need a different scope) level (int): the level to import from, this can be used for relative imports
[ "Import", "the", "requested", "items", "into", "the", "global", "scope" ]
train
https://github.com/WoLpH/python-utils/blob/6bbe13bab33bd9965b0edd379f26261b31a3e427/python_utils/import_.py#L6-L78
WoLpH/python-utils
python_utils/formatters.py
camel_to_underscore
def camel_to_underscore(name): '''Convert camel case style naming to underscore style naming If there are existing underscores they will be collapsed with the to-be-added underscores. Multiple consecutive capital letters will not be split except for the last one. >>> camel_to_underscore('SpamEggsAndBacon') 'spam_eggs_and_bacon' >>> camel_to_underscore('Spam_and_bacon') 'spam_and_bacon' >>> camel_to_underscore('Spam_And_Bacon') 'spam_and_bacon' >>> camel_to_underscore('__SpamAndBacon__') '__spam_and_bacon__' >>> camel_to_underscore('__SpamANDBacon__') '__spam_and_bacon__' ''' output = [] for i, c in enumerate(name): if i > 0: pc = name[i - 1] if c.isupper() and not pc.isupper() and pc != '_': # Uppercase and the previous character isn't upper/underscore? # Add the underscore output.append('_') elif i > 3 and not c.isupper(): # Will return the last 3 letters to check if we are changing # case previous = name[i - 3:i] if previous.isalpha() and previous.isupper(): output.insert(len(output) - 1, '_') output.append(c.lower()) return ''.join(output)
python
def camel_to_underscore(name): '''Convert camel case style naming to underscore style naming If there are existing underscores they will be collapsed with the to-be-added underscores. Multiple consecutive capital letters will not be split except for the last one. >>> camel_to_underscore('SpamEggsAndBacon') 'spam_eggs_and_bacon' >>> camel_to_underscore('Spam_and_bacon') 'spam_and_bacon' >>> camel_to_underscore('Spam_And_Bacon') 'spam_and_bacon' >>> camel_to_underscore('__SpamAndBacon__') '__spam_and_bacon__' >>> camel_to_underscore('__SpamANDBacon__') '__spam_and_bacon__' ''' output = [] for i, c in enumerate(name): if i > 0: pc = name[i - 1] if c.isupper() and not pc.isupper() and pc != '_': # Uppercase and the previous character isn't upper/underscore? # Add the underscore output.append('_') elif i > 3 and not c.isupper(): # Will return the last 3 letters to check if we are changing # case previous = name[i - 3:i] if previous.isalpha() and previous.isupper(): output.insert(len(output) - 1, '_') output.append(c.lower()) return ''.join(output)
[ "def", "camel_to_underscore", "(", "name", ")", ":", "output", "=", "[", "]", "for", "i", ",", "c", "in", "enumerate", "(", "name", ")", ":", "if", "i", ">", "0", ":", "pc", "=", "name", "[", "i", "-", "1", "]", "if", "c", ".", "isupper", "(", ")", "and", "not", "pc", ".", "isupper", "(", ")", "and", "pc", "!=", "'_'", ":", "# Uppercase and the previous character isn't upper/underscore?", "# Add the underscore", "output", ".", "append", "(", "'_'", ")", "elif", "i", ">", "3", "and", "not", "c", ".", "isupper", "(", ")", ":", "# Will return the last 3 letters to check if we are changing", "# case", "previous", "=", "name", "[", "i", "-", "3", ":", "i", "]", "if", "previous", ".", "isalpha", "(", ")", "and", "previous", ".", "isupper", "(", ")", ":", "output", ".", "insert", "(", "len", "(", "output", ")", "-", "1", ",", "'_'", ")", "output", ".", "append", "(", "c", ".", "lower", "(", ")", ")", "return", "''", ".", "join", "(", "output", ")" ]
Convert camel case style naming to underscore style naming If there are existing underscores they will be collapsed with the to-be-added underscores. Multiple consecutive capital letters will not be split except for the last one. >>> camel_to_underscore('SpamEggsAndBacon') 'spam_eggs_and_bacon' >>> camel_to_underscore('Spam_and_bacon') 'spam_and_bacon' >>> camel_to_underscore('Spam_And_Bacon') 'spam_and_bacon' >>> camel_to_underscore('__SpamAndBacon__') '__spam_and_bacon__' >>> camel_to_underscore('__SpamANDBacon__') '__spam_and_bacon__'
[ "Convert", "camel", "case", "style", "naming", "to", "underscore", "style", "naming" ]
train
https://github.com/WoLpH/python-utils/blob/6bbe13bab33bd9965b0edd379f26261b31a3e427/python_utils/formatters.py#L4-L39
WoLpH/python-utils
python_utils/formatters.py
timesince
def timesince(dt, default='just now'): ''' Returns string representing 'time since' e.g. 3 days ago, 5 hours ago etc. >>> now = datetime.datetime.now() >>> timesince(now) 'just now' >>> timesince(now - datetime.timedelta(seconds=1)) '1 second ago' >>> timesince(now - datetime.timedelta(seconds=2)) '2 seconds ago' >>> timesince(now - datetime.timedelta(seconds=60)) '1 minute ago' >>> timesince(now - datetime.timedelta(seconds=61)) '1 minute and 1 second ago' >>> timesince(now - datetime.timedelta(seconds=62)) '1 minute and 2 seconds ago' >>> timesince(now - datetime.timedelta(seconds=120)) '2 minutes ago' >>> timesince(now - datetime.timedelta(seconds=121)) '2 minutes and 1 second ago' >>> timesince(now - datetime.timedelta(seconds=122)) '2 minutes and 2 seconds ago' >>> timesince(now - datetime.timedelta(seconds=3599)) '59 minutes and 59 seconds ago' >>> timesince(now - datetime.timedelta(seconds=3600)) '1 hour ago' >>> timesince(now - datetime.timedelta(seconds=3601)) '1 hour and 1 second ago' >>> timesince(now - datetime.timedelta(seconds=3602)) '1 hour and 2 seconds ago' >>> timesince(now - datetime.timedelta(seconds=3660)) '1 hour and 1 minute ago' >>> timesince(now - datetime.timedelta(seconds=3661)) '1 hour and 1 minute ago' >>> timesince(now - datetime.timedelta(seconds=3720)) '1 hour and 2 minutes ago' >>> timesince(now - datetime.timedelta(seconds=3721)) '1 hour and 2 minutes ago' >>> timesince(datetime.timedelta(seconds=3721)) '1 hour and 2 minutes ago' ''' if isinstance(dt, datetime.timedelta): diff = dt else: now = datetime.datetime.now() diff = abs(now - dt) periods = ( (diff.days / 365, 'year', 'years'), (diff.days % 365 / 30, 'month', 'months'), (diff.days % 30 / 7, 'week', 'weeks'), (diff.days % 7, 'day', 'days'), (diff.seconds / 3600, 'hour', 'hours'), (diff.seconds % 3600 / 60, 'minute', 'minutes'), (diff.seconds % 60, 'second', 'seconds'), ) output = [] for period, singular, plural in periods: if int(period): if int(period) == 1: output.append('%d %s' % (period, singular)) else: output.append('%d %s' % (period, plural)) if output: return '%s ago' % ' and '.join(output[:2]) return default
python
def timesince(dt, default='just now'): ''' Returns string representing 'time since' e.g. 3 days ago, 5 hours ago etc. >>> now = datetime.datetime.now() >>> timesince(now) 'just now' >>> timesince(now - datetime.timedelta(seconds=1)) '1 second ago' >>> timesince(now - datetime.timedelta(seconds=2)) '2 seconds ago' >>> timesince(now - datetime.timedelta(seconds=60)) '1 minute ago' >>> timesince(now - datetime.timedelta(seconds=61)) '1 minute and 1 second ago' >>> timesince(now - datetime.timedelta(seconds=62)) '1 minute and 2 seconds ago' >>> timesince(now - datetime.timedelta(seconds=120)) '2 minutes ago' >>> timesince(now - datetime.timedelta(seconds=121)) '2 minutes and 1 second ago' >>> timesince(now - datetime.timedelta(seconds=122)) '2 minutes and 2 seconds ago' >>> timesince(now - datetime.timedelta(seconds=3599)) '59 minutes and 59 seconds ago' >>> timesince(now - datetime.timedelta(seconds=3600)) '1 hour ago' >>> timesince(now - datetime.timedelta(seconds=3601)) '1 hour and 1 second ago' >>> timesince(now - datetime.timedelta(seconds=3602)) '1 hour and 2 seconds ago' >>> timesince(now - datetime.timedelta(seconds=3660)) '1 hour and 1 minute ago' >>> timesince(now - datetime.timedelta(seconds=3661)) '1 hour and 1 minute ago' >>> timesince(now - datetime.timedelta(seconds=3720)) '1 hour and 2 minutes ago' >>> timesince(now - datetime.timedelta(seconds=3721)) '1 hour and 2 minutes ago' >>> timesince(datetime.timedelta(seconds=3721)) '1 hour and 2 minutes ago' ''' if isinstance(dt, datetime.timedelta): diff = dt else: now = datetime.datetime.now() diff = abs(now - dt) periods = ( (diff.days / 365, 'year', 'years'), (diff.days % 365 / 30, 'month', 'months'), (diff.days % 30 / 7, 'week', 'weeks'), (diff.days % 7, 'day', 'days'), (diff.seconds / 3600, 'hour', 'hours'), (diff.seconds % 3600 / 60, 'minute', 'minutes'), (diff.seconds % 60, 'second', 'seconds'), ) output = [] for period, singular, plural in periods: if int(period): if int(period) == 1: output.append('%d %s' % (period, singular)) else: output.append('%d %s' % (period, plural)) if output: return '%s ago' % ' and '.join(output[:2]) return default
[ "def", "timesince", "(", "dt", ",", "default", "=", "'just now'", ")", ":", "if", "isinstance", "(", "dt", ",", "datetime", ".", "timedelta", ")", ":", "diff", "=", "dt", "else", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "diff", "=", "abs", "(", "now", "-", "dt", ")", "periods", "=", "(", "(", "diff", ".", "days", "/", "365", ",", "'year'", ",", "'years'", ")", ",", "(", "diff", ".", "days", "%", "365", "/", "30", ",", "'month'", ",", "'months'", ")", ",", "(", "diff", ".", "days", "%", "30", "/", "7", ",", "'week'", ",", "'weeks'", ")", ",", "(", "diff", ".", "days", "%", "7", ",", "'day'", ",", "'days'", ")", ",", "(", "diff", ".", "seconds", "/", "3600", ",", "'hour'", ",", "'hours'", ")", ",", "(", "diff", ".", "seconds", "%", "3600", "/", "60", ",", "'minute'", ",", "'minutes'", ")", ",", "(", "diff", ".", "seconds", "%", "60", ",", "'second'", ",", "'seconds'", ")", ",", ")", "output", "=", "[", "]", "for", "period", ",", "singular", ",", "plural", "in", "periods", ":", "if", "int", "(", "period", ")", ":", "if", "int", "(", "period", ")", "==", "1", ":", "output", ".", "append", "(", "'%d %s'", "%", "(", "period", ",", "singular", ")", ")", "else", ":", "output", ".", "append", "(", "'%d %s'", "%", "(", "period", ",", "plural", ")", ")", "if", "output", ":", "return", "'%s ago'", "%", "' and '", ".", "join", "(", "output", "[", ":", "2", "]", ")", "return", "default" ]
Returns string representing 'time since' e.g. 3 days ago, 5 hours ago etc. >>> now = datetime.datetime.now() >>> timesince(now) 'just now' >>> timesince(now - datetime.timedelta(seconds=1)) '1 second ago' >>> timesince(now - datetime.timedelta(seconds=2)) '2 seconds ago' >>> timesince(now - datetime.timedelta(seconds=60)) '1 minute ago' >>> timesince(now - datetime.timedelta(seconds=61)) '1 minute and 1 second ago' >>> timesince(now - datetime.timedelta(seconds=62)) '1 minute and 2 seconds ago' >>> timesince(now - datetime.timedelta(seconds=120)) '2 minutes ago' >>> timesince(now - datetime.timedelta(seconds=121)) '2 minutes and 1 second ago' >>> timesince(now - datetime.timedelta(seconds=122)) '2 minutes and 2 seconds ago' >>> timesince(now - datetime.timedelta(seconds=3599)) '59 minutes and 59 seconds ago' >>> timesince(now - datetime.timedelta(seconds=3600)) '1 hour ago' >>> timesince(now - datetime.timedelta(seconds=3601)) '1 hour and 1 second ago' >>> timesince(now - datetime.timedelta(seconds=3602)) '1 hour and 2 seconds ago' >>> timesince(now - datetime.timedelta(seconds=3660)) '1 hour and 1 minute ago' >>> timesince(now - datetime.timedelta(seconds=3661)) '1 hour and 1 minute ago' >>> timesince(now - datetime.timedelta(seconds=3720)) '1 hour and 2 minutes ago' >>> timesince(now - datetime.timedelta(seconds=3721)) '1 hour and 2 minutes ago' >>> timesince(datetime.timedelta(seconds=3721)) '1 hour and 2 minutes ago'
[ "Returns", "string", "representing", "time", "since", "e", ".", "g", ".", "3", "days", "ago", "5", "hours", "ago", "etc", "." ]
train
https://github.com/WoLpH/python-utils/blob/6bbe13bab33bd9965b0edd379f26261b31a3e427/python_utils/formatters.py#L42-L112
WoLpH/python-utils
python_utils/time.py
timedelta_to_seconds
def timedelta_to_seconds(delta): '''Convert a timedelta to seconds with the microseconds as fraction Note that this method has become largely obsolete with the `timedelta.total_seconds()` method introduced in Python 2.7. >>> from datetime import timedelta >>> '%d' % timedelta_to_seconds(timedelta(days=1)) '86400' >>> '%d' % timedelta_to_seconds(timedelta(seconds=1)) '1' >>> '%.6f' % timedelta_to_seconds(timedelta(seconds=1, microseconds=1)) '1.000001' >>> '%.6f' % timedelta_to_seconds(timedelta(microseconds=1)) '0.000001' ''' # Only convert to float if needed if delta.microseconds: total = delta.microseconds * 1e-6 else: total = 0 total += delta.seconds total += delta.days * 60 * 60 * 24 return total
python
def timedelta_to_seconds(delta): '''Convert a timedelta to seconds with the microseconds as fraction Note that this method has become largely obsolete with the `timedelta.total_seconds()` method introduced in Python 2.7. >>> from datetime import timedelta >>> '%d' % timedelta_to_seconds(timedelta(days=1)) '86400' >>> '%d' % timedelta_to_seconds(timedelta(seconds=1)) '1' >>> '%.6f' % timedelta_to_seconds(timedelta(seconds=1, microseconds=1)) '1.000001' >>> '%.6f' % timedelta_to_seconds(timedelta(microseconds=1)) '0.000001' ''' # Only convert to float if needed if delta.microseconds: total = delta.microseconds * 1e-6 else: total = 0 total += delta.seconds total += delta.days * 60 * 60 * 24 return total
[ "def", "timedelta_to_seconds", "(", "delta", ")", ":", "# Only convert to float if needed", "if", "delta", ".", "microseconds", ":", "total", "=", "delta", ".", "microseconds", "*", "1e-6", "else", ":", "total", "=", "0", "total", "+=", "delta", ".", "seconds", "total", "+=", "delta", ".", "days", "*", "60", "*", "60", "*", "24", "return", "total" ]
Convert a timedelta to seconds with the microseconds as fraction Note that this method has become largely obsolete with the `timedelta.total_seconds()` method introduced in Python 2.7. >>> from datetime import timedelta >>> '%d' % timedelta_to_seconds(timedelta(days=1)) '86400' >>> '%d' % timedelta_to_seconds(timedelta(seconds=1)) '1' >>> '%.6f' % timedelta_to_seconds(timedelta(seconds=1, microseconds=1)) '1.000001' >>> '%.6f' % timedelta_to_seconds(timedelta(microseconds=1)) '0.000001'
[ "Convert", "a", "timedelta", "to", "seconds", "with", "the", "microseconds", "as", "fraction" ]
train
https://github.com/WoLpH/python-utils/blob/6bbe13bab33bd9965b0edd379f26261b31a3e427/python_utils/time.py#L10-L33
WoLpH/python-utils
python_utils/time.py
format_time
def format_time(timestamp, precision=datetime.timedelta(seconds=1)): '''Formats timedelta/datetime/seconds >>> format_time('1') '0:00:01' >>> format_time(1.234) '0:00:01' >>> format_time(1) '0:00:01' >>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6)) '2000-01-02 03:04:05' >>> format_time(datetime.date(2000, 1, 2)) '2000-01-02' >>> format_time(datetime.timedelta(seconds=3661)) '1:01:01' >>> format_time(None) '--:--:--' >>> format_time(format_time) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: Unknown type ... ''' precision_seconds = precision.total_seconds() if isinstance(timestamp, six.string_types + six.integer_types + (float, )): try: castfunc = six.integer_types[-1] timestamp = datetime.timedelta(seconds=castfunc(timestamp)) except OverflowError: # pragma: no cover timestamp = None if isinstance(timestamp, datetime.timedelta): seconds = timestamp.total_seconds() # Truncate the number to the given precision seconds = seconds - (seconds % precision_seconds) return str(datetime.timedelta(seconds=seconds)) elif isinstance(timestamp, datetime.datetime): # Python 2 doesn't have the timestamp method if hasattr(timestamp, 'timestamp'): # pragma: no cover seconds = timestamp.timestamp() else: seconds = timedelta_to_seconds(timestamp - epoch) # Truncate the number to the given precision seconds = seconds - (seconds % precision_seconds) try: # pragma: no cover if six.PY3: dt = datetime.datetime.fromtimestamp(seconds) else: dt = datetime.datetime.utcfromtimestamp(seconds) except ValueError: # pragma: no cover dt = datetime.datetime.max return str(dt) elif isinstance(timestamp, datetime.date): return str(timestamp) elif timestamp is None: return '--:--:--' else: raise TypeError('Unknown type %s: %r' % (type(timestamp), timestamp))
python
def format_time(timestamp, precision=datetime.timedelta(seconds=1)): '''Formats timedelta/datetime/seconds >>> format_time('1') '0:00:01' >>> format_time(1.234) '0:00:01' >>> format_time(1) '0:00:01' >>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6)) '2000-01-02 03:04:05' >>> format_time(datetime.date(2000, 1, 2)) '2000-01-02' >>> format_time(datetime.timedelta(seconds=3661)) '1:01:01' >>> format_time(None) '--:--:--' >>> format_time(format_time) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: Unknown type ... ''' precision_seconds = precision.total_seconds() if isinstance(timestamp, six.string_types + six.integer_types + (float, )): try: castfunc = six.integer_types[-1] timestamp = datetime.timedelta(seconds=castfunc(timestamp)) except OverflowError: # pragma: no cover timestamp = None if isinstance(timestamp, datetime.timedelta): seconds = timestamp.total_seconds() # Truncate the number to the given precision seconds = seconds - (seconds % precision_seconds) return str(datetime.timedelta(seconds=seconds)) elif isinstance(timestamp, datetime.datetime): # Python 2 doesn't have the timestamp method if hasattr(timestamp, 'timestamp'): # pragma: no cover seconds = timestamp.timestamp() else: seconds = timedelta_to_seconds(timestamp - epoch) # Truncate the number to the given precision seconds = seconds - (seconds % precision_seconds) try: # pragma: no cover if six.PY3: dt = datetime.datetime.fromtimestamp(seconds) else: dt = datetime.datetime.utcfromtimestamp(seconds) except ValueError: # pragma: no cover dt = datetime.datetime.max return str(dt) elif isinstance(timestamp, datetime.date): return str(timestamp) elif timestamp is None: return '--:--:--' else: raise TypeError('Unknown type %s: %r' % (type(timestamp), timestamp))
[ "def", "format_time", "(", "timestamp", ",", "precision", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "1", ")", ")", ":", "precision_seconds", "=", "precision", ".", "total_seconds", "(", ")", "if", "isinstance", "(", "timestamp", ",", "six", ".", "string_types", "+", "six", ".", "integer_types", "+", "(", "float", ",", ")", ")", ":", "try", ":", "castfunc", "=", "six", ".", "integer_types", "[", "-", "1", "]", "timestamp", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "castfunc", "(", "timestamp", ")", ")", "except", "OverflowError", ":", "# pragma: no cover", "timestamp", "=", "None", "if", "isinstance", "(", "timestamp", ",", "datetime", ".", "timedelta", ")", ":", "seconds", "=", "timestamp", ".", "total_seconds", "(", ")", "# Truncate the number to the given precision", "seconds", "=", "seconds", "-", "(", "seconds", "%", "precision_seconds", ")", "return", "str", "(", "datetime", ".", "timedelta", "(", "seconds", "=", "seconds", ")", ")", "elif", "isinstance", "(", "timestamp", ",", "datetime", ".", "datetime", ")", ":", "# Python 2 doesn't have the timestamp method", "if", "hasattr", "(", "timestamp", ",", "'timestamp'", ")", ":", "# pragma: no cover", "seconds", "=", "timestamp", ".", "timestamp", "(", ")", "else", ":", "seconds", "=", "timedelta_to_seconds", "(", "timestamp", "-", "epoch", ")", "# Truncate the number to the given precision", "seconds", "=", "seconds", "-", "(", "seconds", "%", "precision_seconds", ")", "try", ":", "# pragma: no cover", "if", "six", ".", "PY3", ":", "dt", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "seconds", ")", "else", ":", "dt", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "seconds", ")", "except", "ValueError", ":", "# pragma: no cover", "dt", "=", "datetime", ".", "datetime", ".", "max", "return", "str", "(", "dt", ")", "elif", "isinstance", "(", "timestamp", ",", "datetime", ".", "date", ")", ":", "return", "str", "(", "timestamp", ")", "elif", "timestamp", "is", "None", ":", "return", "'--:--:--'", "else", ":", "raise", "TypeError", "(", "'Unknown type %s: %r'", "%", "(", "type", "(", "timestamp", ")", ",", "timestamp", ")", ")" ]
Formats timedelta/datetime/seconds >>> format_time('1') '0:00:01' >>> format_time(1.234) '0:00:01' >>> format_time(1) '0:00:01' >>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6)) '2000-01-02 03:04:05' >>> format_time(datetime.date(2000, 1, 2)) '2000-01-02' >>> format_time(datetime.timedelta(seconds=3661)) '1:01:01' >>> format_time(None) '--:--:--' >>> format_time(format_time) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: Unknown type ...
[ "Formats", "timedelta", "/", "datetime", "/", "seconds" ]
train
https://github.com/WoLpH/python-utils/blob/6bbe13bab33bd9965b0edd379f26261b31a3e427/python_utils/time.py#L36-L97
WoLpH/python-utils
python_utils/terminal.py
get_terminal_size
def get_terminal_size(): # pragma: no cover '''Get the current size of your terminal Multiple returns are not always a good idea, but in this case it greatly simplifies the code so I believe it's justified. It's not the prettiest function but that's never really possible with cross-platform code. Returns: width, height: Two integers containing width and height ''' try: # Default to 79 characters for IPython notebooks from IPython import get_ipython ipython = get_ipython() from ipykernel import zmqshell if isinstance(ipython, zmqshell.ZMQInteractiveShell): return 79, 24 except Exception: # pragma: no cover pass try: # This works for Python 3, but not Pypy3. Probably the best method if # it's supported so let's always try import shutil w, h = shutil.get_terminal_size() if w and h: # The off by one is needed due to progressbars in some cases, for # safety we'll always substract it. return w - 1, h except Exception: # pragma: no cover pass try: w = int(os.environ.get('COLUMNS')) h = int(os.environ.get('LINES')) if w and h: return w, h except Exception: # pragma: no cover pass try: import blessings terminal = blessings.Terminal() w = terminal.width h = terminal.height if w and h: return w, h except Exception: # pragma: no cover pass try: w, h = _get_terminal_size_linux() if w and h: return w, h except Exception: # pragma: no cover pass try: # Windows detection doesn't always work, let's try anyhow w, h = _get_terminal_size_windows() if w and h: return w, h except Exception: # pragma: no cover pass try: # needed for window's python in cygwin's xterm! w, h = _get_terminal_size_tput() if w and h: return w, h except Exception: # pragma: no cover pass return 79, 24
python
def get_terminal_size(): # pragma: no cover '''Get the current size of your terminal Multiple returns are not always a good idea, but in this case it greatly simplifies the code so I believe it's justified. It's not the prettiest function but that's never really possible with cross-platform code. Returns: width, height: Two integers containing width and height ''' try: # Default to 79 characters for IPython notebooks from IPython import get_ipython ipython = get_ipython() from ipykernel import zmqshell if isinstance(ipython, zmqshell.ZMQInteractiveShell): return 79, 24 except Exception: # pragma: no cover pass try: # This works for Python 3, but not Pypy3. Probably the best method if # it's supported so let's always try import shutil w, h = shutil.get_terminal_size() if w and h: # The off by one is needed due to progressbars in some cases, for # safety we'll always substract it. return w - 1, h except Exception: # pragma: no cover pass try: w = int(os.environ.get('COLUMNS')) h = int(os.environ.get('LINES')) if w and h: return w, h except Exception: # pragma: no cover pass try: import blessings terminal = blessings.Terminal() w = terminal.width h = terminal.height if w and h: return w, h except Exception: # pragma: no cover pass try: w, h = _get_terminal_size_linux() if w and h: return w, h except Exception: # pragma: no cover pass try: # Windows detection doesn't always work, let's try anyhow w, h = _get_terminal_size_windows() if w and h: return w, h except Exception: # pragma: no cover pass try: # needed for window's python in cygwin's xterm! w, h = _get_terminal_size_tput() if w and h: return w, h except Exception: # pragma: no cover pass return 79, 24
[ "def", "get_terminal_size", "(", ")", ":", "# pragma: no cover", "try", ":", "# Default to 79 characters for IPython notebooks", "from", "IPython", "import", "get_ipython", "ipython", "=", "get_ipython", "(", ")", "from", "ipykernel", "import", "zmqshell", "if", "isinstance", "(", "ipython", ",", "zmqshell", ".", "ZMQInteractiveShell", ")", ":", "return", "79", ",", "24", "except", "Exception", ":", "# pragma: no cover", "pass", "try", ":", "# This works for Python 3, but not Pypy3. Probably the best method if", "# it's supported so let's always try", "import", "shutil", "w", ",", "h", "=", "shutil", ".", "get_terminal_size", "(", ")", "if", "w", "and", "h", ":", "# The off by one is needed due to progressbars in some cases, for", "# safety we'll always substract it.", "return", "w", "-", "1", ",", "h", "except", "Exception", ":", "# pragma: no cover", "pass", "try", ":", "w", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "'COLUMNS'", ")", ")", "h", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "'LINES'", ")", ")", "if", "w", "and", "h", ":", "return", "w", ",", "h", "except", "Exception", ":", "# pragma: no cover", "pass", "try", ":", "import", "blessings", "terminal", "=", "blessings", ".", "Terminal", "(", ")", "w", "=", "terminal", ".", "width", "h", "=", "terminal", ".", "height", "if", "w", "and", "h", ":", "return", "w", ",", "h", "except", "Exception", ":", "# pragma: no cover", "pass", "try", ":", "w", ",", "h", "=", "_get_terminal_size_linux", "(", ")", "if", "w", "and", "h", ":", "return", "w", ",", "h", "except", "Exception", ":", "# pragma: no cover", "pass", "try", ":", "# Windows detection doesn't always work, let's try anyhow", "w", ",", "h", "=", "_get_terminal_size_windows", "(", ")", "if", "w", "and", "h", ":", "return", "w", ",", "h", "except", "Exception", ":", "# pragma: no cover", "pass", "try", ":", "# needed for window's python in cygwin's xterm!", "w", ",", "h", "=", "_get_terminal_size_tput", "(", ")", "if", "w", "and", "h", ":", "return", "w", ",", "h", "except", "Exception", ":", "# pragma: no cover", "pass", "return", "79", ",", "24" ]
Get the current size of your terminal Multiple returns are not always a good idea, but in this case it greatly simplifies the code so I believe it's justified. It's not the prettiest function but that's never really possible with cross-platform code. Returns: width, height: Two integers containing width and height
[ "Get", "the", "current", "size", "of", "your", "terminal" ]
train
https://github.com/WoLpH/python-utils/blob/6bbe13bab33bd9965b0edd379f26261b31a3e427/python_utils/terminal.py#L4-L78
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.AsyncSearchUsers
def AsyncSearchUsers(self, Target): """Asynchronously searches for Skype users. :Parameters: Target : unicode Search target (name or email address). :return: A search identifier. It will be passed along with the results to the `SkypeEvents.AsyncSearchUsersFinished` event after the search is completed. :rtype: int """ if not hasattr(self, '_AsyncSearchUsersCommands'): self._AsyncSearchUsersCommands = [] self.RegisterEventHandler('Reply', self._AsyncSearchUsersReplyHandler) command = Command('SEARCH USERS %s' % tounicode(Target), 'USERS', False, self.Timeout) self._AsyncSearchUsersCommands.append(command) self.SendCommand(command) # return pCookie - search identifier return command.Id
python
def AsyncSearchUsers(self, Target): """Asynchronously searches for Skype users. :Parameters: Target : unicode Search target (name or email address). :return: A search identifier. It will be passed along with the results to the `SkypeEvents.AsyncSearchUsersFinished` event after the search is completed. :rtype: int """ if not hasattr(self, '_AsyncSearchUsersCommands'): self._AsyncSearchUsersCommands = [] self.RegisterEventHandler('Reply', self._AsyncSearchUsersReplyHandler) command = Command('SEARCH USERS %s' % tounicode(Target), 'USERS', False, self.Timeout) self._AsyncSearchUsersCommands.append(command) self.SendCommand(command) # return pCookie - search identifier return command.Id
[ "def", "AsyncSearchUsers", "(", "self", ",", "Target", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_AsyncSearchUsersCommands'", ")", ":", "self", ".", "_AsyncSearchUsersCommands", "=", "[", "]", "self", ".", "RegisterEventHandler", "(", "'Reply'", ",", "self", ".", "_AsyncSearchUsersReplyHandler", ")", "command", "=", "Command", "(", "'SEARCH USERS %s'", "%", "tounicode", "(", "Target", ")", ",", "'USERS'", ",", "False", ",", "self", ".", "Timeout", ")", "self", ".", "_AsyncSearchUsersCommands", ".", "append", "(", "command", ")", "self", ".", "SendCommand", "(", "command", ")", "# return pCookie - search identifier", "return", "command", ".", "Id" ]
Asynchronously searches for Skype users. :Parameters: Target : unicode Search target (name or email address). :return: A search identifier. It will be passed along with the results to the `SkypeEvents.AsyncSearchUsersFinished` event after the search is completed. :rtype: int
[ "Asynchronously", "searches", "for", "Skype", "users", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L376-L394
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.Attach
def Attach(self, Protocol=5, Wait=True): """Establishes a connection to Skype. :Parameters: Protocol : int Minimal Skype protocol version. Wait : bool If set to False, blocks forever until the connection is established. Otherwise, timeouts after the `Timeout`. """ try: self._Api.protocol = Protocol self._Api.attach(self.Timeout, Wait) except SkypeAPIError: self.ResetCache() raise
python
def Attach(self, Protocol=5, Wait=True): """Establishes a connection to Skype. :Parameters: Protocol : int Minimal Skype protocol version. Wait : bool If set to False, blocks forever until the connection is established. Otherwise, timeouts after the `Timeout`. """ try: self._Api.protocol = Protocol self._Api.attach(self.Timeout, Wait) except SkypeAPIError: self.ResetCache() raise
[ "def", "Attach", "(", "self", ",", "Protocol", "=", "5", ",", "Wait", "=", "True", ")", ":", "try", ":", "self", ".", "_Api", ".", "protocol", "=", "Protocol", "self", ".", "_Api", ".", "attach", "(", "self", ".", "Timeout", ",", "Wait", ")", "except", "SkypeAPIError", ":", "self", ".", "ResetCache", "(", ")", "raise" ]
Establishes a connection to Skype. :Parameters: Protocol : int Minimal Skype protocol version. Wait : bool If set to False, blocks forever until the connection is established. Otherwise, timeouts after the `Timeout`.
[ "Establishes", "a", "connection", "to", "Skype", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L396-L411
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.Call
def Call(self, Id=0): """Queries a call object. :Parameters: Id : int Call identifier. :return: Call object. :rtype: `call.Call` """ o = Call(self, Id) o.Status # Test if such a call exists. return o
python
def Call(self, Id=0): """Queries a call object. :Parameters: Id : int Call identifier. :return: Call object. :rtype: `call.Call` """ o = Call(self, Id) o.Status # Test if such a call exists. return o
[ "def", "Call", "(", "self", ",", "Id", "=", "0", ")", ":", "o", "=", "Call", "(", "self", ",", "Id", ")", "o", ".", "Status", "# Test if such a call exists.", "return", "o" ]
Queries a call object. :Parameters: Id : int Call identifier. :return: Call object. :rtype: `call.Call`
[ "Queries", "a", "call", "object", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L413-L425
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.ChangeUserStatus
def ChangeUserStatus(self, Status): """Changes the online status for the current user. :Parameters: Status : `enums`.cus* New online status for the user. :note: This function waits until the online status changes. Alternatively, use the `CurrentUserStatus` property to perform an immediate change of status. """ if self.CurrentUserStatus.upper() == Status.upper(): return self._ChangeUserStatus_Event = threading.Event() self._ChangeUserStatus_Status = Status.upper() self.RegisterEventHandler('UserStatus', self._ChangeUserStatus_UserStatus) self.CurrentUserStatus = Status self._ChangeUserStatus_Event.wait() self.UnregisterEventHandler('UserStatus', self._ChangeUserStatus_UserStatus) del self._ChangeUserStatus_Event, self._ChangeUserStatus_Status
python
def ChangeUserStatus(self, Status): """Changes the online status for the current user. :Parameters: Status : `enums`.cus* New online status for the user. :note: This function waits until the online status changes. Alternatively, use the `CurrentUserStatus` property to perform an immediate change of status. """ if self.CurrentUserStatus.upper() == Status.upper(): return self._ChangeUserStatus_Event = threading.Event() self._ChangeUserStatus_Status = Status.upper() self.RegisterEventHandler('UserStatus', self._ChangeUserStatus_UserStatus) self.CurrentUserStatus = Status self._ChangeUserStatus_Event.wait() self.UnregisterEventHandler('UserStatus', self._ChangeUserStatus_UserStatus) del self._ChangeUserStatus_Event, self._ChangeUserStatus_Status
[ "def", "ChangeUserStatus", "(", "self", ",", "Status", ")", ":", "if", "self", ".", "CurrentUserStatus", ".", "upper", "(", ")", "==", "Status", ".", "upper", "(", ")", ":", "return", "self", ".", "_ChangeUserStatus_Event", "=", "threading", ".", "Event", "(", ")", "self", ".", "_ChangeUserStatus_Status", "=", "Status", ".", "upper", "(", ")", "self", ".", "RegisterEventHandler", "(", "'UserStatus'", ",", "self", ".", "_ChangeUserStatus_UserStatus", ")", "self", ".", "CurrentUserStatus", "=", "Status", "self", ".", "_ChangeUserStatus_Event", ".", "wait", "(", ")", "self", ".", "UnregisterEventHandler", "(", "'UserStatus'", ",", "self", ".", "_ChangeUserStatus_UserStatus", ")", "del", "self", ".", "_ChangeUserStatus_Event", ",", "self", ".", "_ChangeUserStatus_Status" ]
Changes the online status for the current user. :Parameters: Status : `enums`.cus* New online status for the user. :note: This function waits until the online status changes. Alternatively, use the `CurrentUserStatus` property to perform an immediate change of status.
[ "Changes", "the", "online", "status", "for", "the", "current", "user", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L443-L461
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.Chat
def Chat(self, Name=''): """Queries a chat object. :Parameters: Name : str Chat name. :return: A chat object. :rtype: `chat.Chat` """ o = Chat(self, Name) o.Status # Tests if such a chat really exists. return o
python
def Chat(self, Name=''): """Queries a chat object. :Parameters: Name : str Chat name. :return: A chat object. :rtype: `chat.Chat` """ o = Chat(self, Name) o.Status # Tests if such a chat really exists. return o
[ "def", "Chat", "(", "self", ",", "Name", "=", "''", ")", ":", "o", "=", "Chat", "(", "self", ",", "Name", ")", "o", ".", "Status", "# Tests if such a chat really exists.", "return", "o" ]
Queries a chat object. :Parameters: Name : str Chat name. :return: A chat object. :rtype: `chat.Chat`
[ "Queries", "a", "chat", "object", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L463-L475
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.ClearCallHistory
def ClearCallHistory(self, Username='ALL', Type=chsAllCalls): """Clears the call history. :Parameters: Username : str Skypename of the user. A special value of 'ALL' means that entries of all users should be removed. Type : `enums`.clt* Call type. """ cmd = 'CLEAR CALLHISTORY %s %s' % (str(Type), Username) self._DoCommand(cmd, cmd)
python
def ClearCallHistory(self, Username='ALL', Type=chsAllCalls): """Clears the call history. :Parameters: Username : str Skypename of the user. A special value of 'ALL' means that entries of all users should be removed. Type : `enums`.clt* Call type. """ cmd = 'CLEAR CALLHISTORY %s %s' % (str(Type), Username) self._DoCommand(cmd, cmd)
[ "def", "ClearCallHistory", "(", "self", ",", "Username", "=", "'ALL'", ",", "Type", "=", "chsAllCalls", ")", ":", "cmd", "=", "'CLEAR CALLHISTORY %s %s'", "%", "(", "str", "(", "Type", ")", ",", "Username", ")", "self", ".", "_DoCommand", "(", "cmd", ",", "cmd", ")" ]
Clears the call history. :Parameters: Username : str Skypename of the user. A special value of 'ALL' means that entries of all users should be removed. Type : `enums`.clt* Call type.
[ "Clears", "the", "call", "history", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L477-L488
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.Command
def Command(self, Command, Reply=u'', Block=False, Timeout=30000, Id=-1): """Creates an API command object. :Parameters: Command : unicode Command string. Reply : unicode Expected reply. By default any reply is accepted (except errors which raise an `SkypeError` exception). Block : bool If set to True, `SendCommand` method waits for a response from Skype API before returning. Timeout : float, int or long Timeout. Used if Block == True. Timeout may be expressed in milliseconds if the type is int or long or in seconds (or fractions thereof) if the type is float. Id : int Command Id. The default (-1) means it will be assigned automatically as soon as the command is sent. :return: A command object. :rtype: `Command` :see: `SendCommand` """ from api import Command as CommandClass return CommandClass(Command, Reply, Block, Timeout, Id)
python
def Command(self, Command, Reply=u'', Block=False, Timeout=30000, Id=-1): """Creates an API command object. :Parameters: Command : unicode Command string. Reply : unicode Expected reply. By default any reply is accepted (except errors which raise an `SkypeError` exception). Block : bool If set to True, `SendCommand` method waits for a response from Skype API before returning. Timeout : float, int or long Timeout. Used if Block == True. Timeout may be expressed in milliseconds if the type is int or long or in seconds (or fractions thereof) if the type is float. Id : int Command Id. The default (-1) means it will be assigned automatically as soon as the command is sent. :return: A command object. :rtype: `Command` :see: `SendCommand` """ from api import Command as CommandClass return CommandClass(Command, Reply, Block, Timeout, Id)
[ "def", "Command", "(", "self", ",", "Command", ",", "Reply", "=", "u''", ",", "Block", "=", "False", ",", "Timeout", "=", "30000", ",", "Id", "=", "-", "1", ")", ":", "from", "api", "import", "Command", "as", "CommandClass", "return", "CommandClass", "(", "Command", ",", "Reply", ",", "Block", ",", "Timeout", ",", "Id", ")" ]
Creates an API command object. :Parameters: Command : unicode Command string. Reply : unicode Expected reply. By default any reply is accepted (except errors which raise an `SkypeError` exception). Block : bool If set to True, `SendCommand` method waits for a response from Skype API before returning. Timeout : float, int or long Timeout. Used if Block == True. Timeout may be expressed in milliseconds if the type is int or long or in seconds (or fractions thereof) if the type is float. Id : int Command Id. The default (-1) means it will be assigned automatically as soon as the command is sent. :return: A command object. :rtype: `Command` :see: `SendCommand`
[ "Creates", "an", "API", "command", "object", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L501-L526
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.Conference
def Conference(self, Id=0): """Queries a call conference object. :Parameters: Id : int Conference Id. :return: A conference object. :rtype: `Conference` """ o = Conference(self, Id) if Id <= 0 or not o.Calls: raise SkypeError(0, 'Unknown conference') return o
python
def Conference(self, Id=0): """Queries a call conference object. :Parameters: Id : int Conference Id. :return: A conference object. :rtype: `Conference` """ o = Conference(self, Id) if Id <= 0 or not o.Calls: raise SkypeError(0, 'Unknown conference') return o
[ "def", "Conference", "(", "self", ",", "Id", "=", "0", ")", ":", "o", "=", "Conference", "(", "self", ",", "Id", ")", "if", "Id", "<=", "0", "or", "not", "o", ".", "Calls", ":", "raise", "SkypeError", "(", "0", ",", "'Unknown conference'", ")", "return", "o" ]
Queries a call conference object. :Parameters: Id : int Conference Id. :return: A conference object. :rtype: `Conference`
[ "Queries", "a", "call", "conference", "object", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L528-L541
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.CreateChatWith
def CreateChatWith(self, *Usernames): """Creates a chat with one or more users. :Parameters: Usernames : str One or more Skypenames of the users. :return: A chat object :rtype: `Chat` :see: `Chat.AddMembers` """ return Chat(self, chop(self._DoCommand('CHAT CREATE %s' % ', '.join(Usernames)), 2)[1])
python
def CreateChatWith(self, *Usernames): """Creates a chat with one or more users. :Parameters: Usernames : str One or more Skypenames of the users. :return: A chat object :rtype: `Chat` :see: `Chat.AddMembers` """ return Chat(self, chop(self._DoCommand('CHAT CREATE %s' % ', '.join(Usernames)), 2)[1])
[ "def", "CreateChatWith", "(", "self", ",", "*", "Usernames", ")", ":", "return", "Chat", "(", "self", ",", "chop", "(", "self", ".", "_DoCommand", "(", "'CHAT CREATE %s'", "%", "', '", ".", "join", "(", "Usernames", ")", ")", ",", "2", ")", "[", "1", "]", ")" ]
Creates a chat with one or more users. :Parameters: Usernames : str One or more Skypenames of the users. :return: A chat object :rtype: `Chat` :see: `Chat.AddMembers`
[ "Creates", "a", "chat", "with", "one", "or", "more", "users", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L555-L567
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.CreateGroup
def CreateGroup(self, GroupName): """Creates a custom contact group. :Parameters: GroupName : unicode Group name. :return: A group object. :rtype: `Group` :see: `DeleteGroup` """ groups = self.CustomGroups self._DoCommand('CREATE GROUP %s' % tounicode(GroupName)) for g in self.CustomGroups: if g not in groups and g.DisplayName == GroupName: return g raise SkypeError(0, 'Group creating failed')
python
def CreateGroup(self, GroupName): """Creates a custom contact group. :Parameters: GroupName : unicode Group name. :return: A group object. :rtype: `Group` :see: `DeleteGroup` """ groups = self.CustomGroups self._DoCommand('CREATE GROUP %s' % tounicode(GroupName)) for g in self.CustomGroups: if g not in groups and g.DisplayName == GroupName: return g raise SkypeError(0, 'Group creating failed')
[ "def", "CreateGroup", "(", "self", ",", "GroupName", ")", ":", "groups", "=", "self", ".", "CustomGroups", "self", ".", "_DoCommand", "(", "'CREATE GROUP %s'", "%", "tounicode", "(", "GroupName", ")", ")", "for", "g", "in", "self", ".", "CustomGroups", ":", "if", "g", "not", "in", "groups", "and", "g", ".", "DisplayName", "==", "GroupName", ":", "return", "g", "raise", "SkypeError", "(", "0", ",", "'Group creating failed'", ")" ]
Creates a custom contact group. :Parameters: GroupName : unicode Group name. :return: A group object. :rtype: `Group` :see: `DeleteGroup`
[ "Creates", "a", "custom", "contact", "group", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L569-L586
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.CreateSms
def CreateSms(self, MessageType, *TargetNumbers): """Creates an SMS message. :Parameters: MessageType : `enums`.smsMessageType* Message type. TargetNumbers : str One or more target SMS numbers. :return: An sms message object. :rtype: `SmsMessage` """ return SmsMessage(self, chop(self._DoCommand('CREATE SMS %s %s' % (MessageType, ', '.join(TargetNumbers))), 2)[1])
python
def CreateSms(self, MessageType, *TargetNumbers): """Creates an SMS message. :Parameters: MessageType : `enums`.smsMessageType* Message type. TargetNumbers : str One or more target SMS numbers. :return: An sms message object. :rtype: `SmsMessage` """ return SmsMessage(self, chop(self._DoCommand('CREATE SMS %s %s' % (MessageType, ', '.join(TargetNumbers))), 2)[1])
[ "def", "CreateSms", "(", "self", ",", "MessageType", ",", "*", "TargetNumbers", ")", ":", "return", "SmsMessage", "(", "self", ",", "chop", "(", "self", ".", "_DoCommand", "(", "'CREATE SMS %s %s'", "%", "(", "MessageType", ",", "', '", ".", "join", "(", "TargetNumbers", ")", ")", ")", ",", "2", ")", "[", "1", "]", ")" ]
Creates an SMS message. :Parameters: MessageType : `enums`.smsMessageType* Message type. TargetNumbers : str One or more target SMS numbers. :return: An sms message object. :rtype: `SmsMessage`
[ "Creates", "an", "SMS", "message", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L588-L600
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.Greeting
def Greeting(self, Username=''): """Queries the greeting used as voicemail. :Parameters: Username : str Skypename of the user. :return: A voicemail object. :rtype: `Voicemail` """ for v in self.Voicemails: if Username and v.PartnerHandle != Username: continue if v.Type in (vmtDefaultGreeting, vmtCustomGreeting): return v
python
def Greeting(self, Username=''): """Queries the greeting used as voicemail. :Parameters: Username : str Skypename of the user. :return: A voicemail object. :rtype: `Voicemail` """ for v in self.Voicemails: if Username and v.PartnerHandle != Username: continue if v.Type in (vmtDefaultGreeting, vmtCustomGreeting): return v
[ "def", "Greeting", "(", "self", ",", "Username", "=", "''", ")", ":", "for", "v", "in", "self", ".", "Voicemails", ":", "if", "Username", "and", "v", ".", "PartnerHandle", "!=", "Username", ":", "continue", "if", "v", ".", "Type", "in", "(", "vmtDefaultGreeting", ",", "vmtCustomGreeting", ")", ":", "return", "v" ]
Queries the greeting used as voicemail. :Parameters: Username : str Skypename of the user. :return: A voicemail object. :rtype: `Voicemail`
[ "Queries", "the", "greeting", "used", "as", "voicemail", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L638-L652
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.Message
def Message(self, Id=0): """Queries a chat message object. :Parameters: Id : int Message Id. :return: A chat message object. :rtype: `ChatMessage` """ o = ChatMessage(self, Id) o.Status # Test if such an id is known. return o
python
def Message(self, Id=0): """Queries a chat message object. :Parameters: Id : int Message Id. :return: A chat message object. :rtype: `ChatMessage` """ o = ChatMessage(self, Id) o.Status # Test if such an id is known. return o
[ "def", "Message", "(", "self", ",", "Id", "=", "0", ")", ":", "o", "=", "ChatMessage", "(", "self", ",", "Id", ")", "o", ".", "Status", "# Test if such an id is known.", "return", "o" ]
Queries a chat message object. :Parameters: Id : int Message Id. :return: A chat message object. :rtype: `ChatMessage`
[ "Queries", "a", "chat", "message", "object", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L654-L666
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.PlaceCall
def PlaceCall(self, *Targets): """Places a call to a single user or creates a conference call. :Parameters: Targets : str One or more call targets. If multiple targets are specified, a conference call is created. The call target can be a Skypename, phone number, or speed dial code. :return: A call object. :rtype: `call.Call` """ calls = self.ActiveCalls reply = self._DoCommand('CALL %s' % ', '.join(Targets)) # Skype for Windows returns the call status which gives us the call Id; if reply.startswith('CALL '): return Call(self, chop(reply, 2)[1]) # On linux we get 'OK' as reply so we search for the new call on # list of active calls. for c in self.ActiveCalls: if c not in calls: return c raise SkypeError(0, 'Placing call failed')
python
def PlaceCall(self, *Targets): """Places a call to a single user or creates a conference call. :Parameters: Targets : str One or more call targets. If multiple targets are specified, a conference call is created. The call target can be a Skypename, phone number, or speed dial code. :return: A call object. :rtype: `call.Call` """ calls = self.ActiveCalls reply = self._DoCommand('CALL %s' % ', '.join(Targets)) # Skype for Windows returns the call status which gives us the call Id; if reply.startswith('CALL '): return Call(self, chop(reply, 2)[1]) # On linux we get 'OK' as reply so we search for the new call on # list of active calls. for c in self.ActiveCalls: if c not in calls: return c raise SkypeError(0, 'Placing call failed')
[ "def", "PlaceCall", "(", "self", ",", "*", "Targets", ")", ":", "calls", "=", "self", ".", "ActiveCalls", "reply", "=", "self", ".", "_DoCommand", "(", "'CALL %s'", "%", "', '", ".", "join", "(", "Targets", ")", ")", "# Skype for Windows returns the call status which gives us the call Id;", "if", "reply", ".", "startswith", "(", "'CALL '", ")", ":", "return", "Call", "(", "self", ",", "chop", "(", "reply", ",", "2", ")", "[", "1", "]", ")", "# On linux we get 'OK' as reply so we search for the new call on", "# list of active calls.", "for", "c", "in", "self", ".", "ActiveCalls", ":", "if", "c", "not", "in", "calls", ":", "return", "c", "raise", "SkypeError", "(", "0", ",", "'Placing call failed'", ")" ]
Places a call to a single user or creates a conference call. :Parameters: Targets : str One or more call targets. If multiple targets are specified, a conference call is created. The call target can be a Skypename, phone number, or speed dial code. :return: A call object. :rtype: `call.Call`
[ "Places", "a", "call", "to", "a", "single", "user", "or", "creates", "a", "conference", "call", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L680-L701
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.Property
def Property(self, ObjectType, ObjectId, PropName, Set=None): """Queries/sets the properties of an object. :Parameters: ObjectType : str Object type ('USER', 'CALL', 'CHAT', 'CHATMESSAGE', ...). ObjectId : str Object Id, depends on the object type. PropName : str Name of the property to access. Set : unicode or None Value the property should be set to or None if the value should be queried. :return: Property value if Set=None, None otherwise. :rtype: unicode or None """ return self._Property(ObjectType, ObjectId, PropName, Set)
python
def Property(self, ObjectType, ObjectId, PropName, Set=None): """Queries/sets the properties of an object. :Parameters: ObjectType : str Object type ('USER', 'CALL', 'CHAT', 'CHATMESSAGE', ...). ObjectId : str Object Id, depends on the object type. PropName : str Name of the property to access. Set : unicode or None Value the property should be set to or None if the value should be queried. :return: Property value if Set=None, None otherwise. :rtype: unicode or None """ return self._Property(ObjectType, ObjectId, PropName, Set)
[ "def", "Property", "(", "self", ",", "ObjectType", ",", "ObjectId", ",", "PropName", ",", "Set", "=", "None", ")", ":", "return", "self", ".", "_Property", "(", "ObjectType", ",", "ObjectId", ",", "PropName", ",", "Set", ")" ]
Queries/sets the properties of an object. :Parameters: ObjectType : str Object type ('USER', 'CALL', 'CHAT', 'CHATMESSAGE', ...). ObjectId : str Object Id, depends on the object type. PropName : str Name of the property to access. Set : unicode or None Value the property should be set to or None if the value should be queried. :return: Property value if Set=None, None otherwise. :rtype: unicode or None
[ "Queries", "/", "sets", "the", "properties", "of", "an", "object", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L731-L747
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.SendCommand
def SendCommand(self, Command): """Sends an API command. :Parameters: Command : `Command` Command to send. Use `Command` method to create a command. """ try: self._Api.send_command(Command) except SkypeAPIError: self.ResetCache() raise
python
def SendCommand(self, Command): """Sends an API command. :Parameters: Command : `Command` Command to send. Use `Command` method to create a command. """ try: self._Api.send_command(Command) except SkypeAPIError: self.ResetCache() raise
[ "def", "SendCommand", "(", "self", ",", "Command", ")", ":", "try", ":", "self", ".", "_Api", ".", "send_command", "(", "Command", ")", "except", "SkypeAPIError", ":", "self", ".", "ResetCache", "(", ")", "raise" ]
Sends an API command. :Parameters: Command : `Command` Command to send. Use `Command` method to create a command.
[ "Sends", "an", "API", "command", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L770-L781
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.SendSms
def SendSms(self, *TargetNumbers, **Properties): """Creates and sends an SMS message. :Parameters: TargetNumbers : str One or more target SMS numbers. Properties Message properties. Properties available are same as `SmsMessage` object properties. :return: An sms message object. The message is already sent at this point. :rtype: `SmsMessage` """ sms = self.CreateSms(smsMessageTypeOutgoing, *TargetNumbers) for name, value in Properties.items(): if isinstance(getattr(sms.__class__, name, None), property): setattr(sms, name, value) else: raise TypeError('Unknown property: %s' % prop) sms.Send() return sms
python
def SendSms(self, *TargetNumbers, **Properties): """Creates and sends an SMS message. :Parameters: TargetNumbers : str One or more target SMS numbers. Properties Message properties. Properties available are same as `SmsMessage` object properties. :return: An sms message object. The message is already sent at this point. :rtype: `SmsMessage` """ sms = self.CreateSms(smsMessageTypeOutgoing, *TargetNumbers) for name, value in Properties.items(): if isinstance(getattr(sms.__class__, name, None), property): setattr(sms, name, value) else: raise TypeError('Unknown property: %s' % prop) sms.Send() return sms
[ "def", "SendSms", "(", "self", ",", "*", "TargetNumbers", ",", "*", "*", "Properties", ")", ":", "sms", "=", "self", ".", "CreateSms", "(", "smsMessageTypeOutgoing", ",", "*", "TargetNumbers", ")", "for", "name", ",", "value", "in", "Properties", ".", "items", "(", ")", ":", "if", "isinstance", "(", "getattr", "(", "sms", ".", "__class__", ",", "name", ",", "None", ")", ",", "property", ")", ":", "setattr", "(", "sms", ",", "name", ",", "value", ")", "else", ":", "raise", "TypeError", "(", "'Unknown property: %s'", "%", "prop", ")", "sms", ".", "Send", "(", ")", "return", "sms" ]
Creates and sends an SMS message. :Parameters: TargetNumbers : str One or more target SMS numbers. Properties Message properties. Properties available are same as `SmsMessage` object properties. :return: An sms message object. The message is already sent at this point. :rtype: `SmsMessage`
[ "Creates", "and", "sends", "an", "SMS", "message", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L797-L816
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.SendVoicemail
def SendVoicemail(self, Username): """Sends a voicemail to a specified user. :Parameters: Username : str Skypename of the user. :note: Should return a `Voicemail` object. This is not implemented yet. """ if self._Api.protocol >= 6: self._DoCommand('CALLVOICEMAIL %s' % Username) else: self._DoCommand('VOICEMAIL %s' % Username)
python
def SendVoicemail(self, Username): """Sends a voicemail to a specified user. :Parameters: Username : str Skypename of the user. :note: Should return a `Voicemail` object. This is not implemented yet. """ if self._Api.protocol >= 6: self._DoCommand('CALLVOICEMAIL %s' % Username) else: self._DoCommand('VOICEMAIL %s' % Username)
[ "def", "SendVoicemail", "(", "self", ",", "Username", ")", ":", "if", "self", ".", "_Api", ".", "protocol", ">=", "6", ":", "self", ".", "_DoCommand", "(", "'CALLVOICEMAIL %s'", "%", "Username", ")", "else", ":", "self", ".", "_DoCommand", "(", "'VOICEMAIL %s'", "%", "Username", ")" ]
Sends a voicemail to a specified user. :Parameters: Username : str Skypename of the user. :note: Should return a `Voicemail` object. This is not implemented yet.
[ "Sends", "a", "voicemail", "to", "a", "specified", "user", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L818-L830
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.User
def User(self, Username=''): """Queries a user object. :Parameters: Username : str Skypename of the user. :return: A user object. :rtype: `user.User` """ if not Username: Username = self.CurrentUserHandle o = User(self, Username) o.OnlineStatus # Test if such a user exists. return o
python
def User(self, Username=''): """Queries a user object. :Parameters: Username : str Skypename of the user. :return: A user object. :rtype: `user.User` """ if not Username: Username = self.CurrentUserHandle o = User(self, Username) o.OnlineStatus # Test if such a user exists. return o
[ "def", "User", "(", "self", ",", "Username", "=", "''", ")", ":", "if", "not", "Username", ":", "Username", "=", "self", ".", "CurrentUserHandle", "o", "=", "User", "(", "self", ",", "Username", ")", "o", ".", "OnlineStatus", "# Test if such a user exists.", "return", "o" ]
Queries a user object. :Parameters: Username : str Skypename of the user. :return: A user object. :rtype: `user.User`
[ "Queries", "a", "user", "object", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L832-L846
Skype4Py/Skype4Py
Skype4Py/skype.py
Skype.Voicemail
def Voicemail(self, Id): """Queries the voicemail object. :Parameters: Id : int Voicemail Id. :return: A voicemail object. :rtype: `Voicemail` """ o = Voicemail(self, Id) o.Type # Test if such a voicemail exists. return o
python
def Voicemail(self, Id): """Queries the voicemail object. :Parameters: Id : int Voicemail Id. :return: A voicemail object. :rtype: `Voicemail` """ o = Voicemail(self, Id) o.Type # Test if such a voicemail exists. return o
[ "def", "Voicemail", "(", "self", ",", "Id", ")", ":", "o", "=", "Voicemail", "(", "self", ",", "Id", ")", "o", ".", "Type", "# Test if such a voicemail exists.", "return", "o" ]
Queries the voicemail object. :Parameters: Id : int Voicemail Id. :return: A voicemail object. :rtype: `Voicemail`
[ "Queries", "the", "voicemail", "object", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L862-L874
Skype4Py/Skype4Py
Skype4Py/application.py
Application.Connect
def Connect(self, Username, WaitConnected=False): """Connects application to user. :Parameters: Username : str Name of the user to connect to. WaitConnected : bool If True, causes the method to wait until the connection is established. :return: If ``WaitConnected`` is True, returns the stream which can be used to send the data. Otherwise returns None. :rtype: `ApplicationStream` or None """ if WaitConnected: self._Connect_Event = threading.Event() self._Connect_Stream = [None] self._Connect_Username = Username self._Connect_ApplicationStreams(self, self.Streams) self._Owner.RegisterEventHandler('ApplicationStreams', self._Connect_ApplicationStreams) self._Alter('CONNECT', Username) self._Connect_Event.wait() self._Owner.UnregisterEventHandler('ApplicationStreams', self._Connect_ApplicationStreams) try: return self._Connect_Stream[0] finally: del self._Connect_Stream, self._Connect_Event, self._Connect_Username else: self._Alter('CONNECT', Username)
python
def Connect(self, Username, WaitConnected=False): """Connects application to user. :Parameters: Username : str Name of the user to connect to. WaitConnected : bool If True, causes the method to wait until the connection is established. :return: If ``WaitConnected`` is True, returns the stream which can be used to send the data. Otherwise returns None. :rtype: `ApplicationStream` or None """ if WaitConnected: self._Connect_Event = threading.Event() self._Connect_Stream = [None] self._Connect_Username = Username self._Connect_ApplicationStreams(self, self.Streams) self._Owner.RegisterEventHandler('ApplicationStreams', self._Connect_ApplicationStreams) self._Alter('CONNECT', Username) self._Connect_Event.wait() self._Owner.UnregisterEventHandler('ApplicationStreams', self._Connect_ApplicationStreams) try: return self._Connect_Stream[0] finally: del self._Connect_Stream, self._Connect_Event, self._Connect_Username else: self._Alter('CONNECT', Username)
[ "def", "Connect", "(", "self", ",", "Username", ",", "WaitConnected", "=", "False", ")", ":", "if", "WaitConnected", ":", "self", ".", "_Connect_Event", "=", "threading", ".", "Event", "(", ")", "self", ".", "_Connect_Stream", "=", "[", "None", "]", "self", ".", "_Connect_Username", "=", "Username", "self", ".", "_Connect_ApplicationStreams", "(", "self", ",", "self", ".", "Streams", ")", "self", ".", "_Owner", ".", "RegisterEventHandler", "(", "'ApplicationStreams'", ",", "self", ".", "_Connect_ApplicationStreams", ")", "self", ".", "_Alter", "(", "'CONNECT'", ",", "Username", ")", "self", ".", "_Connect_Event", ".", "wait", "(", ")", "self", ".", "_Owner", ".", "UnregisterEventHandler", "(", "'ApplicationStreams'", ",", "self", ".", "_Connect_ApplicationStreams", ")", "try", ":", "return", "self", ".", "_Connect_Stream", "[", "0", "]", "finally", ":", "del", "self", ".", "_Connect_Stream", ",", "self", ".", "_Connect_Event", ",", "self", ".", "_Connect_Username", "else", ":", "self", ".", "_Alter", "(", "'CONNECT'", ",", "Username", ")" ]
Connects application to user. :Parameters: Username : str Name of the user to connect to. WaitConnected : bool If True, causes the method to wait until the connection is established. :return: If ``WaitConnected`` is True, returns the stream which can be used to send the data. Otherwise returns None. :rtype: `ApplicationStream` or None
[ "Connects", "application", "to", "user", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/application.py#L36-L63
Skype4Py/Skype4Py
Skype4Py/application.py
Application.SendDatagram
def SendDatagram(self, Text, Streams=None): """Sends datagram to application streams. :Parameters: Text : unicode Text to send. Streams : sequence of `ApplicationStream` Streams to send the datagram to or None if all currently connected streams should be used. """ if Streams is None: Streams = self.Streams for s in Streams: s.SendDatagram(Text)
python
def SendDatagram(self, Text, Streams=None): """Sends datagram to application streams. :Parameters: Text : unicode Text to send. Streams : sequence of `ApplicationStream` Streams to send the datagram to or None if all currently connected streams should be used. """ if Streams is None: Streams = self.Streams for s in Streams: s.SendDatagram(Text)
[ "def", "SendDatagram", "(", "self", ",", "Text", ",", "Streams", "=", "None", ")", ":", "if", "Streams", "is", "None", ":", "Streams", "=", "self", ".", "Streams", "for", "s", "in", "Streams", ":", "s", ".", "SendDatagram", "(", "Text", ")" ]
Sends datagram to application streams. :Parameters: Text : unicode Text to send. Streams : sequence of `ApplicationStream` Streams to send the datagram to or None if all currently connected streams should be used.
[ "Sends", "datagram", "to", "application", "streams", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/application.py#L75-L88
Skype4Py/Skype4Py
Skype4Py/application.py
ApplicationStream.SendDatagram
def SendDatagram(self, Text): """Sends datagram to stream. :Parameters: Text : unicode Datagram to send. """ self.Application._Alter('DATAGRAM', '%s %s' % (self.Handle, tounicode(Text)))
python
def SendDatagram(self, Text): """Sends datagram to stream. :Parameters: Text : unicode Datagram to send. """ self.Application._Alter('DATAGRAM', '%s %s' % (self.Handle, tounicode(Text)))
[ "def", "SendDatagram", "(", "self", ",", "Text", ")", ":", "self", ".", "Application", ".", "_Alter", "(", "'DATAGRAM'", ",", "'%s %s'", "%", "(", "self", ".", "Handle", ",", "tounicode", "(", "Text", ")", ")", ")" ]
Sends datagram to stream. :Parameters: Text : unicode Datagram to send.
[ "Sends", "datagram", "to", "stream", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/application.py#L173-L180
Skype4Py/Skype4Py
Skype4Py/application.py
ApplicationStream.Write
def Write(self, Text): """Writes data to stream. :Parameters: Text : unicode Data to send. """ self.Application._Alter('WRITE', '%s %s' % (self.Handle, tounicode(Text)))
python
def Write(self, Text): """Writes data to stream. :Parameters: Text : unicode Data to send. """ self.Application._Alter('WRITE', '%s %s' % (self.Handle, tounicode(Text)))
[ "def", "Write", "(", "self", ",", "Text", ")", ":", "self", ".", "Application", ".", "_Alter", "(", "'WRITE'", ",", "'%s %s'", "%", "(", "self", ".", "Handle", ",", "tounicode", "(", "Text", ")", ")", ")" ]
Writes data to stream. :Parameters: Text : unicode Data to send.
[ "Writes", "data", "to", "stream", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/application.py#L182-L189
Skype4Py/Skype4Py
Skype4Py/client.py
Client.CreateEvent
def CreateEvent(self, EventId, Caption, Hint): """Creates a custom event displayed in Skype client's events pane. :Parameters: EventId : unicode Unique identifier for the event. Caption : unicode Caption text. Hint : unicode Hint text. Shown when mouse hoovers over the event. :return: Event object. :rtype: `PluginEvent` """ self._Skype._DoCommand('CREATE EVENT %s CAPTION %s HINT %s' % (tounicode(EventId), quote(tounicode(Caption)), quote(tounicode(Hint)))) return PluginEvent(self._Skype, EventId)
python
def CreateEvent(self, EventId, Caption, Hint): """Creates a custom event displayed in Skype client's events pane. :Parameters: EventId : unicode Unique identifier for the event. Caption : unicode Caption text. Hint : unicode Hint text. Shown when mouse hoovers over the event. :return: Event object. :rtype: `PluginEvent` """ self._Skype._DoCommand('CREATE EVENT %s CAPTION %s HINT %s' % (tounicode(EventId), quote(tounicode(Caption)), quote(tounicode(Hint)))) return PluginEvent(self._Skype, EventId)
[ "def", "CreateEvent", "(", "self", ",", "EventId", ",", "Caption", ",", "Hint", ")", ":", "self", ".", "_Skype", ".", "_DoCommand", "(", "'CREATE EVENT %s CAPTION %s HINT %s'", "%", "(", "tounicode", "(", "EventId", ")", ",", "quote", "(", "tounicode", "(", "Caption", ")", ")", ",", "quote", "(", "tounicode", "(", "Hint", ")", ")", ")", ")", "return", "PluginEvent", "(", "self", ".", "_Skype", ",", "EventId", ")" ]
Creates a custom event displayed in Skype client's events pane. :Parameters: EventId : unicode Unique identifier for the event. Caption : unicode Caption text. Hint : unicode Hint text. Shown when mouse hoovers over the event. :return: Event object. :rtype: `PluginEvent`
[ "Creates", "a", "custom", "event", "displayed", "in", "Skype", "client", "s", "events", "pane", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/client.py#L44-L60
Skype4Py/Skype4Py
Skype4Py/client.py
Client.CreateMenuItem
def CreateMenuItem(self, MenuItemId, PluginContext, CaptionText, HintText=u'', IconPath='', Enabled=True, ContactType=pluginContactTypeAll, MultipleContacts=False): """Creates custom menu item in Skype client's "Do More" menus. :Parameters: MenuItemId : unicode Unique identifier for the menu item. PluginContext : `enums`.pluginContext* Menu item context. Allows to choose in which client windows will the menu item appear. CaptionText : unicode Caption text. HintText : unicode Hint text (optional). Shown when mouse hoovers over the menu item. IconPath : unicode Path to the icon (optional). Enabled : bool Initial state of the menu item. True by default. ContactType : `enums`.pluginContactType* In case of `enums.pluginContextContact` tells which contacts the menu item should appear for. Defaults to `enums.pluginContactTypeAll`. MultipleContacts : bool Set to True if multiple contacts should be allowed (defaults to False). :return: Menu item object. :rtype: `PluginMenuItem` """ cmd = 'CREATE MENU_ITEM %s CONTEXT %s CAPTION %s ENABLED %s' % (tounicode(MenuItemId), PluginContext, quote(tounicode(CaptionText)), cndexp(Enabled, 'true', 'false')) if HintText: cmd += ' HINT %s' % quote(tounicode(HintText)) if IconPath: cmd += ' ICON %s' % quote(path2unicode(IconPath)) if MultipleContacts: cmd += ' ENABLE_MULTIPLE_CONTACTS true' if PluginContext == pluginContextContact: cmd += ' CONTACT_TYPE_FILTER %s' % ContactType self._Skype._DoCommand(cmd) return PluginMenuItem(self._Skype, MenuItemId, CaptionText, HintText, Enabled)
python
def CreateMenuItem(self, MenuItemId, PluginContext, CaptionText, HintText=u'', IconPath='', Enabled=True, ContactType=pluginContactTypeAll, MultipleContacts=False): """Creates custom menu item in Skype client's "Do More" menus. :Parameters: MenuItemId : unicode Unique identifier for the menu item. PluginContext : `enums`.pluginContext* Menu item context. Allows to choose in which client windows will the menu item appear. CaptionText : unicode Caption text. HintText : unicode Hint text (optional). Shown when mouse hoovers over the menu item. IconPath : unicode Path to the icon (optional). Enabled : bool Initial state of the menu item. True by default. ContactType : `enums`.pluginContactType* In case of `enums.pluginContextContact` tells which contacts the menu item should appear for. Defaults to `enums.pluginContactTypeAll`. MultipleContacts : bool Set to True if multiple contacts should be allowed (defaults to False). :return: Menu item object. :rtype: `PluginMenuItem` """ cmd = 'CREATE MENU_ITEM %s CONTEXT %s CAPTION %s ENABLED %s' % (tounicode(MenuItemId), PluginContext, quote(tounicode(CaptionText)), cndexp(Enabled, 'true', 'false')) if HintText: cmd += ' HINT %s' % quote(tounicode(HintText)) if IconPath: cmd += ' ICON %s' % quote(path2unicode(IconPath)) if MultipleContacts: cmd += ' ENABLE_MULTIPLE_CONTACTS true' if PluginContext == pluginContextContact: cmd += ' CONTACT_TYPE_FILTER %s' % ContactType self._Skype._DoCommand(cmd) return PluginMenuItem(self._Skype, MenuItemId, CaptionText, HintText, Enabled)
[ "def", "CreateMenuItem", "(", "self", ",", "MenuItemId", ",", "PluginContext", ",", "CaptionText", ",", "HintText", "=", "u''", ",", "IconPath", "=", "''", ",", "Enabled", "=", "True", ",", "ContactType", "=", "pluginContactTypeAll", ",", "MultipleContacts", "=", "False", ")", ":", "cmd", "=", "'CREATE MENU_ITEM %s CONTEXT %s CAPTION %s ENABLED %s'", "%", "(", "tounicode", "(", "MenuItemId", ")", ",", "PluginContext", ",", "quote", "(", "tounicode", "(", "CaptionText", ")", ")", ",", "cndexp", "(", "Enabled", ",", "'true'", ",", "'false'", ")", ")", "if", "HintText", ":", "cmd", "+=", "' HINT %s'", "%", "quote", "(", "tounicode", "(", "HintText", ")", ")", "if", "IconPath", ":", "cmd", "+=", "' ICON %s'", "%", "quote", "(", "path2unicode", "(", "IconPath", ")", ")", "if", "MultipleContacts", ":", "cmd", "+=", "' ENABLE_MULTIPLE_CONTACTS true'", "if", "PluginContext", "==", "pluginContextContact", ":", "cmd", "+=", "' CONTACT_TYPE_FILTER %s'", "%", "ContactType", "self", ".", "_Skype", ".", "_DoCommand", "(", "cmd", ")", "return", "PluginMenuItem", "(", "self", ".", "_Skype", ",", "MenuItemId", ",", "CaptionText", ",", "HintText", ",", "Enabled", ")" ]
Creates custom menu item in Skype client's "Do More" menus. :Parameters: MenuItemId : unicode Unique identifier for the menu item. PluginContext : `enums`.pluginContext* Menu item context. Allows to choose in which client windows will the menu item appear. CaptionText : unicode Caption text. HintText : unicode Hint text (optional). Shown when mouse hoovers over the menu item. IconPath : unicode Path to the icon (optional). Enabled : bool Initial state of the menu item. True by default. ContactType : `enums`.pluginContactType* In case of `enums.pluginContextContact` tells which contacts the menu item should appear for. Defaults to `enums.pluginContactTypeAll`. MultipleContacts : bool Set to True if multiple contacts should be allowed (defaults to False). :return: Menu item object. :rtype: `PluginMenuItem`
[ "Creates", "custom", "menu", "item", "in", "Skype", "client", "s", "Do", "More", "menus", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/client.py#L62-L99
Skype4Py/Skype4Py
Skype4Py/client.py
Client.Focus
def Focus(self): """Brings the client window into focus. """ self._Skype._Api.allow_focus(self._Skype.Timeout) self._Skype._DoCommand('FOCUS')
python
def Focus(self): """Brings the client window into focus. """ self._Skype._Api.allow_focus(self._Skype.Timeout) self._Skype._DoCommand('FOCUS')
[ "def", "Focus", "(", "self", ")", ":", "self", ".", "_Skype", ".", "_Api", ".", "allow_focus", "(", "self", ".", "_Skype", ".", "Timeout", ")", "self", ".", "_Skype", ".", "_DoCommand", "(", "'FOCUS'", ")" ]
Brings the client window into focus.
[ "Brings", "the", "client", "window", "into", "focus", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/client.py#L101-L105
Skype4Py/Skype4Py
Skype4Py/client.py
Client.OpenDialog
def OpenDialog(self, Name, *Params): """Open dialog. Use this method to open dialogs added in newer Skype versions if there is no dedicated method in Skype4Py. :Parameters: Name : str Dialog name. Params : unicode One or more optional parameters. """ self._Skype._Api.allow_focus(self._Skype.Timeout) params = filter(None, (str(Name),) + Params) self._Skype._DoCommand('OPEN %s' % tounicode(' '.join(params)))
python
def OpenDialog(self, Name, *Params): """Open dialog. Use this method to open dialogs added in newer Skype versions if there is no dedicated method in Skype4Py. :Parameters: Name : str Dialog name. Params : unicode One or more optional parameters. """ self._Skype._Api.allow_focus(self._Skype.Timeout) params = filter(None, (str(Name),) + Params) self._Skype._DoCommand('OPEN %s' % tounicode(' '.join(params)))
[ "def", "OpenDialog", "(", "self", ",", "Name", ",", "*", "Params", ")", ":", "self", ".", "_Skype", ".", "_Api", ".", "allow_focus", "(", "self", ".", "_Skype", ".", "Timeout", ")", "params", "=", "filter", "(", "None", ",", "(", "str", "(", "Name", ")", ",", ")", "+", "Params", ")", "self", ".", "_Skype", ".", "_DoCommand", "(", "'OPEN %s'", "%", "tounicode", "(", "' '", ".", "join", "(", "params", ")", ")", ")" ]
Open dialog. Use this method to open dialogs added in newer Skype versions if there is no dedicated method in Skype4Py. :Parameters: Name : str Dialog name. Params : unicode One or more optional parameters.
[ "Open", "dialog", ".", "Use", "this", "method", "to", "open", "dialogs", "added", "in", "newer", "Skype", "versions", "if", "there", "is", "no", "dedicated", "method", "in", "Skype4Py", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/client.py#L150-L162
Skype4Py/Skype4Py
Skype4Py/client.py
Client.OpenMessageDialog
def OpenMessageDialog(self, Username, Text=u''): """Opens "Send an IM Message" dialog. :Parameters: Username : str Message target. Text : unicode Message text. """ self.OpenDialog('IM', Username, tounicode(Text))
python
def OpenMessageDialog(self, Username, Text=u''): """Opens "Send an IM Message" dialog. :Parameters: Username : str Message target. Text : unicode Message text. """ self.OpenDialog('IM', Username, tounicode(Text))
[ "def", "OpenMessageDialog", "(", "self", ",", "Username", ",", "Text", "=", "u''", ")", ":", "self", ".", "OpenDialog", "(", "'IM'", ",", "Username", ",", "tounicode", "(", "Text", ")", ")" ]
Opens "Send an IM Message" dialog. :Parameters: Username : str Message target. Text : unicode Message text.
[ "Opens", "Send", "an", "IM", "Message", "dialog", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/client.py#L195-L204
Skype4Py/Skype4Py
Skype4Py/client.py
Client.Start
def Start(self, Minimized=False, Nosplash=False): """Starts Skype application. :Parameters: Minimized : bool If True, Skype is started minimized in system tray. Nosplash : bool If True, no splash screen is displayed upon startup. """ self._Skype._Api.startup(Minimized, Nosplash)
python
def Start(self, Minimized=False, Nosplash=False): """Starts Skype application. :Parameters: Minimized : bool If True, Skype is started minimized in system tray. Nosplash : bool If True, no splash screen is displayed upon startup. """ self._Skype._Api.startup(Minimized, Nosplash)
[ "def", "Start", "(", "self", ",", "Minimized", "=", "False", ",", "Nosplash", "=", "False", ")", ":", "self", ".", "_Skype", ".", "_Api", ".", "startup", "(", "Minimized", ",", "Nosplash", ")" ]
Starts Skype application. :Parameters: Minimized : bool If True, Skype is started minimized in system tray. Nosplash : bool If True, no splash screen is displayed upon startup.
[ "Starts", "Skype", "application", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/client.py#L264-L273
Skype4Py/Skype4Py
Skype4Py/api/darwin.py
SkypeAPI.start
def start(self): """ Start the thread associated with this API object. Ensure that the call is made no more than once, to avoid raising a RuntimeError. """ if not self.thread_started: super(SkypeAPI, self).start() self.thread_started = True
python
def start(self): """ Start the thread associated with this API object. Ensure that the call is made no more than once, to avoid raising a RuntimeError. """ if not self.thread_started: super(SkypeAPI, self).start() self.thread_started = True
[ "def", "start", "(", "self", ")", ":", "if", "not", "self", ".", "thread_started", ":", "super", "(", "SkypeAPI", ",", "self", ")", ".", "start", "(", ")", "self", ".", "thread_started", "=", "True" ]
Start the thread associated with this API object. Ensure that the call is made no more than once, to avoid raising a RuntimeError.
[ "Start", "the", "thread", "associated", "with", "this", "API", "object", ".", "Ensure", "that", "the", "call", "is", "made", "no", "more", "than", "once", "to", "avoid", "raising", "a", "RuntimeError", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/api/darwin.py#L302-L310
Skype4Py/Skype4Py
Skype4Py/api/posix_x11.py
threads_init
def threads_init(gtk=True): """Enables multithreading support in Xlib and PyGTK. See the module docstring for more info. :Parameters: gtk : bool May be set to False to skip the PyGTK module. """ # enable X11 multithreading x11.XInitThreads() if gtk: from gtk.gdk import threads_init threads_init()
python
def threads_init(gtk=True): """Enables multithreading support in Xlib and PyGTK. See the module docstring for more info. :Parameters: gtk : bool May be set to False to skip the PyGTK module. """ # enable X11 multithreading x11.XInitThreads() if gtk: from gtk.gdk import threads_init threads_init()
[ "def", "threads_init", "(", "gtk", "=", "True", ")", ":", "# enable X11 multithreading", "x11", ".", "XInitThreads", "(", ")", "if", "gtk", ":", "from", "gtk", ".", "gdk", "import", "threads_init", "threads_init", "(", ")" ]
Enables multithreading support in Xlib and PyGTK. See the module docstring for more info. :Parameters: gtk : bool May be set to False to skip the PyGTK module.
[ "Enables", "multithreading", "support", "in", "Xlib", "and", "PyGTK", ".", "See", "the", "module", "docstring", "for", "more", "info", ".", ":", "Parameters", ":", "gtk", ":", "bool", "May", "be", "set", "to", "False", "to", "skip", "the", "PyGTK", "module", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/api/posix_x11.py#L227-L239
Skype4Py/Skype4Py
Skype4Py/api/posix_x11.py
SkypeAPI.get_skype
def get_skype(self): """Returns Skype window ID or None if Skype not running.""" skype_inst = x11.XInternAtom(self.disp, '_SKYPE_INSTANCE', True) if not skype_inst: return type_ret = Atom() format_ret = c_int() nitems_ret = c_ulong() bytes_after_ret = c_ulong() winp = pointer(Window()) fail = x11.XGetWindowProperty(self.disp, self.win_root, skype_inst, 0, 1, False, 33, byref(type_ret), byref(format_ret), byref(nitems_ret), byref(bytes_after_ret), byref(winp)) if not fail and format_ret.value == 32 and nitems_ret.value == 1: return winp.contents.value
python
def get_skype(self): """Returns Skype window ID or None if Skype not running.""" skype_inst = x11.XInternAtom(self.disp, '_SKYPE_INSTANCE', True) if not skype_inst: return type_ret = Atom() format_ret = c_int() nitems_ret = c_ulong() bytes_after_ret = c_ulong() winp = pointer(Window()) fail = x11.XGetWindowProperty(self.disp, self.win_root, skype_inst, 0, 1, False, 33, byref(type_ret), byref(format_ret), byref(nitems_ret), byref(bytes_after_ret), byref(winp)) if not fail and format_ret.value == 32 and nitems_ret.value == 1: return winp.contents.value
[ "def", "get_skype", "(", "self", ")", ":", "skype_inst", "=", "x11", ".", "XInternAtom", "(", "self", ".", "disp", ",", "'_SKYPE_INSTANCE'", ",", "True", ")", "if", "not", "skype_inst", ":", "return", "type_ret", "=", "Atom", "(", ")", "format_ret", "=", "c_int", "(", ")", "nitems_ret", "=", "c_ulong", "(", ")", "bytes_after_ret", "=", "c_ulong", "(", ")", "winp", "=", "pointer", "(", "Window", "(", ")", ")", "fail", "=", "x11", ".", "XGetWindowProperty", "(", "self", ".", "disp", ",", "self", ".", "win_root", ",", "skype_inst", ",", "0", ",", "1", ",", "False", ",", "33", ",", "byref", "(", "type_ret", ")", ",", "byref", "(", "format_ret", ")", ",", "byref", "(", "nitems_ret", ")", ",", "byref", "(", "bytes_after_ret", ")", ",", "byref", "(", "winp", ")", ")", "if", "not", "fail", "and", "format_ret", ".", "value", "==", "32", "and", "nitems_ret", ".", "value", "==", "1", ":", "return", "winp", ".", "contents", ".", "value" ]
Returns Skype window ID or None if Skype not running.
[ "Returns", "Skype", "window", "ID", "or", "None", "if", "Skype", "not", "running", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/api/posix_x11.py#L323-L337
Skype4Py/Skype4Py
Skype4Py/call.py
Call.Join
def Join(self, Id): """Joins with another call to form a conference. :Parameters: Id : int Call Id of the other call to join to the conference. :return: Conference object. :rtype: `Conference` """ #self._Alter('JOIN_CONFERENCE', Id) reply = self._Owner._DoCommand('SET CALL %s JOIN_CONFERENCE %s' % (self.Id, Id), 'CALL %s CONF_ID' % self.Id) return Conference(self._Owner, reply.split()[-1])
python
def Join(self, Id): """Joins with another call to form a conference. :Parameters: Id : int Call Id of the other call to join to the conference. :return: Conference object. :rtype: `Conference` """ #self._Alter('JOIN_CONFERENCE', Id) reply = self._Owner._DoCommand('SET CALL %s JOIN_CONFERENCE %s' % (self.Id, Id), 'CALL %s CONF_ID' % self.Id) return Conference(self._Owner, reply.split()[-1])
[ "def", "Join", "(", "self", ",", "Id", ")", ":", "#self._Alter('JOIN_CONFERENCE', Id)", "reply", "=", "self", ".", "_Owner", ".", "_DoCommand", "(", "'SET CALL %s JOIN_CONFERENCE %s'", "%", "(", "self", ".", "Id", ",", "Id", ")", ",", "'CALL %s CONF_ID'", "%", "self", ".", "Id", ")", "return", "Conference", "(", "self", ".", "_Owner", ",", "reply", ".", "split", "(", ")", "[", "-", "1", "]", ")" ]
Joins with another call to form a conference. :Parameters: Id : int Call Id of the other call to join to the conference. :return: Conference object. :rtype: `Conference`
[ "Joins", "with", "another", "call", "to", "form", "a", "conference", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/call.py#L175-L188
Skype4Py/Skype4Py
Skype4Py/settings.py
Settings.Avatar
def Avatar(self, Id=1, Set=None): """Sets user avatar picture from file. :Parameters: Id : int Optional avatar Id. Set : str New avatar file name. :deprecated: Use `LoadAvatarFromFile` instead. """ from warnings import warn warn('Settings.Avatar: Use Settings.LoadAvatarFromFile instead.', DeprecationWarning, stacklevel=2) if Set is None: raise TypeError('Argument \'Set\' is mandatory!') self.LoadAvatarFromFile(Set, Id)
python
def Avatar(self, Id=1, Set=None): """Sets user avatar picture from file. :Parameters: Id : int Optional avatar Id. Set : str New avatar file name. :deprecated: Use `LoadAvatarFromFile` instead. """ from warnings import warn warn('Settings.Avatar: Use Settings.LoadAvatarFromFile instead.', DeprecationWarning, stacklevel=2) if Set is None: raise TypeError('Argument \'Set\' is mandatory!') self.LoadAvatarFromFile(Set, Id)
[ "def", "Avatar", "(", "self", ",", "Id", "=", "1", ",", "Set", "=", "None", ")", ":", "from", "warnings", "import", "warn", "warn", "(", "'Settings.Avatar: Use Settings.LoadAvatarFromFile instead.'", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "if", "Set", "is", "None", ":", "raise", "TypeError", "(", "'Argument \\'Set\\' is mandatory!'", ")", "self", ".", "LoadAvatarFromFile", "(", "Set", ",", "Id", ")" ]
Sets user avatar picture from file. :Parameters: Id : int Optional avatar Id. Set : str New avatar file name. :deprecated: Use `LoadAvatarFromFile` instead.
[ "Sets", "user", "avatar", "picture", "from", "file", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/settings.py#L25-L40
Skype4Py/Skype4Py
Skype4Py/settings.py
Settings.LoadAvatarFromFile
def LoadAvatarFromFile(self, Filename, AvatarId=1): """Loads user avatar picture from file. :Parameters: Filename : str Name of the avatar file. AvatarId : int Optional avatar Id. """ s = 'AVATAR %s %s' % (AvatarId, path2unicode(Filename)) self._Skype._DoCommand('SET %s' % s, s)
python
def LoadAvatarFromFile(self, Filename, AvatarId=1): """Loads user avatar picture from file. :Parameters: Filename : str Name of the avatar file. AvatarId : int Optional avatar Id. """ s = 'AVATAR %s %s' % (AvatarId, path2unicode(Filename)) self._Skype._DoCommand('SET %s' % s, s)
[ "def", "LoadAvatarFromFile", "(", "self", ",", "Filename", ",", "AvatarId", "=", "1", ")", ":", "s", "=", "'AVATAR %s %s'", "%", "(", "AvatarId", ",", "path2unicode", "(", "Filename", ")", ")", "self", ".", "_Skype", ".", "_DoCommand", "(", "'SET %s'", "%", "s", ",", "s", ")" ]
Loads user avatar picture from file. :Parameters: Filename : str Name of the avatar file. AvatarId : int Optional avatar Id.
[ "Loads", "user", "avatar", "picture", "from", "file", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/settings.py#L42-L52
Skype4Py/Skype4Py
Skype4Py/settings.py
Settings.RingTone
def RingTone(self, Id=1, Set=None): """Returns/sets a ringtone. :Parameters: Id : int Ringtone Id Set : str Path to new ringtone or None if the current path should be queried. :return: Current path if Set=None, None otherwise. :rtype: str or None """ if Set is None: return unicode2path(self._Skype._Property('RINGTONE', Id, '')) self._Skype._Property('RINGTONE', Id, '', path2unicode(Set))
python
def RingTone(self, Id=1, Set=None): """Returns/sets a ringtone. :Parameters: Id : int Ringtone Id Set : str Path to new ringtone or None if the current path should be queried. :return: Current path if Set=None, None otherwise. :rtype: str or None """ if Set is None: return unicode2path(self._Skype._Property('RINGTONE', Id, '')) self._Skype._Property('RINGTONE', Id, '', path2unicode(Set))
[ "def", "RingTone", "(", "self", ",", "Id", "=", "1", ",", "Set", "=", "None", ")", ":", "if", "Set", "is", "None", ":", "return", "unicode2path", "(", "self", ".", "_Skype", ".", "_Property", "(", "'RINGTONE'", ",", "Id", ",", "''", ")", ")", "self", ".", "_Skype", ".", "_Property", "(", "'RINGTONE'", ",", "Id", ",", "''", ",", "path2unicode", "(", "Set", ")", ")" ]
Returns/sets a ringtone. :Parameters: Id : int Ringtone Id Set : str Path to new ringtone or None if the current path should be queried. :return: Current path if Set=None, None otherwise. :rtype: str or None
[ "Returns", "/", "sets", "a", "ringtone", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/settings.py#L59-L73
Skype4Py/Skype4Py
Skype4Py/settings.py
Settings.RingToneStatus
def RingToneStatus(self, Id=1, Set=None): """Enables/disables a ringtone. :Parameters: Id : int Ringtone Id Set : bool True/False if the ringtone should be enabled/disabled or None if the current status should be queried. :return: Current status if Set=None, None otherwise. :rtype: bool """ if Set is None: return (self._Skype._Property('RINGTONE', Id, 'STATUS') == 'ON') self._Skype._Property('RINGTONE', Id, 'STATUS', cndexp(Set, 'ON', 'OFF'))
python
def RingToneStatus(self, Id=1, Set=None): """Enables/disables a ringtone. :Parameters: Id : int Ringtone Id Set : bool True/False if the ringtone should be enabled/disabled or None if the current status should be queried. :return: Current status if Set=None, None otherwise. :rtype: bool """ if Set is None: return (self._Skype._Property('RINGTONE', Id, 'STATUS') == 'ON') self._Skype._Property('RINGTONE', Id, 'STATUS', cndexp(Set, 'ON', 'OFF'))
[ "def", "RingToneStatus", "(", "self", ",", "Id", "=", "1", ",", "Set", "=", "None", ")", ":", "if", "Set", "is", "None", ":", "return", "(", "self", ".", "_Skype", ".", "_Property", "(", "'RINGTONE'", ",", "Id", ",", "'STATUS'", ")", "==", "'ON'", ")", "self", ".", "_Skype", ".", "_Property", "(", "'RINGTONE'", ",", "Id", ",", "'STATUS'", ",", "cndexp", "(", "Set", ",", "'ON'", ",", "'OFF'", ")", ")" ]
Enables/disables a ringtone. :Parameters: Id : int Ringtone Id Set : bool True/False if the ringtone should be enabled/disabled or None if the current status should be queried. :return: Current status if Set=None, None otherwise. :rtype: bool
[ "Enables", "/", "disables", "a", "ringtone", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/settings.py#L75-L90
Skype4Py/Skype4Py
Skype4Py/settings.py
Settings.SaveAvatarToFile
def SaveAvatarToFile(self, Filename, AvatarId=1): """Saves user avatar picture to file. :Parameters: Filename : str Destination path. AvatarId : int Avatar Id """ s = 'AVATAR %s %s' % (AvatarId, path2unicode(Filename)) self._Skype._DoCommand('GET %s' % s, s)
python
def SaveAvatarToFile(self, Filename, AvatarId=1): """Saves user avatar picture to file. :Parameters: Filename : str Destination path. AvatarId : int Avatar Id """ s = 'AVATAR %s %s' % (AvatarId, path2unicode(Filename)) self._Skype._DoCommand('GET %s' % s, s)
[ "def", "SaveAvatarToFile", "(", "self", ",", "Filename", ",", "AvatarId", "=", "1", ")", ":", "s", "=", "'AVATAR %s %s'", "%", "(", "AvatarId", ",", "path2unicode", "(", "Filename", ")", ")", "self", ".", "_Skype", ".", "_DoCommand", "(", "'GET %s'", "%", "s", ",", "s", ")" ]
Saves user avatar picture to file. :Parameters: Filename : str Destination path. AvatarId : int Avatar Id
[ "Saves", "user", "avatar", "picture", "to", "file", "." ]
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/settings.py#L92-L102