code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if out_filename: params["-out"] = out_filename #else: # params["-out"] = get_tmp_filename(WorkingDir) ih = input_handler or guess_input_handler(seqs, add_seq_names) muscle_app = Muscle( params=params, InputHandler=ih, Working...
def muscle_seqs(seqs, add_seq_names=False, out_filename=None, input_handler=None, params={}, WorkingDir=tempfile.gettempdir(), SuppressStderr=None, SuppressStdout=None)
Muscle align list of sequences. seqs: a list of sequences as strings or objects, you must set add_seq_names=True or sequences in a multiline string, as read() from a fasta file or sequences in a list of lines, as readlines() from a fasta file or a fasta seq filename. == for eg, testcode for guessi...
3.211449
3.391014
0.947047
num_seqs = len(seqs) if num_seqs < 2: raise ValueError, "Muscle requres 2 or more sequences to cluster." num_chars = sum(map(len, seqs)) if num_chars > max_chars: params["-maxiters"] = 2 params["-diags1"] = True params["-sv"] = True #params["-distance1"] = ...
def cluster_seqs(seqs, neighbor_join=False, params={}, add_seq_names=True, WorkingDir=tempfile.gettempdir(), SuppressStderr=None, SuppressStdout=None, max_chars=1000000, max_hours=1.0,...
Muscle cluster list of sequences. seqs: either file name or list of sequence objects or list of strings or single multiline string containing sequences. Addl docs coming soon
4.113131
4.089662
1.005739
params["-maxhours"] = max_hours if tree_type: params["-cluster2"] = tree_type params["-tree2"] = get_tmp_filename(WorkingDir) params["-out"] = get_tmp_filename(WorkingDir) muscle_res = muscle_seqs(seqs, input_handler=input_handler, params=params, ...
def aln_tree_seqs(seqs, input_handler=None, tree_type='neighborjoining', params={}, add_seq_names=True, WorkingDir=tempfile.gettempdir(), SuppressStderr=None, SuppressStdout=None, max_...
Muscle align sequences and report tree from iteration2. Unlike cluster_seqs, returns tree2 which is the tree made during the second muscle iteration (it should be more accurate that the cluster from the first iteration which is made fast based on k-mer words) seqs: either file name or list of sequenc...
3.099916
3.276117
0.946216
if not params: params = {} #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 =...
def align_unaligned_seqs(seqs, moltype=DNA, params=None)
Returns an Alignment object from seqs. seqs: 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 Muscle app controller. Result will be an Alignment object.
4.829744
4.716523
1.024005
aln = align_unaligned_seqs(seqs, moltype=moltype, params=params) tree = build_tree_from_alignment(aln, moltype, best_tree, params) return {'Align':aln, 'Tree':tree}
def align_and_build_tree(seqs, moltype, best_tree=False, params=None)
Returns an alignment and a tree from Sequences object seqs. seqs: a cogent.core.alignment.SequenceCollection 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. ...
3.264874
4.067841
0.802606
# Create instance of app controller, enable tree, disable alignment app = Muscle(InputHandler='_input_as_multiline_string', params=params, \ WorkingDir=tempfile.gettempdir()) app.Parameters['-clusteronly'].on() app.Parameters['-tree1'].on(get_tmp_filename(app.WorkingDir)) ap...
def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params=None)
Returns a tree from Alignment object aln. aln: a cogent.core.alignment.Alignment object, or data that can be used to build one. moltype: cogent.core.moltype.MolType object best_tree: unsupported params: dict of parameters to pass in to the Muscle app controller. The result will be an cogent...
7.929642
7.37855
1.074688
if not params: params = {} #create SequenceCollection object from seqs seqs_collection = SequenceCollection(seqs) #Create mapping between abbreviated IDs and full IDs seqs_int_map, seqs_int_keys = seqs_collection.getIntMap(prefix='seq_') #Create SequenceCollection from int_map. ...
def add_seqs_to_alignment(seqs, aln, 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 Muscle ap...
2.64513
2.545307
1.039219
if not params: params = {} #create SequenceCollection object from aln1 aln1_collection = SequenceCollection(aln1) #Create mapping between abbreviated IDs and full IDs aln1_int_map, aln1_int_keys = aln1_collection.getIntMap(prefix='aln1_') #Create SequenceCollection from int_map. ...
def align_two_alignments(aln1, aln2, 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 Muscle app controller.
2.427089
2.357737
1.029415
if data: try: filename1, filename2 = data except: raise ValueError, "Expected two filenames" self.Parameters['-in'].off() self.Parameters['-in1'].on(filename1) self.Parameters['-in2'].on(filename2) retu...
def _input_as_multifile(self, data)
For use with the -profile option This input handler expects data to be a tuple containing two filenames. Index 0 will be set to -in1 and index 1 to -in2
5.221491
4.403486
1.185763
def get_example(): features = random.sample(string.ascii_letters, NUM_SAMPLES) num_capitalized = len([ letter for letter in features if letter in string.ascii_uppercase ]) num_lowercase = len([ letter for letter in features if letter in string.ascii_lowercase ]) if num_capitalized > num_lowerc...
Make an example for training and testing. Outputs a tuple (label, features) where label is +1 if capital letters are the majority, and -1 otherwise; and features is a list of letters.
null
null
null
file_hash = get_cache_buster(redis, path) return "%s/%s?v=%s" % (oz.settings["static_host"], path, file_hash)
def static_url(redis, path)
Gets the static path for a file
5.983735
6.127131
0.976596
return escape.to_unicode(redis.hget("cache-buster:{}:v3".format(oz.settings["s3_bucket"]), path))
def get_cache_buster(redis, path)
Gets the cache buster value for a given file path
15.628824
14.76685
1.058372
redis.hset("cache-buster:{}:v3".format(oz.settings["s3_bucket"]), path, hash)
def set_cache_buster(redis, path, hash)
Sets the cache buster value for a given file path
12.336738
12.727695
0.969283
global S3Connection if S3Connection != None: settings = oz.settings s3_bucket = s3_bucket or settings["s3_bucket"] opts = {} if settings["s3_host"]: opts["host"] = settings["s3_host"] if settings["aws_access_key"] and settings["aws_secret_key"]: ...
def get_bucket(s3_bucket=None, validate=False)
Gets a bucket from specified settings
2.62414
2.518389
1.041991
bucket_name = s3_bucket or oz.settings["s3_bucket"] if bucket_name: bucket = get_bucket(bucket_name) key = bucket.get_key(path) if not key: key = bucket.new_key(path) return S3File(key) else: return LocalFile(oz.settings["static_path"], path)
def get_file(path, s3_bucket=None)
Gets a file
3.019249
3.170326
0.952347
new_full_path = os.path.join(self.static_path, new_path) if replace or not os.path.exists(new_full_path): shutil.copy2(self.full_path, new_full_path) return True return False
def copy(self, new_path, replace=False)
Uses shutil to copy a file over
2.339736
2.164829
1.080795
if replace or not get_file(new_path).exists(): self.key.copy(self.key.bucket, new_path) return True return False
def copy(self, new_path, replace=False)
Uses boto to copy the file to the new path instead of uploading another file to the new key
5.487185
4.398907
1.247397
global _cached_connection settings = oz.settings if settings["redis_cache_connections"] and _cached_connection != None: return _cached_connection else: conn = redis.StrictRedis( host=settings["redis_host"], port=settings["redis_port"], db=settin...
def create_connection()
Sets up a redis configuration
1.979787
1.884429
1.050603
hit_miss_index = 0 cluster_id_index = otu_id_field seq_label_index = 8 otus = {} unassigned_seqs = [] for line in uc_lines: # skip empty, comment lines if line.startswith('#') or len(line.strip()) == 0: continue curr_line = line.split('\t') i...
def clusters_from_blast_uc_file(uc_lines, otu_id_field=1)
Parses out hit/miss sequences from usearch blast uc file All lines should be 'H'it or 'N'o hit. Returns a dict of OTU ids: sequence labels of the hits, and a list of all sequence labels that miss. uc_lines = open file object of uc file otu_id_field: uc field to use as the otu id. 1 is usearch's Clus...
2.60502
2.417358
1.077631
if not output_filepath: _, output_filepath = mkstemp(prefix='usearch_fasta_sort', suffix='.fasta') log_filepath = join(working_dir, log_name) params = {} app = Usearch(params, WorkingDir=working_dir, HALT_EXEC=HALT_EXEC) data = {'--mergesort': fa...
def usearch_fasta_sort_from_filepath( fasta_filepath, output_filepath=None, log_name="sortlen.log", HALT_EXEC=False, save_intermediate_files=False, remove_usearch_logs=False, working_dir=None)
Generates sorted fasta file via usearch --mergesort. fasta_filepath: filepath to input fasta file output_filepath: filepath for output sorted fasta file. log_name: string to specify log filename HALT_EXEC: Used for debugging app controller save_intermediate_files: Preserve all intermediate files cr...
3.578749
3.461047
1.034008
if not output_filepath: _, output_filepath = mkstemp(prefix='usearch_abundance_sorted', suffix='.fasta') log_filepath = join( working_dir, "minsize_" + str(minsize) + "_" + log_name) params = {} app = Usearch(params, WorkingDir=working...
def usearch_sort_by_abundance( fasta_filepath, output_filepath=None, sizein=True, sizeout=True, minsize=0, log_name="abundance_sort.log", usersort=False, HALT_EXEC=False, save_intermediate_files=False, remove_usearch_logs=False, wor...
Sorts fasta file by abundance fasta_filepath = input fasta file, generally a dereplicated fasta output_filepath = output abundance sorted fasta filepath sizein = not defined in usearch helpstring sizeout = not defined in usearch helpstring minsize = minimum size of cluster to retain. log_name =...
4.309338
4.565775
0.943835
if not output_filepath: _, output_filepath = mkstemp(prefix='usearch_cluster_err_corrected', suffix='.fasta') log_filepath = join(working_dir, log_name) params = {'--sizein': sizein, '--sizeout': sizeout, '--id': percent_id_err,...
def usearch_cluster_error_correction( fasta_filepath, output_filepath=None, output_uc_filepath=None, percent_id_err=0.97, sizein=True, sizeout=True, w=64, slots=16769023, maxrejects=64, log_name="usearch_cluster_err_corrected.log", ...
Cluster for err. correction at percent_id_err, output consensus fasta fasta_filepath = input fasta file, generally a dereplicated fasta output_filepath = output error corrected fasta filepath percent_id_err = minimum identity percent. sizein = not defined in usearch helpstring sizeout = not defined...
2.651961
2.77383
0.956065
if not output_chimera_filepath: _, output_chimera_filepath = mkstemp(prefix='uchime_chimeras_', suffix='.fasta') if not output_non_chimera_filepath: _, output_non_chimera_filepath = mkstemp(prefix='uchime_non_chimeras_', ...
def usearch_chimera_filter_de_novo( fasta_filepath, output_chimera_filepath=None, output_non_chimera_filepath=None, abundance_skew=2.0, log_name="uchime_de_novo_chimera_filtering.log", usersort=False, HALT_EXEC=False, save_intermediate_files=False, ...
Chimera filter de novo, output chimeras and non-chimeras to fastas fasta_filepath = input fasta file, generally a dereplicated fasta output_chimera_filepath = output chimera filepath output_non_chimera_filepath = output non chimera filepath abundance_skew = abundance skew setting for de novo filtering....
2.367947
2.385673
0.99257
output_fp = open(output_concat_filepath, "w") for label, seq in parse_fasta(open(output_fna_clustered, "U")): output_fp.write(">%s\n%s\n" % (label, seq)) for label, seq in parse_fasta(open(output_fna_failures, "U")): output_fp.write(">%s\n%s\n" % (label, seq)) return output_conca...
def concatenate_fastas(output_fna_clustered, output_fna_failures, output_concat_filepath)
Concatenates two input fastas, writes to output_concat_filepath output_fna_clustered: fasta of successful ref clusters output_fna_failures: de novo fasta of cluster failures output_concat_filepath: path to write combined fastas to
1.803838
1.844805
0.977793
fasta_i = open(fasta_filepath, "U") if not output_filepath: _, output_filepath = mkstemp(prefix='enumerated_seqs_', suffix='.fasta') fasta_o = open(output_filepath, "w") for label, seq in parse_fasta(fasta_i): curr_label = ">" + label_prefix ...
def enumerate_otus(fasta_filepath, output_filepath=None, label_prefix="", label_suffix="", retain_label_as_comment=False, count_start=0)
Writes unique, sequential count to OTUs fasta_filepath = input fasta filepath output_filepath = output fasta filepath label_prefix = string to place before enumeration label_suffix = string to place after enumeration retain_label_as_comment = if True, will place existing label in sequence comm...
2.380969
2.351099
1.012705
hit_type_index = 0 seq_label_index = 8 target_label_index = 9 labels_hits = {} labels_to_keep = [] for line in open(uc_filepath, "U"): if line.startswith("#") or len(line.strip()) == 0: continue curr_line = line.split('\t') if curr_line[0] == hit_type:...
def get_fasta_from_uc_file(fasta_filepath, uc_filepath, hit_type="H", output_fna_filepath=None, label_prefix="", output_dir=None)
writes fasta of sequences from uc file of type hit_type fasta_filepath: Filepath of original query fasta file uc_filepath: Filepath of .uc file created by usearch post error filtering hit_type: type to read from first field of .uc file, "H" for hits, "N" for no hits. output_fna_filepath = fasta ...
2.131449
2.153502
0.989759
de_novo_non_chimeras = [] reference_non_chimeras = [] de_novo_nonchimeras_f = open(output_fp_de_novo_nonchimeras, "U") reference_nonchimeras_f = open(output_fp_ref_nonchimeras, "U") output_combined_f = open(output_combined_fp, "w") for label, seq in parse_fasta(de_novo_nonchimeras_f): ...
def get_retained_chimeras(output_fp_de_novo_nonchimeras, output_fp_ref_nonchimeras, output_combined_fp, chimeras_retention='union')
Gets union or intersection of two supplied fasta files output_fp_de_novo_nonchimeras: filepath of nonchimeras from de novo usearch detection. output_fp_ref_nonchimeras: filepath of nonchimeras from reference based usearch detection. output_combined_fp: filepath to write retained sequences to. ...
1.393223
1.403234
0.992865
# Not sure if I feel confortable using blast as a way to recapitulate # original read ids.... if not output_filepath: _, output_filepath = mkstemp(prefix='assign_reads_to_otus', suffix='.uc') log_filepath = join(working_dir, log_name) params = {'-...
def assign_reads_to_otus(original_fasta, filtered_fasta, output_filepath=None, log_name="assign_reads_to_otus.log", perc_id_blast=0.97, global_alignment=True, HALT_EXEC=F...
Uses original fasta file, blasts to assign reads to filtered fasta original_fasta = filepath to original query fasta filtered_fasta = filepath to enumerated, filtered fasta output_filepath = output path to clusters (uc) file log_name = string specifying output log name perc_id_blast = percent ID fo...
4.294404
3.83967
1.11843
if not output_fna_filepath: _, output_fna_filepath = mkstemp(prefix='abundance_sorted', suffix='.fna') if not output_uc_filepath: _, output_uc_filepath = mkstemp(prefix='abundance_sorted', suffix='.uc') ...
def sort_by_abundance_usearch61(seq_path, output_dir='.', rev=False, minlen=64, remove_usearch_logs=False, HALT_EXEC=False, outp...
usearch61 application call to sort fasta file by abundance. seq_path: fasta filepath to be clustered with usearch61 output_dir: directory to output log, OTU mapping, and intermediate files rev: enable reverse strand matching for clustering/sorting minlen: minimum sequence length remove_usearch_log...
2.436877
2.502733
0.973686
if not output_fna_filepath: _, output_fna_filepath = mkstemp(prefix='length_sorted', suffix='.fna') log_filepath = join(output_dir, log_name) params = {'--minseqlength': minlen, '--sortbylength': seq_path, '--output': output_fna_filepath } if not...
def sort_by_length_usearch61(seq_path, output_dir=".", minlen=64, remove_usearch_logs=False, HALT_EXEC=False, output_fna_filepath=None, log_name="...
usearch61 application call to sort fasta file by length. seq_path: fasta filepath to be clustered with usearch61 output_dir: directory to output log, OTU mapping, and intermediate files minlen: minimum sequence length remove_usearch_logs: Saves usearch log files HALT_EXEC: application controller o...
2.75788
2.832429
0.97368
log_filepath = join(output_dir, log_filepath) params = { '--usearch_global': intermediate_fasta, '--db': refseqs_fp, '--minseqlength': minlen, '--id': percent_id, '--uc': output_uc_filepath, '--wordlength': wordlength, '--maxrejects': usearch61_maxr...
def usearch61_cluster_ref(intermediate_fasta, refseqs_fp, percent_id=0.97, rev=False, minlen=64, output_dir=".", remove_usearch_logs=False, ...
Cluster input fasta seqs against reference database seq_path: fasta filepath to be clustered with usearch61 refseqs_fp: reference fasta filepath, used to cluster sequences against. percent_id: percentage id to cluster at rev: enable reverse strand matching for clustering minlen: minimum sequence ...
2.280444
2.5387
0.898273
log_filepath = join(output_dir, log_name) params = {'--minseqlength': minlen, '--cluster_fast': intermediate_fasta, '--id': percent_id, '--uc': output_uc_filepath, '--wordlength': wordlength, '--maxrejects': usearch61_maxrejects, ...
def usearch61_fast_cluster(intermediate_fasta, percent_id=0.97, minlen=64, output_dir=".", remove_usearch_logs=False, wordlength=8, usearch61_maxrejects=8, ...
Performs usearch61 de novo fast clustering via cluster_fast option Only supposed to be used with length sorted data (and performs length sorting automatically) and does not support reverse strand matching intermediate_fasta: fasta filepath to be clustered with usearch61 percent_id: percentage id to ...
2.710952
2.870152
0.944533
log_filepath = join(output_dir, log_name) params = {'--minseqlength': minlen, '--cluster_smallmem': intermediate_fasta, '--id': percent_id, '--uc': output_uc_filepath, '--wordlength': wordlength, '--maxrejects': usearch61_maxrejects, ...
def usearch61_smallmem_cluster(intermediate_fasta, percent_id=0.97, minlen=64, rev=False, output_dir=".", remove_usearch_logs=False, w...
Performs usearch61 de novo clustering via cluster_smallmem option Only supposed to be used with length sorted data (and performs length sorting automatically) and does not support reverse strand matching intermediate_fasta: fasta filepath to be clustered with usearch61 percent_id: percentage id to c...
2.480011
2.45741
1.009197
params = {'--minseqlength': minlen, '--uchime_denovo': abundance_fp, '--uchimeout': uchime_denovo_fp, '--minh': usearch61_minh, '--xn': usearch61_xn, '--dn': usearch61_dn, '--mindiffs': usearch61_mindiffs, '--min...
def usearch61_chimera_check_denovo(abundance_fp, uchime_denovo_fp, minlen=64, output_dir=".", remove_usearch_logs=False, uchime_denovo_log_fp="uc...
Does de novo, abundance based chimera checking with usearch61 abundance_fp: input consensus fasta file with abundance information for each cluster. uchime_denovo_fp: output uchime file for chimera results. minlen: minimum sequence length for usearch input fasta seqs. output_dir: output directory ...
2.044831
2.088498
0.979092
params = {'--minseqlength': minlen, '--uchime_ref': abundance_fp, '--uchimeout': uchime_ref_fp, '--db': reference_seqs_fp, '--minh': usearch61_minh, '--xn': usearch61_xn, '--dn': usearch61_dn, '--mindiffs': usear...
def usearch61_chimera_check_ref(abundance_fp, uchime_ref_fp, reference_seqs_fp, minlen=64, output_dir=".", remove_usearch_logs=False, ...
Does reference based chimera checking with usearch61 abundance_fp: input consensus fasta file with abundance information for each cluster. uchime_ref_fp: output uchime filepath for reference results reference_seqs_fp: reference fasta database for chimera checking. minlen: minimum sequence length f...
2.59231
2.670927
0.970566
dereplicated_clusters = {} seed_hit_ix = 0 seq_id_ix = 8 seed_id_ix = 9 for line in dereplicated_uc_lines: if line.startswith("#") or len(line.strip()) == 0: continue curr_line = line.strip().split('\t') if curr_line[seed_hit_ix] == "S": derepl...
def parse_dereplicated_uc(dereplicated_uc_lines)
Return dict of seq ID:dereplicated seq IDs from dereplicated .uc lines dereplicated_uc_lines: list of lines of .uc file from dereplicated seqs from usearch61 (i.e. open file of abundance sorted .uc data)
2.3831
2.380971
1.000894
clusters = {} failures = [] seed_hit_ix = 0 otu_id_ix = 1 seq_id_ix = 8 ref_id_ix = 9 for line in clustered_uc_lines: if line.startswith("#") or len(line.strip()) == 0: continue curr_line = line.strip().split('\t') if curr_line[seed_hit_ix] == "S":...
def parse_usearch61_clusters(clustered_uc_lines, otu_prefix='denovo', ref_clustered=False)
Returns dict of cluster ID:seq IDs clustered_uc_lines: lines from .uc file resulting from de novo clustering otu_prefix: string added to beginning of OTU ID. ref_clustered: If True, will attempt to create dict keys for clusters as they are read from the .uc file, rather than from seed lines.
2.3088
2.236177
1.032477
clusters = {} for curr_denovo_key in de_novo_clusters.keys(): clusters[curr_denovo_key] = de_novo_clusters[curr_denovo_key] curr_clusters = [] for curr_denovo_id in de_novo_clusters[curr_denovo_key]: curr_clusters += dereplicated_clusters[curr_denovo_id] cluste...
def merge_clusters_dereplicated_seqs(de_novo_clusters, dereplicated_clusters)
combines de novo clusters and dereplicated seqs to OTU id:seqs dict de_novo_clusters: dict of OTU ID:clustered sequences dereplicated_clusters: dict of seq IDs: dereplicated seq IDs
2.018526
2.067259
0.976426
curr_failures = set(failures) dereplicated_ids = set(dereplicated_clusters) for curr_failure in curr_failures: if curr_failure in dereplicated_ids: failures += dereplicated_clusters[curr_failure] return failures
def merge_failures_dereplicated_seqs(failures, dereplicated_clusters)
Appends failures from dereplicated seqs to failures list failures: list of failures dereplicated_clusters: dict of seq IDs: dereplicated seq IDs
3.109963
2.816657
1.104133
parsed_out = open(output_fasta_fp, "w") for label, seq in parse_fasta(open(seq_path), "U"): curr_label = label.split()[0] if curr_label in failures: parsed_out.write(">%s\n%s\n" % (label, seq)) parsed_out.close() return output_fasta_fp
def parse_usearch61_failures(seq_path, failures, output_fasta_fp)
Parses seq IDs from failures list, writes to output_fasta_fp seq_path: filepath of original input fasta file. failures: list/set of failure seq IDs output_fasta_fp: path to write parsed sequences
2.737001
2.961669
0.924141
if oz.settings.get('debug'): exception_type, exception_value, tback = sys.exc_info() is_breakpoint = isinstance(exception_value, oz.error_pages.DebugBreakException) frames = oz.error_pages.get_frames(tback, is_breakpoint) frames.reverse() i...
def _on_error_page_write_error(self, status_code, **kwargs)
Replaces the default Tornado error page with a Django-styled one
4.178675
4.004932
1.043382
value = self.get_cookie(name) if value != None: self.clear_cookie(name) return escape.url_unescape(value)
def get_blink_cookie(self, name)
Gets a blink cookie value
4.254957
4.154637
1.024146
self.set_cookie("blink_message", escape.url_escape(message), httponly=True) self.set_cookie("blink_type", escape.url_escape(type), httponly=True)
def set_blink(self, message, type="info")
Sets the blink, a one-time transactional message that is shown on the next page load
2.973532
3.103211
0.958212
# keys are not remapped. Tested against seq_ids of 100char length seqs = SequenceCollection(seqs, MolType=moltype) #Create mapping between abbreviated IDs and full IDs int_map, int_keys = seqs.getIntMap() #Create SequenceCollection from int_map. int_map = SequenceCollection(int_map,MolType=...
def cdhit_clusters_from_seqs(seqs, moltype=DNA, params=None)
Returns the CD-HIT clusters given seqs seqs : dict like collection of sequences moltype : cogent.core.moltype object params : cd-hit parameters NOTE: This method will call CD_HIT if moltype is PROTIEN, CD_HIT_EST if moltype is RNA/DNA, and raise if any other moltype is ...
4.831007
4.534359
1.065422
# keys are not remapped. Tested against seq_ids of 100char length seqs = SequenceCollection(seqs, MolType=moltype) # setup params and make sure the output argument is set if params is None: params = {} if '-o' not in params: _, params['-o'] = mkstemp() # call the correct v...
def cdhit_from_seqs(seqs, moltype, params=None)
Returns the CD-HIT results given seqs seqs : dict like collection of sequences moltype : cogent.core.moltype object params : cd-hit parameters NOTE: This method will call CD_HIT if moltype is PROTIEN, CD_HIT_EST if moltype is RNA/DNA, and raise if any other moltype is passed.
4.98029
4.546582
1.095392
clusters = [] curr_cluster = [] for l in lines: if l.startswith('>Cluster'): if not curr_cluster: continue clusters.append(curr_cluster) curr_cluster = [] else: curr_cluster.append(clean_cluster_seq_id(l.split()[2])) ...
def parse_cdhit_clstr_file(lines)
Returns a list of list of sequence ids representing clusters
2.393203
2.249152
1.064047
if data: self.Parameters['-i']\ .on(super(CD_HIT,self)._input_as_multiline_string(data)) return ''
def _input_as_multiline_string(self, data)
Writes data to tempfile and sets -i parameter data -- list of lines
17.162863
12.525588
1.370224
if data: self.Parameters['-i']\ .on(super(CD_HIT,self)._input_as_lines(data)) return ''
def _input_as_lines(self, data)
Writes data to tempfile and sets -i parameter data -- list of lines, ready to be written to file
20.903145
14.729444
1.41914
if self.Parameters['-o'].isOn(): return ''.join([self.Parameters['-o'].Value, '.clstr']) else: raise ValueError, "No output file specified"
def _get_clstr_outfile(self)
Returns the absolute path to the clstr outfile
5.741837
4.82235
1.190672
result = {} result['FASTA'] = ResultPath(Path=self._get_seqs_outfile()) result['CLSTR'] = ResultPath(Path=self._get_clstr_outfile()) return result
def _get_result_paths(self, data)
Return dict of {key: ResultPath}
7.039823
5.394265
1.305057
look_ahead = LookAhead(tokens) segments = Segment() while not look_ahead.empty(): if look_ahead.peek().type not in self.whitespace: # Paragraph! paragraph = MatchableSegment(look_ahead.i) while not look_ahead.empty() and \ ...
def segment(self, tokens)
Segments a sequence of tokens into a sequence of segments. :Parameters: tokens : `list` ( :class:`~deltas.Token` )
2.68816
2.79005
0.963481
# we only use one conn at a time currently but we may as well do this... created_conn = False while not created_conn: if len(self.conns) == 0: self.conns.append(PushConnection(self, self.address, self.certfile, self.keyfile)) created_conn = T...
def send(self, payload, token, expiration=None, priority=None, identifier=None)
Attempts to send a push message. On network failures, progagates the exception. It is advised to make all text in the payload dictionary unicode objects and not mix unicode objects and str objects. If str objects are used, they must be in UTF-8 encoding. Args: payload (dict):...
3.963712
4.24784
0.933112
if not self.fbaddress: raise Exception("Attempted to fetch feedback but no feedback_address supplied") fbconn = FeedbackConnection(self, self.fbaddress, self.certfile, self.keyfile) return fbconn.get_all()
def get_all_feedback(self)
Connects to the feedback service and returns any feedback that is sent as a list of FeedbackItem objects. Blocks the current greenlet until all feedback is returned. If a network error occurs before any feedback is received, it is propagated to the caller. Otherwise, it is ignored and ...
6.981668
7.04724
0.990695
if response.startswith('\n'): response = response[1:] tree = etree.fromstring(response) return tree
def _parse_xml(self, response)
Run our XML parser (lxml in this case) over our response text. Lxml doesn't enjoy having xml/encoding information in the header so we strip that out if necessary. We return a parsed XML object that can be used by the calling API method and massaged into a more appropriate format.
5.308011
4.272117
1.242478
status_code = error.response.status_code message = error.message if 403 == status_code: raise NewRelicInvalidApiKeyException(message) elif 404 == status_code: raise NewRelicUnknownApplicationException(message) elif 422 == status_code: ...
def _handle_api_error(self, error)
New Relic cheerfully provides expected API error codes depending on your API call deficiencies so we convert these to exceptions and raise them for the user to handle as they see fit.
2.643079
2.245408
1.177104
current = datetime.datetime.now() try: previous = getattr(self, api_call.__name__ + "_window") # Force the calling of our property so we can # handle not having set it yet. previous.__str__ except AttributeError: now = datetime...
def _api_rate_limit_exceeded(self, api_call, window=60)
We want to keep track of the last time we sent a request to the NewRelic API, but only for certain operations. This method will dynamically add an attribute to the Client class with a unix timestamp with the name of the API api_call we make so that we can check it later. We return the a...
4.859827
4.420214
1.099455
endpoint = "https://rpm.newrelic.com" uri = "{endpoint}/accounts/{id}/applications.xml".format(endpoint=endpoint, id=self.account_id) response = self._make_get_request(uri) applications = [] for application in response.findall('.//application'): application_...
def view_applications(self)
Requires: account ID (taken from Client object) Returns: a list of Application objects Endpoint: rpm.newrelic.com Errors: 403 Invalid API Key Method: Get
3.249606
2.53195
1.28344
endpoint = "https://api.newrelic.com" uri = "{endpoint}/api/v1/accounts/{account_id}/applications/delete.xml"\ .format(endpoint=endpoint, account_id=self.account_id) payload = applications response = self._make_post_request(uri, payload) failed_deletions = ...
def delete_applications(self, applications)
Requires: account ID, application ID (or name). Input should be a dictionary { 'app_id': 1234 , 'app': 'My Application'} Returns: list of failed deletions (if any) Endpoint: api.newrelic.com Errors: None Explicit, failed deletions will be in XML Method: Post
3.770535
3.137919
1.201604
endpoint = "https://rpm.newrelic.com" uri = "{endpoint}/deployments.xml".format(endpoint=endpoint) deploy_event = {} if not application_id is None: deploy_event['deployment[application_id]'] = application_id elif not application_name is None: d...
def notify_deployment(self, application_id=None, application_name=None, description=None, revision=None, changelog=None, user=None)
Notify NewRelic of a deployment. http://newrelic.github.io/newrelic_api/NewRelicApi/Deployment.html :param description: :param revision: :param changelog: :param user: :return: A dictionary containing all of the returned keys from the API
2.069964
2.012023
1.028797
# Make sure we play it slow self._api_rate_limit_exceeded(self.get_metric_names) # Construct our GET request parameters into a nice dictionary parameters = {'re': re, 'limit': limit} endpoint = "https://api.newrelic.com" uri = "{endpoint}/api/v1/applications/{a...
def get_metric_names(self, agent_id, re=None, limit=5000)
Requires: application ID Optional: Regex to filter metric names, limit of results Returns: A dictionary, key: metric name, value: list of fields available for a given metric Method: Get Restrictions: Rate limit to 1x per minute Errors: 403...
6.556716
6.534612
1.003383
# TODO: it may be nice to have some helper methods that make it easier # to query by common time frames based off the time period folding # of the metrics returned by the New Relic API. # Make sure we aren't going to hit an API timeout self._api_rate_limit_e...
def get_metric_data(self, applications, metrics, field, begin, end, summary=False)
Requires: account ID, list of application IDs, list of metrics, metric fields, begin, end Method: Get Endpoint: api.newrelic.com Restrictions: Rate limit to 1x per minute Errors: 403 Invalid API key...
5.695838
5.585226
1.019804
endpoint = "https://rpm.newrelic.com" remote_file = "threshold_values.xml" uri = "{endpoint}/accounts/{account_id}/applications/{app_id}/{xml}".format(endpoint=endpoint, account_id=self.account_id, app_id=application_id, xml=remote_file) response = self._make_get_request(uri) ...
def get_threshold_values(self, application_id)
Requires: account ID, list of application ID Method: Get Endpoint: api.newrelic.com Restrictions: ??? Errors: 403 Invalid API key, 422 Invalid Parameters Returns: A list of threshold_value objects, each will have information about its start/end time, metric name,...
4.122794
3.96375
1.040125
endpoint = "https://api.newrelic.com" uri = "{endpoint}/api/v1/accounts/{id}/servers.xml".format(endpoint=endpoint, id=self.account_id) response = self._make_get_request(uri) servers = [] for server in response.findall('.//server'): server_properties = {} ...
def view_servers(self)
Requires: account ID (taken from Client object) Returns: a list of Server objects Endpoint: api.newrelic.com Errors: 403 Invalid API Key Method: Get
3.035821
2.644729
1.147876
endpoint = "https://api.newrelic.com" uri = "{endpoint}/api/v1/accounts/{account_id}/servers/{server_id}.xml".format( endpoint=endpoint, account_id=self.account_id, server_id=server_id) response = self._make_delete_request(uri) failed_deletion...
def delete_servers(self, server_id)
Requires: account ID, server ID Input should be server id Returns: list of failed deletions (if any) Endpoint: api.newrelic.com Errors: 403 Invalid API Key Method: Delete
2.996866
2.514813
1.191686
abs_r1_path = os.path.abspath(reads1_infile_path) abs_r2_path = os.path.abspath(reads2_infile_path) infile_paths = [abs_r1_path, abs_r2_path] # check / make absolute infile paths for p in infile_paths: if not os.path.exists(p): raise IOError('File not found at: %s' % p) ...
def join_paired_end_reads_fastqjoin( reads1_infile_path, reads2_infile_path, perc_max_diff=None, # typical default is 8 min_overlap=None, # typical default is 6 outfile_label='fastqjoin', params={}, working_dir=tempfile.gettempdir(), SuppressStderr=True,...
Runs fastq-join, with default parameters to assemble paired-end reads. Returns file path string. -reads1_infile_path : reads1.fastq infile path -reads2_infile_path : reads2.fastq infile path -perc_max_diff : maximum % diff of overlap differences allowed -min_overlap : minimum al...
2.721765
2.717186
1.001685
if self.Parameters['-o'].isOn(): output_path = self._absolute(str(self.Parameters['-o'].Value)) else: raise ValueError("No output path specified.") return output_path
def _get_output_path(self)
Checks if a base file label / path is set. Returns absolute path.
6.079585
4.926566
1.234041
if self.Parameters['-r'].isOn(): stitch_path = self._absolute(str(self.Parameters['-r'].Value)) return stitch_path elif self.Parameters['-r'].isOff(): return None
def _get_stitch_report_path(self)
Checks if stitch report label / path is set. Returns absolute path.
5.265127
4.338033
1.213713
output_path = self._get_output_path() result = {} # always output: result['Assembled'] = ResultPath(Path=output_path + 'join', IsWritten=True) result['UnassembledReads1'] = ResultPath(Path=output_path + 'un1', ...
def _get_result_paths(self, data)
Capture fastq-join output. Three output files are produced, in the form of outputjoin : assembled paired reads outputun1 : unassembled reads_1 outputun2 : unassembled reads_2 If a barcode / mate-pairs file is also provided then the following additional files...
3.180452
2.730983
1.164582
''' Given a list of fields (or several other variants of the same), return back a consistent, normalized form of the same. To forms are currently supported: dictionary form: dict 'key' is the field name and dict 'value' is either 1 (include) ...
def parse_fields(fields, as_dict=False)
Given a list of fields (or several other variants of the same), return back a consistent, normalized form of the same. To forms are currently supported: dictionary form: dict 'key' is the field name and dict 'value' is either 1 (include) ...
6.144442
1.745612
3.519936
''' Return back start and end dates given date string :param date: metrique date (range) to apply to pql query The tilde '~' symbol is used as a date range separated. A tilde by itself will mean 'all dates ranges possible' and will therefore search all objects irrelevant of it's _end date...
def date_range(date, func='date')
Return back start and end dates given date string :param date: metrique date (range) to apply to pql query The tilde '~' symbol is used as a date range separated. A tilde by itself will mean 'all dates ranges possible' and will therefore search all objects irrelevant of it's _end date timestamp. ...
6.074894
2.66265
2.281522
''' Given a SQLAlchemy Table() instance, generate a SQLAlchemy Query() instance with the given parameters. :param table: SQLAlchemy Table() instance :param query: MQL query :param date: metrique date range query :param date: metrique date range query element :param fields: list of field...
def parse(table, query=None, date=None, fields=None, distinct=False, limit=None, alias=None)
Given a SQLAlchemy Table() instance, generate a SQLAlchemy Query() instance with the given parameters. :param table: SQLAlchemy Table() instance :param query: MQL query :param date: metrique date range query :param date: metrique date range query element :param fields: list of field names to re...
4.358181
2.904865
1.500304
''' Enqueue an arbitrary synchronous function. Deprecated: Use async version instead ''' worker = self.pick_sticky(0) # just pick first always args = (func,) + func_args coro = worker.enqueue(enums.Task.FUNC, args) asyncio.ensure_future(coro)
def enqueue_sync(self, func, *func_args)
Enqueue an arbitrary synchronous function. Deprecated: Use async version instead
12.292195
8.956233
1.372474
''' Enqueue an arbitrary synchronous function. ''' worker = self.pick_sticky(0) # just pick first always args = (func,) + func_args await worker.enqueue(enums.Task.FUNC, args)
async def async_enqueue_sync(self, func, *func_args)
Enqueue an arbitrary synchronous function.
16.419867
14.146173
1.160728
''' Enqueue the download of the given foreign resource. Deprecated: Use async version instead ''' worker = self.pick_sticky(resource.url_string) coro = worker.enqueue(enums.Task.DOWNLOAD, (resource,)) asyncio.ensure_future(coro)
def enqueue_download(self, resource)
Enqueue the download of the given foreign resource. Deprecated: Use async version instead
15.359205
8.421374
1.823836
''' Enqueue the download of the given foreign resource. ''' worker = self.pick_sticky(resource.url_string) await worker.enqueue(enums.Task.DOWNLOAD, (resource,))
async def async_enqueue_download(self, resource)
Enqueue the download of the given foreign resource.
19.291233
13.049448
1.478318
''' Enqueue use of the given converter to convert to given resources. Deprecated: Use async version instead ''' worker = self.pick_sticky(from_resource.url_string) args = (converter, from_resource, to_resource) coro = worker.enqueue(enums.Task.CONVERT, ar...
def enqueue_convert(self, converter, from_resource, to_resource)
Enqueue use of the given converter to convert to given resources. Deprecated: Use async version instead
10.097931
5.383
1.875893
''' Enqueue use of the given converter to convert to given from and to resources. ''' worker = self.pick_sticky(from_.url_string) args = (converter, from_, to) await worker.enqueue(enums.Task.CONVERT, args)
async def async_enqueue_convert(self, converter, from_, to)
Enqueue use of the given converter to convert to given from and to resources.
15.685034
7.942734
1.974765
''' Enqueue a multi-step conversion process, from the given URL string (which is assumed to have been downloaded / resolved) ''' worker = self.pick_sticky(url_string) args = (url_string, to_type) await worker.enqueue(enums.Task.MULTICONVERT, args)
async def async_enqueue_multiconvert(self, url_string, to_type)
Enqueue a multi-step conversion process, from the given URL string (which is assumed to have been downloaded / resolved)
11.218478
5.017177
2.236014
''' Returns the in-plane strain assuming no lattice relaxation, which is positive for tensile strain and negative for compressive strain. ''' if self._strain_out_of_plane is not None: return ((self._strain_out_of_plane / -2.) * (self.unstrained.c11...
def strain_in_plane(self, **kwargs)
Returns the in-plane strain assuming no lattice relaxation, which is positive for tensile strain and negative for compressive strain.
6.237008
3.889457
1.603568
''' Returns the out-of-plane strain assuming no lattice relaxation, which is negative for tensile strain and positive for compressive strain. This is the strain measured by X-ray diffraction (XRD) symmetric omega-2theta scans. ''' if self._strain_out_of_plane is n...
def strain_out_of_plane(self, **kwargs)
Returns the out-of-plane strain assuming no lattice relaxation, which is negative for tensile strain and positive for compressive strain. This is the strain measured by X-ray diffraction (XRD) symmetric omega-2theta scans.
7.344341
2.550884
2.879135
''' Returns the substrate's lattice parameter. ''' if self.substrate is not None: return self.substrate.a(**kwargs) else: return (self.unstrained.a(**kwargs) / (1. - self.strain_in_plane(**kwargs)))
def substrate_a(self, **kwargs)
Returns the substrate's lattice parameter.
5.577683
3.932504
1.418354
''' Returns the strain-shifted conduction band offset (CBO), assuming the strain affects all conduction band valleys equally. ''' return self.unstrained.CBO(**kwargs) + self.CBO_strain_shift(**kwargs)
def CBO(self, **kwargs)
Returns the strain-shifted conduction band offset (CBO), assuming the strain affects all conduction band valleys equally.
15.172059
3.331132
4.554626
''' Returns the strain-shifted Gamma-valley conduction band offset (CBO), assuming the strain affects all conduction band valleys equally. ''' return (self.unstrained.CBO_Gamma(**kwargs) + self.CBO_strain_shift(**kwargs))
def CBO_Gamma(self, **kwargs)
Returns the strain-shifted Gamma-valley conduction band offset (CBO), assuming the strain affects all conduction band valleys equally.
14.926068
2.943589
5.070704
''' Returns the strain-shifted L-valley conduction band offset (CBO), assuming the strain affects all conduction band valleys equally. ''' return (self.unstrained.CBO_L(**kwargs) + self.CBO_strain_shift(**kwargs))
def CBO_L(self, **kwargs)
Returns the strain-shifted L-valley conduction band offset (CBO), assuming the strain affects all conduction band valleys equally.
14.451994
2.932606
4.928038
''' Returns the strain-shifted X-valley conduction band offset (CBO), assuming the strain affects all conduction band valleys equally. ''' return (self.unstrained.CBO_X(**kwargs) + self.CBO_strain_shift(**kwargs))
def CBO_X(self, **kwargs)
Returns the strain-shifted X-valley conduction band offset (CBO), assuming the strain affects all conduction band valleys equally.
13.609776
2.949825
4.613757
''' Returns the strain-shifted bandgap, ``Eg``. ''' return self.unstrained.Eg(**kwargs) + self.Eg_strain_shift(**kwargs)
def Eg(self, **kwargs)
Returns the strain-shifted bandgap, ``Eg``.
17.915789
5.774509
3.102565
for subsegment_or_token in self: if isinstance(subsegment_or_token, Segment): subsegment = subsegment_or_token for token in subsegment.tokens(): yield token else: token = subsegment_or_token yiel...
def tokens(self)
`generator` : the tokens in this segment
2.918841
2.348529
1.242838
return_error = { "code": self.get_status() } exc_info = kwargs.get("exc_info") if exc_info and isinstance(exc_info[1], oz.json_api.ApiError): return_error["error"] = exc_info[1].message else: return_error["error"] = API_ERROR_CODE_MAP.get(self.get_statu...
def _api_on_write_error(self, status_code, **kwargs)
Catches errors and renders it as a JSON message. Adds the traceback if debug is enabled.
4.368847
3.764472
1.160547
# Get the callback argument if JSONP is allowed callback = self.get_argument("callback", None) if oz.settings["allow_jsonp"] else None # We're pretty strict with what callback names are allowed, just in case if callback and not CALLBACK_VALIDATOR.match(callback): r...
def respond(self, obj)
Gives a response JSON(P) message
4.839264
4.798688
1.008456
if self._decoded_body == None: # Try to decode the JSON body. But raise an error if the # content-type is unexpected, or the JSON is invalid. raw_content_type = self.request.headers.get("content-type") or "" content_type = raw_content_type.split(";")[0]...
def body(self)
Gets the JSON body of the request
3.619978
3.371331
1.073753
return ''.join(map(str, filter(is_not_None, [self.Prefix, self.Name])))
def _get_id(self)
Construct and return the identifier
16.683102
12.430493
1.342111
if val is False: raise ParameterError("Turning the ValuedParameter on with value " "False is the same as turning it off. Use " "another value.") elif self.IsPath: self.Value = FilePath(val) else: ...
def on(self, val=None)
Turns the MixedParameter ON by setting its Value to val An attempt to turn the parameter on with value 'False' will result in an error, since this is the same as turning the parameter off. Turning the MixedParameter ON without a value or with value 'None' will let the parameter...
11.318591
7.653682
1.478843
''' Return a flat list of absolute paths to all assets required by this viewer ''' return sum([ [self.prefix_asset(viewer, relpath) for relpath in viewer.assets] for viewer in self.viewers ], [])
def get_assets(self)
Return a flat list of absolute paths to all assets required by this viewer
8.979395
4.736151
1.895927
''' Returns a BytesResource to build the viewers JavaScript ''' # Basename could be used for controlling caching # basename = 'viewers_%s' % settings.get_cache_string() node_packages = self.get_node_packages() # sort_keys is essential to ensure resulting string is...
def get_resource(self)
Returns a BytesResource to build the viewers JavaScript
9.215097
6.361534
1.448565
parser = ArgumentParser() subs = parser.add_subparsers(dest='cmd') setup_parser = subs.add_parser('search') setup_parser.add_argument('-e', '--engine', dest='engine', required=True, help='Search engine to use.', choices=['bing']) setup...
def main()
Run the core.
2.405166
2.407547
0.999011
message_id = request.GET.get('messageId') status_id = request.GET.get('status') status_msg = NEXMO_STATUSES.get(status_id, UNKNOWN_STATUS) error_id = int(request.GET.get('err-code')) error_msg = NEXMO_MESSAGES.get(error_id, UNKNOWN_MESSAGE) logger.info(u'Nexmo callback: Sms = %s, Status = ...
def callback(request)
Callback URL for Nexmo.
3.504843
3.21893
1.088822
''' Utilize hmac module to hash a secret, a string specifying a resource URL, and a string specifying a target type into a (string) hex digest. ''' # Normalize and sanitize input resource URL and target type, and then # convert to bytes target_type_bytes = str(TypeString(target_type)).encode...
def get_hmac_sha1_digest(secret, resource_url, target_type, api_key=None)
Utilize hmac module to hash a secret, a string specifying a resource URL, and a string specifying a target type into a (string) hex digest.
4.109401
2.901436
1.416334
if os.path.exists(DEPLOY_YAML): _yellow("\nIt looks like you've already gone through the questionnaire.") cont = prompt("Do you want to go through it again and overwrite the current one?", default="No") if cont.strip().lower() == "no": return None _green("\nWelcome to t...
def init(provider=None)
Runs through a questionnaire to set up your project's deploy settings
4.006245
3.911099
1.024327
site = init(provider) if not site: site = yaml.safe_load(_read_file(DEPLOY_YAML)) provider_class = PROVIDERS[site['provider']] provider_class.init(site)
def setup(provider=None)
Creates the provider config files needed to deploy your project
7.739685
7.548242
1.025363
if os.path.exists(DEPLOY_YAML): site = yaml.safe_load(_read_file(DEPLOY_YAML)) provider_class = PROVIDERS[site['provider']] provider_class.deploy()
def deploy(provider=None)
Deploys your project
6.597011
6.729646
0.980291