text
stringlengths
81
112k
Recursively visit the comparators and apply the operations on them. def visit_Compare(self, node: ast.Compare) -> Any: """Recursively visit the comparators and apply the operations on them.""" # pylint: disable=too-many-branches left = self.visit(node=node.left) comparators = [self.vis...
Visit the function and the arguments and finally make the function call with them. def visit_Call(self, node: ast.Call) -> Any: """Visit the function and the arguments and finally make the function call with them.""" func = self.visit(node=node.func) args = [] # type: List[Any] for ar...
Visit the ``test``, and depending on its outcome, the ``body`` or ``orelse``. def visit_IfExp(self, node: ast.IfExp) -> Any: """Visit the ``test``, and depending on its outcome, the ``body`` or ``orelse``.""" test = self.visit(node=node.test) if test: result = self.visit(node=node....
Visit the node's ``value`` and get the attribute from the result. def visit_Attribute(self, node: ast.Attribute) -> Any: """Visit the node's ``value`` and get the attribute from the result.""" value = self.visit(node=node.value) if not isinstance(node.ctx, ast.Load): raise NotImplem...
Visit the node's ``value``. def visit_Index(self, node: ast.Index) -> Any: """Visit the node's ``value``.""" result = self.visit(node=node.value) self.recomputed_values[node] = result return result
Visit ``lower``, ``upper`` and ``step`` and recompute the node as a ``slice``. def visit_Slice(self, node: ast.Slice) -> slice: """Visit ``lower``, ``upper`` and ``step`` and recompute the node as a ``slice``.""" lower = None # type: Optional[int] if node.lower is not None: lower =...
Visit each dimension of the advanced slicing and assemble the dimensions in a tuple. def visit_ExtSlice(self, node: ast.ExtSlice) -> Tuple[Any, ...]: """Visit each dimension of the advanced slicing and assemble the dimensions in a tuple.""" result = tuple(self.visit(node=dim) for dim in node.dims) ...
Visit the ``slice`` and a ``value`` and get the element. def visit_Subscript(self, node: ast.Subscript) -> Any: """Visit the ``slice`` and a ``value`` and get the element.""" value = self.visit(node=node.value) a_slice = self.visit(node=node.slice) result = value[a_slice] self...
Compile the generator or comprehension from the node and execute the compiled code. def _execute_comprehension(self, node: Union[ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp]) -> Any: """Compile the generator or comprehension from the node and execute the compiled code.""" args = [ast.arg(...
Compile the generator expression as a function and call it. def visit_GeneratorExp(self, node: ast.GeneratorExp) -> Any: """Compile the generator expression as a function and call it.""" result = self._execute_comprehension(node=node) for generator in node.generators: self.visit(ge...
Compile the list comprehension as a function and call it. def visit_ListComp(self, node: ast.ListComp) -> Any: """Compile the list comprehension as a function and call it.""" result = self._execute_comprehension(node=node) for generator in node.generators: self.visit(generator.iter...
Compile the set comprehension as a function and call it. def visit_SetComp(self, node: ast.SetComp) -> Any: """Compile the set comprehension as a function and call it.""" result = self._execute_comprehension(node=node) for generator in node.generators: self.visit(generator.iter) ...
Compile the dictionary comprehension as a function and call it. def visit_DictComp(self, node: ast.DictComp) -> Any: """Compile the dictionary comprehension as a function and call it.""" result = self._execute_comprehension(node=node) for generator in node.generators: self.visit(ge...
Raise an exception that this node is unexpected. def visit_Return(self, node: ast.Return) -> Any: # pylint: disable=no-self-use """Raise an exception that this node is unexpected.""" raise AssertionError("Unexpected return node during the re-computation: {}".format(ast.dump(node)))
Raise an exception that this node has not been handled. def generic_visit(self, node: ast.AST) -> None: """Raise an exception that this node has not been handled.""" raise NotImplementedError("Unhandled recomputation of the node: {} {}".format(type(node), node))
Tokenize input text to words. :param string: Text to tokenize :type string: str or unicode :return: words :rtype: list of strings def tokenize_words(string): """ Tokenize input text to words. :param string: Text to tokenize :type string: str or unicode :return: words :rtype: l...
Tokenize input text to sentences. :param string: Text to tokenize :type string: str or unicode :return: sentences :rtype: list of strings def tokenize_sents(string): """ Tokenize input text to sentences. :param string: Text to tokenize :type string: str or unicode :return: sentenc...
Tokenize input text to paragraphs, sentences and words. Tokenization to paragraphs is done using simple Newline algorithm For sentences and words tokenizers above are used :param string: Text to tokenize :type string: str or unicode :return: text, tokenized into paragraphs, sentences and words ...
:type graph: VariantGraph :type collation: Collation def collate(self, graph, collation): ''' :type graph: VariantGraph :type collation: Collation ''' # Build the variant graph for the first witness # this is easy: generate a vertex for every token first_...
Every step we have 3 choices: 1) Move pointer witness a --> omission 2) Move pointer witness b --> addition 3) Move pointer of both witness a/b --> match Note: a replacement is omission followed by an addition or the other way around Choice 1 and 2 are only possible if token a ...
:type source: integer :type target: integer def connect(self, source, target, witnesses): """ :type source: integer :type target: integer """ # print("Adding Edge: "+source+":"+target) if self.graph.has_edge(source, target): self.graph[source][target]...
:type source: integer :type target: integer def connect_near(self, source, target, weight): # Near edges are added to self.near_graph, not self.graph, to avoid cycles """ :type source: integer :type target: integer """ self.near_graph.add_edge(source, target, wei...
:type graph: VariantGraph def merge(self, graph, witness_sigil, witness_tokens, alignments={}): """ :type graph: VariantGraph """ # NOTE: token_to_vertex only contains newly generated vertices token_to_vertex = {} last = graph.start for token in witness_tokens: ...
:type graph: VariantGraph def collate(self, graph): """ :type graph: VariantGraph """ # prepare the token index self.token_index.prepare() self.vertex_array = [None] * len(self.token_index.token_array) # Build the variant graph for the first witness # th...
Parse string of comma-separated x-y/step -like ranges def _parse(self, pattern): """Parse string of comma-separated x-y/step -like ranges""" # Comma separated ranges if pattern.find(',') < 0: subranges = [pattern] else: subranges = pattern.split(',') for...
Class method that returns a new RangeSet with ranges from provided list. def fromlist(cls, rnglist, autostep=None): """Class method that returns a new RangeSet with ranges from provided list.""" inst = RangeSet(autostep=autostep) inst.updaten(rnglist) return inst
Class method that returns a new RangeSet of one single item or a single range (from integer or slice object). def fromone(cls, index, pad=0, autostep=None): """Class method that returns a new RangeSet of one single item or a single range (from integer or slice object).""" inst = RangeSe...
Set autostep value (property) def set_autostep(self, val): """Set autostep value (property)""" if val is None: # disabled by default for pdsh compat (+inf is 1E400, but a bug in # python 2.4 makes it impossible to be pickled, so we use less) # NOTE: Later, we could c...
Iterate over each (optionally padded) string element in RangeSet. def striter(self): """Iterate over each (optionally padded) string element in RangeSet.""" pad = self.padding or 0 for i in self._sorted(): yield "%0*d" % (pad, i)
Object-based iterator over contiguous range sets. def contiguous(self): """Object-based iterator over contiguous range sets.""" pad = self.padding or 0 for sli in self._contiguous_slices(): yield RangeSet.fromone(slice(sli.start, sli.stop, sli.step), pad)
Stringify slices list (x-y/step format) def _strslices(self): """Stringify slices list (x-y/step format)""" pad = self.padding or 0 for sli in self.slices(): if sli.start + 1 == sli.stop: yield "%0*d" % (pad, sli.start) else: assert sli.st...
Internal iterator over contiguous slices in RangeSet. def _contiguous_slices(self): """Internal iterator over contiguous slices in RangeSet.""" k = j = None for i in self._sorted(): if k is None: k = j = i if i - j > 1: yield slice(k, j + ...
Internal generator that is able to retrieve ranges organized by step. Complexity: O(n) with n = number of ranges in tree. def _folded_slices(self): """Internal generator that is able to retrieve ranges organized by step. Complexity: O(n) with n = number of ranges in tree.""" if len(self...
Split the rangeset into nbr sub-rangesets (at most). Each sub-rangeset will have the same number of elements more or less 1. Current rangeset remains unmodified. Returns an iterator. >>> RangeSet("1-5").split(3) RangeSet("1-2") RangeSet("3-4") RangeSet("foo5") ...
Add a range (start, stop, step and padding length) to RangeSet. Like the Python built-in function range(), the last element is the largest start + i * step less than stop. def add_range(self, start, stop, step=1, pad=0): """ Add a range (start, stop, step and padding length) to RangeSet...
Return a shallow copy of a RangeSet. def copy(self): """Return a shallow copy of a RangeSet.""" cpy = self.__class__() cpy._autostep = self._autostep cpy.padding = self.padding cpy.update(self) return cpy
Wrap built-in set operations for RangeSet to workaround built-in set base class issues (RangeSet.__new/init__ not called) def _wrap_set_op(self, fun, arg): """Wrap built-in set operations for RangeSet to workaround built-in set base class issues (RangeSet.__new/init__ not called)""" res...
Return the intersection of two RangeSets as a new RangeSet. (I.e. all elements that are in both sets.) def intersection(self, other): """Return the intersection of two RangeSets as a new RangeSet. (I.e. all elements that are in both sets.) """ #NOTE: This is a work around ...
Return the difference of two RangeSets as a new RangeSet. (I.e. all elements that are in this set and not in the other.) def difference(self, other): """Return the difference of two RangeSets as a new RangeSet. (I.e. all elements that are in this set and not in the other.) """ ...
Report whether another set contains this RangeSet. def issubset(self, other): """Report whether another set contains this RangeSet.""" self._binary_sanity_check(other) return set.issubset(self, other)
Report whether this RangeSet contains another set. def issuperset(self, other): """Report whether this RangeSet contains another set.""" self._binary_sanity_check(other) return set.issuperset(self, other)
Remove all elements of another set from this RangeSet. If strict is True, raise KeyError if an element cannot be removed. (strict is a RangeSet addition) def difference_update(self, other, strict=False): """Remove all elements of another set from this RangeSet. If stri...
Add all integers from an iterable (such as a list). def update(self, iterable): """Add all integers from an iterable (such as a list).""" if isinstance(iterable, RangeSet): # keep padding unless is has not been defined yet if self.padding is None and iterable.padding is not None...
Update a rangeset with the union of itself and several others. def updaten(self, rangesets): """ Update a rangeset with the union of itself and several others. """ for rng in rangesets: if isinstance(rng, set): self.update(rng) else: ...
Add an element to a RangeSet. This has no effect if the element is already present. def add(self, element, pad=0): """Add an element to a RangeSet. This has no effect if the element is already present. """ set.add(self, int(element)) if pad > 0 and self.padding is None: ...
Remove element from the RangeSet if it is a member. If the element is not a member, do nothing. def discard(self, element): """Remove element from the RangeSet if it is a member. If the element is not a member, do nothing. """ try: i = int(element) set....
Universal open file facility. With normal files, this function behaves as the open builtin. With gzip-ed files, it decompress or compress according to the specified mode. In addition, when filename is '-', it opens the standard input or output according to the specified mode. Mode are expected to be...
Stable sort of the sequence a according to the keys given in r. >>> a=range(5) >>> b=[0]*5 >>> r=[2,1,3,0,4] >>> _radixPass(a, b, r, 5, 5) >>> b [3, 1, 0, 2, 4] When n is less than the length of a, the end of b must be left unaltered. >>> b=[5]*5 >>> _radixPass(a, b, r, 2, 2) ...
Exact number of atomic operations in _radixPass. def _nbOperations(n): """ Exact number of atomic operations in _radixPass. """ if n < 2: return 0 else: n0 = (n + 2) // 3 n02 = n0 + n // 3 return 3 * (n02) + n0 + _nbOperations(n02)
This function is a rewrite in Python of the C implementation proposed in Kärkkäinen and Sanders paper. Find the suffix array SA of s[0..n-1] in {1..K}^n Require s[n]=s[n+1]=s[n+2]=0, n>=2 def _suffixArrayWithTrace(s, SA, n, K, operations, totalOperations): """ This function is a rewrite in Python of t...
Returns the length of the longest common prefix of seq1 starting at offset start1 and seq2 starting at offset start2. >>> _longestCommonPrefix("abcdef", "abcghj") 3 >>> _longestCommonPrefix("abcghj", "abcdef") 3 >>> _longestCommonPrefix("miss", "") 0 >>> _longestCommonPrefix("", "mr"...
Compute the longest common prefix for every adjacent suffixes. The result is a list of same size as SA. Given two suffixes at positions i and i+1, their LCP is stored at position i+1. A zero is stored at position 0 of the output. >>> SA=SuffixArray("abba", unit=UNIT_BYTE) >>> SA._LCP_values ...
Command line option parser. def parseArgv(): """ Command line option parser. """ parser = OptionParser() parser.usage = r""" cat <TEXT> | %prog [--unit <UNIT>] [--output <SA_FILE>] Create the suffix array of TEXT with the processing UNIT and optionally store it in SA_FILE for subsequent use. UNIT ...
Entry point for the standalone script. def main(): """ Entry point for the standalone script. """ (options, strings) = parseArgv() global _suffixArray, _trace ############# # Verbosity # ############# _trace = options.verbose ################### # Processing unit # ##...
Add a feature to the suffix array. The callback must return a sequence such that the feature at position i is attached to the suffix referenced by self.SA[i]. It is called with one argument: the instance of SuffixArray self. The callback may traverse self.SA in any fashion. ...
Add a feature to the suffix array. The callback must return the feature corresponding to the suffix at position self.SA[i]. The callback must be callable (a function or lambda). The argument names of the callback are used to determine the data needed. If an argument is the name ...
Tokenizer utility. When processing byte, outputs the string unaltered. The character unit type is used for unicode data, the string is decoded according to the encoding provided. In the case of word unit, EOL characters are detached from the preceding word, and outputs the list o...
Output a string of length tokens in the original form. If string is an integer, it is considered as an offset in the text. Otherwise string is considered as a sequence of ids (see voc and tokId). >>> SA=SuffixArray('mississippi', UNIT_BYTE) >>> SA.reprString(0, 3) 'mis' ...
Save the suffix array instance including all features attached in filename. Accept any filename following the _open conventions, for example if it ends with .gz the file created will be a compressed GZip file. def toFile(self, filename): """ Save the suffix array instance includ...
Load a suffix array instance from filename, a file created by toFile. Accept any filename following the _open conventions. def fromFile(cls, filename): """ Load a suffix array instance from filename, a file created by toFile. Accept any filename following the _open conve...
>>> SA=SuffixArray("mississippi", unit=UNIT_BYTE) >>> SA._findOne("ippi") 1 >>> SA._findOne("missi") 4 def _findOne(self, subString): """ >>> SA=SuffixArray("mississippi", unit=UNIT_BYTE) >>> SA._findOne("ippi") 1 >>> SA._findOne("missi") ...
Dichotomy search of subString in the suffix array. As soon as a suffix which starts with subString is found, it uses the LCPs in order to find the other matching suffixes. The outputs consists in a list of tuple (pos, feature0, feature1, ...) where feature0, feature1, ... are the featur...
Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag `quote` is `True`, the quotation mark character (") is also translated. There is a special handling for `None` which escapes to an empty string. :param s: the string to escape. :param quote: set to true to al...
Add a new entry to the feed. This function can either be called with a :class:`FeedEntry` or some keyword and positional arguments that are forwarded to the :class:`FeedEntry` constructor. def add(self, *args, **kwargs): """Add a new entry to the feed. This function can either be called ...
Return a generator that yields pieces of XML. def generate(self): """Return a generator that yields pieces of XML.""" # atom demands either an author element in every entry or a global one if not self.author: if False in map(lambda e: bool(e.author), self.entries): s...
Yields pieces of ATOM XML. def generate(self): """Yields pieces of ATOM XML.""" base = '' if self.xml_base: base = ' xml:base="%s"' % escape(self.xml_base, True) yield u'<entry%s>\n' % base yield u' ' + _make_text_block('title', self.title, self.title_type) ...
Temporarily override config values. This is similar to :py:func:`django.test.override_settings`,\ use it in testing. :param new_cache_values: Keyword arguments,\ the key should match one in the config,\ a new one is created otherwise,\ the value is overridden within\ the decorated function...
Form values serialization :param object value: A value to be serialized\ for saving it into the database and later\ loading it into the form as initial value def serialize(value, field): """ Form values serialization :param object value: A value to be serialized\ for saving it into the da...
Get version without importing the lib def get_version(package): """Get version without importing the lib""" with io.open(os.path.join(BASE_DIR, package, '__init__.py'), encoding='utf-8') as fh: return [ l.split('=', 1)[1].strip().strip("'").strip('"') for l in fh.readlines() ...
Check :py:class:`djconfig.middleware.DjConfigMiddleware`\ is registered into ``settings.MIDDLEWARE_CLASSES`` def _check_backend(): """ Check :py:class:`djconfig.middleware.DjConfigMiddleware`\ is registered into ``settings.MIDDLEWARE_CLASSES`` """ # Django 1.10 does not allow # both setting...
Register a config form into the registry :param object form_class: The form class to register.\ Must be an instance of :py:class:`djconfig.forms.ConfigForm` :param bool check_middleware: Check\ :py:class:`djconfig.middleware.DjConfigMiddleware`\ is registered into ``settings.MID...
Gets every registered form's field value.\ If a field name is found in the db, it will load it from there.\ Otherwise, the initial value from the field form is used def _reload(self): """ Gets every registered form's field value.\ If a field name is found in the db, it will load...
Reload the config if the config\ model has been updated. This is called\ once on every request by the middleware.\ Should not be called directly. def _reload_maybe(self): """ Reload the config if the config\ model has been updated. This is called\ once on every r...
Save the config with the cleaned data,\ update the last modified date so\ the config is reloaded on other process/nodes.\ Reload the config so it can be called right away. def save(self): """ Save the config with the cleaned data,\ update the last modified date so\ ...
Register a new admin section. :param conf: A subclass of ``djconfig.admin.Config`` :param conf_admin: A subclass of ``djconfig.admin.ConfigAdmin`` :param options: Extra options passed to ``django.contrib.admin.site.register`` def register(conf, conf_admin, **options): """ Register a new admin sect...
Mixed type, used to indicate a field in a schema can be one of many types. Use as a last resort only. The Mixed type can be used directly as a class to indicate any type is permitted for a given field: `"my_field": {"type": Mixed}` It can also be instantiated with list of specific types the fiel...
Validates that a field value matches one of the values given to this validator. def one_of(*args): """ Validates that a field value matches one of the values given to this validator. """ if len(args) == 1 and isinstance(args[0], list): items = args[0] else: items = list(args...
Validates that a field value is greater than or equal to the value given to this validator. def gte(min_value): """ Validates that a field value is greater than or equal to the value given to this validator. """ def validate(value): if value < min_value: return e("{} is not ...
Validates that a field value is less than or equal to the value given to this validator. def lte(max_value): """ Validates that a field value is less than or equal to the value given to this validator. """ def validate(value): if value > max_value: return e("{} is not less t...
Validates that a field value is greater than the value given to this validator. def gt(gt_value): """ Validates that a field value is greater than the value given to this validator. """ def validate(value): if value <= gt_value: return e("{} is not greater than {}", value, g...
Validates that a field value is less than the value given to this validator. def lt(lt_value): """ Validates that a field value is less than the value given to this validator. """ def validate(value): if value >= lt_value: return e("{} is not less than {}", value, lt_value) ...
Validates that a field value is between the two values given to this validator. def between(min_value, max_value): """ Validates that a field value is between the two values given to this validator. """ def validate(value): if value < min_value: return e("{} is not greater t...
Validates that a field value's length is between the bounds given to this validator. def length(min=None, max=None): """ Validates that a field value's length is between the bounds given to this validator. """ def validate(value): if min and len(value) < min: return e("{} d...
Validates that a field value matches the regex given to this validator. def match(pattern): """ Validates that a field value matches the regex given to this validator. """ regex = re.compile(pattern) def validate(value): if not regex.match(value): return e("{} does not match th...
Validates that a fields value is a valid email address. def is_email(): """ Validates that a fields value is a valid email address. """ email = ( ur'(?!^\.)' # No dot at start ur'(?!.*\.@)' # No dot before at sign ur'(?!.*@\.)' # No dot after at sign ur'(?!.*\.$...
Validates that a fields value is a valid URL. def is_url(): """ Validates that a fields value is a valid URL. """ # Stolen from Django regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'...
A wrapper which applies the given validators to each item in a field value of type `list`. Example usage in a Schema: "my_list_field": {"type": Array(int), "validates": each_item(lte(10))} def each_item(*validators): """ A wrapper which applies the given validators to each item in a field val...
Validates that all items in the given field list value are distinct, i.e. that the list contains no duplicates. def distinct(): """ Validates that all items in the given field list value are distinct, i.e. that the list contains no duplicates. """ def validate(value): for i, item in enu...
Applies the defaults described by the this schema to the given document instance as appropriate. Defaults are only applied to fields which are currently unset. def apply_defaults(self, instance): """Applies the defaults described by the this schema to the given document instance as appr...
Validates the given document against this schema. Raises a ValidationException if there are any failures. def validate(self, instance): """Validates the given document against this schema. Raises a ValidationException if there are any failures.""" errors = {} self._validate_inst...
Verifies that this schema's doc spec is valid and makes sense. def _verify(self, path_prefix=None): """Verifies that this schema's doc spec is valid and makes sense.""" for field, spec in self.doc_spec.iteritems(): path = self._append_path(path_prefix, field) # Standard dict-ba...
Verifies a given field specification is valid, recursing into nested schemas if required. def _verify_field_spec(self, spec, path): """Verifies a given field specification is valid, recursing into nested schemas if required.""" # Required should be a boolean if 'required' in spec and not isins...
Verify that the 'type' in the spec is valid def _verify_type(self, spec, path): """Verify that the 'type' in the spec is valid""" field_type = spec['type'] if isinstance(field_type, Schema): # Nested documents cannot have validation if not set(spec.keys()).issubset(set(...
Verifies that the default specified in the given spec is valid. def _verify_default(self, spec, path): """Verifies that the default specified in the given spec is valid.""" field_type = spec['type'] default = spec['default'] # If it's a function there's nothing we can really do except ...
Verify thats the 'validates' argument is valid. def _verify_validates(self, spec, path): """Verify thats the 'validates' argument is valid.""" validates = spec['validates'] if isinstance(validates, list): for validator in validates: self._verify_validator(validator,...
Verifies that a given validator associated with the field at the given path is legitimate. def _verify_validator(self, validator, path): """Verifies that a given validator associated with the field at the given path is legitimate.""" # Validator should be a function if not callable(validator):...
Validates that the given instance of a document conforms to the given schema's structure and validations. Any validation errors are added to the given errors collection. The caller should assume the instance is considered valid if the errors collection is empty when this method returns. def _va...
Validates that the given field value is valid given the associated field spec and path. Any validation failures are added to the given errors collection. def _validate_value(self, value, field_spec, path, errors): """Validates that the given field value is valid given the associated fie...
Loads and parses an INI style configuration file using Python's built-in configparser module. If path is specified, load it. If ``defaults`` (a list of strings) is given, try to load each entry as a file, without throwing any error if the operation fails. If ``defaults`` is not given, the following loca...
Converts a ConfigParser object into a dictionary. The resulting dictionary has sections as keys which point to a dict of the sections options as key => value pairs. def as_dict(config): """ Converts a ConfigParser object into a dictionary. The resulting dictionary has sections as keys which point...