repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
phac-nml/sistr_cmd
sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py
seq_int_arr
def seq_int_arr(seqs): """Convert list of ACGT strings to matix of 1-4 ints Args: seqs (list of str): nucleotide sequences with only 'ACGT' characters Returns: numpy.array of int: matrix of integers from 1 to 4 inclusive representing A, C, G, and T str: nucleotide sequence string ...
python
def seq_int_arr(seqs): """Convert list of ACGT strings to matix of 1-4 ints Args: seqs (list of str): nucleotide sequences with only 'ACGT' characters Returns: numpy.array of int: matrix of integers from 1 to 4 inclusive representing A, C, G, and T str: nucleotide sequence string ...
[ "def", "seq_int_arr", "(", "seqs", ")", ":", "return", "np", ".", "array", "(", "[", "[", "NT_TO_INT", "[", "c", "]", "for", "c", "in", "x", ".", "upper", "(", ")", "]", "for", "x", "in", "seqs", "]", ")" ]
Convert list of ACGT strings to matix of 1-4 ints Args: seqs (list of str): nucleotide sequences with only 'ACGT' characters Returns: numpy.array of int: matrix of integers from 1 to 4 inclusive representing A, C, G, and T str: nucleotide sequence string
[ "Convert", "list", "of", "ACGT", "strings", "to", "matix", "of", "1", "-", "4", "ints" ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py#L19-L29
train
phac-nml/sistr_cmd
sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py
group_alleles_by_start_end_Xbp
def group_alleles_by_start_end_Xbp(arr, bp=28): """Group alleles by matching ends Args: arr (numpy.array): 2D int matrix of alleles bp (int): length of ends to group by Returns: dict of lists: key of start + end strings to list of indices of alleles with matching ends """ s...
python
def group_alleles_by_start_end_Xbp(arr, bp=28): """Group alleles by matching ends Args: arr (numpy.array): 2D int matrix of alleles bp (int): length of ends to group by Returns: dict of lists: key of start + end strings to list of indices of alleles with matching ends """ s...
[ "def", "group_alleles_by_start_end_Xbp", "(", "arr", ",", "bp", "=", "28", ")", ":", "starts", "=", "arr", "[", ":", ",", "0", ":", "bp", "]", "ends", "=", "arr", "[", ":", ",", "-", "bp", ":", "]", "starts_ends_idxs", "=", "defaultdict", "(", "lis...
Group alleles by matching ends Args: arr (numpy.array): 2D int matrix of alleles bp (int): length of ends to group by Returns: dict of lists: key of start + end strings to list of indices of alleles with matching ends
[ "Group", "alleles", "by", "matching", "ends" ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py#L32-L52
train
phac-nml/sistr_cmd
sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py
allele_clusters
def allele_clusters(dists, t=0.025): """Flat clusters from distance matrix Args: dists (numpy.array): pdist distance matrix t (float): fcluster (tree cutting) distance threshold Returns: dict of lists: cluster number to list of indices of distances in cluster """ clusters =...
python
def allele_clusters(dists, t=0.025): """Flat clusters from distance matrix Args: dists (numpy.array): pdist distance matrix t (float): fcluster (tree cutting) distance threshold Returns: dict of lists: cluster number to list of indices of distances in cluster """ clusters =...
[ "def", "allele_clusters", "(", "dists", ",", "t", "=", "0.025", ")", ":", "clusters", "=", "fcluster", "(", "linkage", "(", "dists", ")", ",", "0.025", ",", "criterion", "=", "'distance'", ")", "cluster_idx", "=", "defaultdict", "(", "list", ")", "for", ...
Flat clusters from distance matrix Args: dists (numpy.array): pdist distance matrix t (float): fcluster (tree cutting) distance threshold Returns: dict of lists: cluster number to list of indices of distances in cluster
[ "Flat", "clusters", "from", "distance", "matrix" ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py#L55-L69
train
phac-nml/sistr_cmd
sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py
min_row_dist_sum_idx
def min_row_dist_sum_idx(dists): """Find the index of the row with the minimum row distance sum This should return the index of the row index with the least distance overall to all other rows. Args: dists (np.array): must be square distance matrix Returns: int: index of row wit...
python
def min_row_dist_sum_idx(dists): """Find the index of the row with the minimum row distance sum This should return the index of the row index with the least distance overall to all other rows. Args: dists (np.array): must be square distance matrix Returns: int: index of row wit...
[ "def", "min_row_dist_sum_idx", "(", "dists", ")", ":", "row_sums", "=", "np", ".", "apply_along_axis", "(", "arr", "=", "dists", ",", "axis", "=", "0", ",", "func1d", "=", "np", ".", "sum", ")", "return", "row_sums", ".", "argmin", "(", ")" ]
Find the index of the row with the minimum row distance sum This should return the index of the row index with the least distance overall to all other rows. Args: dists (np.array): must be square distance matrix Returns: int: index of row with min dist row sum
[ "Find", "the", "index", "of", "the", "row", "with", "the", "minimum", "row", "distance", "sum" ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py#L84-L97
train
phac-nml/sistr_cmd
sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py
find_centroid_alleles
def find_centroid_alleles(alleles, bp=28, t=0.025): """Reduce list of alleles to set of centroid alleles based on size grouping, ends matching and hierarchical clustering Workflow for finding centroid alleles: - grouping by size (e.g. 100bp, 101bp, 103bp, etc) - then grouped by `bp` nucleotides at end...
python
def find_centroid_alleles(alleles, bp=28, t=0.025): """Reduce list of alleles to set of centroid alleles based on size grouping, ends matching and hierarchical clustering Workflow for finding centroid alleles: - grouping by size (e.g. 100bp, 101bp, 103bp, etc) - then grouped by `bp` nucleotides at end...
[ "def", "find_centroid_alleles", "(", "alleles", ",", "bp", "=", "28", ",", "t", "=", "0.025", ")", ":", "centroid_alleles", "=", "set", "(", ")", "len_allele", "=", "group_alleles_by_size", "(", "alleles", ")", "for", "length", ",", "seqs", "in", "len_alle...
Reduce list of alleles to set of centroid alleles based on size grouping, ends matching and hierarchical clustering Workflow for finding centroid alleles: - grouping by size (e.g. 100bp, 101bp, 103bp, etc) - then grouped by `bp` nucleotides at ends matching - size and ends grouped alleles hierarchical...
[ "Reduce", "list", "of", "alleles", "to", "set", "of", "centroid", "alleles", "based", "on", "size", "grouping", "ends", "matching", "and", "hierarchical", "clustering" ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py#L112-L169
train
phac-nml/sistr_cmd
sistr/src/mash.py
mash_dist_trusted
def mash_dist_trusted(fasta_path): """ Compute Mash distances of sketch file of genome fasta to RefSeq sketch DB. Args: mash_bin (str): Mash binary path Returns: (str): Mash STDOUT string """ args = [MASH_BIN, 'dist', MASH_SKETCH_FILE, fasta_...
python
def mash_dist_trusted(fasta_path): """ Compute Mash distances of sketch file of genome fasta to RefSeq sketch DB. Args: mash_bin (str): Mash binary path Returns: (str): Mash STDOUT string """ args = [MASH_BIN, 'dist', MASH_SKETCH_FILE, fasta_...
[ "def", "mash_dist_trusted", "(", "fasta_path", ")", ":", "args", "=", "[", "MASH_BIN", ",", "'dist'", ",", "MASH_SKETCH_FILE", ",", "fasta_path", "]", "p", "=", "Popen", "(", "args", ",", "stderr", "=", "PIPE", ",", "stdout", "=", "PIPE", ")", "(", "st...
Compute Mash distances of sketch file of genome fasta to RefSeq sketch DB. Args: mash_bin (str): Mash binary path Returns: (str): Mash STDOUT string
[ "Compute", "Mash", "distances", "of", "sketch", "file", "of", "genome", "fasta", "to", "RefSeq", "sketch", "DB", "." ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/mash.py#L14-L34
train
phac-nml/sistr_cmd
sistr/src/cgmlst/extras/hclust_cutree.py
nr_profiles
def nr_profiles(arr, genomes): """ Get a condensed cgMLST pairwise distance matrix for specified Genomes_ where condensed means redundant cgMLST profiles are only represented once in the distance matrix. Args: user_name (list): List of Genome_ names to retrieve condensed distance matrix for ...
python
def nr_profiles(arr, genomes): """ Get a condensed cgMLST pairwise distance matrix for specified Genomes_ where condensed means redundant cgMLST profiles are only represented once in the distance matrix. Args: user_name (list): List of Genome_ names to retrieve condensed distance matrix for ...
[ "def", "nr_profiles", "(", "arr", ",", "genomes", ")", ":", "gs_collapse", "=", "[", "]", "genome_idx_dict", "=", "{", "}", "indices", "=", "[", "]", "patt_dict", "=", "{", "}", "for", "i", ",", "g", "in", "enumerate", "(", "genomes", ")", ":", "p"...
Get a condensed cgMLST pairwise distance matrix for specified Genomes_ where condensed means redundant cgMLST profiles are only represented once in the distance matrix. Args: user_name (list): List of Genome_ names to retrieve condensed distance matrix for Returns: (numpy.array, list): tup...
[ "Get", "a", "condensed", "cgMLST", "pairwise", "distance", "matrix", "for", "specified", "Genomes_", "where", "condensed", "means", "redundant", "cgMLST", "profiles", "are", "only", "represented", "once", "in", "the", "distance", "matrix", "." ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/extras/hclust_cutree.py#L19-L45
train
phac-nml/sistr_cmd
sistr/src/serovar_prediction/__init__.py
overall_serovar_call
def overall_serovar_call(serovar_prediction, antigen_predictor): """ Predict serovar from cgMLST cluster membership analysis and antigen BLAST results. SerovarPrediction object is assigned H1, H2 and Serogroup from the antigen BLAST results. Antigen BLAST results will predict a particular serovar or lis...
python
def overall_serovar_call(serovar_prediction, antigen_predictor): """ Predict serovar from cgMLST cluster membership analysis and antigen BLAST results. SerovarPrediction object is assigned H1, H2 and Serogroup from the antigen BLAST results. Antigen BLAST results will predict a particular serovar or lis...
[ "def", "overall_serovar_call", "(", "serovar_prediction", ",", "antigen_predictor", ")", ":", "assert", "isinstance", "(", "serovar_prediction", ",", "SerovarPrediction", ")", "assert", "isinstance", "(", "antigen_predictor", ",", "SerovarPredictor", ")", "h1", "=", "...
Predict serovar from cgMLST cluster membership analysis and antigen BLAST results. SerovarPrediction object is assigned H1, H2 and Serogroup from the antigen BLAST results. Antigen BLAST results will predict a particular serovar or list of serovars, however, the cgMLST membership may be able to help narrow ...
[ "Predict", "serovar", "from", "cgMLST", "cluster", "membership", "analysis", "and", "antigen", "BLAST", "results", ".", "SerovarPrediction", "object", "is", "assigned", "H1", "H2", "and", "Serogroup", "from", "the", "antigen", "BLAST", "results", ".", "Antigen", ...
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/serovar_prediction/__init__.py#L434-L540
train
phac-nml/sistr_cmd
sistr/src/cgmlst/__init__.py
process_cgmlst_results
def process_cgmlst_results(df): """Append informative fields to cgMLST330 BLAST results DataFrame The `qseqid` column must contain cgMLST330 query IDs with `{marker name}|{allele number}` format. The `qseqid` parsed allele numbers and marker names are appended as new fields. `is_perfect` column contai...
python
def process_cgmlst_results(df): """Append informative fields to cgMLST330 BLAST results DataFrame The `qseqid` column must contain cgMLST330 query IDs with `{marker name}|{allele number}` format. The `qseqid` parsed allele numbers and marker names are appended as new fields. `is_perfect` column contai...
[ "def", "process_cgmlst_results", "(", "df", ")", ":", "assert", "isinstance", "(", "df", ",", "pd", ".", "DataFrame", ")", "markers", "=", "[", "]", "alleles", "=", "[", "]", "for", "x", "in", "df", "[", "'qseqid'", "]", ":", "marker", ",", "allele",...
Append informative fields to cgMLST330 BLAST results DataFrame The `qseqid` column must contain cgMLST330 query IDs with `{marker name}|{allele number}` format. The `qseqid` parsed allele numbers and marker names are appended as new fields. `is_perfect` column contains boolean values for whether an allele...
[ "Append", "informative", "fields", "to", "cgMLST330", "BLAST", "results", "DataFrame" ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/__init__.py#L40-L82
train
phac-nml/sistr_cmd
sistr/src/cgmlst/__init__.py
alleles_to_retrieve
def alleles_to_retrieve(df): """Alleles to retrieve from genome fasta Get a dict of the genome fasta contig title to a list of blastn results of the allele sequences that must be retrieved from the genome contig. Args: df (pandas.DataFrame): blastn results dataframe Returns: {str:...
python
def alleles_to_retrieve(df): """Alleles to retrieve from genome fasta Get a dict of the genome fasta contig title to a list of blastn results of the allele sequences that must be retrieved from the genome contig. Args: df (pandas.DataFrame): blastn results dataframe Returns: {str:...
[ "def", "alleles_to_retrieve", "(", "df", ")", ":", "contig_blastn_records", "=", "defaultdict", "(", "list", ")", "markers", "=", "df", ".", "marker", ".", "unique", "(", ")", "for", "m", "in", "markers", ":", "dfsub", "=", "df", "[", "df", ".", "marke...
Alleles to retrieve from genome fasta Get a dict of the genome fasta contig title to a list of blastn results of the allele sequences that must be retrieved from the genome contig. Args: df (pandas.DataFrame): blastn results dataframe Returns: {str:[pandas.Series]}: dict of contig tit...
[ "Alleles", "to", "retrieve", "from", "genome", "fasta" ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/__init__.py#L85-L106
train
phac-nml/sistr_cmd
sistr/src/cgmlst/__init__.py
matches_to_marker_results
def matches_to_marker_results(df): """Perfect BLAST matches to marker results dict Parse perfect BLAST matches to marker results dict. Args: df (pandas.DataFrame): DataFrame of perfect BLAST matches Returns: dict: cgMLST330 marker names to matching allele numbers """ assert i...
python
def matches_to_marker_results(df): """Perfect BLAST matches to marker results dict Parse perfect BLAST matches to marker results dict. Args: df (pandas.DataFrame): DataFrame of perfect BLAST matches Returns: dict: cgMLST330 marker names to matching allele numbers """ assert i...
[ "def", "matches_to_marker_results", "(", "df", ")", ":", "assert", "isinstance", "(", "df", ",", "pd", ".", "DataFrame", ")", "from", "collections", "import", "defaultdict", "d", "=", "defaultdict", "(", "list", ")", "for", "idx", ",", "row", "in", "df", ...
Perfect BLAST matches to marker results dict Parse perfect BLAST matches to marker results dict. Args: df (pandas.DataFrame): DataFrame of perfect BLAST matches Returns: dict: cgMLST330 marker names to matching allele numbers
[ "Perfect", "BLAST", "matches", "to", "marker", "results", "dict" ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/__init__.py#L186-L234
train
phac-nml/sistr_cmd
sistr/src/cgmlst/__init__.py
cgmlst_subspecies_call
def cgmlst_subspecies_call(df_relatives): """Call Salmonella subspecies based on cgMLST results This method attempts to find the majority subspecies type within curated public genomes above a cgMLST allelic profile distance threshold. Note: ``CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD`` is the cg...
python
def cgmlst_subspecies_call(df_relatives): """Call Salmonella subspecies based on cgMLST results This method attempts to find the majority subspecies type within curated public genomes above a cgMLST allelic profile distance threshold. Note: ``CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD`` is the cg...
[ "def", "cgmlst_subspecies_call", "(", "df_relatives", ")", ":", "closest_distance", "=", "df_relatives", "[", "'distance'", "]", ".", "min", "(", ")", "if", "closest_distance", ">", "CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD", ":", "logging", ".", "warning", "(", "'Mi...
Call Salmonella subspecies based on cgMLST results This method attempts to find the majority subspecies type within curated public genomes above a cgMLST allelic profile distance threshold. Note: ``CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD`` is the cgMLST distance threshold used to determine...
[ "Call", "Salmonella", "subspecies", "based", "on", "cgMLST", "results" ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/__init__.py#L262-L300
train
phac-nml/sistr_cmd
sistr/sistr_cmd.py
genome_name_from_fasta_path
def genome_name_from_fasta_path(fasta_path): """Extract genome name from fasta filename Get the filename without directory and remove the file extension. Example: With fasta file path ``/path/to/genome_1.fasta``:: fasta_path = '/path/to/genome_1.fasta' genome_name = genome...
python
def genome_name_from_fasta_path(fasta_path): """Extract genome name from fasta filename Get the filename without directory and remove the file extension. Example: With fasta file path ``/path/to/genome_1.fasta``:: fasta_path = '/path/to/genome_1.fasta' genome_name = genome...
[ "def", "genome_name_from_fasta_path", "(", "fasta_path", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "fasta_path", ")", "return", "re", ".", "sub", "(", "r'(\\.fa$)|(\\.fas$)|(\\.fasta$)|(\\.fna$)|(\\.\\w{1,}$)'", ",", "''", ",", "filename", ...
Extract genome name from fasta filename Get the filename without directory and remove the file extension. Example: With fasta file path ``/path/to/genome_1.fasta``:: fasta_path = '/path/to/genome_1.fasta' genome_name = genome_name_from_fasta_path(fasta_path) print(...
[ "Extract", "genome", "name", "from", "fasta", "filename" ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/sistr_cmd.py#L234-L254
train
phac-nml/sistr_cmd
sistr/src/blast_wrapper/__init__.py
BlastReader.df_first_row_to_dict
def df_first_row_to_dict(df): """First DataFrame row to list of dict Args: df (pandas.DataFrame): A DataFrame with at least one row Returns: A list of dict that looks like: [{'C1': 'x'}, {'C2': 'y'}, {'C3': 'z'}] from a DataFrame that looks...
python
def df_first_row_to_dict(df): """First DataFrame row to list of dict Args: df (pandas.DataFrame): A DataFrame with at least one row Returns: A list of dict that looks like: [{'C1': 'x'}, {'C2': 'y'}, {'C3': 'z'}] from a DataFrame that looks...
[ "def", "df_first_row_to_dict", "(", "df", ")", ":", "if", "df", "is", "not", "None", ":", "return", "[", "dict", "(", "r", ")", "for", "i", ",", "r", "in", "df", ".", "head", "(", "1", ")", ".", "iterrows", "(", ")", "]", "[", "0", "]" ]
First DataFrame row to list of dict Args: df (pandas.DataFrame): A DataFrame with at least one row Returns: A list of dict that looks like: [{'C1': 'x'}, {'C2': 'y'}, {'C3': 'z'}] from a DataFrame that looks like: C1 C2 C3 ...
[ "First", "DataFrame", "row", "to", "list", "of", "dict" ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/blast_wrapper/__init__.py#L200-L219
train
phac-nml/sistr_cmd
sistr/misc/add_ref_genomes.py
sketch_fasta
def sketch_fasta(fasta_path, outdir): """Create a Mash sketch from an input fasta file Args: fasta_path (str): input fasta file path. Genome name in fasta filename outdir (str): output directory path to write Mash sketch file to Returns: str: output Mash sketch file path """ ...
python
def sketch_fasta(fasta_path, outdir): """Create a Mash sketch from an input fasta file Args: fasta_path (str): input fasta file path. Genome name in fasta filename outdir (str): output directory path to write Mash sketch file to Returns: str: output Mash sketch file path """ ...
[ "def", "sketch_fasta", "(", "fasta_path", ",", "outdir", ")", ":", "genome_name", "=", "genome_name_from_fasta_path", "(", "fasta_path", ")", "outpath", "=", "os", ".", "path", ".", "join", "(", "outdir", ",", "genome_name", ")", "args", "=", "[", "'mash'", ...
Create a Mash sketch from an input fasta file Args: fasta_path (str): input fasta file path. Genome name in fasta filename outdir (str): output directory path to write Mash sketch file to Returns: str: output Mash sketch file path
[ "Create", "a", "Mash", "sketch", "from", "an", "input", "fasta", "file" ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/misc/add_ref_genomes.py#L65-L85
train
phac-nml/sistr_cmd
sistr/misc/add_ref_genomes.py
merge_sketches
def merge_sketches(outdir, sketch_paths): """Merge new Mash sketches with current Mash sketches Args: outdir (str): output directory to write merged Mash sketch file sketch_paths (list of str): Mash sketch file paths for input fasta files Returns: str: output path for Mash sketch f...
python
def merge_sketches(outdir, sketch_paths): """Merge new Mash sketches with current Mash sketches Args: outdir (str): output directory to write merged Mash sketch file sketch_paths (list of str): Mash sketch file paths for input fasta files Returns: str: output path for Mash sketch f...
[ "def", "merge_sketches", "(", "outdir", ",", "sketch_paths", ")", ":", "merge_sketch_path", "=", "os", ".", "path", ".", "join", "(", "outdir", ",", "'sistr.msh'", ")", "args", "=", "[", "'mash'", ",", "'paste'", ",", "merge_sketch_path", "]", "for", "x", ...
Merge new Mash sketches with current Mash sketches Args: outdir (str): output directory to write merged Mash sketch file sketch_paths (list of str): Mash sketch file paths for input fasta files Returns: str: output path for Mash sketch file with new and old sketches
[ "Merge", "new", "Mash", "sketches", "with", "current", "Mash", "sketches" ]
4630fae72439723b354a94b94fbe76ad2f9f6295
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/misc/add_ref_genomes.py#L88-L107
train
mbr/simplekv
simplekv/__init__.py
KeyValueStore.get_file
def get_file(self, key, file): """Write contents of key to file Like :meth:`.KeyValueStore.put_file`, this method allows backends to implement a specialized function if data needs to be written to disk or streamed. If *file* is a string, contents of *key* are written to a newly...
python
def get_file(self, key, file): """Write contents of key to file Like :meth:`.KeyValueStore.put_file`, this method allows backends to implement a specialized function if data needs to be written to disk or streamed. If *file* is a string, contents of *key* are written to a newly...
[ "def", "get_file", "(", "self", ",", "key", ",", "file", ")", ":", "self", ".", "_check_valid_key", "(", "key", ")", "if", "isinstance", "(", "file", ",", "str", ")", ":", "return", "self", ".", "_get_filename", "(", "key", ",", "file", ")", "else", ...
Write contents of key to file Like :meth:`.KeyValueStore.put_file`, this method allows backends to implement a specialized function if data needs to be written to disk or streamed. If *file* is a string, contents of *key* are written to a newly created file with the filename *f...
[ "Write", "contents", "of", "key", "to", "file" ]
fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6
https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/__init__.py#L77-L100
train
mbr/simplekv
simplekv/__init__.py
KeyValueStore.put_file
def put_file(self, key, file): """Store into key from file on disk Stores data from a source into key. *file* can either be a string, which will be interpretet as a filename, or an object with a *read()* method. If the passed object has a *fileno()* method, it may be used to sp...
python
def put_file(self, key, file): """Store into key from file on disk Stores data from a source into key. *file* can either be a string, which will be interpretet as a filename, or an object with a *read()* method. If the passed object has a *fileno()* method, it may be used to sp...
[ "def", "put_file", "(", "self", ",", "key", ",", "file", ")", ":", "if", "isinstance", "(", "file", ",", "str", ")", ":", "return", "self", ".", "_put_filename", "(", "key", ",", "file", ")", "else", ":", "return", "self", ".", "_put_file", "(", "k...
Store into key from file on disk Stores data from a source into key. *file* can either be a string, which will be interpretet as a filename, or an object with a *read()* method. If the passed object has a *fileno()* method, it may be used to speed up the operation. The...
[ "Store", "into", "key", "from", "file", "on", "disk" ]
fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6
https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/__init__.py#L152-L179
train
mbr/simplekv
simplekv/__init__.py
CopyMixin.copy
def copy(self, source, dest): """Copies a key. The destination is overwritten if does exist. :param source: The source key to copy :param dest: The destination for the copy :returns: The destination key :raises: exceptions.ValueError: If the source or target key are not valid ...
python
def copy(self, source, dest): """Copies a key. The destination is overwritten if does exist. :param source: The source key to copy :param dest: The destination for the copy :returns: The destination key :raises: exceptions.ValueError: If the source or target key are not valid ...
[ "def", "copy", "(", "self", ",", "source", ",", "dest", ")", ":", "self", ".", "_check_valid_key", "(", "source", ")", "self", ".", "_check_valid_key", "(", "dest", ")", "return", "self", ".", "_copy", "(", "source", ",", "dest", ")" ]
Copies a key. The destination is overwritten if does exist. :param source: The source key to copy :param dest: The destination for the copy :returns: The destination key :raises: exceptions.ValueError: If the source or target key are not valid :raises: exceptions.KeyError: If ...
[ "Copies", "a", "key", ".", "The", "destination", "is", "overwritten", "if", "does", "exist", "." ]
fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6
https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/__init__.py#L441-L453
train
napalm-automation/napalm-eos
napalm_eos/eos.py
EOSDriver.compare_config
def compare_config(self): """Implementation of NAPALM method compare_config.""" if self.config_session is None: return '' else: commands = ['show session-config named %s diffs' % self.config_session] result = self.device.run_commands(commands, encoding='text')...
python
def compare_config(self): """Implementation of NAPALM method compare_config.""" if self.config_session is None: return '' else: commands = ['show session-config named %s diffs' % self.config_session] result = self.device.run_commands(commands, encoding='text')...
[ "def", "compare_config", "(", "self", ")", ":", "if", "self", ".", "config_session", "is", "None", ":", "return", "''", "else", ":", "commands", "=", "[", "'show session-config named %s diffs'", "%", "self", ".", "config_session", "]", "result", "=", "self", ...
Implementation of NAPALM method compare_config.
[ "Implementation", "of", "NAPALM", "method", "compare_config", "." ]
a3b37d6ee353e326ab9ea1a09ecc14045b12928b
https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L178-L188
train
napalm-automation/napalm-eos
napalm_eos/eos.py
EOSDriver.discard_config
def discard_config(self): """Implementation of NAPALM method discard_config.""" if self.config_session is not None: commands = [] commands.append('configure session {}'.format(self.config_session)) commands.append('abort') self.device.run_commands(commands...
python
def discard_config(self): """Implementation of NAPALM method discard_config.""" if self.config_session is not None: commands = [] commands.append('configure session {}'.format(self.config_session)) commands.append('abort') self.device.run_commands(commands...
[ "def", "discard_config", "(", "self", ")", ":", "if", "self", ".", "config_session", "is", "not", "None", ":", "commands", "=", "[", "]", "commands", ".", "append", "(", "'configure session {}'", ".", "format", "(", "self", ".", "config_session", ")", ")",...
Implementation of NAPALM method discard_config.
[ "Implementation", "of", "NAPALM", "method", "discard_config", "." ]
a3b37d6ee353e326ab9ea1a09ecc14045b12928b
https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L201-L208
train
napalm-automation/napalm-eos
napalm_eos/eos.py
EOSDriver.rollback
def rollback(self): """Implementation of NAPALM method rollback.""" commands = [] commands.append('configure replace flash:rollback-0') commands.append('write memory') self.device.run_commands(commands)
python
def rollback(self): """Implementation of NAPALM method rollback.""" commands = [] commands.append('configure replace flash:rollback-0') commands.append('write memory') self.device.run_commands(commands)
[ "def", "rollback", "(", "self", ")", ":", "commands", "=", "[", "]", "commands", ".", "append", "(", "'configure replace flash:rollback-0'", ")", "commands", ".", "append", "(", "'write memory'", ")", "self", ".", "device", ".", "run_commands", "(", "commands"...
Implementation of NAPALM method rollback.
[ "Implementation", "of", "NAPALM", "method", "rollback", "." ]
a3b37d6ee353e326ab9ea1a09ecc14045b12928b
https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L210-L215
train
napalm-automation/napalm-eos
napalm_eos/eos.py
EOSDriver.get_facts
def get_facts(self): """Implementation of NAPALM method get_facts.""" commands = [] commands.append('show version') commands.append('show hostname') commands.append('show interfaces') result = self.device.run_commands(commands) version = result[0] hostna...
python
def get_facts(self): """Implementation of NAPALM method get_facts.""" commands = [] commands.append('show version') commands.append('show hostname') commands.append('show interfaces') result = self.device.run_commands(commands) version = result[0] hostna...
[ "def", "get_facts", "(", "self", ")", ":", "commands", "=", "[", "]", "commands", ".", "append", "(", "'show version'", ")", "commands", ".", "append", "(", "'show hostname'", ")", "commands", ".", "append", "(", "'show interfaces'", ")", "result", "=", "s...
Implementation of NAPALM method get_facts.
[ "Implementation", "of", "NAPALM", "method", "get_facts", "." ]
a3b37d6ee353e326ab9ea1a09ecc14045b12928b
https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L217-L244
train
napalm-automation/napalm-eos
napalm_eos/eos.py
EOSDriver.get_config
def get_config(self, retrieve="all"): """get_config implementation for EOS.""" get_startup = retrieve == "all" or retrieve == "startup" get_running = retrieve == "all" or retrieve == "running" get_candidate = (retrieve == "all" or retrieve == "candidate") and self.config_session ...
python
def get_config(self, retrieve="all"): """get_config implementation for EOS.""" get_startup = retrieve == "all" or retrieve == "startup" get_running = retrieve == "all" or retrieve == "running" get_candidate = (retrieve == "all" or retrieve == "candidate") and self.config_session ...
[ "def", "get_config", "(", "self", ",", "retrieve", "=", "\"all\"", ")", ":", "get_startup", "=", "retrieve", "==", "\"all\"", "or", "retrieve", "==", "\"startup\"", "get_running", "=", "retrieve", "==", "\"all\"", "or", "retrieve", "==", "\"running\"", "get_ca...
get_config implementation for EOS.
[ "get_config", "implementation", "for", "EOS", "." ]
a3b37d6ee353e326ab9ea1a09ecc14045b12928b
https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L1517-L1560
train
mbr/simplekv
simplekv/net/botostore.py
map_boto_exceptions
def map_boto_exceptions(key=None, exc_pass=()): """Map boto-specific exceptions to the simplekv-API.""" from boto.exception import BotoClientError, BotoServerError, \ StorageResponseError try: yield except StorageResponseError as e: if e.code == 'NoSuchKey': raise Key...
python
def map_boto_exceptions(key=None, exc_pass=()): """Map boto-specific exceptions to the simplekv-API.""" from boto.exception import BotoClientError, BotoServerError, \ StorageResponseError try: yield except StorageResponseError as e: if e.code == 'NoSuchKey': raise Key...
[ "def", "map_boto_exceptions", "(", "key", "=", "None", ",", "exc_pass", "=", "(", ")", ")", ":", "from", "boto", ".", "exception", "import", "BotoClientError", ",", "BotoServerError", ",", "StorageResponseError", "try", ":", "yield", "except", "StorageResponseEr...
Map boto-specific exceptions to the simplekv-API.
[ "Map", "boto", "-", "specific", "exceptions", "to", "the", "simplekv", "-", "API", "." ]
fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6
https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/net/botostore.py#L11-L23
train
mbr/simplekv
simplekv/net/azurestore.py
_file_md5
def _file_md5(file_): """ Compute the md5 digest of a file in base64 encoding. """ md5 = hashlib.md5() chunk_size = 128 * md5.block_size for chunk in iter(lambda: file_.read(chunk_size), b''): md5.update(chunk) file_.seek(0) byte_digest = md5.digest() return base64.b64encode(...
python
def _file_md5(file_): """ Compute the md5 digest of a file in base64 encoding. """ md5 = hashlib.md5() chunk_size = 128 * md5.block_size for chunk in iter(lambda: file_.read(chunk_size), b''): md5.update(chunk) file_.seek(0) byte_digest = md5.digest() return base64.b64encode(...
[ "def", "_file_md5", "(", "file_", ")", ":", "md5", "=", "hashlib", ".", "md5", "(", ")", "chunk_size", "=", "128", "*", "md5", ".", "block_size", "for", "chunk", "in", "iter", "(", "lambda", ":", "file_", ".", "read", "(", "chunk_size", ")", ",", "...
Compute the md5 digest of a file in base64 encoding.
[ "Compute", "the", "md5", "digest", "of", "a", "file", "in", "base64", "encoding", "." ]
fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6
https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/net/azurestore.py#L25-L35
train
mbr/simplekv
simplekv/net/azurestore.py
_byte_buffer_md5
def _byte_buffer_md5(buffer_): """ Computes the md5 digest of a byte buffer in base64 encoding. """ md5 = hashlib.md5(buffer_) byte_digest = md5.digest() return base64.b64encode(byte_digest).decode()
python
def _byte_buffer_md5(buffer_): """ Computes the md5 digest of a byte buffer in base64 encoding. """ md5 = hashlib.md5(buffer_) byte_digest = md5.digest() return base64.b64encode(byte_digest).decode()
[ "def", "_byte_buffer_md5", "(", "buffer_", ")", ":", "md5", "=", "hashlib", ".", "md5", "(", "buffer_", ")", "byte_digest", "=", "md5", ".", "digest", "(", ")", "return", "base64", ".", "b64encode", "(", "byte_digest", ")", ".", "decode", "(", ")" ]
Computes the md5 digest of a byte buffer in base64 encoding.
[ "Computes", "the", "md5", "digest", "of", "a", "byte", "buffer", "in", "base64", "encoding", "." ]
fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6
https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/net/azurestore.py#L46-L52
train
mbr/simplekv
simplekv/net/azurestore.py
map_azure_exceptions
def map_azure_exceptions(key=None, exc_pass=()): """Map Azure-specific exceptions to the simplekv-API.""" from azure.common import AzureMissingResourceHttpError, AzureHttpError,\ AzureException try: yield except AzureMissingResourceHttpError as ex: if ex.__class__.__name__ not in...
python
def map_azure_exceptions(key=None, exc_pass=()): """Map Azure-specific exceptions to the simplekv-API.""" from azure.common import AzureMissingResourceHttpError, AzureHttpError,\ AzureException try: yield except AzureMissingResourceHttpError as ex: if ex.__class__.__name__ not in...
[ "def", "map_azure_exceptions", "(", "key", "=", "None", ",", "exc_pass", "=", "(", ")", ")", ":", "from", "azure", ".", "common", "import", "AzureMissingResourceHttpError", ",", "AzureHttpError", ",", "AzureException", "try", ":", "yield", "except", "AzureMissin...
Map Azure-specific exceptions to the simplekv-API.
[ "Map", "Azure", "-", "specific", "exceptions", "to", "the", "simplekv", "-", "API", "." ]
fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6
https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/net/azurestore.py#L56-L73
train
mbr/simplekv
simplekv/net/azurestore.py
IOInterface.read
def read(self, size=-1): """Returns 'size' amount of bytes or less if there is no more data. If no size is given all data is returned. size can be >= 0.""" if self.closed: raise ValueError("I/O operation on closed file") with map_azure_exceptions(key=self.key): if...
python
def read(self, size=-1): """Returns 'size' amount of bytes or less if there is no more data. If no size is given all data is returned. size can be >= 0.""" if self.closed: raise ValueError("I/O operation on closed file") with map_azure_exceptions(key=self.key): if...
[ "def", "read", "(", "self", ",", "size", "=", "-", "1", ")", ":", "if", "self", ".", "closed", ":", "raise", "ValueError", "(", "\"I/O operation on closed file\"", ")", "with", "map_azure_exceptions", "(", "key", "=", "self", ".", "key", ")", ":", "if", ...
Returns 'size' amount of bytes or less if there is no more data. If no size is given all data is returned. size can be >= 0.
[ "Returns", "size", "amount", "of", "bytes", "or", "less", "if", "there", "is", "no", "more", "data", ".", "If", "no", "size", "is", "given", "all", "data", "is", "returned", ".", "size", "can", "be", ">", "=", "0", "." ]
fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6
https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/net/azurestore.py#L231-L251
train
mbr/simplekv
simplekv/net/azurestore.py
IOInterface.seek
def seek(self, offset, whence=0): """Move to a new offset either relative or absolute. whence=0 is absolute, whence=1 is relative, whence=2 is relative to the end. Any relative or absolute seek operation which would result in a negative position is undefined and that case can be ignored...
python
def seek(self, offset, whence=0): """Move to a new offset either relative or absolute. whence=0 is absolute, whence=1 is relative, whence=2 is relative to the end. Any relative or absolute seek operation which would result in a negative position is undefined and that case can be ignored...
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "0", ")", ":", "if", "self", ".", "closed", ":", "raise", "ValueError", "(", "\"I/O operation on closed file\"", ")", "if", "whence", "==", "0", ":", "if", "offset", "<", "0", ":", "raise",...
Move to a new offset either relative or absolute. whence=0 is absolute, whence=1 is relative, whence=2 is relative to the end. Any relative or absolute seek operation which would result in a negative position is undefined and that case can be ignored in the implementation. Any ...
[ "Move", "to", "a", "new", "offset", "either", "relative", "or", "absolute", ".", "whence", "=", "0", "is", "absolute", "whence", "=", "1", "is", "relative", "whence", "=", "2", "is", "relative", "to", "the", "end", "." ]
fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6
https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/net/azurestore.py#L253-L278
train
mbr/simplekv
simplekv/git.py
_on_tree
def _on_tree(repo, tree, components, obj): """Mounts an object on a tree, using the given path components. :param tree: Tree object to mount on. :param components: A list of strings of subpaths (i.e. ['foo', 'bar'] is equivalent to '/foo/bar') :param obj: Object to mount. If None...
python
def _on_tree(repo, tree, components, obj): """Mounts an object on a tree, using the given path components. :param tree: Tree object to mount on. :param components: A list of strings of subpaths (i.e. ['foo', 'bar'] is equivalent to '/foo/bar') :param obj: Object to mount. If None...
[ "def", "_on_tree", "(", "repo", ",", "tree", ",", "components", ",", "obj", ")", ":", "if", "len", "(", "components", ")", "==", "1", ":", "if", "isinstance", "(", "obj", ",", "Blob", ")", ":", "mode", "=", "0o100644", "elif", "isinstance", "(", "o...
Mounts an object on a tree, using the given path components. :param tree: Tree object to mount on. :param components: A list of strings of subpaths (i.e. ['foo', 'bar'] is equivalent to '/foo/bar') :param obj: Object to mount. If None, removes the object found at path ...
[ "Mounts", "an", "object", "on", "a", "tree", "using", "the", "given", "path", "components", "." ]
fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6
https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/git.py#L12-L62
train
SUSE-Enceladus/ipa
ipa/ipa_ec2.py
EC2Cloud._connect
def _connect(self): """Connect to ec2 resource.""" resource = None try: resource = boto3.resource( 'ec2', aws_access_key_id=self.access_key_id, aws_secret_access_key=self.secret_access_key, region_name=self.region ...
python
def _connect(self): """Connect to ec2 resource.""" resource = None try: resource = boto3.resource( 'ec2', aws_access_key_id=self.access_key_id, aws_secret_access_key=self.secret_access_key, region_name=self.region ...
[ "def", "_connect", "(", "self", ")", ":", "resource", "=", "None", "try", ":", "resource", "=", "boto3", ".", "resource", "(", "'ec2'", ",", "aws_access_key_id", "=", "self", ".", "access_key_id", ",", "aws_secret_access_key", "=", "self", ".", "secret_acces...
Connect to ec2 resource.
[ "Connect", "to", "ec2", "resource", "." ]
0845eed0ea25a27dbb059ad1016105fa60002228
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_ec2.py#L168-L184
train
SUSE-Enceladus/ipa
ipa/ipa_ec2.py
EC2Cloud._get_user_data
def _get_user_data(self): """ Return formatted bash script string. The public ssh key is added by cloud init to the instance based on the ssh user and private key file. """ key = ipa_utils.generate_public_ssh_key( self.ssh_private_key_file ).decode() ...
python
def _get_user_data(self): """ Return formatted bash script string. The public ssh key is added by cloud init to the instance based on the ssh user and private key file. """ key = ipa_utils.generate_public_ssh_key( self.ssh_private_key_file ).decode() ...
[ "def", "_get_user_data", "(", "self", ")", ":", "key", "=", "ipa_utils", ".", "generate_public_ssh_key", "(", "self", ".", "ssh_private_key_file", ")", ".", "decode", "(", ")", "script", "=", "BASH_SSH_SCRIPT", ".", "format", "(", "user", "=", "self", ".", ...
Return formatted bash script string. The public ssh key is added by cloud init to the instance based on the ssh user and private key file.
[ "Return", "formatted", "bash", "script", "string", "." ]
0845eed0ea25a27dbb059ad1016105fa60002228
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_ec2.py#L221-L232
train
SUSE-Enceladus/ipa
ipa/ipa_ec2.py
EC2Cloud._set_instance_ip
def _set_instance_ip(self): """ Retrieve instance ip and cache it. Current preference is for public ipv4, ipv6 and private. """ instance = self._get_instance() # ipv6 try: ipv6 = instance.network_interfaces[0].ipv6_addresses[0] except (IndexE...
python
def _set_instance_ip(self): """ Retrieve instance ip and cache it. Current preference is for public ipv4, ipv6 and private. """ instance = self._get_instance() # ipv6 try: ipv6 = instance.network_interfaces[0].ipv6_addresses[0] except (IndexE...
[ "def", "_set_instance_ip", "(", "self", ")", ":", "instance", "=", "self", ".", "_get_instance", "(", ")", "try", ":", "ipv6", "=", "instance", ".", "network_interfaces", "[", "0", "]", ".", "ipv6_addresses", "[", "0", "]", "except", "(", "IndexError", "...
Retrieve instance ip and cache it. Current preference is for public ipv4, ipv6 and private.
[ "Retrieve", "instance", "ip", "and", "cache", "it", "." ]
0845eed0ea25a27dbb059ad1016105fa60002228
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_ec2.py#L293-L313
train
tgbugs/pyontutils
pyontutils/process_fixed.py
_process_worker
def _process_worker(call_queue, result_queue): """ This worker is wrapped to block KeyboardInterrupt """ signal.signal(signal.SIGINT, signal.SIG_IGN) #block ctrl-c return _process_worker_base(call_queue, result_queue)
python
def _process_worker(call_queue, result_queue): """ This worker is wrapped to block KeyboardInterrupt """ signal.signal(signal.SIGINT, signal.SIG_IGN) #block ctrl-c return _process_worker_base(call_queue, result_queue)
[ "def", "_process_worker", "(", "call_queue", ",", "result_queue", ")", ":", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "signal", ".", "SIG_IGN", ")", "return", "_process_worker_base", "(", "call_queue", ",", "result_queue", ")" ]
This worker is wrapped to block KeyboardInterrupt
[ "This", "worker", "is", "wrapped", "to", "block", "KeyboardInterrupt" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/process_fixed.py#L6-L9
train
SUSE-Enceladus/ipa
ipa/ipa_distro.py
Distro._set_init_system
def _set_init_system(self, client): """Determine the init system of distribution.""" if not self.init_system: try: out = ipa_utils.execute_ssh_command( client, 'ps -p 1 -o comm=' ) except Exception as e: ...
python
def _set_init_system(self, client): """Determine the init system of distribution.""" if not self.init_system: try: out = ipa_utils.execute_ssh_command( client, 'ps -p 1 -o comm=' ) except Exception as e: ...
[ "def", "_set_init_system", "(", "self", ",", "client", ")", ":", "if", "not", "self", ".", "init_system", ":", "try", ":", "out", "=", "ipa_utils", ".", "execute_ssh_command", "(", "client", ",", "'ps -p 1 -o comm='", ")", "except", "Exception", "as", "e", ...
Determine the init system of distribution.
[ "Determine", "the", "init", "system", "of", "distribution", "." ]
0845eed0ea25a27dbb059ad1016105fa60002228
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_distro.py#L36-L50
train
SUSE-Enceladus/ipa
ipa/ipa_distro.py
Distro.get_vm_info
def get_vm_info(self, client): """Return vm info.""" out = '' self._set_init_system(client) if self.init_system == 'systemd': try: out += 'systemd-analyze:\n\n' out += ipa_utils.execute_ssh_command( client, ...
python
def get_vm_info(self, client): """Return vm info.""" out = '' self._set_init_system(client) if self.init_system == 'systemd': try: out += 'systemd-analyze:\n\n' out += ipa_utils.execute_ssh_command( client, ...
[ "def", "get_vm_info", "(", "self", ",", "client", ")", ":", "out", "=", "''", "self", ".", "_set_init_system", "(", "client", ")", "if", "self", ".", "init_system", "==", "'systemd'", ":", "try", ":", "out", "+=", "'systemd-analyze:\\n\\n'", "out", "+=", ...
Return vm info.
[ "Return", "vm", "info", "." ]
0845eed0ea25a27dbb059ad1016105fa60002228
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_distro.py#L76-L103
train
SUSE-Enceladus/ipa
ipa/ipa_distro.py
Distro.install_package
def install_package(self, client, package): """Install package on instance.""" install_cmd = "{sudo} '{install} {package}'".format( sudo=self.get_sudo_exec_wrapper(), install=self.get_install_cmd(), package=package ) try: out = ipa_utils.e...
python
def install_package(self, client, package): """Install package on instance.""" install_cmd = "{sudo} '{install} {package}'".format( sudo=self.get_sudo_exec_wrapper(), install=self.get_install_cmd(), package=package ) try: out = ipa_utils.e...
[ "def", "install_package", "(", "self", ",", "client", ",", "package", ")", ":", "install_cmd", "=", "\"{sudo} '{install} {package}'\"", ".", "format", "(", "sudo", "=", "self", ".", "get_sudo_exec_wrapper", "(", ")", ",", "install", "=", "self", ".", "get_inst...
Install package on instance.
[ "Install", "package", "on", "instance", "." ]
0845eed0ea25a27dbb059ad1016105fa60002228
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_distro.py#L105-L127
train
SUSE-Enceladus/ipa
ipa/ipa_distro.py
Distro.reboot
def reboot(self, client): """Execute reboot command on instance.""" self._set_init_system(client) reboot_cmd = "{sudo} '{stop_ssh};{reboot}'".format( sudo=self.get_sudo_exec_wrapper(), stop_ssh=self.get_stop_ssh_service_cmd(), reboot=self.get_reboot_cmd() ...
python
def reboot(self, client): """Execute reboot command on instance.""" self._set_init_system(client) reboot_cmd = "{sudo} '{stop_ssh};{reboot}'".format( sudo=self.get_sudo_exec_wrapper(), stop_ssh=self.get_stop_ssh_service_cmd(), reboot=self.get_reboot_cmd() ...
[ "def", "reboot", "(", "self", ",", "client", ")", ":", "self", ".", "_set_init_system", "(", "client", ")", "reboot_cmd", "=", "\"{sudo} '{stop_ssh};{reboot}'\"", ".", "format", "(", "sudo", "=", "self", ".", "get_sudo_exec_wrapper", "(", ")", ",", "stop_ssh",...
Execute reboot command on instance.
[ "Execute", "reboot", "command", "on", "instance", "." ]
0845eed0ea25a27dbb059ad1016105fa60002228
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_distro.py#L129-L148
train
SUSE-Enceladus/ipa
ipa/ipa_distro.py
Distro.update
def update(self, client): """Execute update command on instance.""" update_cmd = "{sudo} '{refresh};{update}'".format( sudo=self.get_sudo_exec_wrapper(), refresh=self.get_refresh_repo_cmd(), update=self.get_update_cmd() ) out = '' try: ...
python
def update(self, client): """Execute update command on instance.""" update_cmd = "{sudo} '{refresh};{update}'".format( sudo=self.get_sudo_exec_wrapper(), refresh=self.get_refresh_repo_cmd(), update=self.get_update_cmd() ) out = '' try: ...
[ "def", "update", "(", "self", ",", "client", ")", ":", "update_cmd", "=", "\"{sudo} '{refresh};{update}'\"", ".", "format", "(", "sudo", "=", "self", ".", "get_sudo_exec_wrapper", "(", ")", ",", "refresh", "=", "self", ".", "get_refresh_repo_cmd", "(", ")", ...
Execute update command on instance.
[ "Execute", "update", "command", "on", "instance", "." ]
0845eed0ea25a27dbb059ad1016105fa60002228
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_distro.py#L150-L168
train
tgbugs/pyontutils
pyontutils/scigraph_client.py
Graph.ordered
def ordered(start, edges, predicate=None, inverse=False): """ Depth first edges from a SciGraph response. """ s, o = 'sub', 'obj' if inverse: s, o = o, s for edge in edges: if predicate is not None and edge['pred'] != predicate: print('scoop!') ...
python
def ordered(start, edges, predicate=None, inverse=False): """ Depth first edges from a SciGraph response. """ s, o = 'sub', 'obj' if inverse: s, o = o, s for edge in edges: if predicate is not None and edge['pred'] != predicate: print('scoop!') ...
[ "def", "ordered", "(", "start", ",", "edges", ",", "predicate", "=", "None", ",", "inverse", "=", "False", ")", ":", "s", ",", "o", "=", "'sub'", ",", "'obj'", "if", "inverse", ":", "s", ",", "o", "=", "o", ",", "s", "for", "edge", "in", "edges...
Depth first edges from a SciGraph response.
[ "Depth", "first", "edges", "from", "a", "SciGraph", "response", "." ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/scigraph_client.py#L741-L753
train
tgbugs/pyontutils
pyontutils/hierarchies.py
tcsort
def tcsort(item): # FIXME SUCH WOW SO INEFFICIENT O_O """ get len of transitive closure assume type items is tree... """ return len(item[1]) + sum(tcsort(kv) for kv in item[1].items())
python
def tcsort(item): # FIXME SUCH WOW SO INEFFICIENT O_O """ get len of transitive closure assume type items is tree... """ return len(item[1]) + sum(tcsort(kv) for kv in item[1].items())
[ "def", "tcsort", "(", "item", ")", ":", "return", "len", "(", "item", "[", "1", "]", ")", "+", "sum", "(", "tcsort", "(", "kv", ")", "for", "kv", "in", "item", "[", "1", "]", ".", "items", "(", ")", ")" ]
get len of transitive closure assume type items is tree...
[ "get", "len", "of", "transitive", "closure", "assume", "type", "items", "is", "tree", "..." ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/hierarchies.py#L43-L45
train
tgbugs/pyontutils
pyontutils/hierarchies.py
get_node
def get_node(start, tree, pnames): """ for each parent find a single branch to root """ def get_first_branch(node): if node not in pnames: # one way to hit a root return [] if pnames[node]: # mmmm names fp = pnames[node][0] if cycle_check(node, fp, pnames): ...
python
def get_node(start, tree, pnames): """ for each parent find a single branch to root """ def get_first_branch(node): if node not in pnames: # one way to hit a root return [] if pnames[node]: # mmmm names fp = pnames[node][0] if cycle_check(node, fp, pnames): ...
[ "def", "get_node", "(", "start", ",", "tree", ",", "pnames", ")", ":", "def", "get_first_branch", "(", "node", ")", ":", "if", "node", "not", "in", "pnames", ":", "return", "[", "]", "if", "pnames", "[", "node", "]", ":", "fp", "=", "pnames", "[", ...
for each parent find a single branch to root
[ "for", "each", "parent", "find", "a", "single", "branch", "to", "root" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/hierarchies.py#L58-L80
train
tgbugs/pyontutils
pyontutils/hierarchies.py
dematerialize
def dematerialize(parent_name, parent_node): # FIXME we need to demat more than just leaves! #FIXME still an issue: Fornix, Striatum, Diagonal Band """ Remove nodes higher in the tree that occur further down the SAME branch. If they occur down OTHER branchs leave them alone. NOTE: modifies in ...
python
def dematerialize(parent_name, parent_node): # FIXME we need to demat more than just leaves! #FIXME still an issue: Fornix, Striatum, Diagonal Band """ Remove nodes higher in the tree that occur further down the SAME branch. If they occur down OTHER branchs leave them alone. NOTE: modifies in ...
[ "def", "dematerialize", "(", "parent_name", ",", "parent_node", ")", ":", "lleaves", "=", "{", "}", "children", "=", "parent_node", "[", "parent_name", "]", "if", "not", "children", ":", "lleaves", "[", "parent_name", "]", "=", "None", "return", "lleaves", ...
Remove nodes higher in the tree that occur further down the SAME branch. If they occur down OTHER branchs leave them alone. NOTE: modifies in place!
[ "Remove", "nodes", "higher", "in", "the", "tree", "that", "occur", "further", "down", "the", "SAME", "branch", ".", "If", "they", "occur", "down", "OTHER", "branchs", "leave", "them", "alone", "." ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/hierarchies.py#L115-L160
train
tgbugs/pyontutils
ilxutils/ilxutils/interlex_sql.py
IlxSql.get_terms
def get_terms(self): ''' GROUP BY is a shortcut to only getting the first in every list of group ''' if not self.terms.empty: return self.terms if self.from_backup: self.terms = open_pickle(TERMS_BACKUP_PATH) return self.terms engine = create_engine(se...
python
def get_terms(self): ''' GROUP BY is a shortcut to only getting the first in every list of group ''' if not self.terms.empty: return self.terms if self.from_backup: self.terms = open_pickle(TERMS_BACKUP_PATH) return self.terms engine = create_engine(se...
[ "def", "get_terms", "(", "self", ")", ":", "if", "not", "self", ".", "terms", ".", "empty", ":", "return", "self", ".", "terms", "if", "self", ".", "from_backup", ":", "self", ".", "terms", "=", "open_pickle", "(", "TERMS_BACKUP_PATH", ")", "return", "...
GROUP BY is a shortcut to only getting the first in every list of group
[ "GROUP", "BY", "is", "a", "shortcut", "to", "only", "getting", "the", "first", "in", "every", "list", "of", "group" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_sql.py#L67-L82
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_scicrunch_client.py
superclasses_bug_fix
def superclasses_bug_fix(data): ''' PHP returns "id" in superclass but only accepts superclass_tid ''' for i, value in enumerate(data['superclasses']): data['superclasses'][i]['superclass_tid'] = data['superclasses'][i].pop('id') return data
python
def superclasses_bug_fix(data): ''' PHP returns "id" in superclass but only accepts superclass_tid ''' for i, value in enumerate(data['superclasses']): data['superclasses'][i]['superclass_tid'] = data['superclasses'][i].pop('id') return data
[ "def", "superclasses_bug_fix", "(", "data", ")", ":", "for", "i", ",", "value", "in", "enumerate", "(", "data", "[", "'superclasses'", "]", ")", ":", "data", "[", "'superclasses'", "]", "[", "i", "]", "[", "'superclass_tid'", "]", "=", "data", "[", "'s...
PHP returns "id" in superclass but only accepts superclass_tid
[ "PHP", "returns", "id", "in", "superclass", "but", "only", "accepts", "superclass_tid" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L47-L51
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_scicrunch_client.py
Client.log_info
def log_info(self, data): ''' Logs successful responses ''' info = 'label={label}, id={id}, ilx={ilx}, superclass_tid={super_id}' info_filled = info.format(label = data['label'], id = data['id'], ilx = data['ilx'],...
python
def log_info(self, data): ''' Logs successful responses ''' info = 'label={label}, id={id}, ilx={ilx}, superclass_tid={super_id}' info_filled = info.format(label = data['label'], id = data['id'], ilx = data['ilx'],...
[ "def", "log_info", "(", "self", ",", "data", ")", ":", "info", "=", "'label={label}, id={id}, ilx={ilx}, superclass_tid={super_id}'", "info_filled", "=", "info", ".", "format", "(", "label", "=", "data", "[", "'label'", "]", ",", "id", "=", "data", "[", "'id'"...
Logs successful responses
[ "Logs", "successful", "responses" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L80-L88
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_scicrunch_client.py
Client.process_request
def process_request(self, req): ''' Checks to see if data returned from database is useable ''' # Check status code of request req.raise_for_status() # if codes not in 200s; error raise # Proper status code, but check if server returned a warning try: output = req.jso...
python
def process_request(self, req): ''' Checks to see if data returned from database is useable ''' # Check status code of request req.raise_for_status() # if codes not in 200s; error raise # Proper status code, but check if server returned a warning try: output = req.jso...
[ "def", "process_request", "(", "self", ",", "req", ")", ":", "req", ".", "raise_for_status", "(", ")", "try", ":", "output", "=", "req", ".", "json", "(", ")", "except", ":", "exit", "(", "req", ".", "text", ")", "try", ":", "error", "=", "output",...
Checks to see if data returned from database is useable
[ "Checks", "to", "see", "if", "data", "returned", "from", "database", "is", "useable" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L111-L128
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_scicrunch_client.py
Client.is_equal
def is_equal(self, string1, string2): ''' Simple string comparator ''' return string1.lower().strip() == string2.lower().strip()
python
def is_equal(self, string1, string2): ''' Simple string comparator ''' return string1.lower().strip() == string2.lower().strip()
[ "def", "is_equal", "(", "self", ",", "string1", ",", "string2", ")", ":", "return", "string1", ".", "lower", "(", ")", ".", "strip", "(", ")", "==", "string2", ".", "lower", "(", ")", ".", "strip", "(", ")" ]
Simple string comparator
[ "Simple", "string", "comparator" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L130-L132
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_scicrunch_client.py
Client.are_ilx
def are_ilx(self, ilx_ids): ''' Checks list of objects to see if they are usable ILX IDs ''' total_data = [] for ilx_id in ilx_ids: ilx_id = ilx_id.replace('http', '').replace('.', '').replace('/', '') data, success = self.get_data_from_ilx(ilx_id) if success:...
python
def are_ilx(self, ilx_ids): ''' Checks list of objects to see if they are usable ILX IDs ''' total_data = [] for ilx_id in ilx_ids: ilx_id = ilx_id.replace('http', '').replace('.', '').replace('/', '') data, success = self.get_data_from_ilx(ilx_id) if success:...
[ "def", "are_ilx", "(", "self", ",", "ilx_ids", ")", ":", "total_data", "=", "[", "]", "for", "ilx_id", "in", "ilx_ids", ":", "ilx_id", "=", "ilx_id", ".", "replace", "(", "'http'", ",", "''", ")", ".", "replace", "(", "'.'", ",", "''", ")", ".", ...
Checks list of objects to see if they are usable ILX IDs
[ "Checks", "list", "of", "objects", "to", "see", "if", "they", "are", "usable", "ILX", "IDs" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L168-L178
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_scicrunch_client.py
Client.add_triple
def add_triple(self, subj, pred, obj): ''' Adds an entity property to an existing entity ''' subj_data, pred_data, obj_data = self.are_ilx([subj, pred, obj]) # RELATIONSHIP PROPERTY if subj_data.get('id') and pred_data.get('id') and obj_data.get('id'): if pred_data['type'] !=...
python
def add_triple(self, subj, pred, obj): ''' Adds an entity property to an existing entity ''' subj_data, pred_data, obj_data = self.are_ilx([subj, pred, obj]) # RELATIONSHIP PROPERTY if subj_data.get('id') and pred_data.get('id') and obj_data.get('id'): if pred_data['type'] !=...
[ "def", "add_triple", "(", "self", ",", "subj", ",", "pred", ",", "obj", ")", ":", "subj_data", ",", "pred_data", ",", "obj_data", "=", "self", ".", "are_ilx", "(", "[", "subj", ",", "pred", ",", "obj", "]", ")", "if", "subj_data", ".", "get", "(", ...
Adds an entity property to an existing entity
[ "Adds", "an", "entity", "property", "to", "an", "existing", "entity" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L180-L214
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_scicrunch_client.py
Client.add_relationship
def add_relationship(self, term1, relationship, term2): ''' Creates a relationship between 3 entities in database ''' url = self.base_path + 'term/add-relationship' data = {'term1_id': term1['id'], 'relationship_tid': relationship['id'], 'term2_id': term2['id'], ...
python
def add_relationship(self, term1, relationship, term2): ''' Creates a relationship between 3 entities in database ''' url = self.base_path + 'term/add-relationship' data = {'term1_id': term1['id'], 'relationship_tid': relationship['id'], 'term2_id': term2['id'], ...
[ "def", "add_relationship", "(", "self", ",", "term1", ",", "relationship", ",", "term2", ")", ":", "url", "=", "self", ".", "base_path", "+", "'term/add-relationship'", "data", "=", "{", "'term1_id'", ":", "term1", "[", "'id'", "]", ",", "'relationship_tid'"...
Creates a relationship between 3 entities in database
[ "Creates", "a", "relationship", "between", "3", "entities", "in", "database" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L216-L225
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_scicrunch_client.py
Client.add_annotation
def add_annotation(self, entity, annotation, value): ''' Adds an annotation proprty to existing entity ''' url = self.base_path + 'term/add-annotation' data = {'tid': entity['id'], 'annotation_tid': annotation['id'], 'value': value, 'term_version':...
python
def add_annotation(self, entity, annotation, value): ''' Adds an annotation proprty to existing entity ''' url = self.base_path + 'term/add-annotation' data = {'tid': entity['id'], 'annotation_tid': annotation['id'], 'value': value, 'term_version':...
[ "def", "add_annotation", "(", "self", ",", "entity", ",", "annotation", ",", "value", ")", ":", "url", "=", "self", ".", "base_path", "+", "'term/add-annotation'", "data", "=", "{", "'tid'", ":", "entity", "[", "'id'", "]", ",", "'annotation_tid'", ":", ...
Adds an annotation proprty to existing entity
[ "Adds", "an", "annotation", "proprty", "to", "existing", "entity" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L227-L235
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_scicrunch_client.py
Client.custom_update
def custom_update(self, data, pred, obj): ''' Updates existing entity proprty based on the predicate input ''' if isinstance(data[pred], str): # for all simple properties of str value data[pred] = str(obj) else: # synonyms, superclasses, and existing_ids have special requirements ...
python
def custom_update(self, data, pred, obj): ''' Updates existing entity proprty based on the predicate input ''' if isinstance(data[pred], str): # for all simple properties of str value data[pred] = str(obj) else: # synonyms, superclasses, and existing_ids have special requirements ...
[ "def", "custom_update", "(", "self", ",", "data", ",", "pred", ",", "obj", ")", ":", "if", "isinstance", "(", "data", "[", "pred", "]", ",", "str", ")", ":", "data", "[", "pred", "]", "=", "str", "(", "obj", ")", "else", ":", "if", "pred", "=="...
Updates existing entity proprty based on the predicate input
[ "Updates", "existing", "entity", "proprty", "based", "on", "the", "predicate", "input" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L237-L274
train
tgbugs/pyontutils
ttlser/ttlser/serializers.py
CustomTurtleSerializer.sortProperties
def sortProperties(self, properties): # modified to sort objects using their global rank """Take a hash from predicate uris to lists of values. Sort the lists of values. Return a sorted list of properties.""" # Sort object lists for prop, objects in properties.items(): o...
python
def sortProperties(self, properties): # modified to sort objects using their global rank """Take a hash from predicate uris to lists of values. Sort the lists of values. Return a sorted list of properties.""" # Sort object lists for prop, objects in properties.items(): o...
[ "def", "sortProperties", "(", "self", ",", "properties", ")", ":", "for", "prop", ",", "objects", "in", "properties", ".", "items", "(", ")", ":", "objects", ".", "sort", "(", "key", "=", "self", ".", "_globalSortKey", ")", "return", "sorted", "(", "pr...
Take a hash from predicate uris to lists of values. Sort the lists of values. Return a sorted list of properties.
[ "Take", "a", "hash", "from", "predicate", "uris", "to", "lists", "of", "values", ".", "Sort", "the", "lists", "of", "values", ".", "Return", "a", "sorted", "list", "of", "properties", "." ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ttlser/ttlser/serializers.py#L561-L569
train
tgbugs/pyontutils
ttlser/ttlser/serializers.py
CustomTurtleSerializer._buildPredicateHash
def _buildPredicateHash(self, subject): # XXX unmodified """ Build a hash key by predicate to a list of objects for the given subject """ properties = {} for s, p, o in self.store.triples((subject, None, None)): oList = properties.get(p, []) oList...
python
def _buildPredicateHash(self, subject): # XXX unmodified """ Build a hash key by predicate to a list of objects for the given subject """ properties = {} for s, p, o in self.store.triples((subject, None, None)): oList = properties.get(p, []) oList...
[ "def", "_buildPredicateHash", "(", "self", ",", "subject", ")", ":", "properties", "=", "{", "}", "for", "s", ",", "p", ",", "o", "in", "self", ".", "store", ".", "triples", "(", "(", "subject", ",", "None", ",", "None", ")", ")", ":", "oList", "...
Build a hash key by predicate to a list of objects for the given subject
[ "Build", "a", "hash", "key", "by", "predicate", "to", "a", "list", "of", "objects", "for", "the", "given", "subject" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ttlser/ttlser/serializers.py#L571-L582
train
tgbugs/pyontutils
ttlser/ttlser/serializers.py
CustomTurtleSerializer.isValidList
def isValidList(self, l): # modified to flatten lists specified using [ a rdf:List; ] syntax """ Checks if l is a valid RDF list, i.e. no nodes have other properties. """ try: if self.store.value(l, RDF.first) is None: return False except: ...
python
def isValidList(self, l): # modified to flatten lists specified using [ a rdf:List; ] syntax """ Checks if l is a valid RDF list, i.e. no nodes have other properties. """ try: if self.store.value(l, RDF.first) is None: return False except: ...
[ "def", "isValidList", "(", "self", ",", "l", ")", ":", "try", ":", "if", "self", ".", "store", ".", "value", "(", "l", ",", "RDF", ".", "first", ")", "is", "None", ":", "return", "False", "except", ":", "return", "False", "while", "l", ":", "if",...
Checks if l is a valid RDF list, i.e. no nodes have other properties.
[ "Checks", "if", "l", "is", "a", "valid", "RDF", "list", "i", ".", "e", ".", "no", "nodes", "have", "other", "properties", "." ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ttlser/ttlser/serializers.py#L620-L637
train
tgbugs/pyontutils
ttlser/ttlser/serializers.py
CustomTurtleSerializer._write
def _write(self, value): """ rename to write and import inspect to debut the callstack """ if ' ' in value: s = inspect.stack() fn = s[1].function super().write('%%DEBUG {} %%'.format(fn)) super().write(value)
python
def _write(self, value): """ rename to write and import inspect to debut the callstack """ if ' ' in value: s = inspect.stack() fn = s[1].function super().write('%%DEBUG {} %%'.format(fn)) super().write(value)
[ "def", "_write", "(", "self", ",", "value", ")", ":", "if", "' '", "in", "value", ":", "s", "=", "inspect", ".", "stack", "(", ")", "fn", "=", "s", "[", "1", "]", ".", "function", "super", "(", ")", ".", "write", "(", "'%%DEBUG {} %%'", ".", "f...
rename to write and import inspect to debut the callstack
[ "rename", "to", "write", "and", "import", "inspect", "to", "debut", "the", "callstack" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ttlser/ttlser/serializers.py#L737-L743
train
tgbugs/pyontutils
ttlser/ttlser/serializers.py
HtmlTurtleSerializer.serialize
def serialize(self, *args, **kwargs): """ Modified to allow additional labels to be passed in. """ if 'labels' in kwargs: # populate labels from outside the local graph self._labels.update(kwargs['labels']) super(HtmlTurtleSerializer, self).serialize(*args, **kwargs)
python
def serialize(self, *args, **kwargs): """ Modified to allow additional labels to be passed in. """ if 'labels' in kwargs: # populate labels from outside the local graph self._labels.update(kwargs['labels']) super(HtmlTurtleSerializer, self).serialize(*args, **kwargs)
[ "def", "serialize", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "'labels'", "in", "kwargs", ":", "self", ".", "_labels", ".", "update", "(", "kwargs", "[", "'labels'", "]", ")", "super", "(", "HtmlTurtleSerializer", ",", "self",...
Modified to allow additional labels to be passed in.
[ "Modified", "to", "allow", "additional", "labels", "to", "be", "passed", "in", "." ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ttlser/ttlser/serializers.py#L818-L823
train
tgbugs/pyontutils
neurondm/neurondm/core.py
addLNT
def addLNT(LocalName, phenoId, predicate, g=None): # XXX deprecated """ Add a local name for a phenotype from a pair of identifiers """ if g is None: s = inspect.stack(0) # horribly inefficient checkCalledInside('LocalNameManager', s) g = s[1][0].f_locals # get globals of calling scop...
python
def addLNT(LocalName, phenoId, predicate, g=None): # XXX deprecated """ Add a local name for a phenotype from a pair of identifiers """ if g is None: s = inspect.stack(0) # horribly inefficient checkCalledInside('LocalNameManager', s) g = s[1][0].f_locals # get globals of calling scop...
[ "def", "addLNT", "(", "LocalName", ",", "phenoId", ",", "predicate", ",", "g", "=", "None", ")", ":", "if", "g", "is", "None", ":", "s", "=", "inspect", ".", "stack", "(", "0", ")", "checkCalledInside", "(", "'LocalNameManager'", ",", "s", ")", "g", ...
Add a local name for a phenotype from a pair of identifiers
[ "Add", "a", "local", "name", "for", "a", "phenotype", "from", "a", "pair", "of", "identifiers" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/neurondm/neurondm/core.py#L2468-L2474
train
tgbugs/pyontutils
neurondm/neurondm/core.py
Config.load_existing
def load_existing(self): """ advanced usage allows loading multiple sets of neurons and using a config object to keep track of the different graphs """ from pyontutils.closed_namespaces import rdfs # bag existing try: next(iter(self.neurons())) raise ...
python
def load_existing(self): """ advanced usage allows loading multiple sets of neurons and using a config object to keep track of the different graphs """ from pyontutils.closed_namespaces import rdfs # bag existing try: next(iter(self.neurons())) raise ...
[ "def", "load_existing", "(", "self", ")", ":", "from", "pyontutils", ".", "closed_namespaces", "import", "rdfs", "try", ":", "next", "(", "iter", "(", "self", ".", "neurons", "(", ")", ")", ")", "raise", "self", ".", "ExistingNeuronsError", "(", "'Existing...
advanced usage allows loading multiple sets of neurons and using a config object to keep track of the different graphs
[ "advanced", "usage", "allows", "loading", "multiple", "sets", "of", "neurons", "and", "using", "a", "config", "object", "to", "keep", "track", "of", "the", "different", "graphs" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/neurondm/neurondm/core.py#L583-L636
train
tgbugs/pyontutils
neurondm/neurondm/core.py
graphBase.label_maker
def label_maker(self): """ needed to defer loading of local conventions to avoid circular dependency issue """ if (not hasattr(graphBase, '_label_maker') or graphBase._label_maker.local_conventions != graphBase.local_conventions): graphBase._label_maker = LabelMaker(graphBase.loc...
python
def label_maker(self): """ needed to defer loading of local conventions to avoid circular dependency issue """ if (not hasattr(graphBase, '_label_maker') or graphBase._label_maker.local_conventions != graphBase.local_conventions): graphBase._label_maker = LabelMaker(graphBase.loc...
[ "def", "label_maker", "(", "self", ")", ":", "if", "(", "not", "hasattr", "(", "graphBase", ",", "'_label_maker'", ")", "or", "graphBase", ".", "_label_maker", ".", "local_conventions", "!=", "graphBase", ".", "local_conventions", ")", ":", "graphBase", ".", ...
needed to defer loading of local conventions to avoid circular dependency issue
[ "needed", "to", "defer", "loading", "of", "local", "conventions", "to", "avoid", "circular", "dependency", "issue" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/neurondm/neurondm/core.py#L1123-L1129
train
tgbugs/pyontutils
neurondm/neurondm/core.py
Neuron._graphify
def _graphify(self, *args, graph=None): # defined """ Lift phenotypeEdges to Restrictions """ if graph is None: graph = self.out_graph ################## LABELS ARE DEFINED HERE ################## gl = self.genLabel ll = self.localLabel ol = self.origLabel ...
python
def _graphify(self, *args, graph=None): # defined """ Lift phenotypeEdges to Restrictions """ if graph is None: graph = self.out_graph ################## LABELS ARE DEFINED HERE ################## gl = self.genLabel ll = self.localLabel ol = self.origLabel ...
[ "def", "_graphify", "(", "self", ",", "*", "args", ",", "graph", "=", "None", ")", ":", "if", "graph", "is", "None", ":", "graph", "=", "self", ".", "out_graph", "gl", "=", "self", ".", "genLabel", "ll", "=", "self", ".", "localLabel", "ol", "=", ...
Lift phenotypeEdges to Restrictions
[ "Lift", "phenotypeEdges", "to", "Restrictions" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/neurondm/neurondm/core.py#L2131-L2163
train
tgbugs/pyontutils
pyontutils/core.py
qname
def qname(uri, warning=False): """ compute qname from defaults """ if warning: print(tc.red('WARNING:'), tc.yellow(f'qname({uri}) is deprecated! please use OntId({uri}).curie')) return __helper_graph.qname(uri)
python
def qname(uri, warning=False): """ compute qname from defaults """ if warning: print(tc.red('WARNING:'), tc.yellow(f'qname({uri}) is deprecated! please use OntId({uri}).curie')) return __helper_graph.qname(uri)
[ "def", "qname", "(", "uri", ",", "warning", "=", "False", ")", ":", "if", "warning", ":", "print", "(", "tc", ".", "red", "(", "'WARNING:'", ")", ",", "tc", ".", "yellow", "(", "f'qname({uri}) is deprecated! please use OntId({uri}).curie'", ")", ")", "return...
compute qname from defaults
[ "compute", "qname", "from", "defaults" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/core.py#L447-L451
train
tgbugs/pyontutils
pyontutils/core.py
cull_prefixes
def cull_prefixes(graph, prefixes={k:v for k, v in uPREFIXES.items() if k != 'NIFTTL'}, cleanup=lambda ps, graph: None, keep=False): """ Remove unused curie prefixes and normalize to a standard set. """ prefs = [''] if keep: prefixes.update({p:str(n) for p, n in graph.namespaces()}...
python
def cull_prefixes(graph, prefixes={k:v for k, v in uPREFIXES.items() if k != 'NIFTTL'}, cleanup=lambda ps, graph: None, keep=False): """ Remove unused curie prefixes and normalize to a standard set. """ prefs = [''] if keep: prefixes.update({p:str(n) for p, n in graph.namespaces()}...
[ "def", "cull_prefixes", "(", "graph", ",", "prefixes", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "uPREFIXES", ".", "items", "(", ")", "if", "k", "!=", "'NIFTTL'", "}", ",", "cleanup", "=", "lambda", "ps", ",", "graph", ":", "None", ","...
Remove unused curie prefixes and normalize to a standard set.
[ "Remove", "unused", "curie", "prefixes", "and", "normalize", "to", "a", "standard", "set", "." ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/core.py#L455-L486
train
tgbugs/pyontutils
pyontutils/core.py
displayTriples
def displayTriples(triples, qname=qname): """ triples can also be an rdflib Graph instance """ [print(*(e[:5] if isinstance(e, rdflib.BNode) else qname(e) for e in t), '.') for t in sorted(triples)]
python
def displayTriples(triples, qname=qname): """ triples can also be an rdflib Graph instance """ [print(*(e[:5] if isinstance(e, rdflib.BNode) else qname(e) for e in t), '.') for t in sorted(triples)]
[ "def", "displayTriples", "(", "triples", ",", "qname", "=", "qname", ")", ":", "[", "print", "(", "*", "(", "e", "[", ":", "5", "]", "if", "isinstance", "(", "e", ",", "rdflib", ".", "BNode", ")", "else", "qname", "(", "e", ")", "for", "e", "in...
triples can also be an rdflib Graph instance
[ "triples", "can", "also", "be", "an", "rdflib", "Graph", "instance" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/core.py#L1171-L1177
train
tgbugs/pyontutils
pyontutils/core.py
makeGraph.write
def write(self, cull=False): """ Serialize self.g and write to self.filename, set cull to true to remove unwanted prefixes """ if cull: cull_prefixes(self).write() else: ser = self.g.serialize(format='nifttl') with open(self.filename, 'wb') as f: ...
python
def write(self, cull=False): """ Serialize self.g and write to self.filename, set cull to true to remove unwanted prefixes """ if cull: cull_prefixes(self).write() else: ser = self.g.serialize(format='nifttl') with open(self.filename, 'wb') as f: ...
[ "def", "write", "(", "self", ",", "cull", "=", "False", ")", ":", "if", "cull", ":", "cull_prefixes", "(", "self", ")", ".", "write", "(", ")", "else", ":", "ser", "=", "self", ".", "g", ".", "serialize", "(", "format", "=", "'nifttl'", ")", "wit...
Serialize self.g and write to self.filename, set cull to true to remove unwanted prefixes
[ "Serialize", "self", ".", "g", "and", "write", "to", "self", ".", "filename", "set", "cull", "to", "true", "to", "remove", "unwanted", "prefixes" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/core.py#L177-L184
train
tgbugs/pyontutils
pyontutils/core.py
makeGraph.add_hierarchy
def add_hierarchy(self, parent, edge, child): # XXX DEPRECATED """ Helper function to simplify the addition of part_of style objectProperties to graphs. FIXME make a method of makeGraph? """ if type(parent) != rdflib.URIRef: parent = self.check_thing(parent) if ...
python
def add_hierarchy(self, parent, edge, child): # XXX DEPRECATED """ Helper function to simplify the addition of part_of style objectProperties to graphs. FIXME make a method of makeGraph? """ if type(parent) != rdflib.URIRef: parent = self.check_thing(parent) if ...
[ "def", "add_hierarchy", "(", "self", ",", "parent", ",", "edge", ",", "child", ")", ":", "if", "type", "(", "parent", ")", "!=", "rdflib", ".", "URIRef", ":", "parent", "=", "self", ".", "check_thing", "(", "parent", ")", "if", "type", "(", "edge", ...
Helper function to simplify the addition of part_of style objectProperties to graphs. FIXME make a method of makeGraph?
[ "Helper", "function", "to", "simplify", "the", "addition", "of", "part_of", "style", "objectProperties", "to", "graphs", ".", "FIXME", "make", "a", "method", "of", "makeGraph?" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/core.py#L282-L298
train
tgbugs/pyontutils
pyontutils/core.py
makeGraph.add_restriction
def add_restriction(self, subject, predicate, object_): """ Lift normal triples into restrictions using someValuesFrom. """ if type(object_) != rdflib.URIRef: object_ = self.check_thing(object_) if type(predicate) != rdflib.URIRef: predicate = self.check_thing(predicate)...
python
def add_restriction(self, subject, predicate, object_): """ Lift normal triples into restrictions using someValuesFrom. """ if type(object_) != rdflib.URIRef: object_ = self.check_thing(object_) if type(predicate) != rdflib.URIRef: predicate = self.check_thing(predicate)...
[ "def", "add_restriction", "(", "self", ",", "subject", ",", "predicate", ",", "object_", ")", ":", "if", "type", "(", "object_", ")", "!=", "rdflib", ".", "URIRef", ":", "object_", "=", "self", ".", "check_thing", "(", "object_", ")", "if", "type", "("...
Lift normal triples into restrictions using someValuesFrom.
[ "Lift", "normal", "triples", "into", "restrictions", "using", "someValuesFrom", "." ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/core.py#L300-L314
train
tgbugs/pyontutils
pyontutils/core.py
makeGraph.qname
def qname(self, uri, generate=False): """ Given a uri return the qname if it exists, otherwise return the uri. """ try: prefix, namespace, name = self.g.namespace_manager.compute_qname(uri, generate=generate) qname = ':'.join((prefix, name)) return qname excep...
python
def qname(self, uri, generate=False): """ Given a uri return the qname if it exists, otherwise return the uri. """ try: prefix, namespace, name = self.g.namespace_manager.compute_qname(uri, generate=generate) qname = ':'.join((prefix, name)) return qname excep...
[ "def", "qname", "(", "self", ",", "uri", ",", "generate", "=", "False", ")", ":", "try", ":", "prefix", ",", "namespace", ",", "name", "=", "self", ".", "g", ".", "namespace_manager", ".", "compute_qname", "(", "uri", ",", "generate", "=", "generate", ...
Given a uri return the qname if it exists, otherwise return the uri.
[ "Given", "a", "uri", "return", "the", "qname", "if", "it", "exists", "otherwise", "return", "the", "uri", "." ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/core.py#L353-L360
train
SUSE-Enceladus/ipa
ipa/scripts/cli_utils.py
archive_history_item
def archive_history_item(item, destination, no_color): """ Archive the log and results file for the given history item. Copy the files and update the results file in destination directory. """ log_src, description = split_history_item(item.strip()) # Get relative path for log: # {provider}...
python
def archive_history_item(item, destination, no_color): """ Archive the log and results file for the given history item. Copy the files and update the results file in destination directory. """ log_src, description = split_history_item(item.strip()) # Get relative path for log: # {provider}...
[ "def", "archive_history_item", "(", "item", ",", "destination", ",", "no_color", ")", ":", "log_src", ",", "description", "=", "split_history_item", "(", "item", ".", "strip", "(", ")", ")", "log_dest", "=", "os", ".", "path", ".", "sep", ".", "join", "(...
Archive the log and results file for the given history item. Copy the files and update the results file in destination directory.
[ "Archive", "the", "log", "and", "results", "file", "for", "the", "given", "history", "item", "." ]
0845eed0ea25a27dbb059ad1016105fa60002228
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/scripts/cli_utils.py#L34-L73
train
SUSE-Enceladus/ipa
ipa/scripts/cli_utils.py
echo_verbose_results
def echo_verbose_results(data, no_color): """Print list of tests and result of each test.""" click.echo() click.echo( '\n'.join( '{}: {}'.format(key, val) for key, val in data['info'].items() ) ) click.echo() for test in data['tests']: if test['outcome'] == 'p...
python
def echo_verbose_results(data, no_color): """Print list of tests and result of each test.""" click.echo() click.echo( '\n'.join( '{}: {}'.format(key, val) for key, val in data['info'].items() ) ) click.echo() for test in data['tests']: if test['outcome'] == 'p...
[ "def", "echo_verbose_results", "(", "data", ",", "no_color", ")", ":", "click", ".", "echo", "(", ")", "click", ".", "echo", "(", "'\\n'", ".", "join", "(", "'{}: {}'", ".", "format", "(", "key", ",", "val", ")", "for", "key", ",", "val", "in", "da...
Print list of tests and result of each test.
[ "Print", "list", "of", "tests", "and", "result", "of", "each", "test", "." ]
0845eed0ea25a27dbb059ad1016105fa60002228
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/scripts/cli_utils.py#L152-L174
train
SUSE-Enceladus/ipa
ipa/scripts/cli_utils.py
get_log_file_from_item
def get_log_file_from_item(history): """ Return the log file based on provided history item. Description is optional. """ try: log_file, description = shlex.split(history) except ValueError: log_file = history.strip() return log_file
python
def get_log_file_from_item(history): """ Return the log file based on provided history item. Description is optional. """ try: log_file, description = shlex.split(history) except ValueError: log_file = history.strip() return log_file
[ "def", "get_log_file_from_item", "(", "history", ")", ":", "try", ":", "log_file", ",", "description", "=", "shlex", ".", "split", "(", "history", ")", "except", "ValueError", ":", "log_file", "=", "history", ".", "strip", "(", ")", "return", "log_file" ]
Return the log file based on provided history item. Description is optional.
[ "Return", "the", "log", "file", "based", "on", "provided", "history", "item", "." ]
0845eed0ea25a27dbb059ad1016105fa60002228
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/scripts/cli_utils.py#L177-L188
train
SUSE-Enceladus/ipa
ipa/scripts/cli_utils.py
results_history
def results_history(history_log, no_color): """Display a list of ipa test results history.""" try: with open(history_log, 'r') as f: lines = f.readlines() except Exception as error: echo_style( 'Unable to process results history log: %s' % error, no_color,...
python
def results_history(history_log, no_color): """Display a list of ipa test results history.""" try: with open(history_log, 'r') as f: lines = f.readlines() except Exception as error: echo_style( 'Unable to process results history log: %s' % error, no_color,...
[ "def", "results_history", "(", "history_log", ",", "no_color", ")", ":", "try", ":", "with", "open", "(", "history_log", ",", "'r'", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "except", "Exception", "as", "error", ":", "echo_st...
Display a list of ipa test results history.
[ "Display", "a", "list", "of", "ipa", "test", "results", "history", "." ]
0845eed0ea25a27dbb059ad1016105fa60002228
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/scripts/cli_utils.py#L191-L207
train
SUSE-Enceladus/ipa
ipa/scripts/cli_utils.py
split_history_item
def split_history_item(history): """ Return the log file and optional description for item. """ try: log_file, description = shlex.split(history) except ValueError: log_file = history.strip() description = None return log_file, description
python
def split_history_item(history): """ Return the log file and optional description for item. """ try: log_file, description = shlex.split(history) except ValueError: log_file = history.strip() description = None return log_file, description
[ "def", "split_history_item", "(", "history", ")", ":", "try", ":", "log_file", ",", "description", "=", "shlex", ".", "split", "(", "history", ")", "except", "ValueError", ":", "log_file", "=", "history", ".", "strip", "(", ")", "description", "=", "None",...
Return the log file and optional description for item.
[ "Return", "the", "log", "file", "and", "optional", "description", "for", "item", "." ]
0845eed0ea25a27dbb059ad1016105fa60002228
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/scripts/cli_utils.py#L210-L220
train
tgbugs/pyontutils
pyontutils/utils.py
get_working_dir
def get_working_dir(script__file__): """ hardcoded sets the 'equivalent' working directory if not in git """ start = Path(script__file__).resolve() _root = Path(start.root) working_dir = start while not list(working_dir.glob('.git')): if working_dir == _root: return work...
python
def get_working_dir(script__file__): """ hardcoded sets the 'equivalent' working directory if not in git """ start = Path(script__file__).resolve() _root = Path(start.root) working_dir = start while not list(working_dir.glob('.git')): if working_dir == _root: return work...
[ "def", "get_working_dir", "(", "script__file__", ")", ":", "start", "=", "Path", "(", "script__file__", ")", ".", "resolve", "(", ")", "_root", "=", "Path", "(", "start", ".", "root", ")", "working_dir", "=", "start", "while", "not", "list", "(", "workin...
hardcoded sets the 'equivalent' working directory if not in git
[ "hardcoded", "sets", "the", "equivalent", "working", "directory", "if", "not", "in", "git" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/utils.py#L23-L34
train
tgbugs/pyontutils
pyontutils/utils.py
sysidpath
def sysidpath(ignore_options=False): """ get a unique identifier for the machine running this function """ # in the event we have to make our own # this should not be passed in a as a parameter # since we need these definitions to be more or less static failover = Path('/tmp/machine-id') if not...
python
def sysidpath(ignore_options=False): """ get a unique identifier for the machine running this function """ # in the event we have to make our own # this should not be passed in a as a parameter # since we need these definitions to be more or less static failover = Path('/tmp/machine-id') if not...
[ "def", "sysidpath", "(", "ignore_options", "=", "False", ")", ":", "failover", "=", "Path", "(", "'/tmp/machine-id'", ")", "if", "not", "ignore_options", ":", "options", "=", "(", "Path", "(", "'/etc/machine-id'", ")", ",", "failover", ",", ")", "for", "op...
get a unique identifier for the machine running this function
[ "get", "a", "unique", "identifier", "for", "the", "machine", "running", "this", "function" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/utils.py#L45-L67
train
tgbugs/pyontutils
pyontutils/scigraph_codegen.py
State.gencode
def gencode(self): """ Run this to generate the code """ ledict = requests.get(self.api_url).json() ledict = self.dotopdict(ledict) out = self.dodict(ledict) self._code = out
python
def gencode(self): """ Run this to generate the code """ ledict = requests.get(self.api_url).json() ledict = self.dotopdict(ledict) out = self.dodict(ledict) self._code = out
[ "def", "gencode", "(", "self", ")", ":", "ledict", "=", "requests", ".", "get", "(", "self", ".", "api_url", ")", ".", "json", "(", ")", "ledict", "=", "self", ".", "dotopdict", "(", "ledict", ")", "out", "=", "self", ".", "dodict", "(", "ledict", ...
Run this to generate the code
[ "Run", "this", "to", "generate", "the", "code" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/scigraph_codegen.py#L613-L618
train
tgbugs/pyontutils
pyontutils/scigraph_codegen.py
State2.dotopdict
def dotopdict(self, dict_): """ Rewrite the 2.0 json to match what we feed the code for 1.2 """ mlookup = {'get':'GET', 'post':'POST'} def rearrange(path, method_dict, method): oid = method_dict['operationId'] self._paths[oid] = path method_dict['nickname'] = ...
python
def dotopdict(self, dict_): """ Rewrite the 2.0 json to match what we feed the code for 1.2 """ mlookup = {'get':'GET', 'post':'POST'} def rearrange(path, method_dict, method): oid = method_dict['operationId'] self._paths[oid] = path method_dict['nickname'] = ...
[ "def", "dotopdict", "(", "self", ",", "dict_", ")", ":", "mlookup", "=", "{", "'get'", ":", "'GET'", ",", "'post'", ":", "'POST'", "}", "def", "rearrange", "(", "path", ",", "method_dict", ",", "method", ")", ":", "oid", "=", "method_dict", "[", "'op...
Rewrite the 2.0 json to match what we feed the code for 1.2
[ "Rewrite", "the", "2", ".", "0", "json", "to", "match", "what", "we", "feed", "the", "code", "for", "1", ".", "2" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/scigraph_codegen.py#L622-L666
train
tgbugs/pyontutils
pyontutils/obo_io.py
OboFile.write
def write(self, filename, type_='obo'): #FIXME this is bugged """ Write file, will not overwrite files with the same name outputs to obo by default but can also output to ttl if passed type_='ttl' when called. """ if os.path.exists(filename): name, ext = file...
python
def write(self, filename, type_='obo'): #FIXME this is bugged """ Write file, will not overwrite files with the same name outputs to obo by default but can also output to ttl if passed type_='ttl' when called. """ if os.path.exists(filename): name, ext = file...
[ "def", "write", "(", "self", ",", "filename", ",", "type_", "=", "'obo'", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "name", ",", "ext", "=", "filename", ".", "rsplit", "(", "'.'", ",", "1", ")", "try", ":", "p...
Write file, will not overwrite files with the same name outputs to obo by default but can also output to ttl if passed type_='ttl' when called.
[ "Write", "file", "will", "not", "overwrite", "files", "with", "the", "same", "name", "outputs", "to", "obo", "by", "default", "but", "can", "also", "output", "to", "ttl", "if", "passed", "type_", "=", "ttl", "when", "called", "." ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/obo_io.py#L189-L213
train
tgbugs/pyontutils
librdflib/librdflib/__init__.py
main
def main(): from IPython import embed """ Python 3.6.6 ibttl 2.605194091796875 ttl 3.8316309452056885 diff lt - ttl -1.2264368534088135 librdfxml 31.267616748809814 rdfxml 58.25124502182007 diff lr - rl -26.983628273010254 simple time 17.405116319656372 """ """ Python 3.5.3 ...
python
def main(): from IPython import embed """ Python 3.6.6 ibttl 2.605194091796875 ttl 3.8316309452056885 diff lt - ttl -1.2264368534088135 librdfxml 31.267616748809814 rdfxml 58.25124502182007 diff lr - rl -26.983628273010254 simple time 17.405116319656372 """ """ Python 3.5.3 ...
[ "def", "main", "(", ")", ":", "from", "IPython", "import", "embed", "from", "time", "import", "time", "rdflib", ".", "plugin", ".", "register", "(", "'librdfxml'", ",", "rdflib", ".", "parser", ".", "Parser", ",", "'librdflib'", ",", "'libRdfxmlParser'", "...
Python 3.6.6 ibttl 2.605194091796875 ttl 3.8316309452056885 diff lt - ttl -1.2264368534088135 librdfxml 31.267616748809814 rdfxml 58.25124502182007 diff lr - rl -26.983628273010254 simple time 17.405116319656372
[ "Python", "3", ".", "6", ".", "6", "ibttl", "2", ".", "605194091796875", "ttl", "3", ".", "8316309452056885", "diff", "lt", "-", "ttl", "-", "1", ".", "2264368534088135", "librdfxml", "31", ".", "267616748809814", "rdfxml", "58", ".", "25124502182007", "di...
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/librdflib/librdflib/__init__.py#L125-L196
train
tgbugs/pyontutils
pyontutils/combinators.py
make_predicate_object_combinator
def make_predicate_object_combinator(function, p, o): """ Combinator to hold predicate object pairs until a subject is supplied and then call a function that accepts a subject, predicate, and object. Create a combinator to defer production of a triple until the missing pieces are supplied. ...
python
def make_predicate_object_combinator(function, p, o): """ Combinator to hold predicate object pairs until a subject is supplied and then call a function that accepts a subject, predicate, and object. Create a combinator to defer production of a triple until the missing pieces are supplied. ...
[ "def", "make_predicate_object_combinator", "(", "function", ",", "p", ",", "o", ")", ":", "def", "predicate_object_combinator", "(", "subject", ")", ":", "return", "function", "(", "subject", ",", "p", ",", "o", ")", "return", "predicate_object_combinator" ]
Combinator to hold predicate object pairs until a subject is supplied and then call a function that accepts a subject, predicate, and object. Create a combinator to defer production of a triple until the missing pieces are supplied. Note that the naming here tells you what is stored IN the comb...
[ "Combinator", "to", "hold", "predicate", "object", "pairs", "until", "a", "subject", "is", "supplied", "and", "then", "call", "a", "function", "that", "accepts", "a", "subject", "predicate", "and", "object", "." ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/combinators.py#L17-L26
train
tgbugs/pyontutils
pyontutils/combinators.py
EquivalentClass.serialize
def serialize(self, subject, *objects_or_combinators): """ object_combinators may also be URIRefs or Literals """ ec_s = rdflib.BNode() if self.operator is not None: if subject is not None: yield subject, self.predicate, ec_s yield from oc(ec_s) ...
python
def serialize(self, subject, *objects_or_combinators): """ object_combinators may also be URIRefs or Literals """ ec_s = rdflib.BNode() if self.operator is not None: if subject is not None: yield subject, self.predicate, ec_s yield from oc(ec_s) ...
[ "def", "serialize", "(", "self", ",", "subject", ",", "*", "objects_or_combinators", ")", ":", "ec_s", "=", "rdflib", ".", "BNode", "(", ")", "if", "self", ".", "operator", "is", "not", "None", ":", "if", "subject", "is", "not", "None", ":", "yield", ...
object_combinators may also be URIRefs or Literals
[ "object_combinators", "may", "also", "be", "URIRefs", "or", "Literals" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/combinators.py#L681-L707
train
shanbay/peeweext
peeweext/model.py
Model.update_with
def update_with(self, **query): """ secure update, mass assignment protected """ for k, v in self._filter_attrs(query).items(): setattr(self, k, v) return self.save()
python
def update_with(self, **query): """ secure update, mass assignment protected """ for k, v in self._filter_attrs(query).items(): setattr(self, k, v) return self.save()
[ "def", "update_with", "(", "self", ",", "**", "query", ")", ":", "for", "k", ",", "v", "in", "self", ".", "_filter_attrs", "(", "query", ")", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "k", ",", "v", ")", "return", "self", ".", "...
secure update, mass assignment protected
[ "secure", "update", "mass", "assignment", "protected" ]
ff62a3d01e4584d50fde1944b9616c3b4236ecf0
https://github.com/shanbay/peeweext/blob/ff62a3d01e4584d50fde1944b9616c3b4236ecf0/peeweext/model.py#L53-L59
train
shanbay/peeweext
peeweext/model.py
Model._validate
def _validate(self): """Validate model data and save errors """ errors = {} for name, validator in self._validators.items(): value = getattr(self, name) try: validator(self, value) except ValidationError as e: errors[n...
python
def _validate(self): """Validate model data and save errors """ errors = {} for name, validator in self._validators.items(): value = getattr(self, name) try: validator(self, value) except ValidationError as e: errors[n...
[ "def", "_validate", "(", "self", ")", ":", "errors", "=", "{", "}", "for", "name", ",", "validator", "in", "self", ".", "_validators", ".", "items", "(", ")", ":", "value", "=", "getattr", "(", "self", ",", "name", ")", "try", ":", "validator", "("...
Validate model data and save errors
[ "Validate", "model", "data", "and", "save", "errors" ]
ff62a3d01e4584d50fde1944b9616c3b4236ecf0
https://github.com/shanbay/peeweext/blob/ff62a3d01e4584d50fde1944b9616c3b4236ecf0/peeweext/model.py#L115-L128
train
tgbugs/pyontutils
ilxutils/ilxutils/nltklib.py
penn_to_wn
def penn_to_wn(tag): """ Convert between a Penn Treebank tag to a simplified Wordnet tag """ if tag.startswith('N'): return 'n' if tag.startswith('V'): return 'v' if tag.startswith('J'): return 'a' if tag.startswith('R'): return 'r' return None
python
def penn_to_wn(tag): """ Convert between a Penn Treebank tag to a simplified Wordnet tag """ if tag.startswith('N'): return 'n' if tag.startswith('V'): return 'v' if tag.startswith('J'): return 'a' if tag.startswith('R'): return 'r' return None
[ "def", "penn_to_wn", "(", "tag", ")", ":", "if", "tag", ".", "startswith", "(", "'N'", ")", ":", "return", "'n'", "if", "tag", ".", "startswith", "(", "'V'", ")", ":", "return", "'v'", "if", "tag", ".", "startswith", "(", "'J'", ")", ":", "return",...
Convert between a Penn Treebank tag to a simplified Wordnet tag
[ "Convert", "between", "a", "Penn", "Treebank", "tag", "to", "a", "simplified", "Wordnet", "tag" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/nltklib.py#L9-L23
train
tgbugs/pyontutils
ilxutils/ilxutils/nltklib.py
sentence_similarity
def sentence_similarity(sentence1, sentence2): """ compute the sentence similarity using Wordnet """ # Tokenize and tag sentence1 = pos_tag(word_tokenize(sentence1)) sentence2 = pos_tag(word_tokenize(sentence2)) # Get the synsets for the tagged words synsets1 = [tagged_to_synset(*tagged_word) f...
python
def sentence_similarity(sentence1, sentence2): """ compute the sentence similarity using Wordnet """ # Tokenize and tag sentence1 = pos_tag(word_tokenize(sentence1)) sentence2 = pos_tag(word_tokenize(sentence2)) # Get the synsets for the tagged words synsets1 = [tagged_to_synset(*tagged_word) f...
[ "def", "sentence_similarity", "(", "sentence1", ",", "sentence2", ")", ":", "sentence1", "=", "pos_tag", "(", "word_tokenize", "(", "sentence1", ")", ")", "sentence2", "=", "pos_tag", "(", "word_tokenize", "(", "sentence2", ")", ")", "synsets1", "=", "[", "t...
compute the sentence similarity using Wordnet
[ "compute", "the", "sentence", "similarity", "using", "Wordnet" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/nltklib.py#L36-L70
train
tgbugs/pyontutils
ilxutils/ilxutils/ontopandas.py
command_line
def command_line(): ''' If you want to use the command line ''' from docopt import docopt doc = docopt( __doc__, version=VERSION ) args = pd.Series({k.replace('--', ''): v for k, v in doc.items()}) if args.all: graph = Graph2Pandas(args.file, _type='all') elif args.type: graph = ...
python
def command_line(): ''' If you want to use the command line ''' from docopt import docopt doc = docopt( __doc__, version=VERSION ) args = pd.Series({k.replace('--', ''): v for k, v in doc.items()}) if args.all: graph = Graph2Pandas(args.file, _type='all') elif args.type: graph = ...
[ "def", "command_line", "(", ")", ":", "from", "docopt", "import", "docopt", "doc", "=", "docopt", "(", "__doc__", ",", "version", "=", "VERSION", ")", "args", "=", "pd", ".", "Series", "(", "{", "k", ".", "replace", "(", "'--'", ",", "''", ")", ":"...
If you want to use the command line
[ "If", "you", "want", "to", "use", "the", "command", "line" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/ontopandas.py#L279-L290
train
tgbugs/pyontutils
ilxutils/ilxutils/ontopandas.py
OntoPandas.save
def save(self, foldername: str, path_to_folder: str=None) -> None: ''' Saves entities into multiple files within the same folder because of pickle-recursive errors that would happen if squeezed into one ''' self.create_pickle((self.g.namespaces, )) self.df.to_pickle(output)
python
def save(self, foldername: str, path_to_folder: str=None) -> None: ''' Saves entities into multiple files within the same folder because of pickle-recursive errors that would happen if squeezed into one ''' self.create_pickle((self.g.namespaces, )) self.df.to_pickle(output)
[ "def", "save", "(", "self", ",", "foldername", ":", "str", ",", "path_to_folder", ":", "str", "=", "None", ")", "->", "None", ":", "self", ".", "create_pickle", "(", "(", "self", ".", "g", ".", "namespaces", ",", ")", ")", "self", ".", "df", ".", ...
Saves entities into multiple files within the same folder because of pickle-recursive errors that would happen if squeezed into one
[ "Saves", "entities", "into", "multiple", "files", "within", "the", "same", "folder", "because", "of", "pickle", "-", "recursive", "errors", "that", "would", "happen", "if", "squeezed", "into", "one" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/ontopandas.py#L54-L58
train
tgbugs/pyontutils
ilxutils/ilxutils/ontopandas.py
OntoPandas.qname
def qname(self, uri: str) -> str: ''' Returns qname of uri in rdflib graph while also saving it ''' try: prefix, namespace, name = self.g.compute_qname(uri) qname = prefix + ':' + name return qname except: try: print('prefix:', pref...
python
def qname(self, uri: str) -> str: ''' Returns qname of uri in rdflib graph while also saving it ''' try: prefix, namespace, name = self.g.compute_qname(uri) qname = prefix + ':' + name return qname except: try: print('prefix:', pref...
[ "def", "qname", "(", "self", ",", "uri", ":", "str", ")", "->", "str", ":", "try", ":", "prefix", ",", "namespace", ",", "name", "=", "self", ".", "g", ".", "compute_qname", "(", "uri", ")", "qname", "=", "prefix", "+", "':'", "+", "name", "retur...
Returns qname of uri in rdflib graph while also saving it
[ "Returns", "qname", "of", "uri", "in", "rdflib", "graph", "while", "also", "saving", "it" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/ontopandas.py#L60-L73
train
tgbugs/pyontutils
ilxutils/ilxutils/ontopandas.py
OntoPandas.get_sparql_dataframe
def get_sparql_dataframe( self ): ''' Iterates through the sparql table and condenses it into a Pandas DataFrame ''' self.result = self.g.query(self.query) cols = set() # set(['qname']) indx = set() data = {} curr_subj = None # place marker for first subj to be processed ...
python
def get_sparql_dataframe( self ): ''' Iterates through the sparql table and condenses it into a Pandas DataFrame ''' self.result = self.g.query(self.query) cols = set() # set(['qname']) indx = set() data = {} curr_subj = None # place marker for first subj to be processed ...
[ "def", "get_sparql_dataframe", "(", "self", ")", ":", "self", ".", "result", "=", "self", ".", "g", ".", "query", "(", "self", ".", "query", ")", "cols", "=", "set", "(", ")", "indx", "=", "set", "(", ")", "data", "=", "{", "}", "curr_subj", "=",...
Iterates through the sparql table and condenses it into a Pandas DataFrame
[ "Iterates", "through", "the", "sparql", "table", "and", "condenses", "it", "into", "a", "Pandas", "DataFrame" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/ontopandas.py#L171-L259
train
tgbugs/pyontutils
ilxutils/ilxutils/ontopandas.py
OntoPandas.df
def df(self, qname_predicates:bool=False, keep_variable_type:bool=True) -> pd.DataFrame: ''' Multi funcitonal DataFrame with settings ''' local_df = self.df.copy() if qname_predicates: for col in self.columns: local_df.rename({col: self.g.qname(col)}) if not k...
python
def df(self, qname_predicates:bool=False, keep_variable_type:bool=True) -> pd.DataFrame: ''' Multi funcitonal DataFrame with settings ''' local_df = self.df.copy() if qname_predicates: for col in self.columns: local_df.rename({col: self.g.qname(col)}) if not k...
[ "def", "df", "(", "self", ",", "qname_predicates", ":", "bool", "=", "False", ",", "keep_variable_type", ":", "bool", "=", "True", ")", "->", "pd", ".", "DataFrame", ":", "local_df", "=", "self", ".", "df", ".", "copy", "(", ")", "if", "qname_predicate...
Multi funcitonal DataFrame with settings
[ "Multi", "funcitonal", "DataFrame", "with", "settings" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/ontopandas.py#L261-L270
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_rdflib.py
SimpleGraph.qname
def qname(self, iri: str) -> str: """ Get qualified name of uri in rdflib graph while also saving it Args: iri: The iri that you want to replace the uri with a known prefix with Returns: qualified name of the iri to be used as the new predicate """ prefix, namespace, name = sel...
python
def qname(self, iri: str) -> str: """ Get qualified name of uri in rdflib graph while also saving it Args: iri: The iri that you want to replace the uri with a known prefix with Returns: qualified name of the iri to be used as the new predicate """ prefix, namespace, name = sel...
[ "def", "qname", "(", "self", ",", "iri", ":", "str", ")", "->", "str", ":", "prefix", ",", "namespace", ",", "name", "=", "self", ".", "g", ".", "compute_qname", "(", "uri", ")", "qname", "=", "prefix", "+", "':'", "+", "name", "self", ".", "rqna...
Get qualified name of uri in rdflib graph while also saving it Args: iri: The iri that you want to replace the uri with a known prefix with Returns: qualified name of the iri to be used as the new predicate
[ "Get", "qualified", "name", "of", "uri", "in", "rdflib", "graph", "while", "also", "saving", "it" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_rdflib.py#L61-L71
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_rdflib.py
SimpleGraph.find_prefix
def find_prefix(self, iri: Union[URIRef, Literal, str]) -> Union[None, str]: """ Finds if uri is in common_namespaces Auto adds prefix if incoming iri has a uri in common_namespaces. If its not in the local library, then it will just be spit out as the iri and not saved/condensed into qualified...
python
def find_prefix(self, iri: Union[URIRef, Literal, str]) -> Union[None, str]: """ Finds if uri is in common_namespaces Auto adds prefix if incoming iri has a uri in common_namespaces. If its not in the local library, then it will just be spit out as the iri and not saved/condensed into qualified...
[ "def", "find_prefix", "(", "self", ",", "iri", ":", "Union", "[", "URIRef", ",", "Literal", ",", "str", "]", ")", "->", "Union", "[", "None", ",", "str", "]", ":", "iri", "=", "str", "(", "iri", ")", "max_iri_len", "=", "0", "max_prefix", "=", "N...
Finds if uri is in common_namespaces Auto adds prefix if incoming iri has a uri in common_namespaces. If its not in the local library, then it will just be spit out as the iri and not saved/condensed into qualified names. The reason for the maxes is find the longest string match. This ...
[ "Finds", "if", "uri", "is", "in", "common_namespaces" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_rdflib.py#L102-L127
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_rdflib.py
SimpleGraph.add_annotation
def add_annotation( self, subj: URIRef, pred: URIRef, obj: Union[Literal, URIRef], a_p: URIRef , a_o: Union[Literal, URIRef], ) -> BNode: """ Adds annotation to rdflib graph. The annotation axiom will filled in if this is a...
python
def add_annotation( self, subj: URIRef, pred: URIRef, obj: Union[Literal, URIRef], a_p: URIRef , a_o: Union[Literal, URIRef], ) -> BNode: """ Adds annotation to rdflib graph. The annotation axiom will filled in if this is a...
[ "def", "add_annotation", "(", "self", ",", "subj", ":", "URIRef", ",", "pred", ":", "URIRef", ",", "obj", ":", "Union", "[", "Literal", ",", "URIRef", "]", ",", "a_p", ":", "URIRef", ",", "a_o", ":", "Union", "[", "Literal", ",", "URIRef", "]", ","...
Adds annotation to rdflib graph. The annotation axiom will filled in if this is a new annotation for the triple. Args: subj: Entity subject to be annotated pref: Entities Predicate Anchor to be annotated obj: Entities Object Anchor to be annotated a_p: A...
[ "Adds", "annotation", "to", "rdflib", "graph", "." ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_rdflib.py#L129-L163
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_rdflib.py
SimpleGraph.add_triple
def add_triple( self, subj: Union[URIRef, str], pred: Union[URIRef, str], obj: Union[URIRef, Literal, str] ) -> None: """ Adds triple to rdflib Graph Triple can be of any subject, predicate, and object of the entity without a need for order. ...
python
def add_triple( self, subj: Union[URIRef, str], pred: Union[URIRef, str], obj: Union[URIRef, Literal, str] ) -> None: """ Adds triple to rdflib Graph Triple can be of any subject, predicate, and object of the entity without a need for order. ...
[ "def", "add_triple", "(", "self", ",", "subj", ":", "Union", "[", "URIRef", ",", "str", "]", ",", "pred", ":", "Union", "[", "URIRef", ",", "str", "]", ",", "obj", ":", "Union", "[", "URIRef", ",", "Literal", ",", "str", "]", ")", "->", "None", ...
Adds triple to rdflib Graph Triple can be of any subject, predicate, and object of the entity without a need for order. Args: subj: Entity subject pred: Entity predicate obj: Entity object Example: In [1]: add_triple( ...: 'h...
[ "Adds", "triple", "to", "rdflib", "Graph" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_rdflib.py#L165-L191
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_rdflib.py
SimpleGraph.process_prefix
def process_prefix(self, prefix: str) -> Union[Namespace, None]: """ Add namespace to graph if it has a local match This allows qnames to be used without adding their respected namespaces if they are in the common_namespaces local dict. This is is to save a butt-ton of time trying to see what ...
python
def process_prefix(self, prefix: str) -> Union[Namespace, None]: """ Add namespace to graph if it has a local match This allows qnames to be used without adding their respected namespaces if they are in the common_namespaces local dict. This is is to save a butt-ton of time trying to see what ...
[ "def", "process_prefix", "(", "self", ",", "prefix", ":", "str", ")", "->", "Union", "[", "Namespace", ",", "None", "]", ":", "if", "self", ".", "namespaces", ".", "get", "(", "prefix", ")", ":", "return", "self", ".", "namespaces", "[", "prefix", "]...
Add namespace to graph if it has a local match This allows qnames to be used without adding their respected namespaces if they are in the common_namespaces local dict. This is is to save a butt-ton of time trying to see what the ontology has as far as uris go. Args: prefix: prefix of t...
[ "Add", "namespace", "to", "graph", "if", "it", "has", "a", "local", "match" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_rdflib.py#L193-L209
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_rdflib.py
SimpleGraph.process_subj_or_pred
def process_subj_or_pred(self, component: Union[URIRef, str]) -> URIRef: """ Adds viable uri from iri or expands viable qname to iri to be triple ready Need to have a viable qualified name (qname) in order to use a qname. You can make it viable by either add the namespace beforehand with add_na...
python
def process_subj_or_pred(self, component: Union[URIRef, str]) -> URIRef: """ Adds viable uri from iri or expands viable qname to iri to be triple ready Need to have a viable qualified name (qname) in order to use a qname. You can make it viable by either add the namespace beforehand with add_na...
[ "def", "process_subj_or_pred", "(", "self", ",", "component", ":", "Union", "[", "URIRef", ",", "str", "]", ")", "->", "URIRef", ":", "if", "'http'", "in", "component", ":", "prefix", "=", "self", ".", "find_prefix", "(", "component", ")", "if", "prefix"...
Adds viable uri from iri or expands viable qname to iri to be triple ready Need to have a viable qualified name (qname) in order to use a qname. You can make it viable by either add the namespace beforehand with add_namespace(s) or if its already in the local common_namespaces preloaded. ...
[ "Adds", "viable", "uri", "from", "iri", "or", "expands", "viable", "qname", "to", "iri", "to", "be", "triple", "ready" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_rdflib.py#L211-L237
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_rdflib.py
SimpleGraph.process_obj
def process_obj(self, obj: Union[URIRef, Literal, str]) -> Union[URIRef, Literal]: """ Gives component the proper node type Args: obj: Entity object to be converted to its appropriate node type Returns: URIRef or Literal type of the object provided. Raises: ...
python
def process_obj(self, obj: Union[URIRef, Literal, str]) -> Union[URIRef, Literal]: """ Gives component the proper node type Args: obj: Entity object to be converted to its appropriate node type Returns: URIRef or Literal type of the object provided. Raises: ...
[ "def", "process_obj", "(", "self", ",", "obj", ":", "Union", "[", "URIRef", ",", "Literal", ",", "str", "]", ")", "->", "Union", "[", "URIRef", ",", "Literal", "]", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", "or", "isinstance", "(", "ob...
Gives component the proper node type Args: obj: Entity object to be converted to its appropriate node type Returns: URIRef or Literal type of the object provided. Raises: SystemExit: If object is a dict or list it becomes str with broken data. Needs to ...
[ "Gives", "component", "the", "proper", "node", "type" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_rdflib.py#L239-L271
train
tgbugs/pyontutils
ilxutils/ilxutils/simple_rdflib.py
SimpleGraph.remove_triple
def remove_triple( self, subj: URIRef, pred: URIRef, obj: Union[URIRef, Literal] ) -> None: """ Removes triple from rdflib Graph You must input the triple in its URIRef or Literal form for each node exactly the way it was inputed or it wil...
python
def remove_triple( self, subj: URIRef, pred: URIRef, obj: Union[URIRef, Literal] ) -> None: """ Removes triple from rdflib Graph You must input the triple in its URIRef or Literal form for each node exactly the way it was inputed or it wil...
[ "def", "remove_triple", "(", "self", ",", "subj", ":", "URIRef", ",", "pred", ":", "URIRef", ",", "obj", ":", "Union", "[", "URIRef", ",", "Literal", "]", ")", "->", "None", ":", "self", ".", "g", ".", "remove", "(", "(", "subj", ",", "pred", ","...
Removes triple from rdflib Graph You must input the triple in its URIRef or Literal form for each node exactly the way it was inputed or it will not delete the triple. Args: subj: Entity subject to be removed it its the only node with this subject; else this is just...
[ "Removes", "triple", "from", "rdflib", "Graph" ]
3d913db29c177db39151592909a4f56170ef8b35
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_rdflib.py#L291-L308
train