INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
find consensus base based on nucleotide frequencies
def find_consensus(bases): """ find consensus base based on nucleotide frequencies """ nucs = ['A', 'T', 'G', 'C', 'N'] total = sum([bases[nuc] for nuc in nucs if nuc in bases]) # save most common base as consensus (random nuc if there is a tie) try: top = max([bases[nuc] for nuc...
print bp frequencies to table genomes = {} # genomes [ genome ] [ contig ] [ sample ] = { bp_stats: {} }
def calc_frequencies(genomes, bp_table, min_cov, min_per): """ print bp frequencies to table genomes = {} # genomes[genome][contig][sample] = {'bp_stats':{}} """ nucs = ['A', 'T', 'G', 'C', 'N'] if bp_table is not False: bp_table = open(bp_table, 'w') header = ['#genome', 'contig...
print consensensus sequences for each genome and sample
def print_consensus(genomes): """ print consensensus sequences for each genome and sample """ # generate consensus sequences cons = {} # cons[genome][sample][contig] = consensus for genome, contigs in list(genomes.items()): cons[genome] = {} for contig, samples in list(contigs.it...
print substitution rate data to table genomes [ genome ] [ contig ] [ sample ] = \ { bp_stats: {} sub_rates [ locus ] = { ref PnPs consensus PnPs }}
def print_stats(genomes): """ print substitution rate data to table genomes[genome][contig][sample] = \ {'bp_stats':{}, 'sub_rates'[locus] = {ref PnPs, consensus PnPs}} """ header = ['#genome', 'contig', 'locus', 'position', 'strand', 'length', \ 'sample', 'coverage', \ ...
quantify genomic variation from mapping genomes [ genome ] [ contig ] [ sample ] = \ { bp_stats: [] sub_rates [ locus ] = { ref PnPs consensus PnPs... }}
def variation(fastas, sams, s2b, annots, qual, min_cov, min_per, no_sub, bp_table, print_con): """ quantify genomic variation from mapping genomes[genome][contig][sample] = \ {'bp_stats':[], 'sub_rates'[locus] = {ref PnPs, consensus PnPs, ...}} """ genomes = {} # save base-pair data...
custom = { ( reads mapped to scaffold )/ ( total reads for sample ) }/ ( length of scaffold )
def calc_custom(custom, genome, scaffold, sequence, scaffold_coverage, total_bases): """ custom = {(reads mapped to scaffold)/(total reads for sample)}/(length of scaffold) """ index = 0 if scaffold in scaffold_coverage: # what if the scaffold does not have bases mapped back to it? (this *should* not happen) if ...
absolute abundance = ( number of bases mapped to genome/ total number of bases in sample ) * 100
def absolute_abundance(coverage, total_bases): """ absolute abundance = (number of bases mapped to genome / total number of bases in sample) * 100 """ absolute = {} for genome in coverage: absolute[genome] = [] index = 0 for calc in coverage[genome]: bases = calc[0] total = total_bases[index] absolu...
cov = number of bases/ length of genome relative abundance = [ ( cov )/ sum ( cov for all genomes ) ] * 100
def relative_abundance(coverage): """ cov = number of bases / length of genome relative abundance = [(cov) / sum(cov for all genomes)] * 100 """ relative = {} sums = [] for genome in coverage: for cov in coverage[genome]: sums.append(0) break for genome in coverage: index = 0 for cov in coverage[geno...
coverage = ( number of bases/ length of genome ) * 100
def genome_coverage(genomes, scaffold_coverage, total_bases): """ coverage = (number of bases / length of genome) * 100 """ coverage = {} custom = {} std = {} for genome in genomes: for sequence in parse_fasta(genome): scaffold = sequence[0].split('>')[1].split()[0] coverage, std = sum_coverage(coverage,...
calculate genome coverage from scaffold coverage table
def parse_cov(cov_table, scaffold2genome): """ calculate genome coverage from scaffold coverage table """ size = {} # size[genome] = genome size mapped = {} # mapped[genome][sample] = mapped bases # parse coverage files for line in open(cov_table): line = line.strip().split('\t') ...
calculate genome coverage from scaffold coverage
def genome_coverage(covs, s2b): """ calculate genome coverage from scaffold coverage """ COV = [] for cov in covs: COV.append(parse_cov(cov, s2b)) return pd.concat(COV)
convert s2b files to dictionary
def parse_s2bs(s2bs): """ convert s2b files to dictionary """ s2b = {} for s in s2bs: for line in open(s): line = line.strip().split('\t') s, b = line[0], line[1] s2b[s] = b return s2b
convert fastas to s2b dictionary
def fa2s2b(fastas): """ convert fastas to s2b dictionary """ s2b = {} for fa in fastas: for seq in parse_fasta(fa): s = seq[0].split('>', 1)[1].split()[0] s2b[s] = fa.rsplit('/', 1)[-1].rsplit('.', 1)[0] return s2b
eth_addr
def eth_addr(f): """eth_addr :param f: eth frame """ data = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (f[0], f[1], f[2], f[3], ...
build_node
def parse_network_data(data_packet=None, include_filter_key=None, filter_keys=[], record_tcp=True, record_udp=True, record_arp=True, record_icmp=True): """build_node :param ...
Filters out sequences with too much ambiguity as defined by the method parameters.
def filter_ambiguity(records, percent=0.5): # , repeats=6) """ Filters out sequences with too much ambiguity as defined by the method parameters. :type records: list :param records: A list of sequences :type repeats: int :param repeats: Defines the number of repeated N that trigger truncat...
: param root: Tree node.: param line: String to parse.: param idx: Global counter of characters parsed.: return: ( list of parsed graphemes incremented character count )
def _parse(self, root, line, idx): """ :param root: Tree node. :param line: String to parse. :param idx: Global counter of characters parsed. :return: (list of parsed graphemes, incremented character count) """ # Base (or degenerate..) case. if len(line) =...
Search package.
def package_existent(name): """Search package. * :class:`bootstrap_py.exceptions.Conflict` exception occurs when user specified name has already existed. * :class:`bootstrap_py.exceptions.BackendFailure` exception occurs when PyPI service is down. :param str name: package name """ ...
Given a BIOM table calculate per - sample relative abundance for each OTU and write out to a tab - separated file listing OTUs as rows and Samples as columns.: type biom: biom object: param biom: BIOM - formatted OTU/ Sample abundance data: type out_fn: str: param out_fn: The full path to the desired output file.: type...
def write_relative_abundance(rel_abd, biomf, out_fn, sort_by=None): """ Given a BIOM table, calculate per-sample relative abundance for each OTU and write out to a tab-separated file listing OTUs as rows and Samples as columns. :type biom: biom object :param biom: BIOM-formatted OTU/Sample abund...
add index to id to make it unique wrt ids
def append_index_id(id, ids): """ add index to id to make it unique wrt ids """ index = 1 mod = '%s_%s' % (id, index) while mod in ids: index += 1 mod = '%s_%s' % (id, index) ids.append(mod) return mod, ids
de - replicate fastas based on sequence names
def de_rep(fastas, append_index, return_original = False): """ de-replicate fastas based on sequence names """ ids = [] for fasta in fastas: for seq in parse_fasta(fasta): header = seq[0].split('>')[1].split() id = header[0] if id not in ids: ...
Request data associated with postcode.
def get(postcode): """ Request data associated with `postcode`. :param postcode: the postcode to search for. The postcode may contain spaces (they will be removed). :returns: a dict of the nearest postcode's data or None if no postcode data is found. """ po...
Request all postcode data within distance miles of postcode.
def get_from_postcode(postcode, distance): """ Request all postcode data within `distance` miles of `postcode`. :param postcode: the postcode to search for. The postcode may contain spaces (they will be removed). :param distance: distance in miles to `postcode`. :returns: a ...
Checks if latitude and longitude correct
def _check_point(self, lat, lng): """ Checks if latitude and longitude correct """ if abs(lat) > 90 or abs(lng) > 180: msg = "Illegal lat and/or lng, (%s, %s) provided." % (lat, lng) raise IllegalPointException(msg)
Checks for cached responses before requesting from web - service
def _lookup(self, skip_cache, fun, *args, **kwargs): """ Checks for cached responses, before requesting from web-service """ if args not in self.cache or skip_cache: self.cache[args] = fun(*args, **kwargs) return self.cache[args]
Calls postcodes. get and by default utilises a local cache.: param skip_cache: optional argument specifying whether to skip the cache and make an explicit request. Given postcode data doesn t really change it s unlikely you will ever want to set this to True.
def get(self, postcode, skip_cache=False): """ Calls `postcodes.get` and by default utilises a local cache. :param skip_cache: optional argument specifying whether to skip the cache and make an explicit request. Given postcode data...
Calls postcodes. get_nearest but checks correctness of lat and long and by default utilises a local cache.
def get_nearest(self, lat, lng, skip_cache=False): """ Calls `postcodes.get_nearest` but checks correctness of `lat` and `long`, and by default utilises a local cache. :param skip_cache: optional argument specifying whether to skip the cache and make an exp...
Calls postcodes. get_from_postcode but checks correctness of distance and by default utilises a local cache.
def get_from_postcode(self, postcode, distance, skip_cache=False): """ Calls `postcodes.get_from_postcode` but checks correctness of `distance`, and by default utilises a local cache. :param skip_cache: optional argument specifying whether to skip the cache ...
Calls postcodes. get_from_geo but checks the correctness of all arguments and by default utilises a local cache.
def get_from_geo(self, lat, lng, distance, skip_cache=False): """ Calls `postcodes.get_from_geo` but checks the correctness of all arguments, and by default utilises a local cache. :param skip_cache: optional argument specifying whether to skip the cache and...
get coordinates of insertions from insertion - masked sequence
def insertions_from_masked(seq): """ get coordinates of insertions from insertion-masked sequence """ insertions = [] prev = True for i, base in enumerate(seq): if base.isupper() and prev is True: insertions.append([]) prev = False elif base.islower(): ...
analyze fa ( names insertions ) and convert fasta to prodigal/ cmscan safe file - find insertions ( masked sequence ) - make upper case - assign names to id number
def analyze_fa(fa): """ analyze fa (names, insertions) and convert fasta to prodigal/cmscan safe file - find insertions (masked sequence) - make upper case - assign names to id number """ if fa.name == '<stdin>': safe = 'temp.id' else: safe = '%s.id' % (fa.name) safe ...
get insertion information from header
def seq_info(names, id2names, insertions, sequences): """ get insertion information from header """ seqs = {} # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]] for name in names: id = id2names[name] gene = name.split('fromHMM::', 1)[0].rs...
make sure thresh % feature is contained within insertion
def check_overlap(pos, ins, thresh): """ make sure thresh % feature is contained within insertion """ ins_pos = ins[0] ins_len = ins[2] ol = overlap(ins_pos, pos) feat_len = pos[1] - pos[0] + 1 # print float(ol) / float(feat_len) if float(ol) / float(feat_len) >= thresh: retur...
find orfs and see if they overlap with insertions # seqs [ id ] = [ gene model [[ i - gene_pos i - model_pos i - length iseq [ orfs ] [ introns ]]... ]]
def find_orfs(fa, seqs): """ find orfs and see if they overlap with insertions # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]] """ faa = '%s.prodigal.faa' % (fa) fna = '%s.prodigal.fna' % (fa) gbk = '%s.prodigal.gbk' % (fa) if os.path.exist...
find introns by searching Rfam intron databse using cmscan # seqs [ id ] = [ gene model [[ i - gene_pos i - model_pos i - length iseq [ orfs ] [ introns ]]... ]]
def find_introns(fa, seqs, sequences, threads): """ find introns by searching Rfam intron databse using cmscan # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]] """ db = '%s/rfam/Rfam.cm.1_1.introns' % (os.environ['databases']) out = '%s.rfam-introns...
search orfs against pfam # seqs [ id ] = [ gene model [[ i - gene_pos i - model_pos i - length iseq [ orfs ] [ introns ] orfs? introns? { orf: annotations } ]... ]]
def annotate_orfs(fa, seqs, threads, threshold = 1e-6): """ search orfs against pfam # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?, {orf: annotations}], ...]] """ db = '%s/pfam/Pfam-A.hmm' % os.environ['databases'] base = fa.rsplit('.', ...
- find ORFs using Prodigal - find introns using cmscan ( vs Rfam intron database ) - check that ORFs and intron overlap with insertion region - plot insertion length versus model position for each insertion ( based on insertion type )
def analyze_insertions(fa, threads = 6): """ - find ORFs using Prodigal - find introns using cmscan (vs Rfam intron database) - check that ORFs and intron overlap with insertion region - plot insertion length versus model position for each insertion (based on insertion type) """ safe, sequen...
convert orf and intron information to boolean # seqs [ id ] = [ gene model [[ i - gene_pos i - model_pos i - length iseq [ orfs ] [ introns ]]... ]] # seqs [ id ] = [ gene model [[ i - gene_pos i - model_pos i - length iseq [ orfs ] [ introns ] orfs? introns? ]... ]]
def seqs2bool(seqs): """ convert orf and intron information to boolean # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns]], ...]] # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?], ...]] """ for seq in s...
print table of results # seqs [ id ] = [ gene model [[ i - gene_pos i - model_pos i - length iseq [ orfs ] [ introns ] orfs? introns? ]... ]]
def print_table(seqs, id2name, name): """ print table of results # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?], ...]] """ itable = open('%s.itable' % (name.rsplit('.', 1)[0]), 'w') print('\t'.join(['#sequence', 'gene', 'model', 'inserti...
print fasta of introns and ORFs # seqs [ id ] = [ gene model [[ i - gene_pos i - model_pos i - length iseq [ orfs ] [ introns ] orfs? introns? [ orf annotations ]]... ]]
def print_seqs(seqs, id2name, name): """ print fasta of introns and ORFs # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?, [orf annotations]], ...]] """ orfs = open('%s.orfs.faa' % (name.rsplit('.', 1)[0]), 'w') introns = open('%s.introns.f...
length of largest insertion
def max_insertion(seqs, gene, domain): """ length of largest insertion """ seqs = [i[2] for i in list(seqs.values()) if i[2] != [] and i[0] == gene and i[1] == domain] lengths = [] for seq in seqs: for ins in seq: lengths.append(int(ins[2])) if lengths == []: retu...
get length of model
def model_length(gene, domain): """ get length of model """ if gene == '16S': domain2max = {'E_coli_K12': int(1538), 'bacteria': int(1689), 'archaea': int(1563), 'eukarya': int(2652)} return domain2max[domain] elif gene == '23S': domain2max = {'E_coli_K12': int(2903), 'bacter...
setup unique marker for every orf annotation - change size if necessary
def setup_markers(seqs): """ setup unique marker for every orf annotation - change size if necessary """ family2marker = {} # family2marker[family] = [marker, size] markers = cycle(['^', 'p', '*', '+', 'x', 'd', '|', 'v', '>', '<', '8']) size = 60 families = [] for seq in list(seqs.v...
plot insertions wrt model positions 2 panels: 1. insertions with ORF - triangle if has intron - circle if no intron 2. insertion does not have ORF - triangle if has intron - circle if no intron * 3. conservation of sequence in model * 4. e. coli positions # seqs [ id ] = [ gene model [[ i - gene_pos i - model_pos i - l...
def plot_insertions(fname, seqs, gene, domain, tax, id2name): """ plot insertions wrt model positions 2 panels: 1. insertions with ORF - triangle if has intron - circle if no intron 2. insertion does not have ORF - triangle if has intron - circ...
plot insertions for each gene and domain
def plot_by_gene_and_domain(name, seqs, tax, id2name): """ plot insertions for each gene and domain """ for gene in set([seq[0] for seq in list(seqs.values())]): for domain in set([seq[1] for seq in list(seqs.values())]): plot_insertions(name, seqs, gene, domain, tax, id2name)
normalize the bit score: normalization factor = average max bit score for the two ORFs normalized = bit score/ normalization factor
def normalize_bit(A, B, bit, id2desc): """ normalize the bit score: normalization factor = average max bit score for the two ORFs normalized = bit score / normalization factor """ Amax, Bmax = id2desc[A][-1], id2desc[B][-1] norm_factor = float(numpy.average([Amax, Bmax])) normalized = bi...
get the description for each ORF
def get_descriptions(fastas): """ get the description for each ORF """ id2desc = {} for fasta in fastas: for seq in parse_fasta(fasta): header = seq[0].split('>')[1].split(' ') id = header[0] if len(header) > 1: desc = ' '.join(header[1:])...
optimize later? slow... should combine with calculate_threshold module
def print_genome_matrix(hits, fastas, id2desc, file_name): """ optimize later? slow ... should combine with calculate_threshold module """ out = open(file_name, 'w') fastas = sorted(fastas) print('## percent identity between genomes', file=out) print('# - \t %s' % ('\t'.join(fastas)), fi...
compare genome to self to get the best possible bit score for each ORF
def self_compare(fastas, id2desc, algorithm): """ compare genome to self to get the best possible bit score for each ORF """ for fasta in fastas: blast = open(search(fasta, fasta, method = algorithm, alignment = 'local')) for hit in best_blast(blast, 1): id, bit = hit[0].spli...
make all pairwise genome comparisons to get rbhs rbh = { genome: { other_genome: { rbh_id: [ rbh_match pident e bit norm_bit ]] }}
def compare_genomes(fastas, id2desc, algorithm): """ make all pairwise genome comparisons to get rbhs rbh = {genome: {other_genome: {rbh_id: [rbh_match, pident, e, bit, norm_bit]]}} """ hits = {} for pair in itertools.permutations(fastas, 2): if pair[0] not in hits: hits[pair...
if thresholds are not specififed calculate based on the distribution of normalized bit scores
def calc_thresholds(rbh, file_name, thresholds = [False, False, False, False], stdevs = 2): """ if thresholds are not specififed, calculate based on the distribution of normalized bit scores """ calc_threshold = thresholds[-1] norm_threshold = {} for pair in itertools.permutations([i for i in rb...
make the network based on rbhs and score thresholds
def rbh_network(id2desc, rbh, file_name, thresholds = [False, False, False, False]): """ make the network based on rbhs and score thresholds """ g = nx.Graph() # network graph for storing rbhs filtered = {} e_thresh, bit_thresh, length_thresh, norm_thresh = thresholds for genome in rbh: ...
make and split a rbh network
def neto(fastas, algorithm = 'usearch', e = 0.01, bit = 40, length = .65, norm_bit = False): """ make and split a rbh network """ thresholds = [e, bit, length, norm_bit] id2desc = get_descriptions(fastas) # get [fasta, description, length] for ORF id id2desc = self_compare(fastas, id...
make a rbh network for all pair - wise genome comparisons - filter network based on normalized bit score ( default automatic ) or specified e - value/ bit score - evaluate the scores for each genome pair compared - build second network that is filtered so that clusters have only one ORF per genome - evaluate the scores...
def network(thresholds, fastas, algorithm = 'usearch'): """ make a rbh network for all pair-wise genome comparisons - filter network based on normalized bit score (default, automatic) or specified e-value / bit score - evaluate the scores for each genome pair compared - build second network that is ...
Returns the subdirectory in userdata which acts as the root of the user - specific filesystem in Steam ( aka all user - specific files are stored under this directory )
def user_specific_data_directory(user_context): """Returns the subdirectory in `userdata` which acts as the root of the user-specific filesystem in Steam (aka all user-specific files are stored under this directory)""" return os.path.join( user_context.steam.userdata_directory, user_context.user_id )
OVERRIDDEN: Initialize required ISO - 19115 data map with XPATHS and specialized functions
def _init_data_map(self): """ OVERRIDDEN: Initialize required ISO-19115 data map with XPATHS and specialized functions """ if self._data_map is not None: return # Initiation happens once # Parse and validate the ISO metadata root if self._xml_tree is None: iso...
Concatenates a list of Attribute Details data structures parsed from a remote file
def _parse_attribute_details(self, prop=ATTRIBUTES): """ Concatenates a list of Attribute Details data structures parsed from a remote file """ parsed_attributes = self._parse_attribute_details_file(prop) if parsed_attributes is None: # If not in the (official) remote location, try ...
Concatenates a list of Attribute Details data structures parsed from a remote file
def _parse_attribute_details_file(self, prop=ATTRIBUTES): """ Concatenates a list of Attribute Details data structures parsed from a remote file """ # Parse content from remote file URL, which may be stored in one of two places: # Starting at: contentInfo/MD_FeatureCatalogueDescription/featu...
Concatenates a list of Digital Form data structures parsed from the metadata
def _parse_digital_forms(self, prop=DIGITAL_FORMS): """ Concatenates a list of Digital Form data structures parsed from the metadata """ xpath_map = self._data_structures[prop] # Parse base digital form fields: 'name', 'content', 'decompression', 'version', 'specification' xpath_root =...
Parse type - specific keywords from the metadata: Theme or Place
def _parse_keywords(self, prop): """ Parse type-specific keywords from the metadata: Theme or Place """ keywords = [] if prop in KEYWORD_PROPS: xpath_root = self._data_map['_keywords_root'] xpath_map = self._data_structures[prop] xtype = xpath_map['keyword_...
Collapses multiple dimensions into a single raster_info complex struct
def _parse_raster_info(self, prop=RASTER_INFO): """ Collapses multiple dimensions into a single raster_info complex struct """ raster_info = {}.fromkeys(_iso_definitions[prop], u'') # Ensure conversion of lists to newlines is in place raster_info['dimensions'] = get_default_for_complex...
Update operation for ISO Attribute Details metadata: write to MD_Metadata/ featureType
def _update_attribute_details(self, **update_props): """ Update operation for ISO Attribute Details metadata: write to "MD_Metadata/featureType" """ tree_to_update = update_props['tree_to_update'] xpath = self._data_map['_attr_citation'] # Cannot write to remote file: remove the featur...
Update operation for ISO Digital Forms metadata: see: gis_metadata. utils. _complex_definitions [ DIGITAL_FORMS ]
def _update_digital_forms(self, **update_props): """ Update operation for ISO Digital Forms metadata :see: gis_metadata.utils._complex_definitions[DIGITAL_FORMS] """ digital_forms = wrap_value(update_props['values']) # Update all Digital Form properties: distributionFor...
Update operation for ISO type - specific Keywords metadata: Theme or Place
def _update_keywords(self, **update_props): """ Update operation for ISO type-specific Keywords metadata: Theme or Place """ tree_to_update = update_props['tree_to_update'] prop = update_props['prop'] values = update_props['values'] keywords = [] if prop in KEYWORD_PRO...
Derives multiple dimensions from a single raster_info complex struct
def _update_raster_info(self, **update_props): """ Derives multiple dimensions from a single raster_info complex struct """ tree_to_update = update_props['tree_to_update'] prop = update_props['prop'] values = update_props.pop('values') # Update number of dimensions at raster_in...
OVERRIDDEN: Prevents writing multiple CharacterStrings per XPATH property
def update(self, use_template=False, **metadata_defaults): """ OVERRIDDEN: Prevents writing multiple CharacterStrings per XPATH property """ self.validate() tree_to_update = self._xml_tree if not use_template else self._get_template(**metadata_defaults) supported_props = self._metadata...
Removes primitive type tags from an XPATH
def _trim_xpath(self, xpath, prop): """ Removes primitive type tags from an XPATH """ xroot = self._get_xroot_for(prop) if xroot is None and isinstance(xpath, string_types): xtags = xpath.split(XPATH_DELIM) if xtags[-1] in _iso_tag_primitives: xroot = X...
Generates the app id for a given shortcut. Steam uses app ids as a unique identifier for games but since shortcuts dont have a canonical serverside representation they need to be generated on the fly. The important part about this function is that it will generate the same app id as Steam does for a given shortcut
def shortcut_app_id(shortcut): """ Generates the app id for a given shortcut. Steam uses app ids as a unique identifier for games, but since shortcuts dont have a canonical serverside representation they need to be generated on the fly. The important part about this function is that it will generate the same ...
Execute git config.
def _config(self): """Execute git config.""" cfg_wr = self.repo.config_writer() cfg_wr.add_section('user') cfg_wr.set_value('user', 'name', self.metadata.author) cfg_wr.set_value('user', 'email', self.metadata.email) cfg_wr.release()
Execute git remote add.
def _remote_add(self): """Execute git remote add.""" self.repo.create_remote( 'origin', 'git@github.com:{username}/{repo}.git'.format( username=self.metadata.username, repo=self.metadata.name))
Starts execution of the script
def start(self): ''' Starts execution of the script ''' # invoke the appropriate sub-command as requested from command-line try: self.args.func() except SystemExit as e: if e.code != 0: raise except KeyboardInterrupt: ...
Define basic command - line arguments required by the script.
def define_baseargs(self, parser): ''' Define basic command-line arguments required by the script. @parser is a parser object created using the `argparse` module. returns: None ''' parser.add_argument('--name', default=sys.argv[0], help='Name to identify this ...
Basically turns payload that looks like \\ n to. In the calling function if this function returns no object is added for that payload.
def cleanup_payload(self, payload): """ Basically, turns payload that looks like ' \\n ' to ''. In the calling function, if this function returns '' no object is added for that payload. """ p = payload.replace('\n', '') p = p.rstrip() p = p.lstrip() ...
: return: a copy of xpath_map but with XPATHs formatted with ordered or keyword values
def format_xpaths(xpath_map, *args, **kwargs): """ :return: a copy of xpath_map, but with XPATHs formatted with ordered or keyword values """ formatted = {}.fromkeys(xpath_map) for key, xpath in iteritems(xpath_map): formatted[key] = xpath.format(*args, **kwargs) return formatted
: return: the base of an XPATH: the part preceding any format keys or attribute references
def get_xpath_root(xpath): """ :return: the base of an XPATH: the part preceding any format keys or attribute references """ if xpath: if xpath.startswith('@'): xpath = '' else: index = xpath.find('/@' if '@' in xpath else '/{') xpath = xpath[:index] if index...
: return: the relative part of an XPATH: that which extends past the root provided
def get_xpath_branch(xroot, xpath): """ :return: the relative part of an XPATH: that which extends past the root provided """ if xroot and xpath and xpath.startswith(xroot): xpath = xpath[len(xroot):] xpath = xpath.lstrip(XPATH_DELIM) return xpath
: return: a tuple with the base of an XPATH followed by any format key or attribute reference
def get_xpath_tuple(xpath): """ :return: a tuple with the base of an XPATH followed by any format key or attribute reference """ xroot = get_xpath_root(xpath) xattr = None if xroot != xpath: xattr = get_xpath_branch(xroot, xpath).strip('@') return (xroot, xattr)
Ensures complex property types have the correct default values
def get_default_for(prop, value): """ Ensures complex property types have the correct default values """ prop = prop.strip('_') # Handle alternate props (leading underscores) val = reduce_value(value) # Filtering of value happens here if prop in _COMPLEX_LISTS: return wrap_value(val) ...
Parse xpath for any attribute reference path/
def has_property(elem_to_parse, xpath): """ Parse xpath for any attribute reference "path/@attr" and check for root and presence of attribute. :return: True if xpath is present in the element along with any attribute referenced, otherwise False """ xroot, attr = get_xpath_tuple(xpath) if not x...
Creates and returns a Dictionary data structure parsed from the metadata.: param tree_to_parse: the XML tree compatible with element_utils to be parsed: param xpath_root: the XPATH location of the structure inside the parent element: param xpath_map: a dict of XPATHs corresponding to a complex definition: param complex...
def parse_complex(tree_to_parse, xpath_root, xpath_map, complex_key): """ Creates and returns a Dictionary data structure parsed from the metadata. :param tree_to_parse: the XML tree compatible with element_utils to be parsed :param xpath_root: the XPATH location of the structure inside the parent eleme...
Creates and returns a list of Dictionary data structures parsed from the metadata.: param tree_to_parse: the XML tree compatible with element_utils to be parsed: param xpath_root: the XPATH location of each structure inside the parent element: param xpath_map: a dict of XPATHs corresponding to a complex definition: par...
def parse_complex_list(tree_to_parse, xpath_root, xpath_map, complex_key): """ Creates and returns a list of Dictionary data structures parsed from the metadata. :param tree_to_parse: the XML tree compatible with element_utils to be parsed :param xpath_root: the XPATH location of each structure inside t...
Creates and returns a Dates Dictionary data structure given the parameters provided: param tree_to_parse: the XML tree from which to construct the Dates data structure: param xpath_map: a map containing the following type - specific XPATHs: multiple range range_begin range_end and single
def parse_dates(tree_to_parse, xpath_map): """ Creates and returns a Dates Dictionary data structure given the parameters provided :param tree_to_parse: the XML tree from which to construct the Dates data structure :param xpath_map: a map containing the following type-specific XPATHs: multiple, ...
Defines the default parsing behavior for metadata values.: param tree_to_parse: the XML tree compatible with element_utils to be parsed: param xpath_root: used to determine the relative XPATH location within the parent element: param xpath_map: a dict of XPATHs that may contain alternate locations for a property: param...
def parse_property(tree_to_parse, xpath_root, xpath_map, prop): """ Defines the default parsing behavior for metadata values. :param tree_to_parse: the XML tree compatible with element_utils to be parsed :param xpath_root: used to determine the relative XPATH location within the parent element :para...
Either update the tree the default way or call the custom updater
def update_property(tree_to_update, xpath_root, xpaths, prop, values, supported=None): """ Either update the tree the default way, or call the custom updater Default Way: Existing values in the tree are overwritten. If xpaths contains a single path, then each value is written to the tree at that path. ...
Default update operation for a single parser property. If xpaths contains one xpath then one element per value will be inserted at that location in the tree_to_update ; otherwise the number of values must match the number of xpaths.
def _update_property(tree_to_update, xpath_root, xpaths, values): """ Default update operation for a single parser property. If xpaths contains one xpath, then one element per value will be inserted at that location in the tree_to_update; otherwise, the number of values must match the number of xpaths. ...
Updates and returns the updated complex Element parsed from tree_to_update.: param tree_to_update: the XML tree compatible with element_utils to be updated: param xpath_root: the XPATH location of the root of the complex Element: param xpath_map: a Dictionary of XPATHs corresponding to the complex structure definition:...
def update_complex(tree_to_update, xpath_root, xpath_map, prop, values): """ Updates and returns the updated complex Element parsed from tree_to_update. :param tree_to_update: the XML tree compatible with element_utils to be updated :param xpath_root: the XPATH location of the root of the complex Elemen...
Updates and returns the list of updated complex Elements parsed from tree_to_update.: param tree_to_update: the XML tree compatible with element_utils to be updated: param xpath_root: the XPATH location of each complex Element: param xpath_map: a Dictionary of XPATHs corresponding to the complex structure definition: p...
def update_complex_list(tree_to_update, xpath_root, xpath_map, prop, values): """ Updates and returns the list of updated complex Elements parsed from tree_to_update. :param tree_to_update: the XML tree compatible with element_utils to be updated :param xpath_root: the XPATH location of each complex Ele...
Validates any metadata property complex or simple ( string or array )
def validate_any(prop, value, xpath_map=None): """ Validates any metadata property, complex or simple (string or array) """ if value is not None: if prop in (ATTRIBUTES, CONTACTS, DIGITAL_FORMS): validate_complex_list(prop, value, xpath_map) elif prop in (BOUNDING_BOX, LARGER_WORKS...
Default validation for single complex data structure
def validate_complex(prop, value, xpath_map=None): """ Default validation for single complex data structure """ if value is not None: validate_type(prop, value, dict) if prop in _complex_definitions: complex_keys = _complex_definitions[prop] else: complex_keys =...
Default validation for Attribute Details data structure
def validate_complex_list(prop, value, xpath_map=None): """ Default validation for Attribute Details data structure """ if value is not None: validate_type(prop, value, (dict, list)) if prop in _complex_definitions: complex_keys = _complex_definitions[prop] else: ...
Default validation for Date Types data structure
def validate_dates(prop, value, xpath_map=None): """ Default validation for Date Types data structure """ if value is not None: validate_type(prop, value, dict) date_keys = set(value) if date_keys: if DATE_TYPE not in date_keys or DATE_VALUES not in date_keys: ...
Default validation for Process Steps data structure
def validate_process_steps(prop, value): """ Default validation for Process Steps data structure """ if value is not None: validate_type(prop, value, (dict, list)) procstep_keys = set(_complex_definitions[prop]) for idx, procstep in enumerate(wrap_value(value)): ps_idx = p...
Ensures the key set contains the base supported properties for a Parser: param props: a set of property names to validate against those supported
def validate_properties(props, required): """ Ensures the key set contains the base supported properties for a Parser :param props: a set of property names to validate against those supported """ props = set(props) required = set(required or _supported_props) if len(required.intersection(p...
Default validation for all types
def validate_type(prop, value, expected): """ Default validation for all types """ # Validate on expected type(s), but ignore None: defaults handled elsewhere if value is not None and not isinstance(value, expected): _validation_error(prop, type(value).__name__, None, expected)
Default validation for updated properties
def _validation_error(prop, prop_type, prop_value, expected): """ Default validation for updated properties """ if prop_type is None: attrib = 'value' assigned = prop_value else: attrib = 'type' assigned = prop_type raise ValidationError( 'Invalid property {attr...
Calls the getter with no arguments and returns its value
def get_prop(self, prop): """ Calls the getter with no arguments and returns its value """ if self._parser is None: raise ConfigurationError('Cannot call ParserProperty."get_prop" with no parser configured') return self._parser(prop) if prop else self._parser()
Calls the setter with the specified keyword arguments for flexibility.: param setter_args: must contain tree_to_update prop values: return: None or the value updated for complex values
def set_prop(self, **setter_args): """ Calls the setter with the specified keyword arguments for flexibility. :param setter_args: must contain tree_to_update, prop, values :return: None, or the value updated for complex values """ if self.xpath: setter_args['...
Given a list of commands ( which are assumed groupable ) return a new command which is a batch ( multi ) command.
def grouped_command(commands): """ Given a list of commands (which are assumed groupable), return a new command which is a batch (multi) command. For ``set`` commands the outcome will be:: set_multi({key: value}, **kwargs) For ``get`` and ``delete`` commands, the outcome will be:: ...
Returns a boolean representing whether these commands can be grouped together or not.
def can_group_commands(command, next_command): """ Returns a boolean representing whether these commands can be grouped together or not. A few things are taken into account for this decision: For ``set`` commands: - Are all arguments other than the key/value the same? For ``delete`` and ...
Returns a list of tuples:
def regroup_commands(commands): """ Returns a list of tuples: [(command_to_run, [list, of, commands])] If the list of commands has a single item, the command was not grouped. """ grouped = [] pending = [] def group_pending(): if not pending: return new...