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 listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
biocore/burrito-fillings | bfillings/infernal.py | Cmalign._tempfile_as_multiline_string | def _tempfile_as_multiline_string(self, data):
"""Write a multiline string to a temp file and return the filename.
data: a multiline string to be written to a file.
* Note: the result will be the filename as a FilePath object
(which is a string subclass).
"""
filename = FilePath(self.getTmpFilename(self.TmpDir))
data_file = open(filename,'w')
data_file.write(data)
data_file.close()
return filename | python | def _tempfile_as_multiline_string(self, data):
"""Write a multiline string to a temp file and return the filename.
data: a multiline string to be written to a file.
* Note: the result will be the filename as a FilePath object
(which is a string subclass).
"""
filename = FilePath(self.getTmpFilename(self.TmpDir))
data_file = open(filename,'w')
data_file.write(data)
data_file.close()
return filename | [
"def",
"_tempfile_as_multiline_string",
"(",
"self",
",",
"data",
")",
":",
"filename",
"=",
"FilePath",
"(",
"self",
".",
"getTmpFilename",
"(",
"self",
".",
"TmpDir",
")",
")",
"data_file",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"data_file",
".",... | Write a multiline string to a temp file and return the filename.
data: a multiline string to be written to a file.
* Note: the result will be the filename as a FilePath object
(which is a string subclass). | [
"Write",
"a",
"multiline",
"string",
"to",
"a",
"temp",
"file",
"and",
"return",
"the",
"filename",
"."
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/infernal.py#L181-L194 |
BoGoEngine/bogo-python | bogo/validation.py | is_valid_sound_tuple | def is_valid_sound_tuple(sound_tuple, final_form=True):
"""
Check if a character combination complies to Vietnamese phonology.
The basic idea is that if one can pronunce a sound_tuple then it's valid.
Sound tuples containing consonants exclusively (almost always
abbreviations) are also valid.
Input:
sound_tuple - a SoundTuple
final_form - whether the tuple represents a complete word
Output:
True if the tuple seems to be Vietnamese, False otherwise.
"""
# We only work with lower case
sound_tuple = SoundTuple._make([s.lower() for s in sound_tuple])
# Words with no vowel are always valid
# FIXME: This looks like it should be toggled by a config key.
if not sound_tuple.vowel:
result = True
elif final_form:
result = \
has_valid_consonants(sound_tuple) and \
has_valid_vowel(sound_tuple) and \
has_valid_accent(sound_tuple)
else:
result = \
has_valid_consonants(sound_tuple) and \
has_valid_vowel_non_final(sound_tuple)
return result | python | def is_valid_sound_tuple(sound_tuple, final_form=True):
"""
Check if a character combination complies to Vietnamese phonology.
The basic idea is that if one can pronunce a sound_tuple then it's valid.
Sound tuples containing consonants exclusively (almost always
abbreviations) are also valid.
Input:
sound_tuple - a SoundTuple
final_form - whether the tuple represents a complete word
Output:
True if the tuple seems to be Vietnamese, False otherwise.
"""
# We only work with lower case
sound_tuple = SoundTuple._make([s.lower() for s in sound_tuple])
# Words with no vowel are always valid
# FIXME: This looks like it should be toggled by a config key.
if not sound_tuple.vowel:
result = True
elif final_form:
result = \
has_valid_consonants(sound_tuple) and \
has_valid_vowel(sound_tuple) and \
has_valid_accent(sound_tuple)
else:
result = \
has_valid_consonants(sound_tuple) and \
has_valid_vowel_non_final(sound_tuple)
return result | [
"def",
"is_valid_sound_tuple",
"(",
"sound_tuple",
",",
"final_form",
"=",
"True",
")",
":",
"# We only work with lower case",
"sound_tuple",
"=",
"SoundTuple",
".",
"_make",
"(",
"[",
"s",
".",
"lower",
"(",
")",
"for",
"s",
"in",
"sound_tuple",
"]",
")",
"... | Check if a character combination complies to Vietnamese phonology.
The basic idea is that if one can pronunce a sound_tuple then it's valid.
Sound tuples containing consonants exclusively (almost always
abbreviations) are also valid.
Input:
sound_tuple - a SoundTuple
final_form - whether the tuple represents a complete word
Output:
True if the tuple seems to be Vietnamese, False otherwise. | [
"Check",
"if",
"a",
"character",
"combination",
"complies",
"to",
"Vietnamese",
"phonology",
".",
"The",
"basic",
"idea",
"is",
"that",
"if",
"one",
"can",
"pronunce",
"a",
"sound_tuple",
"then",
"it",
"s",
"valid",
".",
"Sound",
"tuples",
"containing",
"con... | train | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/validation.py#L84-L115 |
michaelpb/omnic | omnic/types/detectors.py | DetectorManager.detect | def detect(self, path):
'''
Guesses a TypeString from the given path
'''
typestring = UNKNOWN
for detector in self.detectors:
if typestring != UNKNOWN and not detector.can_improve(typestring):
continue
if not detector.can_detect(path):
continue
detected = detector.detect(path)
if detected:
typestring = detected
return typestring | python | def detect(self, path):
'''
Guesses a TypeString from the given path
'''
typestring = UNKNOWN
for detector in self.detectors:
if typestring != UNKNOWN and not detector.can_improve(typestring):
continue
if not detector.can_detect(path):
continue
detected = detector.detect(path)
if detected:
typestring = detected
return typestring | [
"def",
"detect",
"(",
"self",
",",
"path",
")",
":",
"typestring",
"=",
"UNKNOWN",
"for",
"detector",
"in",
"self",
".",
"detectors",
":",
"if",
"typestring",
"!=",
"UNKNOWN",
"and",
"not",
"detector",
".",
"can_improve",
"(",
"typestring",
")",
":",
"co... | Guesses a TypeString from the given path | [
"Guesses",
"a",
"TypeString",
"from",
"the",
"given",
"path"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/types/detectors.py#L26-L39 |
dailymuse/oz | oz/aws_cdn/middleware.py | CDNMiddleware.set_cache_buster | def set_cache_buster(self, path, hash):
"""Sets the cache buster value for a given file path"""
oz.aws_cdn.set_cache_buster(self.redis(), path, hash) | python | def set_cache_buster(self, path, hash):
"""Sets the cache buster value for a given file path"""
oz.aws_cdn.set_cache_buster(self.redis(), path, hash) | [
"def",
"set_cache_buster",
"(",
"self",
",",
"path",
",",
"hash",
")",
":",
"oz",
".",
"aws_cdn",
".",
"set_cache_buster",
"(",
"self",
".",
"redis",
"(",
")",
",",
"path",
",",
"hash",
")"
] | Sets the cache buster value for a given file path | [
"Sets",
"the",
"cache",
"buster",
"value",
"for",
"a",
"given",
"file",
"path"
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/aws_cdn/middleware.py#L26-L28 |
dailymuse/oz | oz/aws_cdn/middleware.py | CDNMiddleware.upload_file | def upload_file(self, path, contents, replace=False):
"""
Uplodas the file to its path with the given `content`, adding the
appropriate parent directories when needed. If the path already exists
and `replace` is `False`, the file will not be uploaded.
"""
f = self.get_file(path)
f.upload(contents, replace=replace)
self.set_cache_buster(path, f.hash()) | python | def upload_file(self, path, contents, replace=False):
"""
Uplodas the file to its path with the given `content`, adding the
appropriate parent directories when needed. If the path already exists
and `replace` is `False`, the file will not be uploaded.
"""
f = self.get_file(path)
f.upload(contents, replace=replace)
self.set_cache_buster(path, f.hash()) | [
"def",
"upload_file",
"(",
"self",
",",
"path",
",",
"contents",
",",
"replace",
"=",
"False",
")",
":",
"f",
"=",
"self",
".",
"get_file",
"(",
"path",
")",
"f",
".",
"upload",
"(",
"contents",
",",
"replace",
"=",
"replace",
")",
"self",
".",
"se... | Uplodas the file to its path with the given `content`, adding the
appropriate parent directories when needed. If the path already exists
and `replace` is `False`, the file will not be uploaded. | [
"Uplodas",
"the",
"file",
"to",
"its",
"path",
"with",
"the",
"given",
"content",
"adding",
"the",
"appropriate",
"parent",
"directories",
"when",
"needed",
".",
"If",
"the",
"path",
"already",
"exists",
"and",
"replace",
"is",
"False",
"the",
"file",
"will"... | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/aws_cdn/middleware.py#L38-L46 |
dailymuse/oz | oz/aws_cdn/middleware.py | CDNMiddleware.copy_file | def copy_file(self, from_path, to_path, replace=False):
"""
Copies a file from a given source path to a destination path, adding
appropriate parent directories when needed. If the destination path
already exists and `replace` is `False`, the file will not be
uploaded.
"""
f = self.get_file(from_path)
if f.copy(to_path, replace):
self.set_cache_buster(to_path, f.hash()) | python | def copy_file(self, from_path, to_path, replace=False):
"""
Copies a file from a given source path to a destination path, adding
appropriate parent directories when needed. If the destination path
already exists and `replace` is `False`, the file will not be
uploaded.
"""
f = self.get_file(from_path)
if f.copy(to_path, replace):
self.set_cache_buster(to_path, f.hash()) | [
"def",
"copy_file",
"(",
"self",
",",
"from_path",
",",
"to_path",
",",
"replace",
"=",
"False",
")",
":",
"f",
"=",
"self",
".",
"get_file",
"(",
"from_path",
")",
"if",
"f",
".",
"copy",
"(",
"to_path",
",",
"replace",
")",
":",
"self",
".",
"set... | Copies a file from a given source path to a destination path, adding
appropriate parent directories when needed. If the destination path
already exists and `replace` is `False`, the file will not be
uploaded. | [
"Copies",
"a",
"file",
"from",
"a",
"given",
"source",
"path",
"to",
"a",
"destination",
"path",
"adding",
"appropriate",
"parent",
"directories",
"when",
"needed",
".",
"If",
"the",
"destination",
"path",
"already",
"exists",
"and",
"replace",
"is",
"False",
... | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/aws_cdn/middleware.py#L48-L57 |
dailymuse/oz | oz/aws_cdn/middleware.py | CDNMiddleware.remove_file | def remove_file(self, path):
"""Removes the given file"""
self.get_file(path).remove()
self.remove_cache_buster(path) | python | def remove_file(self, path):
"""Removes the given file"""
self.get_file(path).remove()
self.remove_cache_buster(path) | [
"def",
"remove_file",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"get_file",
"(",
"path",
")",
".",
"remove",
"(",
")",
"self",
".",
"remove_cache_buster",
"(",
"path",
")"
] | Removes the given file | [
"Removes",
"the",
"given",
"file"
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/aws_cdn/middleware.py#L59-L62 |
biocore/burrito-fillings | bfillings/clustalw.py | alignUnalignedSeqs | def alignUnalignedSeqs(seqs,add_seq_names=True,WorkingDir=None,\
SuppressStderr=None,SuppressStdout=None):
"""Aligns unaligned sequences
seqs: either list of sequence objects or list of strings
add_seq_names: boolean. if True, sequence names are inserted in the list
of sequences. if False, it assumes seqs is a list of lines of some
proper format that the program can handle
"""
if add_seq_names:
app = Clustalw(InputHandler='_input_as_seqs',\
WorkingDir=WorkingDir,SuppressStderr=SuppressStderr,\
SuppressStdout=SuppressStdout)
else:
app = Clustalw(InputHandler='_input_as_lines',\
WorkingDir=WorkingDir,SuppressStderr=SuppressStderr,\
SuppressStdout=SuppressStdout)
return app(seqs) | python | def alignUnalignedSeqs(seqs,add_seq_names=True,WorkingDir=None,\
SuppressStderr=None,SuppressStdout=None):
"""Aligns unaligned sequences
seqs: either list of sequence objects or list of strings
add_seq_names: boolean. if True, sequence names are inserted in the list
of sequences. if False, it assumes seqs is a list of lines of some
proper format that the program can handle
"""
if add_seq_names:
app = Clustalw(InputHandler='_input_as_seqs',\
WorkingDir=WorkingDir,SuppressStderr=SuppressStderr,\
SuppressStdout=SuppressStdout)
else:
app = Clustalw(InputHandler='_input_as_lines',\
WorkingDir=WorkingDir,SuppressStderr=SuppressStderr,\
SuppressStdout=SuppressStdout)
return app(seqs) | [
"def",
"alignUnalignedSeqs",
"(",
"seqs",
",",
"add_seq_names",
"=",
"True",
",",
"WorkingDir",
"=",
"None",
",",
"SuppressStderr",
"=",
"None",
",",
"SuppressStdout",
"=",
"None",
")",
":",
"if",
"add_seq_names",
":",
"app",
"=",
"Clustalw",
"(",
"InputHand... | Aligns unaligned sequences
seqs: either list of sequence objects or list of strings
add_seq_names: boolean. if True, sequence names are inserted in the list
of sequences. if False, it assumes seqs is a list of lines of some
proper format that the program can handle | [
"Aligns",
"unaligned",
"sequences"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L351-L368 |
biocore/burrito-fillings | bfillings/clustalw.py | alignUnalignedSeqsFromFile | def alignUnalignedSeqsFromFile(filename,WorkingDir=None,SuppressStderr=None,\
SuppressStdout=None):
"""Aligns unaligned sequences from some file (file should be right format)
filename: string, the filename of the file containing the sequences
to be aligned in a valid format.
"""
app = Clustalw(WorkingDir=WorkingDir,SuppressStderr=SuppressStderr,\
SuppressStdout=SuppressStdout)
return app(filename) | python | def alignUnalignedSeqsFromFile(filename,WorkingDir=None,SuppressStderr=None,\
SuppressStdout=None):
"""Aligns unaligned sequences from some file (file should be right format)
filename: string, the filename of the file containing the sequences
to be aligned in a valid format.
"""
app = Clustalw(WorkingDir=WorkingDir,SuppressStderr=SuppressStderr,\
SuppressStdout=SuppressStdout)
return app(filename) | [
"def",
"alignUnalignedSeqsFromFile",
"(",
"filename",
",",
"WorkingDir",
"=",
"None",
",",
"SuppressStderr",
"=",
"None",
",",
"SuppressStdout",
"=",
"None",
")",
":",
"app",
"=",
"Clustalw",
"(",
"WorkingDir",
"=",
"WorkingDir",
",",
"SuppressStderr",
"=",
"S... | Aligns unaligned sequences from some file (file should be right format)
filename: string, the filename of the file containing the sequences
to be aligned in a valid format. | [
"Aligns",
"unaligned",
"sequences",
"from",
"some",
"file",
"(",
"file",
"should",
"be",
"right",
"format",
")"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L370-L379 |
biocore/burrito-fillings | bfillings/clustalw.py | alignTwoAlignments | def alignTwoAlignments(aln1,aln2,outfile,WorkingDir=None,SuppressStderr=None,\
SuppressStdout=None):
"""Aligns two alignments. Individual sequences are not realigned
aln1: string, name of file containing the first alignment
aln2: string, name of file containing the second alignment
outfile: you're forced to specify an outfile name, because if you don't
aln1 will be overwritten. So, if you want aln1 to be overwritten, you
should specify the same filename.
WARNING: a .dnd file is created with the same prefix as aln1. So an
existing dendrogram might get overwritten.
"""
app = Clustalw({'-profile':None,'-profile1':aln1,\
'-profile2':aln2,'-outfile':outfile},SuppressStderr=\
SuppressStderr,WorkingDir=WorkingDir,SuppressStdout=SuppressStdout)
app.Parameters['-align'].off()
return app() | python | def alignTwoAlignments(aln1,aln2,outfile,WorkingDir=None,SuppressStderr=None,\
SuppressStdout=None):
"""Aligns two alignments. Individual sequences are not realigned
aln1: string, name of file containing the first alignment
aln2: string, name of file containing the second alignment
outfile: you're forced to specify an outfile name, because if you don't
aln1 will be overwritten. So, if you want aln1 to be overwritten, you
should specify the same filename.
WARNING: a .dnd file is created with the same prefix as aln1. So an
existing dendrogram might get overwritten.
"""
app = Clustalw({'-profile':None,'-profile1':aln1,\
'-profile2':aln2,'-outfile':outfile},SuppressStderr=\
SuppressStderr,WorkingDir=WorkingDir,SuppressStdout=SuppressStdout)
app.Parameters['-align'].off()
return app() | [
"def",
"alignTwoAlignments",
"(",
"aln1",
",",
"aln2",
",",
"outfile",
",",
"WorkingDir",
"=",
"None",
",",
"SuppressStderr",
"=",
"None",
",",
"SuppressStdout",
"=",
"None",
")",
":",
"app",
"=",
"Clustalw",
"(",
"{",
"'-profile'",
":",
"None",
",",
"'-... | Aligns two alignments. Individual sequences are not realigned
aln1: string, name of file containing the first alignment
aln2: string, name of file containing the second alignment
outfile: you're forced to specify an outfile name, because if you don't
aln1 will be overwritten. So, if you want aln1 to be overwritten, you
should specify the same filename.
WARNING: a .dnd file is created with the same prefix as aln1. So an
existing dendrogram might get overwritten. | [
"Aligns",
"two",
"alignments",
".",
"Individual",
"sequences",
"are",
"not",
"realigned"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L381-L397 |
biocore/burrito-fillings | bfillings/clustalw.py | addSeqsToAlignment | def addSeqsToAlignment(aln1,seqs,outfile,WorkingDir=None,SuppressStderr=None,\
SuppressStdout=None):
"""Aligns sequences from second profile against first profile
aln1: string, name of file containing the alignment
seqs: string, name of file containing the sequences that should be added
to the alignment.
opoutfile: string, name of the output file (the new alignment)
"""
app = Clustalw({'-sequences':None,'-profile1':aln1,\
'-profile2':seqs,'-outfile':outfile},SuppressStderr=\
SuppressStderr,WorkingDir=WorkingDir, SuppressStdout=SuppressStdout)
app.Parameters['-align'].off()
return app() | python | def addSeqsToAlignment(aln1,seqs,outfile,WorkingDir=None,SuppressStderr=None,\
SuppressStdout=None):
"""Aligns sequences from second profile against first profile
aln1: string, name of file containing the alignment
seqs: string, name of file containing the sequences that should be added
to the alignment.
opoutfile: string, name of the output file (the new alignment)
"""
app = Clustalw({'-sequences':None,'-profile1':aln1,\
'-profile2':seqs,'-outfile':outfile},SuppressStderr=\
SuppressStderr,WorkingDir=WorkingDir, SuppressStdout=SuppressStdout)
app.Parameters['-align'].off()
return app() | [
"def",
"addSeqsToAlignment",
"(",
"aln1",
",",
"seqs",
",",
"outfile",
",",
"WorkingDir",
"=",
"None",
",",
"SuppressStderr",
"=",
"None",
",",
"SuppressStdout",
"=",
"None",
")",
":",
"app",
"=",
"Clustalw",
"(",
"{",
"'-sequences'",
":",
"None",
",",
"... | Aligns sequences from second profile against first profile
aln1: string, name of file containing the alignment
seqs: string, name of file containing the sequences that should be added
to the alignment.
opoutfile: string, name of the output file (the new alignment) | [
"Aligns",
"sequences",
"from",
"second",
"profile",
"against",
"first",
"profile"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L399-L413 |
biocore/burrito-fillings | bfillings/clustalw.py | buildTreeFromAlignment | def buildTreeFromAlignment(filename,WorkingDir=None,SuppressStderr=None):
"""Builds a new tree from an existing alignment
filename: string, name of file containing the seqs or alignment
"""
app = Clustalw({'-tree':None,'-infile':filename},SuppressStderr=\
SuppressStderr,WorkingDir=WorkingDir)
app.Parameters['-align'].off()
return app() | python | def buildTreeFromAlignment(filename,WorkingDir=None,SuppressStderr=None):
"""Builds a new tree from an existing alignment
filename: string, name of file containing the seqs or alignment
"""
app = Clustalw({'-tree':None,'-infile':filename},SuppressStderr=\
SuppressStderr,WorkingDir=WorkingDir)
app.Parameters['-align'].off()
return app() | [
"def",
"buildTreeFromAlignment",
"(",
"filename",
",",
"WorkingDir",
"=",
"None",
",",
"SuppressStderr",
"=",
"None",
")",
":",
"app",
"=",
"Clustalw",
"(",
"{",
"'-tree'",
":",
"None",
",",
"'-infile'",
":",
"filename",
"}",
",",
"SuppressStderr",
"=",
"S... | Builds a new tree from an existing alignment
filename: string, name of file containing the seqs or alignment | [
"Builds",
"a",
"new",
"tree",
"from",
"an",
"existing",
"alignment"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L415-L423 |
biocore/burrito-fillings | bfillings/clustalw.py | build_tree_from_alignment | def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params=None):
"""Returns a tree from Alignment object aln.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one.
moltype: cogent.core.moltype.MolType object
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: dict of parameters to pass in to the Clustal app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails.
"""
# Create instance of app controller, enable tree, disable alignment
app = Clustalw(InputHandler='_input_as_multiline_string', params=params, \
WorkingDir='/tmp')
app.Parameters['-align'].off()
#Set params to empty dict if None.
if params is None:
params={}
if moltype == DNA or moltype == RNA:
params['-type'] = 'd'
elif moltype == PROTEIN:
params['-type'] = 'p'
else:
raise ValueError, "moltype must be DNA, RNA, or PROTEIN"
# best_tree -> bootstrap
if best_tree:
if '-bootstrap' not in params:
app.Parameters['-bootstrap'].on(1000)
if '-seed' not in params:
app.Parameters['-seed'].on(randint(0,1000))
if '-bootlabels' not in params:
app.Parameters['-bootlabels'].on('nodes')
else:
app.Parameters['-tree'].on()
# Setup mapping. Clustalw clips identifiers. We will need to remap them.
seq_collection = SequenceCollection(aln)
int_map, int_keys = seq_collection.getIntMap()
int_map = SequenceCollection(int_map)
# Collect result
result = app(int_map.toFasta())
# Build tree
tree = DndParser(result['Tree'].read(), constructor=PhyloNode)
for node in tree.tips():
node.Name = int_keys[node.Name]
# Clean up
result.cleanUp()
del(seq_collection, app, result, int_map, int_keys)
return tree | python | def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params=None):
"""Returns a tree from Alignment object aln.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one.
moltype: cogent.core.moltype.MolType object
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: dict of parameters to pass in to the Clustal app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails.
"""
# Create instance of app controller, enable tree, disable alignment
app = Clustalw(InputHandler='_input_as_multiline_string', params=params, \
WorkingDir='/tmp')
app.Parameters['-align'].off()
#Set params to empty dict if None.
if params is None:
params={}
if moltype == DNA or moltype == RNA:
params['-type'] = 'd'
elif moltype == PROTEIN:
params['-type'] = 'p'
else:
raise ValueError, "moltype must be DNA, RNA, or PROTEIN"
# best_tree -> bootstrap
if best_tree:
if '-bootstrap' not in params:
app.Parameters['-bootstrap'].on(1000)
if '-seed' not in params:
app.Parameters['-seed'].on(randint(0,1000))
if '-bootlabels' not in params:
app.Parameters['-bootlabels'].on('nodes')
else:
app.Parameters['-tree'].on()
# Setup mapping. Clustalw clips identifiers. We will need to remap them.
seq_collection = SequenceCollection(aln)
int_map, int_keys = seq_collection.getIntMap()
int_map = SequenceCollection(int_map)
# Collect result
result = app(int_map.toFasta())
# Build tree
tree = DndParser(result['Tree'].read(), constructor=PhyloNode)
for node in tree.tips():
node.Name = int_keys[node.Name]
# Clean up
result.cleanUp()
del(seq_collection, app, result, int_map, int_keys)
return tree | [
"def",
"build_tree_from_alignment",
"(",
"aln",
",",
"moltype",
"=",
"DNA",
",",
"best_tree",
"=",
"False",
",",
"params",
"=",
"None",
")",
":",
"# Create instance of app controller, enable tree, disable alignment",
"app",
"=",
"Clustalw",
"(",
"InputHandler",
"=",
... | Returns a tree from Alignment object aln.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one.
moltype: cogent.core.moltype.MolType object
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: dict of parameters to pass in to the Clustal app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails. | [
"Returns",
"a",
"tree",
"from",
"Alignment",
"object",
"aln",
"."
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L446-L506 |
biocore/burrito-fillings | bfillings/clustalw.py | bootstrap_tree_from_alignment | def bootstrap_tree_from_alignment(aln, seed=None, num_trees=None, params=None):
"""Returns a tree from Alignment object aln with bootstrap support values.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one.
seed: an interger, seed value to use
num_trees: an integer, number of trees to bootstrap against
params: dict of parameters to pass in to the Clustal app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails.
If seed is not specifed in params, a random integer between 0-1000 is used.
"""
# Create instance of controllor, enable bootstrap, disable alignment,tree
app = Clustalw(InputHandler='_input_as_multiline_string', params=params, \
WorkingDir='/tmp')
app.Parameters['-align'].off()
app.Parameters['-tree'].off()
if app.Parameters['-bootstrap'].isOff():
if num_trees is None:
num_trees = 1000
app.Parameters['-bootstrap'].on(num_trees)
if app.Parameters['-seed'].isOff():
if seed is None:
seed = randint(0,1000)
app.Parameters['-seed'].on(seed)
if app.Parameters['-bootlabels'].isOff():
app.Parameters['-bootlabels'].on("node")
# Setup mapping. Clustalw clips identifiers. We will need to remap them.
seq_collection = SequenceCollection(aln)
int_map, int_keys = seq_collection.getIntMap()
int_map = SequenceCollection(int_map)
# Collect result
result = app(int_map.toFasta())
# Build tree
tree = DndParser(result['Tree'].read(), constructor=PhyloNode)
for node in tree.tips():
node.Name = int_keys[node.Name]
# Clean up
result.cleanUp()
del(seq_collection, app, result, int_map, int_keys)
return tree | python | def bootstrap_tree_from_alignment(aln, seed=None, num_trees=None, params=None):
"""Returns a tree from Alignment object aln with bootstrap support values.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one.
seed: an interger, seed value to use
num_trees: an integer, number of trees to bootstrap against
params: dict of parameters to pass in to the Clustal app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails.
If seed is not specifed in params, a random integer between 0-1000 is used.
"""
# Create instance of controllor, enable bootstrap, disable alignment,tree
app = Clustalw(InputHandler='_input_as_multiline_string', params=params, \
WorkingDir='/tmp')
app.Parameters['-align'].off()
app.Parameters['-tree'].off()
if app.Parameters['-bootstrap'].isOff():
if num_trees is None:
num_trees = 1000
app.Parameters['-bootstrap'].on(num_trees)
if app.Parameters['-seed'].isOff():
if seed is None:
seed = randint(0,1000)
app.Parameters['-seed'].on(seed)
if app.Parameters['-bootlabels'].isOff():
app.Parameters['-bootlabels'].on("node")
# Setup mapping. Clustalw clips identifiers. We will need to remap them.
seq_collection = SequenceCollection(aln)
int_map, int_keys = seq_collection.getIntMap()
int_map = SequenceCollection(int_map)
# Collect result
result = app(int_map.toFasta())
# Build tree
tree = DndParser(result['Tree'].read(), constructor=PhyloNode)
for node in tree.tips():
node.Name = int_keys[node.Name]
# Clean up
result.cleanUp()
del(seq_collection, app, result, int_map, int_keys)
return tree | [
"def",
"bootstrap_tree_from_alignment",
"(",
"aln",
",",
"seed",
"=",
"None",
",",
"num_trees",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"# Create instance of controllor, enable bootstrap, disable alignment,tree",
"app",
"=",
"Clustalw",
"(",
"InputHandler",
... | Returns a tree from Alignment object aln with bootstrap support values.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one.
seed: an interger, seed value to use
num_trees: an integer, number of trees to bootstrap against
params: dict of parameters to pass in to the Clustal app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails.
If seed is not specifed in params, a random integer between 0-1000 is used. | [
"Returns",
"a",
"tree",
"from",
"Alignment",
"object",
"aln",
"with",
"bootstrap",
"support",
"values",
"."
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L508-L563 |
biocore/burrito-fillings | bfillings/clustalw.py | align_unaligned_seqs | def align_unaligned_seqs(seqs, moltype=DNA, params=None):
"""Returns an Alignment object from seqs.
seqs: cogent.core.alignment.SequenceCollection object, or data that can be
used to build one.
moltype: a MolType object. DNA, RNA, or PROTEIN.
params: dict of parameters to pass in to the Clustal app controller.
Result will be a cogent.core.alignment.Alignment object.
"""
#create SequenceCollection object from seqs
seq_collection = SequenceCollection(seqs,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
int_map, int_keys = seq_collection.getIntMap()
#Create SequenceCollection from int_map.
int_map = SequenceCollection(int_map,MolType=moltype)
#Create Clustalw app.
app = Clustalw(InputHandler='_input_as_multiline_string',params=params)
#Get results using int_map as input to app
res = app(int_map.toFasta())
#Get alignment as dict out of results
alignment = dict(ClustalParser(res['Align'].readlines()))
#Make new dict mapping original IDs
new_alignment = {}
for k,v in alignment.items():
new_alignment[int_keys[k]]=v
#Create an Alignment object from alignment dict
new_alignment = Alignment(new_alignment,MolType=moltype)
#Clean up
res.cleanUp()
del(seq_collection,int_map,int_keys,app,res,alignment)
return new_alignment | python | def align_unaligned_seqs(seqs, moltype=DNA, params=None):
"""Returns an Alignment object from seqs.
seqs: cogent.core.alignment.SequenceCollection object, or data that can be
used to build one.
moltype: a MolType object. DNA, RNA, or PROTEIN.
params: dict of parameters to pass in to the Clustal app controller.
Result will be a cogent.core.alignment.Alignment object.
"""
#create SequenceCollection object from seqs
seq_collection = SequenceCollection(seqs,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
int_map, int_keys = seq_collection.getIntMap()
#Create SequenceCollection from int_map.
int_map = SequenceCollection(int_map,MolType=moltype)
#Create Clustalw app.
app = Clustalw(InputHandler='_input_as_multiline_string',params=params)
#Get results using int_map as input to app
res = app(int_map.toFasta())
#Get alignment as dict out of results
alignment = dict(ClustalParser(res['Align'].readlines()))
#Make new dict mapping original IDs
new_alignment = {}
for k,v in alignment.items():
new_alignment[int_keys[k]]=v
#Create an Alignment object from alignment dict
new_alignment = Alignment(new_alignment,MolType=moltype)
#Clean up
res.cleanUp()
del(seq_collection,int_map,int_keys,app,res,alignment)
return new_alignment | [
"def",
"align_unaligned_seqs",
"(",
"seqs",
",",
"moltype",
"=",
"DNA",
",",
"params",
"=",
"None",
")",
":",
"#create SequenceCollection object from seqs",
"seq_collection",
"=",
"SequenceCollection",
"(",
"seqs",
",",
"MolType",
"=",
"moltype",
")",
"#Create mappi... | Returns an Alignment object from seqs.
seqs: cogent.core.alignment.SequenceCollection object, or data that can be
used to build one.
moltype: a MolType object. DNA, RNA, or PROTEIN.
params: dict of parameters to pass in to the Clustal app controller.
Result will be a cogent.core.alignment.Alignment object. | [
"Returns",
"an",
"Alignment",
"object",
"from",
"seqs",
"."
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L565-L599 |
biocore/burrito-fillings | bfillings/clustalw.py | add_seqs_to_alignment | def add_seqs_to_alignment(seqs, aln, moltype, params=None):
"""Returns an Alignment object from seqs and existing Alignment.
seqs: a cogent.core.alignment.SequenceCollection object, or data that can
be used to build one.
aln: a cogent.core.alignment.Alignment object, or data that can be used to
build one
params: dict of parameters to pass in to the Clustal app controller.
"""
#create SequenceCollection object from seqs
seq_collection = SequenceCollection(seqs,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
seq_int_map, seq_int_keys = seq_collection.getIntMap()
#Create SequenceCollection from int_map.
seq_int_map = SequenceCollection(seq_int_map,MolType=moltype)
#create Alignment object from aln
aln = Alignment(aln,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
aln_int_map, aln_int_keys = aln.getIntMap(prefix='seqn_')
#Create SequenceCollection from int_map.
aln_int_map = Alignment(aln_int_map,MolType=moltype)
#Update seq_int_keys with aln_int_keys
seq_int_keys.update(aln_int_keys)
#Create Mafft app.
app = Clustalw(InputHandler='_input_as_multiline_string',\
params=params,
SuppressStderr=True)
app.Parameters['-align'].off()
app.Parameters['-infile'].off()
app.Parameters['-sequences'].on()
#Add aln_int_map as profile1
app.Parameters['-profile1'].on(\
app._tempfile_as_multiline_string(aln_int_map.toFasta()))
#Add seq_int_map as profile2
app.Parameters['-profile2'].on(\
app._tempfile_as_multiline_string(seq_int_map.toFasta()))
#Get results using int_map as input to app
res = app()
#Get alignment as dict out of results
alignment = dict(ClustalParser(res['Align'].readlines()))
#Make new dict mapping original IDs
new_alignment = {}
for k,v in alignment.items():
new_alignment[seq_int_keys[k]]=v
#Create an Alignment object from alignment dict
new_alignment = Alignment(new_alignment,MolType=moltype)
#Clean up
res.cleanUp()
remove(app.Parameters['-profile1'].Value)
remove(app.Parameters['-profile2'].Value)
del(seq_collection,seq_int_map,seq_int_keys,\
aln,aln_int_map,aln_int_keys,app,res,alignment)
return new_alignment | python | def add_seqs_to_alignment(seqs, aln, moltype, params=None):
"""Returns an Alignment object from seqs and existing Alignment.
seqs: a cogent.core.alignment.SequenceCollection object, or data that can
be used to build one.
aln: a cogent.core.alignment.Alignment object, or data that can be used to
build one
params: dict of parameters to pass in to the Clustal app controller.
"""
#create SequenceCollection object from seqs
seq_collection = SequenceCollection(seqs,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
seq_int_map, seq_int_keys = seq_collection.getIntMap()
#Create SequenceCollection from int_map.
seq_int_map = SequenceCollection(seq_int_map,MolType=moltype)
#create Alignment object from aln
aln = Alignment(aln,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
aln_int_map, aln_int_keys = aln.getIntMap(prefix='seqn_')
#Create SequenceCollection from int_map.
aln_int_map = Alignment(aln_int_map,MolType=moltype)
#Update seq_int_keys with aln_int_keys
seq_int_keys.update(aln_int_keys)
#Create Mafft app.
app = Clustalw(InputHandler='_input_as_multiline_string',\
params=params,
SuppressStderr=True)
app.Parameters['-align'].off()
app.Parameters['-infile'].off()
app.Parameters['-sequences'].on()
#Add aln_int_map as profile1
app.Parameters['-profile1'].on(\
app._tempfile_as_multiline_string(aln_int_map.toFasta()))
#Add seq_int_map as profile2
app.Parameters['-profile2'].on(\
app._tempfile_as_multiline_string(seq_int_map.toFasta()))
#Get results using int_map as input to app
res = app()
#Get alignment as dict out of results
alignment = dict(ClustalParser(res['Align'].readlines()))
#Make new dict mapping original IDs
new_alignment = {}
for k,v in alignment.items():
new_alignment[seq_int_keys[k]]=v
#Create an Alignment object from alignment dict
new_alignment = Alignment(new_alignment,MolType=moltype)
#Clean up
res.cleanUp()
remove(app.Parameters['-profile1'].Value)
remove(app.Parameters['-profile2'].Value)
del(seq_collection,seq_int_map,seq_int_keys,\
aln,aln_int_map,aln_int_keys,app,res,alignment)
return new_alignment | [
"def",
"add_seqs_to_alignment",
"(",
"seqs",
",",
"aln",
",",
"moltype",
",",
"params",
"=",
"None",
")",
":",
"#create SequenceCollection object from seqs",
"seq_collection",
"=",
"SequenceCollection",
"(",
"seqs",
",",
"MolType",
"=",
"moltype",
")",
"#Create mapp... | Returns an Alignment object from seqs and existing Alignment.
seqs: a cogent.core.alignment.SequenceCollection object, or data that can
be used to build one.
aln: a cogent.core.alignment.Alignment object, or data that can be used to
build one
params: dict of parameters to pass in to the Clustal app controller. | [
"Returns",
"an",
"Alignment",
"object",
"from",
"seqs",
"and",
"existing",
"Alignment",
"."
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L601-L663 |
biocore/burrito-fillings | bfillings/clustalw.py | align_two_alignments | def align_two_alignments(aln1, aln2, moltype, params=None):
"""Returns an Alignment object from two existing Alignments.
aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be
used to build them.
params: dict of parameters to pass in to the Clustal app controller.
"""
#create SequenceCollection object from seqs
aln1 = Alignment(aln1,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
aln1_int_map, aln1_int_keys = aln1.getIntMap()
#Create SequenceCollection from int_map.
aln1_int_map = Alignment(aln1_int_map,MolType=moltype)
#create Alignment object from aln
aln2 = Alignment(aln2,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
aln2_int_map, aln2_int_keys = aln2.getIntMap(prefix='seqn_')
#Create SequenceCollection from int_map.
aln2_int_map = Alignment(aln2_int_map,MolType=moltype)
#Update aln1_int_keys with aln2_int_keys
aln1_int_keys.update(aln2_int_keys)
#Create Mafft app.
app = Clustalw(InputHandler='_input_as_multiline_string',\
params=params,
SuppressStderr=True)
app.Parameters['-align'].off()
app.Parameters['-infile'].off()
app.Parameters['-profile'].on()
#Add aln_int_map as profile1
app.Parameters['-profile1'].on(\
app._tempfile_as_multiline_string(aln1_int_map.toFasta()))
#Add seq_int_map as profile2
app.Parameters['-profile2'].on(\
app._tempfile_as_multiline_string(aln2_int_map.toFasta()))
#Get results using int_map as input to app
res = app()
#Get alignment as dict out of results
alignment = dict(ClustalParser(res['Align'].readlines()))
#Make new dict mapping original IDs
new_alignment = {}
for k,v in alignment.items():
new_alignment[aln1_int_keys[k]]=v
#Create an Alignment object from alignment dict
new_alignment = Alignment(new_alignment,MolType=moltype)
#Clean up
res.cleanUp()
remove(app.Parameters['-profile1'].Value)
remove(app.Parameters['-profile2'].Value)
del(aln1,aln1_int_map,aln1_int_keys,\
aln2,aln2_int_map,aln2_int_keys,app,res,alignment)
return new_alignment | python | def align_two_alignments(aln1, aln2, moltype, params=None):
"""Returns an Alignment object from two existing Alignments.
aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be
used to build them.
params: dict of parameters to pass in to the Clustal app controller.
"""
#create SequenceCollection object from seqs
aln1 = Alignment(aln1,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
aln1_int_map, aln1_int_keys = aln1.getIntMap()
#Create SequenceCollection from int_map.
aln1_int_map = Alignment(aln1_int_map,MolType=moltype)
#create Alignment object from aln
aln2 = Alignment(aln2,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
aln2_int_map, aln2_int_keys = aln2.getIntMap(prefix='seqn_')
#Create SequenceCollection from int_map.
aln2_int_map = Alignment(aln2_int_map,MolType=moltype)
#Update aln1_int_keys with aln2_int_keys
aln1_int_keys.update(aln2_int_keys)
#Create Mafft app.
app = Clustalw(InputHandler='_input_as_multiline_string',\
params=params,
SuppressStderr=True)
app.Parameters['-align'].off()
app.Parameters['-infile'].off()
app.Parameters['-profile'].on()
#Add aln_int_map as profile1
app.Parameters['-profile1'].on(\
app._tempfile_as_multiline_string(aln1_int_map.toFasta()))
#Add seq_int_map as profile2
app.Parameters['-profile2'].on(\
app._tempfile_as_multiline_string(aln2_int_map.toFasta()))
#Get results using int_map as input to app
res = app()
#Get alignment as dict out of results
alignment = dict(ClustalParser(res['Align'].readlines()))
#Make new dict mapping original IDs
new_alignment = {}
for k,v in alignment.items():
new_alignment[aln1_int_keys[k]]=v
#Create an Alignment object from alignment dict
new_alignment = Alignment(new_alignment,MolType=moltype)
#Clean up
res.cleanUp()
remove(app.Parameters['-profile1'].Value)
remove(app.Parameters['-profile2'].Value)
del(aln1,aln1_int_map,aln1_int_keys,\
aln2,aln2_int_map,aln2_int_keys,app,res,alignment)
return new_alignment | [
"def",
"align_two_alignments",
"(",
"aln1",
",",
"aln2",
",",
"moltype",
",",
"params",
"=",
"None",
")",
":",
"#create SequenceCollection object from seqs",
"aln1",
"=",
"Alignment",
"(",
"aln1",
",",
"MolType",
"=",
"moltype",
")",
"#Create mapping between abbrevi... | Returns an Alignment object from two existing Alignments.
aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be
used to build them.
params: dict of parameters to pass in to the Clustal app controller. | [
"Returns",
"an",
"Alignment",
"object",
"from",
"two",
"existing",
"Alignments",
"."
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L665-L724 |
biocore/burrito-fillings | bfillings/clustalw.py | Clustalw._input_as_multiline_string | def _input_as_multiline_string(self, data):
"""Writes data to tempfile and sets -infile parameter
data -- list of lines
"""
if data:
self.Parameters['-infile']\
.on(super(Clustalw,self)._input_as_multiline_string(data))
return '' | python | def _input_as_multiline_string(self, data):
"""Writes data to tempfile and sets -infile parameter
data -- list of lines
"""
if data:
self.Parameters['-infile']\
.on(super(Clustalw,self)._input_as_multiline_string(data))
return '' | [
"def",
"_input_as_multiline_string",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
":",
"self",
".",
"Parameters",
"[",
"'-infile'",
"]",
".",
"on",
"(",
"super",
"(",
"Clustalw",
",",
"self",
")",
".",
"_input_as_multiline_string",
"(",
"data",
")",
... | Writes data to tempfile and sets -infile parameter
data -- list of lines | [
"Writes",
"data",
"to",
"tempfile",
"and",
"sets",
"-",
"infile",
"parameter"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L166-L174 |
biocore/burrito-fillings | bfillings/clustalw.py | Clustalw._input_as_lines | def _input_as_lines(self,data):
"""Writes data to tempfile and sets -infile parameter
data -- list of lines, ready to be written to file
"""
if data:
self.Parameters['-infile']\
.on(super(Clustalw,self)._input_as_lines(data))
return '' | python | def _input_as_lines(self,data):
"""Writes data to tempfile and sets -infile parameter
data -- list of lines, ready to be written to file
"""
if data:
self.Parameters['-infile']\
.on(super(Clustalw,self)._input_as_lines(data))
return '' | [
"def",
"_input_as_lines",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
":",
"self",
".",
"Parameters",
"[",
"'-infile'",
"]",
".",
"on",
"(",
"super",
"(",
"Clustalw",
",",
"self",
")",
".",
"_input_as_lines",
"(",
"data",
")",
")",
"return",
"'... | Writes data to tempfile and sets -infile parameter
data -- list of lines, ready to be written to file | [
"Writes",
"data",
"to",
"tempfile",
"and",
"sets",
"-",
"infile",
"parameter"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L176-L184 |
biocore/burrito-fillings | bfillings/clustalw.py | Clustalw._suffix | def _suffix(self):
"""Return appropriate suffix for alignment file"""
_output_formats={'GCG':'.msf',
'GDE':'.gde',
'PHYLIP':'.phy',
'PIR':'.pir',
'NEXUS':'.nxs'}
if self.Parameters['-output'].isOn():
return _output_formats[self.Parameters['-output'].Value]
else:
return '.aln' | python | def _suffix(self):
"""Return appropriate suffix for alignment file"""
_output_formats={'GCG':'.msf',
'GDE':'.gde',
'PHYLIP':'.phy',
'PIR':'.pir',
'NEXUS':'.nxs'}
if self.Parameters['-output'].isOn():
return _output_formats[self.Parameters['-output'].Value]
else:
return '.aln' | [
"def",
"_suffix",
"(",
"self",
")",
":",
"_output_formats",
"=",
"{",
"'GCG'",
":",
"'.msf'",
",",
"'GDE'",
":",
"'.gde'",
",",
"'PHYLIP'",
":",
"'.phy'",
",",
"'PIR'",
":",
"'.pir'",
",",
"'NEXUS'",
":",
"'.nxs'",
"}",
"if",
"self",
".",
"Parameters",... | Return appropriate suffix for alignment file | [
"Return",
"appropriate",
"suffix",
"for",
"alignment",
"file"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L210-L221 |
biocore/burrito-fillings | bfillings/clustalw.py | Clustalw._aln_filename | def _aln_filename(self,prefix):
"""Return name of file containing the alignment
prefix -- str, prefix of alignment file.
"""
if self.Parameters['-outfile'].isOn():
aln_filename = self._absolute(self.Parameters['-outfile'].Value)
else:
aln_filename = prefix + self._suffix()
return aln_filename | python | def _aln_filename(self,prefix):
"""Return name of file containing the alignment
prefix -- str, prefix of alignment file.
"""
if self.Parameters['-outfile'].isOn():
aln_filename = self._absolute(self.Parameters['-outfile'].Value)
else:
aln_filename = prefix + self._suffix()
return aln_filename | [
"def",
"_aln_filename",
"(",
"self",
",",
"prefix",
")",
":",
"if",
"self",
".",
"Parameters",
"[",
"'-outfile'",
"]",
".",
"isOn",
"(",
")",
":",
"aln_filename",
"=",
"self",
".",
"_absolute",
"(",
"self",
".",
"Parameters",
"[",
"'-outfile'",
"]",
".... | Return name of file containing the alignment
prefix -- str, prefix of alignment file. | [
"Return",
"name",
"of",
"file",
"containing",
"the",
"alignment"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L223-L232 |
biocore/burrito-fillings | bfillings/clustalw.py | Clustalw._get_result_paths | def _get_result_paths(self,data):
"""Return dict of {key: ResultPath}
"""
#clustalw .aln is used when no or unkown output type specified
_treeinfo_formats = {'nj':'.nj',
'dist':'.dst',
'nexus':'.tre'}
result = {}
par = self.Parameters
abs = self._absolute
if par['-align'].isOn():
prefix = par['-infile'].Value.rsplit('.', 1)[0]
#prefix = par['-infile'].Value.split('.')[0]
aln_filename = self._aln_filename(prefix)
if par['-newtree'].isOn():
dnd_filename = abs(par['-newtree'].Value)
elif par['-usetree'].isOn():
dnd_filename = abs(par['-usetree'].Value)
else:
dnd_filename = abs(prefix + '.dnd')
result['Align'] = ResultPath(Path=aln_filename,IsWritten=True)
result['Dendro'] = ResultPath(Path=dnd_filename,IsWritten=True)
elif par['-profile'].isOn():
prefix1 = par['-profile1'].Value.rsplit('.', 1)[0]
prefix2 = par['-profile2'].Value.rsplit('.', 1)[0]
#prefix1 = par['-profile1'].Value.split('.')[0]
#prefix2 = par['-profile2'].Value.split('.')[0]
aln_filename = ''; aln_written = True
dnd1_filename = ''; tree1_written = True
dnd2_filename = ''; tree2_written = True
aln_filename = self._aln_filename(prefix1)
#usetree1
if par['-usetree1'].isOn():
tree1_written = False
#usetree2
if par['-usetree2'].isOn():
tree2_written = False
if par['-newtree1'].isOn():
dnd1_filename = abs(par['-newtree1'].Value)
aln_written=False
else:
dnd1_filename = abs(prefix1 + '.dnd')
if par['-newtree2'].isOn():
dnd2_filename = abs(par['-newtree2'].Value)
aln_written=False
else:
dnd2_filename = abs(prefix2 + '.dnd')
result['Align'] = ResultPath(Path=aln_filename,
IsWritten=aln_written)
result['Dendro1'] = ResultPath(Path=dnd1_filename,
IsWritten=tree1_written)
result['Dendro2'] = ResultPath(Path=dnd2_filename,
IsWritten=tree2_written)
elif par['-sequences'].isOn():
prefix1 = par['-profile1'].Value.rsplit('.', 1)[0]
prefix2 = par['-profile2'].Value.rsplit('.', 1)[0]
#prefix1 = par['-profile1'].Value.split('.')[0] #alignment
#prefix2 = par['-profile2'].Value.split('.')[0] #sequences
aln_filename = ''; aln_written = True
dnd_filename = ''; dnd_written = True
aln_filename = self._aln_filename(prefix2)
if par['-usetree'].isOn():
dnd_written = False
elif par['-newtree'].isOn():
aln_written = False
dnd_filename = abs(par['-newtree'].Value)
else:
dnd_filename = prefix2 + '.dnd'
result['Align'] = ResultPath(Path=aln_filename,\
IsWritten=aln_written)
result['Dendro'] = ResultPath(Path=dnd_filename,\
IsWritten=dnd_written)
elif par['-tree'].isOn():
prefix = par['-infile'].Value.rsplit('.', 1)[0]
#prefix = par['-infile'].Value.split('.')[0]
tree_filename = ''; tree_written = True
treeinfo_filename = ''; treeinfo_written = False
tree_filename = prefix + '.ph'
if par['-outputtree'].isOn() and\
par['-outputtree'].Value != 'phylip':
treeinfo_filename = prefix +\
_treeinfo_formats[par['-outputtree'].Value]
treeinfo_written = True
result['Tree'] = ResultPath(Path=tree_filename,\
IsWritten=tree_written)
result['TreeInfo'] = ResultPath(Path=treeinfo_filename,\
IsWritten=treeinfo_written)
elif par['-bootstrap'].isOn():
prefix = par['-infile'].Value.rsplit('.', 1)[0]
#prefix = par['-infile'].Value.split('.')[0]
boottree_filename = prefix + '.phb'
result['Tree'] = ResultPath(Path=boottree_filename,IsWritten=True)
return result | python | def _get_result_paths(self,data):
"""Return dict of {key: ResultPath}
"""
#clustalw .aln is used when no or unkown output type specified
_treeinfo_formats = {'nj':'.nj',
'dist':'.dst',
'nexus':'.tre'}
result = {}
par = self.Parameters
abs = self._absolute
if par['-align'].isOn():
prefix = par['-infile'].Value.rsplit('.', 1)[0]
#prefix = par['-infile'].Value.split('.')[0]
aln_filename = self._aln_filename(prefix)
if par['-newtree'].isOn():
dnd_filename = abs(par['-newtree'].Value)
elif par['-usetree'].isOn():
dnd_filename = abs(par['-usetree'].Value)
else:
dnd_filename = abs(prefix + '.dnd')
result['Align'] = ResultPath(Path=aln_filename,IsWritten=True)
result['Dendro'] = ResultPath(Path=dnd_filename,IsWritten=True)
elif par['-profile'].isOn():
prefix1 = par['-profile1'].Value.rsplit('.', 1)[0]
prefix2 = par['-profile2'].Value.rsplit('.', 1)[0]
#prefix1 = par['-profile1'].Value.split('.')[0]
#prefix2 = par['-profile2'].Value.split('.')[0]
aln_filename = ''; aln_written = True
dnd1_filename = ''; tree1_written = True
dnd2_filename = ''; tree2_written = True
aln_filename = self._aln_filename(prefix1)
#usetree1
if par['-usetree1'].isOn():
tree1_written = False
#usetree2
if par['-usetree2'].isOn():
tree2_written = False
if par['-newtree1'].isOn():
dnd1_filename = abs(par['-newtree1'].Value)
aln_written=False
else:
dnd1_filename = abs(prefix1 + '.dnd')
if par['-newtree2'].isOn():
dnd2_filename = abs(par['-newtree2'].Value)
aln_written=False
else:
dnd2_filename = abs(prefix2 + '.dnd')
result['Align'] = ResultPath(Path=aln_filename,
IsWritten=aln_written)
result['Dendro1'] = ResultPath(Path=dnd1_filename,
IsWritten=tree1_written)
result['Dendro2'] = ResultPath(Path=dnd2_filename,
IsWritten=tree2_written)
elif par['-sequences'].isOn():
prefix1 = par['-profile1'].Value.rsplit('.', 1)[0]
prefix2 = par['-profile2'].Value.rsplit('.', 1)[0]
#prefix1 = par['-profile1'].Value.split('.')[0] #alignment
#prefix2 = par['-profile2'].Value.split('.')[0] #sequences
aln_filename = ''; aln_written = True
dnd_filename = ''; dnd_written = True
aln_filename = self._aln_filename(prefix2)
if par['-usetree'].isOn():
dnd_written = False
elif par['-newtree'].isOn():
aln_written = False
dnd_filename = abs(par['-newtree'].Value)
else:
dnd_filename = prefix2 + '.dnd'
result['Align'] = ResultPath(Path=aln_filename,\
IsWritten=aln_written)
result['Dendro'] = ResultPath(Path=dnd_filename,\
IsWritten=dnd_written)
elif par['-tree'].isOn():
prefix = par['-infile'].Value.rsplit('.', 1)[0]
#prefix = par['-infile'].Value.split('.')[0]
tree_filename = ''; tree_written = True
treeinfo_filename = ''; treeinfo_written = False
tree_filename = prefix + '.ph'
if par['-outputtree'].isOn() and\
par['-outputtree'].Value != 'phylip':
treeinfo_filename = prefix +\
_treeinfo_formats[par['-outputtree'].Value]
treeinfo_written = True
result['Tree'] = ResultPath(Path=tree_filename,\
IsWritten=tree_written)
result['TreeInfo'] = ResultPath(Path=treeinfo_filename,\
IsWritten=treeinfo_written)
elif par['-bootstrap'].isOn():
prefix = par['-infile'].Value.rsplit('.', 1)[0]
#prefix = par['-infile'].Value.split('.')[0]
boottree_filename = prefix + '.phb'
result['Tree'] = ResultPath(Path=boottree_filename,IsWritten=True)
return result | [
"def",
"_get_result_paths",
"(",
"self",
",",
"data",
")",
":",
"#clustalw .aln is used when no or unkown output type specified",
"_treeinfo_formats",
"=",
"{",
"'nj'",
":",
"'.nj'",
",",
"'dist'",
":",
"'.dst'",
",",
"'nexus'",
":",
"'.tre'",
"}",
"result",
"=",
... | Return dict of {key: ResultPath} | [
"Return",
"dict",
"of",
"{",
"key",
":",
"ResultPath",
"}"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L249-L347 |
EndurantDevs/webargs-sanic | webargs_sanic/sanicparser.py | abort | def abort(http_status_code, exc=None, **kwargs):
"""Raise a HTTPException for the given http_status_code. Attach any keyword
arguments to the exception for later processing.
From Flask-Restful. See NOTICE file for license information.
"""
try:
sanic.exceptions.abort(http_status_code, exc)
except sanic.exceptions.SanicException as err:
err.data = kwargs
err.exc = exc
raise err | python | def abort(http_status_code, exc=None, **kwargs):
"""Raise a HTTPException for the given http_status_code. Attach any keyword
arguments to the exception for later processing.
From Flask-Restful. See NOTICE file for license information.
"""
try:
sanic.exceptions.abort(http_status_code, exc)
except sanic.exceptions.SanicException as err:
err.data = kwargs
err.exc = exc
raise err | [
"def",
"abort",
"(",
"http_status_code",
",",
"exc",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"sanic",
".",
"exceptions",
".",
"abort",
"(",
"http_status_code",
",",
"exc",
")",
"except",
"sanic",
".",
"exceptions",
".",
"SanicExceptio... | Raise a HTTPException for the given http_status_code. Attach any keyword
arguments to the exception for later processing.
From Flask-Restful. See NOTICE file for license information. | [
"Raise",
"a",
"HTTPException",
"for",
"the",
"given",
"http_status_code",
".",
"Attach",
"any",
"keyword",
"arguments",
"to",
"the",
"exception",
"for",
"later",
"processing",
"."
] | train | https://github.com/EndurantDevs/webargs-sanic/blob/8861a3b7d16d43a0b7e6669115eb93b0553f1b63/webargs_sanic/sanicparser.py#L33-L44 |
EndurantDevs/webargs-sanic | webargs_sanic/sanicparser.py | SanicParser.parse_view_args | def parse_view_args(self, req, name, field):
"""Pull a value from the request's ``view_args``."""
return core.get_value(req.match_info, name, field) | python | def parse_view_args(self, req, name, field):
"""Pull a value from the request's ``view_args``."""
return core.get_value(req.match_info, name, field) | [
"def",
"parse_view_args",
"(",
"self",
",",
"req",
",",
"name",
",",
"field",
")",
":",
"return",
"core",
".",
"get_value",
"(",
"req",
".",
"match_info",
",",
"name",
",",
"field",
")"
] | Pull a value from the request's ``view_args``. | [
"Pull",
"a",
"value",
"from",
"the",
"request",
"s",
"view_args",
"."
] | train | https://github.com/EndurantDevs/webargs-sanic/blob/8861a3b7d16d43a0b7e6669115eb93b0553f1b63/webargs_sanic/sanicparser.py#L57-L59 |
EndurantDevs/webargs-sanic | webargs_sanic/sanicparser.py | SanicParser.get_request_from_view_args | def get_request_from_view_args(self, view, args, kwargs):
"""Get request object from a handler function or method. Used internally by
``use_args`` and ``use_kwargs``.
"""
if len(args) > 1 and isinstance(args[1], sanic.request.Request):
req = args[1]
else:
req = args[0]
assert isinstance(
req, sanic.request.Request
), "Request argument not found for handler"
return req | python | def get_request_from_view_args(self, view, args, kwargs):
"""Get request object from a handler function or method. Used internally by
``use_args`` and ``use_kwargs``.
"""
if len(args) > 1 and isinstance(args[1], sanic.request.Request):
req = args[1]
else:
req = args[0]
assert isinstance(
req, sanic.request.Request
), "Request argument not found for handler"
return req | [
"def",
"get_request_from_view_args",
"(",
"self",
",",
"view",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
"and",
"isinstance",
"(",
"args",
"[",
"1",
"]",
",",
"sanic",
".",
"request",
".",
"Request",
")",
":",
"... | Get request object from a handler function or method. Used internally by
``use_args`` and ``use_kwargs``. | [
"Get",
"request",
"object",
"from",
"a",
"handler",
"function",
"or",
"method",
".",
"Used",
"internally",
"by",
"use_args",
"and",
"use_kwargs",
"."
] | train | https://github.com/EndurantDevs/webargs-sanic/blob/8861a3b7d16d43a0b7e6669115eb93b0553f1b63/webargs_sanic/sanicparser.py#L61-L72 |
EndurantDevs/webargs-sanic | webargs_sanic/sanicparser.py | SanicParser.parse_json | def parse_json(self, req, name, field):
"""Pull a json value from the request."""
if not (req.body and is_json_request(req)):
return core.missing
json_data = req.json
if json_data is None:
return core.missing
return core.get_value(json_data, name, field, allow_many_nested=True) | python | def parse_json(self, req, name, field):
"""Pull a json value from the request."""
if not (req.body and is_json_request(req)):
return core.missing
json_data = req.json
if json_data is None:
return core.missing
return core.get_value(json_data, name, field, allow_many_nested=True) | [
"def",
"parse_json",
"(",
"self",
",",
"req",
",",
"name",
",",
"field",
")",
":",
"if",
"not",
"(",
"req",
".",
"body",
"and",
"is_json_request",
"(",
"req",
")",
")",
":",
"return",
"core",
".",
"missing",
"json_data",
"=",
"req",
".",
"json",
"i... | Pull a json value from the request. | [
"Pull",
"a",
"json",
"value",
"from",
"the",
"request",
"."
] | train | https://github.com/EndurantDevs/webargs-sanic/blob/8861a3b7d16d43a0b7e6669115eb93b0553f1b63/webargs_sanic/sanicparser.py#L74-L81 |
EndurantDevs/webargs-sanic | webargs_sanic/sanicparser.py | SanicParser.handle_error | def handle_error(self, error, req, schema):
"""Handles errors during parsing. Aborts the current HTTP request and
responds with a 422 error.
"""
status_code = getattr(error, "status_code", self.DEFAULT_VALIDATION_STATUS)
abort(status_code, exc=error, messages=error.messages, schema=schema) | python | def handle_error(self, error, req, schema):
"""Handles errors during parsing. Aborts the current HTTP request and
responds with a 422 error.
"""
status_code = getattr(error, "status_code", self.DEFAULT_VALIDATION_STATUS)
abort(status_code, exc=error, messages=error.messages, schema=schema) | [
"def",
"handle_error",
"(",
"self",
",",
"error",
",",
"req",
",",
"schema",
")",
":",
"status_code",
"=",
"getattr",
"(",
"error",
",",
"\"status_code\"",
",",
"self",
".",
"DEFAULT_VALIDATION_STATUS",
")",
"abort",
"(",
"status_code",
",",
"exc",
"=",
"e... | Handles errors during parsing. Aborts the current HTTP request and
responds with a 422 error. | [
"Handles",
"errors",
"during",
"parsing",
".",
"Aborts",
"the",
"current",
"HTTP",
"request",
"and",
"responds",
"with",
"a",
"422",
"error",
"."
] | train | https://github.com/EndurantDevs/webargs-sanic/blob/8861a3b7d16d43a0b7e6669115eb93b0553f1b63/webargs_sanic/sanicparser.py#L107-L113 |
michaelpb/omnic | omnic/utils/filesystem.py | directory_walk | def directory_walk(source_d, destination_d):
'''
Walk a directory structure and yield full parallel source and destination
files, munging filenames as necessary
'''
for dirpath, dirnames, filenames in os.walk(source_d):
relpath = os.path.relpath(dirpath, source_d)
if relpath == '.':
relpath = '' # remove implied '.'
for filename in filenames:
suffix = filename
if relpath:
suffix = os.path.join(relpath, filename)
full_source_path = os.path.join(source_d, suffix)
full_destination_path = os.path.join(destination_d, suffix)
yield full_source_path, full_destination_path | python | def directory_walk(source_d, destination_d):
'''
Walk a directory structure and yield full parallel source and destination
files, munging filenames as necessary
'''
for dirpath, dirnames, filenames in os.walk(source_d):
relpath = os.path.relpath(dirpath, source_d)
if relpath == '.':
relpath = '' # remove implied '.'
for filename in filenames:
suffix = filename
if relpath:
suffix = os.path.join(relpath, filename)
full_source_path = os.path.join(source_d, suffix)
full_destination_path = os.path.join(destination_d, suffix)
yield full_source_path, full_destination_path | [
"def",
"directory_walk",
"(",
"source_d",
",",
"destination_d",
")",
":",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"source_d",
")",
":",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"dirpath",
",",
"... | Walk a directory structure and yield full parallel source and destination
files, munging filenames as necessary | [
"Walk",
"a",
"directory",
"structure",
"and",
"yield",
"full",
"parallel",
"source",
"and",
"destination",
"files",
"munging",
"filenames",
"as",
"necessary"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/utils/filesystem.py#L5-L20 |
michaelpb/omnic | omnic/utils/filesystem.py | recursive_symlink_dirs | def recursive_symlink_dirs(source_d, destination_d):
'''
Create dirs and symlink all files recursively from source_d, ignoring
errors (e.g. existing files)
'''
func = os.symlink
if os.name == 'nt':
# NOTE: need to verify that default perms only allow admins to create
# symlinks on Windows
func = shutil.copy
if os.path.exists(destination_d):
os.rmdir(destination_d)
shutil.copytree(source_d, destination_d, copy_function=func) | python | def recursive_symlink_dirs(source_d, destination_d):
'''
Create dirs and symlink all files recursively from source_d, ignoring
errors (e.g. existing files)
'''
func = os.symlink
if os.name == 'nt':
# NOTE: need to verify that default perms only allow admins to create
# symlinks on Windows
func = shutil.copy
if os.path.exists(destination_d):
os.rmdir(destination_d)
shutil.copytree(source_d, destination_d, copy_function=func) | [
"def",
"recursive_symlink_dirs",
"(",
"source_d",
",",
"destination_d",
")",
":",
"func",
"=",
"os",
".",
"symlink",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# NOTE: need to verify that default perms only allow admins to create",
"# symlinks on Windows",
"func",
"="... | Create dirs and symlink all files recursively from source_d, ignoring
errors (e.g. existing files) | [
"Create",
"dirs",
"and",
"symlink",
"all",
"files",
"recursively",
"from",
"source_d",
"ignoring",
"errors",
"(",
"e",
".",
"g",
".",
"existing",
"files",
")"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/utils/filesystem.py#L23-L35 |
michaelpb/omnic | omnic/utils/filesystem.py | recursive_hardlink_dirs | def recursive_hardlink_dirs(source_d, destination_d):
'''
Same as above, except creating hardlinks for all files
'''
func = os.link
if os.name == 'nt':
func = shutil.copy
if os.path.exists(destination_d):
os.rmdir(destination_d)
shutil.copytree(source_d, destination_d, copy_function=func) | python | def recursive_hardlink_dirs(source_d, destination_d):
'''
Same as above, except creating hardlinks for all files
'''
func = os.link
if os.name == 'nt':
func = shutil.copy
if os.path.exists(destination_d):
os.rmdir(destination_d)
shutil.copytree(source_d, destination_d, copy_function=func) | [
"def",
"recursive_hardlink_dirs",
"(",
"source_d",
",",
"destination_d",
")",
":",
"func",
"=",
"os",
".",
"link",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"func",
"=",
"shutil",
".",
"copy",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"destination... | Same as above, except creating hardlinks for all files | [
"Same",
"as",
"above",
"except",
"creating",
"hardlinks",
"for",
"all",
"files"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/utils/filesystem.py#L38-L47 |
michaelpb/omnic | omnic/utils/filesystem.py | flat_git_tree_to_nested | def flat_git_tree_to_nested(flat_tree, prefix=''):
'''
Given an array in format:
[
["100644", "blob", "ab3ce...", "748", ".gitignore" ],
["100644", "blob", "ab3ce...", "748", "path/to/thing" ],
...
]
Outputs in a nested format:
{
"path": "/",
"type": "directory",
"children": [
{
"type": "blob",
"size": 748,
"sha": "ab3ce...",
"mode": "100644",
},
...
],
...
}
'''
root = _make_empty_dir_dict(prefix if prefix else '/')
# Filter all descendents of this prefix
descendent_files = [
info for info in flat_tree
if os.path.dirname(info[PATH]).startswith(prefix)
]
# Figure out strictly leaf nodes of this tree (can be immediately added as
# children)
children_files = [
info for info in descendent_files
if os.path.dirname(info[PATH]) == prefix
]
# Figure out all descendent directories
descendent_dirs = set(
os.path.dirname(info[PATH]) for info in descendent_files
if os.path.dirname(info[PATH]).startswith(prefix)
and not os.path.dirname(info[PATH]) == prefix
)
# Figure out all descendent directories
children_dirs = set(
dir_path for dir_path in descendent_dirs
if os.path.dirname(dir_path) == prefix
)
# Recurse into children dirs, constructing file trees for each of them,
# then appending those
for dir_path in children_dirs:
info = flat_git_tree_to_nested(descendent_files, prefix=dir_path)
root['children'].append(info)
# Append direct children files
for info in children_files:
root['children'].append(_make_child(info))
return root | python | def flat_git_tree_to_nested(flat_tree, prefix=''):
'''
Given an array in format:
[
["100644", "blob", "ab3ce...", "748", ".gitignore" ],
["100644", "blob", "ab3ce...", "748", "path/to/thing" ],
...
]
Outputs in a nested format:
{
"path": "/",
"type": "directory",
"children": [
{
"type": "blob",
"size": 748,
"sha": "ab3ce...",
"mode": "100644",
},
...
],
...
}
'''
root = _make_empty_dir_dict(prefix if prefix else '/')
# Filter all descendents of this prefix
descendent_files = [
info for info in flat_tree
if os.path.dirname(info[PATH]).startswith(prefix)
]
# Figure out strictly leaf nodes of this tree (can be immediately added as
# children)
children_files = [
info for info in descendent_files
if os.path.dirname(info[PATH]) == prefix
]
# Figure out all descendent directories
descendent_dirs = set(
os.path.dirname(info[PATH]) for info in descendent_files
if os.path.dirname(info[PATH]).startswith(prefix)
and not os.path.dirname(info[PATH]) == prefix
)
# Figure out all descendent directories
children_dirs = set(
dir_path for dir_path in descendent_dirs
if os.path.dirname(dir_path) == prefix
)
# Recurse into children dirs, constructing file trees for each of them,
# then appending those
for dir_path in children_dirs:
info = flat_git_tree_to_nested(descendent_files, prefix=dir_path)
root['children'].append(info)
# Append direct children files
for info in children_files:
root['children'].append(_make_child(info))
return root | [
"def",
"flat_git_tree_to_nested",
"(",
"flat_tree",
",",
"prefix",
"=",
"''",
")",
":",
"root",
"=",
"_make_empty_dir_dict",
"(",
"prefix",
"if",
"prefix",
"else",
"'/'",
")",
"# Filter all descendents of this prefix",
"descendent_files",
"=",
"[",
"info",
"for",
... | Given an array in format:
[
["100644", "blob", "ab3ce...", "748", ".gitignore" ],
["100644", "blob", "ab3ce...", "748", "path/to/thing" ],
...
]
Outputs in a nested format:
{
"path": "/",
"type": "directory",
"children": [
{
"type": "blob",
"size": 748,
"sha": "ab3ce...",
"mode": "100644",
},
...
],
...
} | [
"Given",
"an",
"array",
"in",
"format",
":",
"[",
"[",
"100644",
"blob",
"ab3ce",
"...",
"748",
".",
"gitignore",
"]",
"[",
"100644",
"blob",
"ab3ce",
"...",
"748",
"path",
"/",
"to",
"/",
"thing",
"]",
"...",
"]"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/utils/filesystem.py#L71-L134 |
michaelpb/omnic | omnic/config/settingsmanager.py | SettingsManager.load_all | def load_all(self, key, default=None):
'''
Import settings key as a dict or list with values of importable paths
If a default constructor is specified, and a path is not importable, it
falls back to running the given constructor.
'''
value = getattr(self, key)
if default is not None:
def loader(path): return self.load_path_with_default(path, default)
else:
loader = self.load_path
if isinstance(value, dict):
return {key: loader(value) for key, value in value.items()}
elif isinstance(value, list):
return [loader(value) for value in value]
else:
raise ValueError('load_all must be list or dict') | python | def load_all(self, key, default=None):
'''
Import settings key as a dict or list with values of importable paths
If a default constructor is specified, and a path is not importable, it
falls back to running the given constructor.
'''
value = getattr(self, key)
if default is not None:
def loader(path): return self.load_path_with_default(path, default)
else:
loader = self.load_path
if isinstance(value, dict):
return {key: loader(value) for key, value in value.items()}
elif isinstance(value, list):
return [loader(value) for value in value]
else:
raise ValueError('load_all must be list or dict') | [
"def",
"load_all",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"key",
")",
"if",
"default",
"is",
"not",
"None",
":",
"def",
"loader",
"(",
"path",
")",
":",
"return",
"self",
".",
"l... | Import settings key as a dict or list with values of importable paths
If a default constructor is specified, and a path is not importable, it
falls back to running the given constructor. | [
"Import",
"settings",
"key",
"as",
"a",
"dict",
"or",
"list",
"with",
"values",
"of",
"importable",
"paths",
"If",
"a",
"default",
"constructor",
"is",
"specified",
"and",
"a",
"path",
"is",
"not",
"importable",
"it",
"falls",
"back",
"to",
"running",
"the... | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/config/settingsmanager.py#L94-L110 |
michaelpb/omnic | omnic/config/settingsmanager.py | SettingsManager.load_path | def load_path(self, path):
'''
Load and return a given import path to a module or class
'''
containing_module, _, last_item = path.rpartition('.')
if last_item[0].isupper():
# Is a class definition, should do an "import from"
path = containing_module
imported_obj = importlib.import_module(path)
if last_item[0].isupper():
try:
imported_obj = getattr(imported_obj, last_item)
except AttributeError:
msg = 'Cannot import "%s". ' \
'(Hint: CamelCase is only for classes)' % last_item
raise ConfigurationError(msg)
return imported_obj | python | def load_path(self, path):
'''
Load and return a given import path to a module or class
'''
containing_module, _, last_item = path.rpartition('.')
if last_item[0].isupper():
# Is a class definition, should do an "import from"
path = containing_module
imported_obj = importlib.import_module(path)
if last_item[0].isupper():
try:
imported_obj = getattr(imported_obj, last_item)
except AttributeError:
msg = 'Cannot import "%s". ' \
'(Hint: CamelCase is only for classes)' % last_item
raise ConfigurationError(msg)
return imported_obj | [
"def",
"load_path",
"(",
"self",
",",
"path",
")",
":",
"containing_module",
",",
"_",
",",
"last_item",
"=",
"path",
".",
"rpartition",
"(",
"'.'",
")",
"if",
"last_item",
"[",
"0",
"]",
".",
"isupper",
"(",
")",
":",
"# Is a class definition, should do a... | Load and return a given import path to a module or class | [
"Load",
"and",
"return",
"a",
"given",
"import",
"path",
"to",
"a",
"module",
"or",
"class"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/config/settingsmanager.py#L112-L128 |
michaelpb/omnic | omnic/config/settingsmanager.py | SettingsManager.load_path_with_default | def load_path_with_default(self, path, default_constructor):
'''
Same as `load_path(path)', except uses default_constructor on import
errors, or if loaded a auto-generated namespace package (e.g. bare
directory).
'''
try:
imported_obj = self.load_path(path)
except (ImportError, ConfigurationError):
imported_obj = default_constructor(path)
else:
# Ugly but seemingly expedient way to check a module was an
# namespace type module
if (isinstance(imported_obj, ModuleType) and
imported_obj.__spec__.origin == 'namespace'):
imported_obj = default_constructor(path)
return imported_obj | python | def load_path_with_default(self, path, default_constructor):
'''
Same as `load_path(path)', except uses default_constructor on import
errors, or if loaded a auto-generated namespace package (e.g. bare
directory).
'''
try:
imported_obj = self.load_path(path)
except (ImportError, ConfigurationError):
imported_obj = default_constructor(path)
else:
# Ugly but seemingly expedient way to check a module was an
# namespace type module
if (isinstance(imported_obj, ModuleType) and
imported_obj.__spec__.origin == 'namespace'):
imported_obj = default_constructor(path)
return imported_obj | [
"def",
"load_path_with_default",
"(",
"self",
",",
"path",
",",
"default_constructor",
")",
":",
"try",
":",
"imported_obj",
"=",
"self",
".",
"load_path",
"(",
"path",
")",
"except",
"(",
"ImportError",
",",
"ConfigurationError",
")",
":",
"imported_obj",
"="... | Same as `load_path(path)', except uses default_constructor on import
errors, or if loaded a auto-generated namespace package (e.g. bare
directory). | [
"Same",
"as",
"load_path",
"(",
"path",
")",
"except",
"uses",
"default_constructor",
"on",
"import",
"errors",
"or",
"if",
"loaded",
"a",
"auto",
"-",
"generated",
"namespace",
"package",
"(",
"e",
".",
"g",
".",
"bare",
"directory",
")",
"."
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/config/settingsmanager.py#L130-L146 |
michaelpb/omnic | omnic/config/settingsmanager.py | SettingsManager.set | def set(self, **kwargs):
'''
Override existing settings, taking precedence over both user settings
object and default settings. Useful for specific runtime requirements,
such as overriding PORT or HOST.
'''
for lower_key, value in kwargs.items():
if lower_key.lower() != lower_key:
raise ValueError('Requires lowercase: %s' % lower_key)
key = lower_key.upper()
try:
getattr(self, key)
except (AttributeError, ConfigurationError):
raise AttributeError('Cannot override %s' % key)
self.overridden_settings[key] = value | python | def set(self, **kwargs):
'''
Override existing settings, taking precedence over both user settings
object and default settings. Useful for specific runtime requirements,
such as overriding PORT or HOST.
'''
for lower_key, value in kwargs.items():
if lower_key.lower() != lower_key:
raise ValueError('Requires lowercase: %s' % lower_key)
key = lower_key.upper()
try:
getattr(self, key)
except (AttributeError, ConfigurationError):
raise AttributeError('Cannot override %s' % key)
self.overridden_settings[key] = value | [
"def",
"set",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"lower_key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"lower_key",
".",
"lower",
"(",
")",
"!=",
"lower_key",
":",
"raise",
"ValueError",
"(",
"'Requires low... | Override existing settings, taking precedence over both user settings
object and default settings. Useful for specific runtime requirements,
such as overriding PORT or HOST. | [
"Override",
"existing",
"settings",
"taking",
"precedence",
"over",
"both",
"user",
"settings",
"object",
"and",
"default",
"settings",
".",
"Useful",
"for",
"specific",
"runtime",
"requirements",
"such",
"as",
"overriding",
"PORT",
"or",
"HOST",
"."
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/config/settingsmanager.py#L148-L162 |
michaelpb/omnic | omnic/config/settingsmanager.py | SettingsManager.use_settings | def use_settings(self, settings_module):
'''
Useful for tests for overriding current settings manually
'''
self._previous_settings = self.settings_module
self.settings_module = settings_module
self.reconfigure() | python | def use_settings(self, settings_module):
'''
Useful for tests for overriding current settings manually
'''
self._previous_settings = self.settings_module
self.settings_module = settings_module
self.reconfigure() | [
"def",
"use_settings",
"(",
"self",
",",
"settings_module",
")",
":",
"self",
".",
"_previous_settings",
"=",
"self",
".",
"settings_module",
"self",
".",
"settings_module",
"=",
"settings_module",
"self",
".",
"reconfigure",
"(",
")"
] | Useful for tests for overriding current settings manually | [
"Useful",
"for",
"tests",
"for",
"overriding",
"current",
"settings",
"manually"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/config/settingsmanager.py#L164-L170 |
michaelpb/omnic | omnic/config/settingsmanager.py | SettingsManager.use_settings_dict | def use_settings_dict(self, settings_dict):
'''
Slightly cleaner interface to override settings that autogenerates a
settings module based on a given dict.
'''
class SettingsDictModule:
__slots__ = tuple(key.upper() for key in settings_dict.keys())
settings_obj = SettingsDictModule()
for key, value in settings_dict.items():
setattr(settings_obj, key.upper(), value)
self.use_settings(settings_obj) | python | def use_settings_dict(self, settings_dict):
'''
Slightly cleaner interface to override settings that autogenerates a
settings module based on a given dict.
'''
class SettingsDictModule:
__slots__ = tuple(key.upper() for key in settings_dict.keys())
settings_obj = SettingsDictModule()
for key, value in settings_dict.items():
setattr(settings_obj, key.upper(), value)
self.use_settings(settings_obj) | [
"def",
"use_settings_dict",
"(",
"self",
",",
"settings_dict",
")",
":",
"class",
"SettingsDictModule",
":",
"__slots__",
"=",
"tuple",
"(",
"key",
".",
"upper",
"(",
")",
"for",
"key",
"in",
"settings_dict",
".",
"keys",
"(",
")",
")",
"settings_obj",
"="... | Slightly cleaner interface to override settings that autogenerates a
settings module based on a given dict. | [
"Slightly",
"cleaner",
"interface",
"to",
"override",
"settings",
"that",
"autogenerates",
"a",
"settings",
"module",
"based",
"on",
"a",
"given",
"dict",
"."
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/config/settingsmanager.py#L172-L182 |
michaelpb/omnic | omnic/config/settingsmanager.py | SettingsManager.import_path_to_absolute_path | def import_path_to_absolute_path(import_path, file_marker):
'''
Given a Python import path, convert to a likely absolute filesystem
path, by searching for the given filename marker (such as
'package.json' or '__init__.py') through the Python system path. Do not
return given filename.
'''
path_fragment = import_path.replace('.', os.path.sep)
path_suffix = os.path.join(path_fragment, file_marker)
for path_base in sys.path:
path = os.path.join(path_base, path_suffix)
if os.path.exists(path):
return os.path.join(path_base, path_fragment)
msg = 'Cannot find import path: %s, %s'
raise ConfigurationError(msg % (import_path, file_marker)) | python | def import_path_to_absolute_path(import_path, file_marker):
'''
Given a Python import path, convert to a likely absolute filesystem
path, by searching for the given filename marker (such as
'package.json' or '__init__.py') through the Python system path. Do not
return given filename.
'''
path_fragment = import_path.replace('.', os.path.sep)
path_suffix = os.path.join(path_fragment, file_marker)
for path_base in sys.path:
path = os.path.join(path_base, path_suffix)
if os.path.exists(path):
return os.path.join(path_base, path_fragment)
msg = 'Cannot find import path: %s, %s'
raise ConfigurationError(msg % (import_path, file_marker)) | [
"def",
"import_path_to_absolute_path",
"(",
"import_path",
",",
"file_marker",
")",
":",
"path_fragment",
"=",
"import_path",
".",
"replace",
"(",
"'.'",
",",
"os",
".",
"path",
".",
"sep",
")",
"path_suffix",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pat... | Given a Python import path, convert to a likely absolute filesystem
path, by searching for the given filename marker (such as
'package.json' or '__init__.py') through the Python system path. Do not
return given filename. | [
"Given",
"a",
"Python",
"import",
"path",
"convert",
"to",
"a",
"likely",
"absolute",
"filesystem",
"path",
"by",
"searching",
"for",
"the",
"given",
"filename",
"marker",
"(",
"such",
"as",
"package",
".",
"json",
"or",
"__init__",
".",
"py",
")",
"throug... | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/config/settingsmanager.py#L192-L206 |
BoGoEngine/bogo-python | bogo/core.py | get_telex_definition | def get_telex_definition(w_shorthand=True, brackets_shorthand=True):
"""Create a definition dictionary for the TELEX input method
Args:
w_shorthand (optional): allow a stand-alone w to be
interpreted as an ư. Default to True.
brackets_shorthand (optional, True): allow typing ][ as
shorthand for ươ. Default to True.
Returns a dictionary to be passed into process_key().
"""
telex = {
"a": "a^",
"o": "o^",
"e": "e^",
"w": ["u*", "o*", "a+"],
"d": "d-",
"f": "\\",
"s": "/",
"r": "?",
"x": "~",
"j": ".",
}
if w_shorthand:
telex["w"].append('<ư')
if brackets_shorthand:
telex.update({
"]": "<ư",
"[": "<ơ",
"}": "<Ư",
"{": "<Ơ"
})
return telex | python | def get_telex_definition(w_shorthand=True, brackets_shorthand=True):
"""Create a definition dictionary for the TELEX input method
Args:
w_shorthand (optional): allow a stand-alone w to be
interpreted as an ư. Default to True.
brackets_shorthand (optional, True): allow typing ][ as
shorthand for ươ. Default to True.
Returns a dictionary to be passed into process_key().
"""
telex = {
"a": "a^",
"o": "o^",
"e": "e^",
"w": ["u*", "o*", "a+"],
"d": "d-",
"f": "\\",
"s": "/",
"r": "?",
"x": "~",
"j": ".",
}
if w_shorthand:
telex["w"].append('<ư')
if brackets_shorthand:
telex.update({
"]": "<ư",
"[": "<ơ",
"}": "<Ư",
"{": "<Ơ"
})
return telex | [
"def",
"get_telex_definition",
"(",
"w_shorthand",
"=",
"True",
",",
"brackets_shorthand",
"=",
"True",
")",
":",
"telex",
"=",
"{",
"\"a\"",
":",
"\"a^\"",
",",
"\"o\"",
":",
"\"o^\"",
",",
"\"e\"",
":",
"\"e^\"",
",",
"\"w\"",
":",
"[",
"\"u*\"",
",",
... | Create a definition dictionary for the TELEX input method
Args:
w_shorthand (optional): allow a stand-alone w to be
interpreted as an ư. Default to True.
brackets_shorthand (optional, True): allow typing ][ as
shorthand for ươ. Default to True.
Returns a dictionary to be passed into process_key(). | [
"Create",
"a",
"definition",
"dictionary",
"for",
"the",
"TELEX",
"input",
"method"
] | train | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/core.py#L46-L81 |
BoGoEngine/bogo-python | bogo/core.py | process_sequence | def process_sequence(sequence,
rules=None,
skip_non_vietnamese=True):
"""\
Convert a key sequence into a Vietnamese string with diacritical marks.
Args:
rules (optional): see docstring for process_key().
skip_non_vietnamese (optional): see docstring for process_key().
It even supports continous key sequences connected by separators.
i.e. process_sequence('con meof.ddieen') should work.
"""
result = ""
raw = result
result_parts = []
if rules is None:
rules = get_telex_definition()
accepted_chars = _accepted_chars(rules)
for key in sequence:
if key not in accepted_chars:
result_parts.append(result)
result_parts.append(key)
result = ""
raw = ""
else:
result, raw = process_key(
string=result,
key=key,
fallback_sequence=raw,
rules=rules,
skip_non_vietnamese=skip_non_vietnamese)
result_parts.append(result)
return ''.join(result_parts) | python | def process_sequence(sequence,
rules=None,
skip_non_vietnamese=True):
"""\
Convert a key sequence into a Vietnamese string with diacritical marks.
Args:
rules (optional): see docstring for process_key().
skip_non_vietnamese (optional): see docstring for process_key().
It even supports continous key sequences connected by separators.
i.e. process_sequence('con meof.ddieen') should work.
"""
result = ""
raw = result
result_parts = []
if rules is None:
rules = get_telex_definition()
accepted_chars = _accepted_chars(rules)
for key in sequence:
if key not in accepted_chars:
result_parts.append(result)
result_parts.append(key)
result = ""
raw = ""
else:
result, raw = process_key(
string=result,
key=key,
fallback_sequence=raw,
rules=rules,
skip_non_vietnamese=skip_non_vietnamese)
result_parts.append(result)
return ''.join(result_parts) | [
"def",
"process_sequence",
"(",
"sequence",
",",
"rules",
"=",
"None",
",",
"skip_non_vietnamese",
"=",
"True",
")",
":",
"result",
"=",
"\"\"",
"raw",
"=",
"result",
"result_parts",
"=",
"[",
"]",
"if",
"rules",
"is",
"None",
":",
"rules",
"=",
"get_tel... | \
Convert a key sequence into a Vietnamese string with diacritical marks.
Args:
rules (optional): see docstring for process_key().
skip_non_vietnamese (optional): see docstring for process_key().
It even supports continous key sequences connected by separators.
i.e. process_sequence('con meof.ddieen') should work. | [
"\\",
"Convert",
"a",
"key",
"sequence",
"into",
"a",
"Vietnamese",
"string",
"with",
"diacritical",
"marks",
"."
] | train | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/core.py#L114-L150 |
BoGoEngine/bogo-python | bogo/core.py | process_key | def process_key(string, key,
fallback_sequence="", rules=None,
skip_non_vietnamese=True):
"""Process a keystroke.
Args:
string: The previously processed string or "".
key: The keystroke.
fallback_sequence: The previous keystrokes.
rules (optional): A dictionary listing
transformation rules. Defaults to get_telex_definition().
skip_non_vietnamese (optional): Whether to skip results that
doesn't seem like Vietnamese. Defaults to True.
Returns a tuple. The first item of which is the processed
Vietnamese string, the second item is the next fallback sequence.
The two items are to be fed back into the next call of process_key()
as `string` and `fallback_sequence`. If `skip_non_vietnamese` is
True and the resulting string doesn't look like Vietnamese,
both items contain the `fallback_sequence`.
>>> process_key('a', 'a', 'a')
(â, aa)
Note that when a key is an undo key, it won't get appended to
`fallback_sequence`.
>>> process_key('â', 'a', 'aa')
(aa, aa)
`rules` is a dictionary that maps keystrokes to
their effect string. The effects can be one of the following:
'a^': a with circumflex (â), only affect an existing 'a family'
'a+': a with breve (ă), only affect an existing 'a family'
'e^': e with circumflex (ê), only affect an existing 'e family'
'o^': o with circumflex (ô), only affect an existing 'o family'
'o*': o with horn (ơ), only affect an existing 'o family'
'd-': d with bar (đ), only affect an existing 'd'
'/': acute (sắc), affect an existing vowel
'\': grave (huyền), affect an existing vowel
'?': hook (hỏi), affect an existing vowel
'~': tilde (ngã), affect an existing vowel
'.': dot (nặng), affect an existing vowel
'<ư': append ư
'<ơ': append ơ
A keystroke entry can have multiple effects, in which case the
dictionary entry's value should be a list of the possible
effect strings. Although you should try to avoid this if
you are defining a custom input method rule.
"""
# TODO Figure out a way to remove the `string` argument. Perhaps only the
# key sequence is needed?
def default_return():
return string + key, fallback_sequence + key
if rules is None:
rules = get_telex_definition()
comps = utils.separate(string)
# if not _is_processable(comps):
# return default_return()
# Find all possible transformations this keypress can generate
trans_list = _get_transformation_list(
key, rules, fallback_sequence)
# Then apply them one by one
new_comps = list(comps)
for trans in trans_list:
new_comps = _transform(new_comps, trans)
if new_comps == comps:
tmp = list(new_comps)
# If none of the transformations (if any) work
# then this keystroke is probably an undo key.
if _can_undo(new_comps, trans_list):
# The prefix "_" means undo.
for trans in map(lambda x: "_" + x, trans_list):
new_comps = _transform(new_comps, trans)
# Undoing the w key with the TELEX input method with the
# w:<ư extension requires some care.
#
# The input (ư, w) should be undone as w
# on the other hand, (ư, uw) should return uw.
#
# _transform() is not aware of the 2 ways to generate
# ư in TELEX and always think ư was created by uw.
# Therefore, after calling _transform() to undo ư,
# we always get ['', 'u', ''].
#
# So we have to clean it up a bit.
def is_telex_like():
return '<ư' in rules["w"]
def undone_vowel_ends_with_u():
return new_comps[1] and new_comps[1][-1].lower() == "u"
def not_first_key_press():
return len(fallback_sequence) >= 1
def user_typed_ww():
return (fallback_sequence[-1:]+key).lower() == "ww"
def user_didnt_type_uww():
return not (len(fallback_sequence) >= 2 and
fallback_sequence[-2].lower() == "u")
if is_telex_like() and \
not_first_key_press() and \
undone_vowel_ends_with_u() and \
user_typed_ww() and \
user_didnt_type_uww():
# The vowel part of new_comps is supposed to end with
# u now. That u should be removed.
new_comps[1] = new_comps[1][:-1]
if tmp == new_comps:
fallback_sequence += key
new_comps = utils.append_comps(new_comps, key)
else:
fallback_sequence += key
if skip_non_vietnamese is True and key.isalpha() and \
not is_valid_combination(new_comps, final_form=False):
result = fallback_sequence, fallback_sequence
else:
result = utils.join(new_comps), fallback_sequence
return result | python | def process_key(string, key,
fallback_sequence="", rules=None,
skip_non_vietnamese=True):
"""Process a keystroke.
Args:
string: The previously processed string or "".
key: The keystroke.
fallback_sequence: The previous keystrokes.
rules (optional): A dictionary listing
transformation rules. Defaults to get_telex_definition().
skip_non_vietnamese (optional): Whether to skip results that
doesn't seem like Vietnamese. Defaults to True.
Returns a tuple. The first item of which is the processed
Vietnamese string, the second item is the next fallback sequence.
The two items are to be fed back into the next call of process_key()
as `string` and `fallback_sequence`. If `skip_non_vietnamese` is
True and the resulting string doesn't look like Vietnamese,
both items contain the `fallback_sequence`.
>>> process_key('a', 'a', 'a')
(â, aa)
Note that when a key is an undo key, it won't get appended to
`fallback_sequence`.
>>> process_key('â', 'a', 'aa')
(aa, aa)
`rules` is a dictionary that maps keystrokes to
their effect string. The effects can be one of the following:
'a^': a with circumflex (â), only affect an existing 'a family'
'a+': a with breve (ă), only affect an existing 'a family'
'e^': e with circumflex (ê), only affect an existing 'e family'
'o^': o with circumflex (ô), only affect an existing 'o family'
'o*': o with horn (ơ), only affect an existing 'o family'
'd-': d with bar (đ), only affect an existing 'd'
'/': acute (sắc), affect an existing vowel
'\': grave (huyền), affect an existing vowel
'?': hook (hỏi), affect an existing vowel
'~': tilde (ngã), affect an existing vowel
'.': dot (nặng), affect an existing vowel
'<ư': append ư
'<ơ': append ơ
A keystroke entry can have multiple effects, in which case the
dictionary entry's value should be a list of the possible
effect strings. Although you should try to avoid this if
you are defining a custom input method rule.
"""
# TODO Figure out a way to remove the `string` argument. Perhaps only the
# key sequence is needed?
def default_return():
return string + key, fallback_sequence + key
if rules is None:
rules = get_telex_definition()
comps = utils.separate(string)
# if not _is_processable(comps):
# return default_return()
# Find all possible transformations this keypress can generate
trans_list = _get_transformation_list(
key, rules, fallback_sequence)
# Then apply them one by one
new_comps = list(comps)
for trans in trans_list:
new_comps = _transform(new_comps, trans)
if new_comps == comps:
tmp = list(new_comps)
# If none of the transformations (if any) work
# then this keystroke is probably an undo key.
if _can_undo(new_comps, trans_list):
# The prefix "_" means undo.
for trans in map(lambda x: "_" + x, trans_list):
new_comps = _transform(new_comps, trans)
# Undoing the w key with the TELEX input method with the
# w:<ư extension requires some care.
#
# The input (ư, w) should be undone as w
# on the other hand, (ư, uw) should return uw.
#
# _transform() is not aware of the 2 ways to generate
# ư in TELEX and always think ư was created by uw.
# Therefore, after calling _transform() to undo ư,
# we always get ['', 'u', ''].
#
# So we have to clean it up a bit.
def is_telex_like():
return '<ư' in rules["w"]
def undone_vowel_ends_with_u():
return new_comps[1] and new_comps[1][-1].lower() == "u"
def not_first_key_press():
return len(fallback_sequence) >= 1
def user_typed_ww():
return (fallback_sequence[-1:]+key).lower() == "ww"
def user_didnt_type_uww():
return not (len(fallback_sequence) >= 2 and
fallback_sequence[-2].lower() == "u")
if is_telex_like() and \
not_first_key_press() and \
undone_vowel_ends_with_u() and \
user_typed_ww() and \
user_didnt_type_uww():
# The vowel part of new_comps is supposed to end with
# u now. That u should be removed.
new_comps[1] = new_comps[1][:-1]
if tmp == new_comps:
fallback_sequence += key
new_comps = utils.append_comps(new_comps, key)
else:
fallback_sequence += key
if skip_non_vietnamese is True and key.isalpha() and \
not is_valid_combination(new_comps, final_form=False):
result = fallback_sequence, fallback_sequence
else:
result = utils.join(new_comps), fallback_sequence
return result | [
"def",
"process_key",
"(",
"string",
",",
"key",
",",
"fallback_sequence",
"=",
"\"\"",
",",
"rules",
"=",
"None",
",",
"skip_non_vietnamese",
"=",
"True",
")",
":",
"# TODO Figure out a way to remove the `string` argument. Perhaps only the",
"# key sequence is needed?... | Process a keystroke.
Args:
string: The previously processed string or "".
key: The keystroke.
fallback_sequence: The previous keystrokes.
rules (optional): A dictionary listing
transformation rules. Defaults to get_telex_definition().
skip_non_vietnamese (optional): Whether to skip results that
doesn't seem like Vietnamese. Defaults to True.
Returns a tuple. The first item of which is the processed
Vietnamese string, the second item is the next fallback sequence.
The two items are to be fed back into the next call of process_key()
as `string` and `fallback_sequence`. If `skip_non_vietnamese` is
True and the resulting string doesn't look like Vietnamese,
both items contain the `fallback_sequence`.
>>> process_key('a', 'a', 'a')
(â, aa)
Note that when a key is an undo key, it won't get appended to
`fallback_sequence`.
>>> process_key('â', 'a', 'aa')
(aa, aa)
`rules` is a dictionary that maps keystrokes to
their effect string. The effects can be one of the following:
'a^': a with circumflex (â), only affect an existing 'a family'
'a+': a with breve (ă), only affect an existing 'a family'
'e^': e with circumflex (ê), only affect an existing 'e family'
'o^': o with circumflex (ô), only affect an existing 'o family'
'o*': o with horn (ơ), only affect an existing 'o family'
'd-': d with bar (đ), only affect an existing 'd'
'/': acute (sắc), affect an existing vowel
'\': grave (huyền), affect an existing vowel
'?': hook (hỏi), affect an existing vowel
'~': tilde (ngã), affect an existing vowel
'.': dot (nặng), affect an existing vowel
'<ư': append ư
'<ơ': append ơ
A keystroke entry can have multiple effects, in which case the
dictionary entry's value should be a list of the possible
effect strings. Although you should try to avoid this if
you are defining a custom input method rule. | [
"Process",
"a",
"keystroke",
"."
] | train | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/core.py#L153-L286 |
BoGoEngine/bogo-python | bogo/core.py | _get_transformation_list | def _get_transformation_list(key, im, fallback_sequence):
"""
Return the list of transformations inferred from the entered key. The
map between transform types and keys is given by module
bogo_config (if exists) or by variable simple_telex_im
if entered key is not in im, return "+key", meaning appending
the entered key to current text
"""
# if key in im:
# lkey = key
# else:
# lkey = key.lower()
lkey = key.lower()
if lkey in im:
if isinstance(im[lkey], list):
trans_list = im[lkey]
else:
trans_list = [im[lkey]]
for i, trans in enumerate(trans_list):
if trans[0] == '<' and key.isalpha():
trans_list[i] = trans[0] + \
utils.change_case(trans[1], int(key.isupper()))
if trans_list == ['_']:
if len(fallback_sequence) >= 2:
# TODO Use takewhile()/dropwhile() to process the last IM keypress
# instead of assuming it's the last key in fallback_sequence.
t = list(map(lambda x: "_" + x,
_get_transformation_list(fallback_sequence[-2], im,
fallback_sequence[:-1])))
# print(t)
trans_list = t
# else:
# trans_list = ['+' + key]
return trans_list
else:
return ['+' + key] | python | def _get_transformation_list(key, im, fallback_sequence):
"""
Return the list of transformations inferred from the entered key. The
map between transform types and keys is given by module
bogo_config (if exists) or by variable simple_telex_im
if entered key is not in im, return "+key", meaning appending
the entered key to current text
"""
# if key in im:
# lkey = key
# else:
# lkey = key.lower()
lkey = key.lower()
if lkey in im:
if isinstance(im[lkey], list):
trans_list = im[lkey]
else:
trans_list = [im[lkey]]
for i, trans in enumerate(trans_list):
if trans[0] == '<' and key.isalpha():
trans_list[i] = trans[0] + \
utils.change_case(trans[1], int(key.isupper()))
if trans_list == ['_']:
if len(fallback_sequence) >= 2:
# TODO Use takewhile()/dropwhile() to process the last IM keypress
# instead of assuming it's the last key in fallback_sequence.
t = list(map(lambda x: "_" + x,
_get_transformation_list(fallback_sequence[-2], im,
fallback_sequence[:-1])))
# print(t)
trans_list = t
# else:
# trans_list = ['+' + key]
return trans_list
else:
return ['+' + key] | [
"def",
"_get_transformation_list",
"(",
"key",
",",
"im",
",",
"fallback_sequence",
")",
":",
"# if key in im:",
"# lkey = key",
"# else:",
"# lkey = key.lower()",
"lkey",
"=",
"key",
".",
"lower",
"(",
")",
"if",
"lkey",
"in",
"im",
":",
"if",
"isinstan... | Return the list of transformations inferred from the entered key. The
map between transform types and keys is given by module
bogo_config (if exists) or by variable simple_telex_im
if entered key is not in im, return "+key", meaning appending
the entered key to current text | [
"Return",
"the",
"list",
"of",
"transformations",
"inferred",
"from",
"the",
"entered",
"key",
".",
"The",
"map",
"between",
"transform",
"types",
"and",
"keys",
"is",
"given",
"by",
"module",
"bogo_config",
"(",
"if",
"exists",
")",
"or",
"by",
"variable",
... | train | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/core.py#L289-L329 |
BoGoEngine/bogo-python | bogo/core.py | _get_action | def _get_action(trans):
"""
Return the action inferred from the transformation `trans`.
and the parameter going with this action
An _Action.ADD_MARK goes with a Mark
while an _Action.ADD_ACCENT goes with an Accent
"""
# TODO: VIQR-like convention
mark_action = {
'^': (_Action.ADD_MARK, Mark.HAT),
'+': (_Action.ADD_MARK, Mark.BREVE),
'*': (_Action.ADD_MARK, Mark.HORN),
'-': (_Action.ADD_MARK, Mark.BAR),
}
accent_action = {
'\\': (_Action.ADD_ACCENT, Accent.GRAVE),
'/': (_Action.ADD_ACCENT, Accent.ACUTE),
'?': (_Action.ADD_ACCENT, Accent.HOOK),
'~': (_Action.ADD_ACCENT, Accent.TIDLE),
'.': (_Action.ADD_ACCENT, Accent.DOT),
}
if trans[0] in ('<', '+'):
return _Action.ADD_CHAR, trans[1]
if trans[0] == "_":
return _Action.UNDO, trans[1:]
if len(trans) == 2:
return mark_action[trans[1]]
else:
return accent_action[trans[0]] | python | def _get_action(trans):
"""
Return the action inferred from the transformation `trans`.
and the parameter going with this action
An _Action.ADD_MARK goes with a Mark
while an _Action.ADD_ACCENT goes with an Accent
"""
# TODO: VIQR-like convention
mark_action = {
'^': (_Action.ADD_MARK, Mark.HAT),
'+': (_Action.ADD_MARK, Mark.BREVE),
'*': (_Action.ADD_MARK, Mark.HORN),
'-': (_Action.ADD_MARK, Mark.BAR),
}
accent_action = {
'\\': (_Action.ADD_ACCENT, Accent.GRAVE),
'/': (_Action.ADD_ACCENT, Accent.ACUTE),
'?': (_Action.ADD_ACCENT, Accent.HOOK),
'~': (_Action.ADD_ACCENT, Accent.TIDLE),
'.': (_Action.ADD_ACCENT, Accent.DOT),
}
if trans[0] in ('<', '+'):
return _Action.ADD_CHAR, trans[1]
if trans[0] == "_":
return _Action.UNDO, trans[1:]
if len(trans) == 2:
return mark_action[trans[1]]
else:
return accent_action[trans[0]] | [
"def",
"_get_action",
"(",
"trans",
")",
":",
"# TODO: VIQR-like convention",
"mark_action",
"=",
"{",
"'^'",
":",
"(",
"_Action",
".",
"ADD_MARK",
",",
"Mark",
".",
"HAT",
")",
",",
"'+'",
":",
"(",
"_Action",
".",
"ADD_MARK",
",",
"Mark",
".",
"BREVE",... | Return the action inferred from the transformation `trans`.
and the parameter going with this action
An _Action.ADD_MARK goes with a Mark
while an _Action.ADD_ACCENT goes with an Accent | [
"Return",
"the",
"action",
"inferred",
"from",
"the",
"transformation",
"trans",
".",
"and",
"the",
"parameter",
"going",
"with",
"this",
"action",
"An",
"_Action",
".",
"ADD_MARK",
"goes",
"with",
"a",
"Mark",
"while",
"an",
"_Action",
".",
"ADD_ACCENT",
"g... | train | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/core.py#L332-L362 |
BoGoEngine/bogo-python | bogo/core.py | _transform | def _transform(comps, trans):
"""
Transform the given string with transform type trans
"""
logging.debug("== In _transform(%s, %s) ==", comps, trans)
components = list(comps)
action, parameter = _get_action(trans)
if action == _Action.ADD_MARK and \
components[2] == "" and \
mark.strip(components[1]).lower() in ['oe', 'oa'] and trans == "o^":
action, parameter = _Action.ADD_CHAR, trans[0]
if action == _Action.ADD_ACCENT:
logging.debug("add_accent(%s, %s)", components, parameter)
components = accent.add_accent(components, parameter)
elif action == _Action.ADD_MARK and mark.is_valid_mark(components, trans):
logging.debug("add_mark(%s, %s)", components, parameter)
components = mark.add_mark(components, parameter)
# Handle uơ in "huơ", "thuở", "quở"
# If the current word has no last consonant and the first consonant
# is one of "h", "th" and the vowel is "ươ" then change the vowel into
# "uơ", keeping case and accent. If an alphabet character is then added
# into the word then change back to "ươ".
#
# NOTE: In the dictionary, these are the only words having this strange
# vowel so we don't need to worry about other cases.
if accent.remove_accent_string(components[1]).lower() == "ươ" and \
not components[2] and components[0].lower() in ["", "h", "th", "kh"]:
# Backup accents
ac = accent.get_accent_string(components[1])
components[1] = ("u", "U")[components[1][0].isupper()] + components[1][1]
components = accent.add_accent(components, ac)
elif action == _Action.ADD_CHAR:
if trans[0] == "<":
if not components[2]:
# Only allow ư, ơ or ươ sitting alone in the middle part
# and ['g', 'i', '']. If we want to type giowf = 'giờ', separate()
# will create ['g', 'i', '']. Therefore we have to allow
# components[1] == 'i'.
if (components[0].lower(), components[1].lower()) == ('g', 'i'):
components[0] += components[1]
components[1] = ''
if not components[1] or \
(components[1].lower(), trans[1].lower()) == ('ư', 'ơ'):
components[1] += trans[1]
else:
components = utils.append_comps(components, parameter)
if parameter.isalpha() and \
accent.remove_accent_string(components[1]).lower().startswith("uơ"):
ac = accent.get_accent_string(components[1])
components[1] = ('ư', 'Ư')[components[1][0].isupper()] + \
('ơ', 'Ơ')[components[1][1].isupper()] + components[1][2:]
components = accent.add_accent(components, ac)
elif action == _Action.UNDO:
components = _reverse(components, trans[1:])
if action == _Action.ADD_MARK or (action == _Action.ADD_CHAR and parameter.isalpha()):
# If there is any accent, remove and reapply it
# because it is likely to be misplaced in previous transformations
ac = accent.get_accent_string(components[1])
if ac != accent.Accent.NONE:
components = accent.add_accent(components, Accent.NONE)
components = accent.add_accent(components, ac)
logging.debug("After transform: %s", components)
return components | python | def _transform(comps, trans):
"""
Transform the given string with transform type trans
"""
logging.debug("== In _transform(%s, %s) ==", comps, trans)
components = list(comps)
action, parameter = _get_action(trans)
if action == _Action.ADD_MARK and \
components[2] == "" and \
mark.strip(components[1]).lower() in ['oe', 'oa'] and trans == "o^":
action, parameter = _Action.ADD_CHAR, trans[0]
if action == _Action.ADD_ACCENT:
logging.debug("add_accent(%s, %s)", components, parameter)
components = accent.add_accent(components, parameter)
elif action == _Action.ADD_MARK and mark.is_valid_mark(components, trans):
logging.debug("add_mark(%s, %s)", components, parameter)
components = mark.add_mark(components, parameter)
# Handle uơ in "huơ", "thuở", "quở"
# If the current word has no last consonant and the first consonant
# is one of "h", "th" and the vowel is "ươ" then change the vowel into
# "uơ", keeping case and accent. If an alphabet character is then added
# into the word then change back to "ươ".
#
# NOTE: In the dictionary, these are the only words having this strange
# vowel so we don't need to worry about other cases.
if accent.remove_accent_string(components[1]).lower() == "ươ" and \
not components[2] and components[0].lower() in ["", "h", "th", "kh"]:
# Backup accents
ac = accent.get_accent_string(components[1])
components[1] = ("u", "U")[components[1][0].isupper()] + components[1][1]
components = accent.add_accent(components, ac)
elif action == _Action.ADD_CHAR:
if trans[0] == "<":
if not components[2]:
# Only allow ư, ơ or ươ sitting alone in the middle part
# and ['g', 'i', '']. If we want to type giowf = 'giờ', separate()
# will create ['g', 'i', '']. Therefore we have to allow
# components[1] == 'i'.
if (components[0].lower(), components[1].lower()) == ('g', 'i'):
components[0] += components[1]
components[1] = ''
if not components[1] or \
(components[1].lower(), trans[1].lower()) == ('ư', 'ơ'):
components[1] += trans[1]
else:
components = utils.append_comps(components, parameter)
if parameter.isalpha() and \
accent.remove_accent_string(components[1]).lower().startswith("uơ"):
ac = accent.get_accent_string(components[1])
components[1] = ('ư', 'Ư')[components[1][0].isupper()] + \
('ơ', 'Ơ')[components[1][1].isupper()] + components[1][2:]
components = accent.add_accent(components, ac)
elif action == _Action.UNDO:
components = _reverse(components, trans[1:])
if action == _Action.ADD_MARK or (action == _Action.ADD_CHAR and parameter.isalpha()):
# If there is any accent, remove and reapply it
# because it is likely to be misplaced in previous transformations
ac = accent.get_accent_string(components[1])
if ac != accent.Accent.NONE:
components = accent.add_accent(components, Accent.NONE)
components = accent.add_accent(components, ac)
logging.debug("After transform: %s", components)
return components | [
"def",
"_transform",
"(",
"comps",
",",
"trans",
")",
":",
"logging",
".",
"debug",
"(",
"\"== In _transform(%s, %s) ==\"",
",",
"comps",
",",
"trans",
")",
"components",
"=",
"list",
"(",
"comps",
")",
"action",
",",
"parameter",
"=",
"_get_action",
"(",
... | Transform the given string with transform type trans | [
"Transform",
"the",
"given",
"string",
"with",
"transform",
"type",
"trans"
] | train | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/core.py#L365-L434 |
BoGoEngine/bogo-python | bogo/core.py | _reverse | def _reverse(components, trans):
"""
Reverse the effect of transformation 'trans' on 'components'
If the transformation does not affect the components, return the original
string.
"""
action, parameter = _get_action(trans)
comps = list(components)
string = utils.join(comps)
if action == _Action.ADD_CHAR and string[-1].lower() == parameter.lower():
if comps[2]:
i = 2
elif comps[1]:
i = 1
else:
i = 0
comps[i] = comps[i][:-1]
elif action == _Action.ADD_ACCENT:
comps = accent.add_accent(comps, Accent.NONE)
elif action == _Action.ADD_MARK:
if parameter == Mark.BAR:
comps[0] = comps[0][:-1] + \
mark.add_mark_char(comps[0][-1:], Mark.NONE)
else:
if mark.is_valid_mark(comps, trans):
comps[1] = "".join([mark.add_mark_char(c, Mark.NONE)
for c in comps[1]])
return comps | python | def _reverse(components, trans):
"""
Reverse the effect of transformation 'trans' on 'components'
If the transformation does not affect the components, return the original
string.
"""
action, parameter = _get_action(trans)
comps = list(components)
string = utils.join(comps)
if action == _Action.ADD_CHAR and string[-1].lower() == parameter.lower():
if comps[2]:
i = 2
elif comps[1]:
i = 1
else:
i = 0
comps[i] = comps[i][:-1]
elif action == _Action.ADD_ACCENT:
comps = accent.add_accent(comps, Accent.NONE)
elif action == _Action.ADD_MARK:
if parameter == Mark.BAR:
comps[0] = comps[0][:-1] + \
mark.add_mark_char(comps[0][-1:], Mark.NONE)
else:
if mark.is_valid_mark(comps, trans):
comps[1] = "".join([mark.add_mark_char(c, Mark.NONE)
for c in comps[1]])
return comps | [
"def",
"_reverse",
"(",
"components",
",",
"trans",
")",
":",
"action",
",",
"parameter",
"=",
"_get_action",
"(",
"trans",
")",
"comps",
"=",
"list",
"(",
"components",
")",
"string",
"=",
"utils",
".",
"join",
"(",
"comps",
")",
"if",
"action",
"==",... | Reverse the effect of transformation 'trans' on 'components'
If the transformation does not affect the components, return the original
string. | [
"Reverse",
"the",
"effect",
"of",
"transformation",
"trans",
"on",
"components",
"If",
"the",
"transformation",
"does",
"not",
"affect",
"the",
"components",
"return",
"the",
"original",
"string",
"."
] | train | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/core.py#L437-L466 |
BoGoEngine/bogo-python | bogo/core.py | _can_undo | def _can_undo(comps, trans_list):
"""
Return whether a components can be undone with one of the transformation in
trans_list.
"""
comps = list(comps)
accent_list = list(map(accent.get_accent_char, comps[1]))
mark_list = list(map(mark.get_mark_char, utils.join(comps)))
action_list = list(map(lambda x: _get_action(x), trans_list))
def atomic_check(action):
"""
Check if the `action` created one of the marks, accents, or characters
in `comps`.
"""
return (action[0] == _Action.ADD_ACCENT and action[1] in accent_list) \
or (action[0] == _Action.ADD_MARK and action[1] in mark_list) \
or (action[0] == _Action.ADD_CHAR and action[1] == \
accent.remove_accent_char(comps[1][-1])) # ơ, ư
return any(map(atomic_check, action_list)) | python | def _can_undo(comps, trans_list):
"""
Return whether a components can be undone with one of the transformation in
trans_list.
"""
comps = list(comps)
accent_list = list(map(accent.get_accent_char, comps[1]))
mark_list = list(map(mark.get_mark_char, utils.join(comps)))
action_list = list(map(lambda x: _get_action(x), trans_list))
def atomic_check(action):
"""
Check if the `action` created one of the marks, accents, or characters
in `comps`.
"""
return (action[0] == _Action.ADD_ACCENT and action[1] in accent_list) \
or (action[0] == _Action.ADD_MARK and action[1] in mark_list) \
or (action[0] == _Action.ADD_CHAR and action[1] == \
accent.remove_accent_char(comps[1][-1])) # ơ, ư
return any(map(atomic_check, action_list)) | [
"def",
"_can_undo",
"(",
"comps",
",",
"trans_list",
")",
":",
"comps",
"=",
"list",
"(",
"comps",
")",
"accent_list",
"=",
"list",
"(",
"map",
"(",
"accent",
".",
"get_accent_char",
",",
"comps",
"[",
"1",
"]",
")",
")",
"mark_list",
"=",
"list",
"(... | Return whether a components can be undone with one of the transformation in
trans_list. | [
"Return",
"whether",
"a",
"components",
"can",
"be",
"undone",
"with",
"one",
"of",
"the",
"transformation",
"in",
"trans_list",
"."
] | train | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/core.py#L469-L489 |
BoGoEngine/bogo-python | bogo/core.py | handle_backspace | def handle_backspace(converted_string, raw_sequence, im_rules=None):
"""
Returns a new raw_sequence after a backspace. This raw_sequence should
be pushed back to process_sequence().
"""
# I can't find a simple explanation for this, so
# I hope this example can help clarify it:
#
# handle_backspace(thương, thuwongw) -> thuwonw
# handle_backspace(thươn, thuwonw) -> thuwow
# handle_backspace(thươ, thuwow) -> thuw
# handle_backspace(thươ, thuw) -> th
#
# The algorithm for handle_backspace was contributed by @hainp.
if im_rules == None:
im_rules = get_telex_definition()
deleted_char = converted_string[-1]
_accent = accent.get_accent_char(deleted_char)
_mark = mark.get_mark_char(deleted_char)
if _mark or _accent:
# Find a sequence of IM keys at the end of
# raw_sequence
ime_keys_at_end = ""
len_raw_sequence = len(raw_sequence)
i = len_raw_sequence - 1
while i >= 0:
if raw_sequence[i] not in im_rules and \
raw_sequence[i] not in "aeiouyd":
i += 1
break
else:
ime_keys_at_end = raw_sequence[i] + ime_keys_at_end
i -= 1
# Try to find a subsequence from that sequence
# that can be converted to the deleted_char
k = 0
while k < len_raw_sequence:
if process_sequence(raw_sequence[i + k:], im_rules) == deleted_char:
# Delete that subsequence
raw_sequence = raw_sequence[:i + k]
break
k += 1
else:
index = raw_sequence.rfind(deleted_char)
raw_sequence = raw_sequence[:index] + raw_sequence[(index + 1):]
return raw_sequence | python | def handle_backspace(converted_string, raw_sequence, im_rules=None):
"""
Returns a new raw_sequence after a backspace. This raw_sequence should
be pushed back to process_sequence().
"""
# I can't find a simple explanation for this, so
# I hope this example can help clarify it:
#
# handle_backspace(thương, thuwongw) -> thuwonw
# handle_backspace(thươn, thuwonw) -> thuwow
# handle_backspace(thươ, thuwow) -> thuw
# handle_backspace(thươ, thuw) -> th
#
# The algorithm for handle_backspace was contributed by @hainp.
if im_rules == None:
im_rules = get_telex_definition()
deleted_char = converted_string[-1]
_accent = accent.get_accent_char(deleted_char)
_mark = mark.get_mark_char(deleted_char)
if _mark or _accent:
# Find a sequence of IM keys at the end of
# raw_sequence
ime_keys_at_end = ""
len_raw_sequence = len(raw_sequence)
i = len_raw_sequence - 1
while i >= 0:
if raw_sequence[i] not in im_rules and \
raw_sequence[i] not in "aeiouyd":
i += 1
break
else:
ime_keys_at_end = raw_sequence[i] + ime_keys_at_end
i -= 1
# Try to find a subsequence from that sequence
# that can be converted to the deleted_char
k = 0
while k < len_raw_sequence:
if process_sequence(raw_sequence[i + k:], im_rules) == deleted_char:
# Delete that subsequence
raw_sequence = raw_sequence[:i + k]
break
k += 1
else:
index = raw_sequence.rfind(deleted_char)
raw_sequence = raw_sequence[:index] + raw_sequence[(index + 1):]
return raw_sequence | [
"def",
"handle_backspace",
"(",
"converted_string",
",",
"raw_sequence",
",",
"im_rules",
"=",
"None",
")",
":",
"# I can't find a simple explanation for this, so",
"# I hope this example can help clarify it:",
"#",
"# handle_backspace(thương, thuwongw) -> thuwonw",
"# handle_backspa... | Returns a new raw_sequence after a backspace. This raw_sequence should
be pushed back to process_sequence(). | [
"Returns",
"a",
"new",
"raw_sequence",
"after",
"a",
"backspace",
".",
"This",
"raw_sequence",
"should",
"be",
"pushed",
"back",
"to",
"process_sequence",
"()",
"."
] | train | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/core.py#L492-L545 |
BoGoEngine/bogo-python | bogo/mark.py | get_mark_char | def get_mark_char(char):
"""
Get the mark of a single char, if any.
"""
char = accent.remove_accent_char(char.lower())
if char == "":
return Mark.NONE
if char == "đ":
return Mark.BAR
if char in "ă":
return Mark.BREVE
if char in "ơư":
return Mark.HORN
if char in "âêô":
return Mark.HAT
return Mark.NONE | python | def get_mark_char(char):
"""
Get the mark of a single char, if any.
"""
char = accent.remove_accent_char(char.lower())
if char == "":
return Mark.NONE
if char == "đ":
return Mark.BAR
if char in "ă":
return Mark.BREVE
if char in "ơư":
return Mark.HORN
if char in "âêô":
return Mark.HAT
return Mark.NONE | [
"def",
"get_mark_char",
"(",
"char",
")",
":",
"char",
"=",
"accent",
".",
"remove_accent_char",
"(",
"char",
".",
"lower",
"(",
")",
")",
"if",
"char",
"==",
"\"\"",
":",
"return",
"Mark",
".",
"NONE",
"if",
"char",
"==",
"\"đ\":",
"",
"return",
"Ma... | Get the mark of a single char, if any. | [
"Get",
"the",
"mark",
"of",
"a",
"single",
"char",
"if",
"any",
"."
] | train | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/mark.py#L50-L65 |
BoGoEngine/bogo-python | bogo/mark.py | add_mark_at | def add_mark_at(string, index, mark):
"""
Add mark to the index-th character of the given string. Return the new string after applying change.
Notice: index > 0
"""
if index == -1:
return string
# Python can handle the case which index is out of range of given string
return string[:index] + add_mark_char(string[index], mark) + string[index+1:] | python | def add_mark_at(string, index, mark):
"""
Add mark to the index-th character of the given string. Return the new string after applying change.
Notice: index > 0
"""
if index == -1:
return string
# Python can handle the case which index is out of range of given string
return string[:index] + add_mark_char(string[index], mark) + string[index+1:] | [
"def",
"add_mark_at",
"(",
"string",
",",
"index",
",",
"mark",
")",
":",
"if",
"index",
"==",
"-",
"1",
":",
"return",
"string",
"# Python can handle the case which index is out of range of given string",
"return",
"string",
"[",
":",
"index",
"]",
"+",
"add_mark... | Add mark to the index-th character of the given string. Return the new string after applying change.
Notice: index > 0 | [
"Add",
"mark",
"to",
"the",
"index",
"-",
"th",
"character",
"of",
"the",
"given",
"string",
".",
"Return",
"the",
"new",
"string",
"after",
"applying",
"change",
".",
"Notice",
":",
"index",
">",
"0"
] | train | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/mark.py#L100-L108 |
BoGoEngine/bogo-python | bogo/mark.py | add_mark_char | def add_mark_char(char, mark):
"""
Add mark to a single char.
"""
if char == "":
return ""
case = char.isupper()
ac = accent.get_accent_char(char)
char = accent.add_accent_char(char.lower(), Accent.NONE)
new_char = char
if mark == Mark.HAT:
if char in FAMILY_A:
new_char = "â"
elif char in FAMILY_O:
new_char = "ô"
elif char in FAMILY_E:
new_char = "ê"
elif mark == Mark.HORN:
if char in FAMILY_O:
new_char = "ơ"
elif char in FAMILY_U:
new_char = "ư"
elif mark == Mark.BREVE:
if char in FAMILY_A:
new_char = "ă"
elif mark == Mark.BAR:
if char in FAMILY_D:
new_char = "đ"
elif mark == Mark.NONE:
if char in FAMILY_A:
new_char = "a"
elif char in FAMILY_E:
new_char = "e"
elif char in FAMILY_O:
new_char = "o"
elif char in FAMILY_U:
new_char = "u"
elif char in FAMILY_D:
new_char = "d"
new_char = accent.add_accent_char(new_char, ac)
return utils.change_case(new_char, case) | python | def add_mark_char(char, mark):
"""
Add mark to a single char.
"""
if char == "":
return ""
case = char.isupper()
ac = accent.get_accent_char(char)
char = accent.add_accent_char(char.lower(), Accent.NONE)
new_char = char
if mark == Mark.HAT:
if char in FAMILY_A:
new_char = "â"
elif char in FAMILY_O:
new_char = "ô"
elif char in FAMILY_E:
new_char = "ê"
elif mark == Mark.HORN:
if char in FAMILY_O:
new_char = "ơ"
elif char in FAMILY_U:
new_char = "ư"
elif mark == Mark.BREVE:
if char in FAMILY_A:
new_char = "ă"
elif mark == Mark.BAR:
if char in FAMILY_D:
new_char = "đ"
elif mark == Mark.NONE:
if char in FAMILY_A:
new_char = "a"
elif char in FAMILY_E:
new_char = "e"
elif char in FAMILY_O:
new_char = "o"
elif char in FAMILY_U:
new_char = "u"
elif char in FAMILY_D:
new_char = "d"
new_char = accent.add_accent_char(new_char, ac)
return utils.change_case(new_char, case) | [
"def",
"add_mark_char",
"(",
"char",
",",
"mark",
")",
":",
"if",
"char",
"==",
"\"\"",
":",
"return",
"\"\"",
"case",
"=",
"char",
".",
"isupper",
"(",
")",
"ac",
"=",
"accent",
".",
"get_accent_char",
"(",
"char",
")",
"char",
"=",
"accent",
".",
... | Add mark to a single char. | [
"Add",
"mark",
"to",
"a",
"single",
"char",
"."
] | train | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/mark.py#L111-L152 |
BoGoEngine/bogo-python | bogo/mark.py | is_valid_mark | def is_valid_mark(comps, mark_trans):
"""
Check whether the mark given by mark_trans is valid to add to the components
"""
if mark_trans == "*_":
return True
components = list(comps)
if mark_trans[0] == 'd' and components[0] \
and components[0][-1].lower() in ("d", "đ"):
return True
elif components[1] != "" and \
strip(components[1]).lower().find(mark_trans[0]) != -1:
return True
else:
return False | python | def is_valid_mark(comps, mark_trans):
"""
Check whether the mark given by mark_trans is valid to add to the components
"""
if mark_trans == "*_":
return True
components = list(comps)
if mark_trans[0] == 'd' and components[0] \
and components[0][-1].lower() in ("d", "đ"):
return True
elif components[1] != "" and \
strip(components[1]).lower().find(mark_trans[0]) != -1:
return True
else:
return False | [
"def",
"is_valid_mark",
"(",
"comps",
",",
"mark_trans",
")",
":",
"if",
"mark_trans",
"==",
"\"*_\"",
":",
"return",
"True",
"components",
"=",
"list",
"(",
"comps",
")",
"if",
"mark_trans",
"[",
"0",
"]",
"==",
"'d'",
"and",
"components",
"[",
"0",
"... | Check whether the mark given by mark_trans is valid to add to the components | [
"Check",
"whether",
"the",
"mark",
"given",
"by",
"mark_trans",
"is",
"valid",
"to",
"add",
"to",
"the",
"components"
] | train | https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/mark.py#L155-L170 |
gmr/infoblox | infoblox/session.py | Session.delete | def delete(self, path):
"""Call the Infoblox device to delete the ref
:param str ref: The reference id
:rtype: requests.Response
"""
return self.session.delete(self._request_url(path),
auth=self.auth, verify=False) | python | def delete(self, path):
"""Call the Infoblox device to delete the ref
:param str ref: The reference id
:rtype: requests.Response
"""
return self.session.delete(self._request_url(path),
auth=self.auth, verify=False) | [
"def",
"delete",
"(",
"self",
",",
"path",
")",
":",
"return",
"self",
".",
"session",
".",
"delete",
"(",
"self",
".",
"_request_url",
"(",
"path",
")",
",",
"auth",
"=",
"self",
".",
"auth",
",",
"verify",
"=",
"False",
")"
] | Call the Infoblox device to delete the ref
:param str ref: The reference id
:rtype: requests.Response | [
"Call",
"the",
"Infoblox",
"device",
"to",
"delete",
"the",
"ref"
] | train | https://github.com/gmr/infoblox/blob/163dd9cff5f77c08751936c56aa8428acfd2d208/infoblox/session.py#L48-L56 |
gmr/infoblox | infoblox/session.py | Session.get | def get(self, path, data=None, return_fields=None):
"""Call the Infoblox device to get the obj for the data passed in
:param str obj_reference: The object reference data
:param dict data: The data for the get request
:rtype: requests.Response
"""
return self.session.get(self._request_url(path, return_fields),
data=json.dumps(data),
auth=self.auth, verify=False) | python | def get(self, path, data=None, return_fields=None):
"""Call the Infoblox device to get the obj for the data passed in
:param str obj_reference: The object reference data
:param dict data: The data for the get request
:rtype: requests.Response
"""
return self.session.get(self._request_url(path, return_fields),
data=json.dumps(data),
auth=self.auth, verify=False) | [
"def",
"get",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
",",
"return_fields",
"=",
"None",
")",
":",
"return",
"self",
".",
"session",
".",
"get",
"(",
"self",
".",
"_request_url",
"(",
"path",
",",
"return_fields",
")",
",",
"data",
"=",
... | Call the Infoblox device to get the obj for the data passed in
:param str obj_reference: The object reference data
:param dict data: The data for the get request
:rtype: requests.Response | [
"Call",
"the",
"Infoblox",
"device",
"to",
"get",
"the",
"obj",
"for",
"the",
"data",
"passed",
"in"
] | train | https://github.com/gmr/infoblox/blob/163dd9cff5f77c08751936c56aa8428acfd2d208/infoblox/session.py#L58-L68 |
gmr/infoblox | infoblox/session.py | Session.post | def post(self, path, data):
"""Call the Infoblox device to post the obj for the data passed in
:param str obj: The object type
:param dict data: The data for the post
:rtype: requests.Response
"""
LOGGER.debug('Posting data: %r', data)
return self.session.post(self._request_url(path),
data=json.dumps(data or {}),
headers=self.HEADERS, auth=self.auth,
verify=False) | python | def post(self, path, data):
"""Call the Infoblox device to post the obj for the data passed in
:param str obj: The object type
:param dict data: The data for the post
:rtype: requests.Response
"""
LOGGER.debug('Posting data: %r', data)
return self.session.post(self._request_url(path),
data=json.dumps(data or {}),
headers=self.HEADERS, auth=self.auth,
verify=False) | [
"def",
"post",
"(",
"self",
",",
"path",
",",
"data",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Posting data: %r'",
",",
"data",
")",
"return",
"self",
".",
"session",
".",
"post",
"(",
"self",
".",
"_request_url",
"(",
"path",
")",
",",
"data",
"=",
... | Call the Infoblox device to post the obj for the data passed in
:param str obj: The object type
:param dict data: The data for the post
:rtype: requests.Response | [
"Call",
"the",
"Infoblox",
"device",
"to",
"post",
"the",
"obj",
"for",
"the",
"data",
"passed",
"in"
] | train | https://github.com/gmr/infoblox/blob/163dd9cff5f77c08751936c56aa8428acfd2d208/infoblox/session.py#L70-L82 |
dailymuse/oz | oz/cli.py | main | def main():
"""Main entry-point for oz's cli"""
# Hack to make user code available for import
sys.path.append(".")
# Run the specified action
oz.initialize()
retr = optfn.run(list(oz._actions.values()))
if retr == optfn.ERROR_RETURN_CODE:
sys.exit(-1)
elif retr == None:
sys.exit(0)
elif isinstance(retr, int):
sys.exit(retr)
else:
raise Exception("Unexpected return value from action: %s" % retr) | python | def main():
"""Main entry-point for oz's cli"""
# Hack to make user code available for import
sys.path.append(".")
# Run the specified action
oz.initialize()
retr = optfn.run(list(oz._actions.values()))
if retr == optfn.ERROR_RETURN_CODE:
sys.exit(-1)
elif retr == None:
sys.exit(0)
elif isinstance(retr, int):
sys.exit(retr)
else:
raise Exception("Unexpected return value from action: %s" % retr) | [
"def",
"main",
"(",
")",
":",
"# Hack to make user code available for import",
"sys",
".",
"path",
".",
"append",
"(",
"\".\"",
")",
"# Run the specified action",
"oz",
".",
"initialize",
"(",
")",
"retr",
"=",
"optfn",
".",
"run",
"(",
"list",
"(",
"oz",
".... | Main entry-point for oz's cli | [
"Main",
"entry",
"-",
"point",
"for",
"oz",
"s",
"cli"
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/cli.py#L9-L26 |
biocore/burrito-fillings | bfillings/clearcut.py | build_tree_from_alignment | def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params={},\
working_dir='/tmp'):
"""Returns a tree from Alignment object aln.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one.
- Clearcut only accepts aligned sequences. Alignment object used to
handle unaligned sequences.
moltype: a cogent.core.moltype object.
- NOTE: If moltype = RNA, we must convert to DNA since Clearcut v1.0.8
gives incorrect results if RNA is passed in. 'U' is treated as an
incorrect character and is excluded from distance calculations.
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: dict of parameters to pass in to the Clearcut app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails.
"""
params['--out'] = get_tmp_filename(working_dir)
# Create instance of app controller, enable tree, disable alignment
app = Clearcut(InputHandler='_input_as_multiline_string', params=params, \
WorkingDir=working_dir, SuppressStdout=True,\
SuppressStderr=True)
#Input is an alignment
app.Parameters['-a'].on()
#Turn off input as distance matrix
app.Parameters['-d'].off()
#If moltype = RNA, we must convert to DNA.
if moltype == RNA:
moltype = DNA
if best_tree:
app.Parameters['-N'].on()
#Turn on correct moltype
moltype_string = moltype.label.upper()
app.Parameters[MOLTYPE_MAP[moltype_string]].on()
# Setup mapping. Clearcut clips identifiers. We will need to remap them.
# Clearcut only accepts aligned sequences. Let Alignment object handle
# unaligned sequences.
seq_aln = Alignment(aln,MolType=moltype)
#get int mapping
int_map, int_keys = seq_aln.getIntMap()
#create new Alignment object with int_map
int_map = Alignment(int_map)
# Collect result
result = app(int_map.toFasta())
# Build tree
tree = DndParser(result['Tree'].read(), constructor=PhyloNode)
for node in tree.tips():
node.Name = int_keys[node.Name]
# Clean up
result.cleanUp()
del(seq_aln, app, result, int_map, int_keys, params)
return tree | python | def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params={},\
working_dir='/tmp'):
"""Returns a tree from Alignment object aln.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one.
- Clearcut only accepts aligned sequences. Alignment object used to
handle unaligned sequences.
moltype: a cogent.core.moltype object.
- NOTE: If moltype = RNA, we must convert to DNA since Clearcut v1.0.8
gives incorrect results if RNA is passed in. 'U' is treated as an
incorrect character and is excluded from distance calculations.
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: dict of parameters to pass in to the Clearcut app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails.
"""
params['--out'] = get_tmp_filename(working_dir)
# Create instance of app controller, enable tree, disable alignment
app = Clearcut(InputHandler='_input_as_multiline_string', params=params, \
WorkingDir=working_dir, SuppressStdout=True,\
SuppressStderr=True)
#Input is an alignment
app.Parameters['-a'].on()
#Turn off input as distance matrix
app.Parameters['-d'].off()
#If moltype = RNA, we must convert to DNA.
if moltype == RNA:
moltype = DNA
if best_tree:
app.Parameters['-N'].on()
#Turn on correct moltype
moltype_string = moltype.label.upper()
app.Parameters[MOLTYPE_MAP[moltype_string]].on()
# Setup mapping. Clearcut clips identifiers. We will need to remap them.
# Clearcut only accepts aligned sequences. Let Alignment object handle
# unaligned sequences.
seq_aln = Alignment(aln,MolType=moltype)
#get int mapping
int_map, int_keys = seq_aln.getIntMap()
#create new Alignment object with int_map
int_map = Alignment(int_map)
# Collect result
result = app(int_map.toFasta())
# Build tree
tree = DndParser(result['Tree'].read(), constructor=PhyloNode)
for node in tree.tips():
node.Name = int_keys[node.Name]
# Clean up
result.cleanUp()
del(seq_aln, app, result, int_map, int_keys, params)
return tree | [
"def",
"build_tree_from_alignment",
"(",
"aln",
",",
"moltype",
"=",
"DNA",
",",
"best_tree",
"=",
"False",
",",
"params",
"=",
"{",
"}",
",",
"working_dir",
"=",
"'/tmp'",
")",
":",
"params",
"[",
"'--out'",
"]",
"=",
"get_tmp_filename",
"(",
"working_dir... | Returns a tree from Alignment object aln.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one.
- Clearcut only accepts aligned sequences. Alignment object used to
handle unaligned sequences.
moltype: a cogent.core.moltype object.
- NOTE: If moltype = RNA, we must convert to DNA since Clearcut v1.0.8
gives incorrect results if RNA is passed in. 'U' is treated as an
incorrect character and is excluded from distance calculations.
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: dict of parameters to pass in to the Clearcut app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails. | [
"Returns",
"a",
"tree",
"from",
"Alignment",
"object",
"aln",
"."
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clearcut.py#L226-L291 |
biocore/burrito-fillings | bfillings/clearcut.py | build_tree_from_distance_matrix | def build_tree_from_distance_matrix(matrix, best_tree=False, params={},\
working_dir='/tmp'):
"""Returns a tree from a distance matrix.
matrix: a square Dict2D object (cogent.util.dict2d)
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: dict of parameters to pass in to the Clearcut app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails.
"""
params['--out'] = get_tmp_filename(working_dir)
# Create instance of app controller, enable tree, disable alignment
app = Clearcut(InputHandler='_input_as_multiline_string', params=params, \
WorkingDir=working_dir, SuppressStdout=True,\
SuppressStderr=True)
#Turn off input as alignment
app.Parameters['-a'].off()
#Input is a distance matrix
app.Parameters['-d'].on()
if best_tree:
app.Parameters['-N'].on()
# Turn the dict2d object into the expected input format
matrix_input, int_keys = _matrix_input_from_dict2d(matrix)
# Collect result
result = app(matrix_input)
# Build tree
tree = DndParser(result['Tree'].read(), constructor=PhyloNode)
# reassign to original names
for node in tree.tips():
node.Name = int_keys[node.Name]
# Clean up
result.cleanUp()
del(app, result, params)
return tree | python | def build_tree_from_distance_matrix(matrix, best_tree=False, params={},\
working_dir='/tmp'):
"""Returns a tree from a distance matrix.
matrix: a square Dict2D object (cogent.util.dict2d)
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: dict of parameters to pass in to the Clearcut app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails.
"""
params['--out'] = get_tmp_filename(working_dir)
# Create instance of app controller, enable tree, disable alignment
app = Clearcut(InputHandler='_input_as_multiline_string', params=params, \
WorkingDir=working_dir, SuppressStdout=True,\
SuppressStderr=True)
#Turn off input as alignment
app.Parameters['-a'].off()
#Input is a distance matrix
app.Parameters['-d'].on()
if best_tree:
app.Parameters['-N'].on()
# Turn the dict2d object into the expected input format
matrix_input, int_keys = _matrix_input_from_dict2d(matrix)
# Collect result
result = app(matrix_input)
# Build tree
tree = DndParser(result['Tree'].read(), constructor=PhyloNode)
# reassign to original names
for node in tree.tips():
node.Name = int_keys[node.Name]
# Clean up
result.cleanUp()
del(app, result, params)
return tree | [
"def",
"build_tree_from_distance_matrix",
"(",
"matrix",
",",
"best_tree",
"=",
"False",
",",
"params",
"=",
"{",
"}",
",",
"working_dir",
"=",
"'/tmp'",
")",
":",
"params",
"[",
"'--out'",
"]",
"=",
"get_tmp_filename",
"(",
"working_dir",
")",
"# Create insta... | Returns a tree from a distance matrix.
matrix: a square Dict2D object (cogent.util.dict2d)
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: dict of parameters to pass in to the Clearcut app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails. | [
"Returns",
"a",
"tree",
"from",
"a",
"distance",
"matrix",
"."
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clearcut.py#L319-L364 |
biocore/burrito-fillings | bfillings/clearcut.py | _matrix_input_from_dict2d | def _matrix_input_from_dict2d(matrix):
"""makes input for running clearcut on a matrix from a dict2D object"""
#clearcut truncates names to 10 char- need to rename before and
#reassign after
#make a dict of env_index:full name
int_keys = dict([('env_' + str(i), k) for i,k in \
enumerate(sorted(matrix.keys()))])
#invert the dict
int_map = {}
for i in int_keys:
int_map[int_keys[i]] = i
#make a new dict2D object with the integer keys mapped to values instead of
#the original names
new_dists = []
for env1 in matrix:
for env2 in matrix[env1]:
new_dists.append((int_map[env1], int_map[env2], matrix[env1][env2]))
int_map_dists = Dict2D(new_dists)
#names will be fed into the phylipTable function - it is the int map names
names = sorted(int_map_dists.keys())
rows = []
#populated rows with values based on the order of names
#the following code will work for a square matrix only
for index, key1 in enumerate(names):
row = []
for key2 in names:
row.append(str(int_map_dists[key1][key2]))
rows.append(row)
input_matrix = phylipMatrix(rows, names)
#input needs a trailing whitespace or it will fail!
input_matrix += '\n'
return input_matrix, int_keys | python | def _matrix_input_from_dict2d(matrix):
"""makes input for running clearcut on a matrix from a dict2D object"""
#clearcut truncates names to 10 char- need to rename before and
#reassign after
#make a dict of env_index:full name
int_keys = dict([('env_' + str(i), k) for i,k in \
enumerate(sorted(matrix.keys()))])
#invert the dict
int_map = {}
for i in int_keys:
int_map[int_keys[i]] = i
#make a new dict2D object with the integer keys mapped to values instead of
#the original names
new_dists = []
for env1 in matrix:
for env2 in matrix[env1]:
new_dists.append((int_map[env1], int_map[env2], matrix[env1][env2]))
int_map_dists = Dict2D(new_dists)
#names will be fed into the phylipTable function - it is the int map names
names = sorted(int_map_dists.keys())
rows = []
#populated rows with values based on the order of names
#the following code will work for a square matrix only
for index, key1 in enumerate(names):
row = []
for key2 in names:
row.append(str(int_map_dists[key1][key2]))
rows.append(row)
input_matrix = phylipMatrix(rows, names)
#input needs a trailing whitespace or it will fail!
input_matrix += '\n'
return input_matrix, int_keys | [
"def",
"_matrix_input_from_dict2d",
"(",
"matrix",
")",
":",
"#clearcut truncates names to 10 char- need to rename before and",
"#reassign after",
"#make a dict of env_index:full name",
"int_keys",
"=",
"dict",
"(",
"[",
"(",
"'env_'",
"+",
"str",
"(",
"i",
")",
",",
"k",... | makes input for running clearcut on a matrix from a dict2D object | [
"makes",
"input",
"for",
"running",
"clearcut",
"on",
"a",
"matrix",
"from",
"a",
"dict2D",
"object"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clearcut.py#L366-L401 |
biocore/burrito-fillings | bfillings/clearcut.py | Clearcut._input_as_multiline_string | def _input_as_multiline_string(self, data):
"""Writes data to tempfile and sets -infile parameter
data -- list of lines
"""
if data:
self.Parameters['--in']\
.on(super(Clearcut,self)._input_as_multiline_string(data))
return '' | python | def _input_as_multiline_string(self, data):
"""Writes data to tempfile and sets -infile parameter
data -- list of lines
"""
if data:
self.Parameters['--in']\
.on(super(Clearcut,self)._input_as_multiline_string(data))
return '' | [
"def",
"_input_as_multiline_string",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
":",
"self",
".",
"Parameters",
"[",
"'--in'",
"]",
".",
"on",
"(",
"super",
"(",
"Clearcut",
",",
"self",
")",
".",
"_input_as_multiline_string",
"(",
"data",
")",
")... | Writes data to tempfile and sets -infile parameter
data -- list of lines | [
"Writes",
"data",
"to",
"tempfile",
"and",
"sets",
"-",
"infile",
"parameter"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clearcut.py#L126-L134 |
biocore/burrito-fillings | bfillings/clearcut.py | Clearcut._input_as_lines | def _input_as_lines(self,data):
"""Writes data to tempfile and sets -infile parameter
data -- list of lines, ready to be written to file
"""
if data:
self.Parameters['--in']\
.on(super(Clearcut,self)._input_as_lines(data))
return '' | python | def _input_as_lines(self,data):
"""Writes data to tempfile and sets -infile parameter
data -- list of lines, ready to be written to file
"""
if data:
self.Parameters['--in']\
.on(super(Clearcut,self)._input_as_lines(data))
return '' | [
"def",
"_input_as_lines",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
":",
"self",
".",
"Parameters",
"[",
"'--in'",
"]",
".",
"on",
"(",
"super",
"(",
"Clearcut",
",",
"self",
")",
".",
"_input_as_lines",
"(",
"data",
")",
")",
"return",
"''"
... | Writes data to tempfile and sets -infile parameter
data -- list of lines, ready to be written to file | [
"Writes",
"data",
"to",
"tempfile",
"and",
"sets",
"-",
"infile",
"parameter"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clearcut.py#L136-L144 |
biocore/burrito-fillings | bfillings/clearcut.py | Clearcut._tree_filename | def _tree_filename(self):
"""Return name of file containing the alignment
prefix -- str, prefix of alignment file.
"""
if self.Parameters['--out']:
aln_filename = self._absolute(self.Parameters['--out'].Value)
else:
raise ValueError, "No tree output file specified."
return aln_filename | python | def _tree_filename(self):
"""Return name of file containing the alignment
prefix -- str, prefix of alignment file.
"""
if self.Parameters['--out']:
aln_filename = self._absolute(self.Parameters['--out'].Value)
else:
raise ValueError, "No tree output file specified."
return aln_filename | [
"def",
"_tree_filename",
"(",
"self",
")",
":",
"if",
"self",
".",
"Parameters",
"[",
"'--out'",
"]",
":",
"aln_filename",
"=",
"self",
".",
"_absolute",
"(",
"self",
".",
"Parameters",
"[",
"'--out'",
"]",
".",
"Value",
")",
"else",
":",
"raise",
"Val... | Return name of file containing the alignment
prefix -- str, prefix of alignment file. | [
"Return",
"name",
"of",
"file",
"containing",
"the",
"alignment"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clearcut.py#L170-L179 |
andrewgross/pyrelic | pyrelic/base_client.py | BaseClient._make_request | def _make_request(self, request, uri, **kwargs):
"""
This is final step of calling out to the remote API. We set up our
headers, proxy, debugging etc. The only things in **kwargs are
parameters that are overridden on an API method basis (like timeout)
We have a simple attempt/while loop to implement retries w/ delays to
avoid the brittleness of talking over the network to remote services.
These settings can be overridden when creating the Client.
We catch the 'requests' exceptions during our retries and eventually
raise our own NewRelicApiException if we are unsuccessful in contacting
the New Relic API. Additionally we process any non 200 HTTP Errors
and raise an appropriate exception according to the New Relic API
documentation.
Finally we pass back the response text to our XML parser since we have
no business parsing that here. It could be argued that handling API
exceptions/errors shouldn't belong in this method but it is simple
enough for now.
"""
attempts = 0
response = None
while attempts <= self.retries:
try:
response = request(uri, headers=self.headers, proxies=self.proxy, **kwargs)
except (requests.ConnectionError, requests.HTTPError) as ce:
attempts += 1
msg = "Attempting retry {attempts} after {delay} seconds".format(attempts=attempts, delay=self.retry_delay)
logger.error(ce.__doc__)
logger.error(msg)
sleep(self.retry_delay)
else:
break
if response is not None:
try:
response.raise_for_status()
except Exception as e:
self._handle_api_error(e)
else:
raise requests.RequestException
return self._parser(response.text) | python | def _make_request(self, request, uri, **kwargs):
"""
This is final step of calling out to the remote API. We set up our
headers, proxy, debugging etc. The only things in **kwargs are
parameters that are overridden on an API method basis (like timeout)
We have a simple attempt/while loop to implement retries w/ delays to
avoid the brittleness of talking over the network to remote services.
These settings can be overridden when creating the Client.
We catch the 'requests' exceptions during our retries and eventually
raise our own NewRelicApiException if we are unsuccessful in contacting
the New Relic API. Additionally we process any non 200 HTTP Errors
and raise an appropriate exception according to the New Relic API
documentation.
Finally we pass back the response text to our XML parser since we have
no business parsing that here. It could be argued that handling API
exceptions/errors shouldn't belong in this method but it is simple
enough for now.
"""
attempts = 0
response = None
while attempts <= self.retries:
try:
response = request(uri, headers=self.headers, proxies=self.proxy, **kwargs)
except (requests.ConnectionError, requests.HTTPError) as ce:
attempts += 1
msg = "Attempting retry {attempts} after {delay} seconds".format(attempts=attempts, delay=self.retry_delay)
logger.error(ce.__doc__)
logger.error(msg)
sleep(self.retry_delay)
else:
break
if response is not None:
try:
response.raise_for_status()
except Exception as e:
self._handle_api_error(e)
else:
raise requests.RequestException
return self._parser(response.text) | [
"def",
"_make_request",
"(",
"self",
",",
"request",
",",
"uri",
",",
"*",
"*",
"kwargs",
")",
":",
"attempts",
"=",
"0",
"response",
"=",
"None",
"while",
"attempts",
"<=",
"self",
".",
"retries",
":",
"try",
":",
"response",
"=",
"request",
"(",
"u... | This is final step of calling out to the remote API. We set up our
headers, proxy, debugging etc. The only things in **kwargs are
parameters that are overridden on an API method basis (like timeout)
We have a simple attempt/while loop to implement retries w/ delays to
avoid the brittleness of talking over the network to remote services.
These settings can be overridden when creating the Client.
We catch the 'requests' exceptions during our retries and eventually
raise our own NewRelicApiException if we are unsuccessful in contacting
the New Relic API. Additionally we process any non 200 HTTP Errors
and raise an appropriate exception according to the New Relic API
documentation.
Finally we pass back the response text to our XML parser since we have
no business parsing that here. It could be argued that handling API
exceptions/errors shouldn't belong in this method but it is simple
enough for now. | [
"This",
"is",
"final",
"step",
"of",
"calling",
"out",
"to",
"the",
"remote",
"API",
".",
"We",
"set",
"up",
"our",
"headers",
"proxy",
"debugging",
"etc",
".",
"The",
"only",
"things",
"in",
"**",
"kwargs",
"are",
"parameters",
"that",
"are",
"overridde... | train | https://github.com/andrewgross/pyrelic/blob/641abe7bfa56bf850281f2d9c90cebe7ea2dfd1e/pyrelic/base_client.py#L39-L81 |
andrewgross/pyrelic | pyrelic/base_client.py | BaseClient._make_get_request | def _make_get_request(self, uri, parameters=None, timeout=None):
"""
Given a request add in the required parameters and return the parsed
XML object.
"""
if not timeout:
timeout = self.timeout
return self._make_request(requests.get, uri, params=parameters, timeout=timeout) | python | def _make_get_request(self, uri, parameters=None, timeout=None):
"""
Given a request add in the required parameters and return the parsed
XML object.
"""
if not timeout:
timeout = self.timeout
return self._make_request(requests.get, uri, params=parameters, timeout=timeout) | [
"def",
"_make_get_request",
"(",
"self",
",",
"uri",
",",
"parameters",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"timeout",
":",
"timeout",
"=",
"self",
".",
"timeout",
"return",
"self",
".",
"_make_request",
"(",
"requests",
".",... | Given a request add in the required parameters and return the parsed
XML object. | [
"Given",
"a",
"request",
"add",
"in",
"the",
"required",
"parameters",
"and",
"return",
"the",
"parsed",
"XML",
"object",
"."
] | train | https://github.com/andrewgross/pyrelic/blob/641abe7bfa56bf850281f2d9c90cebe7ea2dfd1e/pyrelic/base_client.py#L83-L90 |
andrewgross/pyrelic | pyrelic/base_client.py | BaseClient._make_post_request | def _make_post_request(self, uri, payload, timeout=None):
"""
Given a request add in the required parameters and return the parsed
XML object.
"""
if not timeout:
timeout = self.timeout
return self._make_request(requests.post, uri, data=payload, timeout=timeout) | python | def _make_post_request(self, uri, payload, timeout=None):
"""
Given a request add in the required parameters and return the parsed
XML object.
"""
if not timeout:
timeout = self.timeout
return self._make_request(requests.post, uri, data=payload, timeout=timeout) | [
"def",
"_make_post_request",
"(",
"self",
",",
"uri",
",",
"payload",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"timeout",
":",
"timeout",
"=",
"self",
".",
"timeout",
"return",
"self",
".",
"_make_request",
"(",
"requests",
".",
"post",
",",
... | Given a request add in the required parameters and return the parsed
XML object. | [
"Given",
"a",
"request",
"add",
"in",
"the",
"required",
"parameters",
"and",
"return",
"the",
"parsed",
"XML",
"object",
"."
] | train | https://github.com/andrewgross/pyrelic/blob/641abe7bfa56bf850281f2d9c90cebe7ea2dfd1e/pyrelic/base_client.py#L92-L99 |
andrewgross/pyrelic | pyrelic/base_client.py | BaseClient._make_delete_request | def _make_delete_request(self, uri, timeout=None):
"""
Given a request add in the required parameters and return the parsed
XML object.
"""
if not timeout:
timeout = self.timeout
return self._make_request(requests.delete, uri, timeout=timeout) | python | def _make_delete_request(self, uri, timeout=None):
"""
Given a request add in the required parameters and return the parsed
XML object.
"""
if not timeout:
timeout = self.timeout
return self._make_request(requests.delete, uri, timeout=timeout) | [
"def",
"_make_delete_request",
"(",
"self",
",",
"uri",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"timeout",
":",
"timeout",
"=",
"self",
".",
"timeout",
"return",
"self",
".",
"_make_request",
"(",
"requests",
".",
"delete",
",",
"uri",
",",
... | Given a request add in the required parameters and return the parsed
XML object. | [
"Given",
"a",
"request",
"add",
"in",
"the",
"required",
"parameters",
"and",
"return",
"the",
"parsed",
"XML",
"object",
"."
] | train | https://github.com/andrewgross/pyrelic/blob/641abe7bfa56bf850281f2d9c90cebe7ea2dfd1e/pyrelic/base_client.py#L101-L108 |
michaelpb/omnic | omnic/builtin/converters/manifest.py | ManifestDownloader._close | def _close(self):
'''
Closes aiohttp session and all open file descriptors
'''
if hasattr(self, 'aiohttp'):
if not self.aiohttp.closed:
self.aiohttp.close()
if hasattr(self, 'file_descriptors'):
for fd in self.file_descriptors.values():
if not fd.closed:
fd.close() | python | def _close(self):
'''
Closes aiohttp session and all open file descriptors
'''
if hasattr(self, 'aiohttp'):
if not self.aiohttp.closed:
self.aiohttp.close()
if hasattr(self, 'file_descriptors'):
for fd in self.file_descriptors.values():
if not fd.closed:
fd.close() | [
"def",
"_close",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'aiohttp'",
")",
":",
"if",
"not",
"self",
".",
"aiohttp",
".",
"closed",
":",
"self",
".",
"aiohttp",
".",
"close",
"(",
")",
"if",
"hasattr",
"(",
"self",
",",
"'file_des... | Closes aiohttp session and all open file descriptors | [
"Closes",
"aiohttp",
"session",
"and",
"all",
"open",
"file",
"descriptors"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/builtin/converters/manifest.py#L40-L50 |
mickybart/python-atlasapi | atlasapi/errors.py | ErrPaginationLimits.checkAndRaise | def checkAndRaise(pageNum, itemsPerPage):
"""Check and Raise an Exception if needed
Args:
pageNum (int): Page number
itemsPerPage (int): Number of items per Page
Raises:
ErrPaginationLimits: If we are out of limits
"""
if pageNum < 1:
raise ErrPaginationLimits(ErrPaginationLimits.ERR_PAGE_NUM)
if itemsPerPage < Settings.itemsPerPageMin or itemsPerPage > Settings.itemsPerPageMax:
raise ErrPaginationLimits(ErrPaginationLimits.ERR_ITEMS_PER_PAGE) | python | def checkAndRaise(pageNum, itemsPerPage):
"""Check and Raise an Exception if needed
Args:
pageNum (int): Page number
itemsPerPage (int): Number of items per Page
Raises:
ErrPaginationLimits: If we are out of limits
"""
if pageNum < 1:
raise ErrPaginationLimits(ErrPaginationLimits.ERR_PAGE_NUM)
if itemsPerPage < Settings.itemsPerPageMin or itemsPerPage > Settings.itemsPerPageMax:
raise ErrPaginationLimits(ErrPaginationLimits.ERR_ITEMS_PER_PAGE) | [
"def",
"checkAndRaise",
"(",
"pageNum",
",",
"itemsPerPage",
")",
":",
"if",
"pageNum",
"<",
"1",
":",
"raise",
"ErrPaginationLimits",
"(",
"ErrPaginationLimits",
".",
"ERR_PAGE_NUM",
")",
"if",
"itemsPerPage",
"<",
"Settings",
".",
"itemsPerPageMin",
"or",
"ite... | Check and Raise an Exception if needed
Args:
pageNum (int): Page number
itemsPerPage (int): Number of items per Page
Raises:
ErrPaginationLimits: If we are out of limits | [
"Check",
"and",
"Raise",
"an",
"Exception",
"if",
"needed",
"Args",
":",
"pageNum",
"(",
"int",
")",
":",
"Page",
"number",
"itemsPerPage",
"(",
"int",
")",
":",
"Number",
"of",
"items",
"per",
"Page",
"Raises",
":",
"ErrPaginationLimits",
":",
"If",
"we... | train | https://github.com/mickybart/python-atlasapi/blob/2962c37740998694cb55f82b375b81cc604b953e/atlasapi/errors.py#L51-L66 |
mpapi/lazylights | lazylights.py | parse_packet | def parse_packet(data, format=None):
"""
Parses a Lifx data packet (as a bytestring), returning into a Header object
for the fields that are common to all data packets, and a bytestring of
payload data for the type-specific fields (suitable for passing to
`parse_payload`).
"""
unpacked = struct.unpack(BASE_FORMAT, data[:_FORMAT_SIZE])
psize, protocol, mac, gateway, time, ptype = unpacked
header = Header(psize, protocol, mac, gateway, time, ptype)
return header, data[_FORMAT_SIZE:] | python | def parse_packet(data, format=None):
"""
Parses a Lifx data packet (as a bytestring), returning into a Header object
for the fields that are common to all data packets, and a bytestring of
payload data for the type-specific fields (suitable for passing to
`parse_payload`).
"""
unpacked = struct.unpack(BASE_FORMAT, data[:_FORMAT_SIZE])
psize, protocol, mac, gateway, time, ptype = unpacked
header = Header(psize, protocol, mac, gateway, time, ptype)
return header, data[_FORMAT_SIZE:] | [
"def",
"parse_packet",
"(",
"data",
",",
"format",
"=",
"None",
")",
":",
"unpacked",
"=",
"struct",
".",
"unpack",
"(",
"BASE_FORMAT",
",",
"data",
"[",
":",
"_FORMAT_SIZE",
"]",
")",
"psize",
",",
"protocol",
",",
"mac",
",",
"gateway",
",",
"time",
... | Parses a Lifx data packet (as a bytestring), returning into a Header object
for the fields that are common to all data packets, and a bytestring of
payload data for the type-specific fields (suitable for passing to
`parse_payload`). | [
"Parses",
"a",
"Lifx",
"data",
"packet",
"(",
"as",
"a",
"bytestring",
")",
"returning",
"into",
"a",
"Header",
"object",
"for",
"the",
"fields",
"that",
"are",
"common",
"to",
"all",
"data",
"packets",
"and",
"a",
"bytestring",
"of",
"payload",
"data",
... | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L53-L63 |
mpapi/lazylights | lazylights.py | parse_payload | def parse_payload(data, payload_fmt, *payload_names):
"""
Parses a bytestring of Lifx payload data (the bytes after the common
fields), as returned by `parse_packet`. Returns a dictionary where the keys
are from `payload_names` and the values are the corresponding values from
the bytestring.
"""
payload = struct.unpack(payload_fmt, data)
return dict(zip(payload_names, payload)) | python | def parse_payload(data, payload_fmt, *payload_names):
"""
Parses a bytestring of Lifx payload data (the bytes after the common
fields), as returned by `parse_packet`. Returns a dictionary where the keys
are from `payload_names` and the values are the corresponding values from
the bytestring.
"""
payload = struct.unpack(payload_fmt, data)
return dict(zip(payload_names, payload)) | [
"def",
"parse_payload",
"(",
"data",
",",
"payload_fmt",
",",
"*",
"payload_names",
")",
":",
"payload",
"=",
"struct",
".",
"unpack",
"(",
"payload_fmt",
",",
"data",
")",
"return",
"dict",
"(",
"zip",
"(",
"payload_names",
",",
"payload",
")",
")"
] | Parses a bytestring of Lifx payload data (the bytes after the common
fields), as returned by `parse_packet`. Returns a dictionary where the keys
are from `payload_names` and the values are the corresponding values from
the bytestring. | [
"Parses",
"a",
"bytestring",
"of",
"Lifx",
"payload",
"data",
"(",
"the",
"bytes",
"after",
"the",
"common",
"fields",
")",
"as",
"returned",
"by",
"parse_packet",
".",
"Returns",
"a",
"dictionary",
"where",
"the",
"keys",
"are",
"from",
"payload_names",
"an... | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L66-L74 |
mpapi/lazylights | lazylights.py | build_packet | def build_packet(packet_type, gateway, bulb, payload_fmt, *payload_args,
**kwargs):
"""
Constructs a Lifx packet, returning a bytestring. The arguments are as
follows:
- `packet_type`, an integer
- `gateway`, a 6-byte string containing the mac address of the gateway bulb
- `bulb`, a 6-byte string containing either the mac address of the target
bulb or `ALL_BULBS`
- `payload_fmt`, a `struct`-compatible string that describes the format
of the payload part of the packet
- `payload_args`, the values to use to build the payload part of the packet
Additionally, the `protocol` keyword argument can be used to override the
protocol field in the packet.
"""
protocol = kwargs.get('protocol', COMMAND_PROTOCOL)
packet_fmt = BASE_FORMAT + payload_fmt
packet_size = struct.calcsize(packet_fmt)
return struct.pack(packet_fmt,
packet_size,
protocol,
bulb,
gateway,
0, # timestamp
packet_type,
*payload_args) | python | def build_packet(packet_type, gateway, bulb, payload_fmt, *payload_args,
**kwargs):
"""
Constructs a Lifx packet, returning a bytestring. The arguments are as
follows:
- `packet_type`, an integer
- `gateway`, a 6-byte string containing the mac address of the gateway bulb
- `bulb`, a 6-byte string containing either the mac address of the target
bulb or `ALL_BULBS`
- `payload_fmt`, a `struct`-compatible string that describes the format
of the payload part of the packet
- `payload_args`, the values to use to build the payload part of the packet
Additionally, the `protocol` keyword argument can be used to override the
protocol field in the packet.
"""
protocol = kwargs.get('protocol', COMMAND_PROTOCOL)
packet_fmt = BASE_FORMAT + payload_fmt
packet_size = struct.calcsize(packet_fmt)
return struct.pack(packet_fmt,
packet_size,
protocol,
bulb,
gateway,
0, # timestamp
packet_type,
*payload_args) | [
"def",
"build_packet",
"(",
"packet_type",
",",
"gateway",
",",
"bulb",
",",
"payload_fmt",
",",
"*",
"payload_args",
",",
"*",
"*",
"kwargs",
")",
":",
"protocol",
"=",
"kwargs",
".",
"get",
"(",
"'protocol'",
",",
"COMMAND_PROTOCOL",
")",
"packet_fmt",
"... | Constructs a Lifx packet, returning a bytestring. The arguments are as
follows:
- `packet_type`, an integer
- `gateway`, a 6-byte string containing the mac address of the gateway bulb
- `bulb`, a 6-byte string containing either the mac address of the target
bulb or `ALL_BULBS`
- `payload_fmt`, a `struct`-compatible string that describes the format
of the payload part of the packet
- `payload_args`, the values to use to build the payload part of the packet
Additionally, the `protocol` keyword argument can be used to override the
protocol field in the packet. | [
"Constructs",
"a",
"Lifx",
"packet",
"returning",
"a",
"bytestring",
".",
"The",
"arguments",
"are",
"as",
"follows",
":"
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L77-L105 |
mpapi/lazylights | lazylights.py | _unbytes | def _unbytes(bytestr):
"""
Returns a bytestring from the human-friendly string returned by `_bytes`.
>>> _unbytes('123456')
'\x12\x34\x56'
"""
return ''.join(chr(int(bytestr[k:k + 2], 16))
for k in range(0, len(bytestr), 2)) | python | def _unbytes(bytestr):
"""
Returns a bytestring from the human-friendly string returned by `_bytes`.
>>> _unbytes('123456')
'\x12\x34\x56'
"""
return ''.join(chr(int(bytestr[k:k + 2], 16))
for k in range(0, len(bytestr), 2)) | [
"def",
"_unbytes",
"(",
"bytestr",
")",
":",
"return",
"''",
".",
"join",
"(",
"chr",
"(",
"int",
"(",
"bytestr",
"[",
"k",
":",
"k",
"+",
"2",
"]",
",",
"16",
")",
")",
"for",
"k",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"bytestr",
")",
... | Returns a bytestring from the human-friendly string returned by `_bytes`.
>>> _unbytes('123456')
'\x12\x34\x56' | [
"Returns",
"a",
"bytestring",
"from",
"the",
"human",
"-",
"friendly",
"string",
"returned",
"by",
"_bytes",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L118-L126 |
mpapi/lazylights | lazylights.py | _spawn | def _spawn(func, *args, **kwargs):
"""
Calls `func(*args, **kwargs)` in a daemon thread, and returns the (started)
Thread object.
"""
thr = Thread(target=func, args=args, kwargs=kwargs)
thr.daemon = True
thr.start()
return thr | python | def _spawn(func, *args, **kwargs):
"""
Calls `func(*args, **kwargs)` in a daemon thread, and returns the (started)
Thread object.
"""
thr = Thread(target=func, args=args, kwargs=kwargs)
thr.daemon = True
thr.start()
return thr | [
"def",
"_spawn",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"thr",
"=",
"Thread",
"(",
"target",
"=",
"func",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")",
"thr",
".",
"daemon",
"=",
"True",
"thr",
".",
"st... | Calls `func(*args, **kwargs)` in a daemon thread, and returns the (started)
Thread object. | [
"Calls",
"func",
"(",
"*",
"args",
"**",
"kwargs",
")",
"in",
"a",
"daemon",
"thread",
"and",
"returns",
"the",
"(",
"started",
")",
"Thread",
"object",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L129-L137 |
mpapi/lazylights | lazylights.py | _retry | def _retry(event, attempts, delay):
"""
An iterator of pairs of (attempt number, event set), checking whether
`event` is set up to `attempts` number of times, and delaying `delay`
seconds in between.
Terminates as soon as `event` is set, or until `attempts` have been made.
Intended to be used in a loop, as in:
for num, ok in _retry(event_to_wait_for, 10, 1.0):
do_async_thing_that_sets_event()
_log('tried %d time(s) to set event', num)
if not ok:
raise Exception('failed to set event')
"""
event.clear()
attempted = 0
while attempted < attempts and not event.is_set():
yield attempted, event.is_set()
if event.wait(delay):
break
yield attempted, event.is_set() | python | def _retry(event, attempts, delay):
"""
An iterator of pairs of (attempt number, event set), checking whether
`event` is set up to `attempts` number of times, and delaying `delay`
seconds in between.
Terminates as soon as `event` is set, or until `attempts` have been made.
Intended to be used in a loop, as in:
for num, ok in _retry(event_to_wait_for, 10, 1.0):
do_async_thing_that_sets_event()
_log('tried %d time(s) to set event', num)
if not ok:
raise Exception('failed to set event')
"""
event.clear()
attempted = 0
while attempted < attempts and not event.is_set():
yield attempted, event.is_set()
if event.wait(delay):
break
yield attempted, event.is_set() | [
"def",
"_retry",
"(",
"event",
",",
"attempts",
",",
"delay",
")",
":",
"event",
".",
"clear",
"(",
")",
"attempted",
"=",
"0",
"while",
"attempted",
"<",
"attempts",
"and",
"not",
"event",
".",
"is_set",
"(",
")",
":",
"yield",
"attempted",
",",
"ev... | An iterator of pairs of (attempt number, event set), checking whether
`event` is set up to `attempts` number of times, and delaying `delay`
seconds in between.
Terminates as soon as `event` is set, or until `attempts` have been made.
Intended to be used in a loop, as in:
for num, ok in _retry(event_to_wait_for, 10, 1.0):
do_async_thing_that_sets_event()
_log('tried %d time(s) to set event', num)
if not ok:
raise Exception('failed to set event') | [
"An",
"iterator",
"of",
"pairs",
"of",
"(",
"attempt",
"number",
"event",
"set",
")",
"checking",
"whether",
"event",
"is",
"set",
"up",
"to",
"attempts",
"number",
"of",
"times",
"and",
"delaying",
"delay",
"seconds",
"in",
"between",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L140-L162 |
mpapi/lazylights | lazylights.py | _blocking | def _blocking(lock, state_dict, event, timeout=None):
"""
A contextmanager that clears `state_dict` and `event`, yields, and waits
for the event to be set. Clearing an yielding are done within `lock`.
Used for blocking request/response semantics on the request side, as in:
with _blocking(lock, state, event):
send_request()
The response side would then do something like:
with lock:
state['data'] = '...'
event.set()
"""
with lock:
state_dict.clear()
event.clear()
yield
event.wait(timeout) | python | def _blocking(lock, state_dict, event, timeout=None):
"""
A contextmanager that clears `state_dict` and `event`, yields, and waits
for the event to be set. Clearing an yielding are done within `lock`.
Used for blocking request/response semantics on the request side, as in:
with _blocking(lock, state, event):
send_request()
The response side would then do something like:
with lock:
state['data'] = '...'
event.set()
"""
with lock:
state_dict.clear()
event.clear()
yield
event.wait(timeout) | [
"def",
"_blocking",
"(",
"lock",
",",
"state_dict",
",",
"event",
",",
"timeout",
"=",
"None",
")",
":",
"with",
"lock",
":",
"state_dict",
".",
"clear",
"(",
")",
"event",
".",
"clear",
"(",
")",
"yield",
"event",
".",
"wait",
"(",
"timeout",
")"
] | A contextmanager that clears `state_dict` and `event`, yields, and waits
for the event to be set. Clearing an yielding are done within `lock`.
Used for blocking request/response semantics on the request side, as in:
with _blocking(lock, state, event):
send_request()
The response side would then do something like:
with lock:
state['data'] = '...'
event.set() | [
"A",
"contextmanager",
"that",
"clears",
"state_dict",
"and",
"event",
"yields",
"and",
"waits",
"for",
"the",
"event",
"to",
"be",
"set",
".",
"Clearing",
"an",
"yielding",
"are",
"done",
"within",
"lock",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L166-L186 |
mpapi/lazylights | lazylights.py | Callbacks.register | def register(self, event, fn):
"""
Tell the object to run `fn` whenever a message of type `event` is
received.
"""
self._callbacks.setdefault(event, []).append(fn)
return fn | python | def register(self, event, fn):
"""
Tell the object to run `fn` whenever a message of type `event` is
received.
"""
self._callbacks.setdefault(event, []).append(fn)
return fn | [
"def",
"register",
"(",
"self",
",",
"event",
",",
"fn",
")",
":",
"self",
".",
"_callbacks",
".",
"setdefault",
"(",
"event",
",",
"[",
"]",
")",
".",
"append",
"(",
"fn",
")",
"return",
"fn"
] | Tell the object to run `fn` whenever a message of type `event` is
received. | [
"Tell",
"the",
"object",
"to",
"run",
"fn",
"whenever",
"a",
"message",
"of",
"type",
"event",
"is",
"received",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L200-L206 |
mpapi/lazylights | lazylights.py | Callbacks.put | def put(self, event, *args, **kwargs):
"""
Schedule a callback for `event`, passing `args` and `kwargs` to each
registered callback handler.
"""
self._queue.put((event, args, kwargs)) | python | def put(self, event, *args, **kwargs):
"""
Schedule a callback for `event`, passing `args` and `kwargs` to each
registered callback handler.
"""
self._queue.put((event, args, kwargs)) | [
"def",
"put",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_queue",
".",
"put",
"(",
"(",
"event",
",",
"args",
",",
"kwargs",
")",
")"
] | Schedule a callback for `event`, passing `args` and `kwargs` to each
registered callback handler. | [
"Schedule",
"a",
"callback",
"for",
"event",
"passing",
"args",
"and",
"kwargs",
"to",
"each",
"registered",
"callback",
"handler",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L208-L213 |
mpapi/lazylights | lazylights.py | Callbacks.run | def run(self):
"""
Process all callbacks, until `stop()` is called. Intended to run in
its own thread.
"""
while True:
msg = self._queue.get()
if msg is _SHUTDOWN:
break
event, args, kwargs = msg
self._logger('<< %s', event)
for func in self._callbacks.get(event, []):
func(*args, **kwargs) | python | def run(self):
"""
Process all callbacks, until `stop()` is called. Intended to run in
its own thread.
"""
while True:
msg = self._queue.get()
if msg is _SHUTDOWN:
break
event, args, kwargs = msg
self._logger('<< %s', event)
for func in self._callbacks.get(event, []):
func(*args, **kwargs) | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"msg",
"=",
"self",
".",
"_queue",
".",
"get",
"(",
")",
"if",
"msg",
"is",
"_SHUTDOWN",
":",
"break",
"event",
",",
"args",
",",
"kwargs",
"=",
"msg",
"self",
".",
"_logger",
"(",
"'<< %... | Process all callbacks, until `stop()` is called. Intended to run in
its own thread. | [
"Process",
"all",
"callbacks",
"until",
"stop",
"()",
"is",
"called",
".",
"Intended",
"to",
"run",
"in",
"its",
"own",
"thread",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L221-L233 |
mpapi/lazylights | lazylights.py | PacketReceiver.run | def run(self):
"""
Process all incoming packets, until `stop()` is called. Intended to run
in its own thread.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(self._addr)
sock.settimeout(self._timeout)
with closing(sock):
while not self._shutdown.is_set():
try:
data, addr = sock.recvfrom(self._buffer_size)
except socket.timeout:
continue
header, rest = parse_packet(data)
if header.packet_type in _PAYLOADS:
payload = parse_payload(rest,
*_PAYLOADS[header.packet_type])
self._callbacks.put(header.packet_type,
header, payload, None, addr)
else:
self._callbacks.put(EVENT_UNKNOWN,
header, None, rest, addr) | python | def run(self):
"""
Process all incoming packets, until `stop()` is called. Intended to run
in its own thread.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(self._addr)
sock.settimeout(self._timeout)
with closing(sock):
while not self._shutdown.is_set():
try:
data, addr = sock.recvfrom(self._buffer_size)
except socket.timeout:
continue
header, rest = parse_packet(data)
if header.packet_type in _PAYLOADS:
payload = parse_payload(rest,
*_PAYLOADS[header.packet_type])
self._callbacks.put(header.packet_type,
header, payload, None, addr)
else:
self._callbacks.put(EVENT_UNKNOWN,
header, None, rest, addr) | [
"def",
"run",
"(",
"self",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"sock",
".",
"bind",
"(",
"self",
".",
"_addr",
")",
"sock",
".",
"settimeout",
"(",
"self",
".",
"_tim... | Process all incoming packets, until `stop()` is called. Intended to run
in its own thread. | [
"Process",
"all",
"incoming",
"packets",
"until",
"stop",
"()",
"is",
"called",
".",
"Intended",
"to",
"run",
"in",
"its",
"own",
"thread",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L263-L286 |
mpapi/lazylights | lazylights.py | PacketSender.run | def run(self):
"""
Process all outgoing packets, until `stop()` is called. Intended to run
in its own thread.
"""
while True:
to_send = self._queue.get()
if to_send is _SHUTDOWN:
break
# If we get a gateway object, connect to it. Otherwise, assume
# it's a bytestring and send it out on the socket.
if isinstance(to_send, Gateway):
self._gateway = to_send
self._connected.set()
else:
if not self._gateway:
raise SendException('no gateway')
dest = (self._gateway.addr, self._gateway.port)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(to_send, dest) | python | def run(self):
"""
Process all outgoing packets, until `stop()` is called. Intended to run
in its own thread.
"""
while True:
to_send = self._queue.get()
if to_send is _SHUTDOWN:
break
# If we get a gateway object, connect to it. Otherwise, assume
# it's a bytestring and send it out on the socket.
if isinstance(to_send, Gateway):
self._gateway = to_send
self._connected.set()
else:
if not self._gateway:
raise SendException('no gateway')
dest = (self._gateway.addr, self._gateway.port)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(to_send, dest) | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"to_send",
"=",
"self",
".",
"_queue",
".",
"get",
"(",
")",
"if",
"to_send",
"is",
"_SHUTDOWN",
":",
"break",
"# If we get a gateway object, connect to it. Otherwise, assume",
"# it's a bytestring and send ... | Process all outgoing packets, until `stop()` is called. Intended to run
in its own thread. | [
"Process",
"all",
"outgoing",
"packets",
"until",
"stop",
"()",
"is",
"called",
".",
"Intended",
"to",
"run",
"in",
"its",
"own",
"thread",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L319-L339 |
mpapi/lazylights | lazylights.py | Logger.run | def run(self):
"""
Process all log messages, until `stop()` is called. Intended to run
in its own thread.
"""
while True:
msg = self._queue.get()
if msg is _SHUTDOWN:
break
if self._enabled:
print msg | python | def run(self):
"""
Process all log messages, until `stop()` is called. Intended to run
in its own thread.
"""
while True:
msg = self._queue.get()
if msg is _SHUTDOWN:
break
if self._enabled:
print msg | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"msg",
"=",
"self",
".",
"_queue",
".",
"get",
"(",
")",
"if",
"msg",
"is",
"_SHUTDOWN",
":",
"break",
"if",
"self",
".",
"_enabled",
":",
"print",
"msg"
] | Process all log messages, until `stop()` is called. Intended to run
in its own thread. | [
"Process",
"all",
"log",
"messages",
"until",
"stop",
"()",
"is",
"called",
".",
"Intended",
"to",
"run",
"in",
"its",
"own",
"thread",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L362-L372 |
mpapi/lazylights | lazylights.py | Lifx._on_gateway | def _on_gateway(self, header, payload, rest, addr):
"""
Records a discovered gateway, for connecting to later.
"""
if payload.get('service') == SERVICE_UDP:
self.gateway = Gateway(addr[0], payload['port'], header.gateway)
self.gateway_found_event.set() | python | def _on_gateway(self, header, payload, rest, addr):
"""
Records a discovered gateway, for connecting to later.
"""
if payload.get('service') == SERVICE_UDP:
self.gateway = Gateway(addr[0], payload['port'], header.gateway)
self.gateway_found_event.set() | [
"def",
"_on_gateway",
"(",
"self",
",",
"header",
",",
"payload",
",",
"rest",
",",
"addr",
")",
":",
"if",
"payload",
".",
"get",
"(",
"'service'",
")",
"==",
"SERVICE_UDP",
":",
"self",
".",
"gateway",
"=",
"Gateway",
"(",
"addr",
"[",
"0",
"]",
... | Records a discovered gateway, for connecting to later. | [
"Records",
"a",
"discovered",
"gateway",
"for",
"connecting",
"to",
"later",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L427-L433 |
mpapi/lazylights | lazylights.py | Lifx._on_power_state | def _on_power_state(self, header, payload, rest, addr):
"""
Records the power (on/off) state of bulbs, and forwards to a high-level
callback with human-friendlier arguments.
"""
with self.lock:
self.power_state[header.mac] = payload
if len(self.power_state) >= self.num_bulbs:
self.power_state_event.set()
self.callbacks.put(EVENT_POWER_STATE, self.get_bulb(header.mac),
is_on=bool(payload['is_on'])) | python | def _on_power_state(self, header, payload, rest, addr):
"""
Records the power (on/off) state of bulbs, and forwards to a high-level
callback with human-friendlier arguments.
"""
with self.lock:
self.power_state[header.mac] = payload
if len(self.power_state) >= self.num_bulbs:
self.power_state_event.set()
self.callbacks.put(EVENT_POWER_STATE, self.get_bulb(header.mac),
is_on=bool(payload['is_on'])) | [
"def",
"_on_power_state",
"(",
"self",
",",
"header",
",",
"payload",
",",
"rest",
",",
"addr",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"power_state",
"[",
"header",
".",
"mac",
"]",
"=",
"payload",
"if",
"len",
"(",
"self",
".",
"... | Records the power (on/off) state of bulbs, and forwards to a high-level
callback with human-friendlier arguments. | [
"Records",
"the",
"power",
"(",
"on",
"/",
"off",
")",
"state",
"of",
"bulbs",
"and",
"forwards",
"to",
"a",
"high",
"-",
"level",
"callback",
"with",
"human",
"-",
"friendlier",
"arguments",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L435-L446 |
mpapi/lazylights | lazylights.py | Lifx._on_light_state | def _on_light_state(self, header, payload, rest, addr):
"""
Records the light state of bulbs, and forwards to a high-level callback
with human-friendlier arguments.
"""
with self.lock:
label = payload['label'].strip('\x00')
self.bulbs[header.mac] = bulb = Bulb(label, header.mac)
if len(self.bulbs) >= self.num_bulbs:
self.bulbs_found_event.set()
self.light_state[header.mac] = payload
if len(self.light_state) >= self.num_bulbs:
self.light_state_event.set()
self.callbacks.put(EVENT_LIGHT_STATE, bulb,
raw=payload,
hue=(payload['hue'] / float(0xffff) * 360) % 360.0,
saturation=payload['sat'] / float(0xffff),
brightness=payload['bright'] / float(0xffff),
kelvin=payload['kelvin'],
is_on=bool(payload['power'])) | python | def _on_light_state(self, header, payload, rest, addr):
"""
Records the light state of bulbs, and forwards to a high-level callback
with human-friendlier arguments.
"""
with self.lock:
label = payload['label'].strip('\x00')
self.bulbs[header.mac] = bulb = Bulb(label, header.mac)
if len(self.bulbs) >= self.num_bulbs:
self.bulbs_found_event.set()
self.light_state[header.mac] = payload
if len(self.light_state) >= self.num_bulbs:
self.light_state_event.set()
self.callbacks.put(EVENT_LIGHT_STATE, bulb,
raw=payload,
hue=(payload['hue'] / float(0xffff) * 360) % 360.0,
saturation=payload['sat'] / float(0xffff),
brightness=payload['bright'] / float(0xffff),
kelvin=payload['kelvin'],
is_on=bool(payload['power'])) | [
"def",
"_on_light_state",
"(",
"self",
",",
"header",
",",
"payload",
",",
"rest",
",",
"addr",
")",
":",
"with",
"self",
".",
"lock",
":",
"label",
"=",
"payload",
"[",
"'label'",
"]",
".",
"strip",
"(",
"'\\x00'",
")",
"self",
".",
"bulbs",
"[",
... | Records the light state of bulbs, and forwards to a high-level callback
with human-friendlier arguments. | [
"Records",
"the",
"light",
"state",
"of",
"bulbs",
"and",
"forwards",
"to",
"a",
"high",
"-",
"level",
"callback",
"with",
"human",
"-",
"friendlier",
"arguments",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L448-L469 |
mpapi/lazylights | lazylights.py | Lifx.get_bulb | def get_bulb(self, mac):
"""
Returns a Bulb object corresponding to the bulb with the mac address
`mac` (a 6-byte bytestring).
"""
return self.bulbs.get(mac, Bulb('Bulb %s' % _bytes(mac), mac)) | python | def get_bulb(self, mac):
"""
Returns a Bulb object corresponding to the bulb with the mac address
`mac` (a 6-byte bytestring).
"""
return self.bulbs.get(mac, Bulb('Bulb %s' % _bytes(mac), mac)) | [
"def",
"get_bulb",
"(",
"self",
",",
"mac",
")",
":",
"return",
"self",
".",
"bulbs",
".",
"get",
"(",
"mac",
",",
"Bulb",
"(",
"'Bulb %s'",
"%",
"_bytes",
"(",
"mac",
")",
",",
"mac",
")",
")"
] | Returns a Bulb object corresponding to the bulb with the mac address
`mac` (a 6-byte bytestring). | [
"Returns",
"a",
"Bulb",
"object",
"corresponding",
"to",
"the",
"bulb",
"with",
"the",
"mac",
"address",
"mac",
"(",
"a",
"6",
"-",
"byte",
"bytestring",
")",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L473-L478 |
mpapi/lazylights | lazylights.py | Lifx.send | def send(self, packet_type, bulb, packet_fmt, *packet_args):
"""
Builds and sends a packet to one or more bulbs.
"""
packet = build_packet(packet_type, self.gateway.mac, bulb,
packet_fmt, *packet_args)
self.logger('>> %s', _bytes(packet))
self.sender.put(packet) | python | def send(self, packet_type, bulb, packet_fmt, *packet_args):
"""
Builds and sends a packet to one or more bulbs.
"""
packet = build_packet(packet_type, self.gateway.mac, bulb,
packet_fmt, *packet_args)
self.logger('>> %s', _bytes(packet))
self.sender.put(packet) | [
"def",
"send",
"(",
"self",
",",
"packet_type",
",",
"bulb",
",",
"packet_fmt",
",",
"*",
"packet_args",
")",
":",
"packet",
"=",
"build_packet",
"(",
"packet_type",
",",
"self",
".",
"gateway",
".",
"mac",
",",
"bulb",
",",
"packet_fmt",
",",
"*",
"pa... | Builds and sends a packet to one or more bulbs. | [
"Builds",
"and",
"sends",
"a",
"packet",
"to",
"one",
"or",
"more",
"bulbs",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L482-L489 |
mpapi/lazylights | lazylights.py | Lifx.set_power_state | def set_power_state(self, is_on, bulb=ALL_BULBS, timeout=None):
"""
Sets the power state of one or more bulbs.
"""
with _blocking(self.lock, self.power_state, self.light_state_event,
timeout):
self.send(REQ_SET_POWER_STATE,
bulb, '2s', '\x00\x01' if is_on else '\x00\x00')
self.send(REQ_GET_LIGHT_STATE, ALL_BULBS, '')
return self.power_state | python | def set_power_state(self, is_on, bulb=ALL_BULBS, timeout=None):
"""
Sets the power state of one or more bulbs.
"""
with _blocking(self.lock, self.power_state, self.light_state_event,
timeout):
self.send(REQ_SET_POWER_STATE,
bulb, '2s', '\x00\x01' if is_on else '\x00\x00')
self.send(REQ_GET_LIGHT_STATE, ALL_BULBS, '')
return self.power_state | [
"def",
"set_power_state",
"(",
"self",
",",
"is_on",
",",
"bulb",
"=",
"ALL_BULBS",
",",
"timeout",
"=",
"None",
")",
":",
"with",
"_blocking",
"(",
"self",
".",
"lock",
",",
"self",
".",
"power_state",
",",
"self",
".",
"light_state_event",
",",
"timeou... | Sets the power state of one or more bulbs. | [
"Sets",
"the",
"power",
"state",
"of",
"one",
"or",
"more",
"bulbs",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L491-L500 |
mpapi/lazylights | lazylights.py | Lifx.set_light_state_raw | def set_light_state_raw(self, hue, saturation, brightness, kelvin,
bulb=ALL_BULBS, timeout=None):
"""
Sets the (low-level) light state of one or more bulbs.
"""
with _blocking(self.lock, self.light_state, self.light_state_event,
timeout):
self.send(REQ_SET_LIGHT_STATE, bulb, 'xHHHHI',
hue, saturation, brightness, kelvin, 0)
self.send(REQ_GET_LIGHT_STATE, ALL_BULBS, '')
return self.light_state | python | def set_light_state_raw(self, hue, saturation, brightness, kelvin,
bulb=ALL_BULBS, timeout=None):
"""
Sets the (low-level) light state of one or more bulbs.
"""
with _blocking(self.lock, self.light_state, self.light_state_event,
timeout):
self.send(REQ_SET_LIGHT_STATE, bulb, 'xHHHHI',
hue, saturation, brightness, kelvin, 0)
self.send(REQ_GET_LIGHT_STATE, ALL_BULBS, '')
return self.light_state | [
"def",
"set_light_state_raw",
"(",
"self",
",",
"hue",
",",
"saturation",
",",
"brightness",
",",
"kelvin",
",",
"bulb",
"=",
"ALL_BULBS",
",",
"timeout",
"=",
"None",
")",
":",
"with",
"_blocking",
"(",
"self",
".",
"lock",
",",
"self",
".",
"light_stat... | Sets the (low-level) light state of one or more bulbs. | [
"Sets",
"the",
"(",
"low",
"-",
"level",
")",
"light",
"state",
"of",
"one",
"or",
"more",
"bulbs",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L502-L512 |
mpapi/lazylights | lazylights.py | Lifx.set_light_state | def set_light_state(self, hue, saturation, brightness, kelvin,
bulb=ALL_BULBS, timeout=None):
"""
Sets the light state of one or more bulbs.
Hue is a float from 0 to 360, saturation and brightness are floats from
0 to 1, and kelvin is an integer.
"""
raw_hue = int((hue % 360) / 360.0 * 0xffff) & 0xffff
raw_sat = int(saturation * 0xffff) & 0xffff
raw_bright = int(brightness * 0xffff) & 0xffff
return self.set_light_state_raw(raw_hue, raw_sat, raw_bright, kelvin,
bulb, timeout) | python | def set_light_state(self, hue, saturation, brightness, kelvin,
bulb=ALL_BULBS, timeout=None):
"""
Sets the light state of one or more bulbs.
Hue is a float from 0 to 360, saturation and brightness are floats from
0 to 1, and kelvin is an integer.
"""
raw_hue = int((hue % 360) / 360.0 * 0xffff) & 0xffff
raw_sat = int(saturation * 0xffff) & 0xffff
raw_bright = int(brightness * 0xffff) & 0xffff
return self.set_light_state_raw(raw_hue, raw_sat, raw_bright, kelvin,
bulb, timeout) | [
"def",
"set_light_state",
"(",
"self",
",",
"hue",
",",
"saturation",
",",
"brightness",
",",
"kelvin",
",",
"bulb",
"=",
"ALL_BULBS",
",",
"timeout",
"=",
"None",
")",
":",
"raw_hue",
"=",
"int",
"(",
"(",
"hue",
"%",
"360",
")",
"/",
"360.0",
"*",
... | Sets the light state of one or more bulbs.
Hue is a float from 0 to 360, saturation and brightness are floats from
0 to 1, and kelvin is an integer. | [
"Sets",
"the",
"light",
"state",
"of",
"one",
"or",
"more",
"bulbs",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L514-L526 |
mpapi/lazylights | lazylights.py | Lifx.on_packet | def on_packet(self, packet_type):
"""
Registers a function to be called when packet data is received with a
specific type.
"""
def _wrapper(fn):
return self.callbacks.register(packet_type, fn)
return _wrapper | python | def on_packet(self, packet_type):
"""
Registers a function to be called when packet data is received with a
specific type.
"""
def _wrapper(fn):
return self.callbacks.register(packet_type, fn)
return _wrapper | [
"def",
"on_packet",
"(",
"self",
",",
"packet_type",
")",
":",
"def",
"_wrapper",
"(",
"fn",
")",
":",
"return",
"self",
".",
"callbacks",
".",
"register",
"(",
"packet_type",
",",
"fn",
")",
"return",
"_wrapper"
] | Registers a function to be called when packet data is received with a
specific type. | [
"Registers",
"a",
"function",
"to",
"be",
"called",
"when",
"packet",
"data",
"is",
"received",
"with",
"a",
"specific",
"type",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L569-L576 |
mpapi/lazylights | lazylights.py | Lifx.connect | def connect(self, attempts=20, delay=0.5):
"""
Connects to a gateway, blocking until a connection is made and bulbs
are found.
Step 1: send a gateway discovery packet to the broadcast address, wait
until we've received some info about the gateway.
Step 2: connect to a discovered gateway, wait until the connection has
been completed.
Step 3: ask for info about bulbs, wait until we've found the number of
bulbs we expect.
Raises a ConnectException if any of the steps fail.
"""
# Broadcast discovery packets until we find a gateway.
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
with closing(sock):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
discover_packet = build_packet(REQ_GATEWAY,
ALL_BULBS, ALL_BULBS, '',
protocol=DISCOVERY_PROTOCOL)
for _, ok in _retry(self.gateway_found_event, attempts, delay):
sock.sendto(discover_packet, BROADCAST_ADDRESS)
if not ok:
raise ConnectException('discovery failed')
self.callbacks.put(EVENT_DISCOVERED)
# Tell the sender to connect to the gateway until it does.
for _, ok in _retry(self.sender.is_connected, 1, 3):
self.sender.put(self.gateway)
if not ok:
raise ConnectException('connection failed')
self.callbacks.put(EVENT_CONNECTED)
# Send light state packets to the gateway until we find bulbs.
for _, ok in _retry(self.bulbs_found_event, attempts, delay):
self.send(REQ_GET_LIGHT_STATE, ALL_BULBS, '')
if not ok:
raise ConnectException('only found %d of %d bulbs' % (
len(self.bulbs), self.num_bulbs))
self.callbacks.put(EVENT_BULBS_FOUND) | python | def connect(self, attempts=20, delay=0.5):
"""
Connects to a gateway, blocking until a connection is made and bulbs
are found.
Step 1: send a gateway discovery packet to the broadcast address, wait
until we've received some info about the gateway.
Step 2: connect to a discovered gateway, wait until the connection has
been completed.
Step 3: ask for info about bulbs, wait until we've found the number of
bulbs we expect.
Raises a ConnectException if any of the steps fail.
"""
# Broadcast discovery packets until we find a gateway.
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
with closing(sock):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
discover_packet = build_packet(REQ_GATEWAY,
ALL_BULBS, ALL_BULBS, '',
protocol=DISCOVERY_PROTOCOL)
for _, ok in _retry(self.gateway_found_event, attempts, delay):
sock.sendto(discover_packet, BROADCAST_ADDRESS)
if not ok:
raise ConnectException('discovery failed')
self.callbacks.put(EVENT_DISCOVERED)
# Tell the sender to connect to the gateway until it does.
for _, ok in _retry(self.sender.is_connected, 1, 3):
self.sender.put(self.gateway)
if not ok:
raise ConnectException('connection failed')
self.callbacks.put(EVENT_CONNECTED)
# Send light state packets to the gateway until we find bulbs.
for _, ok in _retry(self.bulbs_found_event, attempts, delay):
self.send(REQ_GET_LIGHT_STATE, ALL_BULBS, '')
if not ok:
raise ConnectException('only found %d of %d bulbs' % (
len(self.bulbs), self.num_bulbs))
self.callbacks.put(EVENT_BULBS_FOUND) | [
"def",
"connect",
"(",
"self",
",",
"attempts",
"=",
"20",
",",
"delay",
"=",
"0.5",
")",
":",
"# Broadcast discovery packets until we find a gateway.",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
",",... | Connects to a gateway, blocking until a connection is made and bulbs
are found.
Step 1: send a gateway discovery packet to the broadcast address, wait
until we've received some info about the gateway.
Step 2: connect to a discovered gateway, wait until the connection has
been completed.
Step 3: ask for info about bulbs, wait until we've found the number of
bulbs we expect.
Raises a ConnectException if any of the steps fail. | [
"Connects",
"to",
"a",
"gateway",
"blocking",
"until",
"a",
"connection",
"is",
"made",
"and",
"bulbs",
"are",
"found",
"."
] | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L580-L623 |
mpapi/lazylights | lazylights.py | Lifx.run | def run(self):
"""
A context manager starting up threads to send and receive data from a
gateway and handle callbacks. Yields when a connection has been made,
and cleans up connections and threads when it's done.
"""
listener_thr = _spawn(self.receiver.run)
callback_thr = _spawn(self.callbacks.run)
sender_thr = _spawn(self.sender.run)
logger_thr = _spawn(self.logger.run)
self.connect()
try:
yield
finally:
self.stop()
# Wait for the listener to finish.
listener_thr.join()
self.callbacks.put('shutdown')
# Tell the other threads to finish, and wait for them.
for obj in [self.callbacks, self.sender, self.logger]:
obj.stop()
for thr in [callback_thr, sender_thr, logger_thr]:
thr.join() | python | def run(self):
"""
A context manager starting up threads to send and receive data from a
gateway and handle callbacks. Yields when a connection has been made,
and cleans up connections and threads when it's done.
"""
listener_thr = _spawn(self.receiver.run)
callback_thr = _spawn(self.callbacks.run)
sender_thr = _spawn(self.sender.run)
logger_thr = _spawn(self.logger.run)
self.connect()
try:
yield
finally:
self.stop()
# Wait for the listener to finish.
listener_thr.join()
self.callbacks.put('shutdown')
# Tell the other threads to finish, and wait for them.
for obj in [self.callbacks, self.sender, self.logger]:
obj.stop()
for thr in [callback_thr, sender_thr, logger_thr]:
thr.join() | [
"def",
"run",
"(",
"self",
")",
":",
"listener_thr",
"=",
"_spawn",
"(",
"self",
".",
"receiver",
".",
"run",
")",
"callback_thr",
"=",
"_spawn",
"(",
"self",
".",
"callbacks",
".",
"run",
")",
"sender_thr",
"=",
"_spawn",
"(",
"self",
".",
"sender",
... | A context manager starting up threads to send and receive data from a
gateway and handle callbacks. Yields when a connection has been made,
and cleans up connections and threads when it's done. | [
"A",
"context",
"manager",
"starting",
"up",
"threads",
"to",
"send",
"and",
"receive",
"data",
"from",
"a",
"gateway",
"and",
"handle",
"callbacks",
".",
"Yields",
"when",
"a",
"connection",
"has",
"been",
"made",
"and",
"cleans",
"up",
"connections",
"and"... | train | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L626-L651 |
michaelpb/omnic | omnic/worker/base.py | BaseWorker.run_multiconvert | async def run_multiconvert(self, url_string, to_type):
'''
Enqueues in succession all conversions steps necessary to take the
given URL and convert it to to_type, storing the result in the cache
'''
async def enq_convert(*args):
await self.enqueue(Task.CONVERT, args)
await tasks.multiconvert(url_string, to_type, enq_convert) | python | async def run_multiconvert(self, url_string, to_type):
'''
Enqueues in succession all conversions steps necessary to take the
given URL and convert it to to_type, storing the result in the cache
'''
async def enq_convert(*args):
await self.enqueue(Task.CONVERT, args)
await tasks.multiconvert(url_string, to_type, enq_convert) | [
"async",
"def",
"run_multiconvert",
"(",
"self",
",",
"url_string",
",",
"to_type",
")",
":",
"async",
"def",
"enq_convert",
"(",
"*",
"args",
")",
":",
"await",
"self",
".",
"enqueue",
"(",
"Task",
".",
"CONVERT",
",",
"args",
")",
"await",
"tasks",
"... | Enqueues in succession all conversions steps necessary to take the
given URL and convert it to to_type, storing the result in the cache | [
"Enqueues",
"in",
"succession",
"all",
"conversions",
"steps",
"necessary",
"to",
"take",
"the",
"given",
"URL",
"and",
"convert",
"it",
"to",
"to_type",
"storing",
"the",
"result",
"in",
"the",
"cache"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/worker/base.py#L90-L97 |
biocore/burrito-fillings | bfillings/mothur.py | parse_otu_list | def parse_otu_list(lines, precision=0.0049):
"""Parser for mothur *.list file
To ensure all distances are of type float, the parser returns a
distance of 0.0 for the unique groups. However, if some sequences
are very similar, mothur may return a grouping at zero distance.
What Mothur really means by this, however, is that the clustering
is at the level of Mothur's precision. In this case, the parser
returns the distance explicitly.
If you are parsing otu's with a non-default precision, you must
specify the precision here to ensure that the parsed distances are
in order.
Returns an iterator over (distance, otu_list)
"""
for line in lines:
if is_empty(line):
continue
tokens = line.strip().split('\t')
distance_str = tokens.pop(0)
if distance_str.lstrip().lower().startswith('u'):
distance = 0.0
elif distance_str == '0.0':
distance = float(precision)
else:
distance = float(distance_str)
num_otus = int(tokens.pop(0))
otu_list = [t.split(',') for t in tokens]
yield (distance, otu_list) | python | def parse_otu_list(lines, precision=0.0049):
"""Parser for mothur *.list file
To ensure all distances are of type float, the parser returns a
distance of 0.0 for the unique groups. However, if some sequences
are very similar, mothur may return a grouping at zero distance.
What Mothur really means by this, however, is that the clustering
is at the level of Mothur's precision. In this case, the parser
returns the distance explicitly.
If you are parsing otu's with a non-default precision, you must
specify the precision here to ensure that the parsed distances are
in order.
Returns an iterator over (distance, otu_list)
"""
for line in lines:
if is_empty(line):
continue
tokens = line.strip().split('\t')
distance_str = tokens.pop(0)
if distance_str.lstrip().lower().startswith('u'):
distance = 0.0
elif distance_str == '0.0':
distance = float(precision)
else:
distance = float(distance_str)
num_otus = int(tokens.pop(0))
otu_list = [t.split(',') for t in tokens]
yield (distance, otu_list) | [
"def",
"parse_otu_list",
"(",
"lines",
",",
"precision",
"=",
"0.0049",
")",
":",
"for",
"line",
"in",
"lines",
":",
"if",
"is_empty",
"(",
"line",
")",
":",
"continue",
"tokens",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
... | Parser for mothur *.list file
To ensure all distances are of type float, the parser returns a
distance of 0.0 for the unique groups. However, if some sequences
are very similar, mothur may return a grouping at zero distance.
What Mothur really means by this, however, is that the clustering
is at the level of Mothur's precision. In this case, the parser
returns the distance explicitly.
If you are parsing otu's with a non-default precision, you must
specify the precision here to ensure that the parsed distances are
in order.
Returns an iterator over (distance, otu_list) | [
"Parser",
"for",
"mothur",
"*",
".",
"list",
"file"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L33-L65 |
biocore/burrito-fillings | bfillings/mothur.py | mothur_classify_file | def mothur_classify_file(
query_file, ref_fp, tax_fp, cutoff=None, iters=None, ksize=None,
output_fp=None, tmp_dir=None):
"""Classify a set of sequences using Mothur's naive bayes method
Dashes are used in Mothur to provide multiple filenames. A
filepath with a dash typically breaks an otherwise valid command
in Mothur. This wrapper script makes a copy of both files, ref_fp
and tax_fp, to ensure that the path has no dashes.
For convenience, we also ensure that each taxon list in the
id-to-taxonomy file ends with a semicolon.
"""
if tmp_dir is None:
tmp_dir = gettempdir()
ref_seq_ids = set()
user_ref_file = open(ref_fp)
tmp_ref_file = NamedTemporaryFile(dir=tmp_dir, suffix=".ref.fa")
for seq_id, seq in parse_fasta(user_ref_file):
id_token = seq_id.split()[0]
ref_seq_ids.add(id_token)
tmp_ref_file.write(">%s\n%s\n" % (seq_id, seq))
tmp_ref_file.seek(0)
user_tax_file = open(tax_fp)
tmp_tax_file = NamedTemporaryFile(dir=tmp_dir, suffix=".tax.txt")
for line in user_tax_file:
line = line.rstrip()
if not line:
continue
# MOTHUR is particular that each assignment end with a semicolon.
if not line.endswith(";"):
line = line + ";"
id_token, _, _ = line.partition("\t")
if id_token in ref_seq_ids:
tmp_tax_file.write(line)
tmp_tax_file.write("\n")
tmp_tax_file.seek(0)
params = {"reference": tmp_ref_file.name, "taxonomy": tmp_tax_file.name}
if cutoff is not None:
params["cutoff"] = cutoff
if ksize is not None:
params["ksize"] = ksize
if iters is not None:
params["iters"] = iters
# Create a temporary working directory to accommodate mothur's output
# files, which are generated automatically based on the input
# file.
work_dir = mkdtemp(dir=tmp_dir)
app = MothurClassifySeqs(
params, InputHandler='_input_as_lines', WorkingDir=work_dir,
TmpDir=tmp_dir)
result = app(query_file)
# Force evaluation so we can safely clean up files
assignments = list(parse_mothur_assignments(result['assignments']))
result.cleanUp()
rmtree(work_dir)
if output_fp is not None:
f = open(output_fp, "w")
for query_id, taxa, conf in assignments:
taxa_str = ";".join(taxa)
f.write("%s\t%s\t%.2f\n" % (query_id, taxa_str, conf))
f.close()
return None
return dict((a, (b, c)) for a, b, c in assignments) | python | def mothur_classify_file(
query_file, ref_fp, tax_fp, cutoff=None, iters=None, ksize=None,
output_fp=None, tmp_dir=None):
"""Classify a set of sequences using Mothur's naive bayes method
Dashes are used in Mothur to provide multiple filenames. A
filepath with a dash typically breaks an otherwise valid command
in Mothur. This wrapper script makes a copy of both files, ref_fp
and tax_fp, to ensure that the path has no dashes.
For convenience, we also ensure that each taxon list in the
id-to-taxonomy file ends with a semicolon.
"""
if tmp_dir is None:
tmp_dir = gettempdir()
ref_seq_ids = set()
user_ref_file = open(ref_fp)
tmp_ref_file = NamedTemporaryFile(dir=tmp_dir, suffix=".ref.fa")
for seq_id, seq in parse_fasta(user_ref_file):
id_token = seq_id.split()[0]
ref_seq_ids.add(id_token)
tmp_ref_file.write(">%s\n%s\n" % (seq_id, seq))
tmp_ref_file.seek(0)
user_tax_file = open(tax_fp)
tmp_tax_file = NamedTemporaryFile(dir=tmp_dir, suffix=".tax.txt")
for line in user_tax_file:
line = line.rstrip()
if not line:
continue
# MOTHUR is particular that each assignment end with a semicolon.
if not line.endswith(";"):
line = line + ";"
id_token, _, _ = line.partition("\t")
if id_token in ref_seq_ids:
tmp_tax_file.write(line)
tmp_tax_file.write("\n")
tmp_tax_file.seek(0)
params = {"reference": tmp_ref_file.name, "taxonomy": tmp_tax_file.name}
if cutoff is not None:
params["cutoff"] = cutoff
if ksize is not None:
params["ksize"] = ksize
if iters is not None:
params["iters"] = iters
# Create a temporary working directory to accommodate mothur's output
# files, which are generated automatically based on the input
# file.
work_dir = mkdtemp(dir=tmp_dir)
app = MothurClassifySeqs(
params, InputHandler='_input_as_lines', WorkingDir=work_dir,
TmpDir=tmp_dir)
result = app(query_file)
# Force evaluation so we can safely clean up files
assignments = list(parse_mothur_assignments(result['assignments']))
result.cleanUp()
rmtree(work_dir)
if output_fp is not None:
f = open(output_fp, "w")
for query_id, taxa, conf in assignments:
taxa_str = ";".join(taxa)
f.write("%s\t%s\t%.2f\n" % (query_id, taxa_str, conf))
f.close()
return None
return dict((a, (b, c)) for a, b, c in assignments) | [
"def",
"mothur_classify_file",
"(",
"query_file",
",",
"ref_fp",
",",
"tax_fp",
",",
"cutoff",
"=",
"None",
",",
"iters",
"=",
"None",
",",
"ksize",
"=",
"None",
",",
"output_fp",
"=",
"None",
",",
"tmp_dir",
"=",
"None",
")",
":",
"if",
"tmp_dir",
"is... | Classify a set of sequences using Mothur's naive bayes method
Dashes are used in Mothur to provide multiple filenames. A
filepath with a dash typically breaks an otherwise valid command
in Mothur. This wrapper script makes a copy of both files, ref_fp
and tax_fp, to ensure that the path has no dashes.
For convenience, we also ensure that each taxon list in the
id-to-taxonomy file ends with a semicolon. | [
"Classify",
"a",
"set",
"of",
"sequences",
"using",
"Mothur",
"s",
"naive",
"bayes",
"method"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L516-L589 |
biocore/burrito-fillings | bfillings/mothur.py | Mothur._compile_mothur_script | def _compile_mothur_script(self):
"""Returns a Mothur batch script as a string"""
def format_opts(*opts):
"""Formats a series of options for a Mothur script"""
return ', '.join(filter(None, map(str, opts)))
vars = {
'in': self._input_filename,
'unique': self._derive_unique_path(),
'dist': self._derive_dist_path(),
'names': self._derive_names_path(),
'cluster_opts': format_opts(
self.Parameters['method'],
self.Parameters['cutoff'],
self.Parameters['precision'],
),
}
script = (
'#'
'unique.seqs(fasta=%(in)s); '
'dist.seqs(fasta=%(unique)s); '
'read.dist(column=%(dist)s, name=%(names)s); '
'cluster(%(cluster_opts)s)' % vars
)
return script | python | def _compile_mothur_script(self):
"""Returns a Mothur batch script as a string"""
def format_opts(*opts):
"""Formats a series of options for a Mothur script"""
return ', '.join(filter(None, map(str, opts)))
vars = {
'in': self._input_filename,
'unique': self._derive_unique_path(),
'dist': self._derive_dist_path(),
'names': self._derive_names_path(),
'cluster_opts': format_opts(
self.Parameters['method'],
self.Parameters['cutoff'],
self.Parameters['precision'],
),
}
script = (
'#'
'unique.seqs(fasta=%(in)s); '
'dist.seqs(fasta=%(unique)s); '
'read.dist(column=%(dist)s, name=%(names)s); '
'cluster(%(cluster_opts)s)' % vars
)
return script | [
"def",
"_compile_mothur_script",
"(",
"self",
")",
":",
"def",
"format_opts",
"(",
"*",
"opts",
")",
":",
"\"\"\"Formats a series of options for a Mothur script\"\"\"",
"return",
"', '",
".",
"join",
"(",
"filter",
"(",
"None",
",",
"map",
"(",
"str",
",",
"opts... | Returns a Mothur batch script as a string | [
"Returns",
"a",
"Mothur",
"batch",
"script",
"as",
"a",
"string"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L212-L235 |
biocore/burrito-fillings | bfillings/mothur.py | Mothur._derive_log_path | def _derive_log_path(self):
"""Guess logfile path produced by Mothur
This method checks the working directory for log files
generated by Mothur. It will raise an ApplicationError if no
log file can be found.
Mothur generates log files named in a nondeterministic way,
using the current time. We return the log file with the most
recent time, although this may lead to incorrect log file
detection if you are running many instances of mothur
simultaneously.
"""
filenames = listdir(self.WorkingDir)
lognames = [
x for x in filenames if re.match(
"^mothur\.\d+\.logfile$",
x)]
if not lognames:
raise ApplicationError(
'No log file detected in directory %s. Contents: \n\t%s' % (
input_dir, '\n\t'.join(possible_logfiles)))
most_recent_logname = sorted(lognames, reverse=True)[0]
return path.join(self.WorkingDir, most_recent_logname) | python | def _derive_log_path(self):
"""Guess logfile path produced by Mothur
This method checks the working directory for log files
generated by Mothur. It will raise an ApplicationError if no
log file can be found.
Mothur generates log files named in a nondeterministic way,
using the current time. We return the log file with the most
recent time, although this may lead to incorrect log file
detection if you are running many instances of mothur
simultaneously.
"""
filenames = listdir(self.WorkingDir)
lognames = [
x for x in filenames if re.match(
"^mothur\.\d+\.logfile$",
x)]
if not lognames:
raise ApplicationError(
'No log file detected in directory %s. Contents: \n\t%s' % (
input_dir, '\n\t'.join(possible_logfiles)))
most_recent_logname = sorted(lognames, reverse=True)[0]
return path.join(self.WorkingDir, most_recent_logname) | [
"def",
"_derive_log_path",
"(",
"self",
")",
":",
"filenames",
"=",
"listdir",
"(",
"self",
".",
"WorkingDir",
")",
"lognames",
"=",
"[",
"x",
"for",
"x",
"in",
"filenames",
"if",
"re",
".",
"match",
"(",
"\"^mothur\\.\\d+\\.logfile$\"",
",",
"x",
")",
"... | Guess logfile path produced by Mothur
This method checks the working directory for log files
generated by Mothur. It will raise an ApplicationError if no
log file can be found.
Mothur generates log files named in a nondeterministic way,
using the current time. We return the log file with the most
recent time, although this may lead to incorrect log file
detection if you are running many instances of mothur
simultaneously. | [
"Guess",
"logfile",
"path",
"produced",
"by",
"Mothur"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L252-L275 |
biocore/burrito-fillings | bfillings/mothur.py | Mothur._derive_unique_path | def _derive_unique_path(self):
"""Guess unique sequences path produced by Mothur"""
base, ext = path.splitext(self._input_filename)
return '%s.unique%s' % (base, ext) | python | def _derive_unique_path(self):
"""Guess unique sequences path produced by Mothur"""
base, ext = path.splitext(self._input_filename)
return '%s.unique%s' % (base, ext) | [
"def",
"_derive_unique_path",
"(",
"self",
")",
":",
"base",
",",
"ext",
"=",
"path",
".",
"splitext",
"(",
"self",
".",
"_input_filename",
")",
"return",
"'%s.unique%s'",
"%",
"(",
"base",
",",
"ext",
")"
] | Guess unique sequences path produced by Mothur | [
"Guess",
"unique",
"sequences",
"path",
"produced",
"by",
"Mothur"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L277-L280 |
biocore/burrito-fillings | bfillings/mothur.py | Mothur.__get_method_abbrev | def __get_method_abbrev(self):
"""Abbreviated form of clustering method parameter.
Used to guess output filenames for MOTHUR.
"""
abbrevs = {
'furthest': 'fn',
'nearest': 'nn',
'average': 'an',
}
if self.Parameters['method'].isOn():
method = self.Parameters['method'].Value
else:
method = self.Parameters['method'].Default
return abbrevs[method] | python | def __get_method_abbrev(self):
"""Abbreviated form of clustering method parameter.
Used to guess output filenames for MOTHUR.
"""
abbrevs = {
'furthest': 'fn',
'nearest': 'nn',
'average': 'an',
}
if self.Parameters['method'].isOn():
method = self.Parameters['method'].Value
else:
method = self.Parameters['method'].Default
return abbrevs[method] | [
"def",
"__get_method_abbrev",
"(",
"self",
")",
":",
"abbrevs",
"=",
"{",
"'furthest'",
":",
"'fn'",
",",
"'nearest'",
":",
"'nn'",
",",
"'average'",
":",
"'an'",
",",
"}",
"if",
"self",
".",
"Parameters",
"[",
"'method'",
"]",
".",
"isOn",
"(",
")",
... | Abbreviated form of clustering method parameter.
Used to guess output filenames for MOTHUR. | [
"Abbreviated",
"form",
"of",
"clustering",
"method",
"parameter",
"."
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L292-L306 |
biocore/burrito-fillings | bfillings/mothur.py | Mothur._derive_list_path | def _derive_list_path(self):
"""Guess otu list file path produced by Mothur"""
base, ext = path.splitext(self._input_filename)
return '%s.unique.%s.list' % (base, self.__get_method_abbrev()) | python | def _derive_list_path(self):
"""Guess otu list file path produced by Mothur"""
base, ext = path.splitext(self._input_filename)
return '%s.unique.%s.list' % (base, self.__get_method_abbrev()) | [
"def",
"_derive_list_path",
"(",
"self",
")",
":",
"base",
",",
"ext",
"=",
"path",
".",
"splitext",
"(",
"self",
".",
"_input_filename",
")",
"return",
"'%s.unique.%s.list'",
"%",
"(",
"base",
",",
"self",
".",
"__get_method_abbrev",
"(",
")",
")"
] | Guess otu list file path produced by Mothur | [
"Guess",
"otu",
"list",
"file",
"path",
"produced",
"by",
"Mothur"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L308-L311 |
biocore/burrito-fillings | bfillings/mothur.py | Mothur._derive_rank_abundance_path | def _derive_rank_abundance_path(self):
"""Guess rank abundance file path produced by Mothur"""
base, ext = path.splitext(self._input_filename)
return '%s.unique.%s.rabund' % (base, self.__get_method_abbrev()) | python | def _derive_rank_abundance_path(self):
"""Guess rank abundance file path produced by Mothur"""
base, ext = path.splitext(self._input_filename)
return '%s.unique.%s.rabund' % (base, self.__get_method_abbrev()) | [
"def",
"_derive_rank_abundance_path",
"(",
"self",
")",
":",
"base",
",",
"ext",
"=",
"path",
".",
"splitext",
"(",
"self",
".",
"_input_filename",
")",
"return",
"'%s.unique.%s.rabund'",
"%",
"(",
"base",
",",
"self",
".",
"__get_method_abbrev",
"(",
")",
"... | Guess rank abundance file path produced by Mothur | [
"Guess",
"rank",
"abundance",
"file",
"path",
"produced",
"by",
"Mothur"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mothur.py#L313-L316 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.