Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _get_alternation(extractors, text):
"""Tries each extractor on the given text and returns the 'best fit'.
Best fit is defined by as the extractor whose result consumed the most text. If more than one
extractor is the best fit, the result of the one that appeared earliest in the list is returned.
If all ex... |
def _get_repetition(extractor, text, *, bounds=(0, None), ignore_whitespace=False):
"""Tries to pull text with extractor repeatedly.
Bounds is a 2-tuple of (lbound, ubound) where lbound is a number and ubound is a number or None.
If the ubound is None, this method will execute extractor on text until extrator ra... |
def _get_exclusion(extractor, exclusion, text):
"""Returns extractor's result if exclusion does not match.
If exclusion raises DeadEnd (meaning it did not match) then the result of extractor(text) is
returned. Otherwise, if exclusion does not raise DeadEnd it means it did match, and we then
raise DeadEnd.
""... |
def _split_ignored(text, ignore_whitespace=True):
"""Return (leading whitespace, trailing text) if ignore_whitespace is true, or ("", text) if
False.
"""
if ignore_whitespace:
leading_ws_count = _count_leading_whitespace(text)
ignored_ws = text[:leading_ws_count]
use_text = text[leading_ws_count:]
... |
def _count_leading_whitespace(text):
"""Returns the number of characters at the beginning of text that are whitespace."""
idx = 0
for idx, char in enumerate(text):
if not char.isspace():
return idx
return idx + 1 |
def _call_extractor(extractor, text):
"""This method calls an extractor on some text.
If extractor is just a string, it is passed as the first value to _get_terminal. Otherwise it is
treated as a callable and text is passed directly to it.
This makes it so you can have a shorthand of terminal(val) <-> val.
... |
def position(self):
"""Gets the position of the text the ParseNode processed. If the ParseNode does not have its
own position, it looks to its first child for its position.
'Value Nodes' (terminals) must have their own position, otherwise this method will throw an
exception when it tries to get the pos... |
def is_empty(self):
"""Returns True if this node has no children, or if all of its children are ParseNode instances
and are empty.
"""
return all(isinstance(c, ParseNode) and c.is_empty for c in self.children) |
def add_ignored(self, ignored):
"""Add ignored text to the node. This will add the length of the ignored text to the node's
consumed property.
"""
if ignored:
if self.ignored:
self.ignored = ignored + self.ignored
else:
self.ignored = ignored
self.consumed += len(ignored... |
def is_type(self, value):
"""Returns True if node_type == value.
If value is a tuple, node_type is checked against each member and True is returned if any of
them match.
"""
if isinstance(value, tuple):
for opt in value:
if self.node_type == opt:
return True
return Fal... |
def flattened(self, pred=flattened_pred_default):
"""Flattens nodes by hoisting children up to ancestor nodes.
A node is hoisted if pred(node) returns True.
"""
if self.is_value:
return self
new_children = []
for child in self.children:
if child.is_empty:
continue
n... |
def trimmed(self, pred=trimmed_pred_default):
"""Trim a ParseTree.
A node is trimmed if pred(node) returns True.
"""
new_children = []
for child in self.children:
if isinstance(child, ParseNode):
new_child = child.trimmed(pred)
else:
new_child = child
if not pred... |
def merged(self, other):
"""Returns a new ParseNode whose type is this node's type, and whose children are all the
children from this node and the other whose length is not 0.
"""
children = [c for c in itertools.chain(self.children, other.children) if len(c) > 0]
# NOTE: Only terminals should have ... |
def retyped(self, new_type):
"""Returns a new node with the same contents as self, but with a new node_type."""
return ParseNode(new_type,
children=list(self.children),
consumed=self.consumed,
position=self.position,
ignored... |
def compressed(self, new_type=None, *, include_ignored=False):
"""Turns the node into a value node, whose single string child is the concatenation of all its
children.
"""
values = []
consumed = 0
ignored = None
for i, child in enumerate(self.children):
consumed += child.consumed
... |
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
ApiCli.get_arguments(self)
# Get the host group name
if self.args.host_group_name is not None:
self.host_group_name = self.args.host_group_name
# Get the list of sources sep... |
def get_scope_list(self) -> list:
"""
Return the list of all contained scope from global to local
"""
# by default only return scoped name
lstparent = [self]
p = self.get_parent()
while p is not None:
lstparent.append(p)
p = p.get_parent()
... |
def get_scope_names(self) -> list:
"""
Return the list of all contained scope from global to local
"""
# allow global scope to have an None string instance
lscope = []
for scope in reversed(self.get_scope_list()):
if scope.name is not None:
# h... |
def position(self) -> Position:
"""The current position of the cursor."""
return Position(self._index, self._lineno, self._col_offset) |
def max_readed_position(self) -> Position:
"""The index of the deepest character readed."""
return Position(self._maxindex, self._maxline, self._maxcol) |
def step_next_char(self):
"""Puts the cursor on the next character."""
self._index += 1
self._col_offset += 1
if self._index > self._maxindex:
self._maxindex = self._index
self._maxcol = self._col_offset
self._maxline = self._lineno |
def step_next_line(self):
"""Sets cursor as beginning of next line."""
self._eol.append(self.position)
self._lineno += 1
self._col_offset = 0 |
def step_prev_line(self):
"""Sets cursor as end of previous line."""
#TODO(bps): raise explicit error for unregistered eol
#assert self._eol[-1].index == self._index
if len(self._eol) > 0:
self.position = self._eol.pop() |
def last_readed_line(self) -> str:
"""Usefull string to compute error message."""
mpos = self._cursor.max_readed_position
mindex = mpos.index
# search last \n
prevline = mindex - 1 if mindex == self.eos_index else mindex
while prevline >= 0 and self._content[prevline] != ... |
def incpos(self, length: int=1) -> int:
"""Increment the cursor to the next character."""
if length < 0:
raise ValueError("length must be positive")
i = 0
while (i < length):
if self._cursor.index < self._len:
if self.peek_char == '\n':
... |
def save_context(self) -> bool:
"""Save current position."""
self._contexts.append(self._cursor.position)
return True |
def restore_context(self) -> bool:
"""Rollback to previous saved position."""
self._cursor.position = self._contexts.pop()
return False |
def to_fmt(self) -> fmt.indentable:
"""
Return an Fmt representation for pretty-printing
"""
qual = "scope"
txt = fmt.sep(" ", [qual])
name = self.show_name()
if name != "":
txt.lsdata.append(name)
if len(self._hsig) > 0 or len(self.mapTypeTranslate) > 0:
lsb = []
... |
def to_fmt(self):
"""
Return an Fmt representation for pretty-printing
"""
qual = "evalctx"
lseval = []
block = fmt.block(":\n", "", fmt.tab(lseval))
txt = fmt.sep(" ", [qual, block])
lseval.append(self._sig.to_fmt())
if len(self.resolution) > 0:
lsb = []
for k in sor... |
def to_fmt(self, with_from=False) -> fmt.indentable:
"""
Return a Fmt representation of Translator for pretty-printing
"""
txt = fmt.sep("\n", [
fmt.sep(
" ",
[
self._type_source,
"to",
self._type_target,
'='... |
def to_fmt(self):
"""
Return an Fmt representation for pretty-printing
"""
params = ""
txt = fmt.sep(" ", ['val'])
name = self.show_name()
if name != "":
txt.lsdata.append(name)
txt.lsdata.append('(%s)' % self.value)
txt.lsdata.append(': ' + self.tret)
return txt |
def to_fmt(self):
"""
Return an Fmt representation for pretty-printing
"""
params = ""
txt = fmt.sep(" ", ['fun'])
name = self.show_name()
if name != "":
txt.lsdata.append(name)
tparams = []
if self.tparams is not None:
tparams = list(self.tparams)
if self.variadi... |
def walk(self, lc: state.LivingContext, user_data=None, parent=None):
"""
TODO: should_test_type??
"""
global _cacheid
# root node autorefence
if parent is None:
parent = self
## walk attributes
if hasattr(self, '__dict__') and not isinstance(self, node.ListNode):
for k i... |
def set_name(self, name: str):
""" You could set the name after construction """
self.name = name
# update internal names
lsig = self._hsig.values()
self._hsig = {}
for s in lsig:
self._hsig[s.internal_name()] = s |
def count_types(self) -> int:
""" Count subtypes """
n = 0
for s in self._hsig.values():
if type(s).__name__ == 'Type':
n += 1
return n |
def count_vars(self) -> int:
""" Count var define by this scope """
n = 0
for s in self._hsig.values():
if hasattr(s, 'is_var') and s.is_var:
n += 1
return n |
def count_funs(self) -> int:
""" Count function define by this scope """
n = 0
for s in self._hsig.values():
if hasattr(s, 'is_fun') and s.is_fun:
n += 1
return n |
def __update_count(self):
""" Update internal counters """
self._ntypes = self.count_types()
self._nvars = self.count_vars()
self._nfuns = self.count_funs() |
def update(self, sig: list or Scope) -> Scope:
""" Update the Set with values of another Set """
values = sig
if hasattr(sig, 'values'):
values = sig.values()
for s in values:
if self.is_namespace:
s.set_parent(self)
if isinstance(s, Sc... |
def union(self, sig: Scope) -> Scope:
""" Create a new Set produce by the union of 2 Set """
new = Scope(sig=self._hsig.values(), state=self.state)
new |= sig
return new |
def intersection_update(self, oset: Scope) -> Scope:
""" Update Set with common values of another Set """
keys = list(self._hsig.keys())
for k in keys:
if k not in oset:
del self._hsig[k]
else:
self._hsig[k] = oset.get(k)
return sel... |
def intersection(self, sig: Scope) -> Scope:
""" Create a new Set produce by the intersection of 2 Set """
new = Scope(sig=self._hsig.values(), state=self.state)
new &= sig
return new |
def difference_update(self, oset: Scope) -> Scope:
""" Remove values common with another Set """
keys = list(self._hsig.keys())
for k in keys:
if k in oset:
del self._hsig[k]
return self |
def difference(self, sig: Scope) -> Scope:
""" Create a new Set produce by a Set subtracted by another Set """
new = Scope(sig=self._hsig.values(), state=self.state)
new -= sig
return new |
def symmetric_difference_update(self, oset: Scope) -> Scope:
""" Remove common values
and Update specific values from another Set
"""
skey = set()
keys = list(self._hsig.keys())
for k in keys:
if k in oset:
skey.add(k)
for k in oset... |
def symmetric_difference(self, sig: Scope) -> Scope:
""" Create a new Set with values present in only one Set """
new = Scope(sig=self._hsig.values(), state=self.state)
new ^= sig
return new |
def add(self, it: Signature) -> bool:
""" Add it to the Set """
if isinstance(it, Scope):
it.state = StateScope.EMBEDDED
txt = it.internal_name()
it.set_parent(self)
if self.is_namespace:
txt = it.internal_name()
if txt == "":
txt = '_'... |
def remove(self, it: Signature) -> bool:
""" Remove it but raise KeyError if not found """
txt = it.internal_name()
if txt not in self._hsig:
raise KeyError(it.show_name() + ' not in Set')
sig = self._hsig[txt]
if isinstance(sig, Scope):
sig.state = StateS... |
def discard(self, it: Signature) -> bool:
""" Remove it only if present """
txt = it.internal_name()
if txt in self._hsig:
sig = self._hsig[txt]
if isinstance(sig, Scope):
sig.state = StateScope.LINKED
del self._hsig[txt]
return Tru... |
def values(self) -> [Signature]:
""" Retrieve all values """
if self.state == StateScope.EMBEDDED and self.parent is not None:
return list(self._hsig.values()) + list(self.parent().values())
else:
return self._hsig.values() |
def first(self) -> Signature:
""" Retrieve the first Signature ordered by mangling descendant """
k = sorted(self._hsig.keys())
return self._hsig[k[0]] |
def last(self) -> Signature:
""" Retrieve the last Signature ordered by mangling descendant """
k = sorted(self._hsig.keys())
return self._hsig[k[-1]] |
def get(self, key: str, default=None) -> Signature:
""" Get a signature instance by its internal_name """
item = default
if key in self._hsig:
item = self._hsig[key]
return item |
def get_by_symbol_name(self, name: str) -> Scope:
""" Retrieve a Set of all signature by symbol name """
lst = []
for s in self.values():
if s.name == name:
# create an EvalCtx only when necessary
lst.append(EvalCtx.from_sig(s))
# include paren... |
def getsig_by_symbol_name(self, name: str) -> Signature:
""" Retrieve the unique Signature of a symbol.
Fail if the Signature is not unique
"""
subscope = self.get_by_symbol_name(name)
if len(subscope) != 1:
raise KeyError("%s have multiple candidates in scope" % name... |
def get_by_return_type(self, tname: str) -> Scope:
""" Retrieve a Set of all signature by (return) type """
lst = []
for s in self.values():
if hasattr(s, 'tret') and s.tret == tname:
lst.append(EvalCtx.from_sig(s))
rscope = Scope(sig=lst, state=StateScope.LIN... |
def get_all_polymorphic_return(self) -> bool:
""" For now, polymorphic return type are handle by symbol artefact.
--> possible multi-polymorphic but with different constraint attached!
"""
lst = []
for s in self.values():
if hasattr(s, 'tret') and s.tret.is_polymorph... |
def get_by_params(self, params: [Scope]) -> (Scope, [[Scope]]):
""" Retrieve a Set of all signature that match the parameter list.
Return a pair:
pair[0] the overloads for the functions
pair[1] the overloads for the parameters
(a list of candidate list of paramet... |
def callInjector(self, old: Node, trans: Translator) -> Node:
""" If don't have injector call from parent """
if self.astTranslatorInjector is None:
if self.parent is not None:
# TODO: think if we forward for all StateScope
# forward to parent scope
... |
def findTranslationTo(self, t2: str) -> (bool, Signature, Translator):
""" Find an arrow (->)
aka a function able to translate something to t2
"""
if not t2.is_polymorphic:
collect = []
for s in self.values():
t1 = s.tret
if t1.is_p... |
def normalize(ast: Node) -> Node:
"""
Normalize an AST nodes.
all builtins containers are replace by referencable subclasses
"""
res = ast
typemap = {DictNode, ListNode, TupleNode}
if type(ast) is dict:
res = DictNode(ast)
elif type(ast) is list:
res = ListNode(ast)
... |
def check(self, ndict: dict, info="") -> bool:
"""
Debug method, help detect cycle and/or
other incoherence in a tree of Node
"""
def iscycle(thing, ndict: dict, info: str) -> bool:
# check if not already here
idthing = id(thing)
ndict[info] = ... |
def set(self, othernode):
"""allow to completly mutate the node into any subclasses of Node"""
self.__class__ = othernode.__class__
self.clean()
if len(othernode) > 0:
for k, v in othernode.items():
self[k] = v
for k, v in vars(othernode).items():
... |
def values(self):
"""
in order
"""
tmp = self
while tmp is not None:
yield tmp.data
tmp = tmp.next |
def rvalues(self):
"""
in reversed order
"""
tmp = self
while tmp is not None:
yield tmp.data
tmp = tmp.prev |
def _pixel_masked(hit, array):
''' Checks whether a hit (column/row) is masked or not. Array is 2D array with boolean elements corresponding to pixles indicating whether a pixel is disabled or not.
'''
if array.shape[0] > hit["column"] and array.shape[1] > hit["row"]:
return array[hit["column"], hit... |
def _finish_cluster(hits, clusters, cluster_size, cluster_hit_indices, cluster_index, cluster_id, charge_correction, noisy_pixels, disabled_pixels):
''' Set hit and cluster information of the cluster (e.g. number of hits in the cluster (cluster_size), total cluster charge (charge), ...).
'''
cluster_charge ... |
def _finish_event(hits, clusters, start_event_hit_index, stop_event_hit_index, start_event_cluster_index, stop_event_cluster_index):
''' Set hit and cluster information of the event (e.g. number of cluster in the event (n_cluster), ...).
'''
for hit_index in range(start_event_hit_index, stop_event_hit_index... |
def _hit_ok(hit, min_hit_charge, max_hit_charge):
''' Check if given hit is withing the limits.
'''
# Omit hits with charge < min_hit_charge
if hit['charge'] < min_hit_charge:
return False
# Omit hits with charge > max_hit_charge
if max_hit_charge != 0 and hit['charge'] > max_hit_charge... |
def _set_1d_array(array, value, size=-1):
''' Set array elemets to value for given number of elements (if size is negative number set all elements to value).
'''
if size >= 0:
for i in range(size):
array[i] = value
else:
for i in range(array.shape[0]):
array[i] = ... |
def _is_in_max_difference(value_1, value_2, max_difference):
''' Helper function to determine the difference of two values that can be np.uints. Works in python and numba mode.
Circumvents numba bug #1653
'''
if value_1 <= value_2:
return value_2 - value_1 <= max_difference
return value_1 - ... |
def _cluster_hits(hits, clusters, assigned_hit_array, cluster_hit_indices, column_cluster_distance, row_cluster_distance, frame_cluster_distance, min_hit_charge, max_hit_charge, ignore_same_hits, noisy_pixels, disabled_pixels):
''' Main precompiled function that loopes over the hits and clusters them
'''
to... |
def get_compute_sig(self) -> Signature:
"""
Compute a signature Using resolution!!!
TODO: discuss of relevance of a final generation for a signature
"""
tret = []
tparams = []
for t in self.tret.components:
if t in self.resolution and self.resolution[... |
def set_parent(self, parent) -> object:
"""
When we add a parent (from Symbol), don't forget to resolve.
"""
ret = self
if parent is not None:
ret = self._sig.set_parent(parent)
self.resolve()
elif not hasattr(self, 'parent'):
# only if... |
def resolve(self):
"""
Process the signature and find definition for type.
"""
# collect types for resolution
t2resolv = []
if hasattr(self._sig, 'tret'):
t2resolv.append(self._sig.tret)
if hasattr(self._sig, 'tparams') and self._sig.tparams is not Non... |
def get_resolved_names(self, type_name: TypeName) -> list:
"""
Use self.resolution to subsitute type_name.
Allow to instanciate polymorphic type ?1, ?toto
"""
if not isinstance(type_name, TypeName):
raise Exception("Take a TypeName as parameter not a %s"
... |
def set_resolved_name(self, ref: dict, type_name2solve: TypeName,
type_name_ref: TypeName):
"""
Warning!!! Need to rethink it when global poly type
"""
if self.resolution[type_name2solve.value] is None:
self.resolution[type_name2solve.value] = ref[ty... |
def to_fmt(self) -> fmt.indentable:
"""
Return an Fmt representation for pretty-printing
"""
lsb = []
if len(self._lsig) > 0:
for s in self._lsig:
lsb.append(s.to_fmt())
block = fmt.block("(", ")", fmt.sep(', ', lsb))
qual = "tuple"
... |
def internal_name(self):
"""
Return the unique internal name
"""
unq = super().internal_name()
if self.tret is not None:
unq += "_" + self.tret
return unq |
def _delete_local(self, filename):
"""Deletes the specified file from the local filesystem."""
if os.path.exists(filename):
os.remove(filename) |
def _delete_s3(self, filename, bucket_name):
"""Deletes the specified file from the given S3 bucket."""
conn = S3Connection(self.access_key_id, self.access_key_secret)
bucket = conn.get_bucket(bucket_name)
if type(filename).__name__ == 'Key':
filename = '/' + filename.name
... |
def delete(self, filename, storage_type=None, bucket_name=None):
"""Deletes the specified file, either locally or from S3, depending on the file's storage type."""
if not (storage_type and bucket_name):
self._delete_local(filename)
else:
if storage_type != 's3':
... |
def _save_local(self, temp_file, filename, obj):
"""Saves the specified file to the local file system."""
path = self._get_path(filename)
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path), self.permission | 0o111)
fd = open(path, 'wb')
... |
def _save_s3(self, temp_file, filename, obj):
"""Saves the specified file to the configured S3 bucket."""
conn = S3Connection(self.access_key_id, self.access_key_secret)
bucket = conn.get_bucket(self.bucket_name)
path = self._get_s3_path(filename)
k = bucket.new_key(path)
... |
def save(self, temp_file, filename, obj):
"""Saves the specified file to either S3 or the local filesystem, depending on the currently enabled storage type."""
if not (self.storage_type and self.bucket_name):
ret = self._save_local(temp_file, filename, obj)
else:
if self... |
def _find_by_path_s3(self, path, bucket_name):
"""Finds files by licking an S3 bucket's contents by prefix."""
conn = S3Connection(self.access_key_id, self.access_key_secret)
bucket = conn.get_bucket(bucket_name)
s3_path = self._get_s3_path(path)
return bucket.list(prefix=s3_p... |
def find_by_path(self, path, storage_type=None, bucket_name=None):
"""Finds files at the specified path / prefix, either on S3 or on the local filesystem."""
if not (storage_type and bucket_name):
return self._find_by_path_local(path)
else:
if storage_type != 's3':
... |
def enum(*sequential, **named):
"""
Build an enum statement
"""
#: build enums from parameter
enums = dict(zip(sequential, range(len(sequential))), **named)
enums['map'] = copy.copy(enums)
#: build reverse mapping
enums['rmap'] = {}
for key, value in enums.items():
if type(va... |
def checktypes(func):
"""Decorator to verify arguments and return types."""
sig = inspect.signature(func)
types = {}
for param in sig.parameters.values():
# Iterate through function's parameters and build the list of
# arguments types
param_type = param.annotation
if par... |
def set_one(chainmap, thing_name, callobject):
""" Add a mapping with key thing_name for callobject in chainmap with
namespace handling.
"""
namespaces = reversed(thing_name.split("."))
lstname = []
for name in namespaces:
lstname.insert(0, name)
strname = '.'.join(lstname)
... |
def add_method(cls):
"""Attach a method to a class."""
def wrapper(f):
#if hasattr(cls, f.__name__):
# raise AttributeError("{} already has a '{}' attribute".format(
# cls.__name__, f.__name__))
setattr(cls, f.__name__, f)
return f
return wrapper |
def hook(cls, hookname=None, erase=False):
"""Attach a method to a parsing class and register it as a parser hook.
The method is registered with its name unless hookname is provided.
"""
if not hasattr(cls, '_hooks'):
raise TypeError(
"%s didn't seems to be a BasicParser subsclas... |
def rule(cls, rulename=None, erase=False):
"""Attach a method to a parsing class and register it as a parser rule.
The method is registered with its name unless rulename is provided.
"""
if not hasattr(cls, '_rules'):
raise TypeError(
"%s didn't seems to be a BasicParser subsclas... |
def directive(directname=None):
"""Attach a class to a parsing class and register it as a parser directive.
The class is registered with its name unless directname is provided.
"""
global _directives
class_dir_list = _directives
def wrapper(f):
nonlocal directname
if direct... |
def decorator(directname=None):
"""
Attach a class to a parsing decorator and register it to the global
decorator list.
The class is registered with its name unless directname is provided
"""
global _decorators
class_deco_list = _decorators
def wrapper(f):
nonlocal d... |
def bind(self, dst: str, src: Node) -> bool:
"""Allow to alias a node to another name.
Useful to bind a node to _ as return of Rule::
R = [
__scope__:L [item:I #add_item(L, I]* #bind('_', L)
]
It's also the default behaviour of ':>'
"""
for m in self.rule_nodes.maps:... |
def read_eol(self) -> bool:
"""Return True if the parser can consume an EOL byte sequence."""
if self.read_eof():
return False
self._stream.save_context()
self.read_char('\r')
if self.read_char('\n'):
return self._stream.validate_context()
return self._stream.restore_context() |
def read_hex_integer(self) -> bool:
"""
read a hexadecimal number
Read the following BNF rule else return False::
readHexInteger = [
[ '0'..'9' | 'a'..'f' | 'A'..'F' ]+
]
"""
if self.read_eof():
return False
self._stream.save_context()
c = self._stream.pe... |
def read_cstring(self) -> bool:
"""
read a double quoted string
Read following BNF rule else return False::
'"' -> ['\\' #char | ~'\\'] '"'
"""
self._stream.save_context()
idx = self._stream.index
if self.read_char("\"") and self.read_until("\"", "\\"):
txt = self._stream[i... |
def push_rule_nodes(self) -> bool:
"""Push context variable to store rule nodes."""
if self.rule_nodes is None:
self.rule_nodes = collections.ChainMap()
self.tag_cache = collections.ChainMap()
self.id_cache = collections.ChainMap()
else:
self.rule_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.