INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Format instruction details for inclusion in disassembly output | def _disassemble(self, lineno_width=3, mark_as_current=False):
"""Format instruction details for inclusion in disassembly output
*lineno_width* sets the width of the line number field (0 omits it)
*mark_as_current* inserts a '-->' marker arrow as part of the line
"""
fields = []... |
Returns intersection of two lists. Assumes the lists are sorted by start positions | def intersection(l1, l2):
'''Returns intersection of two lists. Assumes the lists are sorted by start positions'''
if len(l1) == 0 or len(l2) == 0:
return []
out = []
l2_pos = 0
for l in l1:
while l2_pos < len(l2) and l2[l2_pos].end < l.start:
l2_pos += 1
if l... |
Sorts list merges any overlapping intervals and also adjacent intervals. e. g. [ 0 1 ] [ 1 2 ] would be merge to [ 0. 2 ]. | def merge_overlapping_in_list(l):
'''Sorts list, merges any overlapping intervals, and also adjacent intervals. e.g.
[0,1], [1,2] would be merge to [0,.2].'''
i = 0
l.sort()
while i < len(l) - 1:
u = l[i].union(l[i+1])
if u is not None:
l[i] = u
l.pop(i+1)... |
Sorts list in place then removes any intervals that are completely contained inside another interval | def remove_contained_in_list(l):
'''Sorts list in place, then removes any intervals that are completely
contained inside another interval'''
i = 0
l.sort()
while i < len(l) - 1:
if l[i+1].contains(l[i]):
l.pop(i)
elif l[i].contains(l[i+1]):
l.pop(i+1)
e... |
Returns the distance from the point to the interval. Zero if the point lies inside the interval. | def distance_to_point(self, p):
'''Returns the distance from the point to the interval. Zero if the point lies inside the interval.'''
if self.start <= p <= self.end:
return 0
else:
return min(abs(self.start - p), abs(self.end - p)) |
Returns true iff this interval intersects the interval i | def intersects(self, i):
'''Returns true iff this interval intersects the interval i'''
return self.start <= i.end and i.start <= self.end |
Returns true iff this interval contains the interval i | def contains(self, i):
'''Returns true iff this interval contains the interval i'''
return self.start <= i.start and i.end <= self.end |
If intervals intersect returns their union otherwise returns None | def union(self, i):
'''If intervals intersect, returns their union, otherwise returns None'''
if self.intersects(i) or self.end + 1 == i.start or i.end + 1 == self.start:
return Interval(min(self.start, i.start), max(self.end, i.end))
else:
return None |
Like union but ignores whether the two intervals intersect or not | def union_fill_gap(self, i):
'''Like union, but ignores whether the two intervals intersect or not'''
return Interval(min(self.start, i.start), max(self.end, i.end)) |
If intervals intersect returns their intersection otherwise returns None | def intersection(self, i):
'''If intervals intersect, returns their intersection, otherwise returns None'''
if self.intersects(i):
return Interval(max(self.start, i.start), min(self.end, i.end))
else:
return None |
Iterates over a FASTA or FASTQ file yielding the next sequence in the file until there are no more sequences | def file_reader(fname, read_quals=False):
'''Iterates over a FASTA or FASTQ file, yielding the next sequence in the file until there are no more sequences'''
f = utils.open_file_read(fname)
line = f.readline()
phylip_regex = re.compile('^\s*[0-9]+\s+[0-9]+$')
gbk_regex = re.compile('^LOCUS\s+\S')
... |
Returns Fasta object with the same name of the bases from start to end but not including end | def subseq(self, start, end):
'''Returns Fasta object with the same name, of the bases from start to end, but not including end'''
return Fasta(self.id, self.seq[start:end]) |
Gets the prefix and suffix of an name of a capillary read e. g. xxxxx. p1k or xxxx. q1k. Returns a tuple ( prefix suffx ) | def split_capillary_id(self):
'''Gets the prefix and suffix of an name of a capillary read, e.g. xxxxx.p1k or xxxx.q1k. Returns a tuple (prefix, suffx)'''
try:
a = self.id.rsplit('.', 1)
if a[1].startswith('p'):
dir = 'fwd'
elif a[1].startswith('q'):
... |
Assumes sequence is nucleotides. Returns list of all combinations of redundant nucleotides. e. g. R is A or G so CRT would have combinations CAT and CGT | def expand_nucleotides(self):
'''Assumes sequence is nucleotides. Returns list of all combinations of redundant nucleotides. e.g. R is A or G, so CRT would have combinations CAT and CGT'''
s = list(self.seq)
for i in range(len(s)):
if s[i] in redundant_nts:
s[i] = ''.... |
Removes any trailing/ 1 or/ 2 off the end of the name | def strip_illumina_suffix(self):
'''Removes any trailing /1 or /2 off the end of the name'''
if self.id.endswith('/1') or self.id.endswith('/2'):
self.id = self.id[:-2] |
Returns true if the sequence is all Ns ( upper or lower case ) | def is_all_Ns(self, start=0, end=None):
'''Returns true if the sequence is all Ns (upper or lower case)'''
if end is not None:
if start > end:
raise Error('Error in is_all_Ns. Start coord must be <= end coord')
end += 1
else:
end = len(self)
... |
Adds a random base within window bases around every skip bases. e. g. skip = 10 window = 1 means a random base added somwhere in theintervals [ 9 11 ] [ 19 21 ]... | def add_insertions(self, skip=10, window=1, test=False):
'''Adds a random base within window bases around every skip bases. e.g. skip=10, window=1 means a random base added somwhere in theintervals [9,11], [19,21] ... '''
assert 2 * window < skip
new_seq = list(self.seq)
for i in range(l... |
Replaces all occurrences of old with new | def replace_bases(self, old, new):
'''Replaces all occurrences of 'old' with 'new' '''
self.seq = self.seq.replace(old, new) |
Replaces the sequence from start to end with the sequence new | def replace_interval(self, start, end, new):
'''Replaces the sequence from start to end with the sequence "new"'''
if start > end or start > len(self) - 1 or end > len(self) - 1:
raise Error('Error replacing bases ' + str(start) + '-' + str(end) + ' in sequence ' + self.id)
self.seq... |
Finds the positions of all gaps in the sequence that are at least min_length long. Returns a list of Intervals. Coords are zero - based | def gaps(self, min_length = 1):
'''Finds the positions of all gaps in the sequence that are at least min_length long. Returns a list of Intervals. Coords are zero-based'''
gaps = []
regex = re.compile('N+', re.IGNORECASE)
for m in regex.finditer(self.seq):
if m.span()[1] - m... |
Finds coords of contigs i. e. everything that s not a gap ( N or n ). Returns a list of Intervals. Coords are zero - based | def contig_coords(self):
'''Finds coords of contigs, i.e. everything that's not a gap (N or n). Returns a list of Intervals. Coords are zero-based'''
# contigs are the opposite of gaps, so work out the coords from the gap coords
gaps = self.gaps()
if len(gaps) == 0:
return [... |
Returns a list of ORFs that the sequence has starting on the given frame. Each returned ORF is an interval. Interval object. If revomp = True then finds the ORFs of the reverse complement of the sequence. | def orfs(self, frame=0, revcomp=False):
'''Returns a list of ORFs that the sequence has, starting on the given
frame. Each returned ORF is an interval.Interval object.
If revomp=True, then finds the ORFs of the reverse complement
of the sequence.'''
assert frame in [0,1,... |
Finds all open reading frames in the sequence that are at least as long as min_length. Includes ORFs on the reverse strand. Returns a list of ORFs where each element is a tuple: ( interval. Interval bool ) where bool = True means on the reverse strand | def all_orfs(self, min_length=300):
'''Finds all open reading frames in the sequence, that are at least as
long as min_length. Includes ORFs on the reverse strand.
Returns a list of ORFs, where each element is a tuple:
(interval.Interval, bool)
where bool=True means o... |
Returns true iff length is > = 6 is a multiple of 3 and there is exactly one stop codon in the sequence and it is at the end | def is_complete_orf(self):
'''Returns true iff length is >= 6, is a multiple of 3, and there is exactly one stop codon in the sequence and it is at the end'''
if len(self) %3 != 0 or len(self) < 6:
return False
orfs = self.orfs()
complete_orf = intervals.Interval(0, len(self... |
Returns true iff: length > = 6 length is a multiple of 3 first codon is start last codon is a stop and has no other stop codons | def looks_like_gene(self):
'''Returns true iff: length >=6, length is a multiple of 3, first codon is start, last codon is a stop and has no other stop codons'''
return self.is_complete_orf() \
and len(self) >= 6 \
and len(self) %3 == 0 \
and self.seq[0:3].upper() in geneti... |
Tries to make into a gene sequence. Tries all three reading frames and both strands. Returns a tuple ( new sequence strand frame ) if it was successful. Otherwise returns None. | def make_into_gene(self):
'''Tries to make into a gene sequence. Tries all three reading frames and both strands. Returns a tuple (new sequence, strand, frame) if it was successful. Otherwise returns None.'''
for reverse in [True, False]:
for frame in range(3):
new_seq = copy... |
Removes first start/ end bases off the start/ end of the sequence | def trim(self, start, end):
'''Removes first 'start'/'end' bases off the start/end of the sequence'''
self.seq = self.seq[start:len(self.seq) - end] |
Returns a Fastq object. qual_scores expected to be a list of numbers like you would get in a. qual file | def to_Fastq(self, qual_scores):
'''Returns a Fastq object. qual_scores expected to be a list of numbers, like you would get in a .qual file'''
if len(self) != len(qual_scores):
raise Error('Error making Fastq from Fasta, lengths differ.', self.id)
return Fastq(self.id, self.seq, ''.... |
Finds every occurrence ( including overlapping ones ) of the search_string including on the reverse strand. Returns a list where each element is a tuple ( position strand ) where strand is in [ - + ]. Positions are zero - based | def search(self, search_string):
'''Finds every occurrence (including overlapping ones) of the search_string, including on the reverse strand. Returns a list where each element is a tuple (position, strand) where strand is in ['-', '+']. Positions are zero-based'''
seq = self.seq.upper()
search_... |
Returns a Fasta sequence translated into amino acids. Starts translating from frame where frame expected to be 0 1 or 2 | def translate(self, frame=0):
'''Returns a Fasta sequence, translated into amino acids. Starts translating from 'frame', where frame expected to be 0,1 or 2'''
return Fasta(self.id, ''.join([genetic_codes.codes[genetic_code].get(self.seq[x:x+3].upper(), 'X') for x in range(frame, len(self)-1-frame, 3)])... |
Returns the GC content for the sequence. Notes: This method ignores N when calculating the length of the sequence. It does not however ignore other ambiguous bases. It also only includes the ambiguous base S ( G or C ). In this sense the method is conservative with its calculation. | def gc_content(self, as_decimal=True):
"""Returns the GC content for the sequence.
Notes:
This method ignores N when calculating the length of the sequence.
It does not, however ignore other ambiguous bases. It also only
includes the ambiguous base S (G or C). In this... |
Returns Fastq object with the same name of the bases from start to end but not including end | def subseq(self, start, end):
'''Returns Fastq object with the same name, of the bases from start to end, but not including end'''
return Fastq(self.id, self.seq[start:end], self.qual[start:end]) |
Removes first start/ end bases off the start/ end of the sequence | def trim(self, start, end):
'''Removes first 'start'/'end' bases off the start/end of the sequence'''
super().trim(start, end)
self.qual = self.qual[start:len(self.qual) - end] |
Removes any leading or trailing N or n characters from the sequence | def trim_Ns(self):
'''Removes any leading or trailing N or n characters from the sequence'''
# get index of first base that is not an N
i = 0
while i < len(self) and self.seq[i] in 'nN':
i += 1
# strip off start of sequence and quality
self.seq = self.seq[i:]... |
Replaces the sequence from start to end with the sequence new | def replace_interval(self, start, end, new, qual_string):
'''Replaces the sequence from start to end with the sequence "new"'''
if len(new) != len(qual_string):
raise Error('Length of new seq and qual string in replace_interval() must be equal. Cannot continue')
super().replace_inter... |
Returns a Fasta sequence translated into amino acids. Starts translating from frame where frame expected to be 0 1 or 2 | def translate(self):
'''Returns a Fasta sequence, translated into amino acids. Starts translating from 'frame', where frame expected to be 0,1 or 2'''
fa = super().translate()
return Fastq(fa.id, fa.seq, 'I'*len(fa.seq)) |
Replace every non - acgtn ( case insensitve ) character with an N | def acgtn_only(infile, outfile):
'''Replace every non-acgtn (case insensitve) character with an N'''
f = utils.open_file_write(outfile)
for seq in sequences.file_reader(infile):
seq.replace_non_acgt()
print(seq, file=f)
utils.close(f) |
Convert a CAF file to fastq. Reads shorter than min_length are not output. If clipping information is in the CAF file ( with a line Clipping QUAL... ) and trim = True then trim the reads | def caf_to_fastq(infile, outfile, min_length=0, trim=False):
'''Convert a CAF file to fastq. Reads shorter than min_length are not output. If clipping information is in the CAF file (with a line Clipping QUAL ...) and trim=True, then trim the reads'''
caf_reader = caf.file_reader(infile)
fout = utils.open_f... |
Returns the number of sequences in a file | def count_sequences(infile):
'''Returns the number of sequences in a file'''
seq_reader = sequences.file_reader(infile)
n = 0
for seq in seq_reader:
n += 1
return n |
Makes interleaved file from two sequence files. If used will append suffix1 onto end of every sequence name in infile_1 unless it already ends with suffix1. Similar for sufffix2. | def interleave(infile_1, infile_2, outfile, suffix1=None, suffix2=None):
'''Makes interleaved file from two sequence files. If used, will append suffix1 onto end
of every sequence name in infile_1, unless it already ends with suffix1. Similar for sufffix2.'''
seq_reader_1 = sequences.file_reader(infile_1)
... |
Makes a multi fasta file of random sequences all the same length | def make_random_contigs(contigs, length, outfile, name_by_letters=False, prefix='', seed=None, first_number=1):
'''Makes a multi fasta file of random sequences, all the same length'''
random.seed(a=seed)
fout = utils.open_file_write(outfile)
letters = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
letters_index... |
Returns the mean length of the sequences in the input file. By default uses all sequences. To limit to the first N sequences use limit = N | def mean_length(infile, limit=None):
'''Returns the mean length of the sequences in the input file. By default uses all sequences. To limit to the first N sequences, use limit=N'''
total = 0
count = 0
seq_reader = sequences.file_reader(infile)
for seq in seq_reader:
total += len(seq)
... |
Takes a multi fasta or fastq file and writes a new file that contains just one sequence with the original sequences catted together preserving their order | def merge_to_one_seq(infile, outfile, seqname='union'):
'''Takes a multi fasta or fastq file and writes a new file that contains just one sequence, with the original sequences catted together, preserving their order'''
seq_reader = sequences.file_reader(infile)
seqs = []
for seq in seq_reader:
... |
Makes a file of contigs from scaffolds by splitting at every N. Use number_contigs = True to add. 1. 2 etc onto end of each contig instead of default to append coordinates. | def scaffolds_to_contigs(infile, outfile, number_contigs=False):
'''Makes a file of contigs from scaffolds by splitting at every N.
Use number_contigs=True to add .1, .2, etc onto end of each
contig, instead of default to append coordinates.'''
seq_reader = sequences.file_reader(infile)
fout =... |
Sorts input sequence file by biggest sequence first writes sorted output file. Set smallest_first = True to have smallest first | def sort_by_size(infile, outfile, smallest_first=False):
'''Sorts input sequence file by biggest sequence first, writes sorted output file. Set smallest_first=True to have smallest first'''
seqs = {}
file_to_dict(infile, seqs)
seqs = list(seqs.values())
seqs.sort(key=lambda x: len(x), reverse=not sm... |
Sorts input sequence file by sort - d - k1 1 writes sorted output file. | def sort_by_name(infile, outfile):
'''Sorts input sequence file by sort -d -k1,1, writes sorted output file.'''
seqs = {}
file_to_dict(infile, seqs)
#seqs = list(seqs.values())
#seqs.sort()
fout = utils.open_file_write(outfile)
for name in sorted(seqs):
print(seqs[name], file=fout)
... |
Writes a FASTG file in SPAdes format from input file. Currently only whether or not a sequence is circular is supported. Put circular = set of ids or circular = filename to make those sequences circular in the output. Puts coverage = 1 on all contigs | def to_fastg(infile, outfile, circular=None):
'''Writes a FASTG file in SPAdes format from input file. Currently only whether or not a sequence is circular is supported. Put circular=set of ids, or circular=filename to make those sequences circular in the output. Puts coverage=1 on all contigs'''
if circular is... |
Returns a dictionary of positions of the start of each sequence as if all the sequences were catted into one sequence. eg if file has three sequences seq1 10bp seq2 30bp seq3 20bp then the output would be: { seq1: 0 seq2: 10 seq3: 40 } | def length_offsets_from_fai(fai_file):
'''Returns a dictionary of positions of the start of each sequence, as
if all the sequences were catted into one sequence.
eg if file has three sequences, seq1 10bp, seq2 30bp, seq3 20bp, then
the output would be: {'seq1': 0, 'seq2': 10, 'seq3': 40}'''
... |
Splits a fasta/ q file into separate files file size determined by number of bases. | def split_by_base_count(infile, outfiles_prefix, max_bases, max_seqs=None):
'''Splits a fasta/q file into separate files, file size determined by number of bases.
Puts <= max_bases in each split file The exception is a single sequence >=max_bases
is put in its own file. This does not split sequences.
... |
Splits fasta/ q file into separate files with up to ( chunk_size + tolerance ) bases in each file | def split_by_fixed_size(infile, outfiles_prefix, chunk_size, tolerance, skip_if_all_Ns=False):
'''Splits fasta/q file into separate files, with up to (chunk_size + tolerance) bases in each file'''
file_count = 1
coords = []
small_sequences = [] # sequences shorter than chunk_size
seq_reader = sequ... |
Splits each sequence in infile into chunks of fixed size last chunk can be up to ( chunk_size + tolerance ) in length | def split_by_fixed_size_onefile(infile, outfile, chunk_size, tolerance, skip_if_all_Ns=False):
'''Splits each sequence in infile into chunks of fixed size, last chunk can be up to
(chunk_size + tolerance) in length'''
seq_reader = sequences.file_reader(infile)
f_out = utils.open_file_write(outfile)
... |
Returns dictionary of length stats from an fai file. Keys are: longest shortest mean total_length N50 number | def stats_from_fai(infile):
'''Returns dictionary of length stats from an fai file. Keys are: longest, shortest, mean, total_length, N50, number'''
f = utils.open_file_read(infile)
try:
lengths = sorted([int(line.split('\t')[1]) for line in f], reverse=True)
except:
raise Error('Error ge... |
Converts input sequence file into a Boulder - IO format as used by primer3 | def to_boulderio(infile, outfile):
'''Converts input sequence file into a "Boulder-IO format", as used by primer3'''
seq_reader = sequences.file_reader(infile)
f_out = utils.open_file_write(outfile)
for sequence in seq_reader:
print("SEQUENCE_ID=" + sequence.id, file=f_out)
print("SEQUE... |
Returns the HMAC - HASH of value using a key generated from key_salt and a secret ( which defaults to settings. SECRET_KEY ). | def salted_hmac(key_salt, value, secret=None):
"""
Returns the HMAC-HASH of 'value', using a key generated from key_salt and a
secret (which defaults to settings.SECRET_KEY).
A different key_salt should be passed in for every application of HMAC.
:type key_salt: any
:type value: any
:type ... |
Implements PBKDF2 with the same API as Django s existing implementation using cryptography. | def pbkdf2(password, salt, iterations, dklen=0, digest=None):
"""
Implements PBKDF2 with the same API as Django's existing
implementation, using cryptography.
:type password: any
:type salt: any
:type iterations: int
:type dklen: int
:type digest: cryptography.hazmat.primitives.hashes.H... |
: type data: any: rtype: any | def encrypt(self, data):
"""
:type data: any
:rtype: any
"""
data = force_bytes(data)
iv = os.urandom(16)
return self._encrypt_from_parts(data, iv) |
: type data: bytes: type iv: bytes: rtype: any | def _encrypt_from_parts(self, data, iv):
"""
:type data: bytes
:type iv: bytes
:rtype: any
"""
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_data = padder.update(data) + padder.finalize()
encryptor = Cipher(
algorithms.AES(s... |
: type data: bytes: type ttl: int: rtype: bytes | def decrypt(self, data, ttl=None):
"""
:type data: bytes
:type ttl: int
:rtype: bytes
"""
data = self._signer.unsign(data, ttl)
iv = data[:16]
ciphertext = data[16:]
decryptor = Cipher(
algorithms.AES(self._encryption_key), modes.CBC(i... |
A get or create method for encrypted fields we cache the field in the module to avoid recreation. This also allows us to always return the same class reference for a field. | def get_encrypted_field(base_class):
"""
A get or create method for encrypted fields, we cache the field in
the module to avoid recreation. This also allows us to always return
the same class reference for a field.
:type base_class: models.Field[T]
:rtype: models.Field[EncryptedMixin, T]
""... |
A decorator for creating encrypted model fields. | def encrypt(base_field, key=None, ttl=None):
"""
A decorator for creating encrypted model fields.
:type base_field: models.Field[T]
:param bytes key: This is an optional argument.
Allows for specifying an instance specific encryption key.
:param int ttl: This is an optional argument.
... |
Pickled data is serialized as base64 | def value_to_string(self, obj):
"""Pickled data is serialized as base64"""
value = self.value_from_object(obj)
return b64encode(self._dump(value)).decode('ascii') |
Returns URL - safe sha1 signed base64 compressed JSON string. If key is None settings. SECRET_KEY is used instead. | def dumps(obj,
key=None,
salt='django.core.signing',
serializer=JSONSerializer,
compress=False):
"""
Returns URL-safe, sha1 signed base64 compressed JSON string. If key is
None, settings.SECRET_KEY is used instead.
If compress is True (not the default) checks if ... |
: type value: any: rtype: HMAC | def signature(self, value):
"""
:type value: any
:rtype: HMAC
"""
h = HMAC(self.key, self.digest, backend=settings.CRYPTOGRAPHY_BACKEND)
h.update(force_bytes(value))
return h |
: type value: any: rtype: bytes | def sign(self, value):
"""
:type value: any
:rtype: bytes
"""
payload = struct.pack('>cQ', self.version, int(time.time()))
payload += force_bytes(value)
return payload + self.signature(payload).finalize() |
Retrieve original value and check it wasn t signed more than max_age seconds ago. | def unsign(self, signed_value, ttl=None):
"""
Retrieve original value and check it wasn't signed more
than max_age seconds ago.
:type signed_value: bytes
:type ttl: int | datetime.timedelta
"""
h_size, d_size = struct.calcsize('>cQ'), self.digest.digest_size
... |
Returns a PEP 386 - compliant version number from VERSION. | def get_version(version=None):
"""
Returns a PEP 386-compliant version number from VERSION.
"""
version = get_complete_version(version)
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc rele... |
Returns a tuple of the django_cryptography version. If version argument is non - empty then checks for correctness of the tuple provided. | def get_complete_version(version=None):
"""
Returns a tuple of the django_cryptography version. If version
argument is non-empty, then checks for correctness of the tuple
provided.
"""
if version is None:
from django_cryptography import VERSION as version
else:
assert len(ver... |
Return a value check function which raises a value error if the value is not in a pre - defined enumeration of values. | def enumeration(*args):
"""
Return a value check function which raises a value error if the value is not
in a pre-defined enumeration of values.
If you pass in a list, tuple or set as the single argument, it is assumed
that the list/tuple/set defines the membership of the enumeration.
If you p... |
Return a value check function which raises a ValueError if the value does not match the supplied regular expression see also re. match. | def match_pattern(regex):
"""
Return a value check function which raises a ValueError if the value does
not match the supplied regular expression, see also `re.match`.
"""
prog = re.compile(regex)
def checker(v):
result = prog.match(v)
if result is None:
raise Value... |
Return a value check function which raises a ValueError if the supplied regular expression does not match anywhere in the value see also re. search. | def search_pattern(regex):
"""
Return a value check function which raises a ValueError if the supplied
regular expression does not match anywhere in the value, see also
`re.search`.
"""
prog = re.compile(regex)
def checker(v):
result = prog.search(v)
if result is None:
... |
Return a value check function which raises a ValueError if the supplied value when cast as type is less than min or greater than max. | def number_range_inclusive(min, max, type=float):
"""
Return a value check function which raises a ValueError if the supplied
value when cast as `type` is less than `min` or greater than `max`.
"""
def checker(v):
if type(v) < min or type(v) > max:
raise ValueError(v)
retur... |
Return a value check function which raises a ValueError if the supplied value when cast as type is less than or equal to min or greater than or equal to max. | def number_range_exclusive(min, max, type=float):
"""
Return a value check function which raises a ValueError if the supplied
value when cast as `type` is less than or equal to `min` or greater than
or equal to `max`.
"""
def checker(v):
if type(v) <= min or type(v) >= max:
... |
Return a value check function which raises a ValueError if the supplied value when converted to a datetime using the supplied format string is less than min or greater than max. | def datetime_range_inclusive(min, max, format):
"""
Return a value check function which raises a ValueError if the supplied
value when converted to a datetime using the supplied `format` string is
less than `min` or greater than `max`.
"""
dmin = datetime.strptime(min, format)
dmax = datet... |
Write problems as restructured text to a file ( or stdout/ stderr ). | def write_problems(problems, file, summarize=False, limit=0):
"""
Write problems as restructured text to a file (or stdout/stderr).
"""
w = file.write # convenience variable
w("""
=================
Validation Report
=================
""")
counts = dict() # store problem counts per problem code
... |
Add a header check i. e. check whether the header record is consistent with the expected field names. | def add_header_check(self,
code=HEADER_CHECK_FAILED,
message=MESSAGES[HEADER_CHECK_FAILED]):
"""
Add a header check, i.e., check whether the header record is consistent
with the expected field names.
Arguments
---------
... |
Add a record length check i. e. check whether the length of a record is consistent with the number of expected fields. | def add_record_length_check(self,
code=RECORD_LENGTH_CHECK_FAILED,
message=MESSAGES[RECORD_LENGTH_CHECK_FAILED],
modulus=1):
"""
Add a record length check, i.e., check whether the length of a record is
consistent with the... |
Add a value check function for the specified field. | def add_value_check(self, field_name, value_check,
code=VALUE_CHECK_FAILED,
message=MESSAGES[VALUE_CHECK_FAILED],
modulus=1):
"""
Add a value check function for the specified field.
Arguments
---------
`fie... |
Add a value predicate function for the specified field. | def add_value_predicate(self, field_name, value_predicate,
code=VALUE_PREDICATE_FALSE,
message=MESSAGES[VALUE_PREDICATE_FALSE],
modulus=1):
"""
Add a value predicate function for the specified field.
N.B., everything you ca... |
Add a record check function. | def add_record_check(self, record_check, modulus=1):
"""
Add a record check function.
Arguments
---------
`record_check` - a function that accepts a single argument (a record as
a dictionary of values indexed by field name) and raises a
`RecordError` if the reco... |
Add a record predicate function. | def add_record_predicate(self, record_predicate,
code=RECORD_PREDICATE_FALSE,
message=MESSAGES[RECORD_PREDICATE_FALSE],
modulus=1):
"""
Add a record predicate function.
N.B., everything you can do with record predicates can... |
Add a unique check on a single column or combination of columns. | def add_unique_check(self, key,
code=UNIQUE_CHECK_FAILED,
message=MESSAGES[UNIQUE_CHECK_FAILED]):
"""
Add a unique check on a single column or combination of columns.
Arguments
---------
`key` - a single field name (string) specif... |
Validate data and return a list of validation problems found. | def validate(self, data,
expect_header_row=True,
ignore_lines=0,
summarize=False,
limit=0,
context=None,
report_unexpected_exceptions=True):
"""
Validate `data` and return a list of validation problems ... |
Validate data and return a iterator over problems found. | def ivalidate(self, data,
expect_header_row=True,
ignore_lines=0,
summarize=False,
context=None,
report_unexpected_exceptions=True):
"""
Validate `data` and return a iterator over problems found.
Use this funct... |
Initialise sets used for uniqueness checking. | def _init_unique_sets(self):
"""Initialise sets used for uniqueness checking."""
ks = dict()
for t in self._unique_checks:
key = t[0]
ks[key] = set() # empty set
return ks |
Apply value check functions on the given record r. | def _apply_value_checks(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply value check functions on the given record `r`."""
for field_name, check, code, message, modulus in self._va... |
Apply header checks on the given record r. | def _apply_header_checks(self, i, r, summarize=False, context=None):
"""Apply header checks on the given record `r`."""
for code, message in self._header_checks:
if tuple(r) != self._field_names:
p = {'code': code}
if not summarize:
p['mes... |
Apply record length checks on the given record r. | def _apply_record_length_checks(self, i, r, summarize=False, context=None):
"""Apply record length checks on the given record `r`."""
for code, message, modulus in self._record_length_checks:
if i % modulus == 0: # support sampling
if len(r) != len(self._field_names):
... |
Apply value predicates on the given record r. | def _apply_value_predicates(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply value predicates on the given record `r`."""
for field_name, predicate, code, message, modu... |
Apply record checks on r. | def _apply_record_checks(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply record checks on `r`."""
for check, modulus in self._record_checks:
if i % modu... |
Apply record predicates on r. | def _apply_record_predicates(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply record predicates on `r`."""
for predicate, code, message, modulus in self._record_pred... |
Apply unique checks on r. | def _apply_unique_checks(self, i, r, unique_sets,
summarize=False,
context=None):
"""Apply unique checks on `r`."""
for key, code, message in self._unique_checks:
value = None
values = unique_sets[key]
if isin... |
Invoke each methods on r. | def _apply_each_methods(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Invoke 'each' methods on `r`."""
for a in dir(self):
if a.startswith('each'):
rdict =... |
Apply assert methods on r. | def _apply_assert_methods(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply 'assert' methods on `r`."""
for a in dir(self):
if a.startswith('assert'):
... |
Apply check methods on r. | def _apply_check_methods(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply 'check' methods on `r`."""
for a in dir(self):
if a.startswith('check'):
... |
Apply skip functions on r. | def _apply_skips(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply skip functions on `r`."""
for skip in self._skips:
try:
result = skip(r)
if result is True:... |
Convert the record to a dictionary using field names as keys. | def _as_dict(self, r):
"""Convert the record to a dictionary using field names as keys."""
d = dict()
for i, f in enumerate(self._field_names):
d[f] = r[i] if i < len(r) else None
return d |
Create an example CSV validator for patient demographic data. | def create_validator():
"""Create an example CSV validator for patient demographic data."""
field_names = (
'study_id',
'patient_id',
'gender',
'age_years',
'age_months',
'date_inclusion'
... |
Main function. | def main():
"""Main function."""
# define a command-line argument parser
description = 'Validate a CSV data file.'
parser = argparse.ArgumentParser(description=description)
parser.add_argument('file',
metavar='FILE',
help='a file to be validated')
... |
Convert markdown tables to html since recommonmark can t. This requires 3 steps: Snip out table sections from the markdown Convert them to html Replace the old markdown table with an html table | def process_tables(app, docname, source):
"""
Convert markdown tables to html, since recommonmark can't. This requires 3 steps:
Snip out table sections from the markdown
Convert them to html
Replace the old markdown table with an html table
This function is called by sphinx for each... |
Pack given values v1 v2... into given bytearray buf starting at given bit offset offset. Pack according to given format string fmt. Give fill_padding as False to leave padding bits in buf unmodified. | def pack_into(fmt, buf, offset, *args, **kwargs):
"""Pack given values v1, v2, ... into given bytearray `buf`, starting
at given bit offset `offset`. Pack according to given format
string `fmt`. Give `fill_padding` as ``False`` to leave padding
bits in `buf` unmodified.
"""
return CompiledForm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.