INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Simply convert a string type to bytes if the value is a string and is an instance of six. string_types but not of six. binary_type in python2 struct. pack ( <Q ) is both string_types and binary_type but in python3 struct. pack ( <Q ) is binary_type but not a string_types: param value:: param binary:: return:
def str_to_bytes(value): """ Simply convert a string type to bytes if the value is a string and is an instance of six.string_types but not of six.binary_type in python2 struct.pack("<Q") is both string_types and binary_type but in python3 struct.pack("<Q") is binary_type but not a string_types :...
Evaluate focus node focus in graph g against shape shape in ShEx schema schema
def evaluate(g: Graph, schema: Union[str, ShExJ.Schema], focus: Optional[Union[str, URIRef, IRIREF]], start: Optional[Union[str, URIRef, IRIREF, START, START_TYPE]]=None, debug_trace: bool = False) -> Tuple[bool, Optional[str]]: """ Evaluate focus node `focus` in ...
5. 2 Validation Definition <http:// shex. io/ shex - semantics/ #validation > _
def isValid(cntxt: Context, m: FixedShapeMap) -> Tuple[bool, List[str]]: """`5.2 Validation Definition <http://shex.io/shex-semantics/#validation>`_ The expression isValid(G, m) indicates that for every nodeSelector/shapeLabel pair (n, s) in m, s has a corresponding shape expression se and satisfies(n,...
Check that imports in test_imports succeed otherwise display message in install_hints
def check_sysdeps(vext_files): """ Check that imports in 'test_imports' succeed otherwise display message in 'install_hints' """ @run_in_syspy def run(*modules): result = {} for m in modules: if m: try: __import__(m) ...
copy vext_file to sys. prefix +/ share/ vext/ specs
def install_vexts(vext_files, verify=True): """ copy vext_file to sys.prefix + '/share/vext/specs' (PIP7 seems to remove data_files so we recreate something similar here) """ if verify and not check_sysdeps(vext_files): return spec_dir = join(prefix, 'share/vext/specs') try: ...
Create the default PTH file: return:
def create_pth(): """ Create the default PTH file :return: """ if prefix == '/usr': print("Not creating PTH in real prefix: %s" % prefix) return False with open(vext_pth, 'w') as f: f.write(DEFAULT_PTH_CONTENT) return True
Return the turtle representation of subj as a collection
def format_collection(g: Graph, subj: Union[URIRef, BNode], max_entries: int = None, nentries: int = 0) -> Optional[List[str]]: """ Return the turtle representation of subj as a collection :param g: Graph containing subj :param subj: subject of list :param max_entries: maximum number of list elemen...
: param name: name in format helper. path_name
def get_extra_path(name): """ :param name: name in format helper.path_name sip.default_sip_dir """ # Paths are cached in path_cache helper_name, _, key = name.partition(".") helper = path_helpers.get(helper_name) if not helper: raise ValueError("Helper '{0}' not found.".format(h...
setuptools 12. 2 can trigger a really nasty bug that eats all memory so upgrade it to 18. 8 which is known to be good.
def upgrade_setuptools(): """ setuptools 12.2 can trigger a really nasty bug that eats all memory, so upgrade it to 18.8, which is known to be good. """ # Note - I tried including the higher version in # setup_requires, but was still able to trigger # the bug. - stu.axon global MIN_S...
: return: list of installed packages
def installed_packages(self): """ :return: list of installed packages """ packages = [] CMDLINE = [sys.executable, "-mpip", "freeze"] try: for package in subprocess.check_output(CMDLINE) \ .decode('utf-8'). \ splitlines(): ...
: return: list of package info on installed packages
def package_info(self): """ :return: list of package info on installed packages """ import subprocess # create a commandline like pip show Pillow show package_names = self.installed_packages() if not package_names: # No installed packages yet, so noth...
List of packages that depend on dependency: param dependency: package name e. g. vext or Pillow
def depends_on(self, dependency): """ List of packages that depend on dependency :param dependency: package name, e.g. 'vext' or 'Pillow' """ packages = self.package_info() return [package for package in packages if dependency in package.get("requires", "")]
: return: Absolute paths to any provided vext files
def find_vext_files(self): """ :return: Absolute paths to any provided vext files """ packages = self.depends_on("vext") vext_files = [] for location in [package.get("location") for package in packages]: if not location: continue v...
Need to find any pre - existing vext contained in dependent packages and install them
def run(self): """ Need to find any pre-existing vext contained in dependent packages and install them example: you create a setup.py with install_requires["vext.gi"]: - vext.gi gets installed using bdist_egg - vext itself is now called with bdist_egg and we en...
Iter to a list of servers and instantiate Protocol class.
def set_servers(self, servers): """ Iter to a list of servers and instantiate Protocol class. :param servers: A list of servers :type servers: list :return: Returns nothing :rtype: None """ if isinstance(servers, six.string_types): servers = [...
Send a command to server flush|delete all keys.
def flush_all(self, time=0): """ Send a command to server flush|delete all keys. :param time: Time to wait until flush in seconds. :type time: int :return: True in case of success, False in case of failure :rtype: bool """ returns = [] for server ...
Return server stats.
def stats(self, key=None): """ Return server stats. :param key: Optional if you want status from a key. :type key: six.string_types :return: A dict with server stats :rtype: dict """ # TODO: Stats with key is not working. returns = {} for...
Data from http:// indexed. blogspot. com/ 2007/ 12/ meltdown - indeed. html
def house_explosions(): """ Data from http://indexed.blogspot.com/2007/12/meltdown-indeed.html """ chart = PieChart2D(int(settings.width * 1.7), settings.height) chart.add_data([10, 10, 30, 200]) chart.set_pie_labels([ 'Budding Chemists', 'Propane issues', 'Meth Labs', ...
http:// shex. io/ shex - semantics/ #values
def objectValueMatches(n: Node, vsv: ShExJ.objectValue) -> bool: """ http://shex.io/shex-semantics/#values Implements "n = vsv" where vsv is an objectValue and n is a Node Note that IRIREF is a string pattern, so the matching type is str """ return \ (isinstance(vsv, IRIREF) and isinstance...
Compare: py: class: rdflib. URIRef value with: py: class: ShExJ. IRIREF value
def uriref_matches_iriref(v1: URIRef, v2: Union[str, ShExJ.IRIREF]) -> bool: """ Compare :py:class:`rdflib.URIRef` value with :py:class:`ShExJ.IRIREF` value """ return str(v1) == str(v2)
Determine whether a: py: class: rdflib. URIRef value starts with the text of a: py: class: ShExJ. IRIREF value
def uriref_startswith_iriref(v1: URIRef, v2: Union[str, ShExJ.IRIREF]) -> bool: """ Determine whether a :py:class:`rdflib.URIRef` value starts with the text of a :py:class:`ShExJ.IRIREF` value """ return str(v1).startswith(str(v2))
Compare: py: class: rdflib. Literal with: py: class: ShExJ. objectLiteral
def literal_matches_objectliteral(v1: Literal, v2: ShExJ.ObjectLiteral) -> bool: """ Compare :py:class:`rdflib.Literal` with :py:class:`ShExJ.objectLiteral` """ v2_lit = Literal(str(v2.value), datatype=iriref_to_uriref(v2.type), lang=str(v2.language) if v2.language else None) return v1 == v2_lit
5. 4. 1 Semantics <http:// shex. io/ shex - semantics/ #node - constraint - semantics > _
def satisfiesNodeConstraint(cntxt: Context, n: Node, nc: ShExJ.NodeConstraint, _: DebugContext) -> bool: """ `5.4.1 Semantics <http://shex.io/shex-semantics/#node-constraint-semantics>`_ For a node n and constraint nc, satisfies2(n, nc) if and only if for every nodeKind, datatype, xsFacet and values constr...
5. 4. 2 Node Kind Constraints <http:// shex. io/ shex - semantics/ #nodeKind > _
def nodeSatisfiesNodeKind(cntxt: Context, n: Node, nc: ShExJ.NodeConstraint, c: DebugContext) -> bool: """ `5.4.2 Node Kind Constraints <http://shex.io/shex-semantics/#nodeKind>`_ For a node n and constraint value v, nodeSatisfies(n, v) if: * v = "iri" and n is an IRI. * v = "bnode" and n is a...
5. 4. 3 Datatype Constraints <http:// shex. io/ shex - semantics/ #datatype > _
def nodeSatisfiesDataType(cntxt: Context, n: Node, nc: ShExJ.NodeConstraint, c: DebugContext) -> bool: """ `5.4.3 Datatype Constraints <http://shex.io/shex-semantics/#datatype>`_ For a node n and constraint value v, nodeSatisfies(n, v) if n is an Literal with the datatype v and, if v is in the set of SPARQ...
5. 4. 5 XML Schema String Facet Constraints <ttp:// shex. io/ shex - semantics/ #xs - string > _
def nodeSatisfiesStringFacet(cntxt: Context, n: Node, nc: ShExJ.NodeConstraint, _c: DebugContext) -> bool: """ `5.4.5 XML Schema String Facet Constraints <ttp://shex.io/shex-semantics/#xs-string>`_ String facet constraints apply to the lexical form of the RDF Literals and IRIs and blank node identifiers ...
5. 4. 5 XML Schema Numeric Facet Constraints <http:// shex. io/ shex - semantics/ #xs - numeric > _
def nodeSatisfiesNumericFacet(cntxt: Context, n: Node, nc: ShExJ.NodeConstraint, _c: DebugContext) -> bool: """ `5.4.5 XML Schema Numeric Facet Constraints <http://shex.io/shex-semantics/#xs-numeric>`_ Numeric facet constraints apply to the numeric value of RDF Literals with datatypes listed in SPARQL 1.1 ...
5. 4. 5 Values Constraint <http:// shex. io/ shex - semantics/ #values > _
def nodeSatisfiesValues(cntxt: Context, n: Node, nc: ShExJ.NodeConstraint, _c: DebugContext) -> bool: """ `5.4.5 Values Constraint <http://shex.io/shex-semantics/#values>`_ For a node n and constraint value v, nodeSatisfies(n, v) if n matches some valueSetValue vsv in v. """ if nc.values is None: ...
A term matches a valueSetValue if: * vsv is an objectValue and n = vsv. * vsv is a Language with langTag lt and n is a language - tagged string with a language tag l and l = lt. * vsv is a IriStem LiteralStem or LanguageStem with stem st and nodeIn ( n st ). * vsv is a IriStemRange LiteralStemRange or LanguageStemRange...
def _nodeSatisfiesValue(cntxt: Context, n: Node, vsv: ShExJ.valueSetValue) -> bool: """ A term matches a valueSetValue if: * vsv is an objectValue and n = vsv. * vsv is a Language with langTag lt and n is a language-tagged string with a language tag l and l = lt. * vsv is a IriStem, Lite...
** nodeIn **: asserts that an RDF node n is equal to an RDF term s or is in a set defined by a: py: class: ShExJ. IriStem: py: class: LiteralStem or: py: class: LanguageStem.
def nodeInIriStem(_: Context, n: Node, s: ShExJ.IriStem) -> bool: """ **nodeIn**: asserts that an RDF node n is equal to an RDF term s or is in a set defined by a :py:class:`ShExJ.IriStem`, :py:class:`LiteralStem` or :py:class:`LanguageStem`. The expression `nodeInIriStem(n, s)` is satisfied i...
http:// shex. io/ shex - semantics/ #values
def nodeInLiteralStem(_: Context, n: Node, s: ShExJ.LiteralStem) -> bool: """ http://shex.io/shex-semantics/#values **nodeIn**: asserts that an RDF node n is equal to an RDF term s or is in a set defined by a :py:class:`ShExJ.IriStem`, :py:class:`LiteralStem` or :py:class:`LanguageStem`. T...
http:// shex. io/ shex - semantics/ #values
def nodeInLanguageStem(_: Context, n: Node, s: ShExJ.LanguageStem) -> bool: """ http://shex.io/shex-semantics/#values **nodeIn**: asserts that an RDF node n is equal to an RDF term s or is in a set defined by a :py:class:`ShExJ.IriStem`, :py:class:`LiteralStem` or :py:class:`LanguageStem`. ...
http:// shex. io/ shex - semantics/ #values
def nodeInBnodeStem(_cntxt: Context, _n: Node, _s: Union[str, ShExJ.Wildcard]) -> bool: """ http://shex.io/shex-semantics/#values **nodeIn**: asserts that an RDF node n is equal to an RDF term s or is in a set defined by a :py:class:`ShExJ.IriStem`, :py:class:`LiteralStem` or :py:class:`LanguageSte...
Decorator to run a function in the system python
def run_in_syspy(f): """ Decorator to run a function in the system python :param f: :return: """ fname = f.__name__ code_lines = inspect.getsource(f).splitlines() code = dedent("\n".join(code_lines[1:])) # strip this decorator # add call to the function and print it's result ...
: return: True if in running from a virtualenv
def in_venv(): """ :return: True if in running from a virtualenv Has to detect the case where the python binary is run directly, so VIRTUAL_ENV may not be set """ global _in_venv if _in_venv is not None: return _in_venv if not (os.path.isfile(ORIG_PREFIX_TXT) or os.path.isfile(...
: return: list of site - packages from system python
def getsyssitepackages(): """ :return: list of site-packages from system python """ global _syssitepackages if not _syssitepackages: if not in_venv(): _syssitepackages = get_python_lib() return _syssitepackages @run_in_syspy def run(*args): ...
: return: system python executable
def findsyspy(): """ :return: system python executable """ if not in_venv(): return sys.executable python = basename(realpath(sys.executable)) prefix = None if HAS_ORIG_PREFIX_TXT: with open(ORIG_PREFIX_TXT) as op: prefix = op.read() elif HAS_PY_VENV_CFG: ...
Delete a key/ value from server. If key does not exist it returns True.
def delete(self, key, cas=0): """ Delete a key/value from server. If key does not exist, it returns True. :param key: Key's name to be deleted :param cas: CAS of the key :return: True in case o success and False in case of failure. """ server = self._get_server(k...
Set a value for a key on server.
def set(self, key, value, time=0, compress_level=-1): """ Set a value for a key on server. :param key: Key's name :type key: str :param value: A value to be stored on server. :type value: object :param time: Time in seconds that your key will expire. :typ...
Set multiple keys with it s values on server.
def set_multi(self, mappings, time=0, compress_level=-1): """ Set multiple keys with it's values on server. :param mappings: A dict with keys/values :type mappings: dict :param time: Time in seconds that your key will expire. :type time: int :param compress_level...
Add a key/ value to server ony if it does not exist.
def add(self, key, value, time=0, compress_level=-1): """ Add a key/value to server ony if it does not exist. :param key: Key's name :type key: six.string_types :param value: A value to be stored on server. :type value: object :param time: Time in seconds that yo...
Replace a key/ value to server ony if it does exist.
def replace(self, key, value, time=0, compress_level=-1): """ Replace a key/value to server ony if it does exist. :param key: Key's name :type key: six.string_types :param value: A value to be stored on server. :type value: object :param time: Time in seconds tha...
Get multiple keys from server.
def get_multi(self, keys, get_cas=False): """ Get multiple keys from server. :param keys: A list of keys to from server. :type keys: list :param get_cas: If get_cas is true, each value is (data, cas), with each result's CAS value. :type get_cas: boolean :return: ...
Set a value for a key on server if its CAS value matches cas.
def cas(self, key, value, cas, time=0, compress_level=-1): """ Set a value for a key on server if its CAS value matches cas. :param key: Key's name :type key: six.string_types :param value: A value to be stored on server. :type value: object :param cas: The CAS v...
Increment a key if it exists returns it s actual value if it don t return 0.
def incr(self, key, value): """ Increment a key, if it exists, returns it's actual value, if it don't, return 0. :param key: Key's name :type key: six.string_types :param value: Number to be incremented :type value: int :return: Actual value of the key on server ...
Decrement a key if it exists returns it s actual value if it don t return 0. Minimum value of decrement return is 0.
def decr(self, key, value): """ Decrement a key, if it exists, returns it's actual value, if it don't, return 0. Minimum value of decrement return is 0. :param key: Key's name :type key: six.string_types :param value: Number to be decremented :type value: int ...
5. 5. 2 Semantics <http:// shex. io/ shex - semantics/ #triple - expressions - semantics > _
def satisfiesShape(cntxt: Context, n: Node, S: ShExJ.Shape, c: DebugContext) -> bool: """ `5.5.2 Semantics <http://shex.io/shex-semantics/#triple-expressions-semantics>`_ For a node `n`, shape `S`, graph `G`, and shapeMap `m`, `satisfies(n, S, G, m)` if and only if: * `neigh(G, n)` can be partitioned into...
Let ** outs ** be the arcsOut in remainder: outs = remainder ∩ arcsOut ( G n ).
def valid_remainder(cntxt: Context, n: Node, matchables: RDFGraph, S: ShExJ.Shape) -> bool: """ Let **outs** be the arcsOut in remainder: `outs = remainder ∩ arcsOut(G, n)`. Let **matchables** be the triples in outs whose predicate appears in a TripleConstraint in `expression`. If `expression` is absen...
** matches **: asserts that a triple expression is matched by a set of triples that come from the neighbourhood of a node in an RDF graph. The expression matches ( T expr m ) indicates that a set of triples T can satisfy these rules:
def matches(cntxt: Context, T: RDFGraph, expr: ShExJ.tripleExpr) -> bool: """ **matches**: asserts that a triple expression is matched by a set of triples that come from the neighbourhood of a node in an RDF graph. The expression `matches(T, expr, m)` indicates that a set of triples `T` can satisfy these ...
Evaluate cardinality expression
def matchesCardinality(cntxt: Context, T: RDFGraph, expr: Union[ShExJ.tripleExpr, ShExJ.tripleExprLabel], c: DebugContext) -> bool: """ Evaluate cardinality expression expr has a cardinality of min and/or max not equal to 1, where a max of -1 is treated as unbounded, and T can be par...
Evaluate the expression
def matchesExpr(cntxt: Context, T: RDFGraph, expr: ShExJ.tripleExpr, _: DebugContext) -> bool: """ Evaluate the expression """ if isinstance(expr, ShExJ.OneOf): return matchesOneOf(cntxt, T, expr) elif isinstance(expr, ShExJ.EachOf): return matchesEachOf(cntxt, T, expr) elif isinst...
expr is a OneOf and there is some shape expression se2 in shapeExprs such that a matches ( T se2 m ).
def matchesOneOf(cntxt: Context, T: RDFGraph, expr: ShExJ.OneOf, _: DebugContext) -> bool: """ expr is a OneOf and there is some shape expression se2 in shapeExprs such that a matches(T, se2, m). """ return any(matches(cntxt, T, e) for e in expr.expressions)
expr is an EachOf and there is some partition of T into T1 T2 … such that for every expression expr1 expr2 … in shapeExprs matches ( Tn exprn m ).
def matchesEachOf(cntxt: Context, T: RDFGraph, expr: ShExJ.EachOf, _: DebugContext) -> bool: """ expr is an EachOf and there is some partition of T into T1, T2,… such that for every expression expr1, expr2,… in shapeExprs, matches(Tn, exprn, m). """ return EachOfEvaluator(cntxt, T, expr).evaluate(cnt...
expr is a TripleConstraint and:
def matchesTripleConstraint(cntxt: Context, t: RDFTriple, expr: ShExJ.TripleConstraint, c: DebugContext) -> bool: """ expr is a TripleConstraint and: * t is a triple * t's predicate equals expr's predicate. Let value be t's subject if inverse is true, else t's object. * if inverse is true, t ...
expr is an tripleExprRef and satisfies ( value tripleExprWithId ( tripleExprRef ) G m ). The tripleExprWithId function is defined in Triple Expression Reference Requirement below.
def matchesTripleExprRef(cntxt: Context, T: RDFGraph, expr: ShExJ.tripleExprLabel, _: DebugContext) -> bool: """ expr is an tripleExprRef and satisfies(value, tripleExprWithId(tripleExprRef), G, m). The tripleExprWithId function is defined in Triple Expression Reference Requirement below. """ expr =...
Get a key from server.
def get(self, key, get_cas=False): """ Get a key from server. :param key: Key's name :type key: six.string_types :param get_cas: If true, return (value, cas), where cas is the new CAS value. :type get_cas: boolean :return: Returns a key data from server. ...
Get a key from server returning the value and its CAS key.
def gets(self, key): """ Get a key from server, returning the value and its CAS key. This method is for API compatibility with other implementations. :param key: Key's name :type key: six.string_types :return: Returns (key data, value), or (None, None) if the value is n...
Get multiple keys from server.
def get_multi(self, keys, get_cas=False): """ Get multiple keys from server. :param keys: A list of keys to from server. :type keys: list :param get_cas: If get_cas is true, each value is (data, cas), with each result's CAS value. :type get_cas: boolean :return: ...
Set a value for a key on server.
def set(self, key, value, time=0, compress_level=-1): """ Set a value for a key on server. :param key: Key's name :type key: str :param value: A value to be stored on server. :type value: object :param time: Time in seconds that your key will expire. :typ...
Set multiple keys with it s values on server.
def set_multi(self, mappings, time=0, compress_level=-1): """ Set multiple keys with it's values on server. :param mappings: A dict with keys/values :type mappings: dict :param time: Time in seconds that your key will expire. :type time: int :param compress_level...
Delete a key/ value from server. If key does not exist it returns True.
def delete(self, key, cas=0): """ Delete a key/value from server. If key does not exist, it returns True. :param key: Key's name to be deleted :param cas: CAS of the key :return: True in case o success and False in case of failure. """ returns = [] for se...
Increment a key if it exists returns it s actual value if it don t return 0.
def incr(self, key, value): """ Increment a key, if it exists, returns it's actual value, if it don't, return 0. :param key: Key's name :type key: six.string_types :param value: Number to be incremented :type value: int :return: Actual value of the key on server ...
Decrement a key if it exists returns it s actual value if it don t return 0. Minimum value of decrement return is 0.
def decr(self, key, value): """ Decrement a key, if it exists, returns it's actual value, if it don't, return 0. Minimum value of decrement return is 0. :param key: Key's name :type key: six.string_types :param value: Number to be decremented :type value: int ...
Set the result of the evaluation. If the result is true prune all of the children that didn t cut it
def set_result(self, rval: bool) -> None: """ Set the result of the evaluation. If the result is true, prune all of the children that didn't cut it :param rval: Result of evaluation """ self.result = rval if self.result: self.nodes = [pn for pn in self.nodes if pn.re...
Return the shape expression in the schema referenced by selector if any
def reference_of(selector: shapeLabel, cntxt: Union[Context, ShExJ.Schema] ) -> Optional[ShExJ.shapeExpr]: """ Return the shape expression in the schema referenced by selector, if any :param cntxt: Context node or ShEx Schema :param selector: identifier of element to select within the schema :return: ...
Search for the label in a Schema
def triple_reference_of(label: ShExJ.tripleExprLabel, cntxt: Context) -> Optional[ShExJ.tripleExpr]: """ Search for the label in a Schema """ te: Optional[ShExJ.tripleExpr] = None if cntxt.schema.start is not None: te = triple_in_shape(cntxt.schema.start, label, cntxt) if te is None: for...
Search for the label in a shape expression
def triple_in_shape(expr: ShExJ.shapeExpr, label: ShExJ.tripleExprLabel, cntxt: Context) \ -> Optional[ShExJ.tripleExpr]: """ Search for the label in a shape expression """ te = None if isinstance(expr, (ShExJ.ShapeOr, ShExJ.ShapeAnd)): for expr2 in expr.shapeExprs: te = triple_i...
Return the set of predicates that appears in a TripleConstraint in an expression See: 5. 5. 2 Semantics <http:// shex. io/ shex - semantics/ #triple - expressions - semantics > _ for details
def predicates_in_expression(expression: ShExJ.shapeExpr, cntxt: Context) -> List[IRIREF]: """ Return the set of predicates that "appears in a TripleConstraint in an expression See: `5.5.2 Semantics <http://shex.io/shex-semantics/#triple-expressions-semantics>`_ for details :param expression: Expressi...
Directed predicates in expression -- return all predicates in shapeExpr along with which direction ( s ) they evaluate
def directed_predicates_in_expression(expression: ShExJ.shapeExpr, cntxt: Context) -> Dict[IRIREF, PredDirection]: """ Directed predicates in expression -- return all predicates in shapeExpr along with which direction(s) they evaluate :param expression: Expression to scan :param cntxt: :return: ...
taken from Stack Overflow <https:// codereview. stackexchange. com/ questions/ 1526/ finding - all - k - subset - partitions > _
def algorithm_u(ns, m): """ taken from `Stack Overflow <https://codereview.stackexchange.com/questions/1526/finding-all-k-subset-partitions>`_ """ def visit(nv, av): ps = [[] for _ in range(m)] for jv in range(nv): ps[av[jv + 1]].append(ns[jv]) return ps def f(m...
Partition a list of integers into a list of partitions
def integer_partition(size: int, nparts: int) -> Iterator[List[List[int]]]: """ Partition a list of integers into a list of partitions """ for part in algorithm_u(range(size), nparts): yield part
Partition T into all possible partitions of T of size nparts: param T: Set of RDF triples to be partitioned: param nparts: number of partitions ( e. g. 2 means return all possible 2 set partitions: return: Iterator that returns partitions
def partition_t(T: RDFGraph, nparts: int) -> Iterator[Tuple[RDFGraph, ...]]: """ Partition T into all possible partitions of T of size nparts :param T: Set of RDF triples to be partitioned :param nparts: number of partitions (e.g. 2 means return all possible 2 set partitions :return: Iterator that r...
Partition T into all possible combinations of two subsets: param T: RDF Graph to partition: return:
def partition_2(T: RDFGraph) -> List[Tuple[RDFGraph, RDFGraph]]: """ Partition T into all possible combinations of two subsets :param T: RDF Graph to partition :return: """ for p in partition_t(T, 2): yield p
numeric denotes typed literals with datatypes xsd: integer xsd: decimal xsd: float and xsd: double.
def is_strict_numeric(n: Node) -> bool: """ numeric denotes typed literals with datatypes xsd:integer, xsd:decimal, xsd:float, and xsd:double. """ return is_typed_literal(n) and cast(Literal, n).datatype in [XSD.integer, XSD.decimal, XSD.float, XSD.double]
simple literal denotes a plain literal with no language tag.
def is_simple_literal(n: Node) -> bool: """ simple literal denotes a plain literal with no language tag. """ return is_typed_literal(n) and cast(Literal, n).datatype is None and cast(Literal, n).language is None
5. 7. 1 Semantic Actions Semantics <http:// shex. io/ shex - semantics/ #semantic - actions - semantics > _
def semActsSatisfied(acts: Optional[List[ShExJ.SemAct]], cntxt: Context) -> bool: """ `5.7.1 Semantic Actions Semantics <http://shex.io/shex-semantics/#semantic-actions-semantics>`_ The evaluation semActsSatisfied on a list of SemActs returns success or failure. The evaluation of an individual SemAct is im...
Conditionally print txt
def print(self, txt: str, hold: bool=False) -> None: """ Conditionally print txt :param txt: text to print :param hold: If true, hang on to the text until another print comes through :param hold: If true, drop both print statements if another hasn't intervened :return: "...
Reset the context preceeding an evaluation
def reset(self) -> None: """ Reset the context preceeding an evaluation """ self.evaluating = set() self.assumptions = {} self.known_results = {} self.current_node = None self.evaluate_stack = [] self.bnode_map = {}
Generate the schema_id_map
def _gen_schema_xref(self, expr: Optional[Union[ShExJ.shapeExprLabel, ShExJ.shapeExpr]]) -> None: """ Generate the schema_id_map :param expr: root shape expression """ if expr is not None and not isinstance_(expr, ShExJ.shapeExprLabel) and 'id' in expr and expr.id is not None: ...
Generate the triple expression map ( te_id_map )
def _gen_te_xref(self, expr: Union[ShExJ.tripleExpr, ShExJ.tripleExprLabel]) -> None: """ Generate the triple expression map (te_id_map) :param expr: root triple expression """ if expr is not None and not isinstance_(expr, ShExJ.tripleExprLabel) and 'id' in expr and expr.id is ...
Return the triple expression that corresponds to id
def tripleExprFor(self, id_: ShExJ.tripleExprLabel) -> ShExJ.tripleExpr: """ Return the triple expression that corresponds to id """ return self.te_id_map.get(id_)
Return the shape expression that corresponds to id
def shapeExprFor(self, id_: Union[ShExJ.shapeExprLabel, START]) -> Optional[ShExJ.shapeExpr]: """ Return the shape expression that corresponds to id """ rval = self.schema.start if id_ is START else self.schema_id_map.get(str(id_)) return rval
Visit expr and all of its descendant shapes.
def visit_shapes(self, expr: ShExJ.shapeExpr, f: Callable[[Any, ShExJ.shapeExpr, "Context"], None], arg_cntxt: Any, visit_center: _VisitorCenter = None, follow_inner_shapes: bool=True) -> None: """ Visit expr and all of its "descendant" shapes. :param expr: root shape expre...
Visit a triple expression that was reached through a shape. This in turn is used to visit additional shapes that are referenced by a TripleConstraint: param te: Triple expression reached through a Shape. expression: param visit_center: context used in shape visitor
def _visit_shape_te(self, te: ShExJ.tripleExpr, visit_center: _VisitorCenter) -> None: """ Visit a triple expression that was reached through a shape. This, in turn, is used to visit additional shapes that are referenced by a TripleConstraint :param te: Triple expression reached through ...
Visit a shape expression that was reached through a triple expression. This in turn is used to visit additional triple expressions that are referenced by the Shape
def _visit_te_shape(self, shape: ShExJ.shapeExpr, visit_center: _VisitorCenter) -> None: """ Visit a shape expression that was reached through a triple expression. This, in turn, is used to visit additional triple expressions that are referenced by the Shape :param shape: Shape reached...
Indicate that we are beginning to evaluate n according to shape expression s. If we are already in the process of evaluating ( n s ) as indicated self. evaluating we return our current guess as to the result.
def start_evaluating(self, n: Node, s: ShExJ.shapeExpr) -> Optional[bool]: """Indicate that we are beginning to evaluate n according to shape expression s. If we are already in the process of evaluating (n,s), as indicated self.evaluating, we return our current guess as to the result. :...
Indicate that we have completed an actual evaluation of ( n s ). This is only called when start_evaluating has returned None as the assumed result
def done_evaluating(self, n: Node, s: ShExJ.shapeExpr, result: bool) -> Tuple[bool, bool]: """ Indicate that we have completed an actual evaluation of (n,s). This is only called when start_evaluating has returned None as the assumed result :param n: Node that was evaluated :par...
Move the type identifiers to the end of the object for print purposes
def type_last(self, obj: JsonObj) -> JsonObj: """ Move the type identifiers to the end of the object for print purposes """ def _tl_list(v: List) -> List: return [self.type_last(e) if isinstance(e, JsonObj) else _tl_list(e) if isinstance(e, list) else e for...
5. 3 Shape Expressions <http:// shex. io/ shex - semantics/ #node - constraint - semantics > _
def satisfies(cntxt: Context, n: Node, se: ShExJ.shapeExpr) -> bool: """ `5.3 Shape Expressions <http://shex.io/shex-semantics/#node-constraint-semantics>`_ satisfies: The expression satisfies(n, se, G, m) indicates that a node n and graph G satisfy a shape expression se with shapeM...
Se is a ShapeOr and there is some shape expression se2 in shapeExprs such that satisfies ( n se2 G m ).
def satisifesShapeOr(cntxt: Context, n: Node, se: ShExJ.ShapeOr, _: DebugContext) -> bool: """ Se is a ShapeOr and there is some shape expression se2 in shapeExprs such that satisfies(n, se2, G, m). """ return any(satisfies(cntxt, n, se2) for se2 in se.shapeExprs)
Se is a ShapeAnd and for every shape expression se2 in shapeExprs satisfies ( n se2 G m )
def satisfiesShapeAnd(cntxt: Context, n: Node, se: ShExJ.ShapeAnd, _: DebugContext) -> bool: """ Se is a ShapeAnd and for every shape expression se2 in shapeExprs, satisfies(n, se2, G, m) """ return all(satisfies(cntxt, n, se2) for se2 in se.shapeExprs)
Se is a ShapeNot and for the shape expression se2 at shapeExpr notSatisfies ( n se2 G m )
def satisfiesShapeNot(cntxt: Context, n: Node, se: ShExJ.ShapeNot, _: DebugContext) -> bool: """ Se is a ShapeNot and for the shape expression se2 at shapeExpr, notSatisfies(n, se2, G, m) """ return not satisfies(cntxt, n, se.shapeExpr)
Se is a ShapeExternal and implementation - specific mechansims not defined in this specification indicate success.
def satisfiesExternal(cntxt: Context, n: Node, se: ShExJ.ShapeExternal, c: DebugContext) -> bool: """ Se is a ShapeExternal and implementation-specific mechansims not defined in this specification indicate success. """ if c.debug: print(f"id: {se.id}") extern_shape = cntxt.external_shape_f...
Se is a shapeExprRef and there exists in the schema a shape expression se2 with that id and satisfies ( n se2 G m ).
def satisfiesShapeExprRef(cntxt: Context, n: Node, se: ShExJ.shapeExprLabel, c: DebugContext) -> bool: """ Se is a shapeExprRef and there exists in the schema a shape expression se2 with that id and satisfies(n, se2, G, m). """ if c.debug: print(f"id: {se}") for shape in cntxt.schema.shape...
Cat proximity graph from http:// xkcd. com/ 231/
def cat_proximity(): """Cat proximity graph from http://xkcd.com/231/""" chart = SimpleLineChart(int(settings.width * 1.5), settings.height) chart.set_legend(['INTELLIGENCE', 'INSANITY OF STATEMENTS']) # intelligence data_index = chart.add_data([100. / y for y in range(1, 15)]) # insanity of s...
Return a URIRef for a str or URIRef
def normalize_uri(u: URI) -> URIRef: """ Return a URIRef for a str or URIRef """ return u if isinstance(u, URIRef) else URIRef(str(u))
Return an optional list of URIRefs for p
def normalize_uriparm(p: URIPARM) -> List[URIRef]: """ Return an optional list of URIRefs for p""" return normalize_urilist(p) if isinstance(p, List) else \ normalize_urilist([p]) if isinstance(p, (str, URIRef)) else p
Return the startspec for p
def normalize_startparm(p: STARTPARM) -> List[Union[type(START), START_TYPE, URIRef]]: """ Return the startspec for p """ if not isinstance(p, list): p = [p] return [normalize_uri(e) if isinstance(e, str) and e is not START else e for e in p]
Create a command line parser: return: parser
def genargs(prog: Optional[str] = None) -> ArgumentParser: """ Create a command line parser :return: parser """ parser = ArgumentParser(prog) parser.add_argument("rdf", help="Input RDF file or SPARQL endpoint if slurper or sparql options") parser.add_argument("shex", help="ShEx specification...
Set the RDF DataSet to be evaulated. If rdf is a string the presence of a return is the indicator that it is text instead of a location.
def rdf(self, rdf: Optional[Union[str, Graph]]) -> None: """ Set the RDF DataSet to be evaulated. If ``rdf`` is a string, the presence of a return is the indicator that it is text instead of a location. :param rdf: File name, URL, representation of rdflib Graph """ if isinstanc...