signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def _until_eof(stream): | while True:<EOL><INDENT>line = stream.readline()<EOL>if line == '<STR_LIT>':<EOL><INDENT>break<EOL><DEDENT>yield line<EOL><DEDENT> | Yield lines from an open file.
Iterating over `sys.stdin` continues after EOF marker. This is annoying,
since it means having to type ``^D`` twice to stop. Wrap this function
around the stream to stop at the first EOF marker. | f2258:m0 |
def _fasta_iter(fasta): | <EOL>groups = (group for _, group in<EOL>itertools.groupby(fasta, lambda line: line.startswith('<STR_LIT:>>')))<EOL>for group in groups:<EOL><INDENT>header = next(group)[<NUM_LIT:1>:].strip()<EOL>sequence = '<STR_LIT>'.join(line.strip() for line in next(groups))<EOL>yield header, sequence<EOL><DEDENT> | Given an open FASTA file, yield tuples of (`header`, `sequence`). | f2258:m1 |
def _bed_iter(bed): | records = (line.split()[:<NUM_LIT:3>] for line in bed if<EOL>not (line.startswith('<STR_LIT>') or line.startswith('<STR_LIT>')))<EOL>for chrom, chrom_iter in itertools.groupby(records, lambda x: x[<NUM_LIT:0>]):<EOL><INDENT>yield chrom, ((int(start), int(stop))<EOL>for _, start, stop in chrom_iter)<EOL><DEDENT> | Given an open BED file, yield tuples of (`chrom`, `chrom_iter`) where
`chrom_iter` yields tuples of (`start`, `stop`). | f2258:m2 |
def _pprint_fasta(fasta, annotations=None, annotation_file=None,<EOL>block_length=<NUM_LIT:10>, blocks_per_line=<NUM_LIT:6>): | annotations = annotations or []<EOL>as_by_chrom = collections.defaultdict(lambda: [a for a in annotations] or [])<EOL>if annotation_file:<EOL><INDENT>for chrom, chrom_iter in _bed_iter(annotation_file):<EOL><INDENT>as_by_chrom[chrom].append(list(chrom_iter))<EOL><DEDENT><DEDENT>for header, sequence in _fasta_iter(fasta... | Pretty-print each record in the FASTA file. | f2258:m3 |
def _pprint_line(line, annotations=None, annotation_file=None,<EOL>block_length=<NUM_LIT:10>, blocks_per_line=<NUM_LIT:6>): | annotations = annotations or []<EOL>if annotation_file:<EOL><INDENT>_, chrom_iter = next(_bed_iter(annotation_file))<EOL>annotations.append(list(chrom_iter))<EOL><DEDENT>print(pprint_sequence(line, annotations=annotations,<EOL>block_length=block_length,<EOL>blocks_per_line=blocks_per_line, format=AnsiFormat))<EOL> | Pretty-print one line. | f2258:m4 |
def pprint(sequence_file, annotation=None, annotation_file=None,<EOL>block_length=<NUM_LIT:10>, blocks_per_line=<NUM_LIT:6>): | annotations = []<EOL>if annotation:<EOL><INDENT>annotations.append([(first - <NUM_LIT:1>, last) for first, last in annotation])<EOL><DEDENT>try:<EOL><INDENT>line = next(sequence_file)<EOL>if line.startswith('<STR_LIT:>>'):<EOL><INDENT>_pprint_fasta(itertools.chain([line], sequence_file),<EOL>annotations=annotations,<EO... | Pretty-print sequence(s) from a file. | f2258:m5 |
def main(): | parser = argparse.ArgumentParser(<EOL>description='<STR_LIT>',<EOL>epilog='<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>parser.add_argument(<EOL>'<STR_LIT>', metavar='<STR_LIT>', nargs='<STR_LIT:?>', default=sys.stdin,<EOL>type=argparse.FileType('<STR_LIT:r>'), help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>p... | Command line interface. | f2258:m6 |
def partition_range(stop, annotations=None): | annotations = annotations or []<EOL>partitioning = []<EOL>part_start, part_levels = <NUM_LIT:0>, None<EOL>for p in sorted(set(itertools.chain([<NUM_LIT:0>, stop],<EOL>*itertools.chain(*annotations)))):<EOL><INDENT>if p == stop:<EOL><INDENT>partitioning.append( (part_start, p, part_levels) )<EOL>break<EOL><DEDENT>levels... | Partition the range from 0 to `stop` based on annotations.
>>> partition_range(50, annotations=[[(0, 21), (30, 35)],
... [(15, 32), (40, 46)]])
[(0, 15, {0}),
(15, 21, {0, 1}),
(21, 30, {1}),
(30, 32, {0, 1}),
(32, 35, {0}),
(35, 40, set()),
(4... | f2259:m0 |
def pprint_sequence(sequence, annotations=None, block_length=<NUM_LIT:10>,<EOL>blocks_per_line=<NUM_LIT:6>, format=PlaintextFormat): | annotations = annotations or []<EOL>partitioning = partition_range(len(sequence), annotations)<EOL>margin = int(math.floor(math.log(max(len(sequence), <NUM_LIT:1>), <NUM_LIT:10>))<EOL>+ <NUM_LIT:1>) + len(format.margin[<NUM_LIT:0>])<EOL>result = (format.margin[<NUM_LIT:0>] + '<STR_LIT:1>').rjust(margin) + format.margin... | Pretty-print sequence for use with a monospace font.
>>> sequence = 'MIMANQPLWLDSEVEMNHYQQSHIKSKSPYFPEDKHICWIKIFKAFGT' * 4
>>> print pprint_sequence(sequence, format=PlaintextFormat)
1 MIMANQPLWL DSEVEMNHYQ QSHIKSKSPY FPEDKHICWI KIFKAFGTMI MANQPLWLDS
61 EVEMNHYQQS HIKSKSPYFP EDKHICWIKI FKAFGTMIMA ... | f2259:m1 |
def Seq(sequence, annotations=None, block_length=<NUM_LIT:10>, blocks_per_line=<NUM_LIT:6>,<EOL>style=DEFAULT_STYLE): | seq_id = '<STR_LIT>' + binascii.hexlify(os.urandom(<NUM_LIT:4>))<EOL>pprinted = pprint_sequence(sequence,<EOL>annotations=annotations,<EOL>block_length=block_length,<EOL>blocks_per_line=blocks_per_line,<EOL>format=HtmlFormat)<EOL>return HTML('<STR_LIT>'<EOL>.format(style=style.format(selector='<STR_LIT:#>' + seq_id),<E... | Pretty-printed sequence object that's displayed nicely in the IPython
Notebook.
:arg style: Custom CSS as a `format string`, where a selector for the
top-level ``<pre>`` element is substituted for `{selector}`. See
:data:`DEFAULT_STYLE` for an example.
:type style: str
For a description of the other arguments... | f2261:m0 |
def run(self, toolbox): | self.results.put(toolbox.count)<EOL>toolbox.count += <NUM_LIT:1><EOL> | Append the current count to results and increment. | f2265:c1:m1 |
def put(self, job, result): | self.job.put(job)<EOL>r = result.get()<EOL>return r<EOL> | Perform a job by a member in the pool and return the result. | f2270:c0:m0 |
def contract(self, jobs, result): | for j in jobs:<EOL><INDENT>WorkerPool.put(self, j)<EOL><DEDENT>r = []<EOL>for i in xrange(len(jobs)):<EOL><INDENT>r.append(result.get())<EOL><DEDENT>return r<EOL> | Perform a contract on a number of jobs and block until a result is
retrieved for each job. | f2270:c0:m1 |
def run(self): | while <NUM_LIT:1>:<EOL><INDENT>job = self.jobs.get()<EOL>try:<EOL><INDENT>job.run()<EOL>self.jobs.task_done()<EOL><DEDENT>except TerminationNotice:<EOL><INDENT>self.jobs.task_done()<EOL>break<EOL><DEDENT><DEDENT> | Get jobs from the queue and perform them as they arrive. | f2271:c0:m1 |
def run(self): | while <NUM_LIT:1>:<EOL><INDENT>job = self.jobs.get()<EOL>try:<EOL><INDENT>job.run(toolbox=self.toolbox)<EOL>self.jobs.task_done()<EOL><DEDENT>except TerminationNotice:<EOL><INDENT>self.jobs.task_done()<EOL>break<EOL><DEDENT><DEDENT> | Get jobs from the queue and perform them as they arrive. | f2271:c1:m1 |
def run(self): | pass<EOL> | The actual task for the job should be implemented here. | f2272:c0:m1 |
def _return(self, r): | self.result.put(r)<EOL> | Handle return value by appending to the ``self.result`` queue. | f2272:c2:m2 |
def task_done(self): | pass<EOL> | Does nothing in Python 2.4 | f2274:c0:m0 |
def join(self): | pass<EOL> | Does nothing in Python 2.4 | f2274:c0:m1 |
def grow(self): | t = self.worker_factory(self)<EOL>t.start()<EOL>self._size += <NUM_LIT:1><EOL> | Add another worker to the pool. | f2275:c0:m1 |
def shrink(self): | if self._size <= <NUM_LIT:0>:<EOL><INDENT>raise IndexError("<STR_LIT>")<EOL><DEDENT>self._size -= <NUM_LIT:1><EOL>self.put(SuicideJob())<EOL> | Get rid of one worker from the pool. Raises IndexError if empty. | f2275:c0:m2 |
def shutdown(self): | for i in range(self.size()):<EOL><INDENT>self.put(SuicideJob())<EOL><DEDENT> | Retire the workers. | f2275:c0:m3 |
def size(self): | "<STR_LIT>"<EOL>return self._size<EOL> | Approximate number of active workers | f2275:c0:m4 |
def map(self, fn, *seq): | "<STR_LIT>"<EOL>results = Queue()<EOL>args = zip(*seq)<EOL>for seq in args:<EOL><INDENT>j = SimpleJob(results, fn, seq)<EOL>self.put(j)<EOL><DEDENT>r = []<EOL>for i in range(len(list(args))):<EOL><INDENT>r.append(results.get())<EOL><DEDENT>return r<EOL> | Perform a map operation distributed among the workers. Will | f2275:c0:m5 |
def wait(self): | self.join()<EOL> | DEPRECATED: Use join() instead. | f2275:c0:m6 |
def async_run(self, keyword, *args, **kwargs): | handle = self._last_thread_handle<EOL>thread = self._threaded(keyword, *args, **kwargs)<EOL>thread.start()<EOL>self._thread_pool[handle] = thread<EOL>self._last_thread_handle += <NUM_LIT:1><EOL>return handle<EOL> | Executes the provided Robot Framework keyword in a separate thread and immediately returns a handle to be used with async_get | f2278:c0:m1 |
def async_get(self, handle): | assert handle in self._thread_pool, '<STR_LIT>'<EOL>result = self._thread_pool[handle].result_queue.get()<EOL>del self._thread_pool[handle]<EOL>return result<EOL> | Blocks until the thread created by async_run returns | f2278:c0:m2 |
def _get_handler_from_keyword(self, keyword): | if EXECUTION_CONTEXTS.current is None:<EOL><INDENT>raise RobotNotRunningError('<STR_LIT>')<EOL><DEDENT>return EXECUTION_CONTEXTS.current.get_handler(keyword)<EOL> | Gets the Robot Framework handler associated with the given keyword | f2278:c0:m3 |
def Lower(v): | return _fix_str(v).lower()<EOL> | Transform a string to lower case.
>>> s = Schema(Lower)
>>> s('HI')
'hi' | f2281:m1 |
def Upper(v): | return _fix_str(v).upper()<EOL> | Transform a string to upper case.
>>> s = Schema(Upper)
>>> s('hi')
'HI' | f2281:m2 |
def Capitalize(v): | return _fix_str(v).capitalize()<EOL> | Capitalise a string.
>>> s = Schema(Capitalize)
>>> s('hello world')
'Hello world' | f2281:m3 |
def Title(v): | return _fix_str(v).title()<EOL> | Title case a string.
>>> s = Schema(Title)
>>> s('hello world')
'Hello World' | f2281:m4 |
def Strip(v): | return _fix_str(v).strip()<EOL> | Strip whitespace from a string.
>>> s = Schema(Strip)
>>> s(' hello world ')
'hello world' | f2281:m5 |
def truth(f): | @wraps(f)<EOL>def check(v):<EOL><INDENT>t = f(v)<EOL>if not t:<EOL><INDENT>raise ValueError<EOL><DEDENT>return v<EOL><DEDENT>return check<EOL> | Convenience decorator to convert truth functions into validators.
>>> @truth
... def isdir(v):
... return os.path.isdir(v)
>>> validate = Schema(isdir)
>>> validate('/')
'/'
>>> with raises(MultipleInvalid, 'not a valid value'):
... validate('/notaval... | f2284:m0 |
@message('<STR_LIT>', cls=TrueInvalid)<EOL>@truth<EOL>def IsTrue(v): | return v<EOL> | Assert that a value is true, in the Python sense.
>>> validate = Schema(IsTrue())
"In the Python sense" means that implicitly false values, such as empty
lists, dictionaries, etc. are treated as "false":
>>> with raises(MultipleInvalid, "value was not true"):
... validate([])
>>> validate([... | f2284:m1 |
@message('<STR_LIT>', cls=FalseInvalid)<EOL>def IsFalse(v): | if v:<EOL><INDENT>raise ValueError<EOL><DEDENT>return v<EOL> | Assert that a value is false, in the Python sense.
(see :func:`IsTrue` for more detail)
>>> validate = Schema(IsFalse())
>>> validate([])
[]
>>> with raises(MultipleInvalid, "value was not false"):
... validate(True)
>>> try:
... validate(True)
... except MultipleInvalid as e:
... | f2284:m2 |
@message('<STR_LIT>', cls=BooleanInvalid)<EOL>def Boolean(v): | if isinstance(v, basestring):<EOL><INDENT>v = v.lower()<EOL>if v in ('<STR_LIT:1>', '<STR_LIT:true>', '<STR_LIT:yes>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return True<EOL><DEDENT>if v in ('<STR_LIT:0>', '<STR_LIT:false>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return False<EOL><DEDENT>raise ValueError<E... | Convert human-readable boolean values to a bool.
Accepted values are 1, true, yes, on, enable, and their negatives.
Non-string values are cast to bool.
>>> validate = Schema(Boolean())
>>> validate(True)
True
>>> validate("1")
True
>>> validate("0")
False
>>> with raises(Multip... | f2284:m3 |
@message('<STR_LIT>', cls=EmailInvalid)<EOL>def Email(v): | try:<EOL><INDENT>if not v or "<STR_LIT:@>" not in v:<EOL><INDENT>raise EmailInvalid("<STR_LIT>")<EOL><DEDENT>user_part, domain_part = v.rsplit('<STR_LIT:@>', <NUM_LIT:1>)<EOL>if not (USER_REGEX.match(user_part) and DOMAIN_REGEX.match(domain_part)):<EOL><INDENT>raise EmailInvalid("<STR_LIT>")<EOL><DEDENT>return v<EOL><D... | Verify that the value is an Email or not.
>>> s = Schema(Email())
>>> with raises(MultipleInvalid, 'expected an Email'):
... s("a.com")
>>> with raises(MultipleInvalid, 'expected an Email'):
... s("[email protected]")
>>> with raises(MultipleInvalid, 'expected an Email'):
... s("[email protected]")
>>>... | f2284:m5 |
@message('<STR_LIT>', cls=UrlInvalid)<EOL>def FqdnUrl(v): | try:<EOL><INDENT>parsed_url = _url_validation(v)<EOL>if "<STR_LIT:.>" not in parsed_url.netloc:<EOL><INDENT>raise UrlInvalid("<STR_LIT>")<EOL><DEDENT>return v<EOL><DEDENT>except:<EOL><INDENT>raise ValueError<EOL><DEDENT> | Verify that the value is a Fully qualified domain name URL.
>>> s = Schema(FqdnUrl())
>>> with raises(MultipleInvalid, 'expected a Fully qualified domain name URL'):
... s("http://localhost/")
>>> s('http://w3.org')
'http://w3.org' | f2284:m6 |
@message('<STR_LIT>', cls=UrlInvalid)<EOL>def Url(v): | try:<EOL><INDENT>_url_validation(v)<EOL>return v<EOL><DEDENT>except:<EOL><INDENT>raise ValueError<EOL><DEDENT> | Verify that the value is a URL.
>>> s = Schema(Url())
>>> with raises(MultipleInvalid, 'expected a URL'):
... s(1)
>>> s('http://w3.org')
'http://w3.org' | f2284:m7 |
@message('<STR_LIT>', cls=FileInvalid)<EOL>@truth<EOL>def IsFile(v): | try:<EOL><INDENT>if v:<EOL><INDENT>v = str(v)<EOL>return os.path.isfile(v)<EOL><DEDENT>else:<EOL><INDENT>raise FileInvalid('<STR_LIT>')<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>raise FileInvalid('<STR_LIT>')<EOL><DEDENT> | Verify the file exists.
>>> os.path.basename(IsFile()(__file__)).startswith('validators.py')
True
>>> with raises(FileInvalid, 'not a file'):
... IsFile()("random_filename_goes_here.py")
>>> with raises(FileInvalid, 'Not a file'):
... IsFile()(None) | f2284:m8 |
@message('<STR_LIT>', cls=DirInvalid)<EOL>@truth<EOL>def IsDir(v): | try:<EOL><INDENT>if v:<EOL><INDENT>v = str(v)<EOL>return os.path.isdir(v)<EOL><DEDENT>else:<EOL><INDENT>raise DirInvalid("<STR_LIT>")<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>raise DirInvalid("<STR_LIT>")<EOL><DEDENT> | Verify the directory exists.
>>> IsDir()('/')
'/'
>>> with raises(DirInvalid, 'Not a directory'):
... IsDir()(None) | f2284:m9 |
@message('<STR_LIT>', cls=PathInvalid)<EOL>@truth<EOL>def PathExists(v): | try:<EOL><INDENT>if v:<EOL><INDENT>v = str(v)<EOL>return os.path.exists(v)<EOL><DEDENT>else:<EOL><INDENT>raise PathInvalid("<STR_LIT>")<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>raise PathInvalid("<STR_LIT>")<EOL><DEDENT> | Verify the path exists, regardless of its type.
>>> os.path.basename(PathExists()(__file__)).startswith('validators.py')
True
>>> with raises(Invalid, 'path does not exist'):
... PathExists()("random_filename_goes_here.py")
>>> with raises(PathInvalid, 'Not a Path'):
... PathExists()(None) | f2284:m10 |
def Maybe(validator, msg=None): | return Any(None, validator, msg=msg)<EOL> | Validate that the object matches given validator or is None.
:raises Invalid: if the value does not match the given validator and is not
None
>>> s = Schema(Maybe(int))
>>> s(10)
10
>>> with raises(Invalid):
... s("string") | f2284:m11 |
def __call__(self, v): | precision, scale, decimal_num = self._get_precision_scale(v)<EOL>if self.precision is not None and self.scale is not None and precision != self.precisionand scale != self.scale:<EOL><INDENT>raise Invalid(self.msg or "<STR_LIT>" % (self.precision,<EOL>self.scale))<EOL><DEDENT>else:<EOL><INDENT>if self.precision is not N... | :param v: is a number enclosed with string
:return: Decimal number | f2284:c18:m1 |
def _get_precision_scale(self, number): | try:<EOL><INDENT>decimal_num = Decimal(number)<EOL><DEDENT>except InvalidOperation:<EOL><INDENT>raise Invalid(self.msg or '<STR_LIT>')<EOL><DEDENT>return (len(decimal_num.as_tuple().digits), -(decimal_num.as_tuple().exponent), decimal_num)<EOL> | :param number:
:return: tuple(precision, scale, decimal_number) | f2284:c18:m3 |
def humanize_error(data, validation_error, max_sub_error_length=MAX_VALIDATION_ERROR_ITEM_LENGTH): | if isinstance(validation_error, MultipleInvalid):<EOL><INDENT>return '<STR_LIT:\n>'.join(sorted(<EOL>humanize_error(data, sub_error, max_sub_error_length)<EOL>for sub_error in validation_error.errors<EOL>))<EOL><DEDENT>else:<EOL><INDENT>offending_item_summary = repr(_nested_getitem(data, validation_error.path))<EOL>if ... | Provide a more helpful + complete validation error message than that provided automatically
Invalid and MultipleInvalid do not include the offending value in error messages,
and MultipleInvalid.__str__ only provides the first error. | f2285:m1 |
def Extra(_): | raise er.SchemaError('<STR_LIT>')<EOL> | Allow keys in the data that are not present in the schema. | f2288:m4 |
def _compile_scalar(schema): | if inspect.isclass(schema):<EOL><INDENT>def validate_instance(path, data):<EOL><INDENT>if isinstance(data, schema):<EOL><INDENT>return data<EOL><DEDENT>else:<EOL><INDENT>msg = '<STR_LIT>' % schema.__name__<EOL>raise er.TypeInvalid(msg, path)<EOL><DEDENT><DEDENT>return validate_instance<EOL><DEDENT>if callable(schema):<... | A scalar value.
The schema can either be a value or a type.
>>> _compile_scalar(int)([], 1)
1
>>> with raises(er.Invalid, 'expected float'):
... _compile_scalar(float)([], '1')
Callables have
>>> _compile_scalar(lambda v: float(v))([], '1')
1.0
As a convenience, ValueError's ar... | f2288:m5 |
def _compile_itemsort(): | def is_extra(key_):<EOL><INDENT>return key_ is Extra<EOL><DEDENT>def is_remove(key_):<EOL><INDENT>return isinstance(key_, Remove)<EOL><DEDENT>def is_marker(key_):<EOL><INDENT>return isinstance(key_, Marker)<EOL><DEDENT>def is_type(key_):<EOL><INDENT>return inspect.isclass(key_)<EOL><DEDENT>def is_callable(key_):<EOL><I... | return sort function of mappings | f2288:m6 |
def _iterate_mapping_candidates(schema): | <EOL>return sorted(iteritems(schema), key=_sort_item)<EOL> | Iterate over schema in a meaningful order. | f2288:m7 |
def _iterate_object(obj): | d = {}<EOL>try:<EOL><INDENT>d = vars(obj)<EOL><DEDENT>except TypeError:<EOL><INDENT>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>d = obj._asdict()<EOL><DEDENT><DEDENT>for item in iteritems(d):<EOL><INDENT>yield item<EOL><DEDENT>try:<EOL><INDENT>slots = obj.__slots__<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL>... | Return iterator over object attributes. Respect objects with
defined __slots__. | f2288:m8 |
def message(default=None, cls=None): | if cls and not issubclass(cls, er.Invalid):<EOL><INDENT>raise er.SchemaError("<STR_LIT>")<EOL><DEDENT>def decorator(f):<EOL><INDENT>@wraps(f)<EOL>def check(msg=None, clsoverride=None):<EOL><INDENT>@wraps(f)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>try:<EOL><INDENT>return f(*args, **kwargs)<EOL><DEDENT>except Value... | Convenience decorator to allow functions to provide a message.
Set a default message:
>>> @message('not an integer')
... def isint(v):
... return int(v)
>>> validate = Schema(isint())
>>> with raises(er.MultipleInvalid, 'not an integer'):
... validate('a')
... | f2288:m9 |
def _args_to_dict(func, args): | if sys.version_info >= (<NUM_LIT:3>, <NUM_LIT:0>):<EOL><INDENT>arg_count = func.__code__.co_argcount<EOL>arg_names = func.__code__.co_varnames[:arg_count]<EOL><DEDENT>else:<EOL><INDENT>arg_count = func.func_code.co_argcount<EOL>arg_names = func.func_code.co_varnames[:arg_count]<EOL><DEDENT>arg_value_list = list(args)<E... | Returns argument names as values as key-value pairs. | f2288:m10 |
def _merge_args_with_kwargs(args_dict, kwargs_dict): | ret = args_dict.copy()<EOL>ret.update(kwargs_dict)<EOL>return ret<EOL> | Merge args with kwargs. | f2288:m11 |
def validate(*a, **kw): | RETURNS_KEY = '<STR_LIT>'<EOL>def validate_schema_decorator(func):<EOL><INDENT>returns_defined = False<EOL>returns = None<EOL>schema_args_dict = _args_to_dict(func, a)<EOL>schema_arguments = _merge_args_with_kwargs(schema_args_dict, kw)<EOL>if RETURNS_KEY in schema_arguments:<EOL><INDENT>returns_defined = True<EOL>retu... | Decorator for validating arguments of a function against a given schema.
Set restrictions for arguments:
>>> @validate(arg1=int, arg2=int)
... def foo(arg1, arg2):
... return arg1 * arg2
Set restriction for returned value:
>>> @validate(arg=int, __return__=int)
... ... | f2288:m12 |
def __init__(self, schema, required=False, extra=PREVENT_EXTRA): | self.schema = schema<EOL>self.required = required<EOL>self.extra = int(extra) <EOL>self._compiled = self._compile(schema)<EOL> | Create a new Schema.
:param schema: Validation schema. See :module:`voluptuous` for details.
:param required: Keys defined in the schema must be in the data.
:param extra: Specify how extra keys in the data are treated:
- :const:`~voluptuous.PREVENT_EXTRA`: to disallow any undefined... | f2288:c1:m0 |
@classmethod<EOL><INDENT>def infer(cls, data, **kwargs):<DEDENT> | def value_to_schema_type(value):<EOL><INDENT>if isinstance(value, dict):<EOL><INDENT>if len(value) == <NUM_LIT:0>:<EOL><INDENT>return dict<EOL><DEDENT>return {k: value_to_schema_type(v)<EOL>for k, v in iteritems(value)}<EOL><DEDENT>if isinstance(value, list):<EOL><INDENT>if len(value) == <NUM_LIT:0>:<EOL><INDENT>return... | Create a Schema from concrete data (e.g. an API response).
For example, this will take a dict like:
{
'foo': 1,
'bar': {
'a': True,
'b': False
},
'baz': ['purple', 'monkey', 'dishwasher']
}
And return a Sc... | f2288:c1:m1 |
def __call__(self, data): | try:<EOL><INDENT>return self._compiled([], data)<EOL><DEDENT>except er.MultipleInvalid:<EOL><INDENT>raise<EOL><DEDENT>except er.Invalid as e:<EOL><INDENT>raise er.MultipleInvalid([e])<EOL><DEDENT> | Validate data against this schema. | f2288:c1:m6 |
def _compile_mapping(self, schema, invalid_msg=None): | invalid_msg = invalid_msg or '<STR_LIT>'<EOL>all_required_keys = set(key for key in schema<EOL>if key is not Extra and<EOL>((self.required and not isinstance(key, (Optional, Remove))) or<EOL>isinstance(key, Required)))<EOL>all_default_keys = set(key for key in schema<EOL>if isinstance(key, Required) or<EOL>isinstance(k... | Create validator for given mapping. | f2288:c1:m8 |
def _compile_object(self, schema): | base_validate = self._compile_mapping(<EOL>schema, invalid_msg='<STR_LIT>')<EOL>def validate_object(path, data):<EOL><INDENT>if schema.cls is not UNDEFINED and not isinstance(data, schema.cls):<EOL><INDENT>raise er.ObjectInvalid('<STR_LIT>'.format(schema.cls), path)<EOL><DEDENT>iterable = _iterate_object(data)<EOL>iter... | Validate an object.
Has the same behavior as dictionary validator but work with object
attributes.
For example:
>>> class Structure(object):
... def __init__(self, one=None, three=None):
... self.one = one
... self.three = th... | f2288:c1:m9 |
def _compile_dict(self, schema): | base_validate = self._compile_mapping(<EOL>schema, invalid_msg='<STR_LIT>')<EOL>groups_of_exclusion = {}<EOL>groups_of_inclusion = {}<EOL>for node in schema:<EOL><INDENT>if isinstance(node, Exclusive):<EOL><INDENT>g = groups_of_exclusion.setdefault(node.group_of_exclusion, [])<EOL>g.append(node)<EOL><DEDENT>elif isinst... | Validate a dictionary.
A dictionary schema can contain a set of values, or at most one
validator function/type.
A dictionary schema will only validate a dictionary:
>>> validate = Schema({})
>>> with raises(er.MultipleInvalid, 'expected a dictionary'):
... ... | f2288:c1:m10 |
def _compile_sequence(self, schema, seq_type): | _compiled = [self._compile(s) for s in schema]<EOL>seq_type_name = seq_type.__name__<EOL>def validate_sequence(path, data):<EOL><INDENT>if not isinstance(data, seq_type):<EOL><INDENT>raise er.SequenceTypeInvalid('<STR_LIT>' % seq_type_name, path)<EOL><DEDENT>if not schema:<EOL><INDENT>if data:<EOL><INDENT>raise er.Mult... | Validate a sequence type.
This is a sequence of valid values or validators tried in order.
>>> validator = Schema(['one', 'two', int])
>>> validator(['one'])
['one']
>>> with raises(er.MultipleInvalid, 'expected int @ data[0]'):
... validator([3.5])
>>> valida... | f2288:c1:m11 |
def _compile_tuple(self, schema): | return self._compile_sequence(schema, tuple)<EOL> | Validate a tuple.
A tuple is a sequence of valid values or validators tried in order.
>>> validator = Schema(('one', 'two', int))
>>> validator(('one',))
('one',)
>>> with raises(er.MultipleInvalid, 'expected int @ data[0]'):
... validator((3.5,))
>>> validato... | f2288:c1:m12 |
def _compile_list(self, schema): | return self._compile_sequence(schema, list)<EOL> | Validate a list.
A list is a sequence of valid values or validators tried in order.
>>> validator = Schema(['one', 'two', int])
>>> validator(['one'])
['one']
>>> with raises(er.MultipleInvalid, 'expected int @ data[0]'):
... validator([3.5])
>>> validator([1]... | f2288:c1:m13 |
def _compile_set(self, schema): | type_ = type(schema)<EOL>type_name = type_.__name__<EOL>def validate_set(path, data):<EOL><INDENT>if not isinstance(data, type_):<EOL><INDENT>raise er.Invalid('<STR_LIT>' % type_name, path)<EOL><DEDENT>_compiled = [self._compile(s) for s in schema]<EOL>errors = []<EOL>for value in data:<EOL><INDENT>for validate in _com... | Validate a set.
A set is an unordered collection of unique elements.
>>> validator = Schema({int})
>>> validator(set([42])) == set([42])
True
>>> with raises(er.Invalid, 'expected a set'):
... validator(42)
>>> with raises(er.MultipleInvalid, 'invalid value in... | f2288:c1:m14 |
def extend(self, schema, required=None, extra=None): | assert type(self.schema) == dict and type(schema) == dict, '<STR_LIT>'<EOL>result = self.schema.copy()<EOL>def key_literal(key):<EOL><INDENT>return (key.schema if isinstance(key, Marker) else key)<EOL><DEDENT>result_key_map = dict((key_literal(key), key) for key in result)<EOL>for key, value in iteritems(schema):<EOL><... | Create a new `Schema` by merging this and the provided `schema`.
Neither this `Schema` nor the provided `schema` are modified. The
resulting `Schema` inherits the `required` and `extra` parameters of
this, unless overridden.
Both schemas must be dictionary-based.
:param schema... | f2288:c1:m15 |
def chunk(seq, n):<EOL> | for i in range(<NUM_LIT:0>, len(seq), n):<EOL><INDENT>yield seq[i:i + n]<EOL><DEDENT> | Yield successive n-sized chunks from seq. | f2290:m1 |
def r_num(obj): | if isinstance(obj, (list, tuple)):<EOL><INDENT>it = iter<EOL><DEDENT>else:<EOL><INDENT>it = LinesIterator<EOL><DEDENT>dataset = Dataset([Dataset.FLOAT])<EOL>return dataset.load(it(obj))<EOL> | Read list of numbers. | f2292:m2 |
def r_date_num(obj, multiple=False): | if isinstance(obj, (list, tuple)):<EOL><INDENT>it = iter<EOL><DEDENT>else:<EOL><INDENT>it = LinesIterator<EOL><DEDENT>if multiple:<EOL><INDENT>datasets = {}<EOL>for line in it(obj):<EOL><INDENT>label = line[<NUM_LIT:2>]<EOL>if label not in datasets:<EOL><INDENT>datasets[label] = Dataset([Dataset.DATE, Dataset.FLOAT])<E... | Read date-value table. | f2292:m3 |
def plot_date(datasets, **kwargs): | defaults = {<EOL>'<STR_LIT>': True,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:title>': '<STR_LIT>',<EOL>'<STR_LIT>': None,<EOL>'<STR_LIT>': (<NUM_LIT:8>, <NUM_LIT:6>),<EOL>}<EOL>plot_params = {<EOL>'<STR_LIT>': '<STR_LIT:b>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': <NUM_LIT>,<EOL>... | Plot points with dates.
datasets can be Dataset object or list of Dataset. | f2294:m1 |
def similar_objects(self, num=None, **filters): | tags = self.tags<EOL>if not tags:<EOL><INDENT>return []<EOL><DEDENT>content_type = ContentType.objects.get_for_model(self.__class__)<EOL>filters['<STR_LIT>'] = content_type<EOL>lookup_kwargs = tags._lookup_kwargs()<EOL>lookup_keys = sorted(lookup_kwargs)<EOL>subq = tags.all()<EOL>qs = (tags.through.objects<EOL>.values(... | Find similar objects using related tags. | f2299:c0:m0 |
def get_public_comments_for_model(model): | if not IS_INSTALLED:<EOL><INDENT>return CommentModelStub.objects.none()<EOL><DEDENT>else:<EOL><INDENT>return CommentModel.objects.for_model(model).filter(is_public=True, is_removed=False)<EOL><DEDENT> | Get visible comments for the model. | f2301:m0 |
def get_comments_are_open(instance): | if not IS_INSTALLED:<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>mod = moderator._registry[instance.__class__]<EOL><DEDENT>except KeyError:<EOL><INDENT>return True<EOL><DEDENT>return CommentModerator.allow(mod, None, instance, None)<EOL> | Check if comments are open for the instance | f2301:m1 |
def get_comments_are_moderated(instance): | if not IS_INSTALLED:<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>mod = moderator._registry[instance.__class__]<EOL><DEDENT>except KeyError:<EOL><INDENT>return False<EOL><DEDENT>return CommentModerator.moderate(mod, None, instance, None)<EOL> | Check if comments are moderated for the instance | f2301:m2 |
@property<EOL><INDENT>def comments_are_open(self):<DEDENT> | if not self.enable_comments:<EOL><INDENT>return False<EOL><DEDENT>return get_comments_are_open(self)<EOL> | Check if comments are open | f2301:c2:m0 |
def import_settings_class(setting_name): | config_value = getattr(settings, setting_name)<EOL>if config_value is None:<EOL><INDENT>raise ImproperlyConfigured("<STR_LIT>".format(setting_name))<EOL><DEDENT>return import_class(config_value, setting_name)<EOL> | Return the class pointed to be an app setting variable. | f2315:m0 |
def import_class(import_path, setting_name=None): | mod_name, class_name = import_path.rsplit('<STR_LIT:.>', <NUM_LIT:1>)<EOL>mod = import_module_or_none(mod_name)<EOL>if mod is not None:<EOL><INDENT>try:<EOL><INDENT>return getattr(mod, class_name)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if setting_name:<EOL><INDENT>raise ImproperlyConfig... | Import a class by name. | f2315:m1 |
def import_apps_submodule(submodule): | found_apps = []<EOL>for appconfig in apps.get_app_configs():<EOL><INDENT>app = appconfig.name<EOL>if import_module_or_none('<STR_LIT>'.format(app, submodule)) is not None:<EOL><INDENT>found_apps.append(app)<EOL><DEDENT><DEDENT>return found_apps<EOL> | Look for a submodule is a series of packages, e.g. ".pagetype_plugins" in all INSTALLED_APPS. | f2315:m2 |
def import_module_or_none(module_label): | try:<EOL><INDENT>return importlib.import_module(module_label)<EOL><DEDENT>except ImportError:<EOL><INDENT>__, __, exc_traceback = sys.exc_info()<EOL>frames = traceback.extract_tb(exc_traceback)<EOL>frames = [f for f in frames<EOL>if f[<NUM_LIT:0>] != "<STR_LIT>" and <EOL>f[<NUM_LIT:0>] != IMPORT_PATH_IMPORTLIB and<EOL... | Imports the module with the given name.
Returns None if the module doesn't exist,
but it does propagates import errors in deeper modules. | f2315:m3 |
def request(self, **request): | environ = {<EOL>'<STR_LIT>': self.cookies,<EOL>'<STR_LIT>': '<STR_LIT:/>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT:GET>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>}<EOL>environ.update(self.defaults)<EOL>environ.update(requ... | Similar to parent class, but returns the request object as soon as it
has created it. | f2322:c0:m0 |
def get_version(svn=False, limit=<NUM_LIT:3>): | v = '<STR_LIT:.>'.join([str(i) for i in VERSION[:limit]])<EOL>if svn and limit >= <NUM_LIT:3>:<EOL><INDENT>from django.utils.version import get_svn_revision<EOL>import os<EOL>svn_rev = get_svn_revision(os.path.dirname(__file__))<EOL>if svn_rev:<EOL><INDENT>v = '<STR_LIT>' % (v, svn_rev)<EOL><DEDENT><DEDENT>return v<EOL... | Returns the version as a human-format string. | f2325:m0 |
def __getattribute__(self, name): | get = lambda p:super(MothertongueModelTranslate, self).__getattribute__(p)<EOL>translated_fields = get('<STR_LIT>')<EOL>if name in translated_fields:<EOL><INDENT>try:<EOL><INDENT>translation_set = get('<STR_LIT>')<EOL>code = translation.get_language()<EOL>translated_manager = get(translation_set)<EOL>try:<EOL><INDENT>t... | Specialise to look for translated content, note we use super's
__getattribute__ within this function to avoid a recursion error. | f2327:c0:m1 |
def t_newline(self, t): | t.lexer.lineno += t.value.count("<STR_LIT:\n>")<EOL> | r'\n+ | f2331:c0:m1 |
def p_statement_expr(self, t): | if len(t)<<NUM_LIT:3> :<EOL><INDENT>self.accu.add(Term('<STR_LIT:input>', [t[<NUM_LIT:1>]]))<EOL><DEDENT>else :<EOL><INDENT>self.accu.add(Term('<STR_LIT>', [t[<NUM_LIT:1>],t[<NUM_LIT:3>]]))<EOL>if t[<NUM_LIT:4>]!="<STR_LIT:?>" : self.accu.add(Term('<STR_LIT>', [t[<NUM_LIT:1>],t[<NUM_LIT:3>],t[<NUM_LIT:4>]]))<EOL><DEDEN... | statement : node_expression ARROW node_expression value
| node_expression | f2331:c1:m1 |
def p_node_expression(self, t): | t[<NUM_LIT:0>] = "<STR_LIT>"+t[<NUM_LIT:1>]+"<STR_LIT>"<EOL>self.accu.add(Term('<STR_LIT>', ["<STR_LIT>"+t[<NUM_LIT:1>]+"<STR_LIT>"]))<EOL> | node_expression : IDENT | f2331:c1:m2 |
def p_value(self, t): | if t[<NUM_LIT:1>] == '<STR_LIT:->' : t[<NUM_LIT:0>] = "<STR_LIT>"<EOL>elif t[<NUM_LIT:1>] == '<STR_LIT:+>' : t[<NUM_LIT:0>] = "<STR_LIT:1>"<EOL>elif t[<NUM_LIT:1>] == '<STR_LIT:?>' : t[<NUM_LIT:0>] = "<STR_LIT:?>"<EOL> | value : PLUS
| MINUS
| UNK | f2331:c1:m3 |
def is_consistent(instance): | return get_consistent_labelings(instance,<NUM_LIT:1>) != []<EOL> | [is_consistent(instance)] returns [True] if there exists a consistent extension
to the system described by the TermSet object [instance]. | f2332:m0 |
def get_consistent_labelings(instance,nmodels=<NUM_LIT:0>,exclude=[]): | <EOL>inst = instance.to_file()<EOL>prg = [ consistency_prg, inst, exclude_sol(exclude) ]<EOL>co = str(nmodels)<EOL>solver = GringoClasp(clasp_options=co)<EOL>models = solver.run(prg)<EOL>os.unlink(inst)<EOL>os.unlink(prg[<NUM_LIT:2>])<EOL>return models<EOL> | [consistent_labelings(instance,nmodels,exclude)] returns a list containing
[nmodels] TermSet objects representing consistent extensions of the system
described by the TermSet [instance]. The list [exclude] should contain TermSet objects
representing (maybe partial) solutions that are to be avoided. If [nmodels] equals ... | f2332:m1 |
def get_minimal_inconsistent_cores(instance,nmodels=<NUM_LIT:0>,exclude=[]): | inputs = get_reductions(instance)<EOL>prg = [ dyn_mic_prg, inputs.to_file(), instance.to_file(), exclude_sol(exclude) ]<EOL>options ='<STR_LIT>'+str(nmodels)<EOL>solver = GringoClasp(clasp_options=options)<EOL>models = solver.run(prg, collapseTerms=True, collapseAtoms=False)<EOL>os.unlink(prg[<NUM_LIT:1>])<EOL>o... | [compute_mic(instance,nmodels,exclude)] returns a list containing
[nmodels] TermSet objects representing subset minimal inconsistent cores of the system
described by the TermSet [instance]. The list [exclude] should contain TermSet objects
representing (maybe partial) solutions that are to be avoided. If [nmodels] equa... | f2332:m2 |
def get_predictions_under_minimal_repair(instance, repair_options, optimum): | inst = instance.to_file()<EOL>repops = repair_options.to_file()<EOL>prg = [ inst, repops, prediction_core_prg, repair_cardinality_prg ]<EOL>options = '<STR_LIT>'+str(optimum)<EOL>solver = GringoClasp(clasp_options=options)<EOL>models = solver.run(prg, collapseTerms=True, collapseAtoms=False)<EOL>os.unlink(ins... | Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates | f2332:m12 |
def whatsnew(instance,pred): | accu = TermSet(pred)<EOL>for t in instance:<EOL><INDENT>if t.pred() == '<STR_LIT>':<EOL><INDENT>[_,e,v,s] = t.explode()<EOL>accu.discard(Term('<STR_LIT>',[e,v,s]))<EOL><DEDENT>elif t.p('<STR_LIT>'):<EOL><INDENT>[_,j,i,s] = t.explode()<EOL>accu.discard(Term('<STR_LIT>',[j,i,s]))<EOL><DEDENT><DEDENT>return accu<EOL> | [whatsnew(instance,pred)] is a TermSet equal to [pred] where all predicates
vlabel and elabel which have a corresponding obs_vlabel and obs_elabel in
[instance] have been deleted. This function is meant to see which of the invariants
are not a direct consequence of the observations. | f2332:m14 |
def get_predictions_under_consistency(instance): | inst = instance.to_file()<EOL>prg = [ prediction_prg, inst, exclude_sol([]) ]<EOL>solver = GringoClasp(clasp_options='<STR_LIT>')<EOL>models = solver.run(prg, collapseTerms=True, collapseAtoms=False)<EOL>os.unlink(inst)<EOL>os.unlink(prg[<NUM_LIT:2>])<EOL>return whatsnew(instance,models[<NUM_LIT:0>])<EOL> | Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates | f2332:m15 |
def t_newline(self, t): | t.lexer.lineno += t.value.count("<STR_LIT:\n>")<EOL> | r'\n+ | f2334:c0:m1 |
def p_statement_expr(self, t): | if len(t)<<NUM_LIT:3> :<EOL><INDENT>self.accu.add(Term('<STR_LIT:input>', [t[<NUM_LIT:1>]]))<EOL>print('<STR_LIT:input>', t[<NUM_LIT:1>])<EOL><DEDENT>else :<EOL><INDENT>self.accu.add(Term('<STR_LIT>', ["<STR_LIT>"+t[<NUM_LIT:1>]+"<STR_LIT>","<STR_LIT>"+t[<NUM_LIT:3>]+"<STR_LIT>"]))<EOL>self.accu.add(Term('<STR_LIT>', [... | statement : node_expression PLUS node_expression
| node_expression MINUS node_expression | f2334:c1:m1 |
def p_node_expression(self, t): | if len(t)<<NUM_LIT:3> :<EOL><INDENT>t[<NUM_LIT:0>]=t[<NUM_LIT:1>]<EOL>self.accu.add(Term('<STR_LIT>', ["<STR_LIT>"+t[<NUM_LIT:1>]+"<STR_LIT>"]))<EOL><DEDENT>else : t[<NUM_LIT:0>] = "<STR_LIT>"<EOL> | node_expression : IDENT | f2334:c1:m2 |
def _inputLoop(self): | try:<EOL><INDENT>while self.alive:<EOL><INDENT>try:<EOL><INDENT>c = console.getkey() <EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>print('<STR_LIT>')<EOL>c = serial.to_bytes([<NUM_LIT:3>])<EOL><DEDENT>if c == self.EXIT_CHARACTER: <EOL><INDENT>self.stop()<EOL><DEDENT>elif c == '<STR_LIT:\n>':<EOL... | Loop and copy console->serial until EXIT_CHARCTER character is found. | f2337:c0:m5 |
def _color(self, color, msg): | if self.useColor:<EOL><INDENT>return '<STR_LIT>'.format(color, msg, self.RESET_SEQ)<EOL><DEDENT>else:<EOL><INDENT>return msg<EOL><DEDENT> | Converts a message to be printed to the user's terminal in red | f2337:c1:m2 |
def _boldFace(self, msg): | return self._color(self.BOLD_SEQ, msg)<EOL> | Converts a message to be printed to the user's terminal in bold | f2337:c1:m3 |
def _inputLoop(self): | <EOL>actionChars = {self.EXIT_CHARACTER: self._exit,<EOL>self.EXIT_CHARACTER_2: self._exit,<EOL>console.CURSOR_LEFT: self._cursorLeft,<EOL>console.CURSOR_RIGHT: self._cursorRight,<EOL>console.CURSOR_UP: self._cursorUp,<EOL>console.CURSOR_DOWN: self._cursorDown,<EOL>'<STR_LIT:\n>': self._doConfirmInput,<EOL>'<STR_LIT:\t... | Loop and copy console->serial until EXIT_CHARCTER character is found. | f2337:c1:m6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.