sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def from_extension(extension): """ Look up the BioPython file type corresponding with input extension. Look up is case insensitive. """ if not extension.startswith('.'): raise ValueError("Extensions must begin with a period.") try: return EXTENSION_TO_TYPE[extension.lower()] ...
Look up the BioPython file type corresponding with input extension. Look up is case insensitive.
entailment
def from_filename(file_name): """ Look up the BioPython file type corresponding to an input file name. """ base, extension = os.path.splitext(file_name) if extension in COMPRESS_EXT: # Compressed file extension = os.path.splitext(base)[1] return from_extension(extension)
Look up the BioPython file type corresponding to an input file name.
entailment
def from_handle(fh, stream_default='fasta'): """ Look up the BioPython file type corresponding to a file-like object. For stdin, stdout, and stderr, ``stream_default`` is used. """ if fh in (sys.stdin, sys.stdout, sys.stderr): return stream_default return from_filename(fh.name)
Look up the BioPython file type corresponding to a file-like object. For stdin, stdout, and stderr, ``stream_default`` is used.
entailment
def parse_arguments(argv): """ Extract command-line arguments for different actions. """ parser = argparse.ArgumentParser(description='seqmagick - Manipulate ' + \ ' sequence files.', prog='seqmagick') parser.add_argument('-V', '--version', action='version', version='seqmagick v'...
Extract command-line arguments for different actions.
entailment
def ungap_index_map(sequence, gap_chars='-'): """ Returns a dict mapping from an index in the ungapped sequence to an index in the gapped sequence. >>> ungap_index_map('AC-TG-') {0: 0, 1: 1, 2: 3, 3: 4} """ counter = itertools.count(0).__next__ ungap_indexes = [ counter() if c n...
Returns a dict mapping from an index in the ungapped sequence to an index in the gapped sequence. >>> ungap_index_map('AC-TG-') {0: 0, 1: 1, 2: 3, 3: 4}
entailment
def gap_index_map(sequence, gap_chars='-'): """ Opposite of ungap_index_map: returns mapping from gapped index to ungapped index. >>> gap_index_map('AC-TG-') {0: 0, 1: 1, 3: 2, 4: 3} """ return dict( (v, k) for k, v in list(ungap_index_map(sequence, gap_chars).items()))
Opposite of ungap_index_map: returns mapping from gapped index to ungapped index. >>> gap_index_map('AC-TG-') {0: 0, 1: 1, 3: 2, 4: 3}
entailment
def _iupac_ambiguous_equal(ambig_base, unambig_base): """ Tests two bases for equality, accounting for IUPAC ambiguous DNA ambiguous base may be IUPAC ambiguous, unambiguous must be one of ACGT """ iupac_translation = { 'A': 'A', 'C': 'C', 'G': 'G', 'T': 'T', ...
Tests two bases for equality, accounting for IUPAC ambiguous DNA ambiguous base may be IUPAC ambiguous, unambiguous must be one of ACGT
entailment
def hamming_distance(s1, s2, equality_function=operator.eq): """ Returns the hamming distance between two strings. """ if not len(s1) == len(s2): raise ValueError("String lengths are not equal") # Number of non-matching characters: return sum(not equality_function(c1, c2) for c1, c2 in ...
Returns the hamming distance between two strings.
entailment
def locate_primers(sequences, forward_primer, reverse_primer, reverse_complement, max_hamming_distance): """ Find forward and reverse primers in a set of sequences, return two tuples: (forward_start, forward_end), (reverse_start, reverse_end) """ forward_loc = None reverse_loc...
Find forward and reverse primers in a set of sequences, return two tuples: (forward_start, forward_end), (reverse_start, reverse_end)
entailment
def trim(sequences, start, end): """ Slice the input sequences from start to end """ logging.info("Trimming from %d to %d", start, end) return (sequence[start:end] for sequence in sequences)
Slice the input sequences from start to end
entailment
def action(arguments): """ Trim the alignment as specified """ # Determine file format for input and output source_format = (arguments.source_format or fileformat.from_handle(arguments.source_file)) output_format = (arguments.output_format or fileformat....
Trim the alignment as specified
entailment
def align(self, sequence): """ Aligns the primer to the given query sequence, returning a tuple of: hamming_distance, start, end Where hamming distance is the distance between the primer and aligned sequence, and start and end give the start and end index of the primer ...
Aligns the primer to the given query sequence, returning a tuple of: hamming_distance, start, end Where hamming distance is the distance between the primer and aligned sequence, and start and end give the start and end index of the primer relative to the input sequence.
entailment
def hash_starts_numeric(records): """ Very useful function that only accepts records with a numeric start to their sha-1 hash. """ for record in records: seq_hash = hashlib.sha1(str(record.seq)).hexdigest() if seq_hash[0].isdigit(): yield record
Very useful function that only accepts records with a numeric start to their sha-1 hash.
entailment
def atomic_write(path, mode='wt', permissions=None, file_factory=None, **kwargs): """ Open a file for atomic writing. Generates a temp file, renames to value of ``path``. Arguments: ``permissions``: Permissions to set (default: umask) ``file_factory``: If given, the handle yielded will be the ...
Open a file for atomic writing. Generates a temp file, renames to value of ``path``. Arguments: ``permissions``: Permissions to set (default: umask) ``file_factory``: If given, the handle yielded will be the result of calling file_factory(path) Additional arguments are passed to tempfile....
entailment
def cut_range(string): """ A custom argparse 'type' to deal with sequences ranges such as 5:500. Returns a 0-based slice corresponding to the selection defined by the slice """ value_range = string.split(':') if len(value_range) == 1: start = int(value_range[0]) stop = start ...
A custom argparse 'type' to deal with sequences ranges such as 5:500. Returns a 0-based slice corresponding to the selection defined by the slice
entailment
def typed_range(type_func, minimum, maximum): """ Require variables to be of the specified type, between minimum and maximum """ @functools.wraps(type_func) def inner(string): result = type_func(string) if not result >= minimum and result <= maximum: raise argparse.Argume...
Require variables to be of the specified type, between minimum and maximum
entailment
def partial_append_action(fn, argument_keys=None): """ Creates a new class extending argparse.Action, which appends a partially-applied function to dest. The optional argument_keys argument should either be None (no additional arguments to fn) or an iterable of function keys to partially apply. ...
Creates a new class extending argparse.Action, which appends a partially-applied function to dest. The optional argument_keys argument should either be None (no additional arguments to fn) or an iterable of function keys to partially apply.
entailment
def positive_value(target_type): """ Wraps target_type in a function that requires the parsed argument be >= 0 """ def inner(string): value = target_type(string) if not value >= 0: raise argparse.ArgumentTypeError("Invalid positive number: " + string) ...
Wraps target_type in a function that requires the parsed argument be >= 0
entailment
def add_options(parser): """ Add optional arguments to the parser """ partial_action = common.partial_append_action file_mods = parser.add_argument_group("Sequence File Modification") file_mods.add_argument('--line-wrap', dest='line_wrap', metavar='N', type=int, help='Adjust line wrap fo...
Add optional arguments to the parser
entailment
def build_parser(parser): """ Add shared arguments to the convert or mogrify parser. """ add_options(parser) parser.add_argument('source_file', type=common.FileType('rt'), help="Input sequence file") parser.add_argument('dest_file', help="Output file") return parser
Add shared arguments to the convert or mogrify parser.
entailment
def module_function(string): """ Load a function from a python module using a file name, function name specification of format: /path/to/x.py:function_name[:parameter] """ parts = string.split(':', 2) if len(parts) < 2: raise ValueError( "Illegal specification. Should...
Load a function from a python module using a file name, function name specification of format: /path/to/x.py:function_name[:parameter]
entailment
def parse_cgmlst_alleles(cgmlst_fasta): """Parse cgMLST alleles from fasta file cgMLST FASTA file must have a header format of ">{marker name}|{allele name}" Args: cgmlst_fasta (str): cgMLST fasta file path Returns: dict of list: Marker name to list of allele sequences """ out ...
Parse cgMLST alleles from fasta file cgMLST FASTA file must have a header format of ">{marker name}|{allele name}" Args: cgmlst_fasta (str): cgMLST fasta file path Returns: dict of list: Marker name to list of allele sequences
entailment
def parse_fasta(filepath): ''' Parse a fasta file returning a generator yielding tuples of fasta headers to sequences. Note: This function should give equivalent results to SeqIO from BioPython .. code-block:: python from Bio import SeqIO # biopython to dict of hea...
Parse a fasta file returning a generator yielding tuples of fasta headers to sequences. Note: This function should give equivalent results to SeqIO from BioPython .. code-block:: python from Bio import SeqIO # biopython to dict of header-seq hseqs_bio = {r.desc...
entailment
def fasta_format_check(fasta_path, logger): """ Check that a file is valid FASTA format. - First non-blank line needs to begin with a '>' header character. - Sequence can only contain valid IUPAC nucleotide characters Args: fasta_str (str): FASTA file contents string Raises: ...
Check that a file is valid FASTA format. - First non-blank line needs to begin with a '>' header character. - Sequence can only contain valid IUPAC nucleotide characters Args: fasta_str (str): FASTA file contents string Raises: Exception: If invalid FASTA format
entailment
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 ...
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
entailment
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...
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
entailment
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 =...
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
entailment
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...
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
entailment
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...
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...
entailment
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_...
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
entailment
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 ...
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...
entailment
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...
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 ...
entailment
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...
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...
entailment
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:...
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...
entailment
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...
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
entailment
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...
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...
entailment
def run_cgmlst(blast_runner, full=False): """Perform in silico cgMLST on an input genome Args: blast_runner (sistr.src.blast_wrapper.BlastRunner): blastn runner object with genome fasta initialized Returns: dict: cgMLST ref genome match, distance to closest ref genome, subspecies and serov...
Perform in silico cgMLST on an input genome Args: blast_runner (sistr.src.blast_wrapper.BlastRunner): blastn runner object with genome fasta initialized Returns: dict: cgMLST ref genome match, distance to closest ref genome, subspecies and serovar predictions dict: marker allele match ...
entailment
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...
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(...
entailment
def extend_subj_match_vec(df): """ Get the extended clipped (clamped) start and end subject sequence indices Also get whether each match needs to be reverse complemented and whether each extended match would be truncated by the end of the subject sequence. Args: df (pandas.DataFrame): blas...
Get the extended clipped (clamped) start and end subject sequence indices Also get whether each match needs to be reverse complemented and whether each extended match would be truncated by the end of the subject sequence. Args: df (pandas.DataFrame): blastn results dataframe Returns: ...
entailment
def listattrs(x): """Get all instance and class attributes for an object Get all instance and class attributes for an object except those that start with "__" (double underscore). __dict__ of an object only reports the instance attributes while dir() reports all of the attributes of an ob...
Get all instance and class attributes for an object Get all instance and class attributes for an object except those that start with "__" (double underscore). __dict__ of an object only reports the instance attributes while dir() reports all of the attributes of an object including private on...
entailment
def to_dict(x, depth, exclude_keys=set(), depth_threshold=8): """Transform a nested object/dict/list into a regular dict json.dump(s) and pickle don't like to un/serialize regular Python objects so this function should handle arbitrarily nested objects to be serialized to regular string, float, int...
Transform a nested object/dict/list into a regular dict json.dump(s) and pickle don't like to un/serialize regular Python objects so this function should handle arbitrarily nested objects to be serialized to regular string, float, int, bool, None values. This is a recursive function so by defa...
entailment
def _recur_flatten(key, x, out, sep='.'): """Helper function to flatten_dict Recursively flatten all nested values within a dict Args: key (str): parent key x (object): object to flatten or add to out dict out (dict): 1D output dict sep (str): flattened key separato...
Helper function to flatten_dict Recursively flatten all nested values within a dict Args: key (str): parent key x (object): object to flatten or add to out dict out (dict): 1D output dict sep (str): flattened key separator string Returns: dict: flattene...
entailment
def flatten_dict(x): """Flatten a dict Flatten an arbitrarily nested dict as output by to_dict .. note:: Keys in the flattened dict may get very long. Args: x (dict): Arbitrarily nested dict (maybe resembling a tree) with literal/scalar leaf values Retu...
Flatten a dict Flatten an arbitrarily nested dict as output by to_dict .. note:: Keys in the flattened dict may get very long. Args: x (dict): Arbitrarily nested dict (maybe resembling a tree) with literal/scalar leaf values Returns: dict: flattened...
entailment
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...
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 ...
entailment
def is_blast_result_trunc(qstart, qend, sstart, send, qlen, slen): """Check if a query sequence is truncated by the end of a subject sequence Args: qstart (int): Query sequence start index qend (int): Query sequence end index sstart (int): Subject sequence start inde...
Check if a query sequence is truncated by the end of a subject sequence Args: qstart (int): Query sequence start index qend (int): Query sequence end index sstart (int): Subject sequence start index send (int): Subject sequence end index qlen (int): Q...
entailment
def trunc(qstart, qend, sstart, send, qlen, slen): """Check if a query sequence is truncated by the end of a subject sequence Args: qstart (int pandas.Series): Query sequence start index qend (int pandas.Series): Query sequence end index sstart (int pandas.Series): S...
Check if a query sequence is truncated by the end of a subject sequence Args: qstart (int pandas.Series): Query sequence start index qend (int pandas.Series): Query sequence end index sstart (int pandas.Series): Subject sequence start index send (int pandas.Serie...
entailment
def perfect_matches(self): """ Return pandas DataFrame with perfect BLAST matches (100% identity and coverage) Returns: pandas.DataFrame or None: DataFrame of perfect BLAST matches or None if no perfect matches exist """ if self.is_missing: return None ...
Return pandas DataFrame with perfect BLAST matches (100% identity and coverage) Returns: pandas.DataFrame or None: DataFrame of perfect BLAST matches or None if no perfect matches exist
entailment
def top_result(self): """Return top `blastn` result Try to find a 100% identity and coverage result (perfect match). If one does not exist, then retrieve the result with the highest bitscore. Returns: Ordered dict of BLASTN results or None if no BLASTN results generated ...
Return top `blastn` result Try to find a 100% identity and coverage result (perfect match). If one does not exist, then retrieve the result with the highest bitscore. Returns: Ordered dict of BLASTN results or None if no BLASTN results generated
entailment
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 """ ...
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
entailment
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...
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
entailment
def delete(self, key): """Implementation of :meth:`~simplekv.KeyValueStore.delete`. If an exception occurs in either the cache or backing store, all are passing on. """ self._dstore.delete(key) self.cache.delete(key)
Implementation of :meth:`~simplekv.KeyValueStore.delete`. If an exception occurs in either the cache or backing store, all are passing on.
entailment
def get(self, key): """Implementation of :meth:`~simplekv.KeyValueStore.get`. If a cache miss occurs, the value is retrieved, stored in the cache and returned. If the cache raises an :exc:`~exceptions.IOError`, the cache is ignored, and the backing store is consulted directly. ...
Implementation of :meth:`~simplekv.KeyValueStore.get`. If a cache miss occurs, the value is retrieved, stored in the cache and returned. If the cache raises an :exc:`~exceptions.IOError`, the cache is ignored, and the backing store is consulted directly. It is possible for a c...
entailment
def get_file(self, key, file): """Implementation of :meth:`~simplekv.KeyValueStore.get_file`. If a cache miss occurs, the value is retrieved, stored in the cache and returned. If the cache raises an :exc:`~exceptions.IOError`, the retrieval cannot proceed: If ``file`` was an op...
Implementation of :meth:`~simplekv.KeyValueStore.get_file`. If a cache miss occurs, the value is retrieved, stored in the cache and returned. If the cache raises an :exc:`~exceptions.IOError`, the retrieval cannot proceed: If ``file`` was an open file, data maybe been written to it ...
entailment
def open(self, key): """Implementation of :meth:`~simplekv.KeyValueStore.open`. If a cache miss occurs, the value is retrieved, stored in the cache, then then another open is issued on the cache. If the cache raises an :exc:`~exceptions.IOError`, the cache is ignored, and the b...
Implementation of :meth:`~simplekv.KeyValueStore.open`. If a cache miss occurs, the value is retrieved, stored in the cache, then then another open is issued on the cache. If the cache raises an :exc:`~exceptions.IOError`, the cache is ignored, and the backing store is consulted direct...
entailment
def copy(self, source, dest): """Implementation of :meth:`~simplekv.CopyMixin.copy`. Copies the data in the backing store and removes the destination key from the cache, in case it was already populated. Does not work when the backing store does not implement copy. ""...
Implementation of :meth:`~simplekv.CopyMixin.copy`. Copies the data in the backing store and removes the destination key from the cache, in case it was already populated. Does not work when the backing store does not implement copy.
entailment
def put(self, key, data): """Implementation of :meth:`~simplekv.KeyValueStore.put`. Will store the value in the backing store. After a successful or unsuccessful store, the cache will be invalidated by deleting the key from it. """ try: return self._dstore.pu...
Implementation of :meth:`~simplekv.KeyValueStore.put`. Will store the value in the backing store. After a successful or unsuccessful store, the cache will be invalidated by deleting the key from it.
entailment
def put_file(self, key, file): """Implementation of :meth:`~simplekv.KeyValueStore.put_file`. Will store the value in the backing store. After a successful or unsuccessful store, the cache will be invalidated by deleting the key from it. """ try: return self....
Implementation of :meth:`~simplekv.KeyValueStore.put_file`. Will store the value in the backing store. After a successful or unsuccessful store, the cache will be invalidated by deleting the key from it.
entailment
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...
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...
entailment
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...
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...
entailment
def _check_valid_key(self, key): """Checks if a key is valid and raises a ValueError if its not. When in need of checking a key for validity, always use this method if possible. :param key: The key to be checked """ if not isinstance(key, key_type): raise Va...
Checks if a key is valid and raises a ValueError if its not. When in need of checking a key for validity, always use this method if possible. :param key: The key to be checked
entailment
def _get(self, key): """Implementation for :meth:`~simplekv.KeyValueStore.get`. The default implementation will create a :class:`io.BytesIO`-buffer and then call :meth:`~simplekv.KeyValueStore._get_file`. :param key: Key of value to be retrieved """ buf = BytesIO() ...
Implementation for :meth:`~simplekv.KeyValueStore.get`. The default implementation will create a :class:`io.BytesIO`-buffer and then call :meth:`~simplekv.KeyValueStore._get_file`. :param key: Key of value to be retrieved
entailment
def _get_file(self, key, file): """Write key to file-like object file. Either this method or :meth:`~simplekv.KeyValueStore._get_filename` will be called by :meth:`~simplekv.KeyValueStore.get_file`. Note that this method does not accept strings. :param key: Key to be retrieved ...
Write key to file-like object file. Either this method or :meth:`~simplekv.KeyValueStore._get_filename` will be called by :meth:`~simplekv.KeyValueStore.get_file`. Note that this method does not accept strings. :param key: Key to be retrieved :param file: File-like object to wri...
entailment
def _get_filename(self, key, filename): """Write key to file. Either this method or :meth:`~simplekv.KeyValueStore._get_file` will be called by :meth:`~simplekv.KeyValueStore.get_file`. This method only accepts filenames and will open the file with a mode of ``wb``, then call :me...
Write key to file. Either this method or :meth:`~simplekv.KeyValueStore._get_file` will be called by :meth:`~simplekv.KeyValueStore.get_file`. This method only accepts filenames and will open the file with a mode of ``wb``, then call :meth:`~simplekv.KeyValueStore._get_file`. :p...
entailment
def put(self, key, data, ttl_secs=None): """Like :meth:`~simplekv.KeyValueStore.put`, but with an additional parameter: :param ttl_secs: Number of seconds until the key expires. See above for valid values. :raises exceptions.ValueError: If ``ttl_secs...
Like :meth:`~simplekv.KeyValueStore.put`, but with an additional parameter: :param ttl_secs: Number of seconds until the key expires. See above for valid values. :raises exceptions.ValueError: If ``ttl_secs`` is invalid. :raises exceptions.IOError...
entailment
def put_file(self, key, file, ttl_secs=None): """Like :meth:`~simplekv.KeyValueStore.put_file`, but with an additional parameter: :param ttl_secs: Number of seconds until the key expires. See above for valid values. :raises exceptions.ValueError: If ...
Like :meth:`~simplekv.KeyValueStore.put_file`, but with an additional parameter: :param ttl_secs: Number of seconds until the key expires. See above for valid values. :raises exceptions.ValueError: If ``ttl_secs`` is invalid.
entailment
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 ...
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 ...
entailment
def open(self): """Implementation of NAPALM method open.""" try: if self.transport in ('http', 'https'): connection = pyeapi.client.connect( transport=self.transport, host=self.hostname, username=self.username, ...
Implementation of NAPALM method open.
entailment
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')...
Implementation of NAPALM method compare_config.
entailment
def commit_config(self): """Implementation of NAPALM method commit_config.""" commands = [] commands.append('copy startup-config flash:rollback-0') commands.append('configure session {}'.format(self.config_session)) commands.append('commit') commands.append('write memory'...
Implementation of NAPALM method commit_config.
entailment
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...
Implementation of NAPALM method discard_config.
entailment
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)
Implementation of NAPALM method rollback.
entailment
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...
Implementation of NAPALM method get_facts.
entailment
def get_snmp_information(self): """get_snmp_information() for EOS. Re-written to not use TextFSM""" # Default values snmp_dict = { 'chassis_id': '', 'location': '', 'contact': '', 'community': {} } commands = [ 'show ...
get_snmp_information() for EOS. Re-written to not use TextFSM
entailment
def get_bgp_neighbors_detail(self, neighbor_address=''): """Implementation of get_bgp_neighbors_detail""" def _parse_per_peer_bgp_detail(peer_output): """This function parses the raw data per peer and returns a json structure per peer. """ int_fields = ['...
Implementation of get_bgp_neighbors_detail
entailment
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 ...
get_config implementation for EOS.
entailment
def get_network_instances(self, name=''): """get_network_instances implementation for EOS.""" output = self._show_vrf() vrfs = {} all_vrf_interfaces = {} for vrf in output: if (vrf.get('route_distinguisher', '') == "<not set>" or vrf.get('route_di...
get_network_instances implementation for EOS.
entailment
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...
Map boto-specific exceptions to the simplekv-API.
entailment
def _check_valid_key(self, key): """Checks if a key is valid and raises a ValueError if its not. When in need of checking a key for validity, always use this method if possible. :param key: The key to be checked """ if not isinstance(key, key_type) and key is not None: ...
Checks if a key is valid and raises a ValueError if its not. When in need of checking a key for validity, always use this method if possible. :param key: The key to be checked
entailment
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(...
Compute the md5 digest of a file in base64 encoding.
entailment
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()
Computes the md5 digest of a byte buffer in base64 encoding.
entailment
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...
Map Azure-specific exceptions to the simplekv-API.
entailment
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...
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.
entailment
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...
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 ...
entailment
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...
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 ...
entailment
def build_transgenic_lines(self): """ init class | "transgenic_line_source_name":"stock_number" a Class add superClass | rdfs:subClassOf ilxtr:transgenicLine add *order* | ilxtr:useObjectProperty ilxtr:<order> add name | rdfs:label "name" add def |...
init class | "transgenic_line_source_name":"stock_number" a Class add superClass | rdfs:subClassOf ilxtr:transgenicLine add *order* | ilxtr:useObjectProperty ilxtr:<order> add name | rdfs:label "name" add def | definition: "description" add transtype | ...
entailment
def datagetter(cls): """ example datagetter function, make any local modifications here """ with open('myfile', 'rt') as f: rows = [r for r in csv.reader(f)] dothing = lambda _: [i for i, v in enumerate(_)] rows = [dothing(_) for _ in rows] raise NotImplementedError('...
example datagetter function, make any local modifications here
entailment
def dataproc(cls, graph, data): """ example datagetter function, make any local modifications here """ for thing in data: graph.add_trip(*thing) raise NotImplementedError('You need to implement this yourlself!')
example datagetter function, make any local modifications here
entailment
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 ...
Connect to ec2 resource.
entailment
def _get_instance(self): """Retrieve instance matching instance_id.""" resource = self._connect() try: instance = resource.Instance(self.running_instance_id) except Exception: raise EC2CloudException( 'Instance with ID: {instance_id} not found.'.f...
Retrieve instance matching instance_id.
entailment
def _get_instance_state(self): """ Attempt to retrieve the state of the instance. Raises: EC2CloudException: If the instance cannot be found. """ instance = self._get_instance() state = None try: state = instance.state['Name'] exc...
Attempt to retrieve the state of the instance. Raises: EC2CloudException: If the instance cannot be found.
entailment
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() ...
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.
entailment
def _launch_instance(self): """Launch an instance of the given image.""" resource = self._connect() instance_name = ipa_utils.generate_instance_name('ec2-ipa-test') kwargs = { 'InstanceType': self.instance_type or EC2_DEFAULT_TYPE, 'ImageId': self.image_id, ...
Launch an instance of the given image.
entailment
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...
Retrieve instance ip and cache it. Current preference is for public ipv4, ipv6 and private.
entailment
def _start_instance(self): """Start the instance.""" instance = self._get_instance() instance.start() self._wait_on_instance('running', self.timeout)
Start the instance.
entailment
def _stop_instance(self): """Stop the instance.""" instance = self._get_instance() instance.stop() self._wait_on_instance('stopped', self.timeout)
Stop the instance.
entailment
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)
This worker is wrapped to block KeyboardInterrupt
entailment
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: ...
Determine the init system of distribution.
entailment
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, ...
Return vm info.
entailment
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...
Install package on instance.
entailment
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() ...
Execute reboot command on instance.
entailment