_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q261300 | _arg_parser | validation | def _arg_parser():
"""Factory for creating the argument parser"""
description = "Converts a completezip to a litezip"
parser = argparse.ArgumentParser(description=description)
verbose_group = parser.add_mutually_exclusive_group()
verbose_group.add_argument(
'-v', '--verbose', action='store_t... | python | {
"resource": ""
} |
q261301 | IF.to_bytes | validation | def to_bytes(self, previous: bytes):
"""
Complex code ahead. Comments have been added in as needed.
"""
# First, validate the lengths.
if len(self.conditions) != len(self.body):
raise exc.CompileError("Conditions and body length mismatch!")
bc = b""
... | python | {
"resource": ""
} |
q261302 | FOR_LOOP.to_bytes_35 | validation | def to_bytes_35(self, previous: bytes):
"""
A to-bytes specific to Python 3.5 and below.
"""
# Calculations ahead.
bc = b""
# Calculate the length of the iterator.
it_bc = util.generate_bytecode_from_obb(self.iterator, previous)
bc += it_bc
# Pu... | python | {
"resource": ""
} |
q261303 | FOR_LOOP.to_bytes_36 | validation | def to_bytes_36(self, previous: bytes):
"""
A to-bytes specific to Python 3.6 and above.
"""
# Calculations ahead.
bc = b""
# Calculate the length of the iterator.
it_bc = util.generate_bytecode_from_obb(self.iterator, previous)
bc += it_bc
bc +=... | python | {
"resource": ""
} |
q261304 | validate_content | validation | def validate_content(*objs):
"""Runs the correct validator for given `obj`ects. Assumes all same type"""
from .main import Collection, Module
validator = {
Collection: cnxml.validate_collxml,
Module: cnxml.validate_cnxml,
}[type(objs[0])]
return validator(*[obj.file for obj in objs]) | python | {
"resource": ""
} |
q261305 | validate_litezip | validation | def validate_litezip(struct):
"""Validate the given litezip as `struct`.
Returns a list of validation messages.
"""
msgs = []
def _fmt_err(err):
return (Path(err.filename), "{}:{} -- {}: {}".format(*(err[1:])))
obj_by_type = {}
for obj in struct:
if not is_valid_identifier... | python | {
"resource": ""
} |
q261306 | ensure_instruction | validation | def ensure_instruction(instruction: int) -> bytes:
"""
Wraps an instruction to be Python 3.6+ compatible. This does nothing on Python 3.5 and below.
This is most useful for operating on bare, single-width instructions such as
``RETURN_FUNCTION`` in a version portable way.
:param instruction: The i... | python | {
"resource": ""
} |
q261307 | pack_value | validation | def pack_value(index: int) -> bytes:
"""
Small helper value to pack an index value into bytecode.
This is used for version compat between 3.5- and 3.6+
:param index: The item to pack.
:return: The packed item.
"""
if PY36:
return index.to_bytes(1, byteorder="little")
else:
... | python | {
"resource": ""
} |
q261308 | generate_simple_call | validation | def generate_simple_call(opcode: int, index: int):
"""
Generates a simple call, with an index for something.
:param opcode: The opcode to generate.
:param index: The index to use as an argument.
:return:
"""
bs = b""
# add the opcode
bs += opcode.to_bytes(1, byteorder="little")
... | python | {
"resource": ""
} |
q261309 | generate_bytecode_from_obb | validation | def generate_bytecode_from_obb(obb: object, previous: bytes) -> bytes:
"""
Generates a bytecode from an object.
:param obb: The object to generate.
:param previous: The previous bytecode to use when generating subobjects.
:return: The generated bytecode.
"""
# Generates bytecode from a spec... | python | {
"resource": ""
} |
q261310 | _get_const_info | validation | def _get_const_info(const_index, const_list):
"""
Helper to get optional details about const references
Returns the dereferenced constant and its repr if the constant
list is defined.
Otherwise returns the constant index and its repr().
"""
argval = const_index
if const_list is... | python | {
"resource": ""
} |
q261311 | _get_name_info | validation | def _get_name_info(name_index, name_list):
"""Helper to get optional details about named references
Returns the dereferenced name as both value and repr if the name
list is defined.
Otherwise returns the name index and its repr().
"""
argval = name_index
if name_list is not None:
... | python | {
"resource": ""
} |
q261312 | compile_bytecode | validation | def compile_bytecode(code: list) -> bytes:
"""
Compiles Pyte objects into a bytecode list.
:param code: A list of objects to compile.
:return: The computed bytecode.
"""
bc = b""
for i, op in enumerate(code):
try:
# Get the bytecode.
if isinstance(op, _PyteOp... | python | {
"resource": ""
} |
q261313 | _simulate_stack | validation | def _simulate_stack(code: list) -> int:
"""
Simulates the actions of the stack, to check safety.
This returns the maximum needed stack.
"""
max_stack = 0
curr_stack = 0
def _check_stack(ins):
if curr_stack < 0:
raise CompileError("Stack turned negative on instruction: ... | python | {
"resource": ""
} |
q261314 | compile | validation | def compile(code: list, consts: list, names: list, varnames: list,
func_name: str = "<unknown, compiled>",
arg_count: int = 0, kwarg_defaults: Tuple[Any] = (), use_safety_wrapper: bool = True):
"""
Compiles a set of bytecode instructions into a working function, using Python's bytecode
... | python | {
"resource": ""
} |
q261315 | _parse_document_id | validation | def _parse_document_id(elm_tree):
"""Given the parsed xml to an `ElementTree`,
parse the id from the content.
"""
xpath = '//md:content-id/text()'
return [x for x in elm_tree.xpath(xpath, namespaces=COLLECTION_NSMAP)][0] | python | {
"resource": ""
} |
q261316 | parse_module | validation | def parse_module(path, excludes=None):
"""Parse the file structure to a data structure given the path to
a module directory.
"""
file = path / MODULE_FILENAME
if not file.exists():
raise MissingFile(file)
id = _parse_document_id(etree.parse(file.open()))
excludes = excludes or []
... | python | {
"resource": ""
} |
q261317 | parse_collection | validation | def parse_collection(path, excludes=None):
"""Parse a file structure to a data structure given the path to
a collection directory.
"""
file = path / COLLECTION_FILENAME
if not file.exists():
raise MissingFile(file)
id = _parse_document_id(etree.parse(file.open()))
excludes = exclud... | python | {
"resource": ""
} |
q261318 | parse_litezip | validation | def parse_litezip(path):
"""Parse a litezip file structure to a data structure given the path
to the litezip directory.
"""
struct = [parse_collection(path)]
struct.extend([parse_module(x) for x in path.iterdir()
if x.is_dir() and x.name.startswith('m')])
return tuple(sorted(... | python | {
"resource": ""
} |
q261319 | convert_completezip | validation | def convert_completezip(path):
"""Converts a completezip file structure to a litezip file structure.
Returns a litezip data structure.
"""
for filepath in path.glob('**/index_auto_generated.cnxml'):
filepath.rename(filepath.parent / 'index.cnxml')
logger.debug('removed {}'.format(filepa... | python | {
"resource": ""
} |
q261320 | _get_instructions_bytes | validation | def _get_instructions_bytes(code, varnames=None, names=None, constants=None,
cells=None, linestarts=None, line_offset=0):
"""Iterate over the instructions in a bytecode string.
Generates a sequence of Instruction namedtuples giving the details of each
opcode. Additional informa... | python | {
"resource": ""
} |
q261321 | Instruction._disassemble | validation | 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 = []... | python | {
"resource": ""
} |
q261322 | intersection | validation | 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... | python | {
"resource": ""
} |
q261323 | remove_contained_in_list | validation | 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... | python | {
"resource": ""
} |
q261324 | Interval.distance_to_point | validation | 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)) | python | {
"resource": ""
} |
q261325 | Interval.intersects | validation | def intersects(self, i):
'''Returns true iff this interval intersects the interval i'''
return self.start <= i.end and i.start <= self.end | python | {
"resource": ""
} |
q261326 | Interval.contains | validation | def contains(self, i):
'''Returns true iff this interval contains the interval i'''
return self.start <= i.start and i.end <= self.end | python | {
"resource": ""
} |
q261327 | Interval.union | validation | 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 | python | {
"resource": ""
} |
q261328 | Interval.union_fill_gap | validation | 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)) | python | {
"resource": ""
} |
q261329 | Interval.intersection | validation | 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 | python | {
"resource": ""
} |
q261330 | Fasta.subseq | validation | 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]) | python | {
"resource": ""
} |
q261331 | Fasta.replace_bases | validation | def replace_bases(self, old, new):
'''Replaces all occurrences of 'old' with 'new' '''
self.seq = self.seq.replace(old, new) | python | {
"resource": ""
} |
q261332 | Fasta.gaps | validation | 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... | python | {
"resource": ""
} |
q261333 | Fasta.orfs | validation | 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,... | python | {
"resource": ""
} |
q261334 | Fasta.is_complete_orf | validation | 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... | python | {
"resource": ""
} |
q261335 | Fasta.to_Fastq | validation | 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, ''.... | python | {
"resource": ""
} |
q261336 | Fastq.subseq | validation | 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]) | python | {
"resource": ""
} |
q261337 | Fastq.trim_Ns | validation | 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:]... | python | {
"resource": ""
} |
q261338 | count_sequences | validation | 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 | python | {
"resource": ""
} |
q261339 | interleave | validation | 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)
... | python | {
"resource": ""
} |
q261340 | make_random_contigs | validation | 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... | python | {
"resource": ""
} |
q261341 | mean_length | validation | 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)
... | python | {
"resource": ""
} |
q261342 | merge_to_one_seq | validation | 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:
... | python | {
"resource": ""
} |
q261343 | scaffolds_to_contigs | validation | 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 =... | python | {
"resource": ""
} |
q261344 | sort_by_size | validation | 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... | python | {
"resource": ""
} |
q261345 | sort_by_name | validation | 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)
... | python | {
"resource": ""
} |
q261346 | to_fastg | validation | 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... | python | {
"resource": ""
} |
q261347 | to_boulderio | validation | 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... | python | {
"resource": ""
} |
q261348 | pbkdf2 | validation | 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... | python | {
"resource": ""
} |
q261349 | get_encrypted_field | validation | 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]
""... | python | {
"resource": ""
} |
q261350 | encrypt | validation | 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.
... | python | {
"resource": ""
} |
q261351 | PickledField.value_to_string | validation | 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') | python | {
"resource": ""
} |
q261352 | dumps | validation | 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 ... | python | {
"resource": ""
} |
q261353 | FernetSigner.unsign | validation | 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
... | python | {
"resource": ""
} |
q261354 | get_version | validation | 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... | python | {
"resource": ""
} |
q261355 | get_complete_version | validation | 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... | python | {
"resource": ""
} |
q261356 | enumeration | validation | 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... | python | {
"resource": ""
} |
q261357 | match_pattern | validation | 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... | python | {
"resource": ""
} |
q261358 | search_pattern | validation | 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:
... | python | {
"resource": ""
} |
q261359 | number_range_inclusive | validation | 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... | python | {
"resource": ""
} |
q261360 | number_range_exclusive | validation | 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:
... | python | {
"resource": ""
} |
q261361 | datetime_range_inclusive | validation | 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... | python | {
"resource": ""
} |
q261362 | CSVValidator.add_header_check | validation | 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
---------
... | python | {
"resource": ""
} |
q261363 | CSVValidator.add_record_length_check | validation | 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... | python | {
"resource": ""
} |
q261364 | CSVValidator.add_value_check | validation | 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... | python | {
"resource": ""
} |
q261365 | CSVValidator.add_value_predicate | validation | 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... | python | {
"resource": ""
} |
q261366 | CSVValidator.add_record_check | validation | 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... | python | {
"resource": ""
} |
q261367 | CSVValidator.add_record_predicate | validation | 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... | python | {
"resource": ""
} |
q261368 | CSVValidator.add_unique_check | validation | 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... | python | {
"resource": ""
} |
q261369 | CSVValidator.validate | validation | 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 ... | python | {
"resource": ""
} |
q261370 | CSVValidator.ivalidate | validation | 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... | python | {
"resource": ""
} |
q261371 | CSVValidator._init_unique_sets | validation | 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 | python | {
"resource": ""
} |
q261372 | CSVValidator._apply_value_checks | validation | 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... | python | {
"resource": ""
} |
q261373 | CSVValidator._apply_header_checks | validation | 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... | python | {
"resource": ""
} |
q261374 | CSVValidator._apply_record_length_checks | validation | 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):
... | python | {
"resource": ""
} |
q261375 | CSVValidator._apply_value_predicates | validation | 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... | python | {
"resource": ""
} |
q261376 | CSVValidator._apply_record_checks | validation | 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... | python | {
"resource": ""
} |
q261377 | CSVValidator._apply_record_predicates | validation | 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... | python | {
"resource": ""
} |
q261378 | CSVValidator._apply_unique_checks | validation | 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... | python | {
"resource": ""
} |
q261379 | CSVValidator._apply_each_methods | validation | 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 =... | python | {
"resource": ""
} |
q261380 | CSVValidator._apply_assert_methods | validation | 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'):
... | python | {
"resource": ""
} |
q261381 | CSVValidator._apply_check_methods | validation | 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'):
... | python | {
"resource": ""
} |
q261382 | CSVValidator._apply_skips | validation | 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:... | python | {
"resource": ""
} |
q261383 | CSVValidator._as_dict | validation | 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 | python | {
"resource": ""
} |
q261384 | create_validator | validation | 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'
... | python | {
"resource": ""
} |
q261385 | main | validation | 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')
... | python | {
"resource": ""
} |
q261386 | pack_into | validation | 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... | python | {
"resource": ""
} |
q261387 | byteswap | validation | def byteswap(fmt, data, offset=0):
"""Swap bytes in `data` according to `fmt`, starting at byte `offset`
and return the result. `fmt` must be an iterable, iterating over
number of bytes to swap. For example, the format string ``'24'``
applied to the bytes ``b'\\x00\\x11\\x22\\x33\\x44\\x55'`` will
p... | python | {
"resource": ""
} |
q261388 | TelegramEngine.get_chat_id | validation | def get_chat_id(self, message):
'''
Telegram chat type can be either "private", "group", "supergroup" or
"channel".
Return user ID if it is of type "private", chat ID otherwise.
'''
if message.chat.type == 'private':
return message.user.id
return mess... | python | {
"resource": ""
} |
q261389 | MessengerEngine.build_message | validation | def build_message(self, data):
'''
Return a Message instance according to the data received from
Facebook Messenger API.
'''
if not data:
return None
return Message(
id=data['message']['mid'],
platform=self.platform,
text=d... | python | {
"resource": ""
} |
q261390 | BaseEngine._get_response | validation | async def _get_response(self, message):
"""
Get response running the view with await syntax if it is a
coroutine function, otherwise just run it the normal way.
"""
view = self.discovery_view(message)
if not view:
return
if inspect.iscoroutinefunctio... | python | {
"resource": ""
} |
q261391 | BaseEngine.discovery_view | validation | def discovery_view(self, message):
"""
Use the new message to search for a registered view according
to its pattern.
"""
for handler in self.registered_handlers:
if handler.check(message):
return handler.view
return None | python | {
"resource": ""
} |
q261392 | BaseEngine.message_handler | validation | async def message_handler(self, data):
"""
For each new message, build its platform specific message
object and get a response.
"""
message = self.build_message(data)
if not message:
logger.error(
'[%s] Unable to build Message with data, data=... | python | {
"resource": ""
} |
q261393 | unpack | validation | def unpack(endian, fmt, data):
"""Unpack a byte string to the given format. If the byte string
contains more bytes than required for the given format, the function
returns a tuple of values.
"""
if fmt == 's':
# read data as an array of chars
val = struct.unpack(''.join([endian, str(... | python | {
"resource": ""
} |
q261394 | read_file_header | validation | def read_file_header(fd, endian):
"""Read mat 5 file header of the file fd.
Returns a dict with header values.
"""
fields = [
('description', 's', 116),
('subsystem_offset', 's', 8),
('version', 'H', 2),
('endian_test', 's', 2)
]
hdict = {}
for name, fmt, num_... | python | {
"resource": ""
} |
q261395 | read_elements | validation | def read_elements(fd, endian, mtps, is_name=False):
"""Read elements from the file.
If list of possible matrix data types mtps is provided, the data type
of the elements are verified.
"""
mtpn, num_bytes, data = read_element_tag(fd, endian)
if mtps and mtpn not in [etypes[mtp]['n'] for mtp in m... | python | {
"resource": ""
} |
q261396 | read_header | validation | def read_header(fd, endian):
"""Read and return the matrix header."""
flag_class, nzmax = read_elements(fd, endian, ['miUINT32'])
header = {
'mclass': flag_class & 0x0FF,
'is_logical': (flag_class >> 9 & 1) == 1,
'is_global': (flag_class >> 10 & 1) == 1,
'is_complex': (flag_c... | python | {
"resource": ""
} |
q261397 | read_var_header | validation | def read_var_header(fd, endian):
"""Read full header tag.
Return a dict with the parsed header, the file position of next tag,
a file like object for reading the uncompressed element data.
"""
mtpn, num_bytes = unpack(endian, 'II', fd.read(8))
next_pos = fd.tell() + num_bytes
if mtpn == et... | python | {
"resource": ""
} |
q261398 | read_numeric_array | validation | def read_numeric_array(fd, endian, header, data_etypes):
"""Read a numeric matrix.
Returns an array with rows of the numeric matrix.
"""
if header['is_complex']:
raise ParseError('Complex arrays are not supported')
# read array data (stored as column-major)
data = read_elements(fd, endia... | python | {
"resource": ""
} |
q261399 | read_cell_array | validation | def read_cell_array(fd, endian, header):
"""Read a cell array.
Returns an array with rows of the cell array.
"""
array = [list() for i in range(header['dims'][0])]
for row in range(header['dims'][0]):
for col in range(header['dims'][1]):
# read the matrix header and array
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.