repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
Metatab/metapack | metapack/jupyter/script.py | ScriptIPython.system_piped | def system_piped(self, cmd):
"""Call the given cmd in a subprocess, piping stdout/err
Parameters
----------
cmd : str
Command to execute (can not end in '&', as background processes are
not supported. Should not be a command that expects input
other than s... | python | def system_piped(self, cmd):
"""Call the given cmd in a subprocess, piping stdout/err
Parameters
----------
cmd : str
Command to execute (can not end in '&', as background processes are
not supported. Should not be a command that expects input
other than s... | [
"def",
"system_piped",
"(",
"self",
",",
"cmd",
")",
":",
"if",
"cmd",
".",
"rstrip",
"(",
")",
".",
"endswith",
"(",
"'&'",
")",
":",
"# this is *far* from a rigorous test",
"# We do not support backgrounding processes because we either use",
"# pexpect or pipes to read ... | Call the given cmd in a subprocess, piping stdout/err
Parameters
----------
cmd : str
Command to execute (can not end in '&', as background processes are
not supported. Should not be a command that expects input
other than simple text. | [
"Call",
"the",
"given",
"cmd",
"in",
"a",
"subprocess",
"piping",
"stdout",
"/",
"err"
] | train | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/script.py#L61-L82 |
Metatab/metapack | metapack/jupyter/script.py | ScriptIPython.var_expand | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
"""Expand python variables in a string.
The depth argument indicates how many frames above the caller should
be walked to look for the local namespace where to expand variables.
The global namespace for expansion is alway... | python | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
"""Expand python variables in a string.
The depth argument indicates how many frames above the caller should
be walked to look for the local namespace where to expand variables.
The global namespace for expansion is alway... | [
"def",
"var_expand",
"(",
"self",
",",
"cmd",
",",
"depth",
"=",
"0",
",",
"formatter",
"=",
"DollarFormatter",
"(",
")",
")",
":",
"ns",
"=",
"self",
".",
"user_ns",
".",
"copy",
"(",
")",
"try",
":",
"frame",
"=",
"sys",
".",
"_getframe",
"(",
... | Expand python variables in a string.
The depth argument indicates how many frames above the caller should
be walked to look for the local namespace where to expand variables.
The global namespace for expansion is always the user's interactive
namespace. | [
"Expand",
"python",
"variables",
"in",
"a",
"string",
"."
] | train | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/script.py#L85-L112 |
Metatab/metapack | metapack/jupyter/script.py | ScriptIPython.shebang | def shebang(self, line, cell):
"""Run a cell via a shell command
The `%%script` line is like the #! line of script,
specifying a program (bash, perl, ruby, etc.) with which to run.
The rest of the cell is run by that program.
Examples
--------
::
I... | python | def shebang(self, line, cell):
"""Run a cell via a shell command
The `%%script` line is like the #! line of script,
specifying a program (bash, perl, ruby, etc.) with which to run.
The rest of the cell is run by that program.
Examples
--------
::
I... | [
"def",
"shebang",
"(",
"self",
",",
"line",
",",
"cell",
")",
":",
"argv",
"=",
"arg_split",
"(",
"line",
",",
"posix",
"=",
"not",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
")",
"args",
",",
"cmd",
"=",
"self",
".",
"shebang",
... | Run a cell via a shell command
The `%%script` line is like the #! line of script,
specifying a program (bash, perl, ruby, etc.) with which to run.
The rest of the cell is run by that program.
Examples
--------
::
In [1]: %%script bash
...: f... | [
"Run",
"a",
"cell",
"via",
"a",
"shell",
"command"
] | train | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/script.py#L119-L199 |
project-rig/rig | rig/place_and_route/place/rcm.py | _get_vertices_neighbours | def _get_vertices_neighbours(nets):
"""Generate a listing of each vertex's immedate neighbours in an undirected
interpretation of a graph.
Returns
-------
{vertex: {vertex: weight, ...}), ...}
"""
zero_fn = (lambda: 0)
vertices_neighbours = defaultdict(lambda: defaultdict(zero_fn))
... | python | def _get_vertices_neighbours(nets):
"""Generate a listing of each vertex's immedate neighbours in an undirected
interpretation of a graph.
Returns
-------
{vertex: {vertex: weight, ...}), ...}
"""
zero_fn = (lambda: 0)
vertices_neighbours = defaultdict(lambda: defaultdict(zero_fn))
... | [
"def",
"_get_vertices_neighbours",
"(",
"nets",
")",
":",
"zero_fn",
"=",
"(",
"lambda",
":",
"0",
")",
"vertices_neighbours",
"=",
"defaultdict",
"(",
"lambda",
":",
"defaultdict",
"(",
"zero_fn",
")",
")",
"for",
"net",
"in",
"nets",
":",
"if",
"net",
... | Generate a listing of each vertex's immedate neighbours in an undirected
interpretation of a graph.
Returns
-------
{vertex: {vertex: weight, ...}), ...} | [
"Generate",
"a",
"listing",
"of",
"each",
"vertex",
"s",
"immedate",
"neighbours",
"in",
"an",
"undirected",
"interpretation",
"of",
"a",
"graph",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/rcm.py#L13-L28 |
project-rig/rig | rig/place_and_route/place/rcm.py | _dfs | def _dfs(vertex, vertices_neighbours):
"""Generate all the vertices connected to the supplied vertex in
depth-first-search order.
"""
visited = set()
to_visit = deque([vertex])
while to_visit:
vertex = to_visit.pop()
if vertex not in visited:
yield vertex
... | python | def _dfs(vertex, vertices_neighbours):
"""Generate all the vertices connected to the supplied vertex in
depth-first-search order.
"""
visited = set()
to_visit = deque([vertex])
while to_visit:
vertex = to_visit.pop()
if vertex not in visited:
yield vertex
... | [
"def",
"_dfs",
"(",
"vertex",
",",
"vertices_neighbours",
")",
":",
"visited",
"=",
"set",
"(",
")",
"to_visit",
"=",
"deque",
"(",
"[",
"vertex",
"]",
")",
"while",
"to_visit",
":",
"vertex",
"=",
"to_visit",
".",
"pop",
"(",
")",
"if",
"vertex",
"n... | Generate all the vertices connected to the supplied vertex in
depth-first-search order. | [
"Generate",
"all",
"the",
"vertices",
"connected",
"to",
"the",
"supplied",
"vertex",
"in",
"depth",
"-",
"first",
"-",
"search",
"order",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/rcm.py#L31-L42 |
project-rig/rig | rig/place_and_route/place/rcm.py | _get_connected_subgraphs | def _get_connected_subgraphs(vertices, vertices_neighbours):
"""Break a graph containing unconnected subgraphs into a list of connected
subgraphs.
Returns
-------
[set([vertex, ...]), ...]
"""
remaining_vertices = set(vertices)
subgraphs = []
while remaining_vertices:
subgra... | python | def _get_connected_subgraphs(vertices, vertices_neighbours):
"""Break a graph containing unconnected subgraphs into a list of connected
subgraphs.
Returns
-------
[set([vertex, ...]), ...]
"""
remaining_vertices = set(vertices)
subgraphs = []
while remaining_vertices:
subgra... | [
"def",
"_get_connected_subgraphs",
"(",
"vertices",
",",
"vertices_neighbours",
")",
":",
"remaining_vertices",
"=",
"set",
"(",
"vertices",
")",
"subgraphs",
"=",
"[",
"]",
"while",
"remaining_vertices",
":",
"subgraph",
"=",
"set",
"(",
"_dfs",
"(",
"remaining... | Break a graph containing unconnected subgraphs into a list of connected
subgraphs.
Returns
-------
[set([vertex, ...]), ...] | [
"Break",
"a",
"graph",
"containing",
"unconnected",
"subgraphs",
"into",
"a",
"list",
"of",
"connected",
"subgraphs",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/rcm.py#L45-L60 |
project-rig/rig | rig/place_and_route/place/rcm.py | _cuthill_mckee | def _cuthill_mckee(vertices, vertices_neighbours):
"""Yield the Cuthill-McKee order for a connected, undirected graph.
`Wikipedia
<https://en.wikipedia.org/wiki/Cuthill%E2%80%93McKee_algorithm>`_ provides
a good introduction to the Cuthill-McKee algorithm. The RCM algorithm
attempts to order vertic... | python | def _cuthill_mckee(vertices, vertices_neighbours):
"""Yield the Cuthill-McKee order for a connected, undirected graph.
`Wikipedia
<https://en.wikipedia.org/wiki/Cuthill%E2%80%93McKee_algorithm>`_ provides
a good introduction to the Cuthill-McKee algorithm. The RCM algorithm
attempts to order vertic... | [
"def",
"_cuthill_mckee",
"(",
"vertices",
",",
"vertices_neighbours",
")",
":",
"vertices_degrees",
"=",
"{",
"v",
":",
"sum",
"(",
"itervalues",
"(",
"vertices_neighbours",
"[",
"v",
"]",
")",
")",
"for",
"v",
"in",
"vertices",
"}",
"peripheral_vertex",
"="... | Yield the Cuthill-McKee order for a connected, undirected graph.
`Wikipedia
<https://en.wikipedia.org/wiki/Cuthill%E2%80%93McKee_algorithm>`_ provides
a good introduction to the Cuthill-McKee algorithm. The RCM algorithm
attempts to order vertices in a graph such that their adjacency matrix's
bandw... | [
"Yield",
"the",
"Cuthill",
"-",
"McKee",
"order",
"for",
"a",
"connected",
"undirected",
"graph",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/rcm.py#L63-L103 |
project-rig/rig | rig/place_and_route/place/rcm.py | rcm_vertex_order | def rcm_vertex_order(vertices_resources, nets):
"""A generator which iterates over the vertices in Reverse-Cuthill-McKee
order.
For use as a vertex ordering for the sequential placer.
"""
vertices_neighbours = _get_vertices_neighbours(nets)
for subgraph_vertices in _get_connected_subgraphs(vert... | python | def rcm_vertex_order(vertices_resources, nets):
"""A generator which iterates over the vertices in Reverse-Cuthill-McKee
order.
For use as a vertex ordering for the sequential placer.
"""
vertices_neighbours = _get_vertices_neighbours(nets)
for subgraph_vertices in _get_connected_subgraphs(vert... | [
"def",
"rcm_vertex_order",
"(",
"vertices_resources",
",",
"nets",
")",
":",
"vertices_neighbours",
"=",
"_get_vertices_neighbours",
"(",
"nets",
")",
"for",
"subgraph_vertices",
"in",
"_get_connected_subgraphs",
"(",
"vertices_resources",
",",
"vertices_neighbours",
")",... | A generator which iterates over the vertices in Reverse-Cuthill-McKee
order.
For use as a vertex ordering for the sequential placer. | [
"A",
"generator",
"which",
"iterates",
"over",
"the",
"vertices",
"in",
"Reverse",
"-",
"Cuthill",
"-",
"McKee",
"order",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/rcm.py#L106-L117 |
project-rig/rig | rig/place_and_route/place/rcm.py | rcm_chip_order | def rcm_chip_order(machine):
"""A generator which iterates over a set of chips in a machine in
Reverse-Cuthill-McKee order.
For use as a chip ordering for the sequential placer.
"""
# Convert the Machine description into a placement-problem-style-graph
# where the vertices are chip coordinate t... | python | def rcm_chip_order(machine):
"""A generator which iterates over a set of chips in a machine in
Reverse-Cuthill-McKee order.
For use as a chip ordering for the sequential placer.
"""
# Convert the Machine description into a placement-problem-style-graph
# where the vertices are chip coordinate t... | [
"def",
"rcm_chip_order",
"(",
"machine",
")",
":",
"# Convert the Machine description into a placement-problem-style-graph",
"# where the vertices are chip coordinate tuples (x, y) and each net",
"# represents the links leaving each chip. This allows us to re-use the",
"# rcm_vertex_order function... | A generator which iterates over a set of chips in a machine in
Reverse-Cuthill-McKee order.
For use as a chip ordering for the sequential placer. | [
"A",
"generator",
"which",
"iterates",
"over",
"a",
"set",
"of",
"chips",
"in",
"a",
"machine",
"in",
"Reverse",
"-",
"Cuthill",
"-",
"McKee",
"order",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/rcm.py#L120-L149 |
project-rig/rig | rig/place_and_route/place/rcm.py | place | def place(vertices_resources, nets, machine, constraints):
"""Assigns vertices to chips in Reverse-Cuthill-McKee (RCM) order.
The `RCM <https://en.wikipedia.org/wiki/Cuthill%E2%80%93McKee_algorithm>`_
algorithm (in graph-centric terms) is a simple breadth-first-search-like
heuristic which attempts to y... | python | def place(vertices_resources, nets, machine, constraints):
"""Assigns vertices to chips in Reverse-Cuthill-McKee (RCM) order.
The `RCM <https://en.wikipedia.org/wiki/Cuthill%E2%80%93McKee_algorithm>`_
algorithm (in graph-centric terms) is a simple breadth-first-search-like
heuristic which attempts to y... | [
"def",
"place",
"(",
"vertices_resources",
",",
"nets",
",",
"machine",
",",
"constraints",
")",
":",
"return",
"sequential_place",
"(",
"vertices_resources",
",",
"nets",
",",
"machine",
",",
"constraints",
",",
"rcm_vertex_order",
"(",
"vertices_resources",
",",... | Assigns vertices to chips in Reverse-Cuthill-McKee (RCM) order.
The `RCM <https://en.wikipedia.org/wiki/Cuthill%E2%80%93McKee_algorithm>`_
algorithm (in graph-centric terms) is a simple breadth-first-search-like
heuristic which attempts to yield an ordering of vertices which would yield
a 1D placement ... | [
"Assigns",
"vertices",
"to",
"chips",
"in",
"Reverse",
"-",
"Cuthill",
"-",
"McKee",
"(",
"RCM",
")",
"order",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/rcm.py#L152-L180 |
NicolasLM/spinach | spinach/contrib/datadog.py | register_datadog | def register_datadog(tracer=None, namespace: Optional[str]=None,
service: str='spinach'):
"""Register the Datadog integration.
Exceptions making jobs fail are sent to Sentry.
:param tracer: optionally use a custom ddtrace Tracer instead of the global
one.
:param namespa... | python | def register_datadog(tracer=None, namespace: Optional[str]=None,
service: str='spinach'):
"""Register the Datadog integration.
Exceptions making jobs fail are sent to Sentry.
:param tracer: optionally use a custom ddtrace Tracer instead of the global
one.
:param namespa... | [
"def",
"register_datadog",
"(",
"tracer",
"=",
"None",
",",
"namespace",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"service",
":",
"str",
"=",
"'spinach'",
")",
":",
"if",
"tracer",
"is",
"None",
":",
"from",
"ddtrace",
"import",
"tracer",
"@... | Register the Datadog integration.
Exceptions making jobs fail are sent to Sentry.
:param tracer: optionally use a custom ddtrace Tracer instead of the global
one.
:param namespace: optionally only register the Datadog integration for a
particular Spinach :class:`Engine`
:param se... | [
"Register",
"the",
"Datadog",
"integration",
"."
] | train | https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/contrib/datadog.py#L6-L44 |
Metatab/metapack | metapack/rowgenerator.py | copy_reference | def copy_reference(resource, doc, env, *args, **kwargs):
"""A row-generating function that yields from a reference. This permits an upstream package to be
copied and modified by this package, while being formally referenced as a dependency
The function will generate rows from a reference that has the same ... | python | def copy_reference(resource, doc, env, *args, **kwargs):
"""A row-generating function that yields from a reference. This permits an upstream package to be
copied and modified by this package, while being formally referenced as a dependency
The function will generate rows from a reference that has the same ... | [
"def",
"copy_reference",
"(",
"resource",
",",
"doc",
",",
"env",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"yield",
"from",
"doc",
".",
"reference",
"(",
"resource",
".",
"name",
")"
] | A row-generating function that yields from a reference. This permits an upstream package to be
copied and modified by this package, while being formally referenced as a dependency
The function will generate rows from a reference that has the same name as the resource term | [
"A",
"row",
"-",
"generating",
"function",
"that",
"yields",
"from",
"a",
"reference",
".",
"This",
"permits",
"an",
"upstream",
"package",
"to",
"be",
"copied",
"and",
"modified",
"by",
"this",
"package",
"while",
"being",
"formally",
"referenced",
"as",
"a... | train | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/rowgenerator.py#L164-L171 |
Metatab/metapack | metapack/rowgenerator.py | copy_reference_group | def copy_reference_group(resource, doc, env, *args, **kwargs):
"""
A Row generating function that copies all of the references that have the same 'Group' argument as this reference
The 'RefArgs' argument is a comma seperated list of arguments from the references that will be prepended to each
row.
... | python | def copy_reference_group(resource, doc, env, *args, **kwargs):
"""
A Row generating function that copies all of the references that have the same 'Group' argument as this reference
The 'RefArgs' argument is a comma seperated list of arguments from the references that will be prepended to each
row.
... | [
"def",
"copy_reference_group",
"(",
"resource",
",",
"doc",
",",
"env",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"all_headers",
"=",
"[",
"]",
"# Combine all of the headers into a list of tuples by position",
"for",
"ref",
"in",
"doc",
".",
"referenc... | A Row generating function that copies all of the references that have the same 'Group' argument as this reference
The 'RefArgs' argument is a comma seperated list of arguments from the references that will be prepended to each
row.
:param resource:
:param doc:
:param env:
:param args:
:par... | [
"A",
"Row",
"generating",
"function",
"that",
"copies",
"all",
"of",
"the",
"references",
"that",
"have",
"the",
"same",
"Group",
"argument",
"as",
"this",
"reference"
] | train | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/rowgenerator.py#L173-L218 |
Metatab/metapack | metapack/package/filesystem.py | FileSystemPackageBuilder.is_older_than_metadata | def is_older_than_metadata(self):
"""
Return True if the package save file is older than the metadata. If it is, it should be rebuilt. Returns
False if the time of either can't be determined
:param path: Optional extra save path, used in save_path()
"""
try:
... | python | def is_older_than_metadata(self):
"""
Return True if the package save file is older than the metadata. If it is, it should be rebuilt. Returns
False if the time of either can't be determined
:param path: Optional extra save path, used in save_path()
"""
try:
... | [
"def",
"is_older_than_metadata",
"(",
"self",
")",
":",
"try",
":",
"path",
"=",
"self",
".",
"doc_file",
".",
"path",
"except",
"AttributeError",
":",
"path",
"=",
"self",
".",
"doc_file",
"source_ref",
"=",
"self",
".",
"_doc",
".",
"ref",
".",
"path",... | Return True if the package save file is older than the metadata. If it is, it should be rebuilt. Returns
False if the time of either can't be determined
:param path: Optional extra save path, used in save_path() | [
"Return",
"True",
"if",
"the",
"package",
"save",
"file",
"is",
"older",
"than",
"the",
"metadata",
".",
"If",
"it",
"is",
"it",
"should",
"be",
"rebuilt",
".",
"Returns",
"False",
"if",
"the",
"time",
"of",
"either",
"can",
"t",
"be",
"determined"
] | train | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/package/filesystem.py#L82-L104 |
Metatab/metapack | metapack/package/filesystem.py | FileSystemPackageBuilder._load_resource | def _load_resource(self, source_r, abs_path=False):
"""The CSV package has no resources, so we just need to resolve the URLs to them. Usually, the
CSV package is built from a file system ackage on a publically acessible server. """
from itertools import islice
from metapack.exc impo... | python | def _load_resource(self, source_r, abs_path=False):
"""The CSV package has no resources, so we just need to resolve the URLs to them. Usually, the
CSV package is built from a file system ackage on a publically acessible server. """
from itertools import islice
from metapack.exc impo... | [
"def",
"_load_resource",
"(",
"self",
",",
"source_r",
",",
"abs_path",
"=",
"False",
")",
":",
"from",
"itertools",
"import",
"islice",
"from",
"metapack",
".",
"exc",
"import",
"MetapackError",
"from",
"os",
".",
"path",
"import",
"splitext",
"# Refetch the ... | The CSV package has no resources, so we just need to resolve the URLs to them. Usually, the
CSV package is built from a file system ackage on a publically acessible server. | [
"The",
"CSV",
"package",
"has",
"no",
"resources",
"so",
"we",
"just",
"need",
"to",
"resolve",
"the",
"URLs",
"to",
"them",
".",
"Usually",
"the",
"CSV",
"package",
"is",
"built",
"from",
"a",
"file",
"system",
"ackage",
"on",
"a",
"publically",
"acessi... | train | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/package/filesystem.py#L150-L228 |
Metatab/metapack | metapack/package/filesystem.py | FileSystemPackageBuilder._load_documentation | def _load_documentation(self, term, contents, file_name):
"""Load a single documentation entry"""
try:
title = term['title'].value
except KeyError:
self.warn("Documentation has no title, skipping: '{}' ".format(term.value))
return
if term.term_is('Ro... | python | def _load_documentation(self, term, contents, file_name):
"""Load a single documentation entry"""
try:
title = term['title'].value
except KeyError:
self.warn("Documentation has no title, skipping: '{}' ".format(term.value))
return
if term.term_is('Ro... | [
"def",
"_load_documentation",
"(",
"self",
",",
"term",
",",
"contents",
",",
"file_name",
")",
":",
"try",
":",
"title",
"=",
"term",
"[",
"'title'",
"]",
".",
"value",
"except",
"KeyError",
":",
"self",
".",
"warn",
"(",
"\"Documentation has no title, skip... | Load a single documentation entry | [
"Load",
"a",
"single",
"documentation",
"entry"
] | train | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/package/filesystem.py#L272-L307 |
narwhaljames/restapi-logging-handler | restapi_logging_handler/restapi_logging_handler.py | serialize | def serialize(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime.datetime):
serial = obj.isoformat(sep='T')
return serial
if isinstance(obj, uuid.UUID):
serial = str(obj)
return serial
try:
return obj.__dict... | python | def serialize(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime.datetime):
serial = obj.isoformat(sep='T')
return serial
if isinstance(obj, uuid.UUID):
serial = str(obj)
return serial
try:
return obj.__dict... | [
"def",
"serialize",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"datetime",
".",
"datetime",
")",
":",
"serial",
"=",
"obj",
".",
"isoformat",
"(",
"sep",
"=",
"'T'",
")",
"return",
"serial",
"if",
"isinstance",
"(",
"obj",
",",
"uuid"... | JSON serializer for objects not serializable by default json code | [
"JSON",
"serializer",
"for",
"objects",
"not",
"serializable",
"by",
"default",
"json",
"code"
] | train | https://github.com/narwhaljames/restapi-logging-handler/blob/edaedd3e702e68cfd102bc9fbfa4a33e0c002913/restapi_logging_handler/restapi_logging_handler.py#L97-L119 |
narwhaljames/restapi-logging-handler | restapi_logging_handler/restapi_logging_handler.py | RestApiHandler._getPayload | def _getPayload(self, record):
"""
The data that will be sent to the RESTful API
"""
try:
# top level payload items
d = record.__dict__
pid = d.pop('process', 'nopid')
tid = d.pop('thread', 'notid')
payload = {
... | python | def _getPayload(self, record):
"""
The data that will be sent to the RESTful API
"""
try:
# top level payload items
d = record.__dict__
pid = d.pop('process', 'nopid')
tid = d.pop('thread', 'notid')
payload = {
... | [
"def",
"_getPayload",
"(",
"self",
",",
"record",
")",
":",
"try",
":",
"# top level payload items",
"d",
"=",
"record",
".",
"__dict__",
"pid",
"=",
"d",
".",
"pop",
"(",
"'process'",
",",
"'nopid'",
")",
"tid",
"=",
"d",
".",
"pop",
"(",
"'thread'",
... | The data that will be sent to the RESTful API | [
"The",
"data",
"that",
"will",
"be",
"sent",
"to",
"the",
"RESTful",
"API"
] | train | https://github.com/narwhaljames/restapi-logging-handler/blob/edaedd3e702e68cfd102bc9fbfa4a33e0c002913/restapi_logging_handler/restapi_logging_handler.py#L166-L211 |
narwhaljames/restapi-logging-handler | restapi_logging_handler/restapi_logging_handler.py | RestApiHandler._prepPayload | def _prepPayload(self, record):
"""
record: generated from logger module
This preps the payload to be formatted in whatever content-type is
expected from the RESTful API.
returns: a tuple of the data and the http content-type
"""
payload = self._getPayload(record... | python | def _prepPayload(self, record):
"""
record: generated from logger module
This preps the payload to be formatted in whatever content-type is
expected from the RESTful API.
returns: a tuple of the data and the http content-type
"""
payload = self._getPayload(record... | [
"def",
"_prepPayload",
"(",
"self",
",",
"record",
")",
":",
"payload",
"=",
"self",
".",
"_getPayload",
"(",
"record",
")",
"json_data",
"=",
"json",
".",
"dumps",
"(",
"payload",
",",
"default",
"=",
"serialize",
")",
"return",
"{",
"'json'",
":",
"(... | record: generated from logger module
This preps the payload to be formatted in whatever content-type is
expected from the RESTful API.
returns: a tuple of the data and the http content-type | [
"record",
":",
"generated",
"from",
"logger",
"module",
"This",
"preps",
"the",
"payload",
"to",
"be",
"formatted",
"in",
"whatever",
"content",
"-",
"type",
"is",
"expected",
"from",
"the",
"RESTful",
"API",
"."
] | train | https://github.com/narwhaljames/restapi-logging-handler/blob/edaedd3e702e68cfd102bc9fbfa4a33e0c002913/restapi_logging_handler/restapi_logging_handler.py#L213-L226 |
narwhaljames/restapi-logging-handler | restapi_logging_handler/restapi_logging_handler.py | RestApiHandler.emit | def emit(self, record):
"""
Override emit() method in handler parent for sending log to RESTful API
"""
# avoid infinite recursion
if record.name.startswith('requests'):
return
data, header = self._prepPayload(record)
try:
self.session.po... | python | def emit(self, record):
"""
Override emit() method in handler parent for sending log to RESTful API
"""
# avoid infinite recursion
if record.name.startswith('requests'):
return
data, header = self._prepPayload(record)
try:
self.session.po... | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"# avoid infinite recursion",
"if",
"record",
".",
"name",
".",
"startswith",
"(",
"'requests'",
")",
":",
"return",
"data",
",",
"header",
"=",
"self",
".",
"_prepPayload",
"(",
"record",
")",
"try",
... | Override emit() method in handler parent for sending log to RESTful API | [
"Override",
"emit",
"()",
"method",
"in",
"handler",
"parent",
"for",
"sending",
"log",
"to",
"RESTful",
"API"
] | train | https://github.com/narwhaljames/restapi-logging-handler/blob/edaedd3e702e68cfd102bc9fbfa4a33e0c002913/restapi_logging_handler/restapi_logging_handler.py#L228-L243 |
narwhaljames/restapi-logging-handler | restapi_logging_handler/loggly_handler.py | LogglyHandler._getEndpoint | def _getEndpoint(self, add_tags=None):
"""
Override Build Loggly's RESTful API endpoint
"""
return 'https://logs-01.loggly.com/bulk/{0}/tag/{1}/'.format(
self.custom_token,
self._implodeTags(add_tags=add_tags)
) | python | def _getEndpoint(self, add_tags=None):
"""
Override Build Loggly's RESTful API endpoint
"""
return 'https://logs-01.loggly.com/bulk/{0}/tag/{1}/'.format(
self.custom_token,
self._implodeTags(add_tags=add_tags)
) | [
"def",
"_getEndpoint",
"(",
"self",
",",
"add_tags",
"=",
"None",
")",
":",
"return",
"'https://logs-01.loggly.com/bulk/{0}/tag/{1}/'",
".",
"format",
"(",
"self",
".",
"custom_token",
",",
"self",
".",
"_implodeTags",
"(",
"add_tags",
"=",
"add_tags",
")",
")"
... | Override Build Loggly's RESTful API endpoint | [
"Override",
"Build",
"Loggly",
"s",
"RESTful",
"API",
"endpoint"
] | train | https://github.com/narwhaljames/restapi-logging-handler/blob/edaedd3e702e68cfd102bc9fbfa4a33e0c002913/restapi_logging_handler/loggly_handler.py#L109-L117 |
narwhaljames/restapi-logging-handler | restapi_logging_handler/loggly_handler.py | LogglyHandler._getPayload | def _getPayload(self, record):
"""
The data that will be sent to loggly.
"""
payload = super(LogglyHandler, self)._getPayload(record)
payload['tags'] = self._implodeTags()
return payload | python | def _getPayload(self, record):
"""
The data that will be sent to loggly.
"""
payload = super(LogglyHandler, self)._getPayload(record)
payload['tags'] = self._implodeTags()
return payload | [
"def",
"_getPayload",
"(",
"self",
",",
"record",
")",
":",
"payload",
"=",
"super",
"(",
"LogglyHandler",
",",
"self",
")",
".",
"_getPayload",
"(",
"record",
")",
"payload",
"[",
"'tags'",
"]",
"=",
"self",
".",
"_implodeTags",
"(",
")",
"return",
"p... | The data that will be sent to loggly. | [
"The",
"data",
"that",
"will",
"be",
"sent",
"to",
"loggly",
"."
] | train | https://github.com/narwhaljames/restapi-logging-handler/blob/edaedd3e702e68cfd102bc9fbfa4a33e0c002913/restapi_logging_handler/loggly_handler.py#L128-L135 |
narwhaljames/restapi-logging-handler | restapi_logging_handler/loggly_handler.py | LogglyHandler.emit | def emit(self, record):
"""
Override emit() method in handler parent for sending log to RESTful
API
"""
pid = os.getpid()
if pid != self.pid:
self.pid = pid
self.logs = []
self.timer = self._flushAndRepeatTimer()
atexit.reg... | python | def emit(self, record):
"""
Override emit() method in handler parent for sending log to RESTful
API
"""
pid = os.getpid()
if pid != self.pid:
self.pid = pid
self.logs = []
self.timer = self._flushAndRepeatTimer()
atexit.reg... | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"if",
"pid",
"!=",
"self",
".",
"pid",
":",
"self",
".",
"pid",
"=",
"pid",
"self",
".",
"logs",
"=",
"[",
"]",
"self",
".",
"timer",
"=",
"self",... | Override emit() method in handler parent for sending log to RESTful
API | [
"Override",
"emit",
"()",
"method",
"in",
"handler",
"parent",
"for",
"sending",
"log",
"to",
"RESTful",
"API"
] | train | https://github.com/narwhaljames/restapi-logging-handler/blob/edaedd3e702e68cfd102bc9fbfa4a33e0c002913/restapi_logging_handler/loggly_handler.py#L183-L200 |
Metatab/metapack | metapack/doc.py | MetapackDoc.nonver_name | def nonver_name(self):
"""Return the non versioned name"""
nv = self.as_version(None)
if not nv:
import re
nv = re.sub(r'-[^-]+$', '', self.name)
return nv | python | def nonver_name(self):
"""Return the non versioned name"""
nv = self.as_version(None)
if not nv:
import re
nv = re.sub(r'-[^-]+$', '', self.name)
return nv | [
"def",
"nonver_name",
"(",
"self",
")",
":",
"nv",
"=",
"self",
".",
"as_version",
"(",
"None",
")",
"if",
"not",
"nv",
":",
"import",
"re",
"nv",
"=",
"re",
".",
"sub",
"(",
"r'-[^-]+$'",
",",
"''",
",",
"self",
".",
"name",
")",
"return",
"nv"
... | Return the non versioned name | [
"Return",
"the",
"non",
"versioned",
"name"
] | train | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/doc.py#L101-L108 |
Metatab/metapack | metapack/doc.py | MetapackDoc.wrappable_term | def wrappable_term(self, term):
"""Return the Root.Description, possibly combining multiple terms.
:return:
"""
return ' '.join(e.value.strip() for e in self['Root'].find(term) if e and e.value) | python | def wrappable_term(self, term):
"""Return the Root.Description, possibly combining multiple terms.
:return:
"""
return ' '.join(e.value.strip() for e in self['Root'].find(term) if e and e.value) | [
"def",
"wrappable_term",
"(",
"self",
",",
"term",
")",
":",
"return",
"' '",
".",
"join",
"(",
"e",
".",
"value",
".",
"strip",
"(",
")",
"for",
"e",
"in",
"self",
"[",
"'Root'",
"]",
".",
"find",
"(",
"term",
")",
"if",
"e",
"and",
"e",
".",
... | Return the Root.Description, possibly combining multiple terms.
:return: | [
"Return",
"the",
"Root",
".",
"Description",
"possibly",
"combining",
"multiple",
"terms",
".",
":",
"return",
":"
] | train | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/doc.py#L123-L128 |
Metatab/metapack | metapack/doc.py | MetapackDoc.set_wrappable_term | def set_wrappable_term(self, v, term):
"""Set the Root.Description, possibly splitting long descriptions across multiple terms. """
import textwrap
for t in self['Root'].find(term):
self.remove_term(t)
for l in textwrap.wrap(v, 80):
self['Root'].new_term(term, ... | python | def set_wrappable_term(self, v, term):
"""Set the Root.Description, possibly splitting long descriptions across multiple terms. """
import textwrap
for t in self['Root'].find(term):
self.remove_term(t)
for l in textwrap.wrap(v, 80):
self['Root'].new_term(term, ... | [
"def",
"set_wrappable_term",
"(",
"self",
",",
"v",
",",
"term",
")",
":",
"import",
"textwrap",
"for",
"t",
"in",
"self",
"[",
"'Root'",
"]",
".",
"find",
"(",
"term",
")",
":",
"self",
".",
"remove_term",
"(",
"t",
")",
"for",
"l",
"in",
"textwra... | Set the Root.Description, possibly splitting long descriptions across multiple terms. | [
"Set",
"the",
"Root",
".",
"Description",
"possibly",
"splitting",
"long",
"descriptions",
"across",
"multiple",
"terms",
"."
] | train | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/doc.py#L130-L139 |
Metatab/metapack | metapack/doc.py | MetapackDoc.get_lib_module_dict | def get_lib_module_dict(self):
"""Load the 'lib' directory as a python module, so it can be used to provide functions
for rowpipe transforms. This only works filesystem packages"""
from importlib import import_module
if not self.ref:
return {}
u = parse_app_url(se... | python | def get_lib_module_dict(self):
"""Load the 'lib' directory as a python module, so it can be used to provide functions
for rowpipe transforms. This only works filesystem packages"""
from importlib import import_module
if not self.ref:
return {}
u = parse_app_url(se... | [
"def",
"get_lib_module_dict",
"(",
"self",
")",
":",
"from",
"importlib",
"import",
"import_module",
"if",
"not",
"self",
".",
"ref",
":",
"return",
"{",
"}",
"u",
"=",
"parse_app_url",
"(",
"self",
".",
"ref",
")",
"if",
"u",
".",
"scheme",
"==",
"'fi... | Load the 'lib' directory as a python module, so it can be used to provide functions
for rowpipe transforms. This only works filesystem packages | [
"Load",
"the",
"lib",
"directory",
"as",
"a",
"python",
"module",
"so",
"it",
"can",
"be",
"used",
"to",
"provide",
"functions",
"for",
"rowpipe",
"transforms",
".",
"This",
"only",
"works",
"filesystem",
"packages"
] | train | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/doc.py#L187-L219 |
Metatab/metapack | metapack/doc.py | MetapackDoc._repr_html_ | def _repr_html_(self, **kwargs):
"""Produce HTML for Jupyter Notebook"""
from jinja2 import Template
from markdown import markdown as convert_markdown
extensions = [
'markdown.extensions.extra',
'markdown.extensions.admonition'
]
return convert_m... | python | def _repr_html_(self, **kwargs):
"""Produce HTML for Jupyter Notebook"""
from jinja2 import Template
from markdown import markdown as convert_markdown
extensions = [
'markdown.extensions.extra',
'markdown.extensions.admonition'
]
return convert_m... | [
"def",
"_repr_html_",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"jinja2",
"import",
"Template",
"from",
"markdown",
"import",
"markdown",
"as",
"convert_markdown",
"extensions",
"=",
"[",
"'markdown.extensions.extra'",
",",
"'markdown.extensions.admoni... | Produce HTML for Jupyter Notebook | [
"Produce",
"HTML",
"for",
"Jupyter",
"Notebook"
] | train | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/doc.py#L233-L243 |
Metatab/metapack | metapack/doc.py | MetapackDoc.write_csv | def write_csv(self, path=None):
"""Write CSV file. Sorts the sections before calling the superclass write_csv"""
# Sort the Sections
self.sort_sections(['Root', 'Contacts', 'Documentation', 'References', 'Resources', 'Citations', 'Schema'])
# Sort Terms in the root section
# ... | python | def write_csv(self, path=None):
"""Write CSV file. Sorts the sections before calling the superclass write_csv"""
# Sort the Sections
self.sort_sections(['Root', 'Contacts', 'Documentation', 'References', 'Resources', 'Citations', 'Schema'])
# Sort Terms in the root section
# ... | [
"def",
"write_csv",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"# Sort the Sections",
"self",
".",
"sort_sections",
"(",
"[",
"'Root'",
",",
"'Contacts'",
",",
"'Documentation'",
",",
"'References'",
",",
"'Resources'",
",",
"'Citations'",
",",
"'Schema'... | Write CSV file. Sorts the sections before calling the superclass write_csv | [
"Write",
"CSV",
"file",
".",
"Sorts",
"the",
"sections",
"before",
"calling",
"the",
"superclass",
"write_csv"
] | train | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/doc.py#L283-L304 |
project-rig/rig | rig/wizard.py | dimensions_wizard | def dimensions_wizard():
"""A wizard which attempts to determine the dimensions of a SpiNNaker
system.
.. warning::
Since SC&MP v2.0.0 it is not necessary to know the dimensions of a
SpiNNaker machine in order to boot it. As a result, most applications
will no longer require this w... | python | def dimensions_wizard():
"""A wizard which attempts to determine the dimensions of a SpiNNaker
system.
.. warning::
Since SC&MP v2.0.0 it is not necessary to know the dimensions of a
SpiNNaker machine in order to boot it. As a result, most applications
will no longer require this w... | [
"def",
"dimensions_wizard",
"(",
")",
":",
"option",
"=",
"yield",
"MultipleChoice",
"(",
"\"What type of SpiNNaker system to you have?\"",
",",
"[",
"\"A single four-chip 'SpiNN-3' board\"",
",",
"\"A single forty-eight-chip 'SpiNN-5' board\"",
",",
"\"Multiple forty-eight-chip 'S... | A wizard which attempts to determine the dimensions of a SpiNNaker
system.
.. warning::
Since SC&MP v2.0.0 it is not necessary to know the dimensions of a
SpiNNaker machine in order to boot it. As a result, most applications
will no longer require this wizard step.
Returns ``{"dim... | [
"A",
"wizard",
"which",
"attempts",
"to",
"determine",
"the",
"dimensions",
"of",
"a",
"SpiNNaker",
"system",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/wizard.py#L90-L137 |
project-rig/rig | rig/wizard.py | ip_address_wizard | def ip_address_wizard():
"""A wizard which attempts to determine the IP of a SpiNNaker system.
Returns ``{"ip_address": "..."}`` via the :py:exc:`~rig.wizard.Success`
exception.
"""
option = yield MultipleChoice(
"Would you like to auto-detect the SpiNNaker system's IP address?",
["... | python | def ip_address_wizard():
"""A wizard which attempts to determine the IP of a SpiNNaker system.
Returns ``{"ip_address": "..."}`` via the :py:exc:`~rig.wizard.Success`
exception.
"""
option = yield MultipleChoice(
"Would you like to auto-detect the SpiNNaker system's IP address?",
["... | [
"def",
"ip_address_wizard",
"(",
")",
":",
"option",
"=",
"yield",
"MultipleChoice",
"(",
"\"Would you like to auto-detect the SpiNNaker system's IP address?\"",
",",
"[",
"\"Auto-detect\"",
",",
"\"Manually Enter IP address or hostname\"",
"]",
",",
"0",
")",
"assert",
"0"... | A wizard which attempts to determine the IP of a SpiNNaker system.
Returns ``{"ip_address": "..."}`` via the :py:exc:`~rig.wizard.Success`
exception. | [
"A",
"wizard",
"which",
"attempts",
"to",
"determine",
"the",
"IP",
"of",
"a",
"SpiNNaker",
"system",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/wizard.py#L140-L167 |
project-rig/rig | rig/wizard.py | cat | def cat(*wizards):
"""A higher-order wizard which is the concatenation of a number of other
wizards.
The resulting data is the union of all wizard outputs.
"""
data = {}
for wizard in wizards:
try:
response = None
while True:
response = yield wiz... | python | def cat(*wizards):
"""A higher-order wizard which is the concatenation of a number of other
wizards.
The resulting data is the union of all wizard outputs.
"""
data = {}
for wizard in wizards:
try:
response = None
while True:
response = yield wiz... | [
"def",
"cat",
"(",
"*",
"wizards",
")",
":",
"data",
"=",
"{",
"}",
"for",
"wizard",
"in",
"wizards",
":",
"try",
":",
"response",
"=",
"None",
"while",
"True",
":",
"response",
"=",
"yield",
"wizard",
".",
"send",
"(",
"response",
")",
"except",
"... | A higher-order wizard which is the concatenation of a number of other
wizards.
The resulting data is the union of all wizard outputs. | [
"A",
"higher",
"-",
"order",
"wizard",
"which",
"is",
"the",
"concatenation",
"of",
"a",
"number",
"of",
"other",
"wizards",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/wizard.py#L170-L186 |
project-rig/rig | rig/wizard.py | cli_wrapper | def cli_wrapper(generator):
"""Given a wizard, implements an interactive command-line human-friendly
interface for it.
Parameters
----------
generator
A generator such as one created by calling
:py:func:`rig.wizard.wizard_generator`.
Returns
-------
dict or None
... | python | def cli_wrapper(generator):
"""Given a wizard, implements an interactive command-line human-friendly
interface for it.
Parameters
----------
generator
A generator such as one created by calling
:py:func:`rig.wizard.wizard_generator`.
Returns
-------
dict or None
... | [
"def",
"cli_wrapper",
"(",
"generator",
")",
":",
"first",
"=",
"True",
"response",
"=",
"None",
"while",
"True",
":",
"# Insert blank lines between prompts",
"if",
"not",
"first",
":",
"print",
"(",
")",
"first",
"=",
"False",
"try",
":",
"message",
"=",
... | Given a wizard, implements an interactive command-line human-friendly
interface for it.
Parameters
----------
generator
A generator such as one created by calling
:py:func:`rig.wizard.wizard_generator`.
Returns
-------
dict or None
Returns a dictionary containing th... | [
"Given",
"a",
"wizard",
"implements",
"an",
"interactive",
"command",
"-",
"line",
"human",
"-",
"friendly",
"interface",
"for",
"it",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/wizard.py#L189-L250 |
project-rig/rig | rig/place_and_route/place/sa/python_kernel.py | _net_cost | def _net_cost(net, placements, has_wrap_around_links, machine):
"""Get the cost of a given net.
This function, in principle at least, should estimate the total network
resources consumed by the given net. In practice this estimate is based on
the size of the bounding-box of the net (i.e. HPWL). This sh... | python | def _net_cost(net, placements, has_wrap_around_links, machine):
"""Get the cost of a given net.
This function, in principle at least, should estimate the total network
resources consumed by the given net. In practice this estimate is based on
the size of the bounding-box of the net (i.e. HPWL). This sh... | [
"def",
"_net_cost",
"(",
"net",
",",
"placements",
",",
"has_wrap_around_links",
",",
"machine",
")",
":",
"# This function is by far the hottest code in the entire algorithm, as a",
"# result, small performance improvements in here can have significant",
"# impact on the runtime of the ... | Get the cost of a given net.
This function, in principle at least, should estimate the total network
resources consumed by the given net. In practice this estimate is based on
the size of the bounding-box of the net (i.e. HPWL). This should be
improved at some later time to better account for the effec... | [
"Get",
"the",
"cost",
"of",
"a",
"given",
"net",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/sa/python_kernel.py#L118-L210 |
project-rig/rig | rig/place_and_route/place/sa/python_kernel.py | _vertex_net_cost | def _vertex_net_cost(vertex, v2n, placements, has_wrap_around_links, machine):
"""Get the total cost of the nets connected to the given vertex.
Parameters
----------
vertex
The vertex whose nets we're interested in.
v2n : {vertex: [:py:class:`rig.netlist.Net`, ...], ...}
placements : {v... | python | def _vertex_net_cost(vertex, v2n, placements, has_wrap_around_links, machine):
"""Get the total cost of the nets connected to the given vertex.
Parameters
----------
vertex
The vertex whose nets we're interested in.
v2n : {vertex: [:py:class:`rig.netlist.Net`, ...], ...}
placements : {v... | [
"def",
"_vertex_net_cost",
"(",
"vertex",
",",
"v2n",
",",
"placements",
",",
"has_wrap_around_links",
",",
"machine",
")",
":",
"total_cost",
"=",
"0.0",
"for",
"net",
"in",
"v2n",
"[",
"vertex",
"]",
":",
"total_cost",
"+=",
"_net_cost",
"(",
"net",
",",... | Get the total cost of the nets connected to the given vertex.
Parameters
----------
vertex
The vertex whose nets we're interested in.
v2n : {vertex: [:py:class:`rig.netlist.Net`, ...], ...}
placements : {vertex: (x, y), ...}
has_wrap_around_links : bool
machine : :py:class:`rig.plac... | [
"Get",
"the",
"total",
"cost",
"of",
"the",
"nets",
"connected",
"to",
"the",
"given",
"vertex",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/sa/python_kernel.py#L213-L234 |
project-rig/rig | rig/place_and_route/place/sa/python_kernel.py | _get_candidate_swap | def _get_candidate_swap(resources, location,
l2v, vertices_resources, fixed_vertices, machine):
"""Given a chip location, select a set of vertices which would have to be
moved elsewhere to accommodate the arrival of the specified set of
resources.
Parameters
----------
r... | python | def _get_candidate_swap(resources, location,
l2v, vertices_resources, fixed_vertices, machine):
"""Given a chip location, select a set of vertices which would have to be
moved elsewhere to accommodate the arrival of the specified set of
resources.
Parameters
----------
r... | [
"def",
"_get_candidate_swap",
"(",
"resources",
",",
"location",
",",
"l2v",
",",
"vertices_resources",
",",
"fixed_vertices",
",",
"machine",
")",
":",
"# The resources already available at the given location",
"chip_resources",
"=",
"machine",
"[",
"location",
"]",
"#... | Given a chip location, select a set of vertices which would have to be
moved elsewhere to accommodate the arrival of the specified set of
resources.
Parameters
----------
resources : {resource: value, ...}
The amount of resources which are required at the specified location.
location : ... | [
"Given",
"a",
"chip",
"location",
"select",
"a",
"set",
"of",
"vertices",
"which",
"would",
"have",
"to",
"be",
"moved",
"elsewhere",
"to",
"accommodate",
"the",
"arrival",
"of",
"the",
"specified",
"set",
"of",
"resources",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/sa/python_kernel.py#L237-L292 |
project-rig/rig | rig/place_and_route/place/sa/python_kernel.py | _swap | def _swap(vas, vas_location, vbs, vbs_location, l2v, vertices_resources,
placements, machine):
"""Swap the positions of two sets of vertices.
Parameters
----------
vas : [vertex, ...]
A set of vertices currently at vas_location.
vas_location : (x, y)
vbs : [vertex, ...]
... | python | def _swap(vas, vas_location, vbs, vbs_location, l2v, vertices_resources,
placements, machine):
"""Swap the positions of two sets of vertices.
Parameters
----------
vas : [vertex, ...]
A set of vertices currently at vas_location.
vas_location : (x, y)
vbs : [vertex, ...]
... | [
"def",
"_swap",
"(",
"vas",
",",
"vas_location",
",",
"vbs",
",",
"vbs_location",
",",
"l2v",
",",
"vertices_resources",
",",
"placements",
",",
"machine",
")",
":",
"# Get the lists of vertices at either location",
"vas_location2v",
"=",
"l2v",
"[",
"vas_location",... | Swap the positions of two sets of vertices.
Parameters
----------
vas : [vertex, ...]
A set of vertices currently at vas_location.
vas_location : (x, y)
vbs : [vertex, ...]
A set of vertices currently at vbs_location.
vbs_location : (x, y)
l2v : {(x, y): [vertex, ...], ...}
... | [
"Swap",
"the",
"positions",
"of",
"two",
"sets",
"of",
"vertices",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/sa/python_kernel.py#L295-L349 |
project-rig/rig | rig/place_and_route/place/sa/python_kernel.py | _step | def _step(vertices, d_limit, temperature, placements, l2v, v2n,
vertices_resources, fixed_vertices, machine, has_wrap_around_links,
random):
"""Attempt a single swap operation: the kernel of the Simulated Annealing
algorithm.
Parameters
----------
vertices : [vertex, ...]
... | python | def _step(vertices, d_limit, temperature, placements, l2v, v2n,
vertices_resources, fixed_vertices, machine, has_wrap_around_links,
random):
"""Attempt a single swap operation: the kernel of the Simulated Annealing
algorithm.
Parameters
----------
vertices : [vertex, ...]
... | [
"def",
"_step",
"(",
"vertices",
",",
"d_limit",
",",
"temperature",
",",
"placements",
",",
"l2v",
",",
"v2n",
",",
"vertices_resources",
",",
"fixed_vertices",
",",
"machine",
",",
"has_wrap_around_links",
",",
"random",
")",
":",
"# Special case: If the machine... | Attempt a single swap operation: the kernel of the Simulated Annealing
algorithm.
Parameters
----------
vertices : [vertex, ...]
The set of *movable* vertices.
d_limit : int
The maximum distance over-which swaps are allowed.
temperature : float > 0.0 or None
The temperat... | [
"Attempt",
"a",
"single",
"swap",
"operation",
":",
"the",
"kernel",
"of",
"the",
"Simulated",
"Annealing",
"algorithm",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/sa/python_kernel.py#L352-L478 |
NicolasLM/spinach | spinach/brokers/redis.py | RedisBroker._reset | def _reset(self):
"""Initialization that must happen before the broker is (re)started."""
self._subscriber_thread = None
self._must_stop = threading.Event()
self._number_periodic_tasks = 0 | python | def _reset(self):
"""Initialization that must happen before the broker is (re)started."""
self._subscriber_thread = None
self._must_stop = threading.Event()
self._number_periodic_tasks = 0 | [
"def",
"_reset",
"(",
"self",
")",
":",
"self",
".",
"_subscriber_thread",
"=",
"None",
"self",
".",
"_must_stop",
"=",
"threading",
".",
"Event",
"(",
")",
"self",
".",
"_number_periodic_tasks",
"=",
"0"
] | Initialization that must happen before the broker is (re)started. | [
"Initialization",
"that",
"must",
"happen",
"before",
"the",
"broker",
"is",
"(",
"re",
")",
"started",
"."
] | train | https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/brokers/redis.py#L56-L60 |
NicolasLM/spinach | spinach/brokers/redis.py | RedisBroker._load_script | def _load_script(self, filename: str) -> Script:
"""Load a Lua script.
Read the Lua script file to generate its Script object. If the script
starts with a magic string, add it to the list of scripts requiring an
idempotency token to execute.
"""
with open(path.join(here,... | python | def _load_script(self, filename: str) -> Script:
"""Load a Lua script.
Read the Lua script file to generate its Script object. If the script
starts with a magic string, add it to the list of scripts requiring an
idempotency token to execute.
"""
with open(path.join(here,... | [
"def",
"_load_script",
"(",
"self",
",",
"filename",
":",
"str",
")",
"->",
"Script",
":",
"with",
"open",
"(",
"path",
".",
"join",
"(",
"here",
",",
"'redis_scripts'",
",",
"filename",
")",
",",
"mode",
"=",
"'rb'",
")",
"as",
"f",
":",
"script_dat... | Load a Lua script.
Read the Lua script file to generate its Script object. If the script
starts with a magic string, add it to the list of scripts requiring an
idempotency token to execute. | [
"Load",
"a",
"Lua",
"script",
"."
] | train | https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/brokers/redis.py#L62-L74 |
NicolasLM/spinach | spinach/brokers/redis.py | RedisBroker.enqueue_jobs | def enqueue_jobs(self, jobs: Iterable[Job]):
"""Enqueue a batch of jobs."""
jobs_to_queue = list()
for job in jobs:
if job.should_start:
job.status = JobStatus.QUEUED
else:
job.status = JobStatus.WAITING
jobs_to_queue.append(job... | python | def enqueue_jobs(self, jobs: Iterable[Job]):
"""Enqueue a batch of jobs."""
jobs_to_queue = list()
for job in jobs:
if job.should_start:
job.status = JobStatus.QUEUED
else:
job.status = JobStatus.WAITING
jobs_to_queue.append(job... | [
"def",
"enqueue_jobs",
"(",
"self",
",",
"jobs",
":",
"Iterable",
"[",
"Job",
"]",
")",
":",
"jobs_to_queue",
"=",
"list",
"(",
")",
"for",
"job",
"in",
"jobs",
":",
"if",
"job",
".",
"should_start",
":",
"job",
".",
"status",
"=",
"JobStatus",
".",
... | Enqueue a batch of jobs. | [
"Enqueue",
"a",
"batch",
"of",
"jobs",
"."
] | train | https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/brokers/redis.py#L100-L118 |
NicolasLM/spinach | spinach/brokers/redis.py | RedisBroker.get_jobs_from_queue | def get_jobs_from_queue(self, queue: str, max_jobs: int) -> List[Job]:
"""Get jobs from a queue."""
jobs_json_string = self._run_script(
self._get_jobs_from_queue,
self._to_namespaced(queue),
self._to_namespaced(RUNNING_JOBS_KEY.format(self._id)),
JobStatu... | python | def get_jobs_from_queue(self, queue: str, max_jobs: int) -> List[Job]:
"""Get jobs from a queue."""
jobs_json_string = self._run_script(
self._get_jobs_from_queue,
self._to_namespaced(queue),
self._to_namespaced(RUNNING_JOBS_KEY.format(self._id)),
JobStatu... | [
"def",
"get_jobs_from_queue",
"(",
"self",
",",
"queue",
":",
"str",
",",
"max_jobs",
":",
"int",
")",
"->",
"List",
"[",
"Job",
"]",
":",
"jobs_json_string",
"=",
"self",
".",
"_run_script",
"(",
"self",
".",
"_get_jobs_from_queue",
",",
"self",
".",
"_... | Get jobs from a queue. | [
"Get",
"jobs",
"from",
"a",
"queue",
"."
] | train | https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/brokers/redis.py#L145-L158 |
NicolasLM/spinach | spinach/brokers/redis.py | RedisBroker.register_periodic_tasks | def register_periodic_tasks(self, tasks: Iterable[Task]):
"""Register tasks that need to be scheduled periodically."""
tasks = [task.serialize() for task in tasks]
self._number_periodic_tasks = len(tasks)
self._run_script(
self._register_periodic_tasks,
math.ceil(... | python | def register_periodic_tasks(self, tasks: Iterable[Task]):
"""Register tasks that need to be scheduled periodically."""
tasks = [task.serialize() for task in tasks]
self._number_periodic_tasks = len(tasks)
self._run_script(
self._register_periodic_tasks,
math.ceil(... | [
"def",
"register_periodic_tasks",
"(",
"self",
",",
"tasks",
":",
"Iterable",
"[",
"Task",
"]",
")",
":",
"tasks",
"=",
"[",
"task",
".",
"serialize",
"(",
")",
"for",
"task",
"in",
"tasks",
"]",
"self",
".",
"_number_periodic_tasks",
"=",
"len",
"(",
... | Register tasks that need to be scheduled periodically. | [
"Register",
"tasks",
"that",
"need",
"to",
"be",
"scheduled",
"periodically",
"."
] | train | https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/brokers/redis.py#L203-L213 |
NicolasLM/spinach | spinach/brokers/redis.py | RedisBroker.inspect_periodic_tasks | def inspect_periodic_tasks(self) -> List[Tuple[int, str]]:
"""Get the next periodic task schedule.
Used only for debugging and during tests.
"""
rv = self._r.zrangebyscore(
self._to_namespaced(PERIODIC_TASKS_QUEUE_KEY),
'-inf', '+inf', withscores=True
)
... | python | def inspect_periodic_tasks(self) -> List[Tuple[int, str]]:
"""Get the next periodic task schedule.
Used only for debugging and during tests.
"""
rv = self._r.zrangebyscore(
self._to_namespaced(PERIODIC_TASKS_QUEUE_KEY),
'-inf', '+inf', withscores=True
)
... | [
"def",
"inspect_periodic_tasks",
"(",
"self",
")",
"->",
"List",
"[",
"Tuple",
"[",
"int",
",",
"str",
"]",
"]",
":",
"rv",
"=",
"self",
".",
"_r",
".",
"zrangebyscore",
"(",
"self",
".",
"_to_namespaced",
"(",
"PERIODIC_TASKS_QUEUE_KEY",
")",
",",
"'-in... | Get the next periodic task schedule.
Used only for debugging and during tests. | [
"Get",
"the",
"next",
"periodic",
"task",
"schedule",
"."
] | train | https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/brokers/redis.py#L215-L224 |
NicolasLM/spinach | spinach/brokers/redis.py | RedisBroker.next_future_periodic_delta | def next_future_periodic_delta(self) -> Optional[float]:
"""Give the amount of seconds before the next periodic task is due."""
rv = self._r.zrangebyscore(
self._to_namespaced(PERIODIC_TASKS_QUEUE_KEY),
'-inf', '+inf', start=0, num=1, withscores=True,
score_cast_func=... | python | def next_future_periodic_delta(self) -> Optional[float]:
"""Give the amount of seconds before the next periodic task is due."""
rv = self._r.zrangebyscore(
self._to_namespaced(PERIODIC_TASKS_QUEUE_KEY),
'-inf', '+inf', start=0, num=1, withscores=True,
score_cast_func=... | [
"def",
"next_future_periodic_delta",
"(",
"self",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"rv",
"=",
"self",
".",
"_r",
".",
"zrangebyscore",
"(",
"self",
".",
"_to_namespaced",
"(",
"PERIODIC_TASKS_QUEUE_KEY",
")",
",",
"'-inf'",
",",
"'+inf'",
",",
... | Give the amount of seconds before the next periodic task is due. | [
"Give",
"the",
"amount",
"of",
"seconds",
"before",
"the",
"next",
"periodic",
"task",
"is",
"due",
"."
] | train | https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/brokers/redis.py#L227-L242 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/hnv_neutron_agent.py | main | def main():
"""The entry point for the HNV Agent."""
neutron_config.register_agent_state_opts_helper(CONF)
common_config.init(sys.argv[1:])
neutron_config.setup_logging()
hnv_agent = HNVAgent()
# Start everything.
LOG.info("Agent initialized successfully, now running... ")
hnv_agent.da... | python | def main():
"""The entry point for the HNV Agent."""
neutron_config.register_agent_state_opts_helper(CONF)
common_config.init(sys.argv[1:])
neutron_config.setup_logging()
hnv_agent = HNVAgent()
# Start everything.
LOG.info("Agent initialized successfully, now running... ")
hnv_agent.da... | [
"def",
"main",
"(",
")",
":",
"neutron_config",
".",
"register_agent_state_opts_helper",
"(",
"CONF",
")",
"common_config",
".",
"init",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"neutron_config",
".",
"setup_logging",
"(",
")",
"hnv_agent",
"=",
"... | The entry point for the HNV Agent. | [
"The",
"entry",
"point",
"for",
"the",
"HNV",
"Agent",
"."
] | train | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/hnv_neutron_agent.py#L94-L104 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/hnv_neutron_agent.py | HNVAgent._provision_network | def _provision_network(self, port_id, net_uuid, network_type,
physical_network, segmentation_id):
"""Provision the network with the received information."""
LOG.info("Provisioning network %s", net_uuid)
vswitch_name = self._get_vswitch_name(network_type, physical_netw... | python | def _provision_network(self, port_id, net_uuid, network_type,
physical_network, segmentation_id):
"""Provision the network with the received information."""
LOG.info("Provisioning network %s", net_uuid)
vswitch_name = self._get_vswitch_name(network_type, physical_netw... | [
"def",
"_provision_network",
"(",
"self",
",",
"port_id",
",",
"net_uuid",
",",
"network_type",
",",
"physical_network",
",",
"segmentation_id",
")",
":",
"LOG",
".",
"info",
"(",
"\"Provisioning network %s\"",
",",
"net_uuid",
")",
"vswitch_name",
"=",
"self",
... | Provision the network with the received information. | [
"Provision",
"the",
"network",
"with",
"the",
"received",
"information",
"."
] | train | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/hnv_neutron_agent.py#L57-L68 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/hnv_neutron_agent.py | HNVAgent._port_bound | def _port_bound(self, port_id, network_id, network_type, physical_network,
segmentation_id, port_security_enabled, set_port_sriov):
"""Bind the port to the recived network."""
super(HNVAgent, self)._port_bound(port_id, network_id, network_type,
... | python | def _port_bound(self, port_id, network_id, network_type, physical_network,
segmentation_id, port_security_enabled, set_port_sriov):
"""Bind the port to the recived network."""
super(HNVAgent, self)._port_bound(port_id, network_id, network_type,
... | [
"def",
"_port_bound",
"(",
"self",
",",
"port_id",
",",
"network_id",
",",
"network_type",
",",
"physical_network",
",",
"segmentation_id",
",",
"port_security_enabled",
",",
"set_port_sriov",
")",
":",
"super",
"(",
"HNVAgent",
",",
"self",
")",
".",
"_port_bou... | Bind the port to the recived network. | [
"Bind",
"the",
"port",
"to",
"the",
"recived",
"network",
"."
] | train | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/hnv_neutron_agent.py#L70-L91 |
project-rig/rig | rig/machine_control/scp_connection.py | SCPConnection.send_scp | def send_scp(self, buffer_size, x, y, p, cmd, arg1=0, arg2=0, arg3=0,
data=b'', expected_args=3, timeout=0.0):
"""Transmit a packet to the SpiNNaker machine and block until an
acknowledgement is received.
Parameters
----------
buffer_size : int
Numbe... | python | def send_scp(self, buffer_size, x, y, p, cmd, arg1=0, arg2=0, arg3=0,
data=b'', expected_args=3, timeout=0.0):
"""Transmit a packet to the SpiNNaker machine and block until an
acknowledgement is received.
Parameters
----------
buffer_size : int
Numbe... | [
"def",
"send_scp",
"(",
"self",
",",
"buffer_size",
",",
"x",
",",
"y",
",",
"p",
",",
"cmd",
",",
"arg1",
"=",
"0",
",",
"arg2",
"=",
"0",
",",
"arg3",
"=",
"0",
",",
"data",
"=",
"b''",
",",
"expected_args",
"=",
"3",
",",
"timeout",
"=",
"... | Transmit a packet to the SpiNNaker machine and block until an
acknowledgement is received.
Parameters
----------
buffer_size : int
Number of bytes held in an SCP buffer by SARK, determines how many
bytes will be expected in a socket.
x : int
y : i... | [
"Transmit",
"a",
"packet",
"to",
"the",
"SpiNNaker",
"machine",
"and",
"block",
"until",
"an",
"acknowledgement",
"is",
"received",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/scp_connection.py#L83-L137 |
project-rig/rig | rig/machine_control/scp_connection.py | SCPConnection.send_scp_burst | def send_scp_burst(self, buffer_size, window_size,
parameters_and_callbacks):
"""Send a burst of SCP packets and call a callback for each returned
packet.
Parameters
----------
buffer_size : int
Number of bytes held in an SCP buffer by SARK, de... | python | def send_scp_burst(self, buffer_size, window_size,
parameters_and_callbacks):
"""Send a burst of SCP packets and call a callback for each returned
packet.
Parameters
----------
buffer_size : int
Number of bytes held in an SCP buffer by SARK, de... | [
"def",
"send_scp_burst",
"(",
"self",
",",
"buffer_size",
",",
"window_size",
",",
"parameters_and_callbacks",
")",
":",
"parameters_and_callbacks",
"=",
"iter",
"(",
"parameters_and_callbacks",
")",
"self",
".",
"sock",
".",
"setblocking",
"(",
"False",
")",
"# C... | Send a burst of SCP packets and call a callback for each returned
packet.
Parameters
----------
buffer_size : int
Number of bytes held in an SCP buffer by SARK, determines how many
bytes will be expected in a socket.
window_size : int
Number o... | [
"Send",
"a",
"burst",
"of",
"SCP",
"packets",
"and",
"call",
"a",
"callback",
"for",
"each",
"returned",
"packet",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/scp_connection.py#L139-L304 |
project-rig/rig | rig/machine_control/scp_connection.py | SCPConnection.read | def read(self, buffer_size, window_size, x, y, p, address, length_bytes):
"""Read a bytestring from an address in memory.
..note::
This method is included here to maintain API compatibility with an
`alternative implementation of SCP
<https://github.com/project-rig/ri... | python | def read(self, buffer_size, window_size, x, y, p, address, length_bytes):
"""Read a bytestring from an address in memory.
..note::
This method is included here to maintain API compatibility with an
`alternative implementation of SCP
<https://github.com/project-rig/ri... | [
"def",
"read",
"(",
"self",
",",
"buffer_size",
",",
"window_size",
",",
"x",
",",
"y",
",",
"p",
",",
"address",
",",
"length_bytes",
")",
":",
"# Prepare the buffer to receive the incoming data",
"data",
"=",
"bytearray",
"(",
"length_bytes",
")",
"mem",
"="... | Read a bytestring from an address in memory.
..note::
This method is included here to maintain API compatibility with an
`alternative implementation of SCP
<https://github.com/project-rig/rig-scp>`_.
Parameters
----------
buffer_size : int
... | [
"Read",
"a",
"bytestring",
"from",
"an",
"address",
"in",
"memory",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/scp_connection.py#L306-L370 |
project-rig/rig | rig/machine_control/scp_connection.py | SCPConnection.write | def write(self, buffer_size, window_size, x, y, p, address, data):
"""Write a bytestring to an address in memory.
..note::
This method is included here to maintain API compatibility with an
`alternative implementation of SCP
<https://github.com/project-rig/rig-scp>`_... | python | def write(self, buffer_size, window_size, x, y, p, address, data):
"""Write a bytestring to an address in memory.
..note::
This method is included here to maintain API compatibility with an
`alternative implementation of SCP
<https://github.com/project-rig/rig-scp>`_... | [
"def",
"write",
"(",
"self",
",",
"buffer_size",
",",
"window_size",
",",
"x",
",",
"y",
",",
"p",
",",
"address",
",",
"data",
")",
":",
"# While there is still data perform a write: get the block to write",
"# this time around, determine the data type, perform the write a... | Write a bytestring to an address in memory.
..note::
This method is included here to maintain API compatibility with an
`alternative implementation of SCP
<https://github.com/project-rig/rig-scp>`_.
Parameters
----------
buffer_size : int
... | [
"Write",
"a",
"bytestring",
"to",
"an",
"address",
"in",
"memory",
"."
] | train | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/scp_connection.py#L372-L419 |
belbio/bel | bel/nanopub/validate.py | convert_msg_to_html | def convert_msg_to_html(msg):
"""Convert \n into a <BR> for an HTML formatted message"""
msg = re.sub("\n", "<br />", msg, flags=re.MULTILINE)
return msg | python | def convert_msg_to_html(msg):
"""Convert \n into a <BR> for an HTML formatted message"""
msg = re.sub("\n", "<br />", msg, flags=re.MULTILINE)
return msg | [
"def",
"convert_msg_to_html",
"(",
"msg",
")",
":",
"msg",
"=",
"re",
".",
"sub",
"(",
"\"\\n\"",
",",
"\"<br />\"",
",",
"msg",
",",
"flags",
"=",
"re",
".",
"MULTILINE",
")",
"return",
"msg"
] | Convert \n into a <BR> for an HTML formatted message | [
"Convert",
"\\",
"n",
"into",
"a",
"<BR",
">",
"for",
"an",
"HTML",
"formatted",
"message"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/validate.py#L15-L19 |
belbio/bel | bel/nanopub/validate.py | validate | def validate(nanopub: dict, error_level: str = "WARNING") -> Tuple[str, str, str]:
"""Validate Nanopub
Error Levels are similar to log levels - selecting WARNING includes both
WARNING and ERROR, selecting ERROR just includes ERROR
The validation result is a list of objects containing
{
... | python | def validate(nanopub: dict, error_level: str = "WARNING") -> Tuple[str, str, str]:
"""Validate Nanopub
Error Levels are similar to log levels - selecting WARNING includes both
WARNING and ERROR, selecting ERROR just includes ERROR
The validation result is a list of objects containing
{
... | [
"def",
"validate",
"(",
"nanopub",
":",
"dict",
",",
"error_level",
":",
"str",
"=",
"\"WARNING\"",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
",",
"str",
"]",
":",
"# Validation results",
"v",
"=",
"[",
"]",
"bel_version",
"=",
"config",
"[",
"\"bel\... | Validate Nanopub
Error Levels are similar to log levels - selecting WARNING includes both
WARNING and ERROR, selecting ERROR just includes ERROR
The validation result is a list of objects containing
{
'level': 'Warning|Error',
'section': 'Assertion|Annotation|Structure',
... | [
"Validate",
"Nanopub"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/validate.py#L22-L219 |
belbio/bel | bel/lang/bel_specification.py | get_specification | def get_specification(version: str) -> Mapping[str, Any]:
"""Get BEL Specification
The json file this depends on is generated by belspec_yaml2json as
part of the update_specifications function
Args:
version: e.g. 2.0.0 where the filename
"""
spec_dir = config["bel"]["lang"]["specifica... | python | def get_specification(version: str) -> Mapping[str, Any]:
"""Get BEL Specification
The json file this depends on is generated by belspec_yaml2json as
part of the update_specifications function
Args:
version: e.g. 2.0.0 where the filename
"""
spec_dir = config["bel"]["lang"]["specifica... | [
"def",
"get_specification",
"(",
"version",
":",
"str",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"spec_dir",
"=",
"config",
"[",
"\"bel\"",
"]",
"[",
"\"lang\"",
"]",
"[",
"\"specifications\"",
"]",
"spec_dict",
"=",
"{",
"}",
"bel_version... | Get BEL Specification
The json file this depends on is generated by belspec_yaml2json as
part of the update_specifications function
Args:
version: e.g. 2.0.0 where the filename | [
"Get",
"BEL",
"Specification"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_specification.py#L96-L122 |
belbio/bel | bel/lang/bel_specification.py | get_bel_versions | def get_bel_versions() -> List[str]:
"""Get BEL Language versions supported
Get the list of all BEL Language versions supported. The file this depends
on is generated by belspec_yaml2json and is kept up to date using
`make update_ebnf` or `make update_parsers`. You can also run `belspec_yaml2json`
... | python | def get_bel_versions() -> List[str]:
"""Get BEL Language versions supported
Get the list of all BEL Language versions supported. The file this depends
on is generated by belspec_yaml2json and is kept up to date using
`make update_ebnf` or `make update_parsers`. You can also run `belspec_yaml2json`
... | [
"def",
"get_bel_versions",
"(",
")",
"->",
"List",
"[",
"str",
"]",
":",
"spec_dir",
"=",
"config",
"[",
"\"bel\"",
"]",
"[",
"\"lang\"",
"]",
"[",
"\"specifications\"",
"]",
"fn",
"=",
"f\"{spec_dir}/versions.json\"",
"with",
"open",
"(",
"fn",
",",
"\"r\... | Get BEL Language versions supported
Get the list of all BEL Language versions supported. The file this depends
on is generated by belspec_yaml2json and is kept up to date using
`make update_ebnf` or `make update_parsers`. You can also run `belspec_yaml2json`
directly as it's added as a command by pip... | [
"Get",
"BEL",
"Language",
"versions",
"supported"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_specification.py#L125-L143 |
belbio/bel | bel/lang/bel_specification.py | update_specifications | def update_specifications(force: bool = False):
"""Update BEL specifications
Collect BEL specifications from Github BELBio BEL Specification folder
and store in local directory specified in belbio_conf.yaml
Process all BEL Specifications in YAML into an enhanced JSON version
and capture all BEL ve... | python | def update_specifications(force: bool = False):
"""Update BEL specifications
Collect BEL specifications from Github BELBio BEL Specification folder
and store in local directory specified in belbio_conf.yaml
Process all BEL Specifications in YAML into an enhanced JSON version
and capture all BEL ve... | [
"def",
"update_specifications",
"(",
"force",
":",
"bool",
"=",
"False",
")",
":",
"spec_dir",
"=",
"config",
"[",
"\"bel\"",
"]",
"[",
"\"lang\"",
"]",
"[",
"\"specifications\"",
"]",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"spec_dir",
")",
... | Update BEL specifications
Collect BEL specifications from Github BELBio BEL Specification folder
and store in local directory specified in belbio_conf.yaml
Process all BEL Specifications in YAML into an enhanced JSON version
and capture all BEL versions in a separate file for quick access. | [
"Update",
"BEL",
"specifications"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_specification.py#L146-L194 |
belbio/bel | bel/lang/bel_specification.py | github_belspec_files | def github_belspec_files(spec_dir, force: bool = False):
"""Get belspec files from Github repo
Args:
spec_dir: directory to store the BEL Specification and derived files
force: force update of BEL Specifications from Github - skipped if local files less than 1 day old
"""
if not force... | python | def github_belspec_files(spec_dir, force: bool = False):
"""Get belspec files from Github repo
Args:
spec_dir: directory to store the BEL Specification and derived files
force: force update of BEL Specifications from Github - skipped if local files less than 1 day old
"""
if not force... | [
"def",
"github_belspec_files",
"(",
"spec_dir",
",",
"force",
":",
"bool",
"=",
"False",
")",
":",
"if",
"not",
"force",
":",
"dtnow",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"delta",
"=",
"datetime",
".",
"timedelta",
"(",
"1",
")",... | Get belspec files from Github repo
Args:
spec_dir: directory to store the BEL Specification and derived files
force: force update of BEL Specifications from Github - skipped if local files less than 1 day old | [
"Get",
"belspec",
"files",
"from",
"Github",
"repo"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_specification.py#L197-L242 |
belbio/bel | bel/lang/bel_specification.py | belspec_yaml2json | def belspec_yaml2json(yaml_fn: str, json_fn: str) -> str:
"""Enhance BEL specification and save as JSON file
Load all BEL Specification YAML files and convert to JSON files
after enhancing them. Also create a bel_versions.json file with
all available BEL versions for fast loading.
Args:
y... | python | def belspec_yaml2json(yaml_fn: str, json_fn: str) -> str:
"""Enhance BEL specification and save as JSON file
Load all BEL Specification YAML files and convert to JSON files
after enhancing them. Also create a bel_versions.json file with
all available BEL versions for fast loading.
Args:
y... | [
"def",
"belspec_yaml2json",
"(",
"yaml_fn",
":",
"str",
",",
"json_fn",
":",
"str",
")",
"->",
"str",
":",
"try",
":",
"spec_dict",
"=",
"yaml",
".",
"load",
"(",
"open",
"(",
"yaml_fn",
",",
"\"r\"",
")",
".",
"read",
"(",
")",
",",
"Loader",
"=",... | Enhance BEL specification and save as JSON file
Load all BEL Specification YAML files and convert to JSON files
after enhancing them. Also create a bel_versions.json file with
all available BEL versions for fast loading.
Args:
yaml_fn: original YAML version of BEL Spec
json_fn: enhanc... | [
"Enhance",
"BEL",
"specification",
"and",
"save",
"as",
"JSON",
"file"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_specification.py#L245-L289 |
belbio/bel | bel/lang/bel_specification.py | add_function_signature_help | def add_function_signature_help(spec_dict: dict) -> dict:
"""Add function signature help
Simplify the function signatures for presentation to BEL Editor users
"""
for f in spec_dict["functions"]["signatures"]:
for argset_idx, argset in enumerate(spec_dict["functions"]["signatures"][f]["signatur... | python | def add_function_signature_help(spec_dict: dict) -> dict:
"""Add function signature help
Simplify the function signatures for presentation to BEL Editor users
"""
for f in spec_dict["functions"]["signatures"]:
for argset_idx, argset in enumerate(spec_dict["functions"]["signatures"][f]["signatur... | [
"def",
"add_function_signature_help",
"(",
"spec_dict",
":",
"dict",
")",
"->",
"dict",
":",
"for",
"f",
"in",
"spec_dict",
"[",
"\"functions\"",
"]",
"[",
"\"signatures\"",
"]",
":",
"for",
"argset_idx",
",",
"argset",
"in",
"enumerate",
"(",
"spec_dict",
"... | Add function signature help
Simplify the function signatures for presentation to BEL Editor users | [
"Add",
"function",
"signature",
"help"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_specification.py#L292-L364 |
belbio/bel | bel/lang/bel_specification.py | add_relations | def add_relations(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]:
"""Add relation keys to spec_dict
Args:
spec_dict (Mapping[str, Any]): bel specification dictionary
Returns:
Mapping[str, Any]: bel specification dictionary with added relation keys
"""
# Class 'Mapping' does no... | python | def add_relations(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]:
"""Add relation keys to spec_dict
Args:
spec_dict (Mapping[str, Any]): bel specification dictionary
Returns:
Mapping[str, Any]: bel specification dictionary with added relation keys
"""
# Class 'Mapping' does no... | [
"def",
"add_relations",
"(",
"spec_dict",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"# Class 'Mapping' does not define '__setitem__', so the '[]' operator cannot be used on its instances",
"spec_dict",
"[",
"\"r... | Add relation keys to spec_dict
Args:
spec_dict (Mapping[str, Any]): bel specification dictionary
Returns:
Mapping[str, Any]: bel specification dictionary with added relation keys | [
"Add",
"relation",
"keys",
"to",
"spec_dict"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_specification.py#L367-L397 |
belbio/bel | bel/lang/bel_specification.py | add_functions | def add_functions(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]:
"""Add function keys to spec_dict
Args:
spec_dict (Mapping[str, Any]): bel specification dictionary
Returns:
Mapping[str, Any]: bel specification dictionary with added function keys
"""
# Class 'Mapping' does no... | python | def add_functions(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]:
"""Add function keys to spec_dict
Args:
spec_dict (Mapping[str, Any]): bel specification dictionary
Returns:
Mapping[str, Any]: bel specification dictionary with added function keys
"""
# Class 'Mapping' does no... | [
"def",
"add_functions",
"(",
"spec_dict",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"# Class 'Mapping' does not define '__setitem__', so the '[]' operator cannot be used on its instances",
"spec_dict",
"[",
"\"f... | Add function keys to spec_dict
Args:
spec_dict (Mapping[str, Any]): bel specification dictionary
Returns:
Mapping[str, Any]: bel specification dictionary with added function keys | [
"Add",
"function",
"keys",
"to",
"spec_dict"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_specification.py#L400-L448 |
belbio/bel | bel/lang/bel_specification.py | add_namespaces | def add_namespaces(spec_dict):
"""Add namespace convenience keys, list, list_{short|long}, to_{short|long}"""
for ns in spec_dict["namespaces"]:
spec_dict["namespaces"][ns]["list"] = []
spec_dict["namespaces"][ns]["list_long"] = []
spec_dict["namespaces"][ns]["list_short"] = []
... | python | def add_namespaces(spec_dict):
"""Add namespace convenience keys, list, list_{short|long}, to_{short|long}"""
for ns in spec_dict["namespaces"]:
spec_dict["namespaces"][ns]["list"] = []
spec_dict["namespaces"][ns]["list_long"] = []
spec_dict["namespaces"][ns]["list_short"] = []
... | [
"def",
"add_namespaces",
"(",
"spec_dict",
")",
":",
"for",
"ns",
"in",
"spec_dict",
"[",
"\"namespaces\"",
"]",
":",
"spec_dict",
"[",
"\"namespaces\"",
"]",
"[",
"ns",
"]",
"[",
"\"list\"",
"]",
"=",
"[",
"]",
"spec_dict",
"[",
"\"namespaces\"",
"]",
"... | Add namespace convenience keys, list, list_{short|long}, to_{short|long} | [
"Add",
"namespace",
"convenience",
"keys",
"list",
"list_",
"{",
"short|long",
"}",
"to_",
"{",
"short|long",
"}"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_specification.py#L451-L476 |
belbio/bel | bel/lang/bel_specification.py | enhance_function_signatures | def enhance_function_signatures(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]:
"""Enhance function signatures
Add required and optional objects to signatures objects for semantic validation
support.
Args:
spec_dict (Mapping[str, Any]): bel specification dictionary
Returns:
Ma... | python | def enhance_function_signatures(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]:
"""Enhance function signatures
Add required and optional objects to signatures objects for semantic validation
support.
Args:
spec_dict (Mapping[str, Any]): bel specification dictionary
Returns:
Ma... | [
"def",
"enhance_function_signatures",
"(",
"spec_dict",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"for",
"func",
"in",
"spec_dict",
"[",
"\"functions\"",
"]",
"[",
"\"signatures\"",
"]",
":",
"fo... | Enhance function signatures
Add required and optional objects to signatures objects for semantic validation
support.
Args:
spec_dict (Mapping[str, Any]): bel specification dictionary
Returns:
Mapping[str, Any]: return enhanced bel specification dict | [
"Enhance",
"function",
"signatures"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_specification.py#L479-L542 |
belbio/bel | bel/lang/bel_specification.py | get_ebnf_template | def get_ebnf_template():
"""Get EBNF template from Github belbio/bel_specifications repo"""
spec_dir = config["bel"]["lang"]["specifications"]
local_fp = f"{spec_dir}/bel.ebnf.j2"
repo_url = (
"https://api.github.com/repos/belbio/bel_specifications/contents/resources/bel.ebnf.j2"
)
pa... | python | def get_ebnf_template():
"""Get EBNF template from Github belbio/bel_specifications repo"""
spec_dir = config["bel"]["lang"]["specifications"]
local_fp = f"{spec_dir}/bel.ebnf.j2"
repo_url = (
"https://api.github.com/repos/belbio/bel_specifications/contents/resources/bel.ebnf.j2"
)
pa... | [
"def",
"get_ebnf_template",
"(",
")",
":",
"spec_dir",
"=",
"config",
"[",
"\"bel\"",
"]",
"[",
"\"lang\"",
"]",
"[",
"\"specifications\"",
"]",
"local_fp",
"=",
"f\"{spec_dir}/bel.ebnf.j2\"",
"repo_url",
"=",
"(",
"\"https://api.github.com/repos/belbio/bel_specificatio... | Get EBNF template from Github belbio/bel_specifications repo | [
"Get",
"EBNF",
"template",
"from",
"Github",
"belbio",
"/",
"bel_specifications",
"repo"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_specification.py#L545-L589 |
belbio/bel | bel/lang/bel_specification.py | create_ebnf_parser | def create_ebnf_parser(files):
"""Create EBNF files and EBNF-based parsers"""
flag = False
for belspec_fn in files:
# Get EBNF Jinja template from Github if enabled
if config["bel"]["lang"]["specification_github_repo"]:
tmpl_fn = get_ebnf_template()
# Check if EBNF file... | python | def create_ebnf_parser(files):
"""Create EBNF files and EBNF-based parsers"""
flag = False
for belspec_fn in files:
# Get EBNF Jinja template from Github if enabled
if config["bel"]["lang"]["specification_github_repo"]:
tmpl_fn = get_ebnf_template()
# Check if EBNF file... | [
"def",
"create_ebnf_parser",
"(",
"files",
")",
":",
"flag",
"=",
"False",
"for",
"belspec_fn",
"in",
"files",
":",
"# Get EBNF Jinja template from Github if enabled",
"if",
"config",
"[",
"\"bel\"",
"]",
"[",
"\"lang\"",
"]",
"[",
"\"specification_github_repo\"",
"... | Create EBNF files and EBNF-based parsers | [
"Create",
"EBNF",
"files",
"and",
"EBNF",
"-",
"based",
"parsers"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_specification.py#L592-L661 |
belbio/bel | bel/lang/bel_specification.py | get_function_help | def get_function_help(function: str, bel_spec: BELSpec):
"""Get function_help given function name
This will get the function summary template (argument summary in signature)
and the argument help listing.
"""
function_long = bel_spec["functions"]["to_long"].get(function)
function_help = []
... | python | def get_function_help(function: str, bel_spec: BELSpec):
"""Get function_help given function name
This will get the function summary template (argument summary in signature)
and the argument help listing.
"""
function_long = bel_spec["functions"]["to_long"].get(function)
function_help = []
... | [
"def",
"get_function_help",
"(",
"function",
":",
"str",
",",
"bel_spec",
":",
"BELSpec",
")",
":",
"function_long",
"=",
"bel_spec",
"[",
"\"functions\"",
"]",
"[",
"\"to_long\"",
"]",
".",
"get",
"(",
"function",
")",
"function_help",
"=",
"[",
"]",
"if"... | Get function_help given function name
This will get the function summary template (argument summary in signature)
and the argument help listing. | [
"Get",
"function_help",
"given",
"function",
"name"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_specification.py#L664-L684 |
belbio/bel | bel/lang/completion.py | in_span | def in_span(loc: int, span: Span) -> bool:
"""Checks if loc is inside span"""
if loc >= span[0] and loc <= span[1]:
return True
else:
return False | python | def in_span(loc: int, span: Span) -> bool:
"""Checks if loc is inside span"""
if loc >= span[0] and loc <= span[1]:
return True
else:
return False | [
"def",
"in_span",
"(",
"loc",
":",
"int",
",",
"span",
":",
"Span",
")",
"->",
"bool",
":",
"if",
"loc",
">=",
"span",
"[",
"0",
"]",
"and",
"loc",
"<=",
"span",
"[",
"1",
"]",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Checks if loc is inside span | [
"Checks",
"if",
"loc",
"is",
"inside",
"span"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/completion.py#L35-L41 |
belbio/bel | bel/lang/completion.py | cursor | def cursor(
belstr: str, ast: AST, cursor_loc: int, result: Mapping[str, Any] = None
) -> Mapping[str, Any]:
"""Find BEL function or argument at cursor location
Args:
belstr: BEL String used to create the completion_text
ast (Mapping[str, Any]): AST (dict) of BEL String
cursor_loc (... | python | def cursor(
belstr: str, ast: AST, cursor_loc: int, result: Mapping[str, Any] = None
) -> Mapping[str, Any]:
"""Find BEL function or argument at cursor location
Args:
belstr: BEL String used to create the completion_text
ast (Mapping[str, Any]): AST (dict) of BEL String
cursor_loc (... | [
"def",
"cursor",
"(",
"belstr",
":",
"str",
",",
"ast",
":",
"AST",
",",
"cursor_loc",
":",
"int",
",",
"result",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"log",
".",
"deb... | Find BEL function or argument at cursor location
Args:
belstr: BEL String used to create the completion_text
ast (Mapping[str, Any]): AST (dict) of BEL String
cursor_loc (int): given cursor location from input field
cursor_loc starts at 0, think of it like a block cursor coverin... | [
"Find",
"BEL",
"function",
"or",
"argument",
"at",
"cursor",
"location"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/completion.py#L44-L175 |
belbio/bel | bel/lang/completion.py | nsarg_completions | def nsarg_completions(
completion_text: str,
entity_types: list,
bel_spec: BELSpec,
namespace: str,
species_id: str,
bel_fmt: str,
size: int,
):
"""Namespace completions
Args:
completion_text
entity_types: used to filter namespace search results
bel_spec: use... | python | def nsarg_completions(
completion_text: str,
entity_types: list,
bel_spec: BELSpec,
namespace: str,
species_id: str,
bel_fmt: str,
size: int,
):
"""Namespace completions
Args:
completion_text
entity_types: used to filter namespace search results
bel_spec: use... | [
"def",
"nsarg_completions",
"(",
"completion_text",
":",
"str",
",",
"entity_types",
":",
"list",
",",
"bel_spec",
":",
"BELSpec",
",",
"namespace",
":",
"str",
",",
"species_id",
":",
"str",
",",
"bel_fmt",
":",
"str",
",",
"size",
":",
"int",
",",
")",... | Namespace completions
Args:
completion_text
entity_types: used to filter namespace search results
bel_spec: used to search default namespaces
namespace: used to filter namespace search results
species_id: used to filter namespace search results
bel_fmt: used to selec... | [
"Namespace",
"completions"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/completion.py#L178-L266 |
belbio/bel | bel/lang/completion.py | relation_completions | def relation_completions(
completion_text: str, bel_spec: BELSpec, bel_fmt: str, size: int
) -> list:
"""Filter BEL relations by prefix
Args:
prefix: completion string
bel_fmt: short, medium, long BEL formats
spec: BEL specification
Returns:
list: list of BEL relations ... | python | def relation_completions(
completion_text: str, bel_spec: BELSpec, bel_fmt: str, size: int
) -> list:
"""Filter BEL relations by prefix
Args:
prefix: completion string
bel_fmt: short, medium, long BEL formats
spec: BEL specification
Returns:
list: list of BEL relations ... | [
"def",
"relation_completions",
"(",
"completion_text",
":",
"str",
",",
"bel_spec",
":",
"BELSpec",
",",
"bel_fmt",
":",
"str",
",",
"size",
":",
"int",
")",
"->",
"list",
":",
"if",
"bel_fmt",
"==",
"\"short\"",
":",
"relation_list",
"=",
"bel_spec",
"[",... | Filter BEL relations by prefix
Args:
prefix: completion string
bel_fmt: short, medium, long BEL formats
spec: BEL specification
Returns:
list: list of BEL relations that match prefix | [
"Filter",
"BEL",
"relations",
"by",
"prefix"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/completion.py#L269-L305 |
belbio/bel | bel/lang/completion.py | function_completions | def function_completions(
completion_text: str,
bel_spec: BELSpec,
function_list: list,
bel_fmt: str,
size: int,
) -> list:
"""Filter BEL functions by prefix
Args:
prefix: completion string
bel_fmt: short, medium, long BEL formats
spec: BEL specification
Returns... | python | def function_completions(
completion_text: str,
bel_spec: BELSpec,
function_list: list,
bel_fmt: str,
size: int,
) -> list:
"""Filter BEL functions by prefix
Args:
prefix: completion string
bel_fmt: short, medium, long BEL formats
spec: BEL specification
Returns... | [
"def",
"function_completions",
"(",
"completion_text",
":",
"str",
",",
"bel_spec",
":",
"BELSpec",
",",
"function_list",
":",
"list",
",",
"bel_fmt",
":",
"str",
",",
"size",
":",
"int",
",",
")",
"->",
"list",
":",
"# Convert provided function list to correct ... | Filter BEL functions by prefix
Args:
prefix: completion string
bel_fmt: short, medium, long BEL formats
spec: BEL specification
Returns:
list: list of BEL functions that match prefix | [
"Filter",
"BEL",
"functions",
"by",
"prefix"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/completion.py#L308-L366 |
belbio/bel | bel/lang/completion.py | arg_completions | def arg_completions(
completion_text: str,
parent_function: str,
args: list,
arg_idx: int,
bel_spec: BELSpec,
bel_fmt: str,
species_id: str,
namespace: str,
size: int,
):
"""Function argument completion
Only allow legal options for completion given function name, arguments a... | python | def arg_completions(
completion_text: str,
parent_function: str,
args: list,
arg_idx: int,
bel_spec: BELSpec,
bel_fmt: str,
species_id: str,
namespace: str,
size: int,
):
"""Function argument completion
Only allow legal options for completion given function name, arguments a... | [
"def",
"arg_completions",
"(",
"completion_text",
":",
"str",
",",
"parent_function",
":",
"str",
",",
"args",
":",
"list",
",",
"arg_idx",
":",
"int",
",",
"bel_spec",
":",
"BELSpec",
",",
"bel_fmt",
":",
"str",
",",
"species_id",
":",
"str",
",",
"name... | Function argument completion
Only allow legal options for completion given function name, arguments and index of argument
to replace.
Args:
completion_text: text to use for completion - used for creating highlight
parent_function: BEL function containing these args
args: arguments ... | [
"Function",
"argument",
"completion"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/completion.py#L369-L491 |
belbio/bel | bel/lang/completion.py | add_completions | def add_completions(
replace_list: list, belstr: str, replace_span: Span, completion_text: str
) -> List[Mapping[str, Any]]:
"""Create completions to return given replacement list
Args:
replace_list: list of completion replacement values
belstr: BEL String
replace_span: start, stop ... | python | def add_completions(
replace_list: list, belstr: str, replace_span: Span, completion_text: str
) -> List[Mapping[str, Any]]:
"""Create completions to return given replacement list
Args:
replace_list: list of completion replacement values
belstr: BEL String
replace_span: start, stop ... | [
"def",
"add_completions",
"(",
"replace_list",
":",
"list",
",",
"belstr",
":",
"str",
",",
"replace_span",
":",
"Span",
",",
"completion_text",
":",
"str",
")",
"->",
"List",
"[",
"Mapping",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"completions",
"=",
"... | Create completions to return given replacement list
Args:
replace_list: list of completion replacement values
belstr: BEL String
replace_span: start, stop of belstr to replace
completion_text: text to use for completion - used for creating highlight
Returns:
[{
... | [
"Create",
"completions",
"to",
"return",
"given",
"replacement",
"list"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/completion.py#L494-L582 |
belbio/bel | bel/lang/completion.py | get_completions | def get_completions(
belstr: str,
cursor_loc: int,
bel_spec: BELSpec,
bel_comp: str,
bel_fmt: str,
species_id: str,
size: int,
):
"""Get BEL Assertion completions
Args:
Results:
"""
ast, errors = pparse.get_ast_dict(belstr)
spans = pparse.collect_spans(ast)
... | python | def get_completions(
belstr: str,
cursor_loc: int,
bel_spec: BELSpec,
bel_comp: str,
bel_fmt: str,
species_id: str,
size: int,
):
"""Get BEL Assertion completions
Args:
Results:
"""
ast, errors = pparse.get_ast_dict(belstr)
spans = pparse.collect_spans(ast)
... | [
"def",
"get_completions",
"(",
"belstr",
":",
"str",
",",
"cursor_loc",
":",
"int",
",",
"bel_spec",
":",
"BELSpec",
",",
"bel_comp",
":",
"str",
",",
"bel_fmt",
":",
"str",
",",
"species_id",
":",
"str",
",",
"size",
":",
"int",
",",
")",
":",
"ast"... | Get BEL Assertion completions
Args:
Results: | [
"Get",
"BEL",
"Assertion",
"completions"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/completion.py#L585-L655 |
belbio/bel | bel/lang/completion.py | bel_completion | def bel_completion(
belstr: str,
cursor_loc: int = -1,
bel_version: str = default_bel_version,
bel_comp: str = None,
bel_fmt: str = "medium",
species_id: str = None,
size: int = 20,
) -> Mapping[str, Any]:
"""BEL Completion
Args:
belstr (str): BEL String to provide completio... | python | def bel_completion(
belstr: str,
cursor_loc: int = -1,
bel_version: str = default_bel_version,
bel_comp: str = None,
bel_fmt: str = "medium",
species_id: str = None,
size: int = 20,
) -> Mapping[str, Any]:
"""BEL Completion
Args:
belstr (str): BEL String to provide completio... | [
"def",
"bel_completion",
"(",
"belstr",
":",
"str",
",",
"cursor_loc",
":",
"int",
"=",
"-",
"1",
",",
"bel_version",
":",
"str",
"=",
"default_bel_version",
",",
"bel_comp",
":",
"str",
"=",
"None",
",",
"bel_fmt",
":",
"str",
"=",
"\"medium\"",
",",
... | BEL Completion
Args:
belstr (str): BEL String to provide completion for
cursor_loc (int): cursor location - default of -1 means end of string
bel_version (str): BEL Language version to use for completion
bel_comp (str): ['subject', 'object', 'full', None] - a nested statement has to... | [
"BEL",
"Completion"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/completion.py#L658-L726 |
belbio/bel | bel/lang/partialparse.py | parse_chars | def parse_chars(bels: list, errors: Errors) -> Tuple[CharLocs, Errors]:
"""Scan BEL string to map parens, quotes, commas
Args:
bels: bel string as an array of characters
errors: list of error tuples ('<type>', '<msg>')
Returns:
(char_locs, errors): character locations and errors
... | python | def parse_chars(bels: list, errors: Errors) -> Tuple[CharLocs, Errors]:
"""Scan BEL string to map parens, quotes, commas
Args:
bels: bel string as an array of characters
errors: list of error tuples ('<type>', '<msg>')
Returns:
(char_locs, errors): character locations and errors
... | [
"def",
"parse_chars",
"(",
"bels",
":",
"list",
",",
"errors",
":",
"Errors",
")",
"->",
"Tuple",
"[",
"CharLocs",
",",
"Errors",
"]",
":",
"pstack",
",",
"qstack",
",",
"nested_pstack",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"parens",
",",
... | Scan BEL string to map parens, quotes, commas
Args:
bels: bel string as an array of characters
errors: list of error tuples ('<type>', '<msg>')
Returns:
(char_locs, errors): character locations and errors | [
"Scan",
"BEL",
"string",
"to",
"map",
"parens",
"quotes",
"commas"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L110-L232 |
belbio/bel | bel/lang/partialparse.py | parse_functions | def parse_functions(
bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:
"""Parse functions from BEL using paren, comma, quote character locations
Args:
bels: BEL string as list of chars
char_locs: paren, comma, quote character locations
error... | python | def parse_functions(
bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:
"""Parse functions from BEL using paren, comma, quote character locations
Args:
bels: BEL string as list of chars
char_locs: paren, comma, quote character locations
error... | [
"def",
"parse_functions",
"(",
"bels",
":",
"list",
",",
"char_locs",
":",
"CharLocs",
",",
"parsed",
":",
"Parsed",
",",
"errors",
":",
"Errors",
")",
"->",
"Tuple",
"[",
"Parsed",
",",
"Errors",
"]",
":",
"parens",
"=",
"char_locs",
"[",
"\"parens\"",
... | Parse functions from BEL using paren, comma, quote character locations
Args:
bels: BEL string as list of chars
char_locs: paren, comma, quote character locations
errors: Any error messages generated during the parse
Returns:
(functions, errors): function names and locations and... | [
"Parse",
"functions",
"from",
"BEL",
"using",
"paren",
"comma",
"quote",
"character",
"locations"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L235-L303 |
belbio/bel | bel/lang/partialparse.py | parse_args | def parse_args(
bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:
"""Parse arguments from functions
Args:
bels: BEL string as list of chars
char_locs: char locations for parens, commas and quotes
parsed: function locations
errors: er... | python | def parse_args(
bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:
"""Parse arguments from functions
Args:
bels: BEL string as list of chars
char_locs: char locations for parens, commas and quotes
parsed: function locations
errors: er... | [
"def",
"parse_args",
"(",
"bels",
":",
"list",
",",
"char_locs",
":",
"CharLocs",
",",
"parsed",
":",
"Parsed",
",",
"errors",
":",
"Errors",
")",
"->",
"Tuple",
"[",
"Parsed",
",",
"Errors",
"]",
":",
"commas",
"=",
"char_locs",
"[",
"\"commas\"",
"]"... | Parse arguments from functions
Args:
bels: BEL string as list of chars
char_locs: char locations for parens, commas and quotes
parsed: function locations
errors: error messages
Returns:
(functions, errors): function and arg locations plus error messages | [
"Parse",
"arguments",
"from",
"functions"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L306-L362 |
belbio/bel | bel/lang/partialparse.py | arg_types | def arg_types(parsed: Parsed, errors: Errors) -> Tuple[Parsed, Errors]:
"""Add argument types to parsed function data structure
Args:
parsed: function and arg locations in BEL string
errors: error messages
Returns:
(parsed, errors): parsed, arguments with arg types plus error messa... | python | def arg_types(parsed: Parsed, errors: Errors) -> Tuple[Parsed, Errors]:
"""Add argument types to parsed function data structure
Args:
parsed: function and arg locations in BEL string
errors: error messages
Returns:
(parsed, errors): parsed, arguments with arg types plus error messa... | [
"def",
"arg_types",
"(",
"parsed",
":",
"Parsed",
",",
"errors",
":",
"Errors",
")",
"->",
"Tuple",
"[",
"Parsed",
",",
"Errors",
"]",
":",
"func_pattern",
"=",
"re",
".",
"compile",
"(",
"r\"\\s*[a-zA-Z]+\\(\"",
")",
"nsarg_pattern",
"=",
"re",
".",
"co... | Add argument types to parsed function data structure
Args:
parsed: function and arg locations in BEL string
errors: error messages
Returns:
(parsed, errors): parsed, arguments with arg types plus error messages | [
"Add",
"argument",
"types",
"to",
"parsed",
"function",
"data",
"structure"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L365-L408 |
belbio/bel | bel/lang/partialparse.py | parse_relations | def parse_relations(
belstr: str, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:
"""Parse relations from BEL string
Args:
belstr: BEL string as one single string (not list of chars)
char_locs: paren, comma and quote char locations
parsed: data struct... | python | def parse_relations(
belstr: str, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:
"""Parse relations from BEL string
Args:
belstr: BEL string as one single string (not list of chars)
char_locs: paren, comma and quote char locations
parsed: data struct... | [
"def",
"parse_relations",
"(",
"belstr",
":",
"str",
",",
"char_locs",
":",
"CharLocs",
",",
"parsed",
":",
"Parsed",
",",
"errors",
":",
"Errors",
")",
"->",
"Tuple",
"[",
"Parsed",
",",
"Errors",
"]",
":",
"quotes",
"=",
"char_locs",
"[",
"\"quotes\"",... | Parse relations from BEL string
Args:
belstr: BEL string as one single string (not list of chars)
char_locs: paren, comma and quote char locations
parsed: data structure for parsed functions, relations, nested
errors: error messages
Returns:
(parsed, errors): | [
"Parse",
"relations",
"from",
"BEL",
"string"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L411-L468 |
belbio/bel | bel/lang/partialparse.py | parse_nested | def parse_nested(
bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:
""" Parse nested BEL object """
for sp in char_locs[
"nested_parens"
]: # sp = start parenthesis, ep = end parenthesis
ep, level = char_locs["nested_parens"][sp]
if ep ... | python | def parse_nested(
bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:
""" Parse nested BEL object """
for sp in char_locs[
"nested_parens"
]: # sp = start parenthesis, ep = end parenthesis
ep, level = char_locs["nested_parens"][sp]
if ep ... | [
"def",
"parse_nested",
"(",
"bels",
":",
"list",
",",
"char_locs",
":",
"CharLocs",
",",
"parsed",
":",
"Parsed",
",",
"errors",
":",
"Errors",
")",
"->",
"Tuple",
"[",
"Parsed",
",",
"Errors",
"]",
":",
"for",
"sp",
"in",
"char_locs",
"[",
"\"nested_p... | Parse nested BEL object | [
"Parse",
"nested",
"BEL",
"object"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L471-L484 |
belbio/bel | bel/lang/partialparse.py | dump_json | def dump_json(d: dict) -> None:
"""Dump json when using tuples for dictionary keys
Have to convert tuples to strings to dump out as json
"""
import json
k = d.keys()
v = d.values()
k1 = [str(i) for i in k]
return json.dumps(dict(zip(*[k1, v])), indent=4) | python | def dump_json(d: dict) -> None:
"""Dump json when using tuples for dictionary keys
Have to convert tuples to strings to dump out as json
"""
import json
k = d.keys()
v = d.values()
k1 = [str(i) for i in k]
return json.dumps(dict(zip(*[k1, v])), indent=4) | [
"def",
"dump_json",
"(",
"d",
":",
"dict",
")",
"->",
"None",
":",
"import",
"json",
"k",
"=",
"d",
".",
"keys",
"(",
")",
"v",
"=",
"d",
".",
"values",
"(",
")",
"k1",
"=",
"[",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"k",
"]",
"return",
... | Dump json when using tuples for dictionary keys
Have to convert tuples to strings to dump out as json | [
"Dump",
"json",
"when",
"using",
"tuples",
"for",
"dictionary",
"keys"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L487-L499 |
belbio/bel | bel/lang/partialparse.py | collect_spans | def collect_spans(ast: AST) -> List[Tuple[str, Tuple[int, int]]]:
"""Collect flattened list of spans of BEL syntax types
Provide simple list of BEL syntax type spans for highlighting.
Function names, NSargs, NS prefix, NS value and StrArgs will be
tagged.
Args:
ast: AST of BEL assertion
... | python | def collect_spans(ast: AST) -> List[Tuple[str, Tuple[int, int]]]:
"""Collect flattened list of spans of BEL syntax types
Provide simple list of BEL syntax type spans for highlighting.
Function names, NSargs, NS prefix, NS value and StrArgs will be
tagged.
Args:
ast: AST of BEL assertion
... | [
"def",
"collect_spans",
"(",
"ast",
":",
"AST",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"]",
":",
"spans",
"=",
"[",
"]",
"if",
"ast",
".",
"get",
"(",
"\"subject\"",
",",
"False",
")",
":",
... | Collect flattened list of spans of BEL syntax types
Provide simple list of BEL syntax type spans for highlighting.
Function names, NSargs, NS prefix, NS value and StrArgs will be
tagged.
Args:
ast: AST of BEL assertion
Returns:
List[Tuple[str, Tuple[int, int]]]: list of span objec... | [
"Collect",
"flattened",
"list",
"of",
"spans",
"of",
"BEL",
"syntax",
"types"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L502-L550 |
belbio/bel | bel/lang/partialparse.py | print_spans | def print_spans(spans, max_idx: int) -> None:
"""Quick test to show how character spans match original BEL String
Mostly for debugging purposes
"""
bel_spans = [" "] * (max_idx + 3)
for val, span in spans:
if val in ["Nested", "NSArg"]:
continue
for i in range(span[0], ... | python | def print_spans(spans, max_idx: int) -> None:
"""Quick test to show how character spans match original BEL String
Mostly for debugging purposes
"""
bel_spans = [" "] * (max_idx + 3)
for val, span in spans:
if val in ["Nested", "NSArg"]:
continue
for i in range(span[0], ... | [
"def",
"print_spans",
"(",
"spans",
",",
"max_idx",
":",
"int",
")",
"->",
"None",
":",
"bel_spans",
"=",
"[",
"\" \"",
"]",
"*",
"(",
"max_idx",
"+",
"3",
")",
"for",
"val",
",",
"span",
"in",
"spans",
":",
"if",
"val",
"in",
"[",
"\"Nested\"",
... | Quick test to show how character spans match original BEL String
Mostly for debugging purposes | [
"Quick",
"test",
"to",
"show",
"how",
"character",
"spans",
"match",
"original",
"BEL",
"String"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L577-L598 |
belbio/bel | bel/lang/partialparse.py | parsed_function_to_ast | def parsed_function_to_ast(parsed: Parsed, parsed_key):
"""Create AST for top-level functions"""
sub = parsed[parsed_key]
subtree = {
"type": "Function",
"span": sub["span"],
"function": {
"name": sub["name"],
"name_span": sub["name_span"],
"pare... | python | def parsed_function_to_ast(parsed: Parsed, parsed_key):
"""Create AST for top-level functions"""
sub = parsed[parsed_key]
subtree = {
"type": "Function",
"span": sub["span"],
"function": {
"name": sub["name"],
"name_span": sub["name_span"],
"pare... | [
"def",
"parsed_function_to_ast",
"(",
"parsed",
":",
"Parsed",
",",
"parsed_key",
")",
":",
"sub",
"=",
"parsed",
"[",
"parsed_key",
"]",
"subtree",
"=",
"{",
"\"type\"",
":",
"\"Function\"",
",",
"\"span\"",
":",
"sub",
"[",
"\"span\"",
"]",
",",
"\"funct... | Create AST for top-level functions | [
"Create",
"AST",
"for",
"top",
"-",
"level",
"functions"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L603-L644 |
belbio/bel | bel/lang/partialparse.py | parsed_top_level_errors | def parsed_top_level_errors(parsed, errors, component_type: str = "") -> Errors:
"""Check full parse for errors
Args:
parsed:
errors:
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input
"""
# Error ... | python | def parsed_top_level_errors(parsed, errors, component_type: str = "") -> Errors:
"""Check full parse for errors
Args:
parsed:
errors:
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input
"""
# Error ... | [
"def",
"parsed_top_level_errors",
"(",
"parsed",
",",
"errors",
",",
"component_type",
":",
"str",
"=",
"\"\"",
")",
"->",
"Errors",
":",
"# Error check",
"fn_cnt",
"=",
"0",
"rel_cnt",
"=",
"0",
"nested_cnt",
"=",
"0",
"for",
"key",
"in",
"parsed",
":",
... | Check full parse for errors
Args:
parsed:
errors:
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input | [
"Check",
"full",
"parse",
"for",
"errors"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L647-L736 |
belbio/bel | bel/lang/partialparse.py | parsed_to_ast | def parsed_to_ast(parsed: Parsed, errors: Errors, component_type: str = ""):
"""Convert parsed data struct to AST dictionary
Args:
parsed:
errors:
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input
"""
... | python | def parsed_to_ast(parsed: Parsed, errors: Errors, component_type: str = ""):
"""Convert parsed data struct to AST dictionary
Args:
parsed:
errors:
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input
"""
... | [
"def",
"parsed_to_ast",
"(",
"parsed",
":",
"Parsed",
",",
"errors",
":",
"Errors",
",",
"component_type",
":",
"str",
"=",
"\"\"",
")",
":",
"ast",
"=",
"{",
"}",
"sorted_keys",
"=",
"sorted",
"(",
"parsed",
".",
"keys",
"(",
")",
")",
"# Setup top-le... | Convert parsed data struct to AST dictionary
Args:
parsed:
errors:
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input | [
"Convert",
"parsed",
"data",
"struct",
"to",
"AST",
"dictionary"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L739-L796 |
belbio/bel | bel/lang/partialparse.py | get_ast_dict | def get_ast_dict(belstr, component_type: str = ""):
"""Convert BEL string to AST dictionary
Args:
belstr: BEL string
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input
"""
errors = []
parsed = {}
b... | python | def get_ast_dict(belstr, component_type: str = ""):
"""Convert BEL string to AST dictionary
Args:
belstr: BEL string
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input
"""
errors = []
parsed = {}
b... | [
"def",
"get_ast_dict",
"(",
"belstr",
",",
"component_type",
":",
"str",
"=",
"\"\"",
")",
":",
"errors",
"=",
"[",
"]",
"parsed",
"=",
"{",
"}",
"bels",
"=",
"list",
"(",
"belstr",
")",
"char_locs",
",",
"errors",
"=",
"parse_chars",
"(",
"bels",
",... | Convert BEL string to AST dictionary
Args:
belstr: BEL string
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input | [
"Convert",
"BEL",
"string",
"to",
"AST",
"dictionary"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L799-L821 |
belbio/bel | bel/lang/partialparse.py | get_ast_obj | def get_ast_obj(belstr, bel_version, component_type: str = ""):
"""Convert AST partialparse dict to BELAst"""
ast_dict, errors = get_ast_dict(belstr, component_type)
spec = bel_specification.get_specification(bel_version)
subj = ast_dict["subject"]
subj_ast = add_ast_fn(subj, spec)
relation ... | python | def get_ast_obj(belstr, bel_version, component_type: str = ""):
"""Convert AST partialparse dict to BELAst"""
ast_dict, errors = get_ast_dict(belstr, component_type)
spec = bel_specification.get_specification(bel_version)
subj = ast_dict["subject"]
subj_ast = add_ast_fn(subj, spec)
relation ... | [
"def",
"get_ast_obj",
"(",
"belstr",
",",
"bel_version",
",",
"component_type",
":",
"str",
"=",
"\"\"",
")",
":",
"ast_dict",
",",
"errors",
"=",
"get_ast_dict",
"(",
"belstr",
",",
"component_type",
")",
"spec",
"=",
"bel_specification",
".",
"get_specificat... | Convert AST partialparse dict to BELAst | [
"Convert",
"AST",
"partialparse",
"dict",
"to",
"BELAst"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L824-L859 |
belbio/bel | bel/lang/partialparse.py | add_ast_fn | def add_ast_fn(d, spec, parent_function=None):
"""Convert dict AST to object AST Function
Args:
ast_fn: AST object Function
d: AST as dictionary
spec: BEL Specification
Return:
ast_fn
"""
if d["type"] == "Function":
ast_fn = Function(d["function"]["name"], ... | python | def add_ast_fn(d, spec, parent_function=None):
"""Convert dict AST to object AST Function
Args:
ast_fn: AST object Function
d: AST as dictionary
spec: BEL Specification
Return:
ast_fn
"""
if d["type"] == "Function":
ast_fn = Function(d["function"]["name"], ... | [
"def",
"add_ast_fn",
"(",
"d",
",",
"spec",
",",
"parent_function",
"=",
"None",
")",
":",
"if",
"d",
"[",
"\"type\"",
"]",
"==",
"\"Function\"",
":",
"ast_fn",
"=",
"Function",
"(",
"d",
"[",
"\"function\"",
"]",
"[",
"\"name\"",
"]",
",",
"spec",
"... | Convert dict AST to object AST Function
Args:
ast_fn: AST object Function
d: AST as dictionary
spec: BEL Specification
Return:
ast_fn | [
"Convert",
"dict",
"AST",
"to",
"object",
"AST",
"Function"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L862-L885 |
belbio/bel | bel/lang/bel_utils.py | convert_nsarg | def convert_nsarg(
nsarg: str,
api_url: str = None,
namespace_targets: Mapping[str, List[str]] = None,
canonicalize: bool = False,
decanonicalize: bool = False,
) -> str:
"""[De]Canonicalize NSArg
Args:
nsarg (str): bel statement string or partial string (e.g. subject or object)
... | python | def convert_nsarg(
nsarg: str,
api_url: str = None,
namespace_targets: Mapping[str, List[str]] = None,
canonicalize: bool = False,
decanonicalize: bool = False,
) -> str:
"""[De]Canonicalize NSArg
Args:
nsarg (str): bel statement string or partial string (e.g. subject or object)
... | [
"def",
"convert_nsarg",
"(",
"nsarg",
":",
"str",
",",
"api_url",
":",
"str",
"=",
"None",
",",
"namespace_targets",
":",
"Mapping",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"canonicalize",
":",
"bool",
"=",
"False",
",",
"dec... | [De]Canonicalize NSArg
Args:
nsarg (str): bel statement string or partial string (e.g. subject or object)
api_url (str): BEL.bio api url to use, e.g. https://api.bel.bio/v1
namespace_targets (Mapping[str, List[str]]): formatted as in configuration file example
canonicalize (bool): u... | [
"[",
"De",
"]",
"Canonicalize",
"NSArg"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_utils.py#L28-L82 |
belbio/bel | bel/lang/bel_utils.py | convert_namespaces_str | def convert_namespaces_str(
bel_str: str,
api_url: str = None,
namespace_targets: Mapping[str, List[str]] = None,
canonicalize: bool = False,
decanonicalize: bool = False,
) -> str:
"""Convert namespace in string
Uses a regex expression to extract all NSArgs and replace them with the
up... | python | def convert_namespaces_str(
bel_str: str,
api_url: str = None,
namespace_targets: Mapping[str, List[str]] = None,
canonicalize: bool = False,
decanonicalize: bool = False,
) -> str:
"""Convert namespace in string
Uses a regex expression to extract all NSArgs and replace them with the
up... | [
"def",
"convert_namespaces_str",
"(",
"bel_str",
":",
"str",
",",
"api_url",
":",
"str",
"=",
"None",
",",
"namespace_targets",
":",
"Mapping",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"canonicalize",
":",
"bool",
"=",
"False",
... | Convert namespace in string
Uses a regex expression to extract all NSArgs and replace them with the
updated NSArg from the BEL.bio API terms endpoint.
Args:
bel_str (str): bel statement string or partial string (e.g. subject or object)
api_url (str): BEL.bio api url to use, e.g. https://ap... | [
"Convert",
"namespace",
"in",
"string"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_utils.py#L85-L126 |
belbio/bel | bel/lang/bel_utils.py | convert_namespaces_ast | def convert_namespaces_ast(
ast,
api_url: str = None,
namespace_targets: Mapping[str, List[str]] = None,
canonicalize: bool = False,
decanonicalize: bool = False,
):
"""Recursively convert namespaces of BEL Entities in BEL AST using API endpoint
Canonicalization and decanonicalization is de... | python | def convert_namespaces_ast(
ast,
api_url: str = None,
namespace_targets: Mapping[str, List[str]] = None,
canonicalize: bool = False,
decanonicalize: bool = False,
):
"""Recursively convert namespaces of BEL Entities in BEL AST using API endpoint
Canonicalization and decanonicalization is de... | [
"def",
"convert_namespaces_ast",
"(",
"ast",
",",
"api_url",
":",
"str",
"=",
"None",
",",
"namespace_targets",
":",
"Mapping",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"canonicalize",
":",
"bool",
"=",
"False",
",",
"decanonicali... | Recursively convert namespaces of BEL Entities in BEL AST using API endpoint
Canonicalization and decanonicalization is determined by endpoint used and namespace_targets.
Args:
ast (BEL): BEL AST
api_url (str): endpoint url with a placeholder for the term_id (either /terms/<term_id>/canonicali... | [
"Recursively",
"convert",
"namespaces",
"of",
"BEL",
"Entities",
"in",
"BEL",
"AST",
"using",
"API",
"endpoint"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_utils.py#L129-L187 |
belbio/bel | bel/lang/bel_utils.py | populate_ast_nsarg_defaults | def populate_ast_nsarg_defaults(ast, belast, species_id=None):
"""Recursively populate NSArg AST entries for default (de)canonical values
This was added specifically for the BEL Pipeline. It is designed to
run directly against ArangoDB and not through the BELAPI.
Args:
ast (BEL): BEL AST
... | python | def populate_ast_nsarg_defaults(ast, belast, species_id=None):
"""Recursively populate NSArg AST entries for default (de)canonical values
This was added specifically for the BEL Pipeline. It is designed to
run directly against ArangoDB and not through the BELAPI.
Args:
ast (BEL): BEL AST
... | [
"def",
"populate_ast_nsarg_defaults",
"(",
"ast",
",",
"belast",
",",
"species_id",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"ast",
",",
"NSArg",
")",
":",
"given_term_id",
"=",
"\"{}:{}\"",
".",
"format",
"(",
"ast",
".",
"namespace",
",",
"ast",
... | Recursively populate NSArg AST entries for default (de)canonical values
This was added specifically for the BEL Pipeline. It is designed to
run directly against ArangoDB and not through the BELAPI.
Args:
ast (BEL): BEL AST
Returns:
BEL: BEL AST | [
"Recursively",
"populate",
"NSArg",
"AST",
"entries",
"for",
"default",
"(",
"de",
")",
"canonical",
"values"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_utils.py#L190-L232 |
belbio/bel | bel/lang/bel_utils.py | orthologize | def orthologize(ast, bo, species_id: str):
"""Recursively orthologize BEL Entities in BEL AST using API endpoint
NOTE: - will take first ortholog returned in BEL.bio API result (which may return more than one ortholog)
Args:
ast (BEL): BEL AST
endpoint (str): endpoint url with a placeholde... | python | def orthologize(ast, bo, species_id: str):
"""Recursively orthologize BEL Entities in BEL AST using API endpoint
NOTE: - will take first ortholog returned in BEL.bio API result (which may return more than one ortholog)
Args:
ast (BEL): BEL AST
endpoint (str): endpoint url with a placeholde... | [
"def",
"orthologize",
"(",
"ast",
",",
"bo",
",",
"species_id",
":",
"str",
")",
":",
"# if species_id == 'TAX:9606' and str(ast) == 'MGI:Sult2a1':",
"# import pdb; pdb.set_trace()",
"if",
"not",
"species_id",
":",
"bo",
".",
"validation_messages",
".",
"append",
"(... | Recursively orthologize BEL Entities in BEL AST using API endpoint
NOTE: - will take first ortholog returned in BEL.bio API result (which may return more than one ortholog)
Args:
ast (BEL): BEL AST
endpoint (str): endpoint url with a placeholder for the term_id
Returns:
BEL: BEL A... | [
"Recursively",
"orthologize",
"BEL",
"Entities",
"in",
"BEL",
"AST",
"using",
"API",
"endpoint"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_utils.py#L235-L283 |
belbio/bel | bel/lang/bel_utils.py | populate_ast_nsarg_orthologs | def populate_ast_nsarg_orthologs(ast, species):
"""Recursively collect NSArg orthologs for BEL AST
This requires bo.collect_nsarg_norms() to be run first so NSArg.canonical is available
Args:
ast: AST at recursive point in belobj
species: dictionary of species ids vs labels for or
"""
... | python | def populate_ast_nsarg_orthologs(ast, species):
"""Recursively collect NSArg orthologs for BEL AST
This requires bo.collect_nsarg_norms() to be run first so NSArg.canonical is available
Args:
ast: AST at recursive point in belobj
species: dictionary of species ids vs labels for or
"""
... | [
"def",
"populate_ast_nsarg_orthologs",
"(",
"ast",
",",
"species",
")",
":",
"ortholog_namespace",
"=",
"\"EG\"",
"if",
"isinstance",
"(",
"ast",
",",
"NSArg",
")",
":",
"if",
"re",
".",
"match",
"(",
"ortholog_namespace",
",",
"ast",
".",
"canonical",
")",
... | Recursively collect NSArg orthologs for BEL AST
This requires bo.collect_nsarg_norms() to be run first so NSArg.canonical is available
Args:
ast: AST at recursive point in belobj
species: dictionary of species ids vs labels for or | [
"Recursively",
"collect",
"NSArg",
"orthologs",
"for",
"BEL",
"AST"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_utils.py#L286-L314 |
belbio/bel | bel/lang/bel_utils.py | preprocess_bel_stmt | def preprocess_bel_stmt(stmt: str) -> str:
"""Clean up basic formatting of BEL statement
Args:
stmt: BEL statement as single string
Returns:
cleaned BEL statement
"""
stmt = stmt.strip() # remove newline at end of stmt
stmt = re.sub(r",+", ",", stmt) # remove multiple commas... | python | def preprocess_bel_stmt(stmt: str) -> str:
"""Clean up basic formatting of BEL statement
Args:
stmt: BEL statement as single string
Returns:
cleaned BEL statement
"""
stmt = stmt.strip() # remove newline at end of stmt
stmt = re.sub(r",+", ",", stmt) # remove multiple commas... | [
"def",
"preprocess_bel_stmt",
"(",
"stmt",
":",
"str",
")",
"->",
"str",
":",
"stmt",
"=",
"stmt",
".",
"strip",
"(",
")",
"# remove newline at end of stmt",
"stmt",
"=",
"re",
".",
"sub",
"(",
"r\",+\"",
",",
"\",\"",
",",
"stmt",
")",
"# remove multiple ... | Clean up basic formatting of BEL statement
Args:
stmt: BEL statement as single string
Returns:
cleaned BEL statement | [
"Clean",
"up",
"basic",
"formatting",
"of",
"BEL",
"statement"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_utils.py#L317-L332 |
belbio/bel | bel/lang/bel_utils.py | quoting_nsarg | def quoting_nsarg(nsarg_value):
"""Quoting nsargs
If needs quotes (only if it contains whitespace, comma or ')' ), make sure
it is quoted, else don't add them.
"""
quoted = re.findall(r'^"(.*)"$', nsarg_value)
if re.search(
r"[),\s]", nsarg_value
): # quote only if it contai... | python | def quoting_nsarg(nsarg_value):
"""Quoting nsargs
If needs quotes (only if it contains whitespace, comma or ')' ), make sure
it is quoted, else don't add them.
"""
quoted = re.findall(r'^"(.*)"$', nsarg_value)
if re.search(
r"[),\s]", nsarg_value
): # quote only if it contai... | [
"def",
"quoting_nsarg",
"(",
"nsarg_value",
")",
":",
"quoted",
"=",
"re",
".",
"findall",
"(",
"r'^\"(.*)\"$'",
",",
"nsarg_value",
")",
"if",
"re",
".",
"search",
"(",
"r\"[),\\s]\"",
",",
"nsarg_value",
")",
":",
"# quote only if it contains whitespace, comma o... | Quoting nsargs
If needs quotes (only if it contains whitespace, comma or ')' ), make sure
it is quoted, else don't add them. | [
"Quoting",
"nsargs"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_utils.py#L336-L357 |
belbio/bel | bel/lang/bel_utils.py | _dump_spec | def _dump_spec(spec):
"""Dump bel specification dictionary using YAML
Formats this with an extra indentation for lists to make it easier to
use cold folding on the YAML version of the spec dictionary.
"""
with open("spec.yaml", "w") as f:
yaml.dump(spec, f, Dumper=MyDumper, default_flow_sty... | python | def _dump_spec(spec):
"""Dump bel specification dictionary using YAML
Formats this with an extra indentation for lists to make it easier to
use cold folding on the YAML version of the spec dictionary.
"""
with open("spec.yaml", "w") as f:
yaml.dump(spec, f, Dumper=MyDumper, default_flow_sty... | [
"def",
"_dump_spec",
"(",
"spec",
")",
":",
"with",
"open",
"(",
"\"spec.yaml\"",
",",
"\"w\"",
")",
"as",
"f",
":",
"yaml",
".",
"dump",
"(",
"spec",
",",
"f",
",",
"Dumper",
"=",
"MyDumper",
",",
"default_flow_style",
"=",
"False",
")"
] | Dump bel specification dictionary using YAML
Formats this with an extra indentation for lists to make it easier to
use cold folding on the YAML version of the spec dictionary. | [
"Dump",
"bel",
"specification",
"dictionary",
"using",
"YAML"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_utils.py#L450-L457 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.