repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
jfear/sramongo | sramongo/sra2mongo.py | arguments | def arguments():
"""Pulls in command line arguments."""
DESCRIPTION = """\
"""
parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=Raw)
parser.add_argument("--email", dest="email", action='store', required=False, default=False,
help="An email address is required for querying Entrez databases.")
parser.add_argument("--api", dest="api_key", action='store', required=False, default=False,
help="A users ENTREZ API Key. Will speed up download.")
parser.add_argument("--query", dest="query", action='store', required=True,
help="Query to submit to Entrez.")
parser.add_argument("--host", dest="host", action='store', required=False, default='localhost',
help="Location of an already running database.")
parser.add_argument("--port", dest="port", action='store', type=int, required=False, default=27017,
help="Mongo database port.")
parser.add_argument("--db", dest="db", action='store', required=False, default='sramongo',
help="Name of the database.")
parser.add_argument("--debug", dest="debug", action='store_true', required=False,
help="Turn on debug output.")
parser.add_argument("--force", dest="force", action='store_true', required=False,
help="Forces clearing the cache.")
args = parser.parse_args()
if not (args.email or args.api_key):
logger.error('You must provide either an `--email` or `--api`.')
sys.exit()
return args | python | def arguments():
"""Pulls in command line arguments."""
DESCRIPTION = """\
"""
parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=Raw)
parser.add_argument("--email", dest="email", action='store', required=False, default=False,
help="An email address is required for querying Entrez databases.")
parser.add_argument("--api", dest="api_key", action='store', required=False, default=False,
help="A users ENTREZ API Key. Will speed up download.")
parser.add_argument("--query", dest="query", action='store', required=True,
help="Query to submit to Entrez.")
parser.add_argument("--host", dest="host", action='store', required=False, default='localhost',
help="Location of an already running database.")
parser.add_argument("--port", dest="port", action='store', type=int, required=False, default=27017,
help="Mongo database port.")
parser.add_argument("--db", dest="db", action='store', required=False, default='sramongo',
help="Name of the database.")
parser.add_argument("--debug", dest="debug", action='store_true', required=False,
help="Turn on debug output.")
parser.add_argument("--force", dest="force", action='store_true', required=False,
help="Forces clearing the cache.")
args = parser.parse_args()
if not (args.email or args.api_key):
logger.error('You must provide either an `--email` or `--api`.')
sys.exit()
return args | [
"def",
"arguments",
"(",
")",
":",
"DESCRIPTION",
"=",
"\"\"\"\\\n \"\"\"",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"DESCRIPTION",
",",
"formatter_class",
"=",
"Raw",
")",
"parser",
".",
"add_argument",
"(",
"\"--email\"",
"... | Pulls in command line arguments. | [
"Pulls",
"in",
"command",
"line",
"arguments",
"."
] | 82a9a157e44bda4100be385c644b3ac21be66038 | https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/sra2mongo.py#L24-L62 | train | 53,400 |
BlueBrain/hpcbench | hpcbench/net/__init__.py | BeNet.run | def run(self, *nodes):
"""Execute benchmarks on every node specified in arguments.
If none are given, then execute benchmarks on every nodes
specified in the ``network.nodes`` campaign configuration.
"""
nodes = nodes or self.nodes
self._prelude(*nodes)
@write_yaml_report
def _run():
self._build_installer()
runner = functools.partial(run_on_host, self.campaign)
if self.campaign.network.max_concurrent_runs > 1:
pool = Pool(self.campaign.network.max_concurrent_runs)
pool.map(runner, nodes)
else:
for node in nodes:
runner(node)
return nodes
with pushd(self.campaign_path):
_run() | python | def run(self, *nodes):
"""Execute benchmarks on every node specified in arguments.
If none are given, then execute benchmarks on every nodes
specified in the ``network.nodes`` campaign configuration.
"""
nodes = nodes or self.nodes
self._prelude(*nodes)
@write_yaml_report
def _run():
self._build_installer()
runner = functools.partial(run_on_host, self.campaign)
if self.campaign.network.max_concurrent_runs > 1:
pool = Pool(self.campaign.network.max_concurrent_runs)
pool.map(runner, nodes)
else:
for node in nodes:
runner(node)
return nodes
with pushd(self.campaign_path):
_run() | [
"def",
"run",
"(",
"self",
",",
"*",
"nodes",
")",
":",
"nodes",
"=",
"nodes",
"or",
"self",
".",
"nodes",
"self",
".",
"_prelude",
"(",
"*",
"nodes",
")",
"@",
"write_yaml_report",
"def",
"_run",
"(",
")",
":",
"self",
".",
"_build_installer",
"(",
... | Execute benchmarks on every node specified in arguments.
If none are given, then execute benchmarks on every nodes
specified in the ``network.nodes`` campaign configuration. | [
"Execute",
"benchmarks",
"on",
"every",
"node",
"specified",
"in",
"arguments",
".",
"If",
"none",
"are",
"given",
"then",
"execute",
"benchmarks",
"on",
"every",
"nodes",
"specified",
"in",
"the",
"network",
".",
"nodes",
"campaign",
"configuration",
"."
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/net/__init__.py#L97-L118 | train | 53,401 |
BlueBrain/hpcbench | hpcbench/net/__init__.py | BeNetHost.run | def run(self):
"""Execute benchmark on the specified node
"""
with self._scp_bensh_runner():
self._execute_bensh_runner()
path = self._retrieve_tarball()
try:
self._aggregate_tarball(path)
finally:
os.remove(path) | python | def run(self):
"""Execute benchmark on the specified node
"""
with self._scp_bensh_runner():
self._execute_bensh_runner()
path = self._retrieve_tarball()
try:
self._aggregate_tarball(path)
finally:
os.remove(path) | [
"def",
"run",
"(",
"self",
")",
":",
"with",
"self",
".",
"_scp_bensh_runner",
"(",
")",
":",
"self",
".",
"_execute_bensh_runner",
"(",
")",
"path",
"=",
"self",
".",
"_retrieve_tarball",
"(",
")",
"try",
":",
"self",
".",
"_aggregate_tarball",
"(",
"pa... | Execute benchmark on the specified node | [
"Execute",
"benchmark",
"on",
"the",
"specified",
"node"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/net/__init__.py#L190-L199 | train | 53,402 |
BlueBrain/hpcbench | hpcbench/benchmark/imb.py | IMB.node_pairing | def node_pairing(self):
"""if "node" then test current node and next one
if "tag", then create tests for every pair of the current tag.
"""
value = self.attributes['node_pairing']
if value not in IMB.NODE_PAIRING:
msg = 'Unexpected {0} value: got "{1}" but valid values are {2}'
msg = msg.format('node_pairing', value, IMB.NODE_PAIRING)
raise ValueError(msg)
return value | python | def node_pairing(self):
"""if "node" then test current node and next one
if "tag", then create tests for every pair of the current tag.
"""
value = self.attributes['node_pairing']
if value not in IMB.NODE_PAIRING:
msg = 'Unexpected {0} value: got "{1}" but valid values are {2}'
msg = msg.format('node_pairing', value, IMB.NODE_PAIRING)
raise ValueError(msg)
return value | [
"def",
"node_pairing",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"attributes",
"[",
"'node_pairing'",
"]",
"if",
"value",
"not",
"in",
"IMB",
".",
"NODE_PAIRING",
":",
"msg",
"=",
"'Unexpected {0} value: got \"{1}\" but valid values are {2}'",
"msg",
"=",
... | if "node" then test current node and next one
if "tag", then create tests for every pair of the current tag. | [
"if",
"node",
"then",
"test",
"current",
"node",
"and",
"next",
"one",
"if",
"tag",
"then",
"create",
"tests",
"for",
"every",
"pair",
"of",
"the",
"current",
"tag",
"."
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/imb.py#L252-L261 | train | 53,403 |
PolyJIT/benchbuild | benchbuild/projects/gentoo/gentoo.py | setup_benchbuild | def setup_benchbuild():
"""
Setup benchbuild inside a container.
This will query a for an existing installation of benchbuild and
try to upgrade it to the latest version, if possible.
"""
LOG.debug("Setting up Benchbuild...")
venv_dir = local.path("/benchbuild")
prefixes = CFG["container"]["prefixes"].value
prefixes.append(venv_dir)
CFG["container"]["prefixes"] = prefixes
src_dir = str(CFG["source_dir"])
have_src = src_dir is not None
if have_src:
__mount_source(src_dir)
benchbuild = find_benchbuild()
if benchbuild and not requires_update(benchbuild):
if have_src:
__upgrade_from_source(venv_dir, with_deps=False)
return
setup_virtualenv(venv_dir)
if have_src:
__upgrade_from_source(venv_dir)
else:
__upgrade_from_pip(venv_dir) | python | def setup_benchbuild():
"""
Setup benchbuild inside a container.
This will query a for an existing installation of benchbuild and
try to upgrade it to the latest version, if possible.
"""
LOG.debug("Setting up Benchbuild...")
venv_dir = local.path("/benchbuild")
prefixes = CFG["container"]["prefixes"].value
prefixes.append(venv_dir)
CFG["container"]["prefixes"] = prefixes
src_dir = str(CFG["source_dir"])
have_src = src_dir is not None
if have_src:
__mount_source(src_dir)
benchbuild = find_benchbuild()
if benchbuild and not requires_update(benchbuild):
if have_src:
__upgrade_from_source(venv_dir, with_deps=False)
return
setup_virtualenv(venv_dir)
if have_src:
__upgrade_from_source(venv_dir)
else:
__upgrade_from_pip(venv_dir) | [
"def",
"setup_benchbuild",
"(",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Setting up Benchbuild...\"",
")",
"venv_dir",
"=",
"local",
".",
"path",
"(",
"\"/benchbuild\"",
")",
"prefixes",
"=",
"CFG",
"[",
"\"container\"",
"]",
"[",
"\"prefixes\"",
"]",
".",
"va... | Setup benchbuild inside a container.
This will query a for an existing installation of benchbuild and
try to upgrade it to the latest version, if possible. | [
"Setup",
"benchbuild",
"inside",
"a",
"container",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/projects/gentoo/gentoo.py#L288-L317 | train | 53,404 |
BlueBrain/hpcbench | hpcbench/cli/bennett.py | main | def main(argv=None):
"""ben-nett entry point"""
arguments = cli_common(__doc__, argv=argv)
benet = BeNet(arguments['CAMPAIGN_FILE'])
benet.run()
if argv is not None:
return benet | python | def main(argv=None):
"""ben-nett entry point"""
arguments = cli_common(__doc__, argv=argv)
benet = BeNet(arguments['CAMPAIGN_FILE'])
benet.run()
if argv is not None:
return benet | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"arguments",
"=",
"cli_common",
"(",
"__doc__",
",",
"argv",
"=",
"argv",
")",
"benet",
"=",
"BeNet",
"(",
"arguments",
"[",
"'CAMPAIGN_FILE'",
"]",
")",
"benet",
".",
"run",
"(",
")",
"if",
"argv",
... | ben-nett entry point | [
"ben",
"-",
"nett",
"entry",
"point"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/cli/bennett.py#L19-L25 | train | 53,405 |
BlueBrain/hpcbench | hpcbench/cli/benelastic.py | main | def main(argv=None):
"""ben-elastic entry point"""
arguments = cli_common(__doc__, argv=argv)
es_export = ESExporter(arguments['CAMPAIGN-DIR'], arguments['--es'])
es_export.export()
if argv is not None:
return es_export | python | def main(argv=None):
"""ben-elastic entry point"""
arguments = cli_common(__doc__, argv=argv)
es_export = ESExporter(arguments['CAMPAIGN-DIR'], arguments['--es'])
es_export.export()
if argv is not None:
return es_export | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"arguments",
"=",
"cli_common",
"(",
"__doc__",
",",
"argv",
"=",
"argv",
")",
"es_export",
"=",
"ESExporter",
"(",
"arguments",
"[",
"'CAMPAIGN-DIR'",
"]",
",",
"arguments",
"[",
"'--es'",
"]",
")",
"... | ben-elastic entry point | [
"ben",
"-",
"elastic",
"entry",
"point"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/cli/benelastic.py#L20-L26 | train | 53,406 |
Capitains/Nautilus | capitains_nautilus/apis/cts.py | CTSApi.r_cts | def r_cts(self):
""" Actual main route of CTS APIs. Transfer typical requests through the ?request=REQUESTNAME route
:return: Response
"""
_request = request.args.get("request", None)
if _request is not None:
try:
if _request.lower() == "getcapabilities":
return self._get_capabilities(
urn=request.args.get("urn", None)
)
elif _request.lower() == "getpassage":
return self._get_passage(
urn=request.args.get("urn", None)
)
elif _request.lower() == "getpassageplus":
return self._get_passage_plus(
urn=request.args.get("urn", None)
)
elif _request.lower() == "getlabel":
return self._get_label(
urn=request.args.get("urn", None)
)
elif _request.lower() == "getfirsturn":
return self._get_first_urn(
urn=request.args.get("urn", None)
)
elif _request.lower() == "getprevnexturn":
return self._get_prev_next(
urn=request.args.get("urn", None)
)
elif _request.lower() == "getvalidreff":
return self._get_valid_reff(
urn=request.args.get("urn", None),
level=request.args.get("level", 1, type=int)
)
except NautilusError as E:
return self.cts_error(error_name=E.__class__.__name__, message=E.__doc__)
return self.cts_error(MissingParameter.__name__, message=MissingParameter.__doc__) | python | def r_cts(self):
""" Actual main route of CTS APIs. Transfer typical requests through the ?request=REQUESTNAME route
:return: Response
"""
_request = request.args.get("request", None)
if _request is not None:
try:
if _request.lower() == "getcapabilities":
return self._get_capabilities(
urn=request.args.get("urn", None)
)
elif _request.lower() == "getpassage":
return self._get_passage(
urn=request.args.get("urn", None)
)
elif _request.lower() == "getpassageplus":
return self._get_passage_plus(
urn=request.args.get("urn", None)
)
elif _request.lower() == "getlabel":
return self._get_label(
urn=request.args.get("urn", None)
)
elif _request.lower() == "getfirsturn":
return self._get_first_urn(
urn=request.args.get("urn", None)
)
elif _request.lower() == "getprevnexturn":
return self._get_prev_next(
urn=request.args.get("urn", None)
)
elif _request.lower() == "getvalidreff":
return self._get_valid_reff(
urn=request.args.get("urn", None),
level=request.args.get("level", 1, type=int)
)
except NautilusError as E:
return self.cts_error(error_name=E.__class__.__name__, message=E.__doc__)
return self.cts_error(MissingParameter.__name__, message=MissingParameter.__doc__) | [
"def",
"r_cts",
"(",
"self",
")",
":",
"_request",
"=",
"request",
".",
"args",
".",
"get",
"(",
"\"request\"",
",",
"None",
")",
"if",
"_request",
"is",
"not",
"None",
":",
"try",
":",
"if",
"_request",
".",
"lower",
"(",
")",
"==",
"\"getcapabiliti... | Actual main route of CTS APIs. Transfer typical requests through the ?request=REQUESTNAME route
:return: Response | [
"Actual",
"main",
"route",
"of",
"CTS",
"APIs",
".",
"Transfer",
"typical",
"requests",
"through",
"the",
"?request",
"=",
"REQUESTNAME",
"route"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L25-L64 | train | 53,407 |
Capitains/Nautilus | capitains_nautilus/apis/cts.py | CTSApi.cts_error | def cts_error(self, error_name, message=None):
""" Create a CTS Error reply
:param error_name: Name of the error
:param message: Message of the Error
:return: CTS Error Response with information (XML)
"""
self.nautilus_extension.logger.info(
"CTS error thrown {} for {} ({})".format(
error_name,
request.query_string.decode(),
message)
)
return render_template(
"cts/Error.xml",
errorType=error_name,
message=message
), 404, {"content-type": "application/xml"} | python | def cts_error(self, error_name, message=None):
""" Create a CTS Error reply
:param error_name: Name of the error
:param message: Message of the Error
:return: CTS Error Response with information (XML)
"""
self.nautilus_extension.logger.info(
"CTS error thrown {} for {} ({})".format(
error_name,
request.query_string.decode(),
message)
)
return render_template(
"cts/Error.xml",
errorType=error_name,
message=message
), 404, {"content-type": "application/xml"} | [
"def",
"cts_error",
"(",
"self",
",",
"error_name",
",",
"message",
"=",
"None",
")",
":",
"self",
".",
"nautilus_extension",
".",
"logger",
".",
"info",
"(",
"\"CTS error thrown {} for {} ({})\"",
".",
"format",
"(",
"error_name",
",",
"request",
".",
"query_... | Create a CTS Error reply
:param error_name: Name of the error
:param message: Message of the Error
:return: CTS Error Response with information (XML) | [
"Create",
"a",
"CTS",
"Error",
"reply"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L66-L83 | train | 53,408 |
Capitains/Nautilus | capitains_nautilus/apis/cts.py | CTSApi._get_capabilities | def _get_capabilities(self, urn=None):
""" Provisional route for GetCapabilities request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetCapabilities response
"""
r = self.resolver.getMetadata(objectId=urn)
if len(r.parents) > 0:
r = r.parents[-1]
r = render_template(
"cts/GetCapabilities.xml",
filters="urn={}".format(urn),
inventory=Markup(r.export(Mimetypes.XML.CTS))
)
return r, 200, {"content-type": "application/xml"} | python | def _get_capabilities(self, urn=None):
""" Provisional route for GetCapabilities request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetCapabilities response
"""
r = self.resolver.getMetadata(objectId=urn)
if len(r.parents) > 0:
r = r.parents[-1]
r = render_template(
"cts/GetCapabilities.xml",
filters="urn={}".format(urn),
inventory=Markup(r.export(Mimetypes.XML.CTS))
)
return r, 200, {"content-type": "application/xml"} | [
"def",
"_get_capabilities",
"(",
"self",
",",
"urn",
"=",
"None",
")",
":",
"r",
"=",
"self",
".",
"resolver",
".",
"getMetadata",
"(",
"objectId",
"=",
"urn",
")",
"if",
"len",
"(",
"r",
".",
"parents",
")",
">",
"0",
":",
"r",
"=",
"r",
".",
... | Provisional route for GetCapabilities request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetCapabilities response | [
"Provisional",
"route",
"for",
"GetCapabilities",
"request"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L85-L100 | train | 53,409 |
Capitains/Nautilus | capitains_nautilus/apis/cts.py | CTSApi._get_passage | def _get_passage(self, urn):
""" Provisional route for GetPassage request
:param urn: URN to filter the resource
:return: GetPassage response
"""
urn = URN(urn)
subreference = None
if len(urn) < 4:
raise InvalidURN
if urn.reference is not None:
subreference = str(urn.reference)
node = self.resolver.getTextualNode(textId=urn.upTo(URN.NO_PASSAGE), subreference=subreference)
r = render_template(
"cts/GetPassage.xml",
filters="urn={}".format(urn),
request_urn=str(urn),
full_urn=node.urn,
passage=Markup(node.export(Mimetypes.XML.TEI))
)
return r, 200, {"content-type": "application/xml"} | python | def _get_passage(self, urn):
""" Provisional route for GetPassage request
:param urn: URN to filter the resource
:return: GetPassage response
"""
urn = URN(urn)
subreference = None
if len(urn) < 4:
raise InvalidURN
if urn.reference is not None:
subreference = str(urn.reference)
node = self.resolver.getTextualNode(textId=urn.upTo(URN.NO_PASSAGE), subreference=subreference)
r = render_template(
"cts/GetPassage.xml",
filters="urn={}".format(urn),
request_urn=str(urn),
full_urn=node.urn,
passage=Markup(node.export(Mimetypes.XML.TEI))
)
return r, 200, {"content-type": "application/xml"} | [
"def",
"_get_passage",
"(",
"self",
",",
"urn",
")",
":",
"urn",
"=",
"URN",
"(",
"urn",
")",
"subreference",
"=",
"None",
"if",
"len",
"(",
"urn",
")",
"<",
"4",
":",
"raise",
"InvalidURN",
"if",
"urn",
".",
"reference",
"is",
"not",
"None",
":",
... | Provisional route for GetPassage request
:param urn: URN to filter the resource
:return: GetPassage response | [
"Provisional",
"route",
"for",
"GetPassage",
"request"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L102-L123 | train | 53,410 |
Capitains/Nautilus | capitains_nautilus/apis/cts.py | CTSApi._get_passage_plus | def _get_passage_plus(self, urn):
""" Provisional route for GetPassagePlus request
:param urn: URN to filter the resource
:return: GetPassagePlus response
"""
urn = URN(urn)
subreference = None
if len(urn) < 4:
raise InvalidURN
if urn.reference is not None:
subreference = str(urn.reference)
node = self.resolver.getTextualNode(textId=urn.upTo(URN.NO_PASSAGE), subreference=subreference)
r = render_template(
"cts/GetPassagePlus.xml",
filters="urn={}".format(urn),
request_urn=str(urn),
full_urn=node.urn,
prev_urn=node.prevId,
next_urn=node.nextId,
metadata={
"groupname": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.groupname)],
"title": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.title)],
"description": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.description)],
"label": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.label)]
},
citation=Markup(node.citation.export(Mimetypes.XML.CTS)),
passage=Markup(node.export(Mimetypes.XML.TEI))
)
return r, 200, {"content-type": "application/xml"} | python | def _get_passage_plus(self, urn):
""" Provisional route for GetPassagePlus request
:param urn: URN to filter the resource
:return: GetPassagePlus response
"""
urn = URN(urn)
subreference = None
if len(urn) < 4:
raise InvalidURN
if urn.reference is not None:
subreference = str(urn.reference)
node = self.resolver.getTextualNode(textId=urn.upTo(URN.NO_PASSAGE), subreference=subreference)
r = render_template(
"cts/GetPassagePlus.xml",
filters="urn={}".format(urn),
request_urn=str(urn),
full_urn=node.urn,
prev_urn=node.prevId,
next_urn=node.nextId,
metadata={
"groupname": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.groupname)],
"title": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.title)],
"description": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.description)],
"label": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.label)]
},
citation=Markup(node.citation.export(Mimetypes.XML.CTS)),
passage=Markup(node.export(Mimetypes.XML.TEI))
)
return r, 200, {"content-type": "application/xml"} | [
"def",
"_get_passage_plus",
"(",
"self",
",",
"urn",
")",
":",
"urn",
"=",
"URN",
"(",
"urn",
")",
"subreference",
"=",
"None",
"if",
"len",
"(",
"urn",
")",
"<",
"4",
":",
"raise",
"InvalidURN",
"if",
"urn",
".",
"reference",
"is",
"not",
"None",
... | Provisional route for GetPassagePlus request
:param urn: URN to filter the resource
:return: GetPassagePlus response | [
"Provisional",
"route",
"for",
"GetPassagePlus",
"request"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L125-L154 | train | 53,411 |
Capitains/Nautilus | capitains_nautilus/apis/cts.py | CTSApi._get_valid_reff | def _get_valid_reff(self, urn, level):
""" Provisional route for GetValidReff request
:param urn: URN to filter the resource
:return: GetValidReff response
"""
urn = URN(urn)
subreference = None
textId=urn.upTo(URN.NO_PASSAGE)
if urn.reference is not None:
subreference = str(urn.reference)
reffs = self.resolver.getReffs(textId=textId, subreference=subreference, level=level)
r = render_template(
"cts/GetValidReff.xml",
reffs=reffs,
urn=textId,
level=level,
request_urn=str(urn)
)
return r, 200, {"content-type": "application/xml"} | python | def _get_valid_reff(self, urn, level):
""" Provisional route for GetValidReff request
:param urn: URN to filter the resource
:return: GetValidReff response
"""
urn = URN(urn)
subreference = None
textId=urn.upTo(URN.NO_PASSAGE)
if urn.reference is not None:
subreference = str(urn.reference)
reffs = self.resolver.getReffs(textId=textId, subreference=subreference, level=level)
r = render_template(
"cts/GetValidReff.xml",
reffs=reffs,
urn=textId,
level=level,
request_urn=str(urn)
)
return r, 200, {"content-type": "application/xml"} | [
"def",
"_get_valid_reff",
"(",
"self",
",",
"urn",
",",
"level",
")",
":",
"urn",
"=",
"URN",
"(",
"urn",
")",
"subreference",
"=",
"None",
"textId",
"=",
"urn",
".",
"upTo",
"(",
"URN",
".",
"NO_PASSAGE",
")",
"if",
"urn",
".",
"reference",
"is",
... | Provisional route for GetValidReff request
:param urn: URN to filter the resource
:return: GetValidReff response | [
"Provisional",
"route",
"for",
"GetValidReff",
"request"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L156-L175 | train | 53,412 |
Capitains/Nautilus | capitains_nautilus/apis/cts.py | CTSApi._get_prev_next | def _get_prev_next(self, urn):
""" Provisional route for GetPrevNext request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetPrevNext response
"""
urn = URN(urn)
subreference = None
textId = urn.upTo(URN.NO_PASSAGE)
if urn.reference is not None:
subreference = str(urn.reference)
previous, nextious = self.resolver.getSiblings(textId=textId, subreference=subreference)
r = render_template(
"cts/GetPrevNext.xml",
prev_urn=previous,
next_urn=nextious,
urn=textId,
request_urn=str(urn)
)
return r, 200, {"content-type": "application/xml"} | python | def _get_prev_next(self, urn):
""" Provisional route for GetPrevNext request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetPrevNext response
"""
urn = URN(urn)
subreference = None
textId = urn.upTo(URN.NO_PASSAGE)
if urn.reference is not None:
subreference = str(urn.reference)
previous, nextious = self.resolver.getSiblings(textId=textId, subreference=subreference)
r = render_template(
"cts/GetPrevNext.xml",
prev_urn=previous,
next_urn=nextious,
urn=textId,
request_urn=str(urn)
)
return r, 200, {"content-type": "application/xml"} | [
"def",
"_get_prev_next",
"(",
"self",
",",
"urn",
")",
":",
"urn",
"=",
"URN",
"(",
"urn",
")",
"subreference",
"=",
"None",
"textId",
"=",
"urn",
".",
"upTo",
"(",
"URN",
".",
"NO_PASSAGE",
")",
"if",
"urn",
".",
"reference",
"is",
"not",
"None",
... | Provisional route for GetPrevNext request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetPrevNext response | [
"Provisional",
"route",
"for",
"GetPrevNext",
"request"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L177-L197 | train | 53,413 |
Capitains/Nautilus | capitains_nautilus/apis/cts.py | CTSApi._get_first_urn | def _get_first_urn(self, urn):
""" Provisional route for GetFirstUrn request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetFirstUrn response
"""
urn = URN(urn)
subreference = None
textId = urn.upTo(URN.NO_PASSAGE)
if urn.reference is not None:
subreference = str(urn.reference)
firstId = self.resolver.getTextualNode(textId=textId, subreference=subreference).firstId
r = render_template(
"cts/GetFirstUrn.xml",
firstId=firstId,
full_urn=textId,
request_urn=str(urn)
)
return r, 200, {"content-type": "application/xml"} | python | def _get_first_urn(self, urn):
""" Provisional route for GetFirstUrn request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetFirstUrn response
"""
urn = URN(urn)
subreference = None
textId = urn.upTo(URN.NO_PASSAGE)
if urn.reference is not None:
subreference = str(urn.reference)
firstId = self.resolver.getTextualNode(textId=textId, subreference=subreference).firstId
r = render_template(
"cts/GetFirstUrn.xml",
firstId=firstId,
full_urn=textId,
request_urn=str(urn)
)
return r, 200, {"content-type": "application/xml"} | [
"def",
"_get_first_urn",
"(",
"self",
",",
"urn",
")",
":",
"urn",
"=",
"URN",
"(",
"urn",
")",
"subreference",
"=",
"None",
"textId",
"=",
"urn",
".",
"upTo",
"(",
"URN",
".",
"NO_PASSAGE",
")",
"if",
"urn",
".",
"reference",
"is",
"not",
"None",
... | Provisional route for GetFirstUrn request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetFirstUrn response | [
"Provisional",
"route",
"for",
"GetFirstUrn",
"request"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L199-L218 | train | 53,414 |
Capitains/Nautilus | capitains_nautilus/apis/cts.py | CTSApi._get_label | def _get_label(self, urn):
""" Provisional route for GetLabel request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetLabel response
"""
node = self.resolver.getTextualNode(textId=urn)
r = render_template(
"cts/GetLabel.xml",
request_urn=str(urn),
full_urn=node.urn,
metadata={
"groupname": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.groupname)],
"title": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.title)],
"description": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.description)],
"label": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.label)]
},
citation=Markup(node.citation.export(Mimetypes.XML.CTS))
)
return r, 200, {"content-type": "application/xml"} | python | def _get_label(self, urn):
""" Provisional route for GetLabel request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetLabel response
"""
node = self.resolver.getTextualNode(textId=urn)
r = render_template(
"cts/GetLabel.xml",
request_urn=str(urn),
full_urn=node.urn,
metadata={
"groupname": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.groupname)],
"title": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.title)],
"description": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.description)],
"label": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESPACES.CTS.label)]
},
citation=Markup(node.citation.export(Mimetypes.XML.CTS))
)
return r, 200, {"content-type": "application/xml"} | [
"def",
"_get_label",
"(",
"self",
",",
"urn",
")",
":",
"node",
"=",
"self",
".",
"resolver",
".",
"getTextualNode",
"(",
"textId",
"=",
"urn",
")",
"r",
"=",
"render_template",
"(",
"\"cts/GetLabel.xml\"",
",",
"request_urn",
"=",
"str",
"(",
"urn",
")"... | Provisional route for GetLabel request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetLabel response | [
"Provisional",
"route",
"for",
"GetLabel",
"request"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/apis/cts.py#L220-L240 | train | 53,415 |
OzymandiasTheGreat/python-libinput | libinput/__init__.py | LibInput.events | def events(self):
"""Yield events from the internal libinput's queue.
Yields device events that are subclasses of
:class:`~libinput.event.Event`.
Yields:
:class:`~libinput.event.Event`: Device event.
"""
while True:
events = self._selector.select()
for nevent in range(len(events) + 1):
self._libinput.libinput_dispatch(self._li)
hevent = self._libinput.libinput_get_event(self._li)
if hevent:
type_ = self._libinput.libinput_event_get_type(hevent)
self._libinput.libinput_dispatch(self._li)
if type_.is_pointer():
yield PointerEvent(hevent, self._libinput)
elif type_.is_keyboard():
yield KeyboardEvent(hevent, self._libinput)
elif type_.is_touch():
yield TouchEvent(hevent, self._libinput)
elif type_.is_gesture():
yield GestureEvent(hevent, self._libinput)
elif type_.is_tablet_tool():
yield TabletToolEvent(hevent, self._libinput)
elif type_.is_tablet_pad():
yield TabletPadEvent(hevent, self._libinput)
elif type_.is_switch():
yield SwitchEvent(hevent, self._libinput)
elif type_.is_device():
yield DeviceNotifyEvent(hevent, self._libinput) | python | def events(self):
"""Yield events from the internal libinput's queue.
Yields device events that are subclasses of
:class:`~libinput.event.Event`.
Yields:
:class:`~libinput.event.Event`: Device event.
"""
while True:
events = self._selector.select()
for nevent in range(len(events) + 1):
self._libinput.libinput_dispatch(self._li)
hevent = self._libinput.libinput_get_event(self._li)
if hevent:
type_ = self._libinput.libinput_event_get_type(hevent)
self._libinput.libinput_dispatch(self._li)
if type_.is_pointer():
yield PointerEvent(hevent, self._libinput)
elif type_.is_keyboard():
yield KeyboardEvent(hevent, self._libinput)
elif type_.is_touch():
yield TouchEvent(hevent, self._libinput)
elif type_.is_gesture():
yield GestureEvent(hevent, self._libinput)
elif type_.is_tablet_tool():
yield TabletToolEvent(hevent, self._libinput)
elif type_.is_tablet_pad():
yield TabletPadEvent(hevent, self._libinput)
elif type_.is_switch():
yield SwitchEvent(hevent, self._libinput)
elif type_.is_device():
yield DeviceNotifyEvent(hevent, self._libinput) | [
"def",
"events",
"(",
"self",
")",
":",
"while",
"True",
":",
"events",
"=",
"self",
".",
"_selector",
".",
"select",
"(",
")",
"for",
"nevent",
"in",
"range",
"(",
"len",
"(",
"events",
")",
"+",
"1",
")",
":",
"self",
".",
"_libinput",
".",
"li... | Yield events from the internal libinput's queue.
Yields device events that are subclasses of
:class:`~libinput.event.Event`.
Yields:
:class:`~libinput.event.Event`: Device event. | [
"Yield",
"events",
"from",
"the",
"internal",
"libinput",
"s",
"queue",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/__init__.py#L186-L219 | train | 53,416 |
OzymandiasTheGreat/python-libinput | libinput/__init__.py | LibInput.next_event_type | def next_event_type(self):
"""Return the type of the next event in the internal queue.
This method does not pop the event off the queue and the next call
to :attr:`events` returns that event.
Returns:
~libinput.constant.EventType: The event type of the next available
event or :obj:`None` if no event is available.
"""
type_ = self._libinput.libinput_next_event_type(self._li)
if type_ == 0:
return None
else:
return EventType(type_) | python | def next_event_type(self):
"""Return the type of the next event in the internal queue.
This method does not pop the event off the queue and the next call
to :attr:`events` returns that event.
Returns:
~libinput.constant.EventType: The event type of the next available
event or :obj:`None` if no event is available.
"""
type_ = self._libinput.libinput_next_event_type(self._li)
if type_ == 0:
return None
else:
return EventType(type_) | [
"def",
"next_event_type",
"(",
"self",
")",
":",
"type_",
"=",
"self",
".",
"_libinput",
".",
"libinput_next_event_type",
"(",
"self",
".",
"_li",
")",
"if",
"type_",
"==",
"0",
":",
"return",
"None",
"else",
":",
"return",
"EventType",
"(",
"type_",
")"... | Return the type of the next event in the internal queue.
This method does not pop the event off the queue and the next call
to :attr:`events` returns that event.
Returns:
~libinput.constant.EventType: The event type of the next available
event or :obj:`None` if no event is available. | [
"Return",
"the",
"type",
"of",
"the",
"next",
"event",
"in",
"the",
"internal",
"queue",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/__init__.py#L221-L236 | train | 53,417 |
OzymandiasTheGreat/python-libinput | libinput/__init__.py | LibInputPath.add_device | def add_device(self, path):
"""Add a device to a libinput context.
If successful, the device will be added to the internal list and
re-opened on :meth:`~libinput.LibInput.resume`. The device can be
removed with :meth:`remove_device`.
If the device was successfully initialized, it is returned.
Args:
path (str): Path to an input device.
Returns:
~libinput.define.Device: A device object or :obj:`None`.
"""
hdevice = self._libinput.libinput_path_add_device(
self._li, path.encode())
if hdevice:
return Device(hdevice, self._libinput)
return None | python | def add_device(self, path):
"""Add a device to a libinput context.
If successful, the device will be added to the internal list and
re-opened on :meth:`~libinput.LibInput.resume`. The device can be
removed with :meth:`remove_device`.
If the device was successfully initialized, it is returned.
Args:
path (str): Path to an input device.
Returns:
~libinput.define.Device: A device object or :obj:`None`.
"""
hdevice = self._libinput.libinput_path_add_device(
self._li, path.encode())
if hdevice:
return Device(hdevice, self._libinput)
return None | [
"def",
"add_device",
"(",
"self",
",",
"path",
")",
":",
"hdevice",
"=",
"self",
".",
"_libinput",
".",
"libinput_path_add_device",
"(",
"self",
".",
"_li",
",",
"path",
".",
"encode",
"(",
")",
")",
"if",
"hdevice",
":",
"return",
"Device",
"(",
"hdev... | Add a device to a libinput context.
If successful, the device will be added to the internal list and
re-opened on :meth:`~libinput.LibInput.resume`. The device can be
removed with :meth:`remove_device`.
If the device was successfully initialized, it is returned.
Args:
path (str): Path to an input device.
Returns:
~libinput.define.Device: A device object or :obj:`None`. | [
"Add",
"a",
"device",
"to",
"a",
"libinput",
"context",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/__init__.py#L258-L276 | train | 53,418 |
OzymandiasTheGreat/python-libinput | libinput/__init__.py | LibInputUdev.assign_seat | def assign_seat(self, seat):
"""Assign a seat to this libinput context.
New devices or the removal of existing devices will appear as events
when iterating over :meth:`~libinput.LibInput.get_event`.
:meth:`assign_seat` succeeds even if no input devices are
currently available on this seat, or if devices are available but fail
to open. Devices that do not have the minimum capabilities to be
recognized as pointer, keyboard or touch device are ignored. Such
devices and those that failed to open are ignored until the next call
to :meth:`~libinput.LibInput.resume`.
Warning:
This method may only be called once per context.
Args:
seat (str): A seat identifier.
"""
rc = self._libinput.libinput_udev_assign_seat(self._li, seat.encode())
assert rc == 0, 'Failed to assign {}'.format(seat) | python | def assign_seat(self, seat):
"""Assign a seat to this libinput context.
New devices or the removal of existing devices will appear as events
when iterating over :meth:`~libinput.LibInput.get_event`.
:meth:`assign_seat` succeeds even if no input devices are
currently available on this seat, or if devices are available but fail
to open. Devices that do not have the minimum capabilities to be
recognized as pointer, keyboard or touch device are ignored. Such
devices and those that failed to open are ignored until the next call
to :meth:`~libinput.LibInput.resume`.
Warning:
This method may only be called once per context.
Args:
seat (str): A seat identifier.
"""
rc = self._libinput.libinput_udev_assign_seat(self._li, seat.encode())
assert rc == 0, 'Failed to assign {}'.format(seat) | [
"def",
"assign_seat",
"(",
"self",
",",
"seat",
")",
":",
"rc",
"=",
"self",
".",
"_libinput",
".",
"libinput_udev_assign_seat",
"(",
"self",
".",
"_li",
",",
"seat",
".",
"encode",
"(",
")",
")",
"assert",
"rc",
"==",
"0",
",",
"'Failed to assign {}'",
... | Assign a seat to this libinput context.
New devices or the removal of existing devices will appear as events
when iterating over :meth:`~libinput.LibInput.get_event`.
:meth:`assign_seat` succeeds even if no input devices are
currently available on this seat, or if devices are available but fail
to open. Devices that do not have the minimum capabilities to be
recognized as pointer, keyboard or touch device are ignored. Such
devices and those that failed to open are ignored until the next call
to :meth:`~libinput.LibInput.resume`.
Warning:
This method may only be called once per context.
Args:
seat (str): A seat identifier. | [
"Assign",
"a",
"seat",
"to",
"this",
"libinput",
"context",
"."
] | 1f477ee9f1d56b284b20e0317ea8967c64ef1218 | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/__init__.py#L317-L337 | train | 53,419 |
BlueBrain/hpcbench | hpcbench/api.py | MetricsExtractor.context | def context(self, outdir, log_prefix):
"""Setup instance to extract metrics from the proper run
:param outdir: run directory
:param log_prefix: log filenames prefix
"""
try:
self._outdir = outdir
self._log_prefix = log_prefix
yield
finally:
self._log_prefix = None
self._outdir = None | python | def context(self, outdir, log_prefix):
"""Setup instance to extract metrics from the proper run
:param outdir: run directory
:param log_prefix: log filenames prefix
"""
try:
self._outdir = outdir
self._log_prefix = log_prefix
yield
finally:
self._log_prefix = None
self._outdir = None | [
"def",
"context",
"(",
"self",
",",
"outdir",
",",
"log_prefix",
")",
":",
"try",
":",
"self",
".",
"_outdir",
"=",
"outdir",
"self",
".",
"_log_prefix",
"=",
"log_prefix",
"yield",
"finally",
":",
"self",
".",
"_log_prefix",
"=",
"None",
"self",
".",
... | Setup instance to extract metrics from the proper run
:param outdir: run directory
:param log_prefix: log filenames prefix | [
"Setup",
"instance",
"to",
"extract",
"metrics",
"from",
"the",
"proper",
"run"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/api.py#L117-L129 | train | 53,420 |
sci-bots/svg-model | svg_model/detect_connections.py | auto_detect_adjacent_shapes | def auto_detect_adjacent_shapes(svg_source, shape_i_attr='id',
layer_name='Connections',
shapes_xpath='//svg:path | //svg:polygon',
extend=1.5):
'''
Attempt to automatically find "adjacent" shapes in a SVG layer.
In a layer within a new SVG document, draw each detected connection between
the center points of the corresponding shapes.
Parameters
----------
svg_source : str
Input SVG file as a filepath (or file-like object).
shape_i_attr : str, optional
Attribute of each shape SVG element that uniquely identifies the shape.
layer_name : str, optional
Name to use for the output layer where detected connections are drawn.
.. note:: Any existing layer with the same name will be overwritten.
shapes_xpath : str, optional
XPath path expression to select shape nodes.
By default, all ``svg:path`` and ``svg:polygon`` elements are selected.
extend : float, optional
Extend ``x``/``y`` coords by the specified number of absolute units
from the center point of each shape.
Each shape is stretched independently in the ``x`` and ``y`` direction.
In each direction, a shape is considered adjacent to all other shapes
that are overlapped by the extended shape.
Returns
-------
StringIO.StringIO
File-like object containing SVG document with layer named according to
:data:`layer_name` with the detected connections drawn as ``svg:line``
instances.
'''
# Read SVG polygons into dataframe, one row per polygon vertex.
df_shapes = svg_shapes_to_df(svg_source, xpath=shapes_xpath)
df_shapes = compute_shape_centers(df_shapes, shape_i_attr)
df_shape_connections = extract_adjacent_shapes(df_shapes, shape_i_attr,
extend=extend)
# Parse input file.
xml_root = etree.parse(svg_source)
svg_root = xml_root.xpath('/svg:svg', namespaces=INKSCAPE_NSMAP)[0]
# Get the center coordinate of each shape.
df_shape_centers = (df_shapes.drop_duplicates(subset=[shape_i_attr])
[[shape_i_attr] + ['x_center', 'y_center']]
.set_index(shape_i_attr))
# Get the center coordinate of the shapes corresponding to the two
# endpoints of each connection.
df_connection_centers = (df_shape_centers.loc[df_shape_connections.source]
.reset_index(drop=True)
.join(df_shape_centers.loc[df_shape_connections
.target]
.reset_index(drop=True), lsuffix='_source',
rsuffix='_target'))
# Remove existing connections layer from source, in-memory XML (source file
# remains unmodified). A new connections layer will be added below.
connections_xpath = '//svg:g[@inkscape:label="%s"]' % layer_name
connections_groups = svg_root.xpath(connections_xpath,
namespaces=INKSCAPE_NSMAP)
if connections_groups:
for g in connections_groups:
g.getparent().remove(g)
# Create in-memory SVG
svg_output = \
draw_lines_svg_layer(df_connection_centers
.rename(columns={'x_center_source': 'x_source',
'y_center_source': 'y_source',
'x_center_target': 'x_target',
'y_center_target': 'y_target'}),
layer_name=layer_name)
return svg_output | python | def auto_detect_adjacent_shapes(svg_source, shape_i_attr='id',
layer_name='Connections',
shapes_xpath='//svg:path | //svg:polygon',
extend=1.5):
'''
Attempt to automatically find "adjacent" shapes in a SVG layer.
In a layer within a new SVG document, draw each detected connection between
the center points of the corresponding shapes.
Parameters
----------
svg_source : str
Input SVG file as a filepath (or file-like object).
shape_i_attr : str, optional
Attribute of each shape SVG element that uniquely identifies the shape.
layer_name : str, optional
Name to use for the output layer where detected connections are drawn.
.. note:: Any existing layer with the same name will be overwritten.
shapes_xpath : str, optional
XPath path expression to select shape nodes.
By default, all ``svg:path`` and ``svg:polygon`` elements are selected.
extend : float, optional
Extend ``x``/``y`` coords by the specified number of absolute units
from the center point of each shape.
Each shape is stretched independently in the ``x`` and ``y`` direction.
In each direction, a shape is considered adjacent to all other shapes
that are overlapped by the extended shape.
Returns
-------
StringIO.StringIO
File-like object containing SVG document with layer named according to
:data:`layer_name` with the detected connections drawn as ``svg:line``
instances.
'''
# Read SVG polygons into dataframe, one row per polygon vertex.
df_shapes = svg_shapes_to_df(svg_source, xpath=shapes_xpath)
df_shapes = compute_shape_centers(df_shapes, shape_i_attr)
df_shape_connections = extract_adjacent_shapes(df_shapes, shape_i_attr,
extend=extend)
# Parse input file.
xml_root = etree.parse(svg_source)
svg_root = xml_root.xpath('/svg:svg', namespaces=INKSCAPE_NSMAP)[0]
# Get the center coordinate of each shape.
df_shape_centers = (df_shapes.drop_duplicates(subset=[shape_i_attr])
[[shape_i_attr] + ['x_center', 'y_center']]
.set_index(shape_i_attr))
# Get the center coordinate of the shapes corresponding to the two
# endpoints of each connection.
df_connection_centers = (df_shape_centers.loc[df_shape_connections.source]
.reset_index(drop=True)
.join(df_shape_centers.loc[df_shape_connections
.target]
.reset_index(drop=True), lsuffix='_source',
rsuffix='_target'))
# Remove existing connections layer from source, in-memory XML (source file
# remains unmodified). A new connections layer will be added below.
connections_xpath = '//svg:g[@inkscape:label="%s"]' % layer_name
connections_groups = svg_root.xpath(connections_xpath,
namespaces=INKSCAPE_NSMAP)
if connections_groups:
for g in connections_groups:
g.getparent().remove(g)
# Create in-memory SVG
svg_output = \
draw_lines_svg_layer(df_connection_centers
.rename(columns={'x_center_source': 'x_source',
'y_center_source': 'y_source',
'x_center_target': 'x_target',
'y_center_target': 'y_target'}),
layer_name=layer_name)
return svg_output | [
"def",
"auto_detect_adjacent_shapes",
"(",
"svg_source",
",",
"shape_i_attr",
"=",
"'id'",
",",
"layer_name",
"=",
"'Connections'",
",",
"shapes_xpath",
"=",
"'//svg:path | //svg:polygon'",
",",
"extend",
"=",
"1.5",
")",
":",
"# Read SVG polygons into dataframe, one row ... | Attempt to automatically find "adjacent" shapes in a SVG layer.
In a layer within a new SVG document, draw each detected connection between
the center points of the corresponding shapes.
Parameters
----------
svg_source : str
Input SVG file as a filepath (or file-like object).
shape_i_attr : str, optional
Attribute of each shape SVG element that uniquely identifies the shape.
layer_name : str, optional
Name to use for the output layer where detected connections are drawn.
.. note:: Any existing layer with the same name will be overwritten.
shapes_xpath : str, optional
XPath path expression to select shape nodes.
By default, all ``svg:path`` and ``svg:polygon`` elements are selected.
extend : float, optional
Extend ``x``/``y`` coords by the specified number of absolute units
from the center point of each shape.
Each shape is stretched independently in the ``x`` and ``y`` direction.
In each direction, a shape is considered adjacent to all other shapes
that are overlapped by the extended shape.
Returns
-------
StringIO.StringIO
File-like object containing SVG document with layer named according to
:data:`layer_name` with the detected connections drawn as ``svg:line``
instances. | [
"Attempt",
"to",
"automatically",
"find",
"adjacent",
"shapes",
"in",
"a",
"SVG",
"layer",
"."
] | 2d119650f995e62b29ce0b3151a23f3b957cb072 | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/detect_connections.py#L13-L95 | train | 53,421 |
BlueBrain/hpcbench | hpcbench/toolbox/collections_ext.py | flatten_dict | def flatten_dict(dic, parent_key='', sep='.'):
"""Flatten sub-keys of a dictionary
"""
items = []
for key, value in dic.items():
new_key = parent_key + sep + key if parent_key else key
if isinstance(value, collections.MutableMapping):
items.extend(flatten_dict(value, new_key, sep=sep).items())
elif isinstance(value, list):
for idx, elt in enumerate(value):
items.extend(
flatten_dict(elt, new_key + sep + str(idx), sep=sep).items()
)
else:
items.append((new_key, value))
return dict(items) | python | def flatten_dict(dic, parent_key='', sep='.'):
"""Flatten sub-keys of a dictionary
"""
items = []
for key, value in dic.items():
new_key = parent_key + sep + key if parent_key else key
if isinstance(value, collections.MutableMapping):
items.extend(flatten_dict(value, new_key, sep=sep).items())
elif isinstance(value, list):
for idx, elt in enumerate(value):
items.extend(
flatten_dict(elt, new_key + sep + str(idx), sep=sep).items()
)
else:
items.append((new_key, value))
return dict(items) | [
"def",
"flatten_dict",
"(",
"dic",
",",
"parent_key",
"=",
"''",
",",
"sep",
"=",
"'.'",
")",
":",
"items",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"dic",
".",
"items",
"(",
")",
":",
"new_key",
"=",
"parent_key",
"+",
"sep",
"+",
"key",... | Flatten sub-keys of a dictionary | [
"Flatten",
"sub",
"-",
"keys",
"of",
"a",
"dictionary"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/collections_ext.py#L103-L118 | train | 53,422 |
BlueBrain/hpcbench | hpcbench/toolbox/collections_ext.py | freeze | def freeze(obj):
"""Transform tree of dict and list in read-only
data structure.
dict instances are transformed to FrozenDict, lists
in FrozenList.
"""
if isinstance(obj, collections.Mapping):
return FrozenDict({freeze(k): freeze(v) for k, v in six.iteritems(obj)})
elif isinstance(obj, list):
return FrozenList([freeze(e) for e in obj])
else:
return obj | python | def freeze(obj):
"""Transform tree of dict and list in read-only
data structure.
dict instances are transformed to FrozenDict, lists
in FrozenList.
"""
if isinstance(obj, collections.Mapping):
return FrozenDict({freeze(k): freeze(v) for k, v in six.iteritems(obj)})
elif isinstance(obj, list):
return FrozenList([freeze(e) for e in obj])
else:
return obj | [
"def",
"freeze",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"collections",
".",
"Mapping",
")",
":",
"return",
"FrozenDict",
"(",
"{",
"freeze",
"(",
"k",
")",
":",
"freeze",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
... | Transform tree of dict and list in read-only
data structure.
dict instances are transformed to FrozenDict, lists
in FrozenList. | [
"Transform",
"tree",
"of",
"dict",
"and",
"list",
"in",
"read",
"-",
"only",
"data",
"structure",
".",
"dict",
"instances",
"are",
"transformed",
"to",
"FrozenDict",
"lists",
"in",
"FrozenList",
"."
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/collections_ext.py#L232-L243 | train | 53,423 |
BlueBrain/hpcbench | hpcbench/toolbox/collections_ext.py | Configuration.from_file | def from_file(cls, path):
"""Create a ``Configuration`` from a file
:param path: path to YAML file
:return: new configuration
:rtype: ``Configuration``
"""
if path == '-':
return Configuration(yaml.safe_load(sys.stdin))
if not osp.exists(path) and not osp.isabs(path):
path = osp.join(osp.dirname(osp.abspath(__file__)), path)
with open(path, 'r') as istr:
return Configuration(yaml.safe_load(istr)) | python | def from_file(cls, path):
"""Create a ``Configuration`` from a file
:param path: path to YAML file
:return: new configuration
:rtype: ``Configuration``
"""
if path == '-':
return Configuration(yaml.safe_load(sys.stdin))
if not osp.exists(path) and not osp.isabs(path):
path = osp.join(osp.dirname(osp.abspath(__file__)), path)
with open(path, 'r') as istr:
return Configuration(yaml.safe_load(istr)) | [
"def",
"from_file",
"(",
"cls",
",",
"path",
")",
":",
"if",
"path",
"==",
"'-'",
":",
"return",
"Configuration",
"(",
"yaml",
".",
"safe_load",
"(",
"sys",
".",
"stdin",
")",
")",
"if",
"not",
"osp",
".",
"exists",
"(",
"path",
")",
"and",
"not",
... | Create a ``Configuration`` from a file
:param path: path to YAML file
:return: new configuration
:rtype: ``Configuration`` | [
"Create",
"a",
"Configuration",
"from",
"a",
"file"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/collections_ext.py#L59-L71 | train | 53,424 |
Metatab/metatab | metatab/terms.py | Term.file_ref | def file_ref(self):
"""Return a string for the file, row and column of the term."""
from metatab.util import slugify
assert self.file_name is None or isinstance(self.file_name, str)
if self.file_name is not None and self.row is not None:
parts = split(self.file_name);
return "{} {}:{} ".format(parts[-1], self.row, self.col)
elif self.row is not None:
return " {}:{} ".format(self.row, self.col)
else:
return '' | python | def file_ref(self):
"""Return a string for the file, row and column of the term."""
from metatab.util import slugify
assert self.file_name is None or isinstance(self.file_name, str)
if self.file_name is not None and self.row is not None:
parts = split(self.file_name);
return "{} {}:{} ".format(parts[-1], self.row, self.col)
elif self.row is not None:
return " {}:{} ".format(self.row, self.col)
else:
return '' | [
"def",
"file_ref",
"(",
"self",
")",
":",
"from",
"metatab",
".",
"util",
"import",
"slugify",
"assert",
"self",
".",
"file_name",
"is",
"None",
"or",
"isinstance",
"(",
"self",
".",
"file_name",
",",
"str",
")",
"if",
"self",
".",
"file_name",
"is",
"... | Return a string for the file, row and column of the term. | [
"Return",
"a",
"string",
"for",
"the",
"file",
"row",
"and",
"column",
"of",
"the",
"term",
"."
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L152-L164 | train | 53,425 |
Metatab/metatab | metatab/terms.py | Term.add_child | def add_child(self, child):
"""Add a term to this term's children. Also sets the child term's parent"""
assert isinstance(child, Term)
self.children.append(child)
child.parent = self
assert not child.term_is("Datafile.Section") | python | def add_child(self, child):
"""Add a term to this term's children. Also sets the child term's parent"""
assert isinstance(child, Term)
self.children.append(child)
child.parent = self
assert not child.term_is("Datafile.Section") | [
"def",
"add_child",
"(",
"self",
",",
"child",
")",
":",
"assert",
"isinstance",
"(",
"child",
",",
"Term",
")",
"self",
".",
"children",
".",
"append",
"(",
"child",
")",
"child",
".",
"parent",
"=",
"self",
"assert",
"not",
"child",
".",
"term_is",
... | Add a term to this term's children. Also sets the child term's parent | [
"Add",
"a",
"term",
"to",
"this",
"term",
"s",
"children",
".",
"Also",
"sets",
"the",
"child",
"term",
"s",
"parent"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L166-L171 | train | 53,426 |
Metatab/metatab | metatab/terms.py | Term.new_child | def new_child(self, term, value, **kwargs):
"""Create a new term and add it to this term as a child. Creates grandchildren from the kwargs.
:param term: term name. Just the record term
:param term: Value to assign to the term
:param term: Term properties, which create children of the child term.
"""
tc = self.doc.get_term_class(term.lower())
c = tc(term, str(value) if value is not None else None,
parent=self, doc=self.doc, section=self.section).new_children(**kwargs)
c.term_value_name = self.doc.decl_terms.get(c.join, {}).get('termvaluename', c.term_value_name)
assert not c.term_is("*.Section")
self.children.append(c)
return c | python | def new_child(self, term, value, **kwargs):
"""Create a new term and add it to this term as a child. Creates grandchildren from the kwargs.
:param term: term name. Just the record term
:param term: Value to assign to the term
:param term: Term properties, which create children of the child term.
"""
tc = self.doc.get_term_class(term.lower())
c = tc(term, str(value) if value is not None else None,
parent=self, doc=self.doc, section=self.section).new_children(**kwargs)
c.term_value_name = self.doc.decl_terms.get(c.join, {}).get('termvaluename', c.term_value_name)
assert not c.term_is("*.Section")
self.children.append(c)
return c | [
"def",
"new_child",
"(",
"self",
",",
"term",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"tc",
"=",
"self",
".",
"doc",
".",
"get_term_class",
"(",
"term",
".",
"lower",
"(",
")",
")",
"c",
"=",
"tc",
"(",
"term",
",",
"str",
"(",
"value"... | Create a new term and add it to this term as a child. Creates grandchildren from the kwargs.
:param term: term name. Just the record term
:param term: Value to assign to the term
:param term: Term properties, which create children of the child term. | [
"Create",
"a",
"new",
"term",
"and",
"add",
"it",
"to",
"this",
"term",
"as",
"a",
"child",
".",
"Creates",
"grandchildren",
"from",
"the",
"kwargs",
"."
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L173-L191 | train | 53,427 |
Metatab/metatab | metatab/terms.py | Term.remove_child | def remove_child(self, child):
"""Remove the term from this term's children. """
assert isinstance(child, Term)
self.children.remove(child)
self.doc.remove_term(child) | python | def remove_child(self, child):
"""Remove the term from this term's children. """
assert isinstance(child, Term)
self.children.remove(child)
self.doc.remove_term(child) | [
"def",
"remove_child",
"(",
"self",
",",
"child",
")",
":",
"assert",
"isinstance",
"(",
"child",
",",
"Term",
")",
"self",
".",
"children",
".",
"remove",
"(",
"child",
")",
"self",
".",
"doc",
".",
"remove_term",
"(",
"child",
")"
] | Remove the term from this term's children. | [
"Remove",
"the",
"term",
"from",
"this",
"term",
"s",
"children",
"."
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L193-L197 | train | 53,428 |
Metatab/metatab | metatab/terms.py | Term.new_children | def new_children(self, **kwargs):
"""Create new children from kwargs"""
for k, v in kwargs.items():
self.new_child(k, v)
return self | python | def new_children(self, **kwargs):
"""Create new children from kwargs"""
for k, v in kwargs.items():
self.new_child(k, v)
return self | [
"def",
"new_children",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"self",
".",
"new_child",
"(",
"k",
",",
"v",
")",
"return",
"self"
] | Create new children from kwargs | [
"Create",
"new",
"children",
"from",
"kwargs"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L199-L204 | train | 53,429 |
Metatab/metatab | metatab/terms.py | Term.set_ownership | def set_ownership(self):
"""Recursivelt set the parent, section and doc for a children"""
assert self.section is not None
for t in self.children:
t.parent = self
t._section = self.section
t.doc = self.doc
t.set_ownership() | python | def set_ownership(self):
"""Recursivelt set the parent, section and doc for a children"""
assert self.section is not None
for t in self.children:
t.parent = self
t._section = self.section
t.doc = self.doc
t.set_ownership() | [
"def",
"set_ownership",
"(",
"self",
")",
":",
"assert",
"self",
".",
"section",
"is",
"not",
"None",
"for",
"t",
"in",
"self",
".",
"children",
":",
"t",
".",
"parent",
"=",
"self",
"t",
".",
"_section",
"=",
"self",
".",
"section",
"t",
".",
"doc... | Recursivelt set the parent, section and doc for a children | [
"Recursivelt",
"set",
"the",
"parent",
"section",
"and",
"doc",
"for",
"a",
"children"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L206-L214 | train | 53,430 |
Metatab/metatab | metatab/terms.py | Term.find | def find(self, term, value=False):
"""Return a terms by name. If the name is not qualified, use this term's record name for the parent.
The method will yield all terms with a matching qualified name. """
if '.' in term:
parent, term = term.split('.')
assert parent.lower() == self.record_term_lc, (parent.lower(), self.record_term_lc)
for c in self.children:
if c.record_term_lc == term.lower():
if value is False or c.value == value:
yield c | python | def find(self, term, value=False):
"""Return a terms by name. If the name is not qualified, use this term's record name for the parent.
The method will yield all terms with a matching qualified name. """
if '.' in term:
parent, term = term.split('.')
assert parent.lower() == self.record_term_lc, (parent.lower(), self.record_term_lc)
for c in self.children:
if c.record_term_lc == term.lower():
if value is False or c.value == value:
yield c | [
"def",
"find",
"(",
"self",
",",
"term",
",",
"value",
"=",
"False",
")",
":",
"if",
"'.'",
"in",
"term",
":",
"parent",
",",
"term",
"=",
"term",
".",
"split",
"(",
"'.'",
")",
"assert",
"parent",
".",
"lower",
"(",
")",
"==",
"self",
".",
"re... | Return a terms by name. If the name is not qualified, use this term's record name for the parent.
The method will yield all terms with a matching qualified name. | [
"Return",
"a",
"terms",
"by",
"name",
".",
"If",
"the",
"name",
"is",
"not",
"qualified",
"use",
"this",
"term",
"s",
"record",
"name",
"for",
"the",
"parent",
".",
"The",
"method",
"will",
"yield",
"all",
"terms",
"with",
"a",
"matching",
"qualified",
... | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L216-L226 | train | 53,431 |
Metatab/metatab | metatab/terms.py | Term.get_or_new_child | def get_or_new_child(self, term, value=False, **kwargs):
"""Find a term, using find_first, and set it's value and properties, if it exists. If
it does not, create a new term and children. """
pt, rt = self.split_term(term)
term = self.record_term + '.' + rt
c = self.find_first(rt)
if c is None:
tc = self.doc.get_term_class(term.lower())
c = tc(term, value, parent=self, doc=self.doc, section=self.section).new_children(**kwargs)
assert not c.term_is("Datafile.Section"), (self, c)
self.children.append(c)
else:
if value is not False:
c.value = value
for k, v in kwargs.items():
c.get_or_new_child(k, v)
# Check that the term was inserted and can be found.
assert self.find_first(rt)
assert self.find_first(rt) == c
return c | python | def get_or_new_child(self, term, value=False, **kwargs):
"""Find a term, using find_first, and set it's value and properties, if it exists. If
it does not, create a new term and children. """
pt, rt = self.split_term(term)
term = self.record_term + '.' + rt
c = self.find_first(rt)
if c is None:
tc = self.doc.get_term_class(term.lower())
c = tc(term, value, parent=self, doc=self.doc, section=self.section).new_children(**kwargs)
assert not c.term_is("Datafile.Section"), (self, c)
self.children.append(c)
else:
if value is not False:
c.value = value
for k, v in kwargs.items():
c.get_or_new_child(k, v)
# Check that the term was inserted and can be found.
assert self.find_first(rt)
assert self.find_first(rt) == c
return c | [
"def",
"get_or_new_child",
"(",
"self",
",",
"term",
",",
"value",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"pt",
",",
"rt",
"=",
"self",
".",
"split_term",
"(",
"term",
")",
"term",
"=",
"self",
".",
"record_term",
"+",
"'.'",
"+",
"rt",
... | Find a term, using find_first, and set it's value and properties, if it exists. If
it does not, create a new term and children. | [
"Find",
"a",
"term",
"using",
"find_first",
"and",
"set",
"it",
"s",
"value",
"and",
"properties",
"if",
"it",
"exists",
".",
"If",
"it",
"does",
"not",
"create",
"a",
"new",
"term",
"and",
"children",
"."
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L254-L281 | train | 53,432 |
Metatab/metatab | metatab/terms.py | Term.get_value | def get_value(self, item, default=None):
"""Get the value of a child"""
try:
return self[item].value
except (AttributeError, KeyError) as e:
return default | python | def get_value(self, item, default=None):
"""Get the value of a child"""
try:
return self[item].value
except (AttributeError, KeyError) as e:
return default | [
"def",
"get_value",
"(",
"self",
",",
"item",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
"[",
"item",
"]",
".",
"value",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
"as",
"e",
":",
"return",
"default"
] | Get the value of a child | [
"Get",
"the",
"value",
"of",
"a",
"child"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L390-L395 | train | 53,433 |
Metatab/metatab | metatab/terms.py | Term.qualified_term | def qualified_term(self):
"""Return the fully qualified term name. The parent will be 'root' if there is no parent term defined. """
assert self.parent is not None or self.parent_term_lc == 'root'
if self.parent:
return self.parent.record_term_lc + '.' + self.record_term_lc
else:
return 'root.' + self.record_term_lc | python | def qualified_term(self):
"""Return the fully qualified term name. The parent will be 'root' if there is no parent term defined. """
assert self.parent is not None or self.parent_term_lc == 'root'
if self.parent:
return self.parent.record_term_lc + '.' + self.record_term_lc
else:
return 'root.' + self.record_term_lc | [
"def",
"qualified_term",
"(",
"self",
")",
":",
"assert",
"self",
".",
"parent",
"is",
"not",
"None",
"or",
"self",
".",
"parent_term_lc",
"==",
"'root'",
"if",
"self",
".",
"parent",
":",
"return",
"self",
".",
"parent",
".",
"record_term_lc",
"+",
"'.'... | Return the fully qualified term name. The parent will be 'root' if there is no parent term defined. | [
"Return",
"the",
"fully",
"qualified",
"term",
"name",
".",
"The",
"parent",
"will",
"be",
"root",
"if",
"there",
"is",
"no",
"parent",
"term",
"defined",
"."
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L437-L445 | train | 53,434 |
Metatab/metatab | metatab/terms.py | Term.term_is | def term_is(self, v):
"""Return True if the fully qualified name of the term is the same as the argument. If the
argument is a list or tuple, return True if any of the term names match.
Either the parent or the record term can be '*' ( 'Table.*' or '*.Name' ) to match any value for
either the parent or record term.
"""
if isinstance(v, str):
if '.' not in v:
v = 'root.' + v
v_p, v_r = self.split_term_lower(v)
if self.join_lc == v.lower():
return True
elif v_r == '*' and v_p == self.parent_term_lc:
return True
elif v_p == '*' and v_r == self.record_term_lc:
return True
elif v_p == '*' and v_r == '*':
return True
else:
return False
else:
return any(self.term_is(e) for e in v) | python | def term_is(self, v):
"""Return True if the fully qualified name of the term is the same as the argument. If the
argument is a list or tuple, return True if any of the term names match.
Either the parent or the record term can be '*' ( 'Table.*' or '*.Name' ) to match any value for
either the parent or record term.
"""
if isinstance(v, str):
if '.' not in v:
v = 'root.' + v
v_p, v_r = self.split_term_lower(v)
if self.join_lc == v.lower():
return True
elif v_r == '*' and v_p == self.parent_term_lc:
return True
elif v_p == '*' and v_r == self.record_term_lc:
return True
elif v_p == '*' and v_r == '*':
return True
else:
return False
else:
return any(self.term_is(e) for e in v) | [
"def",
"term_is",
"(",
"self",
",",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"str",
")",
":",
"if",
"'.'",
"not",
"in",
"v",
":",
"v",
"=",
"'root.'",
"+",
"v",
"v_p",
",",
"v_r",
"=",
"self",
".",
"split_term_lower",
"(",
"v",
")",
... | Return True if the fully qualified name of the term is the same as the argument. If the
argument is a list or tuple, return True if any of the term names match.
Either the parent or the record term can be '*' ( 'Table.*' or '*.Name' ) to match any value for
either the parent or record term. | [
"Return",
"True",
"if",
"the",
"fully",
"qualified",
"name",
"of",
"the",
"term",
"is",
"the",
"same",
"as",
"the",
"argument",
".",
"If",
"the",
"argument",
"is",
"a",
"list",
"or",
"tuple",
"return",
"True",
"if",
"any",
"of",
"the",
"term",
"names",... | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L447-L476 | train | 53,435 |
Metatab/metatab | metatab/terms.py | Term.arg_props | def arg_props(self):
"""Return the value and scalar properties as a dictionary. Returns only argumnet properties,
properties declared on the same row as a term. It will return an entry for all of the args declared by the
term's section. Use props to get values of all children and
arg props combined"""
d = dict(zip([str(e).lower() for e in self.section.property_names], self.args))
# print({ c.record_term_lc:c.value for c in self.children})
d[self.term_value_name.lower()] = self.value
return d | python | def arg_props(self):
"""Return the value and scalar properties as a dictionary. Returns only argumnet properties,
properties declared on the same row as a term. It will return an entry for all of the args declared by the
term's section. Use props to get values of all children and
arg props combined"""
d = dict(zip([str(e).lower() for e in self.section.property_names], self.args))
# print({ c.record_term_lc:c.value for c in self.children})
d[self.term_value_name.lower()] = self.value
return d | [
"def",
"arg_props",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
"zip",
"(",
"[",
"str",
"(",
"e",
")",
".",
"lower",
"(",
")",
"for",
"e",
"in",
"self",
".",
"section",
".",
"property_names",
"]",
",",
"self",
".",
"args",
")",
")",
"# print(... | Return the value and scalar properties as a dictionary. Returns only argumnet properties,
properties declared on the same row as a term. It will return an entry for all of the args declared by the
term's section. Use props to get values of all children and
arg props combined | [
"Return",
"the",
"value",
"and",
"scalar",
"properties",
"as",
"a",
"dictionary",
".",
"Returns",
"only",
"argumnet",
"properties",
"properties",
"declared",
"on",
"the",
"same",
"row",
"as",
"a",
"term",
".",
"It",
"will",
"return",
"an",
"entry",
"for",
... | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L516-L527 | train | 53,436 |
Metatab/metatab | metatab/terms.py | Term.all_props | def all_props(self):
"""Return a dictionary with the values of all children, and place holders for all of the section
argumemts. It combines props and arg_props"""
d = self.arg_props
d.update(self.props)
return d | python | def all_props(self):
"""Return a dictionary with the values of all children, and place holders for all of the section
argumemts. It combines props and arg_props"""
d = self.arg_props
d.update(self.props)
return d | [
"def",
"all_props",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"arg_props",
"d",
".",
"update",
"(",
"self",
".",
"props",
")",
"return",
"d"
] | Return a dictionary with the values of all children, and place holders for all of the section
argumemts. It combines props and arg_props | [
"Return",
"a",
"dictionary",
"with",
"the",
"values",
"of",
"all",
"children",
"and",
"place",
"holders",
"for",
"all",
"of",
"the",
"section",
"argumemts",
".",
"It",
"combines",
"props",
"and",
"arg_props"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L530-L537 | train | 53,437 |
Metatab/metatab | metatab/terms.py | Term._convert_to_dict | def _convert_to_dict(cls, term, replace_value_names=True):
"""Converts a record heirarchy to nested dicts.
:param term: Root term at which to start conversion
"""
from collections import OrderedDict
if not term:
return None
if term.children:
d = OrderedDict()
for c in term.children:
if c.child_property_type == 'scalar':
d[c.record_term_lc] = cls._convert_to_dict(c, replace_value_names)
elif c.child_property_type == 'sequence':
try:
d[c.record_term_lc].append(cls._convert_to_dict(c, replace_value_names))
except (KeyError, AttributeError):
# The c.term property doesn't exist, so add a list
d[c.record_term_lc] = [cls._convert_to_dict(c, replace_value_names)]
elif c.child_property_type == 'sconcat': # Concat with a space
if c.record_term_lc in d:
s = d[c.record_term_lc] + ' '
else:
s = ''
d[c.record_term_lc] =s + (cls._convert_to_dict(c, replace_value_names) or '')
elif c.child_property_type == 'bconcat': # Concat with a blank
d[c.record_term_lc] = d.get(c.record_term_lc, '') + (cls._convert_to_dict(c,
replace_value_names)
or '')
else:
try:
d[c.record_term_lc].append(cls._convert_to_dict(c, replace_value_names))
except KeyError:
# The c.term property doesn't exist, so add a scalar or a map
d[c.record_term_lc] = cls._convert_to_dict(c, replace_value_names)
except AttributeError as e:
# d[c.term] exists, but is a scalar, so convert it to a list
d[c.record_term_lc] = [d[c.record_term]] + [cls._convert_to_dict(c, replace_value_names)]
if term.value:
if replace_value_names:
d[term.term_value_name.lower()] = term.value
else:
d['@value'] = term.value
return d
else:
return term.value | python | def _convert_to_dict(cls, term, replace_value_names=True):
"""Converts a record heirarchy to nested dicts.
:param term: Root term at which to start conversion
"""
from collections import OrderedDict
if not term:
return None
if term.children:
d = OrderedDict()
for c in term.children:
if c.child_property_type == 'scalar':
d[c.record_term_lc] = cls._convert_to_dict(c, replace_value_names)
elif c.child_property_type == 'sequence':
try:
d[c.record_term_lc].append(cls._convert_to_dict(c, replace_value_names))
except (KeyError, AttributeError):
# The c.term property doesn't exist, so add a list
d[c.record_term_lc] = [cls._convert_to_dict(c, replace_value_names)]
elif c.child_property_type == 'sconcat': # Concat with a space
if c.record_term_lc in d:
s = d[c.record_term_lc] + ' '
else:
s = ''
d[c.record_term_lc] =s + (cls._convert_to_dict(c, replace_value_names) or '')
elif c.child_property_type == 'bconcat': # Concat with a blank
d[c.record_term_lc] = d.get(c.record_term_lc, '') + (cls._convert_to_dict(c,
replace_value_names)
or '')
else:
try:
d[c.record_term_lc].append(cls._convert_to_dict(c, replace_value_names))
except KeyError:
# The c.term property doesn't exist, so add a scalar or a map
d[c.record_term_lc] = cls._convert_to_dict(c, replace_value_names)
except AttributeError as e:
# d[c.term] exists, but is a scalar, so convert it to a list
d[c.record_term_lc] = [d[c.record_term]] + [cls._convert_to_dict(c, replace_value_names)]
if term.value:
if replace_value_names:
d[term.term_value_name.lower()] = term.value
else:
d['@value'] = term.value
return d
else:
return term.value | [
"def",
"_convert_to_dict",
"(",
"cls",
",",
"term",
",",
"replace_value_names",
"=",
"True",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"if",
"not",
"term",
":",
"return",
"None",
"if",
"term",
".",
"children",
":",
"d",
"=",
"OrderedDict",
... | Converts a record heirarchy to nested dicts.
:param term: Root term at which to start conversion | [
"Converts",
"a",
"record",
"heirarchy",
"to",
"nested",
"dicts",
"."
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L546-L609 | train | 53,438 |
Metatab/metatab | metatab/terms.py | Term.rows | def rows(self):
"""Yield rows for the term, for writing terms to a CSV file. """
# Translate the term value name so it can be assigned to a parameter.
tvm = self.section.doc.decl_terms.get(self.qualified_term, {}).get('termvaluename', '@value')
assert tvm
# Terminal children have no arguments, just a value. Here we put the terminal children
# in a property array, so they can be written to the parent's arg-children columns
# if the section has any.
properties = {tvm: self.value}
for c in self.children:
if c.is_terminal:
if c.record_term_lc:
# This is rare, but can happen if a property child is not given
# a property name by the section -- the "Section" term has a blank column.
properties[c.record_term_lc] = c.value
yield (self.qualified_term, properties)
# The non-terminal children have to get yielded normally -- they can't be arg-children
for c in self.children:
if not c.is_terminal:
for row in c.rows:
yield row | python | def rows(self):
"""Yield rows for the term, for writing terms to a CSV file. """
# Translate the term value name so it can be assigned to a parameter.
tvm = self.section.doc.decl_terms.get(self.qualified_term, {}).get('termvaluename', '@value')
assert tvm
# Terminal children have no arguments, just a value. Here we put the terminal children
# in a property array, so they can be written to the parent's arg-children columns
# if the section has any.
properties = {tvm: self.value}
for c in self.children:
if c.is_terminal:
if c.record_term_lc:
# This is rare, but can happen if a property child is not given
# a property name by the section -- the "Section" term has a blank column.
properties[c.record_term_lc] = c.value
yield (self.qualified_term, properties)
# The non-terminal children have to get yielded normally -- they can't be arg-children
for c in self.children:
if not c.is_terminal:
for row in c.rows:
yield row | [
"def",
"rows",
"(",
"self",
")",
":",
"# Translate the term value name so it can be assigned to a parameter.",
"tvm",
"=",
"self",
".",
"section",
".",
"doc",
".",
"decl_terms",
".",
"get",
"(",
"self",
".",
"qualified_term",
",",
"{",
"}",
")",
".",
"get",
"(... | Yield rows for the term, for writing terms to a CSV file. | [
"Yield",
"rows",
"for",
"the",
"term",
"for",
"writing",
"terms",
"to",
"a",
"CSV",
"file",
"."
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L612-L637 | train | 53,439 |
Metatab/metatab | metatab/terms.py | Term.descendents | def descendents(self):
"""Iterate over all descendent terms"""
for c in self.children:
yield c
for d in c.descendents:
yield d | python | def descendents(self):
"""Iterate over all descendent terms"""
for c in self.children:
yield c
for d in c.descendents:
yield d | [
"def",
"descendents",
"(",
"self",
")",
":",
"for",
"c",
"in",
"self",
".",
"children",
":",
"yield",
"c",
"for",
"d",
"in",
"c",
".",
"descendents",
":",
"yield",
"d"
] | Iterate over all descendent terms | [
"Iterate",
"over",
"all",
"descendent",
"terms"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L640-L647 | train | 53,440 |
Metatab/metatab | metatab/terms.py | SectionTerm.subclass | def subclass(cls, t):
"""Change a term into a Section Term"""
t.doc = None
t.terms = []
t.__class__ = SectionTerm
return t | python | def subclass(cls, t):
"""Change a term into a Section Term"""
t.doc = None
t.terms = []
t.__class__ = SectionTerm
return t | [
"def",
"subclass",
"(",
"cls",
",",
"t",
")",
":",
"t",
".",
"doc",
"=",
"None",
"t",
".",
"terms",
"=",
"[",
"]",
"t",
".",
"__class__",
"=",
"SectionTerm",
"return",
"t"
] | Change a term into a Section Term | [
"Change",
"a",
"term",
"into",
"a",
"Section",
"Term"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L704-L709 | train | 53,441 |
Metatab/metatab | metatab/terms.py | SectionTerm.add_arg | def add_arg(self,arg, prepend=False):
"""Append an arg to the arg list"""
self.args = [arg_.strip() for arg_ in self.args if arg_.strip()]
if arg.title() not in self.args:
if prepend:
self.args = [arg.title()] + self.args
else:
self.args.append(arg.title()) | python | def add_arg(self,arg, prepend=False):
"""Append an arg to the arg list"""
self.args = [arg_.strip() for arg_ in self.args if arg_.strip()]
if arg.title() not in self.args:
if prepend:
self.args = [arg.title()] + self.args
else:
self.args.append(arg.title()) | [
"def",
"add_arg",
"(",
"self",
",",
"arg",
",",
"prepend",
"=",
"False",
")",
":",
"self",
".",
"args",
"=",
"[",
"arg_",
".",
"strip",
"(",
")",
"for",
"arg_",
"in",
"self",
".",
"args",
"if",
"arg_",
".",
"strip",
"(",
")",
"]",
"if",
"arg",
... | Append an arg to the arg list | [
"Append",
"an",
"arg",
"to",
"the",
"arg",
"list"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L724-L733 | train | 53,442 |
Metatab/metatab | metatab/terms.py | SectionTerm.remove_arg | def remove_arg(self, arg):
"""Remove an arg to the arg list"""
self.args = [arg_.strip() for arg_ in self.args if arg_.strip()]
for arg_ in list(self.args):
if arg_.lower() == arg.lower():
self.args.remove(arg_) | python | def remove_arg(self, arg):
"""Remove an arg to the arg list"""
self.args = [arg_.strip() for arg_ in self.args if arg_.strip()]
for arg_ in list(self.args):
if arg_.lower() == arg.lower():
self.args.remove(arg_) | [
"def",
"remove_arg",
"(",
"self",
",",
"arg",
")",
":",
"self",
".",
"args",
"=",
"[",
"arg_",
".",
"strip",
"(",
")",
"for",
"arg_",
"in",
"self",
".",
"args",
"if",
"arg_",
".",
"strip",
"(",
")",
"]",
"for",
"arg_",
"in",
"list",
"(",
"self"... | Remove an arg to the arg list | [
"Remove",
"an",
"arg",
"to",
"the",
"arg",
"list"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L735-L742 | train | 53,443 |
Metatab/metatab | metatab/terms.py | SectionTerm.add_term | def add_term(self, t):
"""Add a term to this section and set it's ownership. Should only be used on root level terms"""
if t not in self.terms:
if t.parent_term_lc == 'root':
self.terms.append(t)
self.doc.add_term(t, add_section=False)
t.set_ownership()
else:
raise GenerateError("Can only add or move root-level terms. Term '{}' parent is '{}' "
.format(t, t.parent_term_lc))
assert t.section or t.join_lc == 'root.root', t | python | def add_term(self, t):
"""Add a term to this section and set it's ownership. Should only be used on root level terms"""
if t not in self.terms:
if t.parent_term_lc == 'root':
self.terms.append(t)
self.doc.add_term(t, add_section=False)
t.set_ownership()
else:
raise GenerateError("Can only add or move root-level terms. Term '{}' parent is '{}' "
.format(t, t.parent_term_lc))
assert t.section or t.join_lc == 'root.root', t | [
"def",
"add_term",
"(",
"self",
",",
"t",
")",
":",
"if",
"t",
"not",
"in",
"self",
".",
"terms",
":",
"if",
"t",
".",
"parent_term_lc",
"==",
"'root'",
":",
"self",
".",
"terms",
".",
"append",
"(",
"t",
")",
"self",
".",
"doc",
".",
"add_term",... | Add a term to this section and set it's ownership. Should only be used on root level terms | [
"Add",
"a",
"term",
"to",
"this",
"section",
"and",
"set",
"it",
"s",
"ownership",
".",
"Should",
"only",
"be",
"used",
"on",
"root",
"level",
"terms"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L744-L758 | train | 53,444 |
Metatab/metatab | metatab/terms.py | SectionTerm.new_term | def new_term(self, term, value, **kwargs):
"""Create a new root-level term in this section"""
tc = self.doc.get_term_class(term.lower())
t = tc(term, value, doc=self.doc, parent=None, section=self).new_children(**kwargs)
self.doc.add_term(t)
return t | python | def new_term(self, term, value, **kwargs):
"""Create a new root-level term in this section"""
tc = self.doc.get_term_class(term.lower())
t = tc(term, value, doc=self.doc, parent=None, section=self).new_children(**kwargs)
self.doc.add_term(t)
return t | [
"def",
"new_term",
"(",
"self",
",",
"term",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"tc",
"=",
"self",
".",
"doc",
".",
"get_term_class",
"(",
"term",
".",
"lower",
"(",
")",
")",
"t",
"=",
"tc",
"(",
"term",
",",
"value",
",",
"doc",... | Create a new root-level term in this section | [
"Create",
"a",
"new",
"root",
"-",
"level",
"term",
"in",
"this",
"section"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L764-L772 | train | 53,445 |
Metatab/metatab | metatab/terms.py | SectionTerm.get_term | def get_term(self, term, value=False):
"""Synonym for find_first, restructed to this section"""
return self.doc.find_first(term, value=value, section=self.name) | python | def get_term(self, term, value=False):
"""Synonym for find_first, restructed to this section"""
return self.doc.find_first(term, value=value, section=self.name) | [
"def",
"get_term",
"(",
"self",
",",
"term",
",",
"value",
"=",
"False",
")",
":",
"return",
"self",
".",
"doc",
".",
"find_first",
"(",
"term",
",",
"value",
"=",
"value",
",",
"section",
"=",
"self",
".",
"name",
")"
] | Synonym for find_first, restructed to this section | [
"Synonym",
"for",
"find_first",
"restructed",
"to",
"this",
"section"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L774-L776 | train | 53,446 |
Metatab/metatab | metatab/terms.py | SectionTerm.remove_term | def remove_term(self, term, remove_from_doc=True):
"""Remove a term from the terms. Must be the identical term, the same object"""
try:
self.terms.remove(term)
except ValueError:
pass
if remove_from_doc:
self.doc.remove_term(term) | python | def remove_term(self, term, remove_from_doc=True):
"""Remove a term from the terms. Must be the identical term, the same object"""
try:
self.terms.remove(term)
except ValueError:
pass
if remove_from_doc:
self.doc.remove_term(term) | [
"def",
"remove_term",
"(",
"self",
",",
"term",
",",
"remove_from_doc",
"=",
"True",
")",
":",
"try",
":",
"self",
".",
"terms",
".",
"remove",
"(",
"term",
")",
"except",
"ValueError",
":",
"pass",
"if",
"remove_from_doc",
":",
"self",
".",
"doc",
"."... | Remove a term from the terms. Must be the identical term, the same object | [
"Remove",
"a",
"term",
"from",
"the",
"terms",
".",
"Must",
"be",
"the",
"identical",
"term",
"the",
"same",
"object"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L833-L842 | train | 53,447 |
Metatab/metatab | metatab/terms.py | SectionTerm.clean | def clean(self):
"""Remove all of the terms from the section, and also remove them from the document"""
terms = list(self)
for t in terms:
self.doc.remove_term(t) | python | def clean(self):
"""Remove all of the terms from the section, and also remove them from the document"""
terms = list(self)
for t in terms:
self.doc.remove_term(t) | [
"def",
"clean",
"(",
"self",
")",
":",
"terms",
"=",
"list",
"(",
"self",
")",
"for",
"t",
"in",
"terms",
":",
"self",
".",
"doc",
".",
"remove_term",
"(",
"t",
")"
] | Remove all of the terms from the section, and also remove them from the document | [
"Remove",
"all",
"of",
"the",
"terms",
"from",
"the",
"section",
"and",
"also",
"remove",
"them",
"from",
"the",
"document"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L844-L849 | train | 53,448 |
Metatab/metatab | metatab/terms.py | SectionTerm._args | def _args(self, term, d):
"""Extract the chldren of a term that are arg-children from those that are row-children. """
# Get the term value name, the property name that should be assigned to the term value.
tvm = self.doc.decl_terms.get(term, {}).get('termvaluename', '@value')
# Convert the keys to lower case
lower_d = {k.lower(): v for k, v in d.items()}
args = []
for n in [tvm] + self.property_names:
args.append(lower_d.get(n.lower(), ''))
try:
del lower_d[n.lower()]
except KeyError:
pass
return term, args, lower_d | python | def _args(self, term, d):
"""Extract the chldren of a term that are arg-children from those that are row-children. """
# Get the term value name, the property name that should be assigned to the term value.
tvm = self.doc.decl_terms.get(term, {}).get('termvaluename', '@value')
# Convert the keys to lower case
lower_d = {k.lower(): v for k, v in d.items()}
args = []
for n in [tvm] + self.property_names:
args.append(lower_d.get(n.lower(), ''))
try:
del lower_d[n.lower()]
except KeyError:
pass
return term, args, lower_d | [
"def",
"_args",
"(",
"self",
",",
"term",
",",
"d",
")",
":",
"# Get the term value name, the property name that should be assigned to the term value.",
"tvm",
"=",
"self",
".",
"doc",
".",
"decl_terms",
".",
"get",
"(",
"term",
",",
"{",
"}",
")",
".",
"get",
... | Extract the chldren of a term that are arg-children from those that are row-children. | [
"Extract",
"the",
"chldren",
"of",
"a",
"term",
"that",
"are",
"arg",
"-",
"children",
"from",
"those",
"that",
"are",
"row",
"-",
"children",
"."
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L899-L918 | train | 53,449 |
Metatab/metatab | metatab/terms.py | SectionTerm.rows | def rows(self):
"""Yield rows for the section"""
for t in self.terms:
for row in t.rows:
term, value = row # Value can either be a string, or a dict
if isinstance(value, dict): # Dict is for properties, which might be arg-children
term, args, remain = self._args(term, value)
yield term, args
# 'remain' is all of the children that didn't have an arg-child column -- the
# section didn't have a column heder for that ther.
for k, v in remain.items():
yield term.split('.')[-1] + '.' + k, v
else:
yield row | python | def rows(self):
"""Yield rows for the section"""
for t in self.terms:
for row in t.rows:
term, value = row # Value can either be a string, or a dict
if isinstance(value, dict): # Dict is for properties, which might be arg-children
term, args, remain = self._args(term, value)
yield term, args
# 'remain' is all of the children that didn't have an arg-child column -- the
# section didn't have a column heder for that ther.
for k, v in remain.items():
yield term.split('.')[-1] + '.' + k, v
else:
yield row | [
"def",
"rows",
"(",
"self",
")",
":",
"for",
"t",
"in",
"self",
".",
"terms",
":",
"for",
"row",
"in",
"t",
".",
"rows",
":",
"term",
",",
"value",
"=",
"row",
"# Value can either be a string, or a dict",
"if",
"isinstance",
"(",
"value",
",",
"dict",
... | Yield rows for the section | [
"Yield",
"rows",
"for",
"the",
"section"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L921-L937 | train | 53,450 |
Metatab/metatab | metatab/terms.py | SectionTerm.lines | def lines(self):
"""Iterate over all of the rows as text lines"""
# Yield the section header
if self.name != 'Root':
yield ('Section', '|'.join([self.value] + self.property_names))
# Yield all of the rows for terms in the section
for row in self.rows:
term, value = row
if not isinstance(value, (list, tuple)):
value = [value]
term = term.replace('root.', '').title()
yield (term, value[0])
children = list(zip(self.property_names, value[1:]))
for prop, value in children:
if value and value.strip():
child_t = '.' + (prop.title())
yield (" "+child_t, value) | python | def lines(self):
"""Iterate over all of the rows as text lines"""
# Yield the section header
if self.name != 'Root':
yield ('Section', '|'.join([self.value] + self.property_names))
# Yield all of the rows for terms in the section
for row in self.rows:
term, value = row
if not isinstance(value, (list, tuple)):
value = [value]
term = term.replace('root.', '').title()
yield (term, value[0])
children = list(zip(self.property_names, value[1:]))
for prop, value in children:
if value and value.strip():
child_t = '.' + (prop.title())
yield (" "+child_t, value) | [
"def",
"lines",
"(",
"self",
")",
":",
"# Yield the section header",
"if",
"self",
".",
"name",
"!=",
"'Root'",
":",
"yield",
"(",
"'Section'",
",",
"'|'",
".",
"join",
"(",
"[",
"self",
".",
"value",
"]",
"+",
"self",
".",
"property_names",
")",
")",
... | Iterate over all of the rows as text lines | [
"Iterate",
"over",
"all",
"of",
"the",
"rows",
"as",
"text",
"lines"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L940-L962 | train | 53,451 |
Metatab/metatab | metatab/terms.py | SectionTerm.as_dict | def as_dict(self, replace_value_names=True):
"""Return the whole section as a dict"""
old_children = self.children
self.children = self.terms
d = super(SectionTerm, self).as_dict(replace_value_names)
self.children = old_children
return d | python | def as_dict(self, replace_value_names=True):
"""Return the whole section as a dict"""
old_children = self.children
self.children = self.terms
d = super(SectionTerm, self).as_dict(replace_value_names)
self.children = old_children
return d | [
"def",
"as_dict",
"(",
"self",
",",
"replace_value_names",
"=",
"True",
")",
":",
"old_children",
"=",
"self",
".",
"children",
"self",
".",
"children",
"=",
"self",
".",
"terms",
"d",
"=",
"super",
"(",
"SectionTerm",
",",
"self",
")",
".",
"as_dict",
... | Return the whole section as a dict | [
"Return",
"the",
"whole",
"section",
"as",
"a",
"dict"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/terms.py#L967-L976 | train | 53,452 |
bjodah/pycompilation | pycompilation/runners.py | CompilerRunner.cmd | def cmd(self):
"""
The command below covers most cases, if you need
someting more complex subclass this.
"""
cmd = (
[self.compiler_binary] +
self.flags +
['-U'+x for x in self.undef] +
['-D'+x for x in self.define] +
['-I'+x for x in self.include_dirs] +
self.sources
)
if self.run_linker:
cmd += (['-L'+x for x in self.library_dirs] +
[(x if os.path.exists(x) else '-l'+x) for x in self.libraries] +
self.linkline)
counted = []
for envvar in re.findall('\$\{(\w+)\}', ' '.join(cmd)):
if os.getenv(envvar) is None:
if envvar not in counted:
counted.append(envvar)
msg = "Environment variable '{}' undefined.".format(
envvar)
self.logger.error(msg)
raise CompilationError(msg)
return cmd | python | def cmd(self):
"""
The command below covers most cases, if you need
someting more complex subclass this.
"""
cmd = (
[self.compiler_binary] +
self.flags +
['-U'+x for x in self.undef] +
['-D'+x for x in self.define] +
['-I'+x for x in self.include_dirs] +
self.sources
)
if self.run_linker:
cmd += (['-L'+x for x in self.library_dirs] +
[(x if os.path.exists(x) else '-l'+x) for x in self.libraries] +
self.linkline)
counted = []
for envvar in re.findall('\$\{(\w+)\}', ' '.join(cmd)):
if os.getenv(envvar) is None:
if envvar not in counted:
counted.append(envvar)
msg = "Environment variable '{}' undefined.".format(
envvar)
self.logger.error(msg)
raise CompilationError(msg)
return cmd | [
"def",
"cmd",
"(",
"self",
")",
":",
"cmd",
"=",
"(",
"[",
"self",
".",
"compiler_binary",
"]",
"+",
"self",
".",
"flags",
"+",
"[",
"'-U'",
"+",
"x",
"for",
"x",
"in",
"self",
".",
"undef",
"]",
"+",
"[",
"'-D'",
"+",
"x",
"for",
"x",
"in",
... | The command below covers most cases, if you need
someting more complex subclass this. | [
"The",
"command",
"below",
"covers",
"most",
"cases",
"if",
"you",
"need",
"someting",
"more",
"complex",
"subclass",
"this",
"."
] | 43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18 | https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/runners.py#L290-L316 | train | 53,453 |
PolyJIT/benchbuild | benchbuild/utils/download.py | get_hash_of_dirs | def get_hash_of_dirs(directory):
"""
Recursively hash the contents of the given directory.
Args:
directory (str): The root directory we want to hash.
Returns:
A hash of all the contents in the directory.
"""
import hashlib
sha = hashlib.sha512()
if not os.path.exists(directory):
return -1
for root, _, files in os.walk(directory):
for name in files:
filepath = local.path(root) / name
if filepath.exists():
with open(filepath, 'rb') as next_file:
for line in next_file:
sha.update(line)
return sha.hexdigest() | python | def get_hash_of_dirs(directory):
"""
Recursively hash the contents of the given directory.
Args:
directory (str): The root directory we want to hash.
Returns:
A hash of all the contents in the directory.
"""
import hashlib
sha = hashlib.sha512()
if not os.path.exists(directory):
return -1
for root, _, files in os.walk(directory):
for name in files:
filepath = local.path(root) / name
if filepath.exists():
with open(filepath, 'rb') as next_file:
for line in next_file:
sha.update(line)
return sha.hexdigest() | [
"def",
"get_hash_of_dirs",
"(",
"directory",
")",
":",
"import",
"hashlib",
"sha",
"=",
"hashlib",
".",
"sha512",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"return",
"-",
"1",
"for",
"root",
",",
"_",
",",
... | Recursively hash the contents of the given directory.
Args:
directory (str): The root directory we want to hash.
Returns:
A hash of all the contents in the directory. | [
"Recursively",
"hash",
"the",
"contents",
"of",
"the",
"given",
"directory",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L23-L45 | train | 53,454 |
PolyJIT/benchbuild | benchbuild/utils/download.py | source_required | def source_required(src_file):
"""
Check, if a download is required.
Args:
src_file: The filename to check for.
src_root: The path we find the file in.
Returns:
True, if we need to download something, False otherwise.
"""
if not src_file.exists():
return True
required = True
hash_file = src_file.with_suffix(".hash", depth=0)
LOG.debug("Hash file location: %s", hash_file)
if hash_file.exists():
new_hash = get_hash_of_dirs(src_file)
with open(hash_file, 'r') as h_file:
old_hash = h_file.readline()
required = not new_hash == old_hash
if required:
from benchbuild.utils.cmd import rm
rm("-r", src_file)
rm(hash_file)
if required:
LOG.info("Source required for: %s", src_file)
LOG.debug("Reason: src-exists: %s hash-exists: %s", src_file.exists(),
hash_file.exists())
return required | python | def source_required(src_file):
"""
Check, if a download is required.
Args:
src_file: The filename to check for.
src_root: The path we find the file in.
Returns:
True, if we need to download something, False otherwise.
"""
if not src_file.exists():
return True
required = True
hash_file = src_file.with_suffix(".hash", depth=0)
LOG.debug("Hash file location: %s", hash_file)
if hash_file.exists():
new_hash = get_hash_of_dirs(src_file)
with open(hash_file, 'r') as h_file:
old_hash = h_file.readline()
required = not new_hash == old_hash
if required:
from benchbuild.utils.cmd import rm
rm("-r", src_file)
rm(hash_file)
if required:
LOG.info("Source required for: %s", src_file)
LOG.debug("Reason: src-exists: %s hash-exists: %s", src_file.exists(),
hash_file.exists())
return required | [
"def",
"source_required",
"(",
"src_file",
")",
":",
"if",
"not",
"src_file",
".",
"exists",
"(",
")",
":",
"return",
"True",
"required",
"=",
"True",
"hash_file",
"=",
"src_file",
".",
"with_suffix",
"(",
"\".hash\"",
",",
"depth",
"=",
"0",
")",
"LOG",... | Check, if a download is required.
Args:
src_file: The filename to check for.
src_root: The path we find the file in.
Returns:
True, if we need to download something, False otherwise. | [
"Check",
"if",
"a",
"download",
"is",
"required",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L48-L78 | train | 53,455 |
PolyJIT/benchbuild | benchbuild/utils/download.py | update_hash | def update_hash(src_file):
"""
Update the hash for the given file.
Args:
src: The file name.
root: The path of the given file.
"""
hash_file = local.path(src_file) + ".hash"
new_hash = 0
with open(hash_file, 'w') as h_file:
new_hash = get_hash_of_dirs(src_file)
h_file.write(str(new_hash))
return new_hash | python | def update_hash(src_file):
"""
Update the hash for the given file.
Args:
src: The file name.
root: The path of the given file.
"""
hash_file = local.path(src_file) + ".hash"
new_hash = 0
with open(hash_file, 'w') as h_file:
new_hash = get_hash_of_dirs(src_file)
h_file.write(str(new_hash))
return new_hash | [
"def",
"update_hash",
"(",
"src_file",
")",
":",
"hash_file",
"=",
"local",
".",
"path",
"(",
"src_file",
")",
"+",
"\".hash\"",
"new_hash",
"=",
"0",
"with",
"open",
"(",
"hash_file",
",",
"'w'",
")",
"as",
"h_file",
":",
"new_hash",
"=",
"get_hash_of_d... | Update the hash for the given file.
Args:
src: The file name.
root: The path of the given file. | [
"Update",
"the",
"hash",
"for",
"the",
"given",
"file",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L81-L94 | train | 53,456 |
PolyJIT/benchbuild | benchbuild/utils/download.py | Copy | def Copy(From, To):
"""
Small copy wrapper.
Args:
From (str): Path to the SOURCE.
To (str): Path to the TARGET.
"""
from benchbuild.utils.cmd import cp
cp("-ar", "--reflink=auto", From, To) | python | def Copy(From, To):
"""
Small copy wrapper.
Args:
From (str): Path to the SOURCE.
To (str): Path to the TARGET.
"""
from benchbuild.utils.cmd import cp
cp("-ar", "--reflink=auto", From, To) | [
"def",
"Copy",
"(",
"From",
",",
"To",
")",
":",
"from",
"benchbuild",
".",
"utils",
".",
"cmd",
"import",
"cp",
"cp",
"(",
"\"-ar\"",
",",
"\"--reflink=auto\"",
",",
"From",
",",
"To",
")"
] | Small copy wrapper.
Args:
From (str): Path to the SOURCE.
To (str): Path to the TARGET. | [
"Small",
"copy",
"wrapper",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L97-L106 | train | 53,457 |
PolyJIT/benchbuild | benchbuild/utils/download.py | CopyNoFail | def CopyNoFail(src, root=None):
"""
Just copy fName into the current working directory, if it exists.
No action is executed, if fName does not exist. No Hash is checked.
Args:
src: The filename we want to copy to '.'.
root: The optional source dir we should pull fName from. Defaults
to benchbuild.settings.CFG["tmpdir"].
Returns:
True, if we copied something.
"""
if root is None:
root = str(CFG["tmp_dir"])
src_path = local.path(root) / src
if src_path.exists():
Copy(src_path, '.')
return True
return False | python | def CopyNoFail(src, root=None):
"""
Just copy fName into the current working directory, if it exists.
No action is executed, if fName does not exist. No Hash is checked.
Args:
src: The filename we want to copy to '.'.
root: The optional source dir we should pull fName from. Defaults
to benchbuild.settings.CFG["tmpdir"].
Returns:
True, if we copied something.
"""
if root is None:
root = str(CFG["tmp_dir"])
src_path = local.path(root) / src
if src_path.exists():
Copy(src_path, '.')
return True
return False | [
"def",
"CopyNoFail",
"(",
"src",
",",
"root",
"=",
"None",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"str",
"(",
"CFG",
"[",
"\"tmp_dir\"",
"]",
")",
"src_path",
"=",
"local",
".",
"path",
"(",
"root",
")",
"/",
"src",
"if",
"src_pa... | Just copy fName into the current working directory, if it exists.
No action is executed, if fName does not exist. No Hash is checked.
Args:
src: The filename we want to copy to '.'.
root: The optional source dir we should pull fName from. Defaults
to benchbuild.settings.CFG["tmpdir"].
Returns:
True, if we copied something. | [
"Just",
"copy",
"fName",
"into",
"the",
"current",
"working",
"directory",
"if",
"it",
"exists",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L109-L130 | train | 53,458 |
PolyJIT/benchbuild | benchbuild/utils/download.py | Wget | def Wget(src_url, tgt_name, tgt_root=None):
"""
Download url, if required.
Args:
src_url (str): Our SOURCE url.
tgt_name (str): The filename we want to have on disk.
tgt_root (str): The TARGET directory for the download.
Defaults to ``CFG["tmpdir"]``.
"""
if tgt_root is None:
tgt_root = str(CFG["tmp_dir"])
from benchbuild.utils.cmd import wget
tgt_file = local.path(tgt_root) / tgt_name
if not source_required(tgt_file):
Copy(tgt_file, ".")
return
wget(src_url, "-O", tgt_file)
update_hash(tgt_file)
Copy(tgt_file, ".") | python | def Wget(src_url, tgt_name, tgt_root=None):
"""
Download url, if required.
Args:
src_url (str): Our SOURCE url.
tgt_name (str): The filename we want to have on disk.
tgt_root (str): The TARGET directory for the download.
Defaults to ``CFG["tmpdir"]``.
"""
if tgt_root is None:
tgt_root = str(CFG["tmp_dir"])
from benchbuild.utils.cmd import wget
tgt_file = local.path(tgt_root) / tgt_name
if not source_required(tgt_file):
Copy(tgt_file, ".")
return
wget(src_url, "-O", tgt_file)
update_hash(tgt_file)
Copy(tgt_file, ".") | [
"def",
"Wget",
"(",
"src_url",
",",
"tgt_name",
",",
"tgt_root",
"=",
"None",
")",
":",
"if",
"tgt_root",
"is",
"None",
":",
"tgt_root",
"=",
"str",
"(",
"CFG",
"[",
"\"tmp_dir\"",
"]",
")",
"from",
"benchbuild",
".",
"utils",
".",
"cmd",
"import",
"... | Download url, if required.
Args:
src_url (str): Our SOURCE url.
tgt_name (str): The filename we want to have on disk.
tgt_root (str): The TARGET directory for the download.
Defaults to ``CFG["tmpdir"]``. | [
"Download",
"url",
"if",
"required",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L133-L155 | train | 53,459 |
PolyJIT/benchbuild | benchbuild/utils/download.py | with_wget | def with_wget(url_dict=None, target_file=None):
"""
Decorate a project class with wget-based version information.
This adds two attributes to a project class:
- A `versions` method that returns a list of available versions
for this project.
- A `repository` attribute that provides a repository string to
download from later.
We use the `git rev-list` subcommand to list available versions.
Args:
url_dict (dict): A dictionary that assigns a version to a download URL.
target_file (str): An optional path where we should put the clone.
If unspecified, we will use the `SRC_FILE` attribute of
the decorated class.
"""
def wget_decorator(cls):
def download_impl(self):
"""Download the selected version from the url_dict value."""
t_file = target_file if target_file else self.SRC_FILE
t_version = url_dict[self.version]
Wget(t_version, t_file)
@staticmethod
def versions_impl():
"""Return a list of versions from the url_dict keys."""
return list(url_dict.keys())
cls.versions = versions_impl
cls.download = download_impl
return cls
return wget_decorator | python | def with_wget(url_dict=None, target_file=None):
"""
Decorate a project class with wget-based version information.
This adds two attributes to a project class:
- A `versions` method that returns a list of available versions
for this project.
- A `repository` attribute that provides a repository string to
download from later.
We use the `git rev-list` subcommand to list available versions.
Args:
url_dict (dict): A dictionary that assigns a version to a download URL.
target_file (str): An optional path where we should put the clone.
If unspecified, we will use the `SRC_FILE` attribute of
the decorated class.
"""
def wget_decorator(cls):
def download_impl(self):
"""Download the selected version from the url_dict value."""
t_file = target_file if target_file else self.SRC_FILE
t_version = url_dict[self.version]
Wget(t_version, t_file)
@staticmethod
def versions_impl():
"""Return a list of versions from the url_dict keys."""
return list(url_dict.keys())
cls.versions = versions_impl
cls.download = download_impl
return cls
return wget_decorator | [
"def",
"with_wget",
"(",
"url_dict",
"=",
"None",
",",
"target_file",
"=",
"None",
")",
":",
"def",
"wget_decorator",
"(",
"cls",
")",
":",
"def",
"download_impl",
"(",
"self",
")",
":",
"\"\"\"Download the selected version from the url_dict value.\"\"\"",
"t_file",... | Decorate a project class with wget-based version information.
This adds two attributes to a project class:
- A `versions` method that returns a list of available versions
for this project.
- A `repository` attribute that provides a repository string to
download from later.
We use the `git rev-list` subcommand to list available versions.
Args:
url_dict (dict): A dictionary that assigns a version to a download URL.
target_file (str): An optional path where we should put the clone.
If unspecified, we will use the `SRC_FILE` attribute of
the decorated class. | [
"Decorate",
"a",
"project",
"class",
"with",
"wget",
"-",
"based",
"version",
"information",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L158-L192 | train | 53,460 |
PolyJIT/benchbuild | benchbuild/utils/download.py | Git | def Git(repository, directory, rev=None, prefix=None, shallow_clone=True):
"""
Get a clone of the given repo
Args:
repository (str): Git URL of the SOURCE repo.
directory (str): Name of the repo folder on disk.
tgt_root (str): TARGET folder for the git repo.
Defaults to ``CFG["tmpdir"]``
shallow_clone (bool): Only clone the repository shallow
Defaults to true
"""
repository_loc = str(prefix)
if prefix is None:
repository_loc = str(CFG["tmp_dir"])
from benchbuild.utils.cmd import git
src_dir = local.path(repository_loc) / directory
if not source_required(src_dir):
Copy(src_dir, ".")
return
extra_param = []
if shallow_clone:
extra_param.append("--depth")
extra_param.append("1")
git("clone", extra_param, repository, src_dir)
if rev:
with local.cwd(src_dir):
git("checkout", rev)
update_hash(src_dir)
Copy(src_dir, ".")
return repository_loc | python | def Git(repository, directory, rev=None, prefix=None, shallow_clone=True):
"""
Get a clone of the given repo
Args:
repository (str): Git URL of the SOURCE repo.
directory (str): Name of the repo folder on disk.
tgt_root (str): TARGET folder for the git repo.
Defaults to ``CFG["tmpdir"]``
shallow_clone (bool): Only clone the repository shallow
Defaults to true
"""
repository_loc = str(prefix)
if prefix is None:
repository_loc = str(CFG["tmp_dir"])
from benchbuild.utils.cmd import git
src_dir = local.path(repository_loc) / directory
if not source_required(src_dir):
Copy(src_dir, ".")
return
extra_param = []
if shallow_clone:
extra_param.append("--depth")
extra_param.append("1")
git("clone", extra_param, repository, src_dir)
if rev:
with local.cwd(src_dir):
git("checkout", rev)
update_hash(src_dir)
Copy(src_dir, ".")
return repository_loc | [
"def",
"Git",
"(",
"repository",
",",
"directory",
",",
"rev",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"shallow_clone",
"=",
"True",
")",
":",
"repository_loc",
"=",
"str",
"(",
"prefix",
")",
"if",
"prefix",
"is",
"None",
":",
"repository_loc",
... | Get a clone of the given repo
Args:
repository (str): Git URL of the SOURCE repo.
directory (str): Name of the repo folder on disk.
tgt_root (str): TARGET folder for the git repo.
Defaults to ``CFG["tmpdir"]``
shallow_clone (bool): Only clone the repository shallow
Defaults to true | [
"Get",
"a",
"clone",
"of",
"the",
"given",
"repo"
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L195-L230 | train | 53,461 |
PolyJIT/benchbuild | benchbuild/utils/download.py | with_git | def with_git(repo,
target_dir=None,
limit=None,
refspec="HEAD",
clone=True,
rev_list_args=None,
version_filter=lambda version: True):
"""
Decorate a project class with git-based version information.
This adds two attributes to a project class:
- A `versions` method that returns a list of available versions
for this project.
- A `repository` attribute that provides a repository string to
download from later.
We use the `git rev-list` subcommand to list available versions.
Args:
repo (str): Repository to download from, this will be stored
in the `repository` attribute of the decorated class.
target_dir (str): An optional path where we should put the clone.
If unspecified, we will use the `SRC_FILE` attribute of
the decorated class.
limit (int): Limit the number of commits to consider for available
versions. Versions are 'ordered' from latest to oldest.
refspec (str): A git refspec string to start listing the versions from.
clone (bool): Should we clone the repo if it isn't already available
in our tmp dir? Defaults to `True`. You can set this to False to
avoid time consuming clones, when the project has not been accessed
at least once in your installation.
ref_list_args (list of str): Additional arguments you want to pass to
`git rev-list`.
version_filter (class filter): Filter function to remove unwanted
project versions.
"""
if not rev_list_args:
rev_list_args = []
def git_decorator(cls):
from benchbuild.utils.cmd import git
@staticmethod
def versions_impl():
"""Return a list of versions from the git hashes up to :limit:."""
directory = cls.SRC_FILE if target_dir is None else target_dir
repo_prefix = local.path(str(CFG["tmp_dir"]))
repo_loc = local.path(repo_prefix) / directory
if source_required(repo_loc):
if not clone:
return []
git("clone", repo, repo_loc)
update_hash(repo_loc)
with local.cwd(repo_loc):
rev_list = git("rev-list", "--abbrev-commit", "--abbrev=10",
refspec, *rev_list_args).strip().split('\n')
latest = git("rev-parse", "--short=10",
refspec).strip().split('\n')
cls.VERSION = latest[0]
if limit:
return list(filter(version_filter, rev_list))[:limit]
return list(filter(version_filter, rev_list))
def download_impl(self):
"""Download the selected version."""
nonlocal target_dir, git
directory = cls.SRC_FILE if target_dir is None else target_dir
Git(self.repository, directory)
with local.cwd(directory):
git("checkout", self.version)
cls.versions = versions_impl
cls.download = download_impl
cls.repository = repo
return cls
return git_decorator | python | def with_git(repo,
target_dir=None,
limit=None,
refspec="HEAD",
clone=True,
rev_list_args=None,
version_filter=lambda version: True):
"""
Decorate a project class with git-based version information.
This adds two attributes to a project class:
- A `versions` method that returns a list of available versions
for this project.
- A `repository` attribute that provides a repository string to
download from later.
We use the `git rev-list` subcommand to list available versions.
Args:
repo (str): Repository to download from, this will be stored
in the `repository` attribute of the decorated class.
target_dir (str): An optional path where we should put the clone.
If unspecified, we will use the `SRC_FILE` attribute of
the decorated class.
limit (int): Limit the number of commits to consider for available
versions. Versions are 'ordered' from latest to oldest.
refspec (str): A git refspec string to start listing the versions from.
clone (bool): Should we clone the repo if it isn't already available
in our tmp dir? Defaults to `True`. You can set this to False to
avoid time consuming clones, when the project has not been accessed
at least once in your installation.
ref_list_args (list of str): Additional arguments you want to pass to
`git rev-list`.
version_filter (class filter): Filter function to remove unwanted
project versions.
"""
if not rev_list_args:
rev_list_args = []
def git_decorator(cls):
from benchbuild.utils.cmd import git
@staticmethod
def versions_impl():
"""Return a list of versions from the git hashes up to :limit:."""
directory = cls.SRC_FILE if target_dir is None else target_dir
repo_prefix = local.path(str(CFG["tmp_dir"]))
repo_loc = local.path(repo_prefix) / directory
if source_required(repo_loc):
if not clone:
return []
git("clone", repo, repo_loc)
update_hash(repo_loc)
with local.cwd(repo_loc):
rev_list = git("rev-list", "--abbrev-commit", "--abbrev=10",
refspec, *rev_list_args).strip().split('\n')
latest = git("rev-parse", "--short=10",
refspec).strip().split('\n')
cls.VERSION = latest[0]
if limit:
return list(filter(version_filter, rev_list))[:limit]
return list(filter(version_filter, rev_list))
def download_impl(self):
"""Download the selected version."""
nonlocal target_dir, git
directory = cls.SRC_FILE if target_dir is None else target_dir
Git(self.repository, directory)
with local.cwd(directory):
git("checkout", self.version)
cls.versions = versions_impl
cls.download = download_impl
cls.repository = repo
return cls
return git_decorator | [
"def",
"with_git",
"(",
"repo",
",",
"target_dir",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"refspec",
"=",
"\"HEAD\"",
",",
"clone",
"=",
"True",
",",
"rev_list_args",
"=",
"None",
",",
"version_filter",
"=",
"lambda",
"version",
":",
"True",
")",
... | Decorate a project class with git-based version information.
This adds two attributes to a project class:
- A `versions` method that returns a list of available versions
for this project.
- A `repository` attribute that provides a repository string to
download from later.
We use the `git rev-list` subcommand to list available versions.
Args:
repo (str): Repository to download from, this will be stored
in the `repository` attribute of the decorated class.
target_dir (str): An optional path where we should put the clone.
If unspecified, we will use the `SRC_FILE` attribute of
the decorated class.
limit (int): Limit the number of commits to consider for available
versions. Versions are 'ordered' from latest to oldest.
refspec (str): A git refspec string to start listing the versions from.
clone (bool): Should we clone the repo if it isn't already available
in our tmp dir? Defaults to `True`. You can set this to False to
avoid time consuming clones, when the project has not been accessed
at least once in your installation.
ref_list_args (list of str): Additional arguments you want to pass to
`git rev-list`.
version_filter (class filter): Filter function to remove unwanted
project versions. | [
"Decorate",
"a",
"project",
"class",
"with",
"git",
"-",
"based",
"version",
"information",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L233-L312 | train | 53,462 |
PolyJIT/benchbuild | benchbuild/utils/download.py | Svn | def Svn(url, fname, to=None):
"""
Checkout the SVN repo.
Args:
url (str): The SVN SOURCE repo.
fname (str): The name of the repo on disk.
to (str): The name of the TARGET folder on disk.
Defaults to ``CFG["tmpdir"]``
"""
if to is None:
to = str(CFG["tmp_dir"])
src_dir = local.path(to) / fname
if not source_required(src_dir):
Copy(src_dir, ".")
return
from benchbuild.utils.cmd import svn
svn("co", url, src_dir)
update_hash(src_dir)
Copy(src_dir, ".") | python | def Svn(url, fname, to=None):
"""
Checkout the SVN repo.
Args:
url (str): The SVN SOURCE repo.
fname (str): The name of the repo on disk.
to (str): The name of the TARGET folder on disk.
Defaults to ``CFG["tmpdir"]``
"""
if to is None:
to = str(CFG["tmp_dir"])
src_dir = local.path(to) / fname
if not source_required(src_dir):
Copy(src_dir, ".")
return
from benchbuild.utils.cmd import svn
svn("co", url, src_dir)
update_hash(src_dir)
Copy(src_dir, ".") | [
"def",
"Svn",
"(",
"url",
",",
"fname",
",",
"to",
"=",
"None",
")",
":",
"if",
"to",
"is",
"None",
":",
"to",
"=",
"str",
"(",
"CFG",
"[",
"\"tmp_dir\"",
"]",
")",
"src_dir",
"=",
"local",
".",
"path",
"(",
"to",
")",
"/",
"fname",
"if",
"no... | Checkout the SVN repo.
Args:
url (str): The SVN SOURCE repo.
fname (str): The name of the repo on disk.
to (str): The name of the TARGET folder on disk.
Defaults to ``CFG["tmpdir"]`` | [
"Checkout",
"the",
"SVN",
"repo",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L315-L336 | train | 53,463 |
PolyJIT/benchbuild | benchbuild/utils/download.py | Rsync | def Rsync(url, tgt_name, tgt_root=None):
"""
RSync a folder.
Args:
url (str): The url of the SOURCE location.
fname (str): The name of the TARGET.
to (str): Path of the target location.
Defaults to ``CFG["tmpdir"]``.
"""
if tgt_root is None:
tgt_root = str(CFG["tmp_dir"])
from benchbuild.utils.cmd import rsync
tgt_dir = local.path(tgt_root) / tgt_name
if not source_required(tgt_dir):
Copy(tgt_dir, ".")
return
rsync("-a", url, tgt_dir)
update_hash(tgt_dir)
Copy(tgt_dir, ".") | python | def Rsync(url, tgt_name, tgt_root=None):
"""
RSync a folder.
Args:
url (str): The url of the SOURCE location.
fname (str): The name of the TARGET.
to (str): Path of the target location.
Defaults to ``CFG["tmpdir"]``.
"""
if tgt_root is None:
tgt_root = str(CFG["tmp_dir"])
from benchbuild.utils.cmd import rsync
tgt_dir = local.path(tgt_root) / tgt_name
if not source_required(tgt_dir):
Copy(tgt_dir, ".")
return
rsync("-a", url, tgt_dir)
update_hash(tgt_dir)
Copy(tgt_dir, ".") | [
"def",
"Rsync",
"(",
"url",
",",
"tgt_name",
",",
"tgt_root",
"=",
"None",
")",
":",
"if",
"tgt_root",
"is",
"None",
":",
"tgt_root",
"=",
"str",
"(",
"CFG",
"[",
"\"tmp_dir\"",
"]",
")",
"from",
"benchbuild",
".",
"utils",
".",
"cmd",
"import",
"rsy... | RSync a folder.
Args:
url (str): The url of the SOURCE location.
fname (str): The name of the TARGET.
to (str): Path of the target location.
Defaults to ``CFG["tmpdir"]``. | [
"RSync",
"a",
"folder",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/download.py#L339-L361 | train | 53,464 |
portfoliome/foil | foil/strings.py | camel_to_snake | def camel_to_snake(s: str) -> str:
"""Convert string from camel case to snake case."""
return CAMEL_CASE_RE.sub(r'_\1', s).strip().lower() | python | def camel_to_snake(s: str) -> str:
"""Convert string from camel case to snake case."""
return CAMEL_CASE_RE.sub(r'_\1', s).strip().lower() | [
"def",
"camel_to_snake",
"(",
"s",
":",
"str",
")",
"->",
"str",
":",
"return",
"CAMEL_CASE_RE",
".",
"sub",
"(",
"r'_\\1'",
",",
"s",
")",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")"
] | Convert string from camel case to snake case. | [
"Convert",
"string",
"from",
"camel",
"case",
"to",
"snake",
"case",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/strings.py#L7-L10 | train | 53,465 |
portfoliome/foil | foil/strings.py | snake_to_camel | def snake_to_camel(s: str) -> str:
"""Convert string from snake case to camel case."""
fragments = s.split('_')
return fragments[0] + ''.join(x.title() for x in fragments[1:]) | python | def snake_to_camel(s: str) -> str:
"""Convert string from snake case to camel case."""
fragments = s.split('_')
return fragments[0] + ''.join(x.title() for x in fragments[1:]) | [
"def",
"snake_to_camel",
"(",
"s",
":",
"str",
")",
"->",
"str",
":",
"fragments",
"=",
"s",
".",
"split",
"(",
"'_'",
")",
"return",
"fragments",
"[",
"0",
"]",
"+",
"''",
".",
"join",
"(",
"x",
".",
"title",
"(",
")",
"for",
"x",
"in",
"fragm... | Convert string from snake case to camel case. | [
"Convert",
"string",
"from",
"snake",
"case",
"to",
"camel",
"case",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/strings.py#L13-L18 | train | 53,466 |
BlueBrain/hpcbench | hpcbench/benchmark/standard.py | Configuration._create_extractors | def _create_extractors(cls, metrics):
"""Build metrics extractors according to the `metrics` config
:param metrics: Benchmark `metrics` configuration section
"""
metrics_dict = {}
# group entries by `category` attribute (default is "standard")
for metric, config in six.iteritems(metrics):
category = config.get('category', StdBenchmark.DEFAULT_CATEGORY)
metrics_dict.setdefault(category, {})[metric] = config
# create one StdExtractor instance per category,
# passing associated metrics
return dict(
(category, StdExtractor(metrics))
for category, metrics in six.iteritems(metrics_dict)
) | python | def _create_extractors(cls, metrics):
"""Build metrics extractors according to the `metrics` config
:param metrics: Benchmark `metrics` configuration section
"""
metrics_dict = {}
# group entries by `category` attribute (default is "standard")
for metric, config in six.iteritems(metrics):
category = config.get('category', StdBenchmark.DEFAULT_CATEGORY)
metrics_dict.setdefault(category, {})[metric] = config
# create one StdExtractor instance per category,
# passing associated metrics
return dict(
(category, StdExtractor(metrics))
for category, metrics in six.iteritems(metrics_dict)
) | [
"def",
"_create_extractors",
"(",
"cls",
",",
"metrics",
")",
":",
"metrics_dict",
"=",
"{",
"}",
"# group entries by `category` attribute (default is \"standard\")",
"for",
"metric",
",",
"config",
"in",
"six",
".",
"iteritems",
"(",
"metrics",
")",
":",
"category"... | Build metrics extractors according to the `metrics` config
:param metrics: Benchmark `metrics` configuration section | [
"Build",
"metrics",
"extractors",
"according",
"to",
"the",
"metrics",
"config"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/standard.py#L160-L175 | train | 53,467 |
BlueBrain/hpcbench | hpcbench/benchmark/standard.py | StdExtractor.froms | def froms(self):
"""Group metrics according to the `from` property.
"""
eax = {}
for name, config in six.iteritems(self._metrics):
from_ = self._get_property(config, 'from', default=self.stdout)
eax.setdefault(from_, {})[name] = config
return eax | python | def froms(self):
"""Group metrics according to the `from` property.
"""
eax = {}
for name, config in six.iteritems(self._metrics):
from_ = self._get_property(config, 'from', default=self.stdout)
eax.setdefault(from_, {})[name] = config
return eax | [
"def",
"froms",
"(",
"self",
")",
":",
"eax",
"=",
"{",
"}",
"for",
"name",
",",
"config",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_metrics",
")",
":",
"from_",
"=",
"self",
".",
"_get_property",
"(",
"config",
",",
"'from'",
",",
"defaul... | Group metrics according to the `from` property. | [
"Group",
"metrics",
"according",
"to",
"the",
"from",
"property",
"."
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/standard.py#L296-L303 | train | 53,468 |
sci-bots/svg-model | svg_model/tesselate.py | tesselate_shapes_frame | def tesselate_shapes_frame(df_shapes, shape_i_columns):
'''
Tesselate each shape path into one or more triangles.
Parameters
----------
df_shapes : pandas.DataFrame
Table containing vertices of shapes, one row per vertex, with the *at
least* the following columns:
- ``x``: The x-coordinate of the vertex.
- ``y``: The y-coordinate of the vertex.
shape_i_columns : str or list
Column(s) forming key to differentiate rows/vertices for each distinct
shape.
Returns
-------
pandas.DataFrame
Table where each row corresponds to a triangle vertex, with the following
columns:
- ``shape_i_columns[]``: The shape path index column(s).
- ``triangle_i``: The integer triangle index within each electrode path.
- ``vertex_i``: The integer vertex index within each triangle.
'''
frames = []
if isinstance(shape_i_columns, bytes):
shape_i_columns = [shape_i_columns]
for shape_i, df_path in df_shapes.groupby(shape_i_columns):
points_i = df_path[['x', 'y']].values
if (points_i[0] == points_i[-1]).all():
# XXX End point is the same as the start point (do not include it).
points_i = points_i[:-1]
try:
triangulator = Triangulator(points_i)
except:
import pdb; pdb.set_trace()
continue
if not isinstance(shape_i, (list, tuple)):
shape_i = [shape_i]
for i, triangle_i in enumerate(triangulator.triangles()):
triangle_points_i = [shape_i + [i] + [j, x, y]
for j, (x, y) in enumerate(triangle_i)]
frames.extend(triangle_points_i)
frames = None if not frames else frames
return pd.DataFrame(frames, columns=shape_i_columns +
['triangle_i', 'vertex_i', 'x', 'y']) | python | def tesselate_shapes_frame(df_shapes, shape_i_columns):
'''
Tesselate each shape path into one or more triangles.
Parameters
----------
df_shapes : pandas.DataFrame
Table containing vertices of shapes, one row per vertex, with the *at
least* the following columns:
- ``x``: The x-coordinate of the vertex.
- ``y``: The y-coordinate of the vertex.
shape_i_columns : str or list
Column(s) forming key to differentiate rows/vertices for each distinct
shape.
Returns
-------
pandas.DataFrame
Table where each row corresponds to a triangle vertex, with the following
columns:
- ``shape_i_columns[]``: The shape path index column(s).
- ``triangle_i``: The integer triangle index within each electrode path.
- ``vertex_i``: The integer vertex index within each triangle.
'''
frames = []
if isinstance(shape_i_columns, bytes):
shape_i_columns = [shape_i_columns]
for shape_i, df_path in df_shapes.groupby(shape_i_columns):
points_i = df_path[['x', 'y']].values
if (points_i[0] == points_i[-1]).all():
# XXX End point is the same as the start point (do not include it).
points_i = points_i[:-1]
try:
triangulator = Triangulator(points_i)
except:
import pdb; pdb.set_trace()
continue
if not isinstance(shape_i, (list, tuple)):
shape_i = [shape_i]
for i, triangle_i in enumerate(triangulator.triangles()):
triangle_points_i = [shape_i + [i] + [j, x, y]
for j, (x, y) in enumerate(triangle_i)]
frames.extend(triangle_points_i)
frames = None if not frames else frames
return pd.DataFrame(frames, columns=shape_i_columns +
['triangle_i', 'vertex_i', 'x', 'y']) | [
"def",
"tesselate_shapes_frame",
"(",
"df_shapes",
",",
"shape_i_columns",
")",
":",
"frames",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"shape_i_columns",
",",
"bytes",
")",
":",
"shape_i_columns",
"=",
"[",
"shape_i_columns",
"]",
"for",
"shape_i",
",",
"df_pa... | Tesselate each shape path into one or more triangles.
Parameters
----------
df_shapes : pandas.DataFrame
Table containing vertices of shapes, one row per vertex, with the *at
least* the following columns:
- ``x``: The x-coordinate of the vertex.
- ``y``: The y-coordinate of the vertex.
shape_i_columns : str or list
Column(s) forming key to differentiate rows/vertices for each distinct
shape.
Returns
-------
pandas.DataFrame
Table where each row corresponds to a triangle vertex, with the following
columns:
- ``shape_i_columns[]``: The shape path index column(s).
- ``triangle_i``: The integer triangle index within each electrode path.
- ``vertex_i``: The integer vertex index within each triangle. | [
"Tesselate",
"each",
"shape",
"path",
"into",
"one",
"or",
"more",
"triangles",
"."
] | 2d119650f995e62b29ce0b3151a23f3b957cb072 | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/tesselate.py#L10-L59 | train | 53,469 |
BlueBrain/hpcbench | hpcbench/toolbox/contextlib_ext.py | mkdtemp | def mkdtemp(*args, **kwargs):
"""Create a temporary directory in a with-context
keyword remove: Remove the directory when leaving the
context if True. Default is True.
other keywords arguments are given to the tempfile.mkdtemp
function.
"""
remove = kwargs.pop('remove', True)
path = tempfile.mkdtemp(*args, **kwargs)
try:
yield path
finally:
if remove:
shutil.rmtree(path) | python | def mkdtemp(*args, **kwargs):
"""Create a temporary directory in a with-context
keyword remove: Remove the directory when leaving the
context if True. Default is True.
other keywords arguments are given to the tempfile.mkdtemp
function.
"""
remove = kwargs.pop('remove', True)
path = tempfile.mkdtemp(*args, **kwargs)
try:
yield path
finally:
if remove:
shutil.rmtree(path) | [
"def",
"mkdtemp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"remove",
"=",
"kwargs",
".",
"pop",
"(",
"'remove'",
",",
"True",
")",
"path",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
... | Create a temporary directory in a with-context
keyword remove: Remove the directory when leaving the
context if True. Default is True.
other keywords arguments are given to the tempfile.mkdtemp
function. | [
"Create",
"a",
"temporary",
"directory",
"in",
"a",
"with",
"-",
"context"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/contextlib_ext.py#L91-L105 | train | 53,470 |
Metatab/metatab | metatab/util.py | slugify | def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.type(
"""
import re
import unicodedata
value = str(value)
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('utf8').strip().lower()
value = re.sub(r'[^\w\s\-\.]', '', value)
value = re.sub(r'[-\s]+', '-', value)
return value | python | def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.type(
"""
import re
import unicodedata
value = str(value)
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('utf8').strip().lower()
value = re.sub(r'[^\w\s\-\.]', '', value)
value = re.sub(r'[-\s]+', '-', value)
return value | [
"def",
"slugify",
"(",
"value",
")",
":",
"import",
"re",
"import",
"unicodedata",
"value",
"=",
"str",
"(",
"value",
")",
"value",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKD'",
",",
"value",
")",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
... | Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.type( | [
"Normalizes",
"string",
"converts",
"to",
"lowercase",
"removes",
"non",
"-",
"alpha",
"characters",
"and",
"converts",
"spaces",
"to",
"hyphens",
".",
"type",
"("
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/util.py#L40-L51 | train | 53,471 |
Metatab/metatab | metatab/util.py | import_name_or_class | def import_name_or_class(name):
" Import an obect as either a fully qualified, dotted name, "
if isinstance(name, str):
# for "a.b.c.d" -> [ 'a.b.c', 'd' ]
module_name, object_name = name.rsplit('.',1)
# __import__ loads the multi-level of module, but returns
# the top level, which we have to descend into
mod = __import__(module_name)
components = name.split('.')
for comp in components[1:]: # Already got the top level, so start at 1
mod = getattr(mod, comp)
return mod
else:
return name | python | def import_name_or_class(name):
" Import an obect as either a fully qualified, dotted name, "
if isinstance(name, str):
# for "a.b.c.d" -> [ 'a.b.c', 'd' ]
module_name, object_name = name.rsplit('.',1)
# __import__ loads the multi-level of module, but returns
# the top level, which we have to descend into
mod = __import__(module_name)
components = name.split('.')
for comp in components[1:]: # Already got the top level, so start at 1
mod = getattr(mod, comp)
return mod
else:
return name | [
"def",
"import_name_or_class",
"(",
"name",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"# for \"a.b.c.d\" -> [ 'a.b.c', 'd' ]",
"module_name",
",",
"object_name",
"=",
"name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"# __import__ loads th... | Import an obect as either a fully qualified, dotted name, | [
"Import",
"an",
"obect",
"as",
"either",
"a",
"fully",
"qualified",
"dotted",
"name"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/util.py#L208-L226 | train | 53,472 |
BlueBrain/hpcbench | hpcbench/campaign.py | pip_installer_url | def pip_installer_url(version=None):
"""Get argument to give to ``pip`` to install HPCBench.
"""
version = version or hpcbench.__version__
version = str(version)
if '.dev' in version:
git_rev = 'master'
if 'TRAVIS_BRANCH' in os.environ:
git_rev = version.split('+', 1)[-1]
if '.' in git_rev: # get rid of date suffix
git_rev = git_rev.split('.', 1)[0]
git_rev = git_rev[1:] # get rid of scm letter
return 'git+{project_url}@{git_rev}#egg=hpcbench'.format(
project_url='http://github.com/BlueBrain/hpcbench',
git_rev=git_rev or 'master',
)
return 'hpcbench=={}'.format(version) | python | def pip_installer_url(version=None):
"""Get argument to give to ``pip`` to install HPCBench.
"""
version = version or hpcbench.__version__
version = str(version)
if '.dev' in version:
git_rev = 'master'
if 'TRAVIS_BRANCH' in os.environ:
git_rev = version.split('+', 1)[-1]
if '.' in git_rev: # get rid of date suffix
git_rev = git_rev.split('.', 1)[0]
git_rev = git_rev[1:] # get rid of scm letter
return 'git+{project_url}@{git_rev}#egg=hpcbench'.format(
project_url='http://github.com/BlueBrain/hpcbench',
git_rev=git_rev or 'master',
)
return 'hpcbench=={}'.format(version) | [
"def",
"pip_installer_url",
"(",
"version",
"=",
"None",
")",
":",
"version",
"=",
"version",
"or",
"hpcbench",
".",
"__version__",
"version",
"=",
"str",
"(",
"version",
")",
"if",
"'.dev'",
"in",
"version",
":",
"git_rev",
"=",
"'master'",
"if",
"'TRAVIS... | Get argument to give to ``pip`` to install HPCBench. | [
"Get",
"argument",
"to",
"give",
"to",
"pip",
"to",
"install",
"HPCBench",
"."
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L31-L47 | train | 53,473 |
BlueBrain/hpcbench | hpcbench/campaign.py | from_file | def from_file(campaign_file, **kwargs):
"""Load campaign from YAML file
:return: memory representation of the YAML file
:rtype: dictionary
"""
realpath = osp.realpath(campaign_file)
if osp.isdir(realpath):
campaign_file = osp.join(campaign_file, YAML_CAMPAIGN_FILE)
campaign = Configuration.from_file(campaign_file)
return default_campaign(campaign, **kwargs) | python | def from_file(campaign_file, **kwargs):
"""Load campaign from YAML file
:return: memory representation of the YAML file
:rtype: dictionary
"""
realpath = osp.realpath(campaign_file)
if osp.isdir(realpath):
campaign_file = osp.join(campaign_file, YAML_CAMPAIGN_FILE)
campaign = Configuration.from_file(campaign_file)
return default_campaign(campaign, **kwargs) | [
"def",
"from_file",
"(",
"campaign_file",
",",
"*",
"*",
"kwargs",
")",
":",
"realpath",
"=",
"osp",
".",
"realpath",
"(",
"campaign_file",
")",
"if",
"osp",
".",
"isdir",
"(",
"realpath",
")",
":",
"campaign_file",
"=",
"osp",
".",
"join",
"(",
"campa... | Load campaign from YAML file
:return: memory representation of the YAML file
:rtype: dictionary | [
"Load",
"campaign",
"from",
"YAML",
"file"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L165-L175 | train | 53,474 |
BlueBrain/hpcbench | hpcbench/campaign.py | default_campaign | def default_campaign(
campaign=None, expandcampvars=True, exclude_nodes=None, frozen=True
):
"""Fill an existing campaign with default
values for optional keys
:param campaign: dictionary
:type campaign: str
:param exclude_nodes: node set to exclude from allocations
:type exclude_nodes: str
:param expandcampvars: should env variables be expanded? True by default
:type expandcampvars: bool
:param frozen: whether the returned data-structure is immutable or not
:type frozen: bool
:return: object provided in parameter
:rtype: dictionary
"""
campaign = campaign or nameddict()
def _merger(_camp, _deft):
for key in _deft.keys():
if (
key in _camp
and isinstance(_camp[key], dict)
and isinstance(_deft[key], collections.Mapping)
):
_merger(_camp[key], _deft[key])
elif key not in _camp:
_camp[key] = _deft[key]
_merger(campaign, DEFAULT_CAMPAIGN)
campaign.setdefault('campaign_id', str(uuid.uuid4()))
for precondition in campaign.precondition.keys():
config = campaign.precondition[precondition]
if not isinstance(config, list):
campaign.precondition[precondition] = [config]
def _expandvars(value):
if isinstance(value, six.string_types):
return expandvars(value)
return value
if expandcampvars:
campaign = nameddict(dict_map_kv(campaign, _expandvars))
else:
campaign = nameddict(campaign)
if expandcampvars:
if campaign.network.get('tags') is None:
campaign.network['tags'] = {}
NetworkConfig(campaign).expand()
return freeze(campaign) if frozen else campaign | python | def default_campaign(
campaign=None, expandcampvars=True, exclude_nodes=None, frozen=True
):
"""Fill an existing campaign with default
values for optional keys
:param campaign: dictionary
:type campaign: str
:param exclude_nodes: node set to exclude from allocations
:type exclude_nodes: str
:param expandcampvars: should env variables be expanded? True by default
:type expandcampvars: bool
:param frozen: whether the returned data-structure is immutable or not
:type frozen: bool
:return: object provided in parameter
:rtype: dictionary
"""
campaign = campaign or nameddict()
def _merger(_camp, _deft):
for key in _deft.keys():
if (
key in _camp
and isinstance(_camp[key], dict)
and isinstance(_deft[key], collections.Mapping)
):
_merger(_camp[key], _deft[key])
elif key not in _camp:
_camp[key] = _deft[key]
_merger(campaign, DEFAULT_CAMPAIGN)
campaign.setdefault('campaign_id', str(uuid.uuid4()))
for precondition in campaign.precondition.keys():
config = campaign.precondition[precondition]
if not isinstance(config, list):
campaign.precondition[precondition] = [config]
def _expandvars(value):
if isinstance(value, six.string_types):
return expandvars(value)
return value
if expandcampvars:
campaign = nameddict(dict_map_kv(campaign, _expandvars))
else:
campaign = nameddict(campaign)
if expandcampvars:
if campaign.network.get('tags') is None:
campaign.network['tags'] = {}
NetworkConfig(campaign).expand()
return freeze(campaign) if frozen else campaign | [
"def",
"default_campaign",
"(",
"campaign",
"=",
"None",
",",
"expandcampvars",
"=",
"True",
",",
"exclude_nodes",
"=",
"None",
",",
"frozen",
"=",
"True",
")",
":",
"campaign",
"=",
"campaign",
"or",
"nameddict",
"(",
")",
"def",
"_merger",
"(",
"_camp",
... | Fill an existing campaign with default
values for optional keys
:param campaign: dictionary
:type campaign: str
:param exclude_nodes: node set to exclude from allocations
:type exclude_nodes: str
:param expandcampvars: should env variables be expanded? True by default
:type expandcampvars: bool
:param frozen: whether the returned data-structure is immutable or not
:type frozen: bool
:return: object provided in parameter
:rtype: dictionary | [
"Fill",
"an",
"existing",
"campaign",
"with",
"default",
"values",
"for",
"optional",
"keys"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L178-L229 | train | 53,475 |
BlueBrain/hpcbench | hpcbench/campaign.py | get_benchmark_types | def get_benchmark_types(campaign):
"""Get of benchmarks referenced in the configuration
:return: benchmarks
:rtype: string generator
"""
for benchmarks in campaign.benchmarks.values():
for name, benchmark in benchmarks.items():
if name != 'sbatch': # exclude special sbatch name
yield benchmark.type | python | def get_benchmark_types(campaign):
"""Get of benchmarks referenced in the configuration
:return: benchmarks
:rtype: string generator
"""
for benchmarks in campaign.benchmarks.values():
for name, benchmark in benchmarks.items():
if name != 'sbatch': # exclude special sbatch name
yield benchmark.type | [
"def",
"get_benchmark_types",
"(",
"campaign",
")",
":",
"for",
"benchmarks",
"in",
"campaign",
".",
"benchmarks",
".",
"values",
"(",
")",
":",
"for",
"name",
",",
"benchmark",
"in",
"benchmarks",
".",
"items",
"(",
")",
":",
"if",
"name",
"!=",
"'sbatc... | Get of benchmarks referenced in the configuration
:return: benchmarks
:rtype: string generator | [
"Get",
"of",
"benchmarks",
"referenced",
"in",
"the",
"configuration"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L409-L418 | train | 53,476 |
BlueBrain/hpcbench | hpcbench/campaign.py | get_metrics | def get_metrics(campaign, report, top=True):
"""Extract metrics from existing campaign
:param campaign: campaign loaded with `hpcbench.campaign.from_file`
:param report: instance of `hpcbench.campaign.ReportNode`
:param top: this function is recursive. This parameter
help distinguishing top-call.
"""
if top and campaign.process.type == 'slurm':
for path, _ in report.collect('jobid', with_path=True):
for child in ReportNode(path).children.values():
for metrics in get_metrics(campaign, child, top=False):
yield metrics
else:
def metrics_node_extract(report):
metrics_file = osp.join(report.path, JSON_METRICS_FILE)
if osp.exists(metrics_file):
with open(metrics_file) as istr:
return json.load(istr)
def metrics_iterator(report):
return filter(
lambda eax: eax[1] is not None,
report.map(metrics_node_extract, with_path=True),
)
for path, metrics in metrics_iterator(report):
yield report.path_context(path), metrics | python | def get_metrics(campaign, report, top=True):
"""Extract metrics from existing campaign
:param campaign: campaign loaded with `hpcbench.campaign.from_file`
:param report: instance of `hpcbench.campaign.ReportNode`
:param top: this function is recursive. This parameter
help distinguishing top-call.
"""
if top and campaign.process.type == 'slurm':
for path, _ in report.collect('jobid', with_path=True):
for child in ReportNode(path).children.values():
for metrics in get_metrics(campaign, child, top=False):
yield metrics
else:
def metrics_node_extract(report):
metrics_file = osp.join(report.path, JSON_METRICS_FILE)
if osp.exists(metrics_file):
with open(metrics_file) as istr:
return json.load(istr)
def metrics_iterator(report):
return filter(
lambda eax: eax[1] is not None,
report.map(metrics_node_extract, with_path=True),
)
for path, metrics in metrics_iterator(report):
yield report.path_context(path), metrics | [
"def",
"get_metrics",
"(",
"campaign",
",",
"report",
",",
"top",
"=",
"True",
")",
":",
"if",
"top",
"and",
"campaign",
".",
"process",
".",
"type",
"==",
"'slurm'",
":",
"for",
"path",
",",
"_",
"in",
"report",
".",
"collect",
"(",
"'jobid'",
",",
... | Extract metrics from existing campaign
:param campaign: campaign loaded with `hpcbench.campaign.from_file`
:param report: instance of `hpcbench.campaign.ReportNode`
:param top: this function is recursive. This parameter
help distinguishing top-call. | [
"Extract",
"metrics",
"from",
"existing",
"campaign"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L421-L449 | train | 53,477 |
BlueBrain/hpcbench | hpcbench/campaign.py | Generator.write | def write(self, file):
"""Write YAML campaign template to the given open file
"""
render(
self.template,
file,
benchmarks=self.benchmarks,
hostname=socket.gethostname(),
) | python | def write(self, file):
"""Write YAML campaign template to the given open file
"""
render(
self.template,
file,
benchmarks=self.benchmarks,
hostname=socket.gethostname(),
) | [
"def",
"write",
"(",
"self",
",",
"file",
")",
":",
"render",
"(",
"self",
".",
"template",
",",
"file",
",",
"benchmarks",
"=",
"self",
".",
"benchmarks",
",",
"hostname",
"=",
"socket",
".",
"gethostname",
"(",
")",
",",
")"
] | Write YAML campaign template to the given open file | [
"Write",
"YAML",
"campaign",
"template",
"to",
"the",
"given",
"open",
"file"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L104-L112 | train | 53,478 |
BlueBrain/hpcbench | hpcbench/campaign.py | NetworkConfig.expand | def expand(self):
"""Perform node expansion of network section.
"""
if self.slurm:
self._introspect_slurm_cluster()
self.network.nodes = self._expand_nodes(self.network.nodes)
self._expand_tags() | python | def expand(self):
"""Perform node expansion of network section.
"""
if self.slurm:
self._introspect_slurm_cluster()
self.network.nodes = self._expand_nodes(self.network.nodes)
self._expand_tags() | [
"def",
"expand",
"(",
"self",
")",
":",
"if",
"self",
".",
"slurm",
":",
"self",
".",
"_introspect_slurm_cluster",
"(",
")",
"self",
".",
"network",
".",
"nodes",
"=",
"self",
".",
"_expand_nodes",
"(",
"self",
".",
"network",
".",
"nodes",
")",
"self"... | Perform node expansion of network section. | [
"Perform",
"node",
"expansion",
"of",
"network",
"section",
"."
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L254-L260 | train | 53,479 |
BlueBrain/hpcbench | hpcbench/campaign.py | CampaignMerge.ensure_has_same_campaigns | def ensure_has_same_campaigns(self):
"""Ensure that the 2 campaigns to merge have been generated
from the same campaign.yaml
"""
lhs_yaml = osp.join(self.lhs, 'campaign.yaml')
rhs_yaml = osp.join(self.rhs, 'campaign.yaml')
assert osp.isfile(lhs_yaml)
assert osp.isfile(rhs_yaml)
assert filecmp.cmp(lhs_yaml, rhs_yaml) | python | def ensure_has_same_campaigns(self):
"""Ensure that the 2 campaigns to merge have been generated
from the same campaign.yaml
"""
lhs_yaml = osp.join(self.lhs, 'campaign.yaml')
rhs_yaml = osp.join(self.rhs, 'campaign.yaml')
assert osp.isfile(lhs_yaml)
assert osp.isfile(rhs_yaml)
assert filecmp.cmp(lhs_yaml, rhs_yaml) | [
"def",
"ensure_has_same_campaigns",
"(",
"self",
")",
":",
"lhs_yaml",
"=",
"osp",
".",
"join",
"(",
"self",
".",
"lhs",
",",
"'campaign.yaml'",
")",
"rhs_yaml",
"=",
"osp",
".",
"join",
"(",
"self",
".",
"rhs",
",",
"'campaign.yaml'",
")",
"assert",
"os... | Ensure that the 2 campaigns to merge have been generated
from the same campaign.yaml | [
"Ensure",
"that",
"the",
"2",
"campaigns",
"to",
"merge",
"have",
"been",
"generated",
"from",
"the",
"same",
"campaign",
".",
"yaml"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L531-L539 | train | 53,480 |
BlueBrain/hpcbench | hpcbench/campaign.py | ReportNode.path_context | def path_context(self, path):
"""Build of dictionary of fields extracted from
the given path"""
prefix = os.path.commonprefix([path, self._path])
relative_path = path[len(prefix) :]
relative_path = relative_path.strip(os.sep)
attrs = self.CONTEXT_ATTRS
for i, elt in enumerate(relative_path.split(os.sep)):
yield attrs[i], elt
yield 'path', path | python | def path_context(self, path):
"""Build of dictionary of fields extracted from
the given path"""
prefix = os.path.commonprefix([path, self._path])
relative_path = path[len(prefix) :]
relative_path = relative_path.strip(os.sep)
attrs = self.CONTEXT_ATTRS
for i, elt in enumerate(relative_path.split(os.sep)):
yield attrs[i], elt
yield 'path', path | [
"def",
"path_context",
"(",
"self",
",",
"path",
")",
":",
"prefix",
"=",
"os",
".",
"path",
".",
"commonprefix",
"(",
"[",
"path",
",",
"self",
".",
"_path",
"]",
")",
"relative_path",
"=",
"path",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"relati... | Build of dictionary of fields extracted from
the given path | [
"Build",
"of",
"dictionary",
"of",
"fields",
"extracted",
"from",
"the",
"given",
"path"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L603-L612 | train | 53,481 |
BlueBrain/hpcbench | hpcbench/campaign.py | ReportNode.collect | def collect(self, *keys, **kwargs):
"""Generator function traversing
tree structure to collect values of a specified key.
:param keys: the keys to look for in the report
:type key: str
:keyword recursive: look for key in children nodes
:type recursive: bool
:keyword with_path: whether the yield values is a tuple
of 2 elements containing report-path and the value
or simply the value.
:type with_path: bool
:rtype: generator providing either values or
tuples of 2 elements containing report path and value
depending on with_path parameter
"""
if not keys:
raise Exception('Missing key')
has_values = functools.reduce(
operator.__and__, [key in self.data for key in keys], True
)
if has_values:
values = tuple([self.data[key] for key in keys])
if len(values) == 1:
values = values[0]
if kwargs.get('with_path', False):
yield self.path, values
else:
yield values
if kwargs.get('recursive', True):
for child in self.children.values():
for value in child.collect(*keys, **kwargs):
yield value | python | def collect(self, *keys, **kwargs):
"""Generator function traversing
tree structure to collect values of a specified key.
:param keys: the keys to look for in the report
:type key: str
:keyword recursive: look for key in children nodes
:type recursive: bool
:keyword with_path: whether the yield values is a tuple
of 2 elements containing report-path and the value
or simply the value.
:type with_path: bool
:rtype: generator providing either values or
tuples of 2 elements containing report path and value
depending on with_path parameter
"""
if not keys:
raise Exception('Missing key')
has_values = functools.reduce(
operator.__and__, [key in self.data for key in keys], True
)
if has_values:
values = tuple([self.data[key] for key in keys])
if len(values) == 1:
values = values[0]
if kwargs.get('with_path', False):
yield self.path, values
else:
yield values
if kwargs.get('recursive', True):
for child in self.children.values():
for value in child.collect(*keys, **kwargs):
yield value | [
"def",
"collect",
"(",
"self",
",",
"*",
"keys",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"keys",
":",
"raise",
"Exception",
"(",
"'Missing key'",
")",
"has_values",
"=",
"functools",
".",
"reduce",
"(",
"operator",
".",
"__and__",
",",
"[",
"... | Generator function traversing
tree structure to collect values of a specified key.
:param keys: the keys to look for in the report
:type key: str
:keyword recursive: look for key in children nodes
:type recursive: bool
:keyword with_path: whether the yield values is a tuple
of 2 elements containing report-path and the value
or simply the value.
:type with_path: bool
:rtype: generator providing either values or
tuples of 2 elements containing report path and value
depending on with_path parameter | [
"Generator",
"function",
"traversing",
"tree",
"structure",
"to",
"collect",
"values",
"of",
"a",
"specified",
"key",
"."
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L659-L692 | train | 53,482 |
BlueBrain/hpcbench | hpcbench/campaign.py | ReportNode.collect_one | def collect_one(self, *args, **kwargs):
"""Same as `collect` but expects to have only one result.
:return: the only result directly, not the generator like `collect`.
"""
generator = self.collect(*args, **kwargs)
try:
value = next(generator)
except StopIteration:
raise Exception("Expected exactly one value don't have any")
try:
next(generator)
except StopIteration:
return value
raise Exception('Expected exactly one value but have more') | python | def collect_one(self, *args, **kwargs):
"""Same as `collect` but expects to have only one result.
:return: the only result directly, not the generator like `collect`.
"""
generator = self.collect(*args, **kwargs)
try:
value = next(generator)
except StopIteration:
raise Exception("Expected exactly one value don't have any")
try:
next(generator)
except StopIteration:
return value
raise Exception('Expected exactly one value but have more') | [
"def",
"collect_one",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"generator",
"=",
"self",
".",
"collect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"value",
"=",
"next",
"(",
"generator",
")",
"except",
"... | Same as `collect` but expects to have only one result.
:return: the only result directly, not the generator like `collect`. | [
"Same",
"as",
"collect",
"but",
"expects",
"to",
"have",
"only",
"one",
"result",
"."
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L694-L708 | train | 53,483 |
eng-tools/sfsimodels | sfsimodels/models/buildings.py | Frame.set_beam_prop | def set_beam_prop(self, prop, values, repeat="up"):
"""
Specify the properties of the beams
:param values:
:param repeat: if 'up' then duplicate up the structure
:return:
"""
values = np.array(values)
if repeat == "up":
assert len(values.shape) == 1
values = [values for ss in range(self.n_storeys)]
else:
assert len(values.shape) == 2
if len(values[0]) != self.n_bays:
raise ModelError("beam depths does not match number of bays (%i)." % self.n_bays)
for ss in range(self.n_storeys):
for i in range(self.n_bays):
self._beams[ss][i].set_section_prop(prop, values[0][i]) | python | def set_beam_prop(self, prop, values, repeat="up"):
"""
Specify the properties of the beams
:param values:
:param repeat: if 'up' then duplicate up the structure
:return:
"""
values = np.array(values)
if repeat == "up":
assert len(values.shape) == 1
values = [values for ss in range(self.n_storeys)]
else:
assert len(values.shape) == 2
if len(values[0]) != self.n_bays:
raise ModelError("beam depths does not match number of bays (%i)." % self.n_bays)
for ss in range(self.n_storeys):
for i in range(self.n_bays):
self._beams[ss][i].set_section_prop(prop, values[0][i]) | [
"def",
"set_beam_prop",
"(",
"self",
",",
"prop",
",",
"values",
",",
"repeat",
"=",
"\"up\"",
")",
":",
"values",
"=",
"np",
".",
"array",
"(",
"values",
")",
"if",
"repeat",
"==",
"\"up\"",
":",
"assert",
"len",
"(",
"values",
".",
"shape",
")",
... | Specify the properties of the beams
:param values:
:param repeat: if 'up' then duplicate up the structure
:return: | [
"Specify",
"the",
"properties",
"of",
"the",
"beams"
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/buildings.py#L391-L409 | train | 53,484 |
eng-tools/sfsimodels | sfsimodels/models/buildings.py | Frame.set_column_prop | def set_column_prop(self, prop, values, repeat="up"):
"""
Specify the properties of the columns
:param values:
:param repeat: if 'up' then duplicate up the structure
:return:
"""
values = np.array(values)
if repeat == "up":
assert len(values.shape) == 1
values = [values for ss in range(self.n_storeys)]
else:
assert len(values.shape) == 2
if len(values[0]) != self.n_cols:
raise ModelError("column props does not match n_cols (%i)." % self.n_cols)
for ss in range(self.n_storeys):
for i in range(self.n_cols):
self._columns[ss][i].set_section_prop(prop, values[0][i]) | python | def set_column_prop(self, prop, values, repeat="up"):
"""
Specify the properties of the columns
:param values:
:param repeat: if 'up' then duplicate up the structure
:return:
"""
values = np.array(values)
if repeat == "up":
assert len(values.shape) == 1
values = [values for ss in range(self.n_storeys)]
else:
assert len(values.shape) == 2
if len(values[0]) != self.n_cols:
raise ModelError("column props does not match n_cols (%i)." % self.n_cols)
for ss in range(self.n_storeys):
for i in range(self.n_cols):
self._columns[ss][i].set_section_prop(prop, values[0][i]) | [
"def",
"set_column_prop",
"(",
"self",
",",
"prop",
",",
"values",
",",
"repeat",
"=",
"\"up\"",
")",
":",
"values",
"=",
"np",
".",
"array",
"(",
"values",
")",
"if",
"repeat",
"==",
"\"up\"",
":",
"assert",
"len",
"(",
"values",
".",
"shape",
")",
... | Specify the properties of the columns
:param values:
:param repeat: if 'up' then duplicate up the structure
:return: | [
"Specify",
"the",
"properties",
"of",
"the",
"columns"
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/buildings.py#L411-L429 | train | 53,485 |
simonvh/norns | norns/cfg.py | Config.load | def load(self, path):
"""
Load yaml-formatted config file.
Parameters
----------
path : str
path to config file
"""
with open(path) as f:
self.config = full_load(f)
if self.config is None:
sys.stderr.write("Warning: config file is empty!\n")
self.config = {} | python | def load(self, path):
"""
Load yaml-formatted config file.
Parameters
----------
path : str
path to config file
"""
with open(path) as f:
self.config = full_load(f)
if self.config is None:
sys.stderr.write("Warning: config file is empty!\n")
self.config = {} | [
"def",
"load",
"(",
"self",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"self",
".",
"config",
"=",
"full_load",
"(",
"f",
")",
"if",
"self",
".",
"config",
"is",
"None",
":",
"sys",
".",
"stderr",
".",
"write",
"("... | Load yaml-formatted config file.
Parameters
----------
path : str
path to config file | [
"Load",
"yaml",
"-",
"formatted",
"config",
"file",
"."
] | 81db0004c558f91479176daf1918b8c9473b5ee2 | https://github.com/simonvh/norns/blob/81db0004c558f91479176daf1918b8c9473b5ee2/norns/cfg.py#L60-L73 | train | 53,486 |
simonvh/norns | norns/cfg.py | Config.save | def save(self):
"""
Save current state of config dictionary.
"""
with open(self.config_file, "w") as f:
f.write(dump(self.config, default_flow_style=False)) | python | def save(self):
"""
Save current state of config dictionary.
"""
with open(self.config_file, "w") as f:
f.write(dump(self.config, default_flow_style=False)) | [
"def",
"save",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"config_file",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"dump",
"(",
"self",
".",
"config",
",",
"default_flow_style",
"=",
"False",
")",
")"
] | Save current state of config dictionary. | [
"Save",
"current",
"state",
"of",
"config",
"dictionary",
"."
] | 81db0004c558f91479176daf1918b8c9473b5ee2 | https://github.com/simonvh/norns/blob/81db0004c558f91479176daf1918b8c9473b5ee2/norns/cfg.py#L75-L80 | train | 53,487 |
Capitains/Nautilus | capitains_nautilus/flask_ext.py | FlaskNautilus.register | def register(self, extension, extension_name):
""" Register an extension into the Nautilus Router
:param extension: Extension
:param extension_name: Name of the Extension
:return:
"""
self._extensions[extension_name] = extension
self.ROUTES.extend([
tuple(list(t) + [extension_name])
for t in extension.ROUTES
])
self.CACHED.extend([
(f_name, extension_name)
for f_name in extension.CACHED
])
# This order allows for user defaults to overwrite extension ones
self.Access_Control_Allow_Methods.update({
k: v
for k, v in extension.Access_Control_Allow_Methods.items()
if k not in self.Access_Control_Allow_Methods
}) | python | def register(self, extension, extension_name):
""" Register an extension into the Nautilus Router
:param extension: Extension
:param extension_name: Name of the Extension
:return:
"""
self._extensions[extension_name] = extension
self.ROUTES.extend([
tuple(list(t) + [extension_name])
for t in extension.ROUTES
])
self.CACHED.extend([
(f_name, extension_name)
for f_name in extension.CACHED
])
# This order allows for user defaults to overwrite extension ones
self.Access_Control_Allow_Methods.update({
k: v
for k, v in extension.Access_Control_Allow_Methods.items()
if k not in self.Access_Control_Allow_Methods
}) | [
"def",
"register",
"(",
"self",
",",
"extension",
",",
"extension_name",
")",
":",
"self",
".",
"_extensions",
"[",
"extension_name",
"]",
"=",
"extension",
"self",
".",
"ROUTES",
".",
"extend",
"(",
"[",
"tuple",
"(",
"list",
"(",
"t",
")",
"+",
"[",
... | Register an extension into the Nautilus Router
:param extension: Extension
:param extension_name: Name of the Extension
:return: | [
"Register",
"an",
"extension",
"into",
"the",
"Nautilus",
"Router"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/flask_ext.py#L91-L113 | train | 53,488 |
Capitains/Nautilus | capitains_nautilus/flask_ext.py | FlaskNautilus.setLogger | def setLogger(self, logger):
""" Set up the Logger for the application
:param logger: logging.Logger object
:return: Logger instance
"""
self.logger = logger
if logger is None:
self.logger = logging.getLogger("capitains_nautilus")
formatter = logging.Formatter("[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s")
stream = FlaskNautilus.LoggingHandler()
stream.setLevel(logging.INFO)
stream.setFormatter(formatter)
self.logger.addHandler(stream)
if self.resolver:
self.resolver.logger = self.logger
return self.logger | python | def setLogger(self, logger):
""" Set up the Logger for the application
:param logger: logging.Logger object
:return: Logger instance
"""
self.logger = logger
if logger is None:
self.logger = logging.getLogger("capitains_nautilus")
formatter = logging.Formatter("[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s")
stream = FlaskNautilus.LoggingHandler()
stream.setLevel(logging.INFO)
stream.setFormatter(formatter)
self.logger.addHandler(stream)
if self.resolver:
self.resolver.logger = self.logger
return self.logger | [
"def",
"setLogger",
"(",
"self",
",",
"logger",
")",
":",
"self",
".",
"logger",
"=",
"logger",
"if",
"logger",
"is",
"None",
":",
"self",
".",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"capitains_nautilus\"",
")",
"formatter",
"=",
"logging",
"... | Set up the Logger for the application
:param logger: logging.Logger object
:return: Logger instance | [
"Set",
"up",
"the",
"Logger",
"for",
"the",
"application"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/flask_ext.py#L119-L137 | train | 53,489 |
Capitains/Nautilus | capitains_nautilus/flask_ext.py | FlaskNautilus.init_app | def init_app(self, app):
""" Initiate the extension on the application
:param app: Flask Application
:return: Blueprint for Flask Nautilus registered in app
:rtype: Blueprint
"""
self.init_blueprint(app)
if self.flaskcache is not None:
for func, extension_name in self.CACHED:
func = getattr(self._extensions[extension_name], func)
setattr(
self._extensions[extension_name],
func.__name__,
self.flaskcache.memoize()(func)
)
return self.blueprint | python | def init_app(self, app):
""" Initiate the extension on the application
:param app: Flask Application
:return: Blueprint for Flask Nautilus registered in app
:rtype: Blueprint
"""
self.init_blueprint(app)
if self.flaskcache is not None:
for func, extension_name in self.CACHED:
func = getattr(self._extensions[extension_name], func)
setattr(
self._extensions[extension_name],
func.__name__,
self.flaskcache.memoize()(func)
)
return self.blueprint | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"init_blueprint",
"(",
"app",
")",
"if",
"self",
".",
"flaskcache",
"is",
"not",
"None",
":",
"for",
"func",
",",
"extension_name",
"in",
"self",
".",
"CACHED",
":",
"func",
"=",
"get... | Initiate the extension on the application
:param app: Flask Application
:return: Blueprint for Flask Nautilus registered in app
:rtype: Blueprint | [
"Initiate",
"the",
"extension",
"on",
"the",
"application"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/flask_ext.py#L139-L158 | train | 53,490 |
Capitains/Nautilus | capitains_nautilus/flask_ext.py | FlaskNautilus.init_blueprint | def init_blueprint(self, app):
""" Properly generates the blueprint, registering routes and filters and connecting the app and the blueprint
:return: Blueprint of the extension
:rtype: Blueprint
"""
self.blueprint = Blueprint(
self.name,
self.name,
template_folder=resource_filename("capitains_nautilus", "data/templates"),
url_prefix=self.prefix
)
# Register routes
for url, name, methods, extension_name in self.ROUTES:
self.blueprint.add_url_rule(
url,
view_func=self.view(name, extension_name),
endpoint=name[2:],
methods=methods
)
app.register_blueprint(self.blueprint)
return self.blueprint | python | def init_blueprint(self, app):
""" Properly generates the blueprint, registering routes and filters and connecting the app and the blueprint
:return: Blueprint of the extension
:rtype: Blueprint
"""
self.blueprint = Blueprint(
self.name,
self.name,
template_folder=resource_filename("capitains_nautilus", "data/templates"),
url_prefix=self.prefix
)
# Register routes
for url, name, methods, extension_name in self.ROUTES:
self.blueprint.add_url_rule(
url,
view_func=self.view(name, extension_name),
endpoint=name[2:],
methods=methods
)
app.register_blueprint(self.blueprint)
return self.blueprint | [
"def",
"init_blueprint",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"blueprint",
"=",
"Blueprint",
"(",
"self",
".",
"name",
",",
"self",
".",
"name",
",",
"template_folder",
"=",
"resource_filename",
"(",
"\"capitains_nautilus\"",
",",
"\"data/templates\... | Properly generates the blueprint, registering routes and filters and connecting the app and the blueprint
:return: Blueprint of the extension
:rtype: Blueprint | [
"Properly",
"generates",
"the",
"blueprint",
"registering",
"routes",
"and",
"filters",
"and",
"connecting",
"the",
"app",
"and",
"the",
"blueprint"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/flask_ext.py#L160-L183 | train | 53,491 |
Capitains/Nautilus | capitains_nautilus/flask_ext.py | FlaskNautilus.view | def view(self, function_name, extension_name):
""" Builds response according to a function name
:param function_name: Route name / function name
:param extension_name: Name of the extension holding the function
:return: Function
"""
if isinstance(self.Access_Control_Allow_Origin, dict):
d = {
"Access-Control-Allow-Origin": self.Access_Control_Allow_Origin[function_name],
"Access-Control-Allow-Methods": self.Access_Control_Allow_Methods[function_name]
}
else:
d = {
"Access-Control-Allow-Origin": self.Access_Control_Allow_Origin,
"Access-Control-Allow-Methods": self.Access_Control_Allow_Methods[function_name]
}
def r(*x, **y):
val = getattr(self._extensions[extension_name], function_name)(*x, **y)
if isinstance(val, Response):
val.headers.extend(d)
return val
else:
val = list(val)
val[2].update(d)
return tuple(val)
return r | python | def view(self, function_name, extension_name):
""" Builds response according to a function name
:param function_name: Route name / function name
:param extension_name: Name of the extension holding the function
:return: Function
"""
if isinstance(self.Access_Control_Allow_Origin, dict):
d = {
"Access-Control-Allow-Origin": self.Access_Control_Allow_Origin[function_name],
"Access-Control-Allow-Methods": self.Access_Control_Allow_Methods[function_name]
}
else:
d = {
"Access-Control-Allow-Origin": self.Access_Control_Allow_Origin,
"Access-Control-Allow-Methods": self.Access_Control_Allow_Methods[function_name]
}
def r(*x, **y):
val = getattr(self._extensions[extension_name], function_name)(*x, **y)
if isinstance(val, Response):
val.headers.extend(d)
return val
else:
val = list(val)
val[2].update(d)
return tuple(val)
return r | [
"def",
"view",
"(",
"self",
",",
"function_name",
",",
"extension_name",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"Access_Control_Allow_Origin",
",",
"dict",
")",
":",
"d",
"=",
"{",
"\"Access-Control-Allow-Origin\"",
":",
"self",
".",
"Access_Control_All... | Builds response according to a function name
:param function_name: Route name / function name
:param extension_name: Name of the extension holding the function
:return: Function | [
"Builds",
"response",
"according",
"to",
"a",
"function",
"name"
] | 6be453fe0cc0e2c1b89ff06e5af1409165fc1411 | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/flask_ext.py#L185-L212 | train | 53,492 |
PolyJIT/benchbuild | benchbuild/utils/slurm.py | script | def script(experiment, projects):
"""
Prepare a slurm script that executes the experiment for a given project.
Args:
experiment: The experiment we want to execute
projects: All projects we generate an array job for.
"""
benchbuild_c = local[local.path(sys.argv[0])]
slurm_script = local.cwd / experiment.name + "-" + str(
CFG['slurm']['script'])
srun = local["srun"]
srun_args = []
if not CFG["slurm"]["multithread"]:
srun_args.append("--hint=nomultithread")
if not CFG["slurm"]["turbo"]:
srun_args.append("--pstate-turbo=off")
srun = srun[srun_args]
srun = srun[benchbuild_c["run"]]
return __save__(slurm_script, srun, experiment, projects) | python | def script(experiment, projects):
"""
Prepare a slurm script that executes the experiment for a given project.
Args:
experiment: The experiment we want to execute
projects: All projects we generate an array job for.
"""
benchbuild_c = local[local.path(sys.argv[0])]
slurm_script = local.cwd / experiment.name + "-" + str(
CFG['slurm']['script'])
srun = local["srun"]
srun_args = []
if not CFG["slurm"]["multithread"]:
srun_args.append("--hint=nomultithread")
if not CFG["slurm"]["turbo"]:
srun_args.append("--pstate-turbo=off")
srun = srun[srun_args]
srun = srun[benchbuild_c["run"]]
return __save__(slurm_script, srun, experiment, projects) | [
"def",
"script",
"(",
"experiment",
",",
"projects",
")",
":",
"benchbuild_c",
"=",
"local",
"[",
"local",
".",
"path",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"]",
"slurm_script",
"=",
"local",
".",
"cwd",
"/",
"experiment",
".",
"name",
"+",
... | Prepare a slurm script that executes the experiment for a given project.
Args:
experiment: The experiment we want to execute
projects: All projects we generate an array job for. | [
"Prepare",
"a",
"slurm",
"script",
"that",
"executes",
"the",
"experiment",
"for",
"a",
"given",
"project",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/slurm.py#L20-L42 | train | 53,493 |
mromanello/hucitlib | scripts/populate.py | fetch_text_structure | def fetch_text_structure(urn, endpoint="http://cts.perseids.org/api/cts"):
"""
Fetches the text structure of a given work from a CTS endpoint.
:param urn: the work's CTS URN (at the work-level!,
e.g."urn:cts:greekLit:tlg0012.tlg001")
:type urn: string
:param endpoint: the URL of the CTS endpoint to use (defaults to Perseids')
:type endpoint: string
:return: a dict with keys "urn", "provenance", "valid_reffs", "levels"
:rtype: dict
"""
structure = {
"urn": urn,
"provenance": endpoint,
"valid_reffs": {}
}
orig_edition = None
suffix = 'grc' if 'greekLit' in urn else 'lat'
resolver = HttpCtsResolver(HttpCtsRetriever(endpoint))
work_metadata = resolver.getMetadata(urn)
# among all editions for this work, pick the one in Greek or Latin
try:
orig_edition = next(iter(
work_metadata.children[edition]
for edition in work_metadata.children
if suffix in str(work_metadata.children[edition].urn)
))
except Exception as e:
print(e)
return None
assert orig_edition is not None
# get information about the work's citation scheme
structure["levels"] = [
(n + 1, level.name.lower())
for n, level in enumerate(orig_edition.citation)
]
# for each hierarchical level of the text
# fetch all citable text elements
for level_n, level_label in structure["levels"]:
structure["valid_reffs"][level_n] = []
for ref in resolver.getReffs(urn, level=level_n):
print(ref)
element = {
"current": "{}:{}".format(urn, ref),
}
if "." in ref:
element["parent"] = "{}:{}".format(
urn,
".".join(ref.split(".")[:level_n - 1])
)
# TODO: parallelize this bit
textual_node = resolver.getTextualNode(
textId=urn,
subreference=ref,
prevnext=True
)
if textual_node.nextId is not None:
element["previous"] = "{}:{}".format(urn, textual_node.nextId)
if textual_node.prevId is not None:
element["following"] = "{}:{}".format(urn, textual_node.prevId)
structure["valid_reffs"][level_n].append(element)
return structure | python | def fetch_text_structure(urn, endpoint="http://cts.perseids.org/api/cts"):
"""
Fetches the text structure of a given work from a CTS endpoint.
:param urn: the work's CTS URN (at the work-level!,
e.g."urn:cts:greekLit:tlg0012.tlg001")
:type urn: string
:param endpoint: the URL of the CTS endpoint to use (defaults to Perseids')
:type endpoint: string
:return: a dict with keys "urn", "provenance", "valid_reffs", "levels"
:rtype: dict
"""
structure = {
"urn": urn,
"provenance": endpoint,
"valid_reffs": {}
}
orig_edition = None
suffix = 'grc' if 'greekLit' in urn else 'lat'
resolver = HttpCtsResolver(HttpCtsRetriever(endpoint))
work_metadata = resolver.getMetadata(urn)
# among all editions for this work, pick the one in Greek or Latin
try:
orig_edition = next(iter(
work_metadata.children[edition]
for edition in work_metadata.children
if suffix in str(work_metadata.children[edition].urn)
))
except Exception as e:
print(e)
return None
assert orig_edition is not None
# get information about the work's citation scheme
structure["levels"] = [
(n + 1, level.name.lower())
for n, level in enumerate(orig_edition.citation)
]
# for each hierarchical level of the text
# fetch all citable text elements
for level_n, level_label in structure["levels"]:
structure["valid_reffs"][level_n] = []
for ref in resolver.getReffs(urn, level=level_n):
print(ref)
element = {
"current": "{}:{}".format(urn, ref),
}
if "." in ref:
element["parent"] = "{}:{}".format(
urn,
".".join(ref.split(".")[:level_n - 1])
)
# TODO: parallelize this bit
textual_node = resolver.getTextualNode(
textId=urn,
subreference=ref,
prevnext=True
)
if textual_node.nextId is not None:
element["previous"] = "{}:{}".format(urn, textual_node.nextId)
if textual_node.prevId is not None:
element["following"] = "{}:{}".format(urn, textual_node.prevId)
structure["valid_reffs"][level_n].append(element)
return structure | [
"def",
"fetch_text_structure",
"(",
"urn",
",",
"endpoint",
"=",
"\"http://cts.perseids.org/api/cts\"",
")",
":",
"structure",
"=",
"{",
"\"urn\"",
":",
"urn",
",",
"\"provenance\"",
":",
"endpoint",
",",
"\"valid_reffs\"",
":",
"{",
"}",
"}",
"orig_edition",
"=... | Fetches the text structure of a given work from a CTS endpoint.
:param urn: the work's CTS URN (at the work-level!,
e.g."urn:cts:greekLit:tlg0012.tlg001")
:type urn: string
:param endpoint: the URL of the CTS endpoint to use (defaults to Perseids')
:type endpoint: string
:return: a dict with keys "urn", "provenance", "valid_reffs", "levels"
:rtype: dict | [
"Fetches",
"the",
"text",
"structure",
"of",
"a",
"given",
"work",
"from",
"a",
"CTS",
"endpoint",
"."
] | 6587d1b04eb7e5b48ad7359be845e5d3b444d6fa | https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/scripts/populate.py#L34-L104 | train | 53,494 |
PolyJIT/benchbuild | benchbuild/experiments/empty.py | NoMeasurement.actions_for_project | def actions_for_project(self, project):
"""Execute all actions but don't do anything as extension."""
project.runtime_extension = run.RuntimeExtension(project, self)
return self.default_runtime_actions(project) | python | def actions_for_project(self, project):
"""Execute all actions but don't do anything as extension."""
project.runtime_extension = run.RuntimeExtension(project, self)
return self.default_runtime_actions(project) | [
"def",
"actions_for_project",
"(",
"self",
",",
"project",
")",
":",
"project",
".",
"runtime_extension",
"=",
"run",
".",
"RuntimeExtension",
"(",
"project",
",",
"self",
")",
"return",
"self",
".",
"default_runtime_actions",
"(",
"project",
")"
] | Execute all actions but don't do anything as extension. | [
"Execute",
"all",
"actions",
"but",
"don",
"t",
"do",
"anything",
"as",
"extension",
"."
] | 9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58 | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/experiments/empty.py#L28-L31 | train | 53,495 |
eng-tools/sfsimodels | sfsimodels/sensors.py | read_json_sensor_file | def read_json_sensor_file(ffp):
"""
Reads the sensor file and stores it as a dictionary.
:param ffp: full file path to json file
:return:
"""
sensor_path = ffp
si = json.load(open(sensor_path))
for m_type in si:
# Convert keys from strings to integers
si[m_type] = {int(k): v for k, v in si[m_type].items()}
return si | python | def read_json_sensor_file(ffp):
"""
Reads the sensor file and stores it as a dictionary.
:param ffp: full file path to json file
:return:
"""
sensor_path = ffp
si = json.load(open(sensor_path))
for m_type in si:
# Convert keys from strings to integers
si[m_type] = {int(k): v for k, v in si[m_type].items()}
return si | [
"def",
"read_json_sensor_file",
"(",
"ffp",
")",
":",
"sensor_path",
"=",
"ffp",
"si",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"sensor_path",
")",
")",
"for",
"m_type",
"in",
"si",
":",
"# Convert keys from strings to integers",
"si",
"[",
"m_type",
"]",... | Reads the sensor file and stores it as a dictionary.
:param ffp: full file path to json file
:return: | [
"Reads",
"the",
"sensor",
"file",
"and",
"stores",
"it",
"as",
"a",
"dictionary",
"."
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/sensors.py#L4-L16 | train | 53,496 |
eng-tools/sfsimodels | sfsimodels/sensors.py | get_all_sensor_codes | def get_all_sensor_codes(si, wild_sensor_code):
"""
Get all sensor sensor_codes that match a wild sensor code
:param si: dict, sensor index json dictionary
:param wild_sensor_code: str, a sensor code with "*" for wildcards (e.g. ACCX-*-L2C-*)
:return:
"""
mtype_and_ory, x, y, z = wild_sensor_code.split("-")
if mtype_and_ory == "*":
mtypes = list(si)
elif mtype_and_ory[-1] in "XYZ" and "ACCX" not in si: # Need to support old sensor_file.json files.
mtypes = [mtype_and_ory[:-1]]
else:
mtypes = [mtype_and_ory]
all_sensor_codes = []
for mtype in mtypes:
for m_number in si[mtype]:
if x in ["*", si[mtype][m_number]['X-CODE']] and \
y in ["*", si[mtype][m_number]['Y-CODE']] and \
z in ["*", si[mtype][m_number]['Z-CODE']]:
cc = get_sensor_code_by_number(si, mtype, m_number)
all_sensor_codes.append(cc)
return all_sensor_codes | python | def get_all_sensor_codes(si, wild_sensor_code):
"""
Get all sensor sensor_codes that match a wild sensor code
:param si: dict, sensor index json dictionary
:param wild_sensor_code: str, a sensor code with "*" for wildcards (e.g. ACCX-*-L2C-*)
:return:
"""
mtype_and_ory, x, y, z = wild_sensor_code.split("-")
if mtype_and_ory == "*":
mtypes = list(si)
elif mtype_and_ory[-1] in "XYZ" and "ACCX" not in si: # Need to support old sensor_file.json files.
mtypes = [mtype_and_ory[:-1]]
else:
mtypes = [mtype_and_ory]
all_sensor_codes = []
for mtype in mtypes:
for m_number in si[mtype]:
if x in ["*", si[mtype][m_number]['X-CODE']] and \
y in ["*", si[mtype][m_number]['Y-CODE']] and \
z in ["*", si[mtype][m_number]['Z-CODE']]:
cc = get_sensor_code_by_number(si, mtype, m_number)
all_sensor_codes.append(cc)
return all_sensor_codes | [
"def",
"get_all_sensor_codes",
"(",
"si",
",",
"wild_sensor_code",
")",
":",
"mtype_and_ory",
",",
"x",
",",
"y",
",",
"z",
"=",
"wild_sensor_code",
".",
"split",
"(",
"\"-\"",
")",
"if",
"mtype_and_ory",
"==",
"\"*\"",
":",
"mtypes",
"=",
"list",
"(",
"... | Get all sensor sensor_codes that match a wild sensor code
:param si: dict, sensor index json dictionary
:param wild_sensor_code: str, a sensor code with "*" for wildcards (e.g. ACCX-*-L2C-*)
:return: | [
"Get",
"all",
"sensor",
"sensor_codes",
"that",
"match",
"a",
"wild",
"sensor",
"code"
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/sensors.py#L19-L44 | train | 53,497 |
eng-tools/sfsimodels | sfsimodels/sensors.py | get_mtype_and_number_from_code | def get_mtype_and_number_from_code(si, sensor_code):
"""
Given a sensor sensor_code, get motion type and sensor number
:param si: dict, sensor index json dictionary
:param sensor_code: str, a sensor code (e.g. ACCX-UB1-L2C-M)
:return:
"""
mtype_and_ory, x, y, z = sensor_code.split("-")
if mtype_and_ory[-1] in "XYZ" and "ACCX" not in si: # Need to support old sensor_file.json files.
mtype = mtype_and_ory[:-1]
else:
mtype = mtype_and_ory
for m_number in si[mtype]:
cc = get_sensor_code_by_number(si, mtype, m_number)
if cc == sensor_code:
return mtype, m_number
return None, None | python | def get_mtype_and_number_from_code(si, sensor_code):
"""
Given a sensor sensor_code, get motion type and sensor number
:param si: dict, sensor index json dictionary
:param sensor_code: str, a sensor code (e.g. ACCX-UB1-L2C-M)
:return:
"""
mtype_and_ory, x, y, z = sensor_code.split("-")
if mtype_and_ory[-1] in "XYZ" and "ACCX" not in si: # Need to support old sensor_file.json files.
mtype = mtype_and_ory[:-1]
else:
mtype = mtype_and_ory
for m_number in si[mtype]:
cc = get_sensor_code_by_number(si, mtype, m_number)
if cc == sensor_code:
return mtype, m_number
return None, None | [
"def",
"get_mtype_and_number_from_code",
"(",
"si",
",",
"sensor_code",
")",
":",
"mtype_and_ory",
",",
"x",
",",
"y",
",",
"z",
"=",
"sensor_code",
".",
"split",
"(",
"\"-\"",
")",
"if",
"mtype_and_ory",
"[",
"-",
"1",
"]",
"in",
"\"XYZ\"",
"and",
"\"AC... | Given a sensor sensor_code, get motion type and sensor number
:param si: dict, sensor index json dictionary
:param sensor_code: str, a sensor code (e.g. ACCX-UB1-L2C-M)
:return: | [
"Given",
"a",
"sensor",
"sensor_code",
"get",
"motion",
"type",
"and",
"sensor",
"number"
] | 65a690ca440d61307f5a9b8478e4704f203a5925 | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/sensors.py#L85-L102 | train | 53,498 |
mromanello/hucitlib | knowledge_base/surfext/__init__.py | HucitAuthor.get_names | def get_names(self):
"""
Returns a dict where key is the language and value is the name in that language.
Example:
{'it':"Sofocle"}
"""
names = [id for id in self.ecrm_P1_is_identified_by if id.uri == surf.ns.EFRBROO['F12_Name']]
self.names = []
for name in names:
for variant in name.rdfs_label:
self.names.append((variant.language,variant.title()))
return self.names | python | def get_names(self):
"""
Returns a dict where key is the language and value is the name in that language.
Example:
{'it':"Sofocle"}
"""
names = [id for id in self.ecrm_P1_is_identified_by if id.uri == surf.ns.EFRBROO['F12_Name']]
self.names = []
for name in names:
for variant in name.rdfs_label:
self.names.append((variant.language,variant.title()))
return self.names | [
"def",
"get_names",
"(",
"self",
")",
":",
"names",
"=",
"[",
"id",
"for",
"id",
"in",
"self",
".",
"ecrm_P1_is_identified_by",
"if",
"id",
".",
"uri",
"==",
"surf",
".",
"ns",
".",
"EFRBROO",
"[",
"'F12_Name'",
"]",
"]",
"self",
".",
"names",
"=",
... | Returns a dict where key is the language and value is the name in that language.
Example:
{'it':"Sofocle"} | [
"Returns",
"a",
"dict",
"where",
"key",
"is",
"the",
"language",
"and",
"value",
"is",
"the",
"name",
"in",
"that",
"language",
"."
] | 6587d1b04eb7e5b48ad7359be845e5d3b444d6fa | https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L67-L79 | train | 53,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.