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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
project-rig/rig | docs/source/circuit_sim_tutorial/05_circuit_simulation/circuit_simulator.py | Stimulus._write_config | def _write_config(self, memory):
"""Write the configuration for this stimulus to memory."""
memory.seek(0)
memory.write(struct.pack("<II",
# sim_length
self._simulator.length,
# output_key
self.output.routing_key))
# NB: memory.write will automatically truncate any excess stimulus
memory.write(bitarray(
self.stimulus.ljust(self._simulator.length, "0"),
endian="little").tobytes()) | python | def _write_config(self, memory):
"""Write the configuration for this stimulus to memory."""
memory.seek(0)
memory.write(struct.pack("<II",
# sim_length
self._simulator.length,
# output_key
self.output.routing_key))
# NB: memory.write will automatically truncate any excess stimulus
memory.write(bitarray(
self.stimulus.ljust(self._simulator.length, "0"),
endian="little").tobytes()) | [
"def",
"_write_config",
"(",
"self",
",",
"memory",
")",
":",
"memory",
".",
"seek",
"(",
"0",
")",
"memory",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"\"<II\"",
",",
"# sim_length",
"self",
".",
"_simulator",
".",
"length",
",",
"# output_key",
... | Write the configuration for this stimulus to memory. | [
"Write",
"the",
"configuration",
"for",
"this",
"stimulus",
"to",
"memory",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/docs/source/circuit_sim_tutorial/05_circuit_simulation/circuit_simulator.py#L247-L259 | train | 50,700 |
Metatab/metapack | metapack/jupyter/exec.py | execute_notebook | def execute_notebook(nb_path, pkg_dir, dataframes, write_notebook=False, env=None):
"""
Execute a notebook after adding the prolog and epilog. Can also add %mt_materialize magics to
write dataframes to files
:param nb_path: path to a notebook.
:param pkg_dir: Directory to which dataframes are materialized
:param dataframes: List of names of dataframes to materialize
:return: a Notebook object
"""
import nbformat
from metapack.jupyter.preprocessors import AddEpilog, AddProlog
from metapack.jupyter.exporters import ExecutePreprocessor, Config
from os.path import dirname, join, splitext, basename
from nbconvert.preprocessors.execute import CellExecutionError
with open(nb_path, encoding='utf8') as f:
nb = nbformat.read(f, as_version=4)
root, ext = splitext(basename(nb_path))
c = Config()
nb, resources = AddProlog(config=c, env=env or {}).preprocess(nb, {})
nb, resources = AddEpilog(config=c, pkg_dir=pkg_dir,
dataframes=dataframes,
).preprocess(nb, {})
def _write_notebook(nb_path, root, ext, write_notebook):
if write_notebook:
if write_notebook is True:
exec_nb_path = join(dirname(nb_path), root + '-executed' + ext)
else:
exec_nb_path = write_notebook
with open(exec_nb_path, 'w', encoding='utf8') as f:
nbformat.write(nb, f)
_write_notebook(nb_path, root, ext, write_notebook)
try:
ep = ExecutePreprocessor(config=c)
ep.timeout = 5*60
nb, _ = ep.preprocess(nb, {'metadata': {'path': dirname(nb_path)}})
except (CellExecutionError, TimeoutError) as e:
err_nb_path = join(dirname(nb_path), root + '-errors' + ext)
with open(err_nb_path, 'w', encoding='utf8') as f:
nbformat.write(nb, f)
raise CellExecutionError("Errors executing noteboook. See notebook at {} for details.\n{}"
.format(err_nb_path, ''))
except ImportError as e:
raise NotebookError("Failed to import a library required for notebook execution: {}".format(str(e)))
_write_notebook(nb_path, root, ext, write_notebook)
return nb | python | def execute_notebook(nb_path, pkg_dir, dataframes, write_notebook=False, env=None):
"""
Execute a notebook after adding the prolog and epilog. Can also add %mt_materialize magics to
write dataframes to files
:param nb_path: path to a notebook.
:param pkg_dir: Directory to which dataframes are materialized
:param dataframes: List of names of dataframes to materialize
:return: a Notebook object
"""
import nbformat
from metapack.jupyter.preprocessors import AddEpilog, AddProlog
from metapack.jupyter.exporters import ExecutePreprocessor, Config
from os.path import dirname, join, splitext, basename
from nbconvert.preprocessors.execute import CellExecutionError
with open(nb_path, encoding='utf8') as f:
nb = nbformat.read(f, as_version=4)
root, ext = splitext(basename(nb_path))
c = Config()
nb, resources = AddProlog(config=c, env=env or {}).preprocess(nb, {})
nb, resources = AddEpilog(config=c, pkg_dir=pkg_dir,
dataframes=dataframes,
).preprocess(nb, {})
def _write_notebook(nb_path, root, ext, write_notebook):
if write_notebook:
if write_notebook is True:
exec_nb_path = join(dirname(nb_path), root + '-executed' + ext)
else:
exec_nb_path = write_notebook
with open(exec_nb_path, 'w', encoding='utf8') as f:
nbformat.write(nb, f)
_write_notebook(nb_path, root, ext, write_notebook)
try:
ep = ExecutePreprocessor(config=c)
ep.timeout = 5*60
nb, _ = ep.preprocess(nb, {'metadata': {'path': dirname(nb_path)}})
except (CellExecutionError, TimeoutError) as e:
err_nb_path = join(dirname(nb_path), root + '-errors' + ext)
with open(err_nb_path, 'w', encoding='utf8') as f:
nbformat.write(nb, f)
raise CellExecutionError("Errors executing noteboook. See notebook at {} for details.\n{}"
.format(err_nb_path, ''))
except ImportError as e:
raise NotebookError("Failed to import a library required for notebook execution: {}".format(str(e)))
_write_notebook(nb_path, root, ext, write_notebook)
return nb | [
"def",
"execute_notebook",
"(",
"nb_path",
",",
"pkg_dir",
",",
"dataframes",
",",
"write_notebook",
"=",
"False",
",",
"env",
"=",
"None",
")",
":",
"import",
"nbformat",
"from",
"metapack",
".",
"jupyter",
".",
"preprocessors",
"import",
"AddEpilog",
",",
... | Execute a notebook after adding the prolog and epilog. Can also add %mt_materialize magics to
write dataframes to files
:param nb_path: path to a notebook.
:param pkg_dir: Directory to which dataframes are materialized
:param dataframes: List of names of dataframes to materialize
:return: a Notebook object | [
"Execute",
"a",
"notebook",
"after",
"adding",
"the",
"prolog",
"and",
"epilog",
".",
"Can",
"also",
"add",
"%mt_materialize",
"magics",
"to",
"write",
"dataframes",
"to",
"files"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/exec.py#L11-L72 | train | 50,701 |
Metatab/metapack | metapack/jupyter/convert.py | convert_documentation | def convert_documentation(nb_path):
"""Run only the document conversion portion of the notebook conversion
The final document will not be completel
"""
with open(nb_path) as f:
nb = nbformat.reads(f.read(), as_version=4)
doc = ExtractInlineMetatabDoc(package_url="metapack+file:" + dirname(nb_path)).run(nb)
package_name = doc.as_version(None)
output_dir = join(getcwd(), package_name)
de = DocumentationExporter(config=Config(), log=logger, metadata=doc_metadata(doc))
prt('Converting documentation')
output, resources = de.from_filename(nb_path)
fw = FilesWriter()
fw.build_directory = join(output_dir, 'docs')
fw.write(output, resources, notebook_name='notebook')
prt("Wrote documentation to {}".format(fw.build_directory)) | python | def convert_documentation(nb_path):
"""Run only the document conversion portion of the notebook conversion
The final document will not be completel
"""
with open(nb_path) as f:
nb = nbformat.reads(f.read(), as_version=4)
doc = ExtractInlineMetatabDoc(package_url="metapack+file:" + dirname(nb_path)).run(nb)
package_name = doc.as_version(None)
output_dir = join(getcwd(), package_name)
de = DocumentationExporter(config=Config(), log=logger, metadata=doc_metadata(doc))
prt('Converting documentation')
output, resources = de.from_filename(nb_path)
fw = FilesWriter()
fw.build_directory = join(output_dir, 'docs')
fw.write(output, resources, notebook_name='notebook')
prt("Wrote documentation to {}".format(fw.build_directory)) | [
"def",
"convert_documentation",
"(",
"nb_path",
")",
":",
"with",
"open",
"(",
"nb_path",
")",
"as",
"f",
":",
"nb",
"=",
"nbformat",
".",
"reads",
"(",
"f",
".",
"read",
"(",
")",
",",
"as_version",
"=",
"4",
")",
"doc",
"=",
"ExtractInlineMetatabDoc"... | Run only the document conversion portion of the notebook conversion
The final document will not be completel | [
"Run",
"only",
"the",
"document",
"conversion",
"portion",
"of",
"the",
"notebook",
"conversion"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/convert.py#L23-L46 | train | 50,702 |
Metatab/metapack | metapack/jupyter/convert.py | doc_metadata | def doc_metadata(doc):
"""Create a metadata dict from a MetatabDoc, for Document conversion"""
r = doc['Root'].as_dict()
r.update(doc['Contacts'].as_dict())
r['author'] = r.get('author', r.get('creator', r.get('wrangler')))
return r | python | def doc_metadata(doc):
"""Create a metadata dict from a MetatabDoc, for Document conversion"""
r = doc['Root'].as_dict()
r.update(doc['Contacts'].as_dict())
r['author'] = r.get('author', r.get('creator', r.get('wrangler')))
return r | [
"def",
"doc_metadata",
"(",
"doc",
")",
":",
"r",
"=",
"doc",
"[",
"'Root'",
"]",
".",
"as_dict",
"(",
")",
"r",
".",
"update",
"(",
"doc",
"[",
"'Contacts'",
"]",
".",
"as_dict",
"(",
")",
")",
"r",
"[",
"'author'",
"]",
"=",
"r",
".",
"get",
... | Create a metadata dict from a MetatabDoc, for Document conversion | [
"Create",
"a",
"metadata",
"dict",
"from",
"a",
"MetatabDoc",
"for",
"Document",
"conversion"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/convert.py#L111-L118 | train | 50,703 |
Metatab/metapack | metapack/jupyter/convert.py | extract_notebook_metatab | def extract_notebook_metatab(nb_path: Path):
"""Extract the metatab lines from a notebook and return a Metapack doc """
from metatab.rowgenerators import TextRowGenerator
import nbformat
with nb_path.open() as f:
nb = nbformat.read(f, as_version=4)
lines = '\n'.join(['Declare: metatab-latest'] + [get_cell_source(nb, tag) for tag in ['metadata', 'resources',
'schema']])
doc = MetapackDoc(TextRowGenerator(lines))
doc['Root'].get_or_new_term('Root.Title').value = get_cell_source(nb, 'Title').strip('#').strip()
doc['Root'].get_or_new_term('Root.Description').value = get_cell_source(nb, 'Description')
doc['Documentation'].get_or_new_term('Root.Readme').value = get_cell_source(nb, 'readme')
return doc | python | def extract_notebook_metatab(nb_path: Path):
"""Extract the metatab lines from a notebook and return a Metapack doc """
from metatab.rowgenerators import TextRowGenerator
import nbformat
with nb_path.open() as f:
nb = nbformat.read(f, as_version=4)
lines = '\n'.join(['Declare: metatab-latest'] + [get_cell_source(nb, tag) for tag in ['metadata', 'resources',
'schema']])
doc = MetapackDoc(TextRowGenerator(lines))
doc['Root'].get_or_new_term('Root.Title').value = get_cell_source(nb, 'Title').strip('#').strip()
doc['Root'].get_or_new_term('Root.Description').value = get_cell_source(nb, 'Description')
doc['Documentation'].get_or_new_term('Root.Readme').value = get_cell_source(nb, 'readme')
return doc | [
"def",
"extract_notebook_metatab",
"(",
"nb_path",
":",
"Path",
")",
":",
"from",
"metatab",
".",
"rowgenerators",
"import",
"TextRowGenerator",
"import",
"nbformat",
"with",
"nb_path",
".",
"open",
"(",
")",
"as",
"f",
":",
"nb",
"=",
"nbformat",
".",
"read... | Extract the metatab lines from a notebook and return a Metapack doc | [
"Extract",
"the",
"metatab",
"lines",
"from",
"a",
"notebook",
"and",
"return",
"a",
"Metapack",
"doc"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/convert.py#L181-L199 | train | 50,704 |
Metatab/metapack | metapack/package/core.py | PackageBuilder.add_resource | def add_resource(self, ref, **properties):
"""Add one or more resources entities, from a url and property values,
possibly adding multiple entries for an excel spreadsheet or ZIP file"""
raise NotImplementedError("Still uses decompose_url")
du = Bunch(decompose_url(ref))
added = []
if du.proto == 'file' and isdir(ref):
for f in self.find_files(ref, ['csv']):
if f.endswith(DEFAULT_METATAB_FILE):
continue
if self._doc.find_first('Root.Datafile', value=f):
self.prt("Datafile exists for '{}', ignoring".format(f))
else:
added.extend(self.add_resource(f, **properties))
else:
self.prt("Enumerating '{}'".format(ref))
for c in enumerate_contents(ref, self._cache):
added.append(self.add_single_resource(c.rebuild_url(), **properties))
return added | python | def add_resource(self, ref, **properties):
"""Add one or more resources entities, from a url and property values,
possibly adding multiple entries for an excel spreadsheet or ZIP file"""
raise NotImplementedError("Still uses decompose_url")
du = Bunch(decompose_url(ref))
added = []
if du.proto == 'file' and isdir(ref):
for f in self.find_files(ref, ['csv']):
if f.endswith(DEFAULT_METATAB_FILE):
continue
if self._doc.find_first('Root.Datafile', value=f):
self.prt("Datafile exists for '{}', ignoring".format(f))
else:
added.extend(self.add_resource(f, **properties))
else:
self.prt("Enumerating '{}'".format(ref))
for c in enumerate_contents(ref, self._cache):
added.append(self.add_single_resource(c.rebuild_url(), **properties))
return added | [
"def",
"add_resource",
"(",
"self",
",",
"ref",
",",
"*",
"*",
"properties",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Still uses decompose_url\"",
")",
"du",
"=",
"Bunch",
"(",
"decompose_url",
"(",
"ref",
")",
")",
"added",
"=",
"[",
"]",
"if",
... | Add one or more resources entities, from a url and property values,
possibly adding multiple entries for an excel spreadsheet or ZIP file | [
"Add",
"one",
"or",
"more",
"resources",
"entities",
"from",
"a",
"url",
"and",
"property",
"values",
"possibly",
"adding",
"multiple",
"entries",
"for",
"an",
"excel",
"spreadsheet",
"or",
"ZIP",
"file"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/package/core.py#L298-L323 | train | 50,705 |
Metatab/metapack | metapack/package/core.py | PackageBuilder._clean_doc | def _clean_doc(self, doc=None):
"""Clean the doc before writing it, removing unnecessary properties and doing other operations."""
if doc is None:
doc = self.doc
resources = doc['Resources']
# We don't need these anymore because all of the data written into the package is normalized.
for arg in ['startline', 'headerlines', 'encoding']:
for e in list(resources.args):
if e.lower() == arg:
resources.args.remove(e)
for term in resources:
term['startline'] = None
term['headerlines'] = None
term['encoding'] = None
schema = doc['Schema']
## FIXME! This is probably dangerous, because the section args are changing, but the children
## are not, so when these two are combined in the Term.properties() acessors, the values are off.
## Because of this, _clean_doc should be run immediately before writing the doc.
for arg in ['altname', 'transform']:
for e in list(schema.args):
if e.lower() == arg:
schema.args.remove(e)
for table in self.doc.find('Root.Table'):
for col in table.find('Column'):
try:
col.value = col['altname'].value
except:
pass
col['altname'] = None
col['transform'] = None
# Remove any DSNs
#for dsn_t in self.doc.find('Root.Dsn'):
# self.doc.remove_term(dsn_t)
return doc | python | def _clean_doc(self, doc=None):
"""Clean the doc before writing it, removing unnecessary properties and doing other operations."""
if doc is None:
doc = self.doc
resources = doc['Resources']
# We don't need these anymore because all of the data written into the package is normalized.
for arg in ['startline', 'headerlines', 'encoding']:
for e in list(resources.args):
if e.lower() == arg:
resources.args.remove(e)
for term in resources:
term['startline'] = None
term['headerlines'] = None
term['encoding'] = None
schema = doc['Schema']
## FIXME! This is probably dangerous, because the section args are changing, but the children
## are not, so when these two are combined in the Term.properties() acessors, the values are off.
## Because of this, _clean_doc should be run immediately before writing the doc.
for arg in ['altname', 'transform']:
for e in list(schema.args):
if e.lower() == arg:
schema.args.remove(e)
for table in self.doc.find('Root.Table'):
for col in table.find('Column'):
try:
col.value = col['altname'].value
except:
pass
col['altname'] = None
col['transform'] = None
# Remove any DSNs
#for dsn_t in self.doc.find('Root.Dsn'):
# self.doc.remove_term(dsn_t)
return doc | [
"def",
"_clean_doc",
"(",
"self",
",",
"doc",
"=",
"None",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc",
"=",
"self",
".",
"doc",
"resources",
"=",
"doc",
"[",
"'Resources'",
"]",
"# We don't need these anymore because all of the data written into the package i... | Clean the doc before writing it, removing unnecessary properties and doing other operations. | [
"Clean",
"the",
"doc",
"before",
"writing",
"it",
"removing",
"unnecessary",
"properties",
"and",
"doing",
"other",
"operations",
"."
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/package/core.py#L325-L370 | train | 50,706 |
Metatab/metapack | metapack/package/core.py | PackageBuilder._load_resources | def _load_resources(self, abs_path=False):
"""Copy all of the Datafile entries into the package"""
from metapack.doc import MetapackDoc
assert type(self.doc) == MetapackDoc
for r in self.datafiles:
# Special handling for SQL is probably a really bad idea. It should be handled as
# a Rowgenerator.
if r.term_is('root.sql'):
if not r.value:
self.warn("No value for SQL URL for {} ".format(r.term))
continue
try:
self._load_resource(r, abs_path)
except Exception as e:
if r.props.get('ignoreerrors'):
self.warn(f"Ignoring errors for {r.name}: {str(e)}")
pass
else:
raise e
else:
if not r.url:
self.warn("No value for URL for {} ".format(r.term))
continue
try:
if self._resource.exists(r):
self.prt("Resource '{}' exists, skipping".format(r.name))
continue
except AttributeError:
pass
self.prt("Reading resource {} from {} ".format(r.name, r.resolved_url))
try:
if not r.headers:
raise PackageError("Resource {} does not have header. Have schemas been generated?"
.format(r.name))
except AttributeError:
raise PackageError("Resource '{}' of type {} does not have a headers property"
.format(r.url, type(r)))
try:
self._load_resource(r, abs_path)
except Exception as e:
if r.props.get('ignoreerrors'):
self.warn(f"Ignoring errors for {r.name}: {str(e)}")
pass
else:
raise e | python | def _load_resources(self, abs_path=False):
"""Copy all of the Datafile entries into the package"""
from metapack.doc import MetapackDoc
assert type(self.doc) == MetapackDoc
for r in self.datafiles:
# Special handling for SQL is probably a really bad idea. It should be handled as
# a Rowgenerator.
if r.term_is('root.sql'):
if not r.value:
self.warn("No value for SQL URL for {} ".format(r.term))
continue
try:
self._load_resource(r, abs_path)
except Exception as e:
if r.props.get('ignoreerrors'):
self.warn(f"Ignoring errors for {r.name}: {str(e)}")
pass
else:
raise e
else:
if not r.url:
self.warn("No value for URL for {} ".format(r.term))
continue
try:
if self._resource.exists(r):
self.prt("Resource '{}' exists, skipping".format(r.name))
continue
except AttributeError:
pass
self.prt("Reading resource {} from {} ".format(r.name, r.resolved_url))
try:
if not r.headers:
raise PackageError("Resource {} does not have header. Have schemas been generated?"
.format(r.name))
except AttributeError:
raise PackageError("Resource '{}' of type {} does not have a headers property"
.format(r.url, type(r)))
try:
self._load_resource(r, abs_path)
except Exception as e:
if r.props.get('ignoreerrors'):
self.warn(f"Ignoring errors for {r.name}: {str(e)}")
pass
else:
raise e | [
"def",
"_load_resources",
"(",
"self",
",",
"abs_path",
"=",
"False",
")",
":",
"from",
"metapack",
".",
"doc",
"import",
"MetapackDoc",
"assert",
"type",
"(",
"self",
".",
"doc",
")",
"==",
"MetapackDoc",
"for",
"r",
"in",
"self",
".",
"datafiles",
":",... | Copy all of the Datafile entries into the package | [
"Copy",
"all",
"of",
"the",
"Datafile",
"entries",
"into",
"the",
"package"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/package/core.py#L372-L427 | train | 50,707 |
Metatab/metapack | metapack/package/core.py | PackageBuilder._load_documentation_files | def _load_documentation_files(self):
"""Copy all of the Datafile """
for t in self.doc.find(['Root.Documentation', 'Root.Image', 'Root.Notebook']):
resource = self._get_ref_contents(t)
if not resource:
continue
if t.term_is('Root.Documentation'):
# Prefer the slugified title to the base name, because in cases of collections
# of many data releases, like annual datasets, documentation files may all have the same name,
# but the titles should be different.
real_name_base, ext = splitext(resource.resource_file)
name = t.get_value('name') if t.get_value('name') else real_name_base
real_name = slugify(name) + ext
self._load_documentation(t, resource.read(), resource.resource_file)
# Root.Readme is a special term added from Jupyter notebooks, so README files
# can be generated for packages.
t = self.doc.find_first('Root.Readme')
if t and (t.value or '').strip():
# Since the text is comming from a notebook, it probably does not have a title
t['title'] = 'Readme'
readme = '# '+ (self.doc.get_value('Root.Title') or '').strip()
if self.doc.description:
readme += '\n\n' + (self.doc.description or '').strip()
if (t.value or '').strip():
readme += '\n\n' +(t.value or '').strip()
self._load_documentation(t, readme.encode('utf8'), 'README.md') | python | def _load_documentation_files(self):
"""Copy all of the Datafile """
for t in self.doc.find(['Root.Documentation', 'Root.Image', 'Root.Notebook']):
resource = self._get_ref_contents(t)
if not resource:
continue
if t.term_is('Root.Documentation'):
# Prefer the slugified title to the base name, because in cases of collections
# of many data releases, like annual datasets, documentation files may all have the same name,
# but the titles should be different.
real_name_base, ext = splitext(resource.resource_file)
name = t.get_value('name') if t.get_value('name') else real_name_base
real_name = slugify(name) + ext
self._load_documentation(t, resource.read(), resource.resource_file)
# Root.Readme is a special term added from Jupyter notebooks, so README files
# can be generated for packages.
t = self.doc.find_first('Root.Readme')
if t and (t.value or '').strip():
# Since the text is comming from a notebook, it probably does not have a title
t['title'] = 'Readme'
readme = '# '+ (self.doc.get_value('Root.Title') or '').strip()
if self.doc.description:
readme += '\n\n' + (self.doc.description or '').strip()
if (t.value or '').strip():
readme += '\n\n' +(t.value or '').strip()
self._load_documentation(t, readme.encode('utf8'), 'README.md') | [
"def",
"_load_documentation_files",
"(",
"self",
")",
":",
"for",
"t",
"in",
"self",
".",
"doc",
".",
"find",
"(",
"[",
"'Root.Documentation'",
",",
"'Root.Image'",
",",
"'Root.Notebook'",
"]",
")",
":",
"resource",
"=",
"self",
".",
"_get_ref_contents",
"("... | Copy all of the Datafile | [
"Copy",
"all",
"of",
"the",
"Datafile"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/package/core.py#L491-L528 | train | 50,708 |
Metatab/metapack | metapack/package/core.py | PackageBuilder._load_files | def _load_files(self):
"""Load other files"""
def copy_dir(path):
for (dr, _, files) in walk(path):
for fn in files:
if '__pycache__' in fn:
continue
relpath = dr.replace(self.source_dir, '').strip('/')
src = parse_app_url(join(dr, fn))
dest = join(relpath, fn)
resource = src.get_resource()
self._load_file( dest, resource.read())
for term in self.resources(term = 'Root.Pythonlib'):
uv = parse_app_url(term.value)
ur = parse_app_url(self.source_dir)
# In the case that the input doc is a file, and the ref is to a file,
# try interpreting the file as relative.
if ur.proto == 'file' and uv.proto == 'file':
# Either a file or a directory
path = join(self.source_dir, uv.path)
if isdir(path):
copy_dir(path)
else:
# Load it as a URL
f = self._get_ref_contents(term)
try:
self._load_file(term.value,f.read() )
except Exception as e:
raise PackageError("Failed to load file for '{}': {} ".format(term.value, e))
nb_dir = join(self.source_dir, 'notebooks')
if exists(nb_dir) and isdir(nb_dir):
copy_dir(nb_dir) | python | def _load_files(self):
"""Load other files"""
def copy_dir(path):
for (dr, _, files) in walk(path):
for fn in files:
if '__pycache__' in fn:
continue
relpath = dr.replace(self.source_dir, '').strip('/')
src = parse_app_url(join(dr, fn))
dest = join(relpath, fn)
resource = src.get_resource()
self._load_file( dest, resource.read())
for term in self.resources(term = 'Root.Pythonlib'):
uv = parse_app_url(term.value)
ur = parse_app_url(self.source_dir)
# In the case that the input doc is a file, and the ref is to a file,
# try interpreting the file as relative.
if ur.proto == 'file' and uv.proto == 'file':
# Either a file or a directory
path = join(self.source_dir, uv.path)
if isdir(path):
copy_dir(path)
else:
# Load it as a URL
f = self._get_ref_contents(term)
try:
self._load_file(term.value,f.read() )
except Exception as e:
raise PackageError("Failed to load file for '{}': {} ".format(term.value, e))
nb_dir = join(self.source_dir, 'notebooks')
if exists(nb_dir) and isdir(nb_dir):
copy_dir(nb_dir) | [
"def",
"_load_files",
"(",
"self",
")",
":",
"def",
"copy_dir",
"(",
"path",
")",
":",
"for",
"(",
"dr",
",",
"_",
",",
"files",
")",
"in",
"walk",
"(",
"path",
")",
":",
"for",
"fn",
"in",
"files",
":",
"if",
"'__pycache__'",
"in",
"fn",
":",
... | Load other files | [
"Load",
"other",
"files"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/package/core.py#L534-L577 | train | 50,709 |
Metatab/metapack | metapack/support/pylib.py | row_generator | def row_generator(resource, doc, env, *args, **kwargs):
""" An example row generator function.
Reference this function in a Metatab file as the value of a Datafile:
Datafile: python:pylib#row_generator
The function must yield rows, with the first being headers, and subsequenct rows being data.
:param resource: The Datafile term being processed
:param doc: The Metatab document that contains the term being processed
:param args: Positional arguments passed to the generator
:param kwargs: Keyword arguments passed to the generator
:return:
The env argument is a dict with these environmental keys:
* CACHE_DIR
* RESOURCE_NAME
* RESOLVED_URL
* WORKING_DIR
* METATAB_DOC
* METATAB_WORKING_DIR
* METATAB_PACKAGE
It also contains key/value pairs for all of the properties of the resource.
"""
yield 'a b c'.split()
for i in range(10):
yield [i, i*2, i*3] | python | def row_generator(resource, doc, env, *args, **kwargs):
""" An example row generator function.
Reference this function in a Metatab file as the value of a Datafile:
Datafile: python:pylib#row_generator
The function must yield rows, with the first being headers, and subsequenct rows being data.
:param resource: The Datafile term being processed
:param doc: The Metatab document that contains the term being processed
:param args: Positional arguments passed to the generator
:param kwargs: Keyword arguments passed to the generator
:return:
The env argument is a dict with these environmental keys:
* CACHE_DIR
* RESOURCE_NAME
* RESOLVED_URL
* WORKING_DIR
* METATAB_DOC
* METATAB_WORKING_DIR
* METATAB_PACKAGE
It also contains key/value pairs for all of the properties of the resource.
"""
yield 'a b c'.split()
for i in range(10):
yield [i, i*2, i*3] | [
"def",
"row_generator",
"(",
"resource",
",",
"doc",
",",
"env",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"yield",
"'a b c'",
".",
"split",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"10",
")",
":",
"yield",
"[",
"i",
",",
"i",
"*",
... | An example row generator function.
Reference this function in a Metatab file as the value of a Datafile:
Datafile: python:pylib#row_generator
The function must yield rows, with the first being headers, and subsequenct rows being data.
:param resource: The Datafile term being processed
:param doc: The Metatab document that contains the term being processed
:param args: Positional arguments passed to the generator
:param kwargs: Keyword arguments passed to the generator
:return:
The env argument is a dict with these environmental keys:
* CACHE_DIR
* RESOURCE_NAME
* RESOLVED_URL
* WORKING_DIR
* METATAB_DOC
* METATAB_WORKING_DIR
* METATAB_PACKAGE
It also contains key/value pairs for all of the properties of the resource. | [
"An",
"example",
"row",
"generator",
"function",
"."
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/support/pylib.py#L4-L37 | train | 50,710 |
Metatab/metapack | metapack/support/pylib.py | example_transform | def example_transform(v, row, row_n, i_s, i_d, header_s, header_d,scratch, errors, accumulator):
""" An example column transform.
This is an example of a column transform with all of the arguments listed. An real transform
can omit any ( or all ) of these, and can supply them in any order; the calling code will inspect the
signature.
When the function is listed as a transform for a column, it is called for every row of data.
:param v: The current value of the column
:param row: A RowProxy object for the whiole row.
:param row_n: The current row number.
:param i_s: The numeric index of the source column
:param i_d: The numeric index for the destination column
:param header_s: The name of the source column
:param header_d: The name of the destination column
:param scratch: A dict that can be used for storing any values. Persists between rows.
:param errors: A dict used to store error messages. Persists for all columns in a row, but not between rows.
:param accumulator: A dict for use in accumulating values, such as computing aggregates.
:return: The final value to be supplied for the column.
"""
return str(v)+'-foo' | python | def example_transform(v, row, row_n, i_s, i_d, header_s, header_d,scratch, errors, accumulator):
""" An example column transform.
This is an example of a column transform with all of the arguments listed. An real transform
can omit any ( or all ) of these, and can supply them in any order; the calling code will inspect the
signature.
When the function is listed as a transform for a column, it is called for every row of data.
:param v: The current value of the column
:param row: A RowProxy object for the whiole row.
:param row_n: The current row number.
:param i_s: The numeric index of the source column
:param i_d: The numeric index for the destination column
:param header_s: The name of the source column
:param header_d: The name of the destination column
:param scratch: A dict that can be used for storing any values. Persists between rows.
:param errors: A dict used to store error messages. Persists for all columns in a row, but not between rows.
:param accumulator: A dict for use in accumulating values, such as computing aggregates.
:return: The final value to be supplied for the column.
"""
return str(v)+'-foo' | [
"def",
"example_transform",
"(",
"v",
",",
"row",
",",
"row_n",
",",
"i_s",
",",
"i_d",
",",
"header_s",
",",
"header_d",
",",
"scratch",
",",
"errors",
",",
"accumulator",
")",
":",
"return",
"str",
"(",
"v",
")",
"+",
"'-foo'"
] | An example column transform.
This is an example of a column transform with all of the arguments listed. An real transform
can omit any ( or all ) of these, and can supply them in any order; the calling code will inspect the
signature.
When the function is listed as a transform for a column, it is called for every row of data.
:param v: The current value of the column
:param row: A RowProxy object for the whiole row.
:param row_n: The current row number.
:param i_s: The numeric index of the source column
:param i_d: The numeric index for the destination column
:param header_s: The name of the source column
:param header_d: The name of the destination column
:param scratch: A dict that can be used for storing any values. Persists between rows.
:param errors: A dict used to store error messages. Persists for all columns in a row, but not between rows.
:param accumulator: A dict for use in accumulating values, such as computing aggregates.
:return: The final value to be supplied for the column. | [
"An",
"example",
"column",
"transform",
"."
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/support/pylib.py#L40-L62 | train | 50,711 |
Metatab/metapack | metapack/index.py | search_index_file | def search_index_file():
"""Return the default local index file, from the download cache"""
from metapack import Downloader
from os import environ
return environ.get('METAPACK_SEARCH_INDEX',
Downloader.get_instance().cache.getsyspath('index.json')) | python | def search_index_file():
"""Return the default local index file, from the download cache"""
from metapack import Downloader
from os import environ
return environ.get('METAPACK_SEARCH_INDEX',
Downloader.get_instance().cache.getsyspath('index.json')) | [
"def",
"search_index_file",
"(",
")",
":",
"from",
"metapack",
"import",
"Downloader",
"from",
"os",
"import",
"environ",
"return",
"environ",
".",
"get",
"(",
"'METAPACK_SEARCH_INDEX'",
",",
"Downloader",
".",
"get_instance",
"(",
")",
".",
"cache",
".",
"get... | Return the default local index file, from the download cache | [
"Return",
"the",
"default",
"local",
"index",
"file",
"from",
"the",
"download",
"cache"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/index.py#L15-L21 | train | 50,712 |
Metatab/metapack | metapack/index.py | SearchIndex.write | def write(self):
"""Safely write the index data to the index file """
index_file = self.path
new_index_file = index_file + '.new'
bak_index_file = index_file + '.bak'
if not self._db:
return
with open(new_index_file, 'w') as f:
json.dump(self._db, f, indent=4)
if exists(index_file):
copy(index_file, bak_index_file)
rename(new_index_file, index_file) | python | def write(self):
"""Safely write the index data to the index file """
index_file = self.path
new_index_file = index_file + '.new'
bak_index_file = index_file + '.bak'
if not self._db:
return
with open(new_index_file, 'w') as f:
json.dump(self._db, f, indent=4)
if exists(index_file):
copy(index_file, bak_index_file)
rename(new_index_file, index_file) | [
"def",
"write",
"(",
"self",
")",
":",
"index_file",
"=",
"self",
".",
"path",
"new_index_file",
"=",
"index_file",
"+",
"'.new'",
"bak_index_file",
"=",
"index_file",
"+",
"'.bak'",
"if",
"not",
"self",
".",
"_db",
":",
"return",
"with",
"open",
"(",
"n... | Safely write the index data to the index file | [
"Safely",
"write",
"the",
"index",
"data",
"to",
"the",
"index",
"file"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/index.py#L55-L70 | train | 50,713 |
Metatab/metapack | metapack/index.py | SearchIndex.update | def update(self,o):
"""Update from another index or index dict"""
self.open()
try:
self._db.update(o._db)
except AttributeError:
self._db.update(o) | python | def update(self,o):
"""Update from another index or index dict"""
self.open()
try:
self._db.update(o._db)
except AttributeError:
self._db.update(o) | [
"def",
"update",
"(",
"self",
",",
"o",
")",
":",
"self",
".",
"open",
"(",
")",
"try",
":",
"self",
".",
"_db",
".",
"update",
"(",
"o",
".",
"_db",
")",
"except",
"AttributeError",
":",
"self",
".",
"_db",
".",
"update",
"(",
"o",
")"
] | Update from another index or index dict | [
"Update",
"from",
"another",
"index",
"or",
"index",
"dict"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/index.py#L140-L148 | train | 50,714 |
ungarj/tilematrix | tilematrix/tmx/main.py | bounds | def bounds(ctx, tile):
"""Print Tile bounds."""
click.echo(
'%s %s %s %s' % TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
).tile(*tile).bounds(pixelbuffer=ctx.obj['pixelbuffer'])
) | python | def bounds(ctx, tile):
"""Print Tile bounds."""
click.echo(
'%s %s %s %s' % TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
).tile(*tile).bounds(pixelbuffer=ctx.obj['pixelbuffer'])
) | [
"def",
"bounds",
"(",
"ctx",
",",
"tile",
")",
":",
"click",
".",
"echo",
"(",
"'%s %s %s %s'",
"%",
"TilePyramid",
"(",
"ctx",
".",
"obj",
"[",
"'grid'",
"]",
",",
"tile_size",
"=",
"ctx",
".",
"obj",
"[",
"'tile_size'",
"]",
",",
"metatiling",
"=",... | Print Tile bounds. | [
"Print",
"Tile",
"bounds",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/tmx/main.py#L40-L48 | train | 50,715 |
ungarj/tilematrix | tilematrix/tmx/main.py | bbox | def bbox(ctx, tile):
"""Print Tile bounding box as geometry."""
geom = TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
).tile(*tile).bbox(pixelbuffer=ctx.obj['pixelbuffer'])
if ctx.obj['output_format'] in ['WKT', 'Tile']:
click.echo(geom)
elif ctx.obj['output_format'] == 'GeoJSON':
click.echo(geojson.dumps(geom)) | python | def bbox(ctx, tile):
"""Print Tile bounding box as geometry."""
geom = TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
).tile(*tile).bbox(pixelbuffer=ctx.obj['pixelbuffer'])
if ctx.obj['output_format'] in ['WKT', 'Tile']:
click.echo(geom)
elif ctx.obj['output_format'] == 'GeoJSON':
click.echo(geojson.dumps(geom)) | [
"def",
"bbox",
"(",
"ctx",
",",
"tile",
")",
":",
"geom",
"=",
"TilePyramid",
"(",
"ctx",
".",
"obj",
"[",
"'grid'",
"]",
",",
"tile_size",
"=",
"ctx",
".",
"obj",
"[",
"'tile_size'",
"]",
",",
"metatiling",
"=",
"ctx",
".",
"obj",
"[",
"'metatilin... | Print Tile bounding box as geometry. | [
"Print",
"Tile",
"bounding",
"box",
"as",
"geometry",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/tmx/main.py#L54-L64 | train | 50,716 |
ungarj/tilematrix | tilematrix/tmx/main.py | tile | def tile(ctx, point, zoom):
"""Print Tile containing POINT.."""
tile = TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
).tile_from_xy(*point, zoom=zoom)
if ctx.obj['output_format'] == 'Tile':
click.echo('%s %s %s' % tile.id)
elif ctx.obj['output_format'] == 'WKT':
click.echo(tile.bbox(pixelbuffer=ctx.obj['pixelbuffer']))
elif ctx.obj['output_format'] == 'GeoJSON':
click.echo(
geojson.dumps(
geojson.FeatureCollection([
geojson.Feature(
geometry=tile.bbox(pixelbuffer=ctx.obj['pixelbuffer']),
properties=dict(
zoom=tile.zoom,
row=tile.row,
col=tile.col
)
)
])
)
) | python | def tile(ctx, point, zoom):
"""Print Tile containing POINT.."""
tile = TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
).tile_from_xy(*point, zoom=zoom)
if ctx.obj['output_format'] == 'Tile':
click.echo('%s %s %s' % tile.id)
elif ctx.obj['output_format'] == 'WKT':
click.echo(tile.bbox(pixelbuffer=ctx.obj['pixelbuffer']))
elif ctx.obj['output_format'] == 'GeoJSON':
click.echo(
geojson.dumps(
geojson.FeatureCollection([
geojson.Feature(
geometry=tile.bbox(pixelbuffer=ctx.obj['pixelbuffer']),
properties=dict(
zoom=tile.zoom,
row=tile.row,
col=tile.col
)
)
])
)
) | [
"def",
"tile",
"(",
"ctx",
",",
"point",
",",
"zoom",
")",
":",
"tile",
"=",
"TilePyramid",
"(",
"ctx",
".",
"obj",
"[",
"'grid'",
"]",
",",
"tile_size",
"=",
"ctx",
".",
"obj",
"[",
"'tile_size'",
"]",
",",
"metatiling",
"=",
"ctx",
".",
"obj",
... | Print Tile containing POINT.. | [
"Print",
"Tile",
"containing",
"POINT",
".."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/tmx/main.py#L71-L96 | train | 50,717 |
ungarj/tilematrix | tilematrix/tmx/main.py | tiles | def tiles(ctx, bounds, zoom):
"""Print Tiles from bounds."""
tiles = TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
).tiles_from_bounds(bounds, zoom=zoom)
if ctx.obj['output_format'] == 'Tile':
for tile in tiles:
click.echo('%s %s %s' % tile.id)
elif ctx.obj['output_format'] == 'WKT':
for tile in tiles:
click.echo(tile.bbox(pixelbuffer=ctx.obj['pixelbuffer']))
elif ctx.obj['output_format'] == 'GeoJSON':
click.echo(
'{\n'
' "type": "FeatureCollection",\n'
' "features": ['
)
# print tiles as they come and only add comma if there is a next tile
try:
tile = next(tiles)
while True:
gj = ' %s' % geojson.Feature(
geometry=tile.bbox(pixelbuffer=ctx.obj['pixelbuffer']),
properties=dict(
zoom=tile.zoom,
row=tile.row,
col=tile.col
)
)
try:
tile = next(tiles)
click.echo(gj + ',')
except StopIteration:
click.echo(gj)
raise
except StopIteration:
pass
click.echo(
' ]\n'
'}'
) | python | def tiles(ctx, bounds, zoom):
"""Print Tiles from bounds."""
tiles = TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
).tiles_from_bounds(bounds, zoom=zoom)
if ctx.obj['output_format'] == 'Tile':
for tile in tiles:
click.echo('%s %s %s' % tile.id)
elif ctx.obj['output_format'] == 'WKT':
for tile in tiles:
click.echo(tile.bbox(pixelbuffer=ctx.obj['pixelbuffer']))
elif ctx.obj['output_format'] == 'GeoJSON':
click.echo(
'{\n'
' "type": "FeatureCollection",\n'
' "features": ['
)
# print tiles as they come and only add comma if there is a next tile
try:
tile = next(tiles)
while True:
gj = ' %s' % geojson.Feature(
geometry=tile.bbox(pixelbuffer=ctx.obj['pixelbuffer']),
properties=dict(
zoom=tile.zoom,
row=tile.row,
col=tile.col
)
)
try:
tile = next(tiles)
click.echo(gj + ',')
except StopIteration:
click.echo(gj)
raise
except StopIteration:
pass
click.echo(
' ]\n'
'}'
) | [
"def",
"tiles",
"(",
"ctx",
",",
"bounds",
",",
"zoom",
")",
":",
"tiles",
"=",
"TilePyramid",
"(",
"ctx",
".",
"obj",
"[",
"'grid'",
"]",
",",
"tile_size",
"=",
"ctx",
".",
"obj",
"[",
"'tile_size'",
"]",
",",
"metatiling",
"=",
"ctx",
".",
"obj",... | Print Tiles from bounds. | [
"Print",
"Tiles",
"from",
"bounds",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/tmx/main.py#L103-L145 | train | 50,718 |
ungarj/tilematrix | tilematrix/tmx/main.py | snap_bbox | def snap_bbox(ctx, bounds, zoom):
"""Snap bbox to tile grid."""
click.echo(box(*tilematrix.snap_bounds(
bounds=bounds,
tile_pyramid=TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
),
zoom=zoom,
pixelbuffer=ctx.obj['pixelbuffer']
))) | python | def snap_bbox(ctx, bounds, zoom):
"""Snap bbox to tile grid."""
click.echo(box(*tilematrix.snap_bounds(
bounds=bounds,
tile_pyramid=TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
),
zoom=zoom,
pixelbuffer=ctx.obj['pixelbuffer']
))) | [
"def",
"snap_bbox",
"(",
"ctx",
",",
"bounds",
",",
"zoom",
")",
":",
"click",
".",
"echo",
"(",
"box",
"(",
"*",
"tilematrix",
".",
"snap_bounds",
"(",
"bounds",
"=",
"bounds",
",",
"tile_pyramid",
"=",
"TilePyramid",
"(",
"ctx",
".",
"obj",
"[",
"'... | Snap bbox to tile grid. | [
"Snap",
"bbox",
"to",
"tile",
"grid",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/tmx/main.py#L170-L181 | train | 50,719 |
project-rig/rig | rig/place_and_route/place/rand.py | place | def place(vertices_resources, nets, machine, constraints,
random=default_random):
"""A random placer.
This algorithm performs uniform-random placement of vertices (completely
ignoring connectivty) and thus in the general case is likely to produce
very poor quality placements. It exists primarily as a baseline comparison
for placement quality and is probably of little value to most users.
Parameters
----------
random : :py:class:`random.Random`
Defaults to ``import random`` but can be set to your own instance of
:py:class:`random.Random` to allow you to control the seed and produce
deterministic results. For results to be deterministic,
vertices_resources must be supplied as an
:py:class:`collections.OrderedDict`.
"""
# Within the algorithm we modify the resource availability values in the
# machine to account for the effects of the current placement. As a result,
# an internal copy of the structure must be made.
machine = machine.copy()
# {vertex: (x, y), ...} gives the location of all vertices, updated
# throughout the function.
placements = {}
# Handle constraints
vertices_resources, nets, constraints, substitutions = \
apply_same_chip_constraints(vertices_resources, nets, constraints)
for constraint in constraints:
if isinstance(constraint, LocationConstraint):
# Location constraints are handled by recording the set of fixed
# vertex locations and subtracting their resources from the chips
# they're allocated to.
location = constraint.location
if location not in machine:
raise InvalidConstraintError(
"Chip requested by {} unavailable".format(machine))
vertex = constraint.vertex
# Record the constrained vertex's location
placements[vertex] = location
# Make sure the vertex fits at the requested location (updating the
# resource availability after placement)
resources = vertices_resources[vertex]
machine[location] = subtract_resources(machine[location],
resources)
if overallocated(machine[location]):
raise InsufficientResourceError(
"Cannot meet {}".format(constraint))
elif isinstance(constraint, # pragma: no branch
ReserveResourceConstraint):
apply_reserve_resource_constraint(machine, constraint)
# The set of vertices which have not been constrained.
movable_vertices = [v for v in vertices_resources
if v not in placements]
locations = set(machine)
for vertex in movable_vertices:
# Keep choosing random chips until we find one where the vertex fits.
while True:
if len(locations) == 0:
raise InsufficientResourceError(
"Ran out of chips while attempting to place vertex "
"{}".format(vertex))
location = random.sample(locations, 1)[0]
resources_if_placed = subtract_resources(
machine[location], vertices_resources[vertex])
if overallocated(resources_if_placed):
# The vertex won't fit on this chip, we'll assume it is full
# and not try it in the future.
locations.remove(location)
else:
# The vertex fits: record the resources consumed and move on to
# the next vertex.
placements[vertex] = location
machine[location] = resources_if_placed
break
finalise_same_chip_constraints(substitutions, placements)
return placements | python | def place(vertices_resources, nets, machine, constraints,
random=default_random):
"""A random placer.
This algorithm performs uniform-random placement of vertices (completely
ignoring connectivty) and thus in the general case is likely to produce
very poor quality placements. It exists primarily as a baseline comparison
for placement quality and is probably of little value to most users.
Parameters
----------
random : :py:class:`random.Random`
Defaults to ``import random`` but can be set to your own instance of
:py:class:`random.Random` to allow you to control the seed and produce
deterministic results. For results to be deterministic,
vertices_resources must be supplied as an
:py:class:`collections.OrderedDict`.
"""
# Within the algorithm we modify the resource availability values in the
# machine to account for the effects of the current placement. As a result,
# an internal copy of the structure must be made.
machine = machine.copy()
# {vertex: (x, y), ...} gives the location of all vertices, updated
# throughout the function.
placements = {}
# Handle constraints
vertices_resources, nets, constraints, substitutions = \
apply_same_chip_constraints(vertices_resources, nets, constraints)
for constraint in constraints:
if isinstance(constraint, LocationConstraint):
# Location constraints are handled by recording the set of fixed
# vertex locations and subtracting their resources from the chips
# they're allocated to.
location = constraint.location
if location not in machine:
raise InvalidConstraintError(
"Chip requested by {} unavailable".format(machine))
vertex = constraint.vertex
# Record the constrained vertex's location
placements[vertex] = location
# Make sure the vertex fits at the requested location (updating the
# resource availability after placement)
resources = vertices_resources[vertex]
machine[location] = subtract_resources(machine[location],
resources)
if overallocated(machine[location]):
raise InsufficientResourceError(
"Cannot meet {}".format(constraint))
elif isinstance(constraint, # pragma: no branch
ReserveResourceConstraint):
apply_reserve_resource_constraint(machine, constraint)
# The set of vertices which have not been constrained.
movable_vertices = [v for v in vertices_resources
if v not in placements]
locations = set(machine)
for vertex in movable_vertices:
# Keep choosing random chips until we find one where the vertex fits.
while True:
if len(locations) == 0:
raise InsufficientResourceError(
"Ran out of chips while attempting to place vertex "
"{}".format(vertex))
location = random.sample(locations, 1)[0]
resources_if_placed = subtract_resources(
machine[location], vertices_resources[vertex])
if overallocated(resources_if_placed):
# The vertex won't fit on this chip, we'll assume it is full
# and not try it in the future.
locations.remove(location)
else:
# The vertex fits: record the resources consumed and move on to
# the next vertex.
placements[vertex] = location
machine[location] = resources_if_placed
break
finalise_same_chip_constraints(substitutions, placements)
return placements | [
"def",
"place",
"(",
"vertices_resources",
",",
"nets",
",",
"machine",
",",
"constraints",
",",
"random",
"=",
"default_random",
")",
":",
"# Within the algorithm we modify the resource availability values in the",
"# machine to account for the effects of the current placement. As... | A random placer.
This algorithm performs uniform-random placement of vertices (completely
ignoring connectivty) and thus in the general case is likely to produce
very poor quality placements. It exists primarily as a baseline comparison
for placement quality and is probably of little value to most users.
Parameters
----------
random : :py:class:`random.Random`
Defaults to ``import random`` but can be set to your own instance of
:py:class:`random.Random` to allow you to control the seed and produce
deterministic results. For results to be deterministic,
vertices_resources must be supplied as an
:py:class:`collections.OrderedDict`. | [
"A",
"random",
"placer",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/rand.py#L19-L106 | train | 50,720 |
project-rig/rig | rig/place_and_route/place/sa/algorithm.py | _initial_placement | def _initial_placement(movable_vertices, vertices_resources, machine, random):
"""For internal use. Produces a random, sequential initial placement,
updating the resource availabilities of every core in the supplied machine.
Parameters
----------
movable_vertices : {vertex, ...}
A set of the vertices to be given a random initial placement.
vertices_resources : {vertex: {resource: value, ...}, ...}
machine : :py:class:`rig.place_and_route.Machine`
A machine object describing the machine into which the vertices should
be placed.
All chips hosting fixed vertices should have a chip_resource_exceptions
entry which accounts for the allocated resources.
When this function returns, the machine.chip_resource_exceptions will
be updated to account for the resources consumed by the initial
placement of movable vertices.
random : :py:class`random.Random`
The random number generator to use
Returns
-------
{vertex: (x, y), ...}
For all movable_vertices.
Raises
------
InsufficientResourceError
InvalidConstraintError
"""
# Initially fill chips in the system in a random order
locations = list(machine)
random.shuffle(locations)
location_iter = iter(locations)
# Greedily place the vertices in a random order
movable_vertices = list(v for v in vertices_resources
if v in movable_vertices)
random.shuffle(movable_vertices)
vertex_iter = iter(movable_vertices)
placement = {}
try:
location = next(location_iter)
except StopIteration:
raise InsufficientResourceError("No working chips in system.")
while True:
# Get a vertex to place
try:
vertex = next(vertex_iter)
except StopIteration:
# All vertices have been placed
break
# Advance through the set of available locations until we find a chip
# where the vertex fits
while True:
resources_if_placed = subtract_resources(
machine[location], vertices_resources[vertex])
if overallocated(resources_if_placed):
# The vertex won't fit on this chip, move onto the next chip
try:
location = next(location_iter)
continue
except StopIteration:
raise InsufficientResourceError(
"Ran out of chips while attempting to place vertex "
"{}".format(vertex))
else:
# The vertex fits: record the resources consumed and move on to
# the next vertex.
placement[vertex] = location
machine[location] = resources_if_placed
break
return placement | python | def _initial_placement(movable_vertices, vertices_resources, machine, random):
"""For internal use. Produces a random, sequential initial placement,
updating the resource availabilities of every core in the supplied machine.
Parameters
----------
movable_vertices : {vertex, ...}
A set of the vertices to be given a random initial placement.
vertices_resources : {vertex: {resource: value, ...}, ...}
machine : :py:class:`rig.place_and_route.Machine`
A machine object describing the machine into which the vertices should
be placed.
All chips hosting fixed vertices should have a chip_resource_exceptions
entry which accounts for the allocated resources.
When this function returns, the machine.chip_resource_exceptions will
be updated to account for the resources consumed by the initial
placement of movable vertices.
random : :py:class`random.Random`
The random number generator to use
Returns
-------
{vertex: (x, y), ...}
For all movable_vertices.
Raises
------
InsufficientResourceError
InvalidConstraintError
"""
# Initially fill chips in the system in a random order
locations = list(machine)
random.shuffle(locations)
location_iter = iter(locations)
# Greedily place the vertices in a random order
movable_vertices = list(v for v in vertices_resources
if v in movable_vertices)
random.shuffle(movable_vertices)
vertex_iter = iter(movable_vertices)
placement = {}
try:
location = next(location_iter)
except StopIteration:
raise InsufficientResourceError("No working chips in system.")
while True:
# Get a vertex to place
try:
vertex = next(vertex_iter)
except StopIteration:
# All vertices have been placed
break
# Advance through the set of available locations until we find a chip
# where the vertex fits
while True:
resources_if_placed = subtract_resources(
machine[location], vertices_resources[vertex])
if overallocated(resources_if_placed):
# The vertex won't fit on this chip, move onto the next chip
try:
location = next(location_iter)
continue
except StopIteration:
raise InsufficientResourceError(
"Ran out of chips while attempting to place vertex "
"{}".format(vertex))
else:
# The vertex fits: record the resources consumed and move on to
# the next vertex.
placement[vertex] = location
machine[location] = resources_if_placed
break
return placement | [
"def",
"_initial_placement",
"(",
"movable_vertices",
",",
"vertices_resources",
",",
"machine",
",",
"random",
")",
":",
"# Initially fill chips in the system in a random order",
"locations",
"=",
"list",
"(",
"machine",
")",
"random",
".",
"shuffle",
"(",
"locations",... | For internal use. Produces a random, sequential initial placement,
updating the resource availabilities of every core in the supplied machine.
Parameters
----------
movable_vertices : {vertex, ...}
A set of the vertices to be given a random initial placement.
vertices_resources : {vertex: {resource: value, ...}, ...}
machine : :py:class:`rig.place_and_route.Machine`
A machine object describing the machine into which the vertices should
be placed.
All chips hosting fixed vertices should have a chip_resource_exceptions
entry which accounts for the allocated resources.
When this function returns, the machine.chip_resource_exceptions will
be updated to account for the resources consumed by the initial
placement of movable vertices.
random : :py:class`random.Random`
The random number generator to use
Returns
-------
{vertex: (x, y), ...}
For all movable_vertices.
Raises
------
InsufficientResourceError
InvalidConstraintError | [
"For",
"internal",
"use",
".",
"Produces",
"a",
"random",
"sequential",
"initial",
"placement",
"updating",
"the",
"resource",
"availabilities",
"of",
"every",
"core",
"in",
"the",
"supplied",
"machine",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/sa/algorithm.py#L39-L117 | train | 50,721 |
Metatab/metapack | metapack/html.py | _bibliography | def _bibliography(doc, terms, converters=[], format='html'):
"""
Render citations, from a document or a doct of dicts
If the input is a dict, each key is the name of the citation, and the value is a BibTex
formatted dict
:param doc: A MetatabDoc, or a dict of BibTex dicts
:return:
"""
output_backend = 'latex' if format == 'latex' else MetatabHtmlBackend
def mk_cite(v):
for c in converters:
r = c(v)
if r is not False:
return r
return make_citation_dict(v)
if isinstance(doc, MetatabDoc):
# This doesn't work for LaTex, b/c the formatter adds the prologue and epilogue to eery entry
d = [mk_cite(t) for t in terms]
cd = {e['name_link']: e for e in d}
else:
cd = {k: mk_cite(v, i) for i, (k, v) in enumerate(doc.items())}
# for k, v in cd.items():
# print (k, v)
return PybtexEngine().format_from_string(safe_dump({'entries': cd}),
style=MetatabStyle,
output_backend=output_backend,
bib_format='yaml') | python | def _bibliography(doc, terms, converters=[], format='html'):
"""
Render citations, from a document or a doct of dicts
If the input is a dict, each key is the name of the citation, and the value is a BibTex
formatted dict
:param doc: A MetatabDoc, or a dict of BibTex dicts
:return:
"""
output_backend = 'latex' if format == 'latex' else MetatabHtmlBackend
def mk_cite(v):
for c in converters:
r = c(v)
if r is not False:
return r
return make_citation_dict(v)
if isinstance(doc, MetatabDoc):
# This doesn't work for LaTex, b/c the formatter adds the prologue and epilogue to eery entry
d = [mk_cite(t) for t in terms]
cd = {e['name_link']: e for e in d}
else:
cd = {k: mk_cite(v, i) for i, (k, v) in enumerate(doc.items())}
# for k, v in cd.items():
# print (k, v)
return PybtexEngine().format_from_string(safe_dump({'entries': cd}),
style=MetatabStyle,
output_backend=output_backend,
bib_format='yaml') | [
"def",
"_bibliography",
"(",
"doc",
",",
"terms",
",",
"converters",
"=",
"[",
"]",
",",
"format",
"=",
"'html'",
")",
":",
"output_backend",
"=",
"'latex'",
"if",
"format",
"==",
"'latex'",
"else",
"MetatabHtmlBackend",
"def",
"mk_cite",
"(",
"v",
")",
... | Render citations, from a document or a doct of dicts
If the input is a dict, each key is the name of the citation, and the value is a BibTex
formatted dict
:param doc: A MetatabDoc, or a dict of BibTex dicts
:return: | [
"Render",
"citations",
"from",
"a",
"document",
"or",
"a",
"doct",
"of",
"dicts"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/html.py#L310-L349 | train | 50,722 |
Metatab/metapack | metapack/html.py | markdown | def markdown(doc, title=True, template='short_documentation.md'):
"""Markdown, specifically for the Notes field in a CKAN dataset"""
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader('metapack', 'support/templates')
#autoescape=select_autoescape(['html', 'xml'])
)
context = display_context(doc)
return env.get_template(template).render(**context) | python | def markdown(doc, title=True, template='short_documentation.md'):
"""Markdown, specifically for the Notes field in a CKAN dataset"""
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader('metapack', 'support/templates')
#autoescape=select_autoescape(['html', 'xml'])
)
context = display_context(doc)
return env.get_template(template).render(**context) | [
"def",
"markdown",
"(",
"doc",
",",
"title",
"=",
"True",
",",
"template",
"=",
"'short_documentation.md'",
")",
":",
"from",
"jinja2",
"import",
"Environment",
",",
"PackageLoader",
",",
"select_autoescape",
"env",
"=",
"Environment",
"(",
"loader",
"=",
"Pac... | Markdown, specifically for the Notes field in a CKAN dataset | [
"Markdown",
"specifically",
"for",
"the",
"Notes",
"field",
"in",
"a",
"CKAN",
"dataset"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/html.py#L621-L632 | train | 50,723 |
project-rig/rig | rig/place_and_route/place/breadth_first.py | breadth_first_vertex_order | def breadth_first_vertex_order(vertices_resources, nets):
"""A generator which iterates over a set of vertices in a breadth-first
order in terms of connectivity.
For use as a vertex ordering for the sequential placer.
"""
# Special case: no vertices, just stop immediately
if len(vertices_resources) == 0:
return
# Enumerate the set of nets attached to each vertex
vertex_neighbours = defaultdict(set)
for net in nets:
# Note: Iterating over a Net object produces the set of vertices
# involved in the net.
vertex_neighbours[net.source].update(net)
for sink in net.sinks:
vertex_neighbours[sink].update(net)
# Perform a breadth-first iteration over the vertices.
unplaced_vertices = set(vertices_resources)
vertex_queue = deque()
while vertex_queue or unplaced_vertices:
if not vertex_queue:
vertex_queue.append(unplaced_vertices.pop())
vertex = vertex_queue.popleft()
yield vertex
vertex_queue.extend(v for v in vertex_neighbours[vertex]
if v in unplaced_vertices)
unplaced_vertices.difference_update(vertex_neighbours[vertex]) | python | def breadth_first_vertex_order(vertices_resources, nets):
"""A generator which iterates over a set of vertices in a breadth-first
order in terms of connectivity.
For use as a vertex ordering for the sequential placer.
"""
# Special case: no vertices, just stop immediately
if len(vertices_resources) == 0:
return
# Enumerate the set of nets attached to each vertex
vertex_neighbours = defaultdict(set)
for net in nets:
# Note: Iterating over a Net object produces the set of vertices
# involved in the net.
vertex_neighbours[net.source].update(net)
for sink in net.sinks:
vertex_neighbours[sink].update(net)
# Perform a breadth-first iteration over the vertices.
unplaced_vertices = set(vertices_resources)
vertex_queue = deque()
while vertex_queue or unplaced_vertices:
if not vertex_queue:
vertex_queue.append(unplaced_vertices.pop())
vertex = vertex_queue.popleft()
yield vertex
vertex_queue.extend(v for v in vertex_neighbours[vertex]
if v in unplaced_vertices)
unplaced_vertices.difference_update(vertex_neighbours[vertex]) | [
"def",
"breadth_first_vertex_order",
"(",
"vertices_resources",
",",
"nets",
")",
":",
"# Special case: no vertices, just stop immediately",
"if",
"len",
"(",
"vertices_resources",
")",
"==",
"0",
":",
"return",
"# Enumerate the set of nets attached to each vertex",
"vertex_nei... | A generator which iterates over a set of vertices in a breadth-first
order in terms of connectivity.
For use as a vertex ordering for the sequential placer. | [
"A",
"generator",
"which",
"iterates",
"over",
"a",
"set",
"of",
"vertices",
"in",
"a",
"breadth",
"-",
"first",
"order",
"in",
"terms",
"of",
"connectivity",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/breadth_first.py#L8-L39 | train | 50,724 |
project-rig/rig | rig/place_and_route/place/breadth_first.py | place | def place(vertices_resources, nets, machine, constraints, chip_order=None):
"""Places vertices in breadth-first order onto chips in the machine.
This is a thin wrapper around the :py:func:`sequential
<rig.place_and_route.place.sequential.place>` placement algorithm which
uses the :py:func:`breadth_first_vertex_order` vertex ordering.
Parameters
----------
chip_order : None or iterable
The order in which chips should be tried as a candidate location for a
vertex. See the :py:func:`sequential
<rig.place_and_route.place.sequential.place>` placer's argument of the
same name.
"""
return sequential_place(vertices_resources, nets,
machine, constraints,
breadth_first_vertex_order(vertices_resources,
nets),
chip_order) | python | def place(vertices_resources, nets, machine, constraints, chip_order=None):
"""Places vertices in breadth-first order onto chips in the machine.
This is a thin wrapper around the :py:func:`sequential
<rig.place_and_route.place.sequential.place>` placement algorithm which
uses the :py:func:`breadth_first_vertex_order` vertex ordering.
Parameters
----------
chip_order : None or iterable
The order in which chips should be tried as a candidate location for a
vertex. See the :py:func:`sequential
<rig.place_and_route.place.sequential.place>` placer's argument of the
same name.
"""
return sequential_place(vertices_resources, nets,
machine, constraints,
breadth_first_vertex_order(vertices_resources,
nets),
chip_order) | [
"def",
"place",
"(",
"vertices_resources",
",",
"nets",
",",
"machine",
",",
"constraints",
",",
"chip_order",
"=",
"None",
")",
":",
"return",
"sequential_place",
"(",
"vertices_resources",
",",
"nets",
",",
"machine",
",",
"constraints",
",",
"breadth_first_ve... | Places vertices in breadth-first order onto chips in the machine.
This is a thin wrapper around the :py:func:`sequential
<rig.place_and_route.place.sequential.place>` placement algorithm which
uses the :py:func:`breadth_first_vertex_order` vertex ordering.
Parameters
----------
chip_order : None or iterable
The order in which chips should be tried as a candidate location for a
vertex. See the :py:func:`sequential
<rig.place_and_route.place.sequential.place>` placer's argument of the
same name. | [
"Places",
"vertices",
"in",
"breadth",
"-",
"first",
"order",
"onto",
"chips",
"in",
"the",
"machine",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/breadth_first.py#L42-L61 | train | 50,725 |
TC01/python-xkcd | xkcd.py | Comic.download | def download(self, output="", outputFile="", silent=True):
""" Downloads the image of the comic onto your computer.
Arguments:
output: the output directory where comics will be downloaded to. The
default argument for 'output is the empty string; if the empty
string is passed, it defaults to a "Downloads" directory in your home folder
(this directory will be created if it does not exist).
outputFile: the filename that will be written. If the empty string
is passed, outputFile will default to a string of the form xkcd-(comic number)-(image filename),
so for example, xkcd-1691-optimization.png.
silent: boolean, defaults to True. If set to False, an error will be printed
to standard output should the provided integer argument not be valid.
Returns the path to the downloaded file, or an empty string in the event
of failure."""
image = urllib.urlopen(self.imageLink).read()
#Process optional input to work out where the dowload will go and what it'll be called
if output != "":
output = os.path.abspath(os.path.expanduser(output))
if output == "" or not os.path.exists(output):
output = os.path.expanduser(os.path.join("~", "Downloads"))
# Create ~/Downloads if it doesn't exist, since this is the default path.
if not os.path.exists(output):
os.mkdir(output)
if outputFile == "":
outputFile = "xkcd-" + str(self.number) + "-" + self.imageName
output = os.path.join(output, outputFile)
try:
download = open(output, 'wb')
except:
if not silent:
print("Unable to make file " + output)
return ""
download.write(image)
download.close()
return output | python | def download(self, output="", outputFile="", silent=True):
""" Downloads the image of the comic onto your computer.
Arguments:
output: the output directory where comics will be downloaded to. The
default argument for 'output is the empty string; if the empty
string is passed, it defaults to a "Downloads" directory in your home folder
(this directory will be created if it does not exist).
outputFile: the filename that will be written. If the empty string
is passed, outputFile will default to a string of the form xkcd-(comic number)-(image filename),
so for example, xkcd-1691-optimization.png.
silent: boolean, defaults to True. If set to False, an error will be printed
to standard output should the provided integer argument not be valid.
Returns the path to the downloaded file, or an empty string in the event
of failure."""
image = urllib.urlopen(self.imageLink).read()
#Process optional input to work out where the dowload will go and what it'll be called
if output != "":
output = os.path.abspath(os.path.expanduser(output))
if output == "" or not os.path.exists(output):
output = os.path.expanduser(os.path.join("~", "Downloads"))
# Create ~/Downloads if it doesn't exist, since this is the default path.
if not os.path.exists(output):
os.mkdir(output)
if outputFile == "":
outputFile = "xkcd-" + str(self.number) + "-" + self.imageName
output = os.path.join(output, outputFile)
try:
download = open(output, 'wb')
except:
if not silent:
print("Unable to make file " + output)
return ""
download.write(image)
download.close()
return output | [
"def",
"download",
"(",
"self",
",",
"output",
"=",
"\"\"",
",",
"outputFile",
"=",
"\"\"",
",",
"silent",
"=",
"True",
")",
":",
"image",
"=",
"urllib",
".",
"urlopen",
"(",
"self",
".",
"imageLink",
")",
".",
"read",
"(",
")",
"#Process optional inpu... | Downloads the image of the comic onto your computer.
Arguments:
output: the output directory where comics will be downloaded to. The
default argument for 'output is the empty string; if the empty
string is passed, it defaults to a "Downloads" directory in your home folder
(this directory will be created if it does not exist).
outputFile: the filename that will be written. If the empty string
is passed, outputFile will default to a string of the form xkcd-(comic number)-(image filename),
so for example, xkcd-1691-optimization.png.
silent: boolean, defaults to True. If set to False, an error will be printed
to standard output should the provided integer argument not be valid.
Returns the path to the downloaded file, or an empty string in the event
of failure. | [
"Downloads",
"the",
"image",
"of",
"the",
"comic",
"onto",
"your",
"computer",
"."
] | 6998d4073507eea228185e02ad1d9071c77fa955 | https://github.com/TC01/python-xkcd/blob/6998d4073507eea228185e02ad1d9071c77fa955/xkcd.py#L277-L317 | train | 50,726 |
project-rig/rig | setup.py | replace_local_hyperlinks | def replace_local_hyperlinks(
text, base_url="https://github.com/project-rig/rig/blob/master/"):
"""Replace local hyperlinks in RST with absolute addresses using the given
base URL.
This is used to make links in the long description function correctly
outside of the repository (e.g. when published on PyPi).
NOTE: This may need adjusting if further syntax is used.
"""
def get_new_url(url):
return base_url + url[2:]
# Deal with anonymous URLS
for match in re.finditer(r"^__ (?P<url>\./.*)", text, re.MULTILINE):
orig_url = match.groupdict()["url"]
url = get_new_url(orig_url)
text = re.sub("^__ {}".format(orig_url),
"__ {}".format(url), text, flags=re.MULTILINE)
# Deal with named URLS
for match in re.finditer(r"^\.\. _(?P<identifier>[^:]*): (?P<url>\./.*)",
text, re.MULTILINE):
identifier = match.groupdict()["identifier"]
orig_url = match.groupdict()["url"]
url = get_new_url(orig_url)
text = re.sub(
"^\.\. _{}: {}".format(identifier, orig_url),
".. _{}: {}".format(identifier, url),
text, flags=re.MULTILINE)
# Deal with image URLS
for match in re.finditer(r"^\.\. image:: (?P<url>\./.*)",
text, re.MULTILINE):
orig_url = match.groupdict()["url"]
url = get_new_url(orig_url)
text = text.replace(".. image:: {}".format(orig_url),
".. image:: {}".format(url))
return text | python | def replace_local_hyperlinks(
text, base_url="https://github.com/project-rig/rig/blob/master/"):
"""Replace local hyperlinks in RST with absolute addresses using the given
base URL.
This is used to make links in the long description function correctly
outside of the repository (e.g. when published on PyPi).
NOTE: This may need adjusting if further syntax is used.
"""
def get_new_url(url):
return base_url + url[2:]
# Deal with anonymous URLS
for match in re.finditer(r"^__ (?P<url>\./.*)", text, re.MULTILINE):
orig_url = match.groupdict()["url"]
url = get_new_url(orig_url)
text = re.sub("^__ {}".format(orig_url),
"__ {}".format(url), text, flags=re.MULTILINE)
# Deal with named URLS
for match in re.finditer(r"^\.\. _(?P<identifier>[^:]*): (?P<url>\./.*)",
text, re.MULTILINE):
identifier = match.groupdict()["identifier"]
orig_url = match.groupdict()["url"]
url = get_new_url(orig_url)
text = re.sub(
"^\.\. _{}: {}".format(identifier, orig_url),
".. _{}: {}".format(identifier, url),
text, flags=re.MULTILINE)
# Deal with image URLS
for match in re.finditer(r"^\.\. image:: (?P<url>\./.*)",
text, re.MULTILINE):
orig_url = match.groupdict()["url"]
url = get_new_url(orig_url)
text = text.replace(".. image:: {}".format(orig_url),
".. image:: {}".format(url))
return text | [
"def",
"replace_local_hyperlinks",
"(",
"text",
",",
"base_url",
"=",
"\"https://github.com/project-rig/rig/blob/master/\"",
")",
":",
"def",
"get_new_url",
"(",
"url",
")",
":",
"return",
"base_url",
"+",
"url",
"[",
"2",
":",
"]",
"# Deal with anonymous URLS",
"fo... | Replace local hyperlinks in RST with absolute addresses using the given
base URL.
This is used to make links in the long description function correctly
outside of the repository (e.g. when published on PyPi).
NOTE: This may need adjusting if further syntax is used. | [
"Replace",
"local",
"hyperlinks",
"in",
"RST",
"with",
"absolute",
"addresses",
"using",
"the",
"given",
"base",
"URL",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/setup.py#L13-L55 | train | 50,727 |
Metatab/metapack | metapack/cli/index.py | dump_index | def dump_index(args, idx):
"""Create a metatab file for the index"""
import csv
import sys
from metatab import MetatabDoc
doc = MetatabDoc()
pack_section = doc.new_section('Packages', ['Identifier', 'Name', 'Nvname', 'Version', 'Format'])
r = doc['Root']
r.new_term('Root.Title', 'Package Index')
for p in idx.list():
pack_section.new_term('Package',
p['url'],
identifier=p['ident'],
name=p['name'],
nvname=p['nvname'],
version=p['version'],
format=p['format'])
doc.write_csv(args.dump) | python | def dump_index(args, idx):
"""Create a metatab file for the index"""
import csv
import sys
from metatab import MetatabDoc
doc = MetatabDoc()
pack_section = doc.new_section('Packages', ['Identifier', 'Name', 'Nvname', 'Version', 'Format'])
r = doc['Root']
r.new_term('Root.Title', 'Package Index')
for p in idx.list():
pack_section.new_term('Package',
p['url'],
identifier=p['ident'],
name=p['name'],
nvname=p['nvname'],
version=p['version'],
format=p['format'])
doc.write_csv(args.dump) | [
"def",
"dump_index",
"(",
"args",
",",
"idx",
")",
":",
"import",
"csv",
"import",
"sys",
"from",
"metatab",
"import",
"MetatabDoc",
"doc",
"=",
"MetatabDoc",
"(",
")",
"pack_section",
"=",
"doc",
".",
"new_section",
"(",
"'Packages'",
",",
"[",
"'Identifi... | Create a metatab file for the index | [
"Create",
"a",
"metatab",
"file",
"for",
"the",
"index"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/cli/index.py#L223-L248 | train | 50,728 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/layer2.py | Layer2Agent._process_added_port_event | def _process_added_port_event(self, port_name):
"""Callback for added ports."""
LOG.info("Hyper-V VM vNIC added: %s", port_name)
self._added_ports.add(port_name) | python | def _process_added_port_event(self, port_name):
"""Callback for added ports."""
LOG.info("Hyper-V VM vNIC added: %s", port_name)
self._added_ports.add(port_name) | [
"def",
"_process_added_port_event",
"(",
"self",
",",
"port_name",
")",
":",
"LOG",
".",
"info",
"(",
"\"Hyper-V VM vNIC added: %s\"",
",",
"port_name",
")",
"self",
".",
"_added_ports",
".",
"add",
"(",
"port_name",
")"
] | Callback for added ports. | [
"Callback",
"for",
"added",
"ports",
"."
] | 7a89306ab0586c95b99debb44d898f70834508b9 | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L125-L128 | train | 50,729 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/layer2.py | Layer2Agent._load_physical_network_mappings | def _load_physical_network_mappings(self, phys_net_vswitch_mappings):
"""Load all the information regarding the physical network."""
for mapping in phys_net_vswitch_mappings:
parts = mapping.split(':')
if len(parts) != 2:
LOG.debug('Invalid physical network mapping: %s', mapping)
else:
pattern = re.escape(parts[0].strip()).replace('\\*', '.*')
pattern = pattern + '$'
vswitch = parts[1].strip()
self._physical_network_mappings[pattern] = vswitch | python | def _load_physical_network_mappings(self, phys_net_vswitch_mappings):
"""Load all the information regarding the physical network."""
for mapping in phys_net_vswitch_mappings:
parts = mapping.split(':')
if len(parts) != 2:
LOG.debug('Invalid physical network mapping: %s', mapping)
else:
pattern = re.escape(parts[0].strip()).replace('\\*', '.*')
pattern = pattern + '$'
vswitch = parts[1].strip()
self._physical_network_mappings[pattern] = vswitch | [
"def",
"_load_physical_network_mappings",
"(",
"self",
",",
"phys_net_vswitch_mappings",
")",
":",
"for",
"mapping",
"in",
"phys_net_vswitch_mappings",
":",
"parts",
"=",
"mapping",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"parts",
")",
"!=",
"2",
":",... | Load all the information regarding the physical network. | [
"Load",
"all",
"the",
"information",
"regarding",
"the",
"physical",
"network",
"."
] | 7a89306ab0586c95b99debb44d898f70834508b9 | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L134-L144 | train | 50,730 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/layer2.py | Layer2Agent._get_vswitch_name | def _get_vswitch_name(self, network_type, physical_network):
"""Get the vswitch name for the received network information."""
if network_type != constants.TYPE_LOCAL:
vswitch_name = self._get_vswitch_for_physical_network(
physical_network)
else:
vswitch_name = self._local_network_vswitch
if vswitch_name:
return vswitch_name
err_msg = _("No vSwitch configured for physical network "
"'%(physical_network)s'. Neutron network type: "
"'%(network_type)s'.")
raise exception.NetworkingHyperVException(
err_msg % dict(physical_network=physical_network,
network_type=network_type)) | python | def _get_vswitch_name(self, network_type, physical_network):
"""Get the vswitch name for the received network information."""
if network_type != constants.TYPE_LOCAL:
vswitch_name = self._get_vswitch_for_physical_network(
physical_network)
else:
vswitch_name = self._local_network_vswitch
if vswitch_name:
return vswitch_name
err_msg = _("No vSwitch configured for physical network "
"'%(physical_network)s'. Neutron network type: "
"'%(network_type)s'.")
raise exception.NetworkingHyperVException(
err_msg % dict(physical_network=physical_network,
network_type=network_type)) | [
"def",
"_get_vswitch_name",
"(",
"self",
",",
"network_type",
",",
"physical_network",
")",
":",
"if",
"network_type",
"!=",
"constants",
".",
"TYPE_LOCAL",
":",
"vswitch_name",
"=",
"self",
".",
"_get_vswitch_for_physical_network",
"(",
"physical_network",
")",
"el... | Get the vswitch name for the received network information. | [
"Get",
"the",
"vswitch",
"name",
"for",
"the",
"received",
"network",
"information",
"."
] | 7a89306ab0586c95b99debb44d898f70834508b9 | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L189-L205 | train | 50,731 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/layer2.py | Layer2Agent._get_vswitch_for_physical_network | def _get_vswitch_for_physical_network(self, phys_network_name):
"""Get the vswitch name for the received network name."""
for pattern in self._physical_network_mappings:
if phys_network_name is None:
phys_network_name = ''
if re.match(pattern, phys_network_name):
return self._physical_network_mappings[pattern] | python | def _get_vswitch_for_physical_network(self, phys_network_name):
"""Get the vswitch name for the received network name."""
for pattern in self._physical_network_mappings:
if phys_network_name is None:
phys_network_name = ''
if re.match(pattern, phys_network_name):
return self._physical_network_mappings[pattern] | [
"def",
"_get_vswitch_for_physical_network",
"(",
"self",
",",
"phys_network_name",
")",
":",
"for",
"pattern",
"in",
"self",
".",
"_physical_network_mappings",
":",
"if",
"phys_network_name",
"is",
"None",
":",
"phys_network_name",
"=",
"''",
"if",
"re",
".",
"mat... | Get the vswitch name for the received network name. | [
"Get",
"the",
"vswitch",
"name",
"for",
"the",
"received",
"network",
"name",
"."
] | 7a89306ab0586c95b99debb44d898f70834508b9 | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L207-L213 | train | 50,732 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/layer2.py | Layer2Agent._get_network_vswitch_map_by_port_id | def _get_network_vswitch_map_by_port_id(self, port_id):
"""Get the vswitch name for the received port id."""
for network_id, vswitch in six.iteritems(self._network_vswitch_map):
if port_id in vswitch['ports']:
return (network_id, vswitch)
# If the port was not found, just return (None, None)
return (None, None) | python | def _get_network_vswitch_map_by_port_id(self, port_id):
"""Get the vswitch name for the received port id."""
for network_id, vswitch in six.iteritems(self._network_vswitch_map):
if port_id in vswitch['ports']:
return (network_id, vswitch)
# If the port was not found, just return (None, None)
return (None, None) | [
"def",
"_get_network_vswitch_map_by_port_id",
"(",
"self",
",",
"port_id",
")",
":",
"for",
"network_id",
",",
"vswitch",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_network_vswitch_map",
")",
":",
"if",
"port_id",
"in",
"vswitch",
"[",
"'ports'",
"]",
... | Get the vswitch name for the received port id. | [
"Get",
"the",
"vswitch",
"name",
"for",
"the",
"received",
"port",
"id",
"."
] | 7a89306ab0586c95b99debb44d898f70834508b9 | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L215-L222 | train | 50,733 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/layer2.py | Layer2Agent._update_port_status_cache | def _update_port_status_cache(self, device, device_bound=True):
"""Update the ports status cache."""
with self._cache_lock:
if device_bound:
self._bound_ports.add(device)
self._unbound_ports.discard(device)
else:
self._bound_ports.discard(device)
self._unbound_ports.add(device) | python | def _update_port_status_cache(self, device, device_bound=True):
"""Update the ports status cache."""
with self._cache_lock:
if device_bound:
self._bound_ports.add(device)
self._unbound_ports.discard(device)
else:
self._bound_ports.discard(device)
self._unbound_ports.add(device) | [
"def",
"_update_port_status_cache",
"(",
"self",
",",
"device",
",",
"device_bound",
"=",
"True",
")",
":",
"with",
"self",
".",
"_cache_lock",
":",
"if",
"device_bound",
":",
"self",
".",
"_bound_ports",
".",
"add",
"(",
"device",
")",
"self",
".",
"_unbo... | Update the ports status cache. | [
"Update",
"the",
"ports",
"status",
"cache",
"."
] | 7a89306ab0586c95b99debb44d898f70834508b9 | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L224-L232 | train | 50,734 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/layer2.py | Layer2Agent._create_event_listeners | def _create_event_listeners(self):
"""Create and bind the event listeners."""
LOG.debug("Create the event listeners.")
for event_type, callback in self._event_callback_pairs:
LOG.debug("Create listener for %r event", event_type)
listener = self._utils.get_vnic_event_listener(event_type)
eventlet.spawn_n(listener, callback) | python | def _create_event_listeners(self):
"""Create and bind the event listeners."""
LOG.debug("Create the event listeners.")
for event_type, callback in self._event_callback_pairs:
LOG.debug("Create listener for %r event", event_type)
listener = self._utils.get_vnic_event_listener(event_type)
eventlet.spawn_n(listener, callback) | [
"def",
"_create_event_listeners",
"(",
"self",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Create the event listeners.\"",
")",
"for",
"event_type",
",",
"callback",
"in",
"self",
".",
"_event_callback_pairs",
":",
"LOG",
".",
"debug",
"(",
"\"Create listener for %r even... | Create and bind the event listeners. | [
"Create",
"and",
"bind",
"the",
"event",
"listeners",
"."
] | 7a89306ab0586c95b99debb44d898f70834508b9 | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L234-L240 | train | 50,735 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/layer2.py | Layer2Agent.process_added_port | def process_added_port(self, device_details):
"""Process the new ports.
Wraps _process_added_port, and treats the sucessful and exception
cases.
"""
device = device_details['device']
port_id = device_details['port_id']
reprocess = True
try:
self._process_added_port(device_details)
LOG.debug("Updating cached port %s status as UP.", port_id)
self._update_port_status_cache(device, device_bound=True)
LOG.info("Port %s processed.", port_id)
except os_win_exc.HyperVvNicNotFound:
LOG.debug('vNIC %s not found. This can happen if the VM was '
'destroyed.', port_id)
reprocess = False
except os_win_exc.HyperVPortNotFoundException:
LOG.debug('vSwitch port %s not found. This can happen if the VM '
'was destroyed.', port_id)
# NOTE(claudiub): just to be on the safe side, in case Hyper-V said
# that the port was added, but it hasn't really, we're leaving
# reprocess = True. If the VM / vNIC was removed, on the next
# reprocess, a HyperVvNicNotFound will be raised.
except Exception as ex:
# NOTE(claudiub): in case of a non-transient error, the port will
# be processed over and over again, and will not be reported as
# bound (e.g.: InvalidParameterValue when setting QoS), until the
# port is deleted. These issues have to be investigated and solved
LOG.exception("Exception encountered while processing "
"port %(port_id)s. Exception: %(ex)s",
dict(port_id=port_id, ex=ex))
else:
# no exception encountered, no need to reprocess.
reprocess = False
if reprocess:
# Readd the port as "added", so it can be reprocessed.
self._added_ports.add(device)
# Force cache refresh.
self._refresh_cache = True
return False
return True | python | def process_added_port(self, device_details):
"""Process the new ports.
Wraps _process_added_port, and treats the sucessful and exception
cases.
"""
device = device_details['device']
port_id = device_details['port_id']
reprocess = True
try:
self._process_added_port(device_details)
LOG.debug("Updating cached port %s status as UP.", port_id)
self._update_port_status_cache(device, device_bound=True)
LOG.info("Port %s processed.", port_id)
except os_win_exc.HyperVvNicNotFound:
LOG.debug('vNIC %s not found. This can happen if the VM was '
'destroyed.', port_id)
reprocess = False
except os_win_exc.HyperVPortNotFoundException:
LOG.debug('vSwitch port %s not found. This can happen if the VM '
'was destroyed.', port_id)
# NOTE(claudiub): just to be on the safe side, in case Hyper-V said
# that the port was added, but it hasn't really, we're leaving
# reprocess = True. If the VM / vNIC was removed, on the next
# reprocess, a HyperVvNicNotFound will be raised.
except Exception as ex:
# NOTE(claudiub): in case of a non-transient error, the port will
# be processed over and over again, and will not be reported as
# bound (e.g.: InvalidParameterValue when setting QoS), until the
# port is deleted. These issues have to be investigated and solved
LOG.exception("Exception encountered while processing "
"port %(port_id)s. Exception: %(ex)s",
dict(port_id=port_id, ex=ex))
else:
# no exception encountered, no need to reprocess.
reprocess = False
if reprocess:
# Readd the port as "added", so it can be reprocessed.
self._added_ports.add(device)
# Force cache refresh.
self._refresh_cache = True
return False
return True | [
"def",
"process_added_port",
"(",
"self",
",",
"device_details",
")",
":",
"device",
"=",
"device_details",
"[",
"'device'",
"]",
"port_id",
"=",
"device_details",
"[",
"'port_id'",
"]",
"reprocess",
"=",
"True",
"try",
":",
"self",
".",
"_process_added_port",
... | Process the new ports.
Wraps _process_added_port, and treats the sucessful and exception
cases. | [
"Process",
"the",
"new",
"ports",
"."
] | 7a89306ab0586c95b99debb44d898f70834508b9 | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L304-L350 | train | 50,736 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/layer2.py | Layer2Agent._treat_devices_added | def _treat_devices_added(self):
"""Process the new devices."""
try:
devices_details_list = self._plugin_rpc.get_devices_details_list(
self._context, self._added_ports, self._agent_id)
except Exception as exc:
LOG.debug("Unable to get ports details for "
"devices %(devices)s: %(exc)s",
{'devices': self._added_ports, 'exc': exc})
return
for device_details in devices_details_list:
device = device_details['device']
LOG.info("Adding port %s", device)
if 'port_id' in device_details:
LOG.info("Port %(device)s updated. "
"Details: %(device_details)s",
{'device': device, 'device_details': device_details})
eventlet.spawn_n(self.process_added_port, device_details)
else:
LOG.debug("Missing port_id from device details: "
"%(device)s. Details: %(device_details)s",
{'device': device, 'device_details': device_details})
LOG.debug("Remove the port from added ports set, so it "
"doesn't get reprocessed.")
self._added_ports.discard(device) | python | def _treat_devices_added(self):
"""Process the new devices."""
try:
devices_details_list = self._plugin_rpc.get_devices_details_list(
self._context, self._added_ports, self._agent_id)
except Exception as exc:
LOG.debug("Unable to get ports details for "
"devices %(devices)s: %(exc)s",
{'devices': self._added_ports, 'exc': exc})
return
for device_details in devices_details_list:
device = device_details['device']
LOG.info("Adding port %s", device)
if 'port_id' in device_details:
LOG.info("Port %(device)s updated. "
"Details: %(device_details)s",
{'device': device, 'device_details': device_details})
eventlet.spawn_n(self.process_added_port, device_details)
else:
LOG.debug("Missing port_id from device details: "
"%(device)s. Details: %(device_details)s",
{'device': device, 'device_details': device_details})
LOG.debug("Remove the port from added ports set, so it "
"doesn't get reprocessed.")
self._added_ports.discard(device) | [
"def",
"_treat_devices_added",
"(",
"self",
")",
":",
"try",
":",
"devices_details_list",
"=",
"self",
".",
"_plugin_rpc",
".",
"get_devices_details_list",
"(",
"self",
".",
"_context",
",",
"self",
".",
"_added_ports",
",",
"self",
".",
"_agent_id",
")",
"exc... | Process the new devices. | [
"Process",
"the",
"new",
"devices",
"."
] | 7a89306ab0586c95b99debb44d898f70834508b9 | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L352-L378 | train | 50,737 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/layer2.py | Layer2Agent._process_removed_port | def _process_removed_port(self, device):
"""Process the removed ports."""
LOG.debug("Trying to remove the port %r", device)
self._update_port_status_cache(device, device_bound=False)
self._port_unbound(device, vnic_deleted=True)
LOG.debug("The port was successfully removed.")
self._removed_ports.discard(device) | python | def _process_removed_port(self, device):
"""Process the removed ports."""
LOG.debug("Trying to remove the port %r", device)
self._update_port_status_cache(device, device_bound=False)
self._port_unbound(device, vnic_deleted=True)
LOG.debug("The port was successfully removed.")
self._removed_ports.discard(device) | [
"def",
"_process_removed_port",
"(",
"self",
",",
"device",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Trying to remove the port %r\"",
",",
"device",
")",
"self",
".",
"_update_port_status_cache",
"(",
"device",
",",
"device_bound",
"=",
"False",
")",
"self",
".",
... | Process the removed ports. | [
"Process",
"the",
"removed",
"ports",
"."
] | 7a89306ab0586c95b99debb44d898f70834508b9 | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L380-L387 | train | 50,738 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/layer2.py | Layer2Agent._treat_devices_removed | def _treat_devices_removed(self):
"""Process the removed devices."""
for device in self._removed_ports.copy():
eventlet.spawn_n(self._process_removed_port, device) | python | def _treat_devices_removed(self):
"""Process the removed devices."""
for device in self._removed_ports.copy():
eventlet.spawn_n(self._process_removed_port, device) | [
"def",
"_treat_devices_removed",
"(",
"self",
")",
":",
"for",
"device",
"in",
"self",
".",
"_removed_ports",
".",
"copy",
"(",
")",
":",
"eventlet",
".",
"spawn_n",
"(",
"self",
".",
"_process_removed_port",
",",
"device",
")"
] | Process the removed devices. | [
"Process",
"the",
"removed",
"devices",
"."
] | 7a89306ab0586c95b99debb44d898f70834508b9 | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L389-L392 | train | 50,739 |
Metatab/metapack | metapack/cli/build.py | build | def build(subparsers):
"""
Build source packages.
The mp build program runs all of the resources listed in a Metatab file and
produces one or more Metapack packages with those resources localized. It
will always try to produce a Filesystem package, and may optionally produce
Excel, Zip and CSV packages.
Typical usage is to be run inside a source package directory with
.. code-block:: bash
$ mp build
To build all of the package types:
.. code-block:: bash
$ mp build -fezc
By default, packages are built with versioned names. The
:option:`--nonversion-name` option will create file packages with
non-versioned name, and the :option:`--nonversioned-link` option will
produce a non-versioned soft link pointing to the versioned file.
"""
parser = subparsers.add_parser(
'build',
help='Build derived packages',
description=build.__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='')
parser.set_defaults(run_command=run_metapack)
parser.add_argument('metatabfile', nargs='?',
help="Path or URL to a metatab file. If not provided, defaults to 'metadata.csv'. "
)
parser.add_argument('-p', '--profile', help="Name of a BOTO or AWS credentails profile", required=False)
parser.add_argument('-D', '--package-directory', help="Write Zip, Excel and CSV packages to an alternate directory",
required=False)
parser.add_argument('-F', '--force', action='store_true', default=False,
help='Force some operations, like updating the name and building packages')
parser.add_argument('-R', '--reuse-resources', action='store_true', default=False,
help='When building Filesystem package, try to reuse resources built in prior build')
group = parser.add_mutually_exclusive_group()
group.add_argument('-n', '--nonversion-name', action='store_true', default=False,
help='Write file packages with non-versioned names')
group.add_argument('-N', '--nonversion-link', action='store_true', default=False,
help='Create links with nonversioned names to file packages')
parser.set_defaults(handler=None)
##
## Derived Package Group
derived_group = parser.add_argument_group('Derived Packages', 'Generate other types of packages')
derived_group.add_argument('-e', '--excel', action='store_true', default=False,
help='Create an excel archive from a metatab file')
derived_group.add_argument('-z', '--zip', action='store_true', default=False,
help='Create a zip archive from a metatab file')
derived_group.add_argument('-f', '--filesystem', action='store_true', default=False,
help='Create a filesystem archive from a metatab file')
derived_group.add_argument('-c', '--csv', action='store_true', default=False,
help='Create a CSV archive from a metatab file')
##
## Administration Group
admin_group = parser.add_argument_group('Administration', 'Information and administration')
admin_group.add_argument('--clean-cache', default=False, action='store_true',
help="Clean the download cache")
admin_group.add_argument('-C', '--clean', default=False, action='store_true',
help="For some operations, like updating schemas, clear the section of existing terms first") | python | def build(subparsers):
"""
Build source packages.
The mp build program runs all of the resources listed in a Metatab file and
produces one or more Metapack packages with those resources localized. It
will always try to produce a Filesystem package, and may optionally produce
Excel, Zip and CSV packages.
Typical usage is to be run inside a source package directory with
.. code-block:: bash
$ mp build
To build all of the package types:
.. code-block:: bash
$ mp build -fezc
By default, packages are built with versioned names. The
:option:`--nonversion-name` option will create file packages with
non-versioned name, and the :option:`--nonversioned-link` option will
produce a non-versioned soft link pointing to the versioned file.
"""
parser = subparsers.add_parser(
'build',
help='Build derived packages',
description=build.__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='')
parser.set_defaults(run_command=run_metapack)
parser.add_argument('metatabfile', nargs='?',
help="Path or URL to a metatab file. If not provided, defaults to 'metadata.csv'. "
)
parser.add_argument('-p', '--profile', help="Name of a BOTO or AWS credentails profile", required=False)
parser.add_argument('-D', '--package-directory', help="Write Zip, Excel and CSV packages to an alternate directory",
required=False)
parser.add_argument('-F', '--force', action='store_true', default=False,
help='Force some operations, like updating the name and building packages')
parser.add_argument('-R', '--reuse-resources', action='store_true', default=False,
help='When building Filesystem package, try to reuse resources built in prior build')
group = parser.add_mutually_exclusive_group()
group.add_argument('-n', '--nonversion-name', action='store_true', default=False,
help='Write file packages with non-versioned names')
group.add_argument('-N', '--nonversion-link', action='store_true', default=False,
help='Create links with nonversioned names to file packages')
parser.set_defaults(handler=None)
##
## Derived Package Group
derived_group = parser.add_argument_group('Derived Packages', 'Generate other types of packages')
derived_group.add_argument('-e', '--excel', action='store_true', default=False,
help='Create an excel archive from a metatab file')
derived_group.add_argument('-z', '--zip', action='store_true', default=False,
help='Create a zip archive from a metatab file')
derived_group.add_argument('-f', '--filesystem', action='store_true', default=False,
help='Create a filesystem archive from a metatab file')
derived_group.add_argument('-c', '--csv', action='store_true', default=False,
help='Create a CSV archive from a metatab file')
##
## Administration Group
admin_group = parser.add_argument_group('Administration', 'Information and administration')
admin_group.add_argument('--clean-cache', default=False, action='store_true',
help="Clean the download cache")
admin_group.add_argument('-C', '--clean', default=False, action='store_true',
help="For some operations, like updating schemas, clear the section of existing terms first") | [
"def",
"build",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'build'",
",",
"help",
"=",
"'Build derived packages'",
",",
"description",
"=",
"build",
".",
"__doc__",
",",
"formatter_class",
"=",
"argparse",
".",
"RawDescr... | Build source packages.
The mp build program runs all of the resources listed in a Metatab file and
produces one or more Metapack packages with those resources localized. It
will always try to produce a Filesystem package, and may optionally produce
Excel, Zip and CSV packages.
Typical usage is to be run inside a source package directory with
.. code-block:: bash
$ mp build
To build all of the package types:
.. code-block:: bash
$ mp build -fezc
By default, packages are built with versioned names. The
:option:`--nonversion-name` option will create file packages with
non-versioned name, and the :option:`--nonversioned-link` option will
produce a non-versioned soft link pointing to the versioned file. | [
"Build",
"source",
"packages",
"."
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/cli/build.py#L34-L126 | train | 50,740 |
Metatab/metapack | metapack/cli/build.py | metatab_derived_handler | def metatab_derived_handler(m):
"""Create local Zip, Excel and Filesystem packages
:param m:
:param skip_if_exists:
:return:
"""
from metapack.exc import PackageError
from metapack.util import get_materialized_data_cache
from shutil import rmtree
create_list = []
url = None
doc = MetapackDoc(m.mt_file)
env = get_lib_module_dict(doc)
package_dir = m.package_root
if m.args.package_directory:
# If this is set, the FS package will be built to m.package_root, but the
# file packages will be built to package_dir
package_dir = parse_app_url(m.args.package_directory)
update_name(m.mt_file, fail_on_missing=False, report_unchanged=False)
process_schemas(m.mt_file, cache=m.cache, clean=m.args.clean, report_found=False)
nv_name = m.args.nonversion_name
nv_link = m.args.nonversion_link
# Remove any data that may have been cached , for instance, from Jupyter notebooks
rmtree(get_materialized_data_cache(doc), ignore_errors=True)
reuse_resources=m.args.reuse_resources
try:
# Always create a filesystem package before ZIP or Excel, so we can use it as a source for
# data for the other packages. This means that Transform processes and programs only need
# to be run once.
_, url, created = make_filesystem_package(m.mt_file, m.package_root, m.cache, env, m.args.force, False,
nv_link, reuse_resources=reuse_resources)
create_list.append(('fs', url, created))
lb_path = Path( m.package_root.fspath,'last_build')
if created or not lb_path.exists():
Path( m.package_root.fspath,'last_build').touch()
m.mt_file = url
env = {} # Don't need it anymore, since no more programs will be run.
if m.args.excel is not False:
_, url, created = make_excel_package(m.mt_file, package_dir, m.cache, env, m.args.force, nv_name, nv_link)
create_list.append(('xlsx', url, created))
if m.args.zip is not False:
_, url, created = make_zip_package(m.mt_file, package_dir, m.cache, env, m.args.force, nv_name, nv_link)
create_list.append(('zip', url, created))
if m.args.csv is not False:
_, url, created = make_csv_package(m.mt_file, package_dir, m.cache, env, m.args.force, nv_name, nv_link)
create_list.append(('csv', url, created))
except PackageError as e:
err("Failed to generate package: {}".format(e))
index_packages(m)
return create_list | python | def metatab_derived_handler(m):
"""Create local Zip, Excel and Filesystem packages
:param m:
:param skip_if_exists:
:return:
"""
from metapack.exc import PackageError
from metapack.util import get_materialized_data_cache
from shutil import rmtree
create_list = []
url = None
doc = MetapackDoc(m.mt_file)
env = get_lib_module_dict(doc)
package_dir = m.package_root
if m.args.package_directory:
# If this is set, the FS package will be built to m.package_root, but the
# file packages will be built to package_dir
package_dir = parse_app_url(m.args.package_directory)
update_name(m.mt_file, fail_on_missing=False, report_unchanged=False)
process_schemas(m.mt_file, cache=m.cache, clean=m.args.clean, report_found=False)
nv_name = m.args.nonversion_name
nv_link = m.args.nonversion_link
# Remove any data that may have been cached , for instance, from Jupyter notebooks
rmtree(get_materialized_data_cache(doc), ignore_errors=True)
reuse_resources=m.args.reuse_resources
try:
# Always create a filesystem package before ZIP or Excel, so we can use it as a source for
# data for the other packages. This means that Transform processes and programs only need
# to be run once.
_, url, created = make_filesystem_package(m.mt_file, m.package_root, m.cache, env, m.args.force, False,
nv_link, reuse_resources=reuse_resources)
create_list.append(('fs', url, created))
lb_path = Path( m.package_root.fspath,'last_build')
if created or not lb_path.exists():
Path( m.package_root.fspath,'last_build').touch()
m.mt_file = url
env = {} # Don't need it anymore, since no more programs will be run.
if m.args.excel is not False:
_, url, created = make_excel_package(m.mt_file, package_dir, m.cache, env, m.args.force, nv_name, nv_link)
create_list.append(('xlsx', url, created))
if m.args.zip is not False:
_, url, created = make_zip_package(m.mt_file, package_dir, m.cache, env, m.args.force, nv_name, nv_link)
create_list.append(('zip', url, created))
if m.args.csv is not False:
_, url, created = make_csv_package(m.mt_file, package_dir, m.cache, env, m.args.force, nv_name, nv_link)
create_list.append(('csv', url, created))
except PackageError as e:
err("Failed to generate package: {}".format(e))
index_packages(m)
return create_list | [
"def",
"metatab_derived_handler",
"(",
"m",
")",
":",
"from",
"metapack",
".",
"exc",
"import",
"PackageError",
"from",
"metapack",
".",
"util",
"import",
"get_materialized_data_cache",
"from",
"shutil",
"import",
"rmtree",
"create_list",
"=",
"[",
"]",
"url",
"... | Create local Zip, Excel and Filesystem packages
:param m:
:param skip_if_exists:
:return: | [
"Create",
"local",
"Zip",
"Excel",
"and",
"Filesystem",
"packages"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/cli/build.py#L161-L234 | train | 50,741 |
Metatab/metapack | metapack/jupyter/__init__.py | init | def init():
"""Initialize features that are normally initialized in the CLI"""
from metapack.appurl import SearchUrl
import metapack as mp
from os import environ
SearchUrl.initialize() # This makes the 'index:" urls work
mp.Downloader.context.update(environ) | python | def init():
"""Initialize features that are normally initialized in the CLI"""
from metapack.appurl import SearchUrl
import metapack as mp
from os import environ
SearchUrl.initialize() # This makes the 'index:" urls work
mp.Downloader.context.update(environ) | [
"def",
"init",
"(",
")",
":",
"from",
"metapack",
".",
"appurl",
"import",
"SearchUrl",
"import",
"metapack",
"as",
"mp",
"from",
"os",
"import",
"environ",
"SearchUrl",
".",
"initialize",
"(",
")",
"# This makes the 'index:\" urls work",
"mp",
".",
"Downloader"... | Initialize features that are normally initialized in the CLI | [
"Initialize",
"features",
"that",
"are",
"normally",
"initialized",
"in",
"the",
"CLI"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/__init__.py#L10-L18 | train | 50,742 |
project-rig/rig | rig/machine_control/struct_file.py | read_struct_file | def read_struct_file(struct_data):
"""Interpret a struct file defining the location of variables in memory.
Parameters
----------
struct_data : :py:class:`bytes`
String of :py:class:`bytes` containing data to interpret as the struct
definition.
Returns
-------
{struct_name: :py:class:`~.Struct`}
A dictionary mapping the struct name to a :py:class:`~.Struct`
instance. **Note:** the struct name will be a string of bytes, e.g.,
`b"vcpu"`.
"""
# Holders for all structs
structs = dict()
# Holders for the current struct
name = None
# Iterate over every line in the file
for i, l in enumerate(struct_data.splitlines()):
# Empty the line of comments, if the line is empty then skip to the
# next line. Split on whitespace to get the tokens.
tokens = re_comment.sub(b"", l).strip().split()
if len(tokens) == 0:
continue
elif len(tokens) == 3:
# 3 tokens implies header data
(key, _, value) = tokens
if key == b"name":
if name is not None:
if structs[name].size is None:
raise ValueError(
"size value missing for struct '{}'".format(name))
if structs[name].base is None:
raise ValueError(
"base value missing for struct '{}'".format(name))
name = value
structs[name] = Struct(name)
elif key == b"size":
structs[name].size = num(value)
elif key == b"base":
structs[name].base = num(value)
else:
raise ValueError(key)
elif len(tokens) == 5:
# 5 tokens implies entry in struct.
(field, pack, offset, printf, default) = tokens
# Convert the packing character from Perl to Python standard
num_pack = re_numbered_pack.match(pack)
if num_pack is not None:
pack = (num_pack.group("num") +
perl_to_python_packs[num_pack.group("char")])
else:
pack = perl_to_python_packs[pack]
# If the field is an array then extract the length
length = 1
field_exp = re_array_field.match(field)
if field_exp is not None:
field = field_exp.group("field")
length = num(field_exp.group("length"))
structs[name][field] = StructField(pack, num(offset), printf,
num(default), length)
else:
raise ValueError(
"line {}: Invalid syntax in struct file".format(i))
# Final check for setting size and base
if structs[name].size is None:
raise ValueError(
"size value missing for struct '{}'".format(name))
if structs[name].base is None:
raise ValueError(
"base value missing for struct '{}'".format(name))
return structs | python | def read_struct_file(struct_data):
"""Interpret a struct file defining the location of variables in memory.
Parameters
----------
struct_data : :py:class:`bytes`
String of :py:class:`bytes` containing data to interpret as the struct
definition.
Returns
-------
{struct_name: :py:class:`~.Struct`}
A dictionary mapping the struct name to a :py:class:`~.Struct`
instance. **Note:** the struct name will be a string of bytes, e.g.,
`b"vcpu"`.
"""
# Holders for all structs
structs = dict()
# Holders for the current struct
name = None
# Iterate over every line in the file
for i, l in enumerate(struct_data.splitlines()):
# Empty the line of comments, if the line is empty then skip to the
# next line. Split on whitespace to get the tokens.
tokens = re_comment.sub(b"", l).strip().split()
if len(tokens) == 0:
continue
elif len(tokens) == 3:
# 3 tokens implies header data
(key, _, value) = tokens
if key == b"name":
if name is not None:
if structs[name].size is None:
raise ValueError(
"size value missing for struct '{}'".format(name))
if structs[name].base is None:
raise ValueError(
"base value missing for struct '{}'".format(name))
name = value
structs[name] = Struct(name)
elif key == b"size":
structs[name].size = num(value)
elif key == b"base":
structs[name].base = num(value)
else:
raise ValueError(key)
elif len(tokens) == 5:
# 5 tokens implies entry in struct.
(field, pack, offset, printf, default) = tokens
# Convert the packing character from Perl to Python standard
num_pack = re_numbered_pack.match(pack)
if num_pack is not None:
pack = (num_pack.group("num") +
perl_to_python_packs[num_pack.group("char")])
else:
pack = perl_to_python_packs[pack]
# If the field is an array then extract the length
length = 1
field_exp = re_array_field.match(field)
if field_exp is not None:
field = field_exp.group("field")
length = num(field_exp.group("length"))
structs[name][field] = StructField(pack, num(offset), printf,
num(default), length)
else:
raise ValueError(
"line {}: Invalid syntax in struct file".format(i))
# Final check for setting size and base
if structs[name].size is None:
raise ValueError(
"size value missing for struct '{}'".format(name))
if structs[name].base is None:
raise ValueError(
"base value missing for struct '{}'".format(name))
return structs | [
"def",
"read_struct_file",
"(",
"struct_data",
")",
":",
"# Holders for all structs",
"structs",
"=",
"dict",
"(",
")",
"# Holders for the current struct",
"name",
"=",
"None",
"# Iterate over every line in the file",
"for",
"i",
",",
"l",
"in",
"enumerate",
"(",
"str... | Interpret a struct file defining the location of variables in memory.
Parameters
----------
struct_data : :py:class:`bytes`
String of :py:class:`bytes` containing data to interpret as the struct
definition.
Returns
-------
{struct_name: :py:class:`~.Struct`}
A dictionary mapping the struct name to a :py:class:`~.Struct`
instance. **Note:** the struct name will be a string of bytes, e.g.,
`b"vcpu"`. | [
"Interpret",
"a",
"struct",
"file",
"defining",
"the",
"location",
"of",
"variables",
"in",
"memory",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/struct_file.py#L9-L91 | train | 50,743 |
project-rig/rig | rig/machine_control/struct_file.py | num | def num(value):
"""Convert a value from one of several bases to an int."""
if re_hex_num.match(value):
return int(value, base=16)
else:
return int(value) | python | def num(value):
"""Convert a value from one of several bases to an int."""
if re_hex_num.match(value):
return int(value, base=16)
else:
return int(value) | [
"def",
"num",
"(",
"value",
")",
":",
"if",
"re_hex_num",
".",
"match",
"(",
"value",
")",
":",
"return",
"int",
"(",
"value",
",",
"base",
"=",
"16",
")",
"else",
":",
"return",
"int",
"(",
"value",
")"
] | Convert a value from one of several bases to an int. | [
"Convert",
"a",
"value",
"from",
"one",
"of",
"several",
"bases",
"to",
"an",
"int",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/struct_file.py#L101-L106 | train | 50,744 |
project-rig/rig | rig/machine_control/struct_file.py | Struct.update_default_values | def update_default_values(self, **updates):
"""Replace the default values of specified fields.
Parameters
----------
Parameters are taken as keyword-arguments of `field=new_value`.
Raises
------
KeyError
If a field doesn't exist in the struct.
"""
for (field, value) in six.iteritems(updates):
fname = six.b(field)
self[fname] = self[fname]._replace(default=value) | python | def update_default_values(self, **updates):
"""Replace the default values of specified fields.
Parameters
----------
Parameters are taken as keyword-arguments of `field=new_value`.
Raises
------
KeyError
If a field doesn't exist in the struct.
"""
for (field, value) in six.iteritems(updates):
fname = six.b(field)
self[fname] = self[fname]._replace(default=value) | [
"def",
"update_default_values",
"(",
"self",
",",
"*",
"*",
"updates",
")",
":",
"for",
"(",
"field",
",",
"value",
")",
"in",
"six",
".",
"iteritems",
"(",
"updates",
")",
":",
"fname",
"=",
"six",
".",
"b",
"(",
"field",
")",
"self",
"[",
"fname"... | Replace the default values of specified fields.
Parameters
----------
Parameters are taken as keyword-arguments of `field=new_value`.
Raises
------
KeyError
If a field doesn't exist in the struct. | [
"Replace",
"the",
"default",
"values",
"of",
"specified",
"fields",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/struct_file.py#L132-L146 | train | 50,745 |
NicolasLM/spinach | spinach/brokers/base.py | Broker.next_future_job_delta | def next_future_job_delta(self) -> Optional[float]:
"""Give the amount of seconds before the next future job is due."""
job = self._get_next_future_job()
if not job:
return None
return (job.at - datetime.now(timezone.utc)).total_seconds() | python | def next_future_job_delta(self) -> Optional[float]:
"""Give the amount of seconds before the next future job is due."""
job = self._get_next_future_job()
if not job:
return None
return (job.at - datetime.now(timezone.utc)).total_seconds() | [
"def",
"next_future_job_delta",
"(",
"self",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"job",
"=",
"self",
".",
"_get_next_future_job",
"(",
")",
"if",
"not",
"job",
":",
"return",
"None",
"return",
"(",
"job",
".",
"at",
"-",
"datetime",
".",
"no... | Give the amount of seconds before the next future job is due. | [
"Give",
"the",
"amount",
"of",
"seconds",
"before",
"the",
"next",
"future",
"job",
"is",
"due",
"."
] | 0122f916643101eab5cdc1f3da662b9446e372aa | https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/brokers/base.py#L102-L107 | train | 50,746 |
project-rig/rig | rig/machine_control/utils.py | sdram_alloc_for_vertices | def sdram_alloc_for_vertices(controller, placements, allocations,
core_as_tag=True, sdram_resource=SDRAM,
cores_resource=Cores, clear=False):
"""Allocate and return a file-like view of a region of SDRAM for each
vertex which uses SDRAM as a resource.
The tag assigned to each region of assigned SDRAM is the index of the
first core that each vertex is assigned. For example::
placements = {vertex: (0, 5)}
allocations = {vertex: {Cores: slice(3, 6),
SDRAM: slice(204, 304)}}
sdram_allocations = sdram_alloc_for_vertices(
controller, placements, allocations
)
Will allocate a 100-byte block of SDRAM for the vertex which is
allocated cores 3-5 on chip (0, 5). The region of SDRAM will be tagged
`3` (because this is the index of the first core).
Parameters
----------
controller : :py:class:`rig.machine_control.MachineController`
Controller to use to allocate the SDRAM.
placements : {vertex: (x, y), ...}
Mapping of vertices to the chips they have been placed on. Same as
produced by placers.
allocations : {vertex: {resource: allocation, ...}, ...}
Mapping of vertices to the resources they have been allocated.
A block of memory of the size specified by the `sdram_resource`
(default: :py:class:`~rig.place_and_route.SDRAM`) resource will be
allocated for each vertex. Note that location of the supplied
allocation is *not* used.
When `core_as_tag=True`, the tag allocated will be the ID of the first
core used by the vertex (indicated by the `cores_resource`, default
:py:class:`~rig.place_and_route.Cores`), otherwise the tag will be set
to 0.
clear : bool
If True the requested memory will be filled with zeros before the
pointer is returned. If False (the default) the memory will be left
as-is.
Other Parameters
----------------
core_as_tag : bool
Use the index of the first allocated core as the tag for the region of
memory, otherwise 0 will be used.
sdram_resource : resource (default :py:class:`~rig.place_and_route.SDRAM`)
Key used to indicate SDRAM usage in the resources dictionary.
cores_resource : resource (default :py:class:`~rig.place_and_route.Cores`)
Key used to indicate cores which have been allocated in the
allocations dictionary.
Returns
-------
{vertex: :py:class:`.MemoryIO`, ...}
A file-like object for each vertex which can be used to read and write
to the region of SDRAM allocated to the vertex.
Raises
------
rig.machine_control.machine_controller.SpiNNakerMemoryError
If the memory cannot be allocated, or a tag is already taken or
invalid.
"""
# For each vertex we perform an SDRAM alloc to get a file-like for
# the vertex.
vertex_memory = dict()
for vertex, allocs in six.iteritems(allocations):
if sdram_resource in allocs:
sdram_slice = allocs[sdram_resource]
assert sdram_slice.step is None
size = sdram_slice.stop - sdram_slice.start
x, y = placements[vertex]
if core_as_tag:
tag = allocs[cores_resource].start
else:
tag = 0
# Get the memory
vertex_memory[vertex] = controller.sdram_alloc_as_filelike(
size, tag, x=x, y=y, clear=clear
)
return vertex_memory | python | def sdram_alloc_for_vertices(controller, placements, allocations,
core_as_tag=True, sdram_resource=SDRAM,
cores_resource=Cores, clear=False):
"""Allocate and return a file-like view of a region of SDRAM for each
vertex which uses SDRAM as a resource.
The tag assigned to each region of assigned SDRAM is the index of the
first core that each vertex is assigned. For example::
placements = {vertex: (0, 5)}
allocations = {vertex: {Cores: slice(3, 6),
SDRAM: slice(204, 304)}}
sdram_allocations = sdram_alloc_for_vertices(
controller, placements, allocations
)
Will allocate a 100-byte block of SDRAM for the vertex which is
allocated cores 3-5 on chip (0, 5). The region of SDRAM will be tagged
`3` (because this is the index of the first core).
Parameters
----------
controller : :py:class:`rig.machine_control.MachineController`
Controller to use to allocate the SDRAM.
placements : {vertex: (x, y), ...}
Mapping of vertices to the chips they have been placed on. Same as
produced by placers.
allocations : {vertex: {resource: allocation, ...}, ...}
Mapping of vertices to the resources they have been allocated.
A block of memory of the size specified by the `sdram_resource`
(default: :py:class:`~rig.place_and_route.SDRAM`) resource will be
allocated for each vertex. Note that location of the supplied
allocation is *not* used.
When `core_as_tag=True`, the tag allocated will be the ID of the first
core used by the vertex (indicated by the `cores_resource`, default
:py:class:`~rig.place_and_route.Cores`), otherwise the tag will be set
to 0.
clear : bool
If True the requested memory will be filled with zeros before the
pointer is returned. If False (the default) the memory will be left
as-is.
Other Parameters
----------------
core_as_tag : bool
Use the index of the first allocated core as the tag for the region of
memory, otherwise 0 will be used.
sdram_resource : resource (default :py:class:`~rig.place_and_route.SDRAM`)
Key used to indicate SDRAM usage in the resources dictionary.
cores_resource : resource (default :py:class:`~rig.place_and_route.Cores`)
Key used to indicate cores which have been allocated in the
allocations dictionary.
Returns
-------
{vertex: :py:class:`.MemoryIO`, ...}
A file-like object for each vertex which can be used to read and write
to the region of SDRAM allocated to the vertex.
Raises
------
rig.machine_control.machine_controller.SpiNNakerMemoryError
If the memory cannot be allocated, or a tag is already taken or
invalid.
"""
# For each vertex we perform an SDRAM alloc to get a file-like for
# the vertex.
vertex_memory = dict()
for vertex, allocs in six.iteritems(allocations):
if sdram_resource in allocs:
sdram_slice = allocs[sdram_resource]
assert sdram_slice.step is None
size = sdram_slice.stop - sdram_slice.start
x, y = placements[vertex]
if core_as_tag:
tag = allocs[cores_resource].start
else:
tag = 0
# Get the memory
vertex_memory[vertex] = controller.sdram_alloc_as_filelike(
size, tag, x=x, y=y, clear=clear
)
return vertex_memory | [
"def",
"sdram_alloc_for_vertices",
"(",
"controller",
",",
"placements",
",",
"allocations",
",",
"core_as_tag",
"=",
"True",
",",
"sdram_resource",
"=",
"SDRAM",
",",
"cores_resource",
"=",
"Cores",
",",
"clear",
"=",
"False",
")",
":",
"# For each vertex we perf... | Allocate and return a file-like view of a region of SDRAM for each
vertex which uses SDRAM as a resource.
The tag assigned to each region of assigned SDRAM is the index of the
first core that each vertex is assigned. For example::
placements = {vertex: (0, 5)}
allocations = {vertex: {Cores: slice(3, 6),
SDRAM: slice(204, 304)}}
sdram_allocations = sdram_alloc_for_vertices(
controller, placements, allocations
)
Will allocate a 100-byte block of SDRAM for the vertex which is
allocated cores 3-5 on chip (0, 5). The region of SDRAM will be tagged
`3` (because this is the index of the first core).
Parameters
----------
controller : :py:class:`rig.machine_control.MachineController`
Controller to use to allocate the SDRAM.
placements : {vertex: (x, y), ...}
Mapping of vertices to the chips they have been placed on. Same as
produced by placers.
allocations : {vertex: {resource: allocation, ...}, ...}
Mapping of vertices to the resources they have been allocated.
A block of memory of the size specified by the `sdram_resource`
(default: :py:class:`~rig.place_and_route.SDRAM`) resource will be
allocated for each vertex. Note that location of the supplied
allocation is *not* used.
When `core_as_tag=True`, the tag allocated will be the ID of the first
core used by the vertex (indicated by the `cores_resource`, default
:py:class:`~rig.place_and_route.Cores`), otherwise the tag will be set
to 0.
clear : bool
If True the requested memory will be filled with zeros before the
pointer is returned. If False (the default) the memory will be left
as-is.
Other Parameters
----------------
core_as_tag : bool
Use the index of the first allocated core as the tag for the region of
memory, otherwise 0 will be used.
sdram_resource : resource (default :py:class:`~rig.place_and_route.SDRAM`)
Key used to indicate SDRAM usage in the resources dictionary.
cores_resource : resource (default :py:class:`~rig.place_and_route.Cores`)
Key used to indicate cores which have been allocated in the
allocations dictionary.
Returns
-------
{vertex: :py:class:`.MemoryIO`, ...}
A file-like object for each vertex which can be used to read and write
to the region of SDRAM allocated to the vertex.
Raises
------
rig.machine_control.machine_controller.SpiNNakerMemoryError
If the memory cannot be allocated, or a tag is already taken or
invalid. | [
"Allocate",
"and",
"return",
"a",
"file",
"-",
"like",
"view",
"of",
"a",
"region",
"of",
"SDRAM",
"for",
"each",
"vertex",
"which",
"uses",
"SDRAM",
"as",
"a",
"resource",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/utils.py#L6-L94 | train | 50,747 |
NicolasLM/spinach | spinach/job.py | advance_job_status | def advance_job_status(namespace: str, job: Job, duration: float,
err: Optional[Exception]):
"""Advance the status of a job depending on its execution.
This function is called after a job has been executed. It calculates its
next status and calls the appropriate signals.
"""
duration = human_duration(duration)
if not err:
job.status = JobStatus.SUCCEEDED
logger.info('Finished execution of %s in %s', job, duration)
return
if job.should_retry:
job.status = JobStatus.NOT_SET
job.retries += 1
if isinstance(err, RetryException) and err.at is not None:
job.at = err.at
else:
job.at = (datetime.now(timezone.utc) +
exponential_backoff(job.retries))
signals.job_schedule_retry.send(namespace, job=job, err=err)
log_args = (
job.retries, job.max_retries + 1, job, duration,
human_duration(
(job.at - datetime.now(tz=timezone.utc)).total_seconds()
)
)
if isinstance(err, RetryException):
logger.info('Retry requested during execution %d/%d of %s '
'after %s, retry in %s', *log_args)
else:
logger.warning('Error during execution %d/%d of %s after %s, '
'retry in %s', *log_args)
return
job.status = JobStatus.FAILED
signals.job_failed.send(namespace, job=job, err=err)
logger.error(
'Error during execution %d/%d of %s after %s',
job.max_retries + 1, job.max_retries + 1, job, duration,
exc_info=err
) | python | def advance_job_status(namespace: str, job: Job, duration: float,
err: Optional[Exception]):
"""Advance the status of a job depending on its execution.
This function is called after a job has been executed. It calculates its
next status and calls the appropriate signals.
"""
duration = human_duration(duration)
if not err:
job.status = JobStatus.SUCCEEDED
logger.info('Finished execution of %s in %s', job, duration)
return
if job.should_retry:
job.status = JobStatus.NOT_SET
job.retries += 1
if isinstance(err, RetryException) and err.at is not None:
job.at = err.at
else:
job.at = (datetime.now(timezone.utc) +
exponential_backoff(job.retries))
signals.job_schedule_retry.send(namespace, job=job, err=err)
log_args = (
job.retries, job.max_retries + 1, job, duration,
human_duration(
(job.at - datetime.now(tz=timezone.utc)).total_seconds()
)
)
if isinstance(err, RetryException):
logger.info('Retry requested during execution %d/%d of %s '
'after %s, retry in %s', *log_args)
else:
logger.warning('Error during execution %d/%d of %s after %s, '
'retry in %s', *log_args)
return
job.status = JobStatus.FAILED
signals.job_failed.send(namespace, job=job, err=err)
logger.error(
'Error during execution %d/%d of %s after %s',
job.max_retries + 1, job.max_retries + 1, job, duration,
exc_info=err
) | [
"def",
"advance_job_status",
"(",
"namespace",
":",
"str",
",",
"job",
":",
"Job",
",",
"duration",
":",
"float",
",",
"err",
":",
"Optional",
"[",
"Exception",
"]",
")",
":",
"duration",
"=",
"human_duration",
"(",
"duration",
")",
"if",
"not",
"err",
... | Advance the status of a job depending on its execution.
This function is called after a job has been executed. It calculates its
next status and calls the appropriate signals. | [
"Advance",
"the",
"status",
"of",
"a",
"job",
"depending",
"on",
"its",
"execution",
"."
] | 0122f916643101eab5cdc1f3da662b9446e372aa | https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/job.py#L152-L197 | train | 50,748 |
ungarj/tilematrix | tilematrix/_tilepyramid.py | TilePyramid.tile | def tile(self, zoom, row, col):
"""
Return Tile object of this TilePyramid.
- zoom: zoom level
- row: tile matrix row
- col: tile matrix column
"""
return Tile(self, zoom, row, col) | python | def tile(self, zoom, row, col):
"""
Return Tile object of this TilePyramid.
- zoom: zoom level
- row: tile matrix row
- col: tile matrix column
"""
return Tile(self, zoom, row, col) | [
"def",
"tile",
"(",
"self",
",",
"zoom",
",",
"row",
",",
"col",
")",
":",
"return",
"Tile",
"(",
"self",
",",
"zoom",
",",
"row",
",",
"col",
")"
] | Return Tile object of this TilePyramid.
- zoom: zoom level
- row: tile matrix row
- col: tile matrix column | [
"Return",
"Tile",
"object",
"of",
"this",
"TilePyramid",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tilepyramid.py#L62-L70 | train | 50,749 |
ungarj/tilematrix | tilematrix/_tilepyramid.py | TilePyramid.tile_x_size | def tile_x_size(self, zoom):
"""
Width of a tile in SRID units at zoom level.
- zoom: zoom level
"""
warnings.warn(DeprecationWarning("tile_x_size is deprecated"))
validate_zoom(zoom)
return round(self.x_size / self.matrix_width(zoom), ROUND) | python | def tile_x_size(self, zoom):
"""
Width of a tile in SRID units at zoom level.
- zoom: zoom level
"""
warnings.warn(DeprecationWarning("tile_x_size is deprecated"))
validate_zoom(zoom)
return round(self.x_size / self.matrix_width(zoom), ROUND) | [
"def",
"tile_x_size",
"(",
"self",
",",
"zoom",
")",
":",
"warnings",
".",
"warn",
"(",
"DeprecationWarning",
"(",
"\"tile_x_size is deprecated\"",
")",
")",
"validate_zoom",
"(",
"zoom",
")",
"return",
"round",
"(",
"self",
".",
"x_size",
"/",
"self",
".",
... | Width of a tile in SRID units at zoom level.
- zoom: zoom level | [
"Width",
"of",
"a",
"tile",
"in",
"SRID",
"units",
"at",
"zoom",
"level",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tilepyramid.py#L92-L100 | train | 50,750 |
ungarj/tilematrix | tilematrix/_tilepyramid.py | TilePyramid.tile_y_size | def tile_y_size(self, zoom):
"""
Height of a tile in SRID units at zoom level.
- zoom: zoom level
"""
warnings.warn(DeprecationWarning("tile_y_size is deprecated"))
validate_zoom(zoom)
return round(self.y_size / self.matrix_height(zoom), ROUND) | python | def tile_y_size(self, zoom):
"""
Height of a tile in SRID units at zoom level.
- zoom: zoom level
"""
warnings.warn(DeprecationWarning("tile_y_size is deprecated"))
validate_zoom(zoom)
return round(self.y_size / self.matrix_height(zoom), ROUND) | [
"def",
"tile_y_size",
"(",
"self",
",",
"zoom",
")",
":",
"warnings",
".",
"warn",
"(",
"DeprecationWarning",
"(",
"\"tile_y_size is deprecated\"",
")",
")",
"validate_zoom",
"(",
"zoom",
")",
"return",
"round",
"(",
"self",
".",
"y_size",
"/",
"self",
".",
... | Height of a tile in SRID units at zoom level.
- zoom: zoom level | [
"Height",
"of",
"a",
"tile",
"in",
"SRID",
"units",
"at",
"zoom",
"level",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tilepyramid.py#L102-L110 | train | 50,751 |
ungarj/tilematrix | tilematrix/_tilepyramid.py | TilePyramid.tile_width | def tile_width(self, zoom):
"""
Tile width in pixel.
- zoom: zoom level
"""
warnings.warn(DeprecationWarning("tile_width is deprecated"))
validate_zoom(zoom)
matrix_pixel = 2**(zoom) * self.tile_size * self.grid.shape.width
tile_pixel = self.tile_size * self.metatiling
return matrix_pixel if tile_pixel > matrix_pixel else tile_pixel | python | def tile_width(self, zoom):
"""
Tile width in pixel.
- zoom: zoom level
"""
warnings.warn(DeprecationWarning("tile_width is deprecated"))
validate_zoom(zoom)
matrix_pixel = 2**(zoom) * self.tile_size * self.grid.shape.width
tile_pixel = self.tile_size * self.metatiling
return matrix_pixel if tile_pixel > matrix_pixel else tile_pixel | [
"def",
"tile_width",
"(",
"self",
",",
"zoom",
")",
":",
"warnings",
".",
"warn",
"(",
"DeprecationWarning",
"(",
"\"tile_width is deprecated\"",
")",
")",
"validate_zoom",
"(",
"zoom",
")",
"matrix_pixel",
"=",
"2",
"**",
"(",
"zoom",
")",
"*",
"self",
".... | Tile width in pixel.
- zoom: zoom level | [
"Tile",
"width",
"in",
"pixel",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tilepyramid.py#L112-L122 | train | 50,752 |
ungarj/tilematrix | tilematrix/_tilepyramid.py | TilePyramid.tile_height | def tile_height(self, zoom):
"""
Tile height in pixel.
- zoom: zoom level
"""
warnings.warn(DeprecationWarning("tile_height is deprecated"))
validate_zoom(zoom)
matrix_pixel = 2**(zoom) * self.tile_size * self.grid.shape.height
tile_pixel = self.tile_size * self.metatiling
return matrix_pixel if tile_pixel > matrix_pixel else tile_pixel | python | def tile_height(self, zoom):
"""
Tile height in pixel.
- zoom: zoom level
"""
warnings.warn(DeprecationWarning("tile_height is deprecated"))
validate_zoom(zoom)
matrix_pixel = 2**(zoom) * self.tile_size * self.grid.shape.height
tile_pixel = self.tile_size * self.metatiling
return matrix_pixel if tile_pixel > matrix_pixel else tile_pixel | [
"def",
"tile_height",
"(",
"self",
",",
"zoom",
")",
":",
"warnings",
".",
"warn",
"(",
"DeprecationWarning",
"(",
"\"tile_height is deprecated\"",
")",
")",
"validate_zoom",
"(",
"zoom",
")",
"matrix_pixel",
"=",
"2",
"**",
"(",
"zoom",
")",
"*",
"self",
... | Tile height in pixel.
- zoom: zoom level | [
"Tile",
"height",
"in",
"pixel",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tilepyramid.py#L124-L134 | train | 50,753 |
ungarj/tilematrix | tilematrix/_tilepyramid.py | TilePyramid.pixel_x_size | def pixel_x_size(self, zoom):
"""
Width of a pixel in SRID units at zoom level.
- zoom: zoom level
"""
validate_zoom(zoom)
return round(
(self.grid.right - self.grid.left) /
(self.grid.shape.width * 2**zoom * self.tile_size),
ROUND
) | python | def pixel_x_size(self, zoom):
"""
Width of a pixel in SRID units at zoom level.
- zoom: zoom level
"""
validate_zoom(zoom)
return round(
(self.grid.right - self.grid.left) /
(self.grid.shape.width * 2**zoom * self.tile_size),
ROUND
) | [
"def",
"pixel_x_size",
"(",
"self",
",",
"zoom",
")",
":",
"validate_zoom",
"(",
"zoom",
")",
"return",
"round",
"(",
"(",
"self",
".",
"grid",
".",
"right",
"-",
"self",
".",
"grid",
".",
"left",
")",
"/",
"(",
"self",
".",
"grid",
".",
"shape",
... | Width of a pixel in SRID units at zoom level.
- zoom: zoom level | [
"Width",
"of",
"a",
"pixel",
"in",
"SRID",
"units",
"at",
"zoom",
"level",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tilepyramid.py#L136-L147 | train | 50,754 |
ungarj/tilematrix | tilematrix/_tilepyramid.py | TilePyramid.pixel_y_size | def pixel_y_size(self, zoom):
"""
Height of a pixel in SRID units at zoom level.
- zoom: zoom level
"""
validate_zoom(zoom)
return round(
(self.grid.top - self.grid.bottom) /
(self.grid.shape.height * 2**zoom * self.tile_size),
ROUND
) | python | def pixel_y_size(self, zoom):
"""
Height of a pixel in SRID units at zoom level.
- zoom: zoom level
"""
validate_zoom(zoom)
return round(
(self.grid.top - self.grid.bottom) /
(self.grid.shape.height * 2**zoom * self.tile_size),
ROUND
) | [
"def",
"pixel_y_size",
"(",
"self",
",",
"zoom",
")",
":",
"validate_zoom",
"(",
"zoom",
")",
"return",
"round",
"(",
"(",
"self",
".",
"grid",
".",
"top",
"-",
"self",
".",
"grid",
".",
"bottom",
")",
"/",
"(",
"self",
".",
"grid",
".",
"shape",
... | Height of a pixel in SRID units at zoom level.
- zoom: zoom level | [
"Height",
"of",
"a",
"pixel",
"in",
"SRID",
"units",
"at",
"zoom",
"level",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tilepyramid.py#L149-L160 | train | 50,755 |
ungarj/tilematrix | tilematrix/_tilepyramid.py | TilePyramid.tiles_from_bbox | def tiles_from_bbox(self, geometry, zoom):
"""
All metatiles intersecting with given bounding box.
- geometry: shapely geometry
- zoom: zoom level
"""
validate_zoom(zoom)
return self.tiles_from_bounds(geometry.bounds, zoom) | python | def tiles_from_bbox(self, geometry, zoom):
"""
All metatiles intersecting with given bounding box.
- geometry: shapely geometry
- zoom: zoom level
"""
validate_zoom(zoom)
return self.tiles_from_bounds(geometry.bounds, zoom) | [
"def",
"tiles_from_bbox",
"(",
"self",
",",
"geometry",
",",
"zoom",
")",
":",
"validate_zoom",
"(",
"zoom",
")",
"return",
"self",
".",
"tiles_from_bounds",
"(",
"geometry",
".",
"bounds",
",",
"zoom",
")"
] | All metatiles intersecting with given bounding box.
- geometry: shapely geometry
- zoom: zoom level | [
"All",
"metatiles",
"intersecting",
"with",
"given",
"bounding",
"box",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tilepyramid.py#L196-L204 | train | 50,756 |
ungarj/tilematrix | tilematrix/_tilepyramid.py | TilePyramid.tiles_from_geom | def tiles_from_geom(self, geometry, zoom):
"""
Return all tiles intersecting with input geometry.
- geometry: shapely geometry
- zoom: zoom level
"""
validate_zoom(zoom)
if geometry.is_empty:
return
if not geometry.is_valid:
raise ValueError("no valid geometry: %s" % geometry.type)
if geometry.geom_type == "Point":
yield self.tile_from_xy(geometry.x, geometry.y, zoom)
elif geometry.geom_type == "MultiPoint":
for point in geometry:
yield self.tile_from_xy(point.x, point.y, zoom)
elif geometry.geom_type in (
"LineString", "MultiLineString", "Polygon", "MultiPolygon",
"GeometryCollection"
):
prepared_geometry = prep(clip_geometry_to_srs_bounds(geometry, self))
for tile in self.tiles_from_bbox(geometry, zoom):
if prepared_geometry.intersects(tile.bbox()):
yield tile | python | def tiles_from_geom(self, geometry, zoom):
"""
Return all tiles intersecting with input geometry.
- geometry: shapely geometry
- zoom: zoom level
"""
validate_zoom(zoom)
if geometry.is_empty:
return
if not geometry.is_valid:
raise ValueError("no valid geometry: %s" % geometry.type)
if geometry.geom_type == "Point":
yield self.tile_from_xy(geometry.x, geometry.y, zoom)
elif geometry.geom_type == "MultiPoint":
for point in geometry:
yield self.tile_from_xy(point.x, point.y, zoom)
elif geometry.geom_type in (
"LineString", "MultiLineString", "Polygon", "MultiPolygon",
"GeometryCollection"
):
prepared_geometry = prep(clip_geometry_to_srs_bounds(geometry, self))
for tile in self.tiles_from_bbox(geometry, zoom):
if prepared_geometry.intersects(tile.bbox()):
yield tile | [
"def",
"tiles_from_geom",
"(",
"self",
",",
"geometry",
",",
"zoom",
")",
":",
"validate_zoom",
"(",
"zoom",
")",
"if",
"geometry",
".",
"is_empty",
":",
"return",
"if",
"not",
"geometry",
".",
"is_valid",
":",
"raise",
"ValueError",
"(",
"\"no valid geometr... | Return all tiles intersecting with input geometry.
- geometry: shapely geometry
- zoom: zoom level | [
"Return",
"all",
"tiles",
"intersecting",
"with",
"input",
"geometry",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tilepyramid.py#L206-L230 | train | 50,757 |
ungarj/tilematrix | tilematrix/_tilepyramid.py | TilePyramid.tile_from_xy | def tile_from_xy(self, x, y, zoom, on_edge_use="rb"):
"""
Return tile covering a point defined by x and y values.
- x: x coordinate
- y: y coordinate
- zoom: zoom level
- on_edge_use: determine which Tile to pick if Point hits a grid edge
- rb: right bottom (default)
- rt: right top
- lt: left top
- lb: left bottom
"""
validate_zoom(zoom)
if x < self.left or x > self.right or y < self.bottom or y > self.top:
raise ValueError("x or y are outside of grid bounds")
if on_edge_use not in ["lb", "rb", "rt", "lt"]:
raise ValueError("on_edge_use must be one of lb, rb, rt or lt")
return _tile_from_xy(self, x, y, zoom, on_edge_use=on_edge_use) | python | def tile_from_xy(self, x, y, zoom, on_edge_use="rb"):
"""
Return tile covering a point defined by x and y values.
- x: x coordinate
- y: y coordinate
- zoom: zoom level
- on_edge_use: determine which Tile to pick if Point hits a grid edge
- rb: right bottom (default)
- rt: right top
- lt: left top
- lb: left bottom
"""
validate_zoom(zoom)
if x < self.left or x > self.right or y < self.bottom or y > self.top:
raise ValueError("x or y are outside of grid bounds")
if on_edge_use not in ["lb", "rb", "rt", "lt"]:
raise ValueError("on_edge_use must be one of lb, rb, rt or lt")
return _tile_from_xy(self, x, y, zoom, on_edge_use=on_edge_use) | [
"def",
"tile_from_xy",
"(",
"self",
",",
"x",
",",
"y",
",",
"zoom",
",",
"on_edge_use",
"=",
"\"rb\"",
")",
":",
"validate_zoom",
"(",
"zoom",
")",
"if",
"x",
"<",
"self",
".",
"left",
"or",
"x",
">",
"self",
".",
"right",
"or",
"y",
"<",
"self"... | Return tile covering a point defined by x and y values.
- x: x coordinate
- y: y coordinate
- zoom: zoom level
- on_edge_use: determine which Tile to pick if Point hits a grid edge
- rb: right bottom (default)
- rt: right top
- lt: left top
- lb: left bottom | [
"Return",
"tile",
"covering",
"a",
"point",
"defined",
"by",
"x",
"and",
"y",
"values",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tilepyramid.py#L232-L250 | train | 50,758 |
happyleavesaoc/python-voobly | utils/update_metadata.py | get_ladder_metadata | def get_ladder_metadata(session, url):
"""Get ladder metadata."""
parsed = make_scrape_request(session, url)
tag = parsed.find('a', href=re.compile(LADDER_ID_REGEX))
return {
'id': int(tag['href'].split('/')[-1]),
'slug': url.split('/')[-1],
'url': url
} | python | def get_ladder_metadata(session, url):
"""Get ladder metadata."""
parsed = make_scrape_request(session, url)
tag = parsed.find('a', href=re.compile(LADDER_ID_REGEX))
return {
'id': int(tag['href'].split('/')[-1]),
'slug': url.split('/')[-1],
'url': url
} | [
"def",
"get_ladder_metadata",
"(",
"session",
",",
"url",
")",
":",
"parsed",
"=",
"make_scrape_request",
"(",
"session",
",",
"url",
")",
"tag",
"=",
"parsed",
".",
"find",
"(",
"'a'",
",",
"href",
"=",
"re",
".",
"compile",
"(",
"LADDER_ID_REGEX",
")",... | Get ladder metadata. | [
"Get",
"ladder",
"metadata",
"."
] | 83b4ab7d630a00459c2a64e55e3ac85c7be38194 | https://github.com/happyleavesaoc/python-voobly/blob/83b4ab7d630a00459c2a64e55e3ac85c7be38194/utils/update_metadata.py#L14-L22 | train | 50,759 |
happyleavesaoc/python-voobly | utils/update_metadata.py | get_ladders_metadata | def get_ladders_metadata(session, parsed):
"""Get metadata for all ladders."""
ladders = {}
for ladder in parsed.find_all('a', href=re.compile(LADDER_URL_REGEX)):
ladders[ladder.text] = get_ladder_metadata(session, ladder['href'])
return ladders | python | def get_ladders_metadata(session, parsed):
"""Get metadata for all ladders."""
ladders = {}
for ladder in parsed.find_all('a', href=re.compile(LADDER_URL_REGEX)):
ladders[ladder.text] = get_ladder_metadata(session, ladder['href'])
return ladders | [
"def",
"get_ladders_metadata",
"(",
"session",
",",
"parsed",
")",
":",
"ladders",
"=",
"{",
"}",
"for",
"ladder",
"in",
"parsed",
".",
"find_all",
"(",
"'a'",
",",
"href",
"=",
"re",
".",
"compile",
"(",
"LADDER_URL_REGEX",
")",
")",
":",
"ladders",
"... | Get metadata for all ladders. | [
"Get",
"metadata",
"for",
"all",
"ladders",
"."
] | 83b4ab7d630a00459c2a64e55e3ac85c7be38194 | https://github.com/happyleavesaoc/python-voobly/blob/83b4ab7d630a00459c2a64e55e3ac85c7be38194/utils/update_metadata.py#L25-L30 | train | 50,760 |
project-rig/rig | rig/scripts/rig_counters.py | sample_counters | def sample_counters(mc, system_info):
"""Sample every router counter in the machine."""
return {
(x, y): mc.get_router_diagnostics(x, y) for (x, y) in system_info
} | python | def sample_counters(mc, system_info):
"""Sample every router counter in the machine."""
return {
(x, y): mc.get_router_diagnostics(x, y) for (x, y) in system_info
} | [
"def",
"sample_counters",
"(",
"mc",
",",
"system_info",
")",
":",
"return",
"{",
"(",
"x",
",",
"y",
")",
":",
"mc",
".",
"get_router_diagnostics",
"(",
"x",
",",
"y",
")",
"for",
"(",
"x",
",",
"y",
")",
"in",
"system_info",
"}"
] | Sample every router counter in the machine. | [
"Sample",
"every",
"router",
"counter",
"in",
"the",
"machine",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/scripts/rig_counters.py#L24-L28 | train | 50,761 |
project-rig/rig | rig/scripts/rig_counters.py | monitor_counters | def monitor_counters(mc, output, counters, detailed, f):
"""Monitor the counters on a specified machine, taking a snap-shot every
time the generator 'f' yields."""
# Print CSV header
output.write("time,{}{}\n".format("x,y," if detailed else "",
",".join(counters)))
system_info = mc.get_system_info()
# Make an initial sample of the counters
last_counter_values = sample_counters(mc, system_info)
start_time = time.time()
for _ in f():
# Snapshot the change in counter values
counter_values = sample_counters(mc, system_info)
delta = deltas(last_counter_values, counter_values)
last_counter_values = counter_values
now = time.time() - start_time
# Output the changes
if detailed:
for x, y in sorted(system_info):
output.write("{:0.1f},{},{},{}\n".format(
now, x, y,
",".join(str(getattr(delta[(x, y)], c))
for c in counters)))
else:
totals = [0 for _ in counters]
for xy in sorted(system_info):
for i, counter in enumerate(counters):
totals[i] += getattr(delta[xy], counter)
output.write("{:0.1f},{}\n".format(
now, ",".join(map(str, totals)))) | python | def monitor_counters(mc, output, counters, detailed, f):
"""Monitor the counters on a specified machine, taking a snap-shot every
time the generator 'f' yields."""
# Print CSV header
output.write("time,{}{}\n".format("x,y," if detailed else "",
",".join(counters)))
system_info = mc.get_system_info()
# Make an initial sample of the counters
last_counter_values = sample_counters(mc, system_info)
start_time = time.time()
for _ in f():
# Snapshot the change in counter values
counter_values = sample_counters(mc, system_info)
delta = deltas(last_counter_values, counter_values)
last_counter_values = counter_values
now = time.time() - start_time
# Output the changes
if detailed:
for x, y in sorted(system_info):
output.write("{:0.1f},{},{},{}\n".format(
now, x, y,
",".join(str(getattr(delta[(x, y)], c))
for c in counters)))
else:
totals = [0 for _ in counters]
for xy in sorted(system_info):
for i, counter in enumerate(counters):
totals[i] += getattr(delta[xy], counter)
output.write("{:0.1f},{}\n".format(
now, ",".join(map(str, totals)))) | [
"def",
"monitor_counters",
"(",
"mc",
",",
"output",
",",
"counters",
",",
"detailed",
",",
"f",
")",
":",
"# Print CSV header",
"output",
".",
"write",
"(",
"\"time,{}{}\\n\"",
".",
"format",
"(",
"\"x,y,\"",
"if",
"detailed",
"else",
"\"\"",
",",
"\",\"",
... | Monitor the counters on a specified machine, taking a snap-shot every
time the generator 'f' yields. | [
"Monitor",
"the",
"counters",
"on",
"a",
"specified",
"machine",
"taking",
"a",
"snap",
"-",
"shot",
"every",
"time",
"the",
"generator",
"f",
"yields",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/scripts/rig_counters.py#L40-L75 | train | 50,762 |
project-rig/rig | rig/scripts/rig_counters.py | press_enter | def press_enter(multiple=False, silent=False):
"""Return a generator function which yields every time the user presses
return."""
def f():
try:
while True:
if silent:
yield input()
else:
sys.stderr.write("<press enter> ")
sys.stderr.flush()
yield input()
if not multiple:
break
except (EOFError, KeyboardInterrupt):
# User Ctrl+D or Ctrl+C'd
if not silent:
# Prevents the user's terminal getting clobbered
sys.stderr.write("\n")
sys.stderr.flush()
return
return f | python | def press_enter(multiple=False, silent=False):
"""Return a generator function which yields every time the user presses
return."""
def f():
try:
while True:
if silent:
yield input()
else:
sys.stderr.write("<press enter> ")
sys.stderr.flush()
yield input()
if not multiple:
break
except (EOFError, KeyboardInterrupt):
# User Ctrl+D or Ctrl+C'd
if not silent:
# Prevents the user's terminal getting clobbered
sys.stderr.write("\n")
sys.stderr.flush()
return
return f | [
"def",
"press_enter",
"(",
"multiple",
"=",
"False",
",",
"silent",
"=",
"False",
")",
":",
"def",
"f",
"(",
")",
":",
"try",
":",
"while",
"True",
":",
"if",
"silent",
":",
"yield",
"input",
"(",
")",
"else",
":",
"sys",
".",
"stderr",
".",
"wri... | Return a generator function which yields every time the user presses
return. | [
"Return",
"a",
"generator",
"function",
"which",
"yields",
"every",
"time",
"the",
"user",
"presses",
"return",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/scripts/rig_counters.py#L78-L101 | train | 50,763 |
project-rig/rig | rig/machine_control/unbooted_ping.py | listen | def listen(timeout=6.0, port=BOOT_PORT):
"""Listen for a 'ping' broadcast message from an unbooted SpiNNaker board.
Unbooted SpiNNaker boards send out a UDP broadcast message every 4-ish
seconds on port 54321. This function listens for such messages and reports
the IP address that it came from.
Parameters
----------
timeout : float
Number of seconds to wait for a message to arrive.
port : int
The port number to listen on.
Returns
-------
str or None
The IP address of the SpiNNaker board from which a ping was received or
None if no ping was observed.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Don't take control of this socket in the system (i.e. allow other
# processes to bind to it) since we're listening for broadcasts.
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Listen for the broadcasts
s.bind(('0.0.0.0', port))
s.settimeout(timeout)
try:
message, (ipaddr, port) = s.recvfrom(512)
return ipaddr
except socket.timeout:
return None | python | def listen(timeout=6.0, port=BOOT_PORT):
"""Listen for a 'ping' broadcast message from an unbooted SpiNNaker board.
Unbooted SpiNNaker boards send out a UDP broadcast message every 4-ish
seconds on port 54321. This function listens for such messages and reports
the IP address that it came from.
Parameters
----------
timeout : float
Number of seconds to wait for a message to arrive.
port : int
The port number to listen on.
Returns
-------
str or None
The IP address of the SpiNNaker board from which a ping was received or
None if no ping was observed.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Don't take control of this socket in the system (i.e. allow other
# processes to bind to it) since we're listening for broadcasts.
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Listen for the broadcasts
s.bind(('0.0.0.0', port))
s.settimeout(timeout)
try:
message, (ipaddr, port) = s.recvfrom(512)
return ipaddr
except socket.timeout:
return None | [
"def",
"listen",
"(",
"timeout",
"=",
"6.0",
",",
"port",
"=",
"BOOT_PORT",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"# Don't take control of this socket in the system (i.e. allow other",
... | Listen for a 'ping' broadcast message from an unbooted SpiNNaker board.
Unbooted SpiNNaker boards send out a UDP broadcast message every 4-ish
seconds on port 54321. This function listens for such messages and reports
the IP address that it came from.
Parameters
----------
timeout : float
Number of seconds to wait for a message to arrive.
port : int
The port number to listen on.
Returns
-------
str or None
The IP address of the SpiNNaker board from which a ping was received or
None if no ping was observed. | [
"Listen",
"for",
"a",
"ping",
"broadcast",
"message",
"from",
"an",
"unbooted",
"SpiNNaker",
"board",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/unbooted_ping.py#L8-L42 | train | 50,764 |
Metatab/metapack | metapack/cli/s3.py | clear_cache | def clear_cache(m, files_processed):
"""Remove any files we may have uploaded from the cache. """
for what, reason, url, path in files_processed:
cp = m.doc.downloader.cache_path(url)
if m.cache.exists(cp):
m.cache.remove(cp) | python | def clear_cache(m, files_processed):
"""Remove any files we may have uploaded from the cache. """
for what, reason, url, path in files_processed:
cp = m.doc.downloader.cache_path(url)
if m.cache.exists(cp):
m.cache.remove(cp) | [
"def",
"clear_cache",
"(",
"m",
",",
"files_processed",
")",
":",
"for",
"what",
",",
"reason",
",",
"url",
",",
"path",
"in",
"files_processed",
":",
"cp",
"=",
"m",
".",
"doc",
".",
"downloader",
".",
"cache_path",
"(",
"url",
")",
"if",
"m",
".",
... | Remove any files we may have uploaded from the cache. | [
"Remove",
"any",
"files",
"we",
"may",
"have",
"uploaded",
"from",
"the",
"cache",
"."
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/cli/s3.py#L135-L142 | train | 50,765 |
Metatab/metapack | metapack/jupyter/magic.py | fill_categorical_na | def fill_categorical_na(df, nan_cat='NA'):
"""Fill categoricals with 'NA', possibly creating a new category,
and fill other NaNa with blanks """
for col in df.columns[df.isna().any()].tolist():
if df[col].dtype.name != 'category':
# If not categorical, fill with a blank, which creates and
# empty cell in CSV.
df[col] = df[col].fillna('')
else:
try:
df[col].cat.add_categories([nan_cat], inplace=True)
except ValueError:
pass
df[col] = df[col].fillna(nan_cat)
return df | python | def fill_categorical_na(df, nan_cat='NA'):
"""Fill categoricals with 'NA', possibly creating a new category,
and fill other NaNa with blanks """
for col in df.columns[df.isna().any()].tolist():
if df[col].dtype.name != 'category':
# If not categorical, fill with a blank, which creates and
# empty cell in CSV.
df[col] = df[col].fillna('')
else:
try:
df[col].cat.add_categories([nan_cat], inplace=True)
except ValueError:
pass
df[col] = df[col].fillna(nan_cat)
return df | [
"def",
"fill_categorical_na",
"(",
"df",
",",
"nan_cat",
"=",
"'NA'",
")",
":",
"for",
"col",
"in",
"df",
".",
"columns",
"[",
"df",
".",
"isna",
"(",
")",
".",
"any",
"(",
")",
"]",
".",
"tolist",
"(",
")",
":",
"if",
"df",
"[",
"col",
"]",
... | Fill categoricals with 'NA', possibly creating a new category,
and fill other NaNa with blanks | [
"Fill",
"categoricals",
"with",
"NA",
"possibly",
"creating",
"a",
"new",
"category",
"and",
"fill",
"other",
"NaNa",
"with",
"blanks"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/magic.py#L41-L59 | train | 50,766 |
Metatab/metapack | metapack/jupyter/pandas.py | MetatabDataFrame.geo | def geo(self):
"""Return a geopandas dataframe"""
import geopandas as gpd
from shapely.geometry.polygon import BaseGeometry
from shapely.wkt import loads
gdf = gpd.GeoDataFrame(self)
first = next(gdf.iterrows())[1].geometry
if isinstance(first, str):
# We have a GeoDataframe, but the geometry column is still strings, so
# it must be converted
shapes = [ loads(row['geometry']) for i, row in gdf.iterrows()]
elif not isinstance(first, BaseGeometry):
# If we are reading a metatab package, the geometry column's type should be
# 'geometry' which will give the geometry values class type of
# rowpipe.valuetype.geo.ShapeValue. However, there are other
# types of objects that have a 'shape' property.
shapes = [row['geometry'].shape for i, row in gdf.iterrows()]
else:
shapes = gdf['geometry']
gdf['geometry'] = gpd.GeoSeries(shapes)
gdf.set_geometry('geometry')
return gdf | python | def geo(self):
"""Return a geopandas dataframe"""
import geopandas as gpd
from shapely.geometry.polygon import BaseGeometry
from shapely.wkt import loads
gdf = gpd.GeoDataFrame(self)
first = next(gdf.iterrows())[1].geometry
if isinstance(first, str):
# We have a GeoDataframe, but the geometry column is still strings, so
# it must be converted
shapes = [ loads(row['geometry']) for i, row in gdf.iterrows()]
elif not isinstance(first, BaseGeometry):
# If we are reading a metatab package, the geometry column's type should be
# 'geometry' which will give the geometry values class type of
# rowpipe.valuetype.geo.ShapeValue. However, there are other
# types of objects that have a 'shape' property.
shapes = [row['geometry'].shape for i, row in gdf.iterrows()]
else:
shapes = gdf['geometry']
gdf['geometry'] = gpd.GeoSeries(shapes)
gdf.set_geometry('geometry')
return gdf | [
"def",
"geo",
"(",
"self",
")",
":",
"import",
"geopandas",
"as",
"gpd",
"from",
"shapely",
".",
"geometry",
".",
"polygon",
"import",
"BaseGeometry",
"from",
"shapely",
".",
"wkt",
"import",
"loads",
"gdf",
"=",
"gpd",
".",
"GeoDataFrame",
"(",
"self",
... | Return a geopandas dataframe | [
"Return",
"a",
"geopandas",
"dataframe"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/pandas.py#L51-L79 | train | 50,767 |
Metatab/metapack | metapack/jupyter/pandas.py | MetatabDataFrame.rows | def rows(self):
"""Yield rows like a partition does, with a header first, then rows. """
yield [self.index.name] + list(self.columns)
for t in self.itertuples():
yield list(t) | python | def rows(self):
"""Yield rows like a partition does, with a header first, then rows. """
yield [self.index.name] + list(self.columns)
for t in self.itertuples():
yield list(t) | [
"def",
"rows",
"(",
"self",
")",
":",
"yield",
"[",
"self",
".",
"index",
".",
"name",
"]",
"+",
"list",
"(",
"self",
".",
"columns",
")",
"for",
"t",
"in",
"self",
".",
"itertuples",
"(",
")",
":",
"yield",
"list",
"(",
"t",
")"
] | Yield rows like a partition does, with a header first, then rows. | [
"Yield",
"rows",
"like",
"a",
"partition",
"does",
"with",
"a",
"header",
"first",
"then",
"rows",
"."
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/pandas.py#L128-L134 | train | 50,768 |
NeuroML/NeuroMLlite | neuromllite/SonataReader.py | _matches_node_set_props | def _matches_node_set_props(type_info, node_set_props):
"""
Check whether the node_set properties match the given model type definition
"""
matches = None
for key in node_set_props:
ns_val = node_set_props[key]
if key in type_info:
if ns_val==type_info[key]:
if matches:
matches = matches and True
else:
matches = True
else:
matches = False
return matches | python | def _matches_node_set_props(type_info, node_set_props):
"""
Check whether the node_set properties match the given model type definition
"""
matches = None
for key in node_set_props:
ns_val = node_set_props[key]
if key in type_info:
if ns_val==type_info[key]:
if matches:
matches = matches and True
else:
matches = True
else:
matches = False
return matches | [
"def",
"_matches_node_set_props",
"(",
"type_info",
",",
"node_set_props",
")",
":",
"matches",
"=",
"None",
"for",
"key",
"in",
"node_set_props",
":",
"ns_val",
"=",
"node_set_props",
"[",
"key",
"]",
"if",
"key",
"in",
"type_info",
":",
"if",
"ns_val",
"==... | Check whether the node_set properties match the given model type definition | [
"Check",
"whether",
"the",
"node_set",
"properties",
"match",
"the",
"given",
"model",
"type",
"definition"
] | f3fa2ff662e40febfa97c045e7f0e6915ad04161 | https://github.com/NeuroML/NeuroMLlite/blob/f3fa2ff662e40febfa97c045e7f0e6915ad04161/neuromllite/SonataReader.py#L62-L77 | train | 50,769 |
NeuroML/NeuroMLlite | neuromllite/SonataReader.py | SonataReader.generate_lems_file | def generate_lems_file(self, nml_file_name, nml_doc):
"""
Generate a LEMS file to use in simulations of the NeuroML file
"""
#pp.pprint(self.simulation_config)
#pp.pprint(self.pop_comp_info)
#pp.pprint(self.node_set_mappings)
if 'output' in self.simulation_config:
gen_spike_saves_for_all_somas = True
target = nml_doc.networks[0].id
sim_id = 'Sim_%s'%target
duration = self.simulation_config['run']['tstop']
dt = self.simulation_config['run']['dt']
lems_file_name = 'LEMS_%s.xml'%sim_id
target_dir = "./"
gen_saves_for_quantities = {}
gen_plots_for_quantities = {}
if 'reports' in self.simulation_config:
if 'membrane_potential' in self.simulation_config['reports']:
mp = self.simulation_config['reports']['membrane_potential']
node_set = self.node_set_mappings[mp['cells']]
for nml_pop in node_set:
comp = self.nml_pop_vs_comps[nml_pop]
ids = node_set[nml_pop]
display = 'Voltages_%s'%nml_pop
file_name = '%s.v.dat'%nml_pop
for id in ids:
quantity = '%s/%i/%s/%s'%(nml_pop,id,comp,'v')
if not nml_pop in self.nml_pops_having_locations:
quantity = '%s[%i]/%s'%(nml_pop,id,'v')
if not display in gen_plots_for_quantities:
gen_plots_for_quantities[display] = []
gen_plots_for_quantities[display].append(quantity)
if not file_name in gen_saves_for_quantities:
gen_saves_for_quantities[file_name] = []
gen_saves_for_quantities[file_name].append(quantity)
generate_lems_file_for_neuroml(sim_id,
nml_file_name,
target,
duration,
dt,
lems_file_name,
target_dir,
include_extra_files = self.nml_includes,
gen_plots_for_all_v = False,
plot_all_segments = False,
gen_plots_for_quantities = gen_plots_for_quantities, # Dict with displays vs lists of quantity paths
gen_saves_for_all_v = False,
save_all_segments = False,
gen_saves_for_quantities = gen_saves_for_quantities, # List of populations, all pops if = []
gen_spike_saves_for_all_somas = gen_spike_saves_for_all_somas,
report_file_name = REPORT_FILE,
copy_neuroml = True,
verbose=True)
return lems_file_name | python | def generate_lems_file(self, nml_file_name, nml_doc):
"""
Generate a LEMS file to use in simulations of the NeuroML file
"""
#pp.pprint(self.simulation_config)
#pp.pprint(self.pop_comp_info)
#pp.pprint(self.node_set_mappings)
if 'output' in self.simulation_config:
gen_spike_saves_for_all_somas = True
target = nml_doc.networks[0].id
sim_id = 'Sim_%s'%target
duration = self.simulation_config['run']['tstop']
dt = self.simulation_config['run']['dt']
lems_file_name = 'LEMS_%s.xml'%sim_id
target_dir = "./"
gen_saves_for_quantities = {}
gen_plots_for_quantities = {}
if 'reports' in self.simulation_config:
if 'membrane_potential' in self.simulation_config['reports']:
mp = self.simulation_config['reports']['membrane_potential']
node_set = self.node_set_mappings[mp['cells']]
for nml_pop in node_set:
comp = self.nml_pop_vs_comps[nml_pop]
ids = node_set[nml_pop]
display = 'Voltages_%s'%nml_pop
file_name = '%s.v.dat'%nml_pop
for id in ids:
quantity = '%s/%i/%s/%s'%(nml_pop,id,comp,'v')
if not nml_pop in self.nml_pops_having_locations:
quantity = '%s[%i]/%s'%(nml_pop,id,'v')
if not display in gen_plots_for_quantities:
gen_plots_for_quantities[display] = []
gen_plots_for_quantities[display].append(quantity)
if not file_name in gen_saves_for_quantities:
gen_saves_for_quantities[file_name] = []
gen_saves_for_quantities[file_name].append(quantity)
generate_lems_file_for_neuroml(sim_id,
nml_file_name,
target,
duration,
dt,
lems_file_name,
target_dir,
include_extra_files = self.nml_includes,
gen_plots_for_all_v = False,
plot_all_segments = False,
gen_plots_for_quantities = gen_plots_for_quantities, # Dict with displays vs lists of quantity paths
gen_saves_for_all_v = False,
save_all_segments = False,
gen_saves_for_quantities = gen_saves_for_quantities, # List of populations, all pops if = []
gen_spike_saves_for_all_somas = gen_spike_saves_for_all_somas,
report_file_name = REPORT_FILE,
copy_neuroml = True,
verbose=True)
return lems_file_name | [
"def",
"generate_lems_file",
"(",
"self",
",",
"nml_file_name",
",",
"nml_doc",
")",
":",
"#pp.pprint(self.simulation_config)",
"#pp.pprint(self.pop_comp_info)",
"#pp.pprint(self.node_set_mappings)",
"if",
"'output'",
"in",
"self",
".",
"simulation_config",
":",
"gen_spike_sa... | Generate a LEMS file to use in simulations of the NeuroML file | [
"Generate",
"a",
"LEMS",
"file",
"to",
"use",
"in",
"simulations",
"of",
"the",
"NeuroML",
"file"
] | f3fa2ff662e40febfa97c045e7f0e6915ad04161 | https://github.com/NeuroML/NeuroMLlite/blob/f3fa2ff662e40febfa97c045e7f0e6915ad04161/neuromllite/SonataReader.py#L834-L898 | train | 50,770 |
ungarj/tilematrix | tilematrix/_funcs.py | clip_geometry_to_srs_bounds | def clip_geometry_to_srs_bounds(geometry, pyramid, multipart=False):
"""
Clip input geometry to SRS bounds of given TilePyramid.
If geometry passes the antimeridian, it will be split up in a multipart
geometry and shifted to within the SRS boundaries.
Note: geometry SRS must be the TilePyramid SRS!
- geometry: any shapely geometry
- pyramid: a TilePyramid object
- multipart: return list of geometries instead of a GeometryCollection
"""
if not geometry.is_valid:
raise ValueError("invalid geometry given")
pyramid_bbox = box(*pyramid.bounds)
# Special case for global tile pyramids if geometry extends over tile
# pyramid boundaries (such as the antimeridian).
if pyramid.is_global and not geometry.within(pyramid_bbox):
inside_geom = geometry.intersection(pyramid_bbox)
outside_geom = geometry.difference(pyramid_bbox)
# shift outside geometry so it lies within SRS bounds
if isinstance(outside_geom, Polygon):
outside_geom = [outside_geom]
all_geoms = [inside_geom]
for geom in outside_geom:
geom_bounds = Bounds(*geom.bounds)
if geom_bounds.left < pyramid.left:
geom = translate(geom, xoff=2*pyramid.right)
elif geom_bounds.right > pyramid.right:
geom = translate(geom, xoff=-2*pyramid.right)
all_geoms.append(geom)
if multipart:
return all_geoms
else:
return GeometryCollection(all_geoms)
else:
if multipart:
return [geometry]
else:
return geometry | python | def clip_geometry_to_srs_bounds(geometry, pyramid, multipart=False):
"""
Clip input geometry to SRS bounds of given TilePyramid.
If geometry passes the antimeridian, it will be split up in a multipart
geometry and shifted to within the SRS boundaries.
Note: geometry SRS must be the TilePyramid SRS!
- geometry: any shapely geometry
- pyramid: a TilePyramid object
- multipart: return list of geometries instead of a GeometryCollection
"""
if not geometry.is_valid:
raise ValueError("invalid geometry given")
pyramid_bbox = box(*pyramid.bounds)
# Special case for global tile pyramids if geometry extends over tile
# pyramid boundaries (such as the antimeridian).
if pyramid.is_global and not geometry.within(pyramid_bbox):
inside_geom = geometry.intersection(pyramid_bbox)
outside_geom = geometry.difference(pyramid_bbox)
# shift outside geometry so it lies within SRS bounds
if isinstance(outside_geom, Polygon):
outside_geom = [outside_geom]
all_geoms = [inside_geom]
for geom in outside_geom:
geom_bounds = Bounds(*geom.bounds)
if geom_bounds.left < pyramid.left:
geom = translate(geom, xoff=2*pyramid.right)
elif geom_bounds.right > pyramid.right:
geom = translate(geom, xoff=-2*pyramid.right)
all_geoms.append(geom)
if multipart:
return all_geoms
else:
return GeometryCollection(all_geoms)
else:
if multipart:
return [geometry]
else:
return geometry | [
"def",
"clip_geometry_to_srs_bounds",
"(",
"geometry",
",",
"pyramid",
",",
"multipart",
"=",
"False",
")",
":",
"if",
"not",
"geometry",
".",
"is_valid",
":",
"raise",
"ValueError",
"(",
"\"invalid geometry given\"",
")",
"pyramid_bbox",
"=",
"box",
"(",
"*",
... | Clip input geometry to SRS bounds of given TilePyramid.
If geometry passes the antimeridian, it will be split up in a multipart
geometry and shifted to within the SRS boundaries.
Note: geometry SRS must be the TilePyramid SRS!
- geometry: any shapely geometry
- pyramid: a TilePyramid object
- multipart: return list of geometries instead of a GeometryCollection | [
"Clip",
"input",
"geometry",
"to",
"SRS",
"bounds",
"of",
"given",
"TilePyramid",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_funcs.py#L19-L60 | train | 50,771 |
ungarj/tilematrix | tilematrix/_funcs.py | snap_bounds | def snap_bounds(bounds=None, tile_pyramid=None, zoom=None, pixelbuffer=0):
"""
Extend bounds to be aligned with union of tile bboxes.
- bounds: (left, bottom, right, top)
- tile_pyramid: a TilePyramid object
- zoom: target zoom level
- pixelbuffer: apply pixelbuffer
"""
bounds = Bounds(*bounds)
validate_zoom(zoom)
lb = _tile_from_xy(tile_pyramid, bounds.left, bounds.bottom, zoom, on_edge_use="rt")
rt = _tile_from_xy(tile_pyramid, bounds.right, bounds.top, zoom, on_edge_use="lb")
left, bottom, _, _ = lb.bounds(pixelbuffer)
_, _, right, top = rt.bounds(pixelbuffer)
return Bounds(left, bottom, right, top) | python | def snap_bounds(bounds=None, tile_pyramid=None, zoom=None, pixelbuffer=0):
"""
Extend bounds to be aligned with union of tile bboxes.
- bounds: (left, bottom, right, top)
- tile_pyramid: a TilePyramid object
- zoom: target zoom level
- pixelbuffer: apply pixelbuffer
"""
bounds = Bounds(*bounds)
validate_zoom(zoom)
lb = _tile_from_xy(tile_pyramid, bounds.left, bounds.bottom, zoom, on_edge_use="rt")
rt = _tile_from_xy(tile_pyramid, bounds.right, bounds.top, zoom, on_edge_use="lb")
left, bottom, _, _ = lb.bounds(pixelbuffer)
_, _, right, top = rt.bounds(pixelbuffer)
return Bounds(left, bottom, right, top) | [
"def",
"snap_bounds",
"(",
"bounds",
"=",
"None",
",",
"tile_pyramid",
"=",
"None",
",",
"zoom",
"=",
"None",
",",
"pixelbuffer",
"=",
"0",
")",
":",
"bounds",
"=",
"Bounds",
"(",
"*",
"bounds",
")",
"validate_zoom",
"(",
"zoom",
")",
"lb",
"=",
"_ti... | Extend bounds to be aligned with union of tile bboxes.
- bounds: (left, bottom, right, top)
- tile_pyramid: a TilePyramid object
- zoom: target zoom level
- pixelbuffer: apply pixelbuffer | [
"Extend",
"bounds",
"to",
"be",
"aligned",
"with",
"union",
"of",
"tile",
"bboxes",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_funcs.py#L63-L78 | train | 50,772 |
ungarj/tilematrix | tilematrix/_funcs.py | _verify_shape_bounds | def _verify_shape_bounds(shape, bounds):
"""Verify that shape corresponds to bounds apect ratio."""
if not isinstance(shape, (tuple, list)) or len(shape) != 2:
raise TypeError(
"shape must be a tuple or list with two elements: %s" % str(shape)
)
if not isinstance(bounds, (tuple, list)) or len(bounds) != 4:
raise TypeError(
"bounds must be a tuple or list with four elements: %s" % str(bounds)
)
shape = Shape(*shape)
bounds = Bounds(*bounds)
shape_ratio = shape.width / shape.height
bounds_ratio = (bounds.right - bounds.left) / (bounds.top - bounds.bottom)
if abs(shape_ratio - bounds_ratio) > DELTA:
min_length = min([
(bounds.right - bounds.left) / shape.width,
(bounds.top - bounds.bottom) / shape.height
])
proposed_bounds = Bounds(
bounds.left,
bounds.bottom,
bounds.left + shape.width * min_length,
bounds.bottom + shape.height * min_length
)
raise ValueError(
"shape ratio (%s) must equal bounds ratio (%s); try %s" % (
shape_ratio, bounds_ratio, proposed_bounds
)
) | python | def _verify_shape_bounds(shape, bounds):
"""Verify that shape corresponds to bounds apect ratio."""
if not isinstance(shape, (tuple, list)) or len(shape) != 2:
raise TypeError(
"shape must be a tuple or list with two elements: %s" % str(shape)
)
if not isinstance(bounds, (tuple, list)) or len(bounds) != 4:
raise TypeError(
"bounds must be a tuple or list with four elements: %s" % str(bounds)
)
shape = Shape(*shape)
bounds = Bounds(*bounds)
shape_ratio = shape.width / shape.height
bounds_ratio = (bounds.right - bounds.left) / (bounds.top - bounds.bottom)
if abs(shape_ratio - bounds_ratio) > DELTA:
min_length = min([
(bounds.right - bounds.left) / shape.width,
(bounds.top - bounds.bottom) / shape.height
])
proposed_bounds = Bounds(
bounds.left,
bounds.bottom,
bounds.left + shape.width * min_length,
bounds.bottom + shape.height * min_length
)
raise ValueError(
"shape ratio (%s) must equal bounds ratio (%s); try %s" % (
shape_ratio, bounds_ratio, proposed_bounds
)
) | [
"def",
"_verify_shape_bounds",
"(",
"shape",
",",
"bounds",
")",
":",
"if",
"not",
"isinstance",
"(",
"shape",
",",
"(",
"tuple",
",",
"list",
")",
")",
"or",
"len",
"(",
"shape",
")",
"!=",
"2",
":",
"raise",
"TypeError",
"(",
"\"shape must be a tuple o... | Verify that shape corresponds to bounds apect ratio. | [
"Verify",
"that",
"shape",
"corresponds",
"to",
"bounds",
"apect",
"ratio",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_funcs.py#L81-L110 | train | 50,773 |
ungarj/tilematrix | tilematrix/_funcs.py | _tile_intersecting_tilepyramid | def _tile_intersecting_tilepyramid(tile, tp):
"""Return all tiles from tilepyramid intersecting with tile."""
if tile.tp.grid != tp.grid:
raise ValueError("Tile and TilePyramid source grids must be the same.")
tile_metatiling = tile.tile_pyramid.metatiling
pyramid_metatiling = tp.metatiling
multiplier = tile_metatiling / pyramid_metatiling
if tile_metatiling > pyramid_metatiling:
return [
tp.tile(
tile.zoom,
int(multiplier) * tile.row + row_offset,
int(multiplier) * tile.col + col_offset
)
for row_offset, col_offset in product(
range(int(multiplier)), range(int(multiplier))
)
]
elif tile_metatiling < pyramid_metatiling:
return [tp.tile(
tile.zoom, int(multiplier * tile.row), int(multiplier * tile.col)
)]
else:
return [tp.tile(*tile.id)] | python | def _tile_intersecting_tilepyramid(tile, tp):
"""Return all tiles from tilepyramid intersecting with tile."""
if tile.tp.grid != tp.grid:
raise ValueError("Tile and TilePyramid source grids must be the same.")
tile_metatiling = tile.tile_pyramid.metatiling
pyramid_metatiling = tp.metatiling
multiplier = tile_metatiling / pyramid_metatiling
if tile_metatiling > pyramid_metatiling:
return [
tp.tile(
tile.zoom,
int(multiplier) * tile.row + row_offset,
int(multiplier) * tile.col + col_offset
)
for row_offset, col_offset in product(
range(int(multiplier)), range(int(multiplier))
)
]
elif tile_metatiling < pyramid_metatiling:
return [tp.tile(
tile.zoom, int(multiplier * tile.row), int(multiplier * tile.col)
)]
else:
return [tp.tile(*tile.id)] | [
"def",
"_tile_intersecting_tilepyramid",
"(",
"tile",
",",
"tp",
")",
":",
"if",
"tile",
".",
"tp",
".",
"grid",
"!=",
"tp",
".",
"grid",
":",
"raise",
"ValueError",
"(",
"\"Tile and TilePyramid source grids must be the same.\"",
")",
"tile_metatiling",
"=",
"tile... | Return all tiles from tilepyramid intersecting with tile. | [
"Return",
"all",
"tiles",
"from",
"tilepyramid",
"intersecting",
"with",
"tile",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_funcs.py#L126-L149 | train | 50,774 |
ungarj/tilematrix | tilematrix/_funcs.py | _global_tiles_from_bounds | def _global_tiles_from_bounds(tp, bounds, zoom):
"""Return also Tiles if bounds cross the antimeridian."""
seen = set()
# clip to tilepyramid top and bottom bounds
left, right = bounds.left, bounds.right
top = tp.top if bounds.top > tp.top else bounds.top
bottom = tp.bottom if bounds.bottom < tp.bottom else bounds.bottom
if left >= tp.left and right <= tp.right:
for tile in _tiles_from_cleaned_bounds(tp, bounds, zoom):
yield tile
# bounds overlap on the Western side with antimeridian
if left < tp.left:
for tile in chain(
# tiles west of antimeridian
_tiles_from_cleaned_bounds(
tp,
Bounds(left + (tp.right - tp.left), bottom, tp.right, top),
zoom
),
# tiles east of antimeridian
_tiles_from_cleaned_bounds(
tp, Bounds(tp.left, bottom, right, top), zoom
)
):
# make output tiles unique
if tile.id not in seen:
seen.add(tile.id)
yield tile
# bounds overlap on the Eastern side with antimeridian
if right > tp.right:
for tile in chain(
# tiles west of antimeridian
_tiles_from_cleaned_bounds(
tp, Bounds(left, bottom, tp.right, top), zoom
),
# tiles east of antimeridian
_tiles_from_cleaned_bounds(
tp,
Bounds(tp.left, bottom, right - (tp.right - tp.left), top),
zoom
)
):
# make output tiles unique
if tile.id not in seen:
seen.add(tile.id)
yield tile | python | def _global_tiles_from_bounds(tp, bounds, zoom):
"""Return also Tiles if bounds cross the antimeridian."""
seen = set()
# clip to tilepyramid top and bottom bounds
left, right = bounds.left, bounds.right
top = tp.top if bounds.top > tp.top else bounds.top
bottom = tp.bottom if bounds.bottom < tp.bottom else bounds.bottom
if left >= tp.left and right <= tp.right:
for tile in _tiles_from_cleaned_bounds(tp, bounds, zoom):
yield tile
# bounds overlap on the Western side with antimeridian
if left < tp.left:
for tile in chain(
# tiles west of antimeridian
_tiles_from_cleaned_bounds(
tp,
Bounds(left + (tp.right - tp.left), bottom, tp.right, top),
zoom
),
# tiles east of antimeridian
_tiles_from_cleaned_bounds(
tp, Bounds(tp.left, bottom, right, top), zoom
)
):
# make output tiles unique
if tile.id not in seen:
seen.add(tile.id)
yield tile
# bounds overlap on the Eastern side with antimeridian
if right > tp.right:
for tile in chain(
# tiles west of antimeridian
_tiles_from_cleaned_bounds(
tp, Bounds(left, bottom, tp.right, top), zoom
),
# tiles east of antimeridian
_tiles_from_cleaned_bounds(
tp,
Bounds(tp.left, bottom, right - (tp.right - tp.left), top),
zoom
)
):
# make output tiles unique
if tile.id not in seen:
seen.add(tile.id)
yield tile | [
"def",
"_global_tiles_from_bounds",
"(",
"tp",
",",
"bounds",
",",
"zoom",
")",
":",
"seen",
"=",
"set",
"(",
")",
"# clip to tilepyramid top and bottom bounds",
"left",
",",
"right",
"=",
"bounds",
".",
"left",
",",
"bounds",
".",
"right",
"top",
"=",
"tp",... | Return also Tiles if bounds cross the antimeridian. | [
"Return",
"also",
"Tiles",
"if",
"bounds",
"cross",
"the",
"antimeridian",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_funcs.py#L152-L201 | train | 50,775 |
Metatab/metapack | metapack/cli/open.py | open_args | def open_args(subparsers):
"""
The `mp open` command will open a resource with the system application, such as Excel or OpenOffice
"""
parser = subparsers.add_parser(
'open',
help='open a CSV resoruce with a system application',
description=open_args.__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.set_defaults(run_command=open_cmd)
parser.add_argument('metatabfile', nargs='?',
help="Path or URL to a metatab file. If not provided, defaults to 'metadata.csv' ")
return parser | python | def open_args(subparsers):
"""
The `mp open` command will open a resource with the system application, such as Excel or OpenOffice
"""
parser = subparsers.add_parser(
'open',
help='open a CSV resoruce with a system application',
description=open_args.__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.set_defaults(run_command=open_cmd)
parser.add_argument('metatabfile', nargs='?',
help="Path or URL to a metatab file. If not provided, defaults to 'metadata.csv' ")
return parser | [
"def",
"open_args",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'open'",
",",
"help",
"=",
"'open a CSV resoruce with a system application'",
",",
"description",
"=",
"open_args",
".",
"__doc__",
",",
"formatter_class",
"=",
... | The `mp open` command will open a resource with the system application, such as Excel or OpenOffice | [
"The",
"mp",
"open",
"command",
"will",
"open",
"a",
"resource",
"with",
"the",
"system",
"application",
"such",
"as",
"Excel",
"or",
"OpenOffice"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/cli/open.py#L23-L40 | train | 50,776 |
project-rig/rig | rig/place_and_route/route/ner.py | ner_net | def ner_net(source, destinations, width, height, wrap_around=False, radius=10):
"""Produce a shortest path tree for a given net using NER.
This is the kernel of the NER algorithm.
Parameters
----------
source : (x, y)
The coordinate of the source vertex.
destinations : iterable([(x, y), ...])
The coordinates of destination vertices.
width : int
Width of the system (nodes)
height : int
Height of the system (nodes)
wrap_around : bool
True if wrap-around links should be used, false if they should be
avoided.
radius : int
Radius of area to search from each node. 20 is arbitrarily selected in
the paper and shown to be acceptable in practice.
Returns
-------
(:py:class:`~.rig.place_and_route.routing_tree.RoutingTree`,
{(x,y): :py:class:`~.rig.place_and_route.routing_tree.RoutingTree`, ...})
A RoutingTree is produced rooted at the source and visiting all
destinations but which does not contain any vertices etc. For
convenience, a dictionarry mapping from destination (x, y) coordinates
to the associated RoutingTree is provided to allow the caller to insert
these items.
"""
# Map from (x, y) to RoutingTree objects
route = {source: RoutingTree(source)}
# Handle each destination, sorted by distance from the source, closest
# first.
for destination in sorted(destinations,
key=(lambda destination:
shortest_mesh_path_length(
to_xyz(source), to_xyz(destination))
if not wrap_around else
shortest_torus_path_length(
to_xyz(source), to_xyz(destination),
width, height))):
# We shall attempt to find our nearest neighbouring placed node.
neighbour = None
# Try to find a nearby (within radius hops) node in the routing tree
# that we can route to (falling back on just routing to the source).
#
# In an implementation according to the algorithm's original
# specification looks for nodes at each point in a growing set of rings
# of concentric hexagons. If it doesn't find any destinations this
# means an awful lot of checks: 1261 for the default radius of 20.
#
# An alternative (but behaviourally identical) implementation scans the
# list of all route nodes created so far and finds the closest node
# which is < radius hops (falling back on the origin if no node is
# closer than radius hops). This implementation requires one check per
# existing route node. In most routes this is probably a lot less than
# 1261 since most routes will probably have at most a few hundred route
# nodes by the time the last destination is being routed.
#
# Which implementation is best is a difficult question to answer:
# * In principle nets with quite localised connections (e.g.
# nearest-neighbour or centroids traffic) may route slightly more
# quickly with the original algorithm since it may very quickly find
# a neighbour.
# * In nets which connect very spaced-out destinations the second
# implementation may be quicker since in such a scenario it is
# unlikely that a neighbour will be found.
# * In extremely high-fan-out nets (e.g. broadcasts), the original
# method is very likely to perform *far* better than the alternative
# method since most iterations will complete immediately while the
# alternative method must scan *all* the route vertices.
# As such, it should be clear that neither method alone is 'best' and
# both have degenerate performance in certain completely reasonable
# styles of net. As a result, a simple heuristic is used to decide
# which technique to use.
#
# The following micro-benchmarks are crude estimate of the
# runtime-per-iteration of each approach (at least in the case of a
# torus topology)::
#
# $ # Original approach
# $ python -m timeit --setup 'x, y, w, h, r = 1, 2, 5, 10, \
# {x:None for x in range(10)}' \
# 'x += 1; y += 1; x %= w; y %= h; (x, y) in r'
# 1000000 loops, best of 3: 0.207 usec per loop
# $ # Alternative approach
# $ python -m timeit --setup 'from rig.geometry import \
# shortest_torus_path_length' \
# 'shortest_torus_path_length( \
# (0, 1, 2), (3, 2, 1), 10, 10)'
# 1000000 loops, best of 3: 0.666 usec per loop
#
# From this we can approximately suggest that the alternative approach
# is 3x more expensive per iteration. A very crude heuristic is to use
# the original approach when the number of route nodes is more than
# 1/3rd of the number of routes checked by the original method.
concentric_hexagons = memoized_concentric_hexagons(radius)
if len(concentric_hexagons) < len(route) / 3:
# Original approach: Start looking for route nodes in a concentric
# spiral pattern out from the destination node.
for x, y in concentric_hexagons:
x += destination[0]
y += destination[1]
if wrap_around:
x %= width
y %= height
if (x, y) in route:
neighbour = (x, y)
break
else:
# Alternative approach: Scan over every route node and check to see
# if any are < radius, picking the closest one if so.
neighbour = None
neighbour_distance = None
for candidate_neighbour in route:
if wrap_around:
distance = shortest_torus_path_length(
to_xyz(candidate_neighbour), to_xyz(destination),
width, height)
else:
distance = shortest_mesh_path_length(
to_xyz(candidate_neighbour), to_xyz(destination))
if distance <= radius and (neighbour is None or
distance < neighbour_distance):
neighbour = candidate_neighbour
neighbour_distance = distance
# Fall back on routing directly to the source if no nodes within radius
# hops of the destination was found.
if neighbour is None:
neighbour = source
# Find the shortest vector from the neighbour to this destination
if wrap_around:
vector = shortest_torus_path(to_xyz(neighbour),
to_xyz(destination),
width, height)
else:
vector = shortest_mesh_path(to_xyz(neighbour), to_xyz(destination))
# The longest-dimension-first route may inadvertently pass through an
# already connected node. If the route is allowed to pass through that
# node it would create a cycle in the route which would be VeryBad(TM).
# As a result, we work backward through the route and truncate it at
# the first point where the route intersects with a connected node.
ldf = longest_dimension_first(vector, neighbour, width, height)
i = len(ldf)
for direction, (x, y) in reversed(ldf):
i -= 1
if (x, y) in route:
# We've just bumped into a node which is already part of the
# route, this becomes our new neighbour and we truncate the LDF
# route. (Note ldf list is truncated just after the current
# position since it gives (direction, destination) pairs).
neighbour = (x, y)
ldf = ldf[i + 1:]
break
# Take the longest dimension first route.
last_node = route[neighbour]
for direction, (x, y) in ldf:
this_node = RoutingTree((x, y))
route[(x, y)] = this_node
last_node.children.append((Routes(direction), this_node))
last_node = this_node
return (route[source], route) | python | def ner_net(source, destinations, width, height, wrap_around=False, radius=10):
"""Produce a shortest path tree for a given net using NER.
This is the kernel of the NER algorithm.
Parameters
----------
source : (x, y)
The coordinate of the source vertex.
destinations : iterable([(x, y), ...])
The coordinates of destination vertices.
width : int
Width of the system (nodes)
height : int
Height of the system (nodes)
wrap_around : bool
True if wrap-around links should be used, false if they should be
avoided.
radius : int
Radius of area to search from each node. 20 is arbitrarily selected in
the paper and shown to be acceptable in practice.
Returns
-------
(:py:class:`~.rig.place_and_route.routing_tree.RoutingTree`,
{(x,y): :py:class:`~.rig.place_and_route.routing_tree.RoutingTree`, ...})
A RoutingTree is produced rooted at the source and visiting all
destinations but which does not contain any vertices etc. For
convenience, a dictionarry mapping from destination (x, y) coordinates
to the associated RoutingTree is provided to allow the caller to insert
these items.
"""
# Map from (x, y) to RoutingTree objects
route = {source: RoutingTree(source)}
# Handle each destination, sorted by distance from the source, closest
# first.
for destination in sorted(destinations,
key=(lambda destination:
shortest_mesh_path_length(
to_xyz(source), to_xyz(destination))
if not wrap_around else
shortest_torus_path_length(
to_xyz(source), to_xyz(destination),
width, height))):
# We shall attempt to find our nearest neighbouring placed node.
neighbour = None
# Try to find a nearby (within radius hops) node in the routing tree
# that we can route to (falling back on just routing to the source).
#
# In an implementation according to the algorithm's original
# specification looks for nodes at each point in a growing set of rings
# of concentric hexagons. If it doesn't find any destinations this
# means an awful lot of checks: 1261 for the default radius of 20.
#
# An alternative (but behaviourally identical) implementation scans the
# list of all route nodes created so far and finds the closest node
# which is < radius hops (falling back on the origin if no node is
# closer than radius hops). This implementation requires one check per
# existing route node. In most routes this is probably a lot less than
# 1261 since most routes will probably have at most a few hundred route
# nodes by the time the last destination is being routed.
#
# Which implementation is best is a difficult question to answer:
# * In principle nets with quite localised connections (e.g.
# nearest-neighbour or centroids traffic) may route slightly more
# quickly with the original algorithm since it may very quickly find
# a neighbour.
# * In nets which connect very spaced-out destinations the second
# implementation may be quicker since in such a scenario it is
# unlikely that a neighbour will be found.
# * In extremely high-fan-out nets (e.g. broadcasts), the original
# method is very likely to perform *far* better than the alternative
# method since most iterations will complete immediately while the
# alternative method must scan *all* the route vertices.
# As such, it should be clear that neither method alone is 'best' and
# both have degenerate performance in certain completely reasonable
# styles of net. As a result, a simple heuristic is used to decide
# which technique to use.
#
# The following micro-benchmarks are crude estimate of the
# runtime-per-iteration of each approach (at least in the case of a
# torus topology)::
#
# $ # Original approach
# $ python -m timeit --setup 'x, y, w, h, r = 1, 2, 5, 10, \
# {x:None for x in range(10)}' \
# 'x += 1; y += 1; x %= w; y %= h; (x, y) in r'
# 1000000 loops, best of 3: 0.207 usec per loop
# $ # Alternative approach
# $ python -m timeit --setup 'from rig.geometry import \
# shortest_torus_path_length' \
# 'shortest_torus_path_length( \
# (0, 1, 2), (3, 2, 1), 10, 10)'
# 1000000 loops, best of 3: 0.666 usec per loop
#
# From this we can approximately suggest that the alternative approach
# is 3x more expensive per iteration. A very crude heuristic is to use
# the original approach when the number of route nodes is more than
# 1/3rd of the number of routes checked by the original method.
concentric_hexagons = memoized_concentric_hexagons(radius)
if len(concentric_hexagons) < len(route) / 3:
# Original approach: Start looking for route nodes in a concentric
# spiral pattern out from the destination node.
for x, y in concentric_hexagons:
x += destination[0]
y += destination[1]
if wrap_around:
x %= width
y %= height
if (x, y) in route:
neighbour = (x, y)
break
else:
# Alternative approach: Scan over every route node and check to see
# if any are < radius, picking the closest one if so.
neighbour = None
neighbour_distance = None
for candidate_neighbour in route:
if wrap_around:
distance = shortest_torus_path_length(
to_xyz(candidate_neighbour), to_xyz(destination),
width, height)
else:
distance = shortest_mesh_path_length(
to_xyz(candidate_neighbour), to_xyz(destination))
if distance <= radius and (neighbour is None or
distance < neighbour_distance):
neighbour = candidate_neighbour
neighbour_distance = distance
# Fall back on routing directly to the source if no nodes within radius
# hops of the destination was found.
if neighbour is None:
neighbour = source
# Find the shortest vector from the neighbour to this destination
if wrap_around:
vector = shortest_torus_path(to_xyz(neighbour),
to_xyz(destination),
width, height)
else:
vector = shortest_mesh_path(to_xyz(neighbour), to_xyz(destination))
# The longest-dimension-first route may inadvertently pass through an
# already connected node. If the route is allowed to pass through that
# node it would create a cycle in the route which would be VeryBad(TM).
# As a result, we work backward through the route and truncate it at
# the first point where the route intersects with a connected node.
ldf = longest_dimension_first(vector, neighbour, width, height)
i = len(ldf)
for direction, (x, y) in reversed(ldf):
i -= 1
if (x, y) in route:
# We've just bumped into a node which is already part of the
# route, this becomes our new neighbour and we truncate the LDF
# route. (Note ldf list is truncated just after the current
# position since it gives (direction, destination) pairs).
neighbour = (x, y)
ldf = ldf[i + 1:]
break
# Take the longest dimension first route.
last_node = route[neighbour]
for direction, (x, y) in ldf:
this_node = RoutingTree((x, y))
route[(x, y)] = this_node
last_node.children.append((Routes(direction), this_node))
last_node = this_node
return (route[source], route) | [
"def",
"ner_net",
"(",
"source",
",",
"destinations",
",",
"width",
",",
"height",
",",
"wrap_around",
"=",
"False",
",",
"radius",
"=",
"10",
")",
":",
"# Map from (x, y) to RoutingTree objects",
"route",
"=",
"{",
"source",
":",
"RoutingTree",
"(",
"source",... | Produce a shortest path tree for a given net using NER.
This is the kernel of the NER algorithm.
Parameters
----------
source : (x, y)
The coordinate of the source vertex.
destinations : iterable([(x, y), ...])
The coordinates of destination vertices.
width : int
Width of the system (nodes)
height : int
Height of the system (nodes)
wrap_around : bool
True if wrap-around links should be used, false if they should be
avoided.
radius : int
Radius of area to search from each node. 20 is arbitrarily selected in
the paper and shown to be acceptable in practice.
Returns
-------
(:py:class:`~.rig.place_and_route.routing_tree.RoutingTree`,
{(x,y): :py:class:`~.rig.place_and_route.routing_tree.RoutingTree`, ...})
A RoutingTree is produced rooted at the source and visiting all
destinations but which does not contain any vertices etc. For
convenience, a dictionarry mapping from destination (x, y) coordinates
to the associated RoutingTree is provided to allow the caller to insert
these items. | [
"Produce",
"a",
"shortest",
"path",
"tree",
"for",
"a",
"given",
"net",
"using",
"NER",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/route/ner.py#L55-L228 | train | 50,777 |
project-rig/rig | rig/place_and_route/route/ner.py | route_has_dead_links | def route_has_dead_links(root, machine):
"""Quickly determine if a route uses any dead links.
Parameters
----------
root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree`
The root of the RoutingTree which contains nothing but RoutingTrees
(i.e. no vertices and links).
machine : :py:class:`~rig.place_and_route.Machine`
The machine in which the routes exist.
Returns
-------
bool
True if the route uses any dead/missing links, False otherwise.
"""
for direction, (x, y), routes in root.traverse():
for route in routes:
if (x, y, route) not in machine:
return True
return False | python | def route_has_dead_links(root, machine):
"""Quickly determine if a route uses any dead links.
Parameters
----------
root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree`
The root of the RoutingTree which contains nothing but RoutingTrees
(i.e. no vertices and links).
machine : :py:class:`~rig.place_and_route.Machine`
The machine in which the routes exist.
Returns
-------
bool
True if the route uses any dead/missing links, False otherwise.
"""
for direction, (x, y), routes in root.traverse():
for route in routes:
if (x, y, route) not in machine:
return True
return False | [
"def",
"route_has_dead_links",
"(",
"root",
",",
"machine",
")",
":",
"for",
"direction",
",",
"(",
"x",
",",
"y",
")",
",",
"routes",
"in",
"root",
".",
"traverse",
"(",
")",
":",
"for",
"route",
"in",
"routes",
":",
"if",
"(",
"x",
",",
"y",
",... | Quickly determine if a route uses any dead links.
Parameters
----------
root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree`
The root of the RoutingTree which contains nothing but RoutingTrees
(i.e. no vertices and links).
machine : :py:class:`~rig.place_and_route.Machine`
The machine in which the routes exist.
Returns
-------
bool
True if the route uses any dead/missing links, False otherwise. | [
"Quickly",
"determine",
"if",
"a",
"route",
"uses",
"any",
"dead",
"links",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/route/ner.py#L413-L433 | train | 50,778 |
project-rig/rig | rig/place_and_route/route/ner.py | avoid_dead_links | def avoid_dead_links(root, machine, wrap_around=False):
"""Modify a RoutingTree to route-around dead links in a Machine.
Uses A* to reconnect disconnected branches of the tree (due to dead links
in the machine).
Parameters
----------
root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree`
The root of the RoutingTree which contains nothing but RoutingTrees
(i.e. no vertices and links).
machine : :py:class:`~rig.place_and_route.Machine`
The machine in which the routes exist.
wrap_around : bool
Consider wrap-around links in pathfinding heuristics.
Returns
-------
(:py:class:`~.rig.place_and_route.routing_tree.RoutingTree`,
{(x,y): :py:class:`~.rig.place_and_route.routing_tree.RoutingTree`, ...})
A new RoutingTree is produced rooted as before. A dictionarry mapping
from (x, y) to the associated RoutingTree is provided for convenience.
Raises
------
:py:class:~rig.place_and_route.exceptions.MachineHasDisconnectedSubregion`
If a path to reconnect the tree cannot be found.
"""
# Make a copy of the RoutingTree with all broken parts disconnected
root, lookup, broken_links = copy_and_disconnect_tree(root, machine)
# For each disconnected subtree, use A* to connect the tree to *any* other
# disconnected subtree. Note that this process will eventually result in
# all disconnected subtrees being connected, the result is a fully
# connected tree.
for parent, child in broken_links:
child_chips = set(c.chip for c in lookup[child])
# Try to reconnect broken links to any other part of the tree
# (excluding this broken subtree itself since that would create a
# cycle).
path = a_star(child, parent,
set(lookup).difference(child_chips),
machine, wrap_around)
# Add new RoutingTree nodes to reconnect the child to the tree.
last_node = lookup[path[0][1]]
last_direction = path[0][0]
for direction, (x, y) in path[1:]:
if (x, y) not in child_chips:
# This path segment traverses new ground so we must create a
# new RoutingTree for the segment.
new_node = RoutingTree((x, y))
# A* will not traverse anything but chips in this tree so this
# assert is meerly a sanity check that this ocurred correctly.
assert (x, y) not in lookup, "Cycle created."
lookup[(x, y)] = new_node
else:
# This path segment overlaps part of the disconnected tree
# (A* doesn't know where the disconnected tree is and thus
# doesn't avoid it). To prevent cycles being introduced, this
# overlapped node is severed from its parent and merged as part
# of the A* path.
new_node = lookup[(x, y)]
# Find the node's current parent and disconnect it.
for node in lookup[child]: # pragma: no branch
dn = [(d, n) for d, n in node.children if n == new_node]
assert len(dn) <= 1
if dn:
node.children.remove(dn[0])
# A node can only have one parent so we can stop now.
break
last_node.children.append((Routes(last_direction), new_node))
last_node = new_node
last_direction = direction
last_node.children.append((last_direction, lookup[child]))
return (root, lookup) | python | def avoid_dead_links(root, machine, wrap_around=False):
"""Modify a RoutingTree to route-around dead links in a Machine.
Uses A* to reconnect disconnected branches of the tree (due to dead links
in the machine).
Parameters
----------
root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree`
The root of the RoutingTree which contains nothing but RoutingTrees
(i.e. no vertices and links).
machine : :py:class:`~rig.place_and_route.Machine`
The machine in which the routes exist.
wrap_around : bool
Consider wrap-around links in pathfinding heuristics.
Returns
-------
(:py:class:`~.rig.place_and_route.routing_tree.RoutingTree`,
{(x,y): :py:class:`~.rig.place_and_route.routing_tree.RoutingTree`, ...})
A new RoutingTree is produced rooted as before. A dictionarry mapping
from (x, y) to the associated RoutingTree is provided for convenience.
Raises
------
:py:class:~rig.place_and_route.exceptions.MachineHasDisconnectedSubregion`
If a path to reconnect the tree cannot be found.
"""
# Make a copy of the RoutingTree with all broken parts disconnected
root, lookup, broken_links = copy_and_disconnect_tree(root, machine)
# For each disconnected subtree, use A* to connect the tree to *any* other
# disconnected subtree. Note that this process will eventually result in
# all disconnected subtrees being connected, the result is a fully
# connected tree.
for parent, child in broken_links:
child_chips = set(c.chip for c in lookup[child])
# Try to reconnect broken links to any other part of the tree
# (excluding this broken subtree itself since that would create a
# cycle).
path = a_star(child, parent,
set(lookup).difference(child_chips),
machine, wrap_around)
# Add new RoutingTree nodes to reconnect the child to the tree.
last_node = lookup[path[0][1]]
last_direction = path[0][0]
for direction, (x, y) in path[1:]:
if (x, y) not in child_chips:
# This path segment traverses new ground so we must create a
# new RoutingTree for the segment.
new_node = RoutingTree((x, y))
# A* will not traverse anything but chips in this tree so this
# assert is meerly a sanity check that this ocurred correctly.
assert (x, y) not in lookup, "Cycle created."
lookup[(x, y)] = new_node
else:
# This path segment overlaps part of the disconnected tree
# (A* doesn't know where the disconnected tree is and thus
# doesn't avoid it). To prevent cycles being introduced, this
# overlapped node is severed from its parent and merged as part
# of the A* path.
new_node = lookup[(x, y)]
# Find the node's current parent and disconnect it.
for node in lookup[child]: # pragma: no branch
dn = [(d, n) for d, n in node.children if n == new_node]
assert len(dn) <= 1
if dn:
node.children.remove(dn[0])
# A node can only have one parent so we can stop now.
break
last_node.children.append((Routes(last_direction), new_node))
last_node = new_node
last_direction = direction
last_node.children.append((last_direction, lookup[child]))
return (root, lookup) | [
"def",
"avoid_dead_links",
"(",
"root",
",",
"machine",
",",
"wrap_around",
"=",
"False",
")",
":",
"# Make a copy of the RoutingTree with all broken parts disconnected",
"root",
",",
"lookup",
",",
"broken_links",
"=",
"copy_and_disconnect_tree",
"(",
"root",
",",
"mac... | Modify a RoutingTree to route-around dead links in a Machine.
Uses A* to reconnect disconnected branches of the tree (due to dead links
in the machine).
Parameters
----------
root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree`
The root of the RoutingTree which contains nothing but RoutingTrees
(i.e. no vertices and links).
machine : :py:class:`~rig.place_and_route.Machine`
The machine in which the routes exist.
wrap_around : bool
Consider wrap-around links in pathfinding heuristics.
Returns
-------
(:py:class:`~.rig.place_and_route.routing_tree.RoutingTree`,
{(x,y): :py:class:`~.rig.place_and_route.routing_tree.RoutingTree`, ...})
A new RoutingTree is produced rooted as before. A dictionarry mapping
from (x, y) to the associated RoutingTree is provided for convenience.
Raises
------
:py:class:~rig.place_and_route.exceptions.MachineHasDisconnectedSubregion`
If a path to reconnect the tree cannot be found. | [
"Modify",
"a",
"RoutingTree",
"to",
"route",
"-",
"around",
"dead",
"links",
"in",
"a",
"Machine",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/route/ner.py#L436-L514 | train | 50,779 |
project-rig/rig | rig/scripts/rig_ps.py | match | def match(string, patterns):
"""Given a string return true if it matches the supplied list of
patterns.
Parameters
----------
string : str
The string to be matched.
patterns : None or [pattern, ...]
The series of regular expressions to attempt to match.
"""
if patterns is None:
return True
else:
return any(re.match(pattern, string)
for pattern in patterns) | python | def match(string, patterns):
"""Given a string return true if it matches the supplied list of
patterns.
Parameters
----------
string : str
The string to be matched.
patterns : None or [pattern, ...]
The series of regular expressions to attempt to match.
"""
if patterns is None:
return True
else:
return any(re.match(pattern, string)
for pattern in patterns) | [
"def",
"match",
"(",
"string",
",",
"patterns",
")",
":",
"if",
"patterns",
"is",
"None",
":",
"return",
"True",
"else",
":",
"return",
"any",
"(",
"re",
".",
"match",
"(",
"pattern",
",",
"string",
")",
"for",
"pattern",
"in",
"patterns",
")"
] | Given a string return true if it matches the supplied list of
patterns.
Parameters
----------
string : str
The string to be matched.
patterns : None or [pattern, ...]
The series of regular expressions to attempt to match. | [
"Given",
"a",
"string",
"return",
"true",
"if",
"it",
"matches",
"the",
"supplied",
"list",
"of",
"patterns",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/scripts/rig_ps.py#L21-L36 | train | 50,780 |
project-rig/rig | rig/scripts/rig_ps.py | get_process_list | def get_process_list(mc, x_=None, y_=None, p_=None,
app_ids=None, applications=None, states=None):
"""Scan a SpiNNaker system's cores filtering by the specified features.
Generates
-------
(x, y, core, state, runtime_exception, application, app_id)
"""
system_info = mc.get_system_info()
for (x, y), chip_info in sorted(iteritems(system_info)):
if x_ is not None and x_ != x:
continue
if y_ is not None and y_ != y:
continue
for p in range(chip_info.num_cores):
if p_ is not None and p_ != p:
continue
try:
status = mc.get_processor_status(x=x, y=y, p=p)
keep = (match(str(status.app_id), app_ids) and
match(status.app_name, applications) and
match(status.cpu_state.name, states))
if keep:
yield (x, y, p,
status.cpu_state,
status.rt_code,
status.app_name,
status.app_id)
except SCPError as e:
# If an error occurs while communicating with a chip, we bodge
# it into the "cpu_status" field and continue (note that it
# will never get filtered out).
class DeadStatus(object):
name = "{}: {}".format(e.__class__.__name__, str(e))
yield (x, y, p, DeadStatus(), None, "", -1) | python | def get_process_list(mc, x_=None, y_=None, p_=None,
app_ids=None, applications=None, states=None):
"""Scan a SpiNNaker system's cores filtering by the specified features.
Generates
-------
(x, y, core, state, runtime_exception, application, app_id)
"""
system_info = mc.get_system_info()
for (x, y), chip_info in sorted(iteritems(system_info)):
if x_ is not None and x_ != x:
continue
if y_ is not None and y_ != y:
continue
for p in range(chip_info.num_cores):
if p_ is not None and p_ != p:
continue
try:
status = mc.get_processor_status(x=x, y=y, p=p)
keep = (match(str(status.app_id), app_ids) and
match(status.app_name, applications) and
match(status.cpu_state.name, states))
if keep:
yield (x, y, p,
status.cpu_state,
status.rt_code,
status.app_name,
status.app_id)
except SCPError as e:
# If an error occurs while communicating with a chip, we bodge
# it into the "cpu_status" field and continue (note that it
# will never get filtered out).
class DeadStatus(object):
name = "{}: {}".format(e.__class__.__name__, str(e))
yield (x, y, p, DeadStatus(), None, "", -1) | [
"def",
"get_process_list",
"(",
"mc",
",",
"x_",
"=",
"None",
",",
"y_",
"=",
"None",
",",
"p_",
"=",
"None",
",",
"app_ids",
"=",
"None",
",",
"applications",
"=",
"None",
",",
"states",
"=",
"None",
")",
":",
"system_info",
"=",
"mc",
".",
"get_s... | Scan a SpiNNaker system's cores filtering by the specified features.
Generates
-------
(x, y, core, state, runtime_exception, application, app_id) | [
"Scan",
"a",
"SpiNNaker",
"system",
"s",
"cores",
"filtering",
"by",
"the",
"specified",
"features",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/scripts/rig_ps.py#L39-L77 | train | 50,781 |
project-rig/rig | rig/place_and_route/utils.py | build_application_map | def build_application_map(vertices_applications, placements, allocations,
core_resource=Cores):
"""Build a mapping from application to a list of cores where the
application is used.
This utility function assumes that each vertex is associated with a
specific application.
Parameters
----------
vertices_applications : {vertex: application, ...}
Applications are represented by the path of their APLX file.
placements : {vertex: (x, y), ...}
allocations : {vertex: {resource: slice, ...}, ...}
One of these resources should match the `core_resource` argument.
core_resource : object
The resource identifier which represents cores.
Returns
-------
{application: {(x, y) : set([c, ...]), ...}, ...}
For each application, for each used chip a set of core numbers onto
which the application should be loaded.
"""
application_map = defaultdict(lambda: defaultdict(set))
for vertex, application in iteritems(vertices_applications):
chip_cores = application_map[application][placements[vertex]]
core_slice = allocations[vertex].get(core_resource, slice(0, 0))
chip_cores.update(range(core_slice.start, core_slice.stop))
return application_map | python | def build_application_map(vertices_applications, placements, allocations,
core_resource=Cores):
"""Build a mapping from application to a list of cores where the
application is used.
This utility function assumes that each vertex is associated with a
specific application.
Parameters
----------
vertices_applications : {vertex: application, ...}
Applications are represented by the path of their APLX file.
placements : {vertex: (x, y), ...}
allocations : {vertex: {resource: slice, ...}, ...}
One of these resources should match the `core_resource` argument.
core_resource : object
The resource identifier which represents cores.
Returns
-------
{application: {(x, y) : set([c, ...]), ...}, ...}
For each application, for each used chip a set of core numbers onto
which the application should be loaded.
"""
application_map = defaultdict(lambda: defaultdict(set))
for vertex, application in iteritems(vertices_applications):
chip_cores = application_map[application][placements[vertex]]
core_slice = allocations[vertex].get(core_resource, slice(0, 0))
chip_cores.update(range(core_slice.start, core_slice.stop))
return application_map | [
"def",
"build_application_map",
"(",
"vertices_applications",
",",
"placements",
",",
"allocations",
",",
"core_resource",
"=",
"Cores",
")",
":",
"application_map",
"=",
"defaultdict",
"(",
"lambda",
":",
"defaultdict",
"(",
"set",
")",
")",
"for",
"vertex",
",... | Build a mapping from application to a list of cores where the
application is used.
This utility function assumes that each vertex is associated with a
specific application.
Parameters
----------
vertices_applications : {vertex: application, ...}
Applications are represented by the path of their APLX file.
placements : {vertex: (x, y), ...}
allocations : {vertex: {resource: slice, ...}, ...}
One of these resources should match the `core_resource` argument.
core_resource : object
The resource identifier which represents cores.
Returns
-------
{application: {(x, y) : set([c, ...]), ...}, ...}
For each application, for each used chip a set of core numbers onto
which the application should be loaded. | [
"Build",
"a",
"mapping",
"from",
"application",
"to",
"a",
"list",
"of",
"cores",
"where",
"the",
"application",
"is",
"used",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/utils.py#L222-L253 | train | 50,782 |
NicolasLM/spinach | spinach/contrib/sentry.py | register_sentry | def register_sentry(raven_client, namespace: Optional[str]=None,
send_retries: bool=False):
"""Register the Sentry integration.
Exceptions making jobs fail are sent to Sentry.
:param raven_client: configured Raven client used to sent errors to Sentry
:param namespace: optionally only register the Sentry integration for a
particular Spinach :class:`Engine`
:param send_retries: whether to also send to Sentry exceptions resulting
in a job being retried
"""
@signals.job_started.connect_via(namespace)
def job_started(namespace, job, **kwargs):
raven_client.context.activate()
raven_client.transaction.push(job.task_name)
@signals.job_finished.connect_via(namespace)
def job_finished(namespace, job, **kwargs):
raven_client.transaction.pop(job.task_name)
raven_client.context.clear()
@signals.job_failed.connect_via(namespace)
def job_failed(namespace, job, **kwargs):
raven_client.captureException(
extra={attr: getattr(job, attr) for attr in job.__slots__}
)
if send_retries:
@signals.job_schedule_retry.connect_via(namespace)
def job_schedule_retry(namespace, job, **kwargs):
raven_client.captureException(
extra={attr: getattr(job, attr) for attr in job.__slots__}
) | python | def register_sentry(raven_client, namespace: Optional[str]=None,
send_retries: bool=False):
"""Register the Sentry integration.
Exceptions making jobs fail are sent to Sentry.
:param raven_client: configured Raven client used to sent errors to Sentry
:param namespace: optionally only register the Sentry integration for a
particular Spinach :class:`Engine`
:param send_retries: whether to also send to Sentry exceptions resulting
in a job being retried
"""
@signals.job_started.connect_via(namespace)
def job_started(namespace, job, **kwargs):
raven_client.context.activate()
raven_client.transaction.push(job.task_name)
@signals.job_finished.connect_via(namespace)
def job_finished(namespace, job, **kwargs):
raven_client.transaction.pop(job.task_name)
raven_client.context.clear()
@signals.job_failed.connect_via(namespace)
def job_failed(namespace, job, **kwargs):
raven_client.captureException(
extra={attr: getattr(job, attr) for attr in job.__slots__}
)
if send_retries:
@signals.job_schedule_retry.connect_via(namespace)
def job_schedule_retry(namespace, job, **kwargs):
raven_client.captureException(
extra={attr: getattr(job, attr) for attr in job.__slots__}
) | [
"def",
"register_sentry",
"(",
"raven_client",
",",
"namespace",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"send_retries",
":",
"bool",
"=",
"False",
")",
":",
"@",
"signals",
".",
"job_started",
".",
"connect_via",
"(",
"namespace",
")",
"def",
... | Register the Sentry integration.
Exceptions making jobs fail are sent to Sentry.
:param raven_client: configured Raven client used to sent errors to Sentry
:param namespace: optionally only register the Sentry integration for a
particular Spinach :class:`Engine`
:param send_retries: whether to also send to Sentry exceptions resulting
in a job being retried | [
"Register",
"the",
"Sentry",
"integration",
"."
] | 0122f916643101eab5cdc1f3da662b9446e372aa | https://github.com/NicolasLM/spinach/blob/0122f916643101eab5cdc1f3da662b9446e372aa/spinach/contrib/sentry.py#L6-L40 | train | 50,783 |
Metatab/metapack | metapack/cli/url.py | add_resource | def add_resource(mt_file, ref, cache):
"""Add a resources entry, downloading the intuiting the file, replacing entries with
the same reference"""
if isinstance(mt_file, MetapackDoc):
doc = mt_file
else:
doc = MetapackDoc(mt_file)
if not 'Resources' in doc:
doc.new_section('Resources')
doc['Resources'].args = [e for e in set(doc['Resources'].args + ['Name', 'StartLine', 'HeaderLines', 'Encoding']) if
e]
seen_names = set()
u = parse_app_url(ref)
# The web and file URLs don't list the same.
if u.proto == 'file':
entries = u.list()
else:
entries = [ssu for su in u.list() for ssu in su.list()]
errors = []
for e in entries:
if not add_single_resource(doc, e, cache=cache, seen_names=seen_names):
errors.append(e)
if errors:
prt()
warn("Found, but failed to add these urls:")
for e in errors:
print(' ', e)
write_doc(doc, mt_file) | python | def add_resource(mt_file, ref, cache):
"""Add a resources entry, downloading the intuiting the file, replacing entries with
the same reference"""
if isinstance(mt_file, MetapackDoc):
doc = mt_file
else:
doc = MetapackDoc(mt_file)
if not 'Resources' in doc:
doc.new_section('Resources')
doc['Resources'].args = [e for e in set(doc['Resources'].args + ['Name', 'StartLine', 'HeaderLines', 'Encoding']) if
e]
seen_names = set()
u = parse_app_url(ref)
# The web and file URLs don't list the same.
if u.proto == 'file':
entries = u.list()
else:
entries = [ssu for su in u.list() for ssu in su.list()]
errors = []
for e in entries:
if not add_single_resource(doc, e, cache=cache, seen_names=seen_names):
errors.append(e)
if errors:
prt()
warn("Found, but failed to add these urls:")
for e in errors:
print(' ', e)
write_doc(doc, mt_file) | [
"def",
"add_resource",
"(",
"mt_file",
",",
"ref",
",",
"cache",
")",
":",
"if",
"isinstance",
"(",
"mt_file",
",",
"MetapackDoc",
")",
":",
"doc",
"=",
"mt_file",
"else",
":",
"doc",
"=",
"MetapackDoc",
"(",
"mt_file",
")",
"if",
"not",
"'Resources'",
... | Add a resources entry, downloading the intuiting the file, replacing entries with
the same reference | [
"Add",
"a",
"resources",
"entry",
"downloading",
"the",
"intuiting",
"the",
"file",
"replacing",
"entries",
"with",
"the",
"same",
"reference"
] | 8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6 | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/cli/url.py#L92-L130 | train | 50,784 |
ungarj/tilematrix | tilematrix/_tile.py | Tile.bounds | def bounds(self, pixelbuffer=0):
"""
Return Tile boundaries.
- pixelbuffer: tile buffer in pixels
"""
left = self._left
bottom = self._bottom
right = self._right
top = self._top
if pixelbuffer:
offset = self.pixel_x_size * float(pixelbuffer)
left -= offset
bottom -= offset
right += offset
top += offset
# on global grids clip at northern and southern TilePyramid bound
if self.tp.grid.is_global:
top = min([top, self.tile_pyramid.top])
bottom = max([bottom, self.tile_pyramid.bottom])
return Bounds(left, bottom, right, top) | python | def bounds(self, pixelbuffer=0):
"""
Return Tile boundaries.
- pixelbuffer: tile buffer in pixels
"""
left = self._left
bottom = self._bottom
right = self._right
top = self._top
if pixelbuffer:
offset = self.pixel_x_size * float(pixelbuffer)
left -= offset
bottom -= offset
right += offset
top += offset
# on global grids clip at northern and southern TilePyramid bound
if self.tp.grid.is_global:
top = min([top, self.tile_pyramid.top])
bottom = max([bottom, self.tile_pyramid.bottom])
return Bounds(left, bottom, right, top) | [
"def",
"bounds",
"(",
"self",
",",
"pixelbuffer",
"=",
"0",
")",
":",
"left",
"=",
"self",
".",
"_left",
"bottom",
"=",
"self",
".",
"_bottom",
"right",
"=",
"self",
".",
"_right",
"top",
"=",
"self",
".",
"_top",
"if",
"pixelbuffer",
":",
"offset",
... | Return Tile boundaries.
- pixelbuffer: tile buffer in pixels | [
"Return",
"Tile",
"boundaries",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tile.py#L93-L113 | train | 50,785 |
ungarj/tilematrix | tilematrix/_tile.py | Tile.affine | def affine(self, pixelbuffer=0):
"""
Return an Affine object of tile.
- pixelbuffer: tile buffer in pixels
"""
return Affine(
self.pixel_x_size,
0,
self.bounds(pixelbuffer).left,
0,
-self.pixel_y_size,
self.bounds(pixelbuffer).top
) | python | def affine(self, pixelbuffer=0):
"""
Return an Affine object of tile.
- pixelbuffer: tile buffer in pixels
"""
return Affine(
self.pixel_x_size,
0,
self.bounds(pixelbuffer).left,
0,
-self.pixel_y_size,
self.bounds(pixelbuffer).top
) | [
"def",
"affine",
"(",
"self",
",",
"pixelbuffer",
"=",
"0",
")",
":",
"return",
"Affine",
"(",
"self",
".",
"pixel_x_size",
",",
"0",
",",
"self",
".",
"bounds",
"(",
"pixelbuffer",
")",
".",
"left",
",",
"0",
",",
"-",
"self",
".",
"pixel_y_size",
... | Return an Affine object of tile.
- pixelbuffer: tile buffer in pixels | [
"Return",
"an",
"Affine",
"object",
"of",
"tile",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tile.py#L123-L136 | train | 50,786 |
ungarj/tilematrix | tilematrix/_tile.py | Tile.shape | def shape(self, pixelbuffer=0):
"""
Return a tuple of tile height and width.
- pixelbuffer: tile buffer in pixels
"""
# apply pixelbuffers
height = self._base_shape.height + 2 * pixelbuffer
width = self._base_shape.width + 2 * pixelbuffer
if pixelbuffer and self.tp.grid.is_global:
# on first and last row, remove pixelbuffer on top or bottom
matrix_height = self.tile_pyramid.matrix_height(self.zoom)
if matrix_height == 1:
height = self._base_shape.height
elif self.row in [0, matrix_height - 1]:
height = self._base_shape.height + pixelbuffer
return Shape(height=height, width=width) | python | def shape(self, pixelbuffer=0):
"""
Return a tuple of tile height and width.
- pixelbuffer: tile buffer in pixels
"""
# apply pixelbuffers
height = self._base_shape.height + 2 * pixelbuffer
width = self._base_shape.width + 2 * pixelbuffer
if pixelbuffer and self.tp.grid.is_global:
# on first and last row, remove pixelbuffer on top or bottom
matrix_height = self.tile_pyramid.matrix_height(self.zoom)
if matrix_height == 1:
height = self._base_shape.height
elif self.row in [0, matrix_height - 1]:
height = self._base_shape.height + pixelbuffer
return Shape(height=height, width=width) | [
"def",
"shape",
"(",
"self",
",",
"pixelbuffer",
"=",
"0",
")",
":",
"# apply pixelbuffers",
"height",
"=",
"self",
".",
"_base_shape",
".",
"height",
"+",
"2",
"*",
"pixelbuffer",
"width",
"=",
"self",
".",
"_base_shape",
".",
"width",
"+",
"2",
"*",
... | Return a tuple of tile height and width.
- pixelbuffer: tile buffer in pixels | [
"Return",
"a",
"tuple",
"of",
"tile",
"height",
"and",
"width",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tile.py#L138-L154 | train | 50,787 |
ungarj/tilematrix | tilematrix/_tile.py | Tile.is_valid | def is_valid(self):
"""Return True if tile is available in tile pyramid."""
if not all([
isinstance(self.zoom, int),
self.zoom >= 0,
isinstance(self.row, int),
self.row >= 0,
isinstance(self.col, int),
self.col >= 0
]):
raise TypeError("zoom, col and row must be integers >= 0")
cols = self.tile_pyramid.matrix_width(self.zoom)
rows = self.tile_pyramid.matrix_height(self.zoom)
if self.col >= cols:
raise ValueError("col (%s) exceeds matrix width (%s)" % (self.col, cols))
if self.row >= rows:
raise ValueError("row (%s) exceeds matrix height (%s)" % (self.row, rows))
return True | python | def is_valid(self):
"""Return True if tile is available in tile pyramid."""
if not all([
isinstance(self.zoom, int),
self.zoom >= 0,
isinstance(self.row, int),
self.row >= 0,
isinstance(self.col, int),
self.col >= 0
]):
raise TypeError("zoom, col and row must be integers >= 0")
cols = self.tile_pyramid.matrix_width(self.zoom)
rows = self.tile_pyramid.matrix_height(self.zoom)
if self.col >= cols:
raise ValueError("col (%s) exceeds matrix width (%s)" % (self.col, cols))
if self.row >= rows:
raise ValueError("row (%s) exceeds matrix height (%s)" % (self.row, rows))
return True | [
"def",
"is_valid",
"(",
"self",
")",
":",
"if",
"not",
"all",
"(",
"[",
"isinstance",
"(",
"self",
".",
"zoom",
",",
"int",
")",
",",
"self",
".",
"zoom",
">=",
"0",
",",
"isinstance",
"(",
"self",
".",
"row",
",",
"int",
")",
",",
"self",
".",... | Return True if tile is available in tile pyramid. | [
"Return",
"True",
"if",
"tile",
"is",
"available",
"in",
"tile",
"pyramid",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tile.py#L156-L173 | train | 50,788 |
ungarj/tilematrix | tilematrix/_tile.py | Tile.get_parent | def get_parent(self):
"""Return tile from previous zoom level."""
return None if self.zoom == 0 else self.tile_pyramid.tile(
self.zoom - 1, self.row // 2, self.col // 2
) | python | def get_parent(self):
"""Return tile from previous zoom level."""
return None if self.zoom == 0 else self.tile_pyramid.tile(
self.zoom - 1, self.row // 2, self.col // 2
) | [
"def",
"get_parent",
"(",
"self",
")",
":",
"return",
"None",
"if",
"self",
".",
"zoom",
"==",
"0",
"else",
"self",
".",
"tile_pyramid",
".",
"tile",
"(",
"self",
".",
"zoom",
"-",
"1",
",",
"self",
".",
"row",
"//",
"2",
",",
"self",
".",
"col",... | Return tile from previous zoom level. | [
"Return",
"tile",
"from",
"previous",
"zoom",
"level",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tile.py#L175-L179 | train | 50,789 |
ungarj/tilematrix | tilematrix/_tile.py | Tile.get_children | def get_children(self):
"""Return tiles from next zoom level."""
next_zoom = self.zoom + 1
return [
self.tile_pyramid.tile(
next_zoom,
self.row * 2 + row_offset,
self.col * 2 + col_offset
)
for row_offset, col_offset in [
(0, 0), # top left
(0, 1), # top right
(1, 1), # bottom right
(1, 0), # bottom left
]
if all([
self.row * 2 + row_offset < self.tp.matrix_height(next_zoom),
self.col * 2 + col_offset < self.tp.matrix_width(next_zoom)
])
] | python | def get_children(self):
"""Return tiles from next zoom level."""
next_zoom = self.zoom + 1
return [
self.tile_pyramid.tile(
next_zoom,
self.row * 2 + row_offset,
self.col * 2 + col_offset
)
for row_offset, col_offset in [
(0, 0), # top left
(0, 1), # top right
(1, 1), # bottom right
(1, 0), # bottom left
]
if all([
self.row * 2 + row_offset < self.tp.matrix_height(next_zoom),
self.col * 2 + col_offset < self.tp.matrix_width(next_zoom)
])
] | [
"def",
"get_children",
"(",
"self",
")",
":",
"next_zoom",
"=",
"self",
".",
"zoom",
"+",
"1",
"return",
"[",
"self",
".",
"tile_pyramid",
".",
"tile",
"(",
"next_zoom",
",",
"self",
".",
"row",
"*",
"2",
"+",
"row_offset",
",",
"self",
".",
"col",
... | Return tiles from next zoom level. | [
"Return",
"tiles",
"from",
"next",
"zoom",
"level",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tile.py#L181-L200 | train | 50,790 |
ungarj/tilematrix | tilematrix/_tile.py | Tile.get_neighbors | def get_neighbors(self, connectedness=8):
"""
Return tile neighbors.
Tile neighbors are unique, i.e. in some edge cases, where both the left
and right neighbor wrapped around the antimeridian is the same. Also,
neighbors ouside the northern and southern TilePyramid boundaries are
excluded, because they are invalid.
-------------
| 8 | 1 | 5 |
-------------
| 4 | x | 2 |
-------------
| 7 | 3 | 6 |
-------------
- connectedness: [4 or 8] return four direct neighbors or all eight.
"""
if connectedness not in [4, 8]:
raise ValueError("only connectedness values 8 or 4 are allowed")
unique_neighbors = {}
# 4-connected neighborsfor pyramid
matrix_offsets = [
(-1, 0), # 1: above
(0, 1), # 2: right
(1, 0), # 3: below
(0, -1) # 4: left
]
if connectedness == 8:
matrix_offsets.extend([
(-1, 1), # 5: above right
(1, 1), # 6: below right
(1, -1), # 7: below left
(-1, -1) # 8: above left
])
for row_offset, col_offset in matrix_offsets:
new_row = self.row + row_offset
new_col = self.col + col_offset
# omit if row is outside of tile matrix
if new_row < 0 or new_row >= self.tp.matrix_height(self.zoom):
continue
# wrap around antimeridian if new column is outside of tile matrix
if new_col < 0:
if not self.tp.is_global:
continue
new_col = self.tp.matrix_width(self.zoom) + new_col
elif new_col >= self.tp.matrix_width(self.zoom):
if not self.tp.is_global:
continue
new_col -= self.tp.matrix_width(self.zoom)
# omit if new tile is current tile
if new_row == self.row and new_col == self.col:
continue
# create new tile
unique_neighbors[(new_row, new_col)] = self.tp.tile(
self.zoom, new_row, new_col
)
return unique_neighbors.values() | python | def get_neighbors(self, connectedness=8):
"""
Return tile neighbors.
Tile neighbors are unique, i.e. in some edge cases, where both the left
and right neighbor wrapped around the antimeridian is the same. Also,
neighbors ouside the northern and southern TilePyramid boundaries are
excluded, because they are invalid.
-------------
| 8 | 1 | 5 |
-------------
| 4 | x | 2 |
-------------
| 7 | 3 | 6 |
-------------
- connectedness: [4 or 8] return four direct neighbors or all eight.
"""
if connectedness not in [4, 8]:
raise ValueError("only connectedness values 8 or 4 are allowed")
unique_neighbors = {}
# 4-connected neighborsfor pyramid
matrix_offsets = [
(-1, 0), # 1: above
(0, 1), # 2: right
(1, 0), # 3: below
(0, -1) # 4: left
]
if connectedness == 8:
matrix_offsets.extend([
(-1, 1), # 5: above right
(1, 1), # 6: below right
(1, -1), # 7: below left
(-1, -1) # 8: above left
])
for row_offset, col_offset in matrix_offsets:
new_row = self.row + row_offset
new_col = self.col + col_offset
# omit if row is outside of tile matrix
if new_row < 0 or new_row >= self.tp.matrix_height(self.zoom):
continue
# wrap around antimeridian if new column is outside of tile matrix
if new_col < 0:
if not self.tp.is_global:
continue
new_col = self.tp.matrix_width(self.zoom) + new_col
elif new_col >= self.tp.matrix_width(self.zoom):
if not self.tp.is_global:
continue
new_col -= self.tp.matrix_width(self.zoom)
# omit if new tile is current tile
if new_row == self.row and new_col == self.col:
continue
# create new tile
unique_neighbors[(new_row, new_col)] = self.tp.tile(
self.zoom, new_row, new_col
)
return unique_neighbors.values() | [
"def",
"get_neighbors",
"(",
"self",
",",
"connectedness",
"=",
"8",
")",
":",
"if",
"connectedness",
"not",
"in",
"[",
"4",
",",
"8",
"]",
":",
"raise",
"ValueError",
"(",
"\"only connectedness values 8 or 4 are allowed\"",
")",
"unique_neighbors",
"=",
"{",
... | Return tile neighbors.
Tile neighbors are unique, i.e. in some edge cases, where both the left
and right neighbor wrapped around the antimeridian is the same. Also,
neighbors ouside the northern and southern TilePyramid boundaries are
excluded, because they are invalid.
-------------
| 8 | 1 | 5 |
-------------
| 4 | x | 2 |
-------------
| 7 | 3 | 6 |
-------------
- connectedness: [4 or 8] return four direct neighbors or all eight. | [
"Return",
"tile",
"neighbors",
"."
] | 6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268 | https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tile.py#L202-L263 | train | 50,791 |
project-rig/rig | rig/bitfield.py | BitField.add_field | def add_field(self, identifier, length=None, start_at=None, tags=None):
"""Add a new field to the BitField.
If any existing fields' values are set, the newly created field will
become a child of those fields. This means that this field will exist
only when the parent fields' values are set as they are currently.
Parameters
----------
identifier : str
A identifier for the field. Must be a valid python identifier.
Field names must be unique within the scope in which they exist and
are only valid within that scope. For example::
>>> bf = BitField(32)
>>> bf.add_field("a")
>>> # Can add multiple fields with the same name if they exist
>>> # in different scopes
>>> bf0 = bf(a=0)
>>> bf0.add_field("b", length=4)
>>> bf1 = bf(a=1)
>>> bf1.add_field("b", length=8)
>>> # Can't add multiple fields with the same name which exist
>>> # within the same or nested scopes.
>>> bf.add_field("a")
Traceback (most recent call last):
ValueError: Field with identifier 'a' already exists
>>> bf.add_field("b")
Traceback (most recent call last):
ValueError: Field with identifier 'b' already exists
Here *three* fields are defined, one called "a" and the other two
called "b". The two fields called "b" are completely unrelated
(they may differ in size, position and associated set of tags) and
are distinguished by the fact that one exists when a=0 and the
other when a=1.
length : int or None
The number of bits in the field. If None the field will be
automatically assigned a length long enough for the largest value
assigned.
start_at : int or None
0-based index of least significant bit of the field within the
bit field. If None the field will be automatically located in free
space in the bit field.
tags : string or collection of strings or None
A (possibly empty) set of tags used to classify the field. Tags
should be valid Python identifiers. If a string, the string must be
a single tag or a space-separated list of tags. If *None*, an empty
set of tags is assumed. These tags are applied recursively to all
fields of which this field is a child.
Raises
------
ValueError
If any the field overlaps with another one or does not fit within
the bit field. Note that fields with unspecified lengths and
positions do not undergo such checks until their length and
position become known when :py:meth:`.assign_fields` is called.
"""
# Check for zero-length fields
if length is not None and length <= 0:
raise ValueError("Fields must be at least one bit in length.")
# Check for fields which don't fit in the bit field
if (start_at is not None and
(0 <= start_at >= self.length or
start_at + (length or 1) > self.length)):
raise ValueError(
"Field doesn't fit within {}-bit bit field.".format(
self.length))
# Check for fields which occupy the same bits
if start_at is not None:
end_at = start_at + (length or 1)
for other_identifier, other_field in \
self.fields.potential_fields(self.field_values):
if other_field.start_at is not None:
other_start_at = other_field.start_at
other_end_at = other_start_at + (other_field.length or 1)
if end_at > other_start_at and other_end_at > start_at:
raise ValueError(
"Field '{}' (range {}-{}) "
"overlaps field '{}' (range {}-{})".format(
identifier,
start_at, end_at,
other_identifier,
other_start_at, other_end_at))
# Normalise tags type
if type(tags) is str:
tags = set(tags.split())
elif tags is None:
tags = set()
else:
tags = set(tags)
# Add the field (checking that the identifier is unique in the process)
field = type(self)._Field(length, start_at, tags)
self.fields.add_field(field, identifier, self.field_values)
# Add tags to all parents of this field
for parent_identifier in self.fields.get_field_requirements(
identifier, self.field_values):
parent = self.fields.get_field(parent_identifier,
self.field_values)
parent.tags.update(tags) | python | def add_field(self, identifier, length=None, start_at=None, tags=None):
"""Add a new field to the BitField.
If any existing fields' values are set, the newly created field will
become a child of those fields. This means that this field will exist
only when the parent fields' values are set as they are currently.
Parameters
----------
identifier : str
A identifier for the field. Must be a valid python identifier.
Field names must be unique within the scope in which they exist and
are only valid within that scope. For example::
>>> bf = BitField(32)
>>> bf.add_field("a")
>>> # Can add multiple fields with the same name if they exist
>>> # in different scopes
>>> bf0 = bf(a=0)
>>> bf0.add_field("b", length=4)
>>> bf1 = bf(a=1)
>>> bf1.add_field("b", length=8)
>>> # Can't add multiple fields with the same name which exist
>>> # within the same or nested scopes.
>>> bf.add_field("a")
Traceback (most recent call last):
ValueError: Field with identifier 'a' already exists
>>> bf.add_field("b")
Traceback (most recent call last):
ValueError: Field with identifier 'b' already exists
Here *three* fields are defined, one called "a" and the other two
called "b". The two fields called "b" are completely unrelated
(they may differ in size, position and associated set of tags) and
are distinguished by the fact that one exists when a=0 and the
other when a=1.
length : int or None
The number of bits in the field. If None the field will be
automatically assigned a length long enough for the largest value
assigned.
start_at : int or None
0-based index of least significant bit of the field within the
bit field. If None the field will be automatically located in free
space in the bit field.
tags : string or collection of strings or None
A (possibly empty) set of tags used to classify the field. Tags
should be valid Python identifiers. If a string, the string must be
a single tag or a space-separated list of tags. If *None*, an empty
set of tags is assumed. These tags are applied recursively to all
fields of which this field is a child.
Raises
------
ValueError
If any the field overlaps with another one or does not fit within
the bit field. Note that fields with unspecified lengths and
positions do not undergo such checks until their length and
position become known when :py:meth:`.assign_fields` is called.
"""
# Check for zero-length fields
if length is not None and length <= 0:
raise ValueError("Fields must be at least one bit in length.")
# Check for fields which don't fit in the bit field
if (start_at is not None and
(0 <= start_at >= self.length or
start_at + (length or 1) > self.length)):
raise ValueError(
"Field doesn't fit within {}-bit bit field.".format(
self.length))
# Check for fields which occupy the same bits
if start_at is not None:
end_at = start_at + (length or 1)
for other_identifier, other_field in \
self.fields.potential_fields(self.field_values):
if other_field.start_at is not None:
other_start_at = other_field.start_at
other_end_at = other_start_at + (other_field.length or 1)
if end_at > other_start_at and other_end_at > start_at:
raise ValueError(
"Field '{}' (range {}-{}) "
"overlaps field '{}' (range {}-{})".format(
identifier,
start_at, end_at,
other_identifier,
other_start_at, other_end_at))
# Normalise tags type
if type(tags) is str:
tags = set(tags.split())
elif tags is None:
tags = set()
else:
tags = set(tags)
# Add the field (checking that the identifier is unique in the process)
field = type(self)._Field(length, start_at, tags)
self.fields.add_field(field, identifier, self.field_values)
# Add tags to all parents of this field
for parent_identifier in self.fields.get_field_requirements(
identifier, self.field_values):
parent = self.fields.get_field(parent_identifier,
self.field_values)
parent.tags.update(tags) | [
"def",
"add_field",
"(",
"self",
",",
"identifier",
",",
"length",
"=",
"None",
",",
"start_at",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"# Check for zero-length fields",
"if",
"length",
"is",
"not",
"None",
"and",
"length",
"<=",
"0",
":",
"rai... | Add a new field to the BitField.
If any existing fields' values are set, the newly created field will
become a child of those fields. This means that this field will exist
only when the parent fields' values are set as they are currently.
Parameters
----------
identifier : str
A identifier for the field. Must be a valid python identifier.
Field names must be unique within the scope in which they exist and
are only valid within that scope. For example::
>>> bf = BitField(32)
>>> bf.add_field("a")
>>> # Can add multiple fields with the same name if they exist
>>> # in different scopes
>>> bf0 = bf(a=0)
>>> bf0.add_field("b", length=4)
>>> bf1 = bf(a=1)
>>> bf1.add_field("b", length=8)
>>> # Can't add multiple fields with the same name which exist
>>> # within the same or nested scopes.
>>> bf.add_field("a")
Traceback (most recent call last):
ValueError: Field with identifier 'a' already exists
>>> bf.add_field("b")
Traceback (most recent call last):
ValueError: Field with identifier 'b' already exists
Here *three* fields are defined, one called "a" and the other two
called "b". The two fields called "b" are completely unrelated
(they may differ in size, position and associated set of tags) and
are distinguished by the fact that one exists when a=0 and the
other when a=1.
length : int or None
The number of bits in the field. If None the field will be
automatically assigned a length long enough for the largest value
assigned.
start_at : int or None
0-based index of least significant bit of the field within the
bit field. If None the field will be automatically located in free
space in the bit field.
tags : string or collection of strings or None
A (possibly empty) set of tags used to classify the field. Tags
should be valid Python identifiers. If a string, the string must be
a single tag or a space-separated list of tags. If *None*, an empty
set of tags is assumed. These tags are applied recursively to all
fields of which this field is a child.
Raises
------
ValueError
If any the field overlaps with another one or does not fit within
the bit field. Note that fields with unspecified lengths and
positions do not undergo such checks until their length and
position become known when :py:meth:`.assign_fields` is called. | [
"Add",
"a",
"new",
"field",
"to",
"the",
"BitField",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/bitfield.py#L81-L189 | train | 50,792 |
project-rig/rig | rig/bitfield.py | BitField.get_value | def get_value(self, tag=None, field=None):
"""Generate an integer whose bits are set according to the values of
fields in this bit field. All other bits are set to zero.
Parameters
----------
tag : str
Optionally specifies that the value should only include fields with
the specified tag.
field : str
Optionally specifies that the value should only include the
specified field.
Raises
------
ValueError
If a field's value, length or position has not been defined. (e.g.
:py:meth:`.assign_fields` has not been called).
UnknownTagError
If the tag specified using the `tag` argument does not exist.
UnavailableFieldError
If the field specified using the `field` argument does not exist or
is not available.
"""
assert not (tag is not None and field is not None), \
"Cannot filter by tag and field simultaneously."
selected_fields = self._select_by_field_or_tag(tag, field)
# Check all selected fields have values defined
missing_fields_idents = set(selected_fields) - set(self.field_values)
if missing_fields_idents:
raise ValueError(
"Cannot generate value with undefined fields {}.".format(
", ".join("'{}'".format(f)
for f in missing_fields_idents)))
# Build the value
value = 0
for identifier, field in iteritems(selected_fields):
if field.length is None or field.start_at is None:
raise ValueError(
"Field '{}' does not have a fixed size/position.".format(
identifier))
value |= (self.field_values[identifier] <<
field.start_at)
return value | python | def get_value(self, tag=None, field=None):
"""Generate an integer whose bits are set according to the values of
fields in this bit field. All other bits are set to zero.
Parameters
----------
tag : str
Optionally specifies that the value should only include fields with
the specified tag.
field : str
Optionally specifies that the value should only include the
specified field.
Raises
------
ValueError
If a field's value, length or position has not been defined. (e.g.
:py:meth:`.assign_fields` has not been called).
UnknownTagError
If the tag specified using the `tag` argument does not exist.
UnavailableFieldError
If the field specified using the `field` argument does not exist or
is not available.
"""
assert not (tag is not None and field is not None), \
"Cannot filter by tag and field simultaneously."
selected_fields = self._select_by_field_or_tag(tag, field)
# Check all selected fields have values defined
missing_fields_idents = set(selected_fields) - set(self.field_values)
if missing_fields_idents:
raise ValueError(
"Cannot generate value with undefined fields {}.".format(
", ".join("'{}'".format(f)
for f in missing_fields_idents)))
# Build the value
value = 0
for identifier, field in iteritems(selected_fields):
if field.length is None or field.start_at is None:
raise ValueError(
"Field '{}' does not have a fixed size/position.".format(
identifier))
value |= (self.field_values[identifier] <<
field.start_at)
return value | [
"def",
"get_value",
"(",
"self",
",",
"tag",
"=",
"None",
",",
"field",
"=",
"None",
")",
":",
"assert",
"not",
"(",
"tag",
"is",
"not",
"None",
"and",
"field",
"is",
"not",
"None",
")",
",",
"\"Cannot filter by tag and field simultaneously.\"",
"selected_fi... | Generate an integer whose bits are set according to the values of
fields in this bit field. All other bits are set to zero.
Parameters
----------
tag : str
Optionally specifies that the value should only include fields with
the specified tag.
field : str
Optionally specifies that the value should only include the
specified field.
Raises
------
ValueError
If a field's value, length or position has not been defined. (e.g.
:py:meth:`.assign_fields` has not been called).
UnknownTagError
If the tag specified using the `tag` argument does not exist.
UnavailableFieldError
If the field specified using the `field` argument does not exist or
is not available. | [
"Generate",
"an",
"integer",
"whose",
"bits",
"are",
"set",
"according",
"to",
"the",
"values",
"of",
"fields",
"in",
"this",
"bit",
"field",
".",
"All",
"other",
"bits",
"are",
"set",
"to",
"zero",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/bitfield.py#L260-L307 | train | 50,793 |
project-rig/rig | rig/bitfield.py | BitField.get_mask | def get_mask(self, tag=None, field=None):
"""Get the mask for all fields which exist in the current bit field.
Parameters
----------
tag : str
Optionally specifies that the mask should only include fields with
the specified tag.
field : str
Optionally specifies that the mask should only include the
specified field.
Raises
------
ValueError
If a field's length or position has not been defined. (e.g.
:py:meth:`.assign_fields` has not been called).
UnknownTagError
If the tag specified using the `tag` argument does not exist.
UnavailableFieldError
If the field specified using the `field` argument does not exist or
is not available.
"""
if tag is not None and field is not None:
raise TypeError("get_mask() takes exactly one keyword argument, "
"either 'field' or 'tag' (both given)")
selected_fields = self._select_by_field_or_tag(tag, field)
# Build the mask (and throw an exception if we encounter a field
# without a fixed size/length.
mask = 0
for identifier, field in iteritems(selected_fields):
if field.length is None or field.start_at is None:
raise ValueError(
"Field '{}' does not have a fixed size/position.".format(
identifier))
mask |= ((1 << field.length) - 1) << field.start_at
return mask | python | def get_mask(self, tag=None, field=None):
"""Get the mask for all fields which exist in the current bit field.
Parameters
----------
tag : str
Optionally specifies that the mask should only include fields with
the specified tag.
field : str
Optionally specifies that the mask should only include the
specified field.
Raises
------
ValueError
If a field's length or position has not been defined. (e.g.
:py:meth:`.assign_fields` has not been called).
UnknownTagError
If the tag specified using the `tag` argument does not exist.
UnavailableFieldError
If the field specified using the `field` argument does not exist or
is not available.
"""
if tag is not None and field is not None:
raise TypeError("get_mask() takes exactly one keyword argument, "
"either 'field' or 'tag' (both given)")
selected_fields = self._select_by_field_or_tag(tag, field)
# Build the mask (and throw an exception if we encounter a field
# without a fixed size/length.
mask = 0
for identifier, field in iteritems(selected_fields):
if field.length is None or field.start_at is None:
raise ValueError(
"Field '{}' does not have a fixed size/position.".format(
identifier))
mask |= ((1 << field.length) - 1) << field.start_at
return mask | [
"def",
"get_mask",
"(",
"self",
",",
"tag",
"=",
"None",
",",
"field",
"=",
"None",
")",
":",
"if",
"tag",
"is",
"not",
"None",
"and",
"field",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"\"get_mask() takes exactly one keyword argument, \"",
"\"eit... | Get the mask for all fields which exist in the current bit field.
Parameters
----------
tag : str
Optionally specifies that the mask should only include fields with
the specified tag.
field : str
Optionally specifies that the mask should only include the
specified field.
Raises
------
ValueError
If a field's length or position has not been defined. (e.g.
:py:meth:`.assign_fields` has not been called).
UnknownTagError
If the tag specified using the `tag` argument does not exist.
UnavailableFieldError
If the field specified using the `field` argument does not exist or
is not available. | [
"Get",
"the",
"mask",
"for",
"all",
"fields",
"which",
"exist",
"in",
"the",
"current",
"bit",
"field",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/bitfield.py#L309-L348 | train | 50,794 |
project-rig/rig | rig/bitfield.py | BitField.get_tags | def get_tags(self, field):
"""Get the set of tags for a given field.
.. note::
The named field must be accessible given the current set of values
defined.
Parameters
----------
field : str
The field whose tag should be read.
Returns
-------
set([tag, ...])
Raises
------
UnavailableFieldError
If the field does not exist or is not available.
"""
return self.fields.get_field(field, self.field_values).tags.copy() | python | def get_tags(self, field):
"""Get the set of tags for a given field.
.. note::
The named field must be accessible given the current set of values
defined.
Parameters
----------
field : str
The field whose tag should be read.
Returns
-------
set([tag, ...])
Raises
------
UnavailableFieldError
If the field does not exist or is not available.
"""
return self.fields.get_field(field, self.field_values).tags.copy() | [
"def",
"get_tags",
"(",
"self",
",",
"field",
")",
":",
"return",
"self",
".",
"fields",
".",
"get_field",
"(",
"field",
",",
"self",
".",
"field_values",
")",
".",
"tags",
".",
"copy",
"(",
")"
] | Get the set of tags for a given field.
.. note::
The named field must be accessible given the current set of values
defined.
Parameters
----------
field : str
The field whose tag should be read.
Returns
-------
set([tag, ...])
Raises
------
UnavailableFieldError
If the field does not exist or is not available. | [
"Get",
"the",
"set",
"of",
"tags",
"for",
"a",
"given",
"field",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/bitfield.py#L396-L417 | train | 50,795 |
project-rig/rig | rig/bitfield.py | BitField.get_location_and_length | def get_location_and_length(self, field):
"""Get the location and length of a field within the bitfield.
.. note::
The named field must be accessible given the current set of values
defined.
Parameters
----------
field : str
The field of interest.
Returns
-------
location, length
A pair of integers defining the bit-number of the least-significant
bit in the field and the total number of bits in the field
respectively.
Raises
------
ValueError
If a field's length or position has not been defined. (e.g.
:py:meth:`.assign_fields` has not been called).
UnavailableFieldError
If the field does not exist or is not available.
"""
field_obj = self.fields.get_field(field, self.field_values)
if field_obj.length is None or field_obj.start_at is None:
raise ValueError(
"Field '{}' does not have a fixed size/position.".format(
field))
return (field_obj.start_at, field_obj.length) | python | def get_location_and_length(self, field):
"""Get the location and length of a field within the bitfield.
.. note::
The named field must be accessible given the current set of values
defined.
Parameters
----------
field : str
The field of interest.
Returns
-------
location, length
A pair of integers defining the bit-number of the least-significant
bit in the field and the total number of bits in the field
respectively.
Raises
------
ValueError
If a field's length or position has not been defined. (e.g.
:py:meth:`.assign_fields` has not been called).
UnavailableFieldError
If the field does not exist or is not available.
"""
field_obj = self.fields.get_field(field, self.field_values)
if field_obj.length is None or field_obj.start_at is None:
raise ValueError(
"Field '{}' does not have a fixed size/position.".format(
field))
return (field_obj.start_at, field_obj.length) | [
"def",
"get_location_and_length",
"(",
"self",
",",
"field",
")",
":",
"field_obj",
"=",
"self",
".",
"fields",
".",
"get_field",
"(",
"field",
",",
"self",
".",
"field_values",
")",
"if",
"field_obj",
".",
"length",
"is",
"None",
"or",
"field_obj",
".",
... | Get the location and length of a field within the bitfield.
.. note::
The named field must be accessible given the current set of values
defined.
Parameters
----------
field : str
The field of interest.
Returns
-------
location, length
A pair of integers defining the bit-number of the least-significant
bit in the field and the total number of bits in the field
respectively.
Raises
------
ValueError
If a field's length or position has not been defined. (e.g.
:py:meth:`.assign_fields` has not been called).
UnavailableFieldError
If the field does not exist or is not available. | [
"Get",
"the",
"location",
"and",
"length",
"of",
"a",
"field",
"within",
"the",
"bitfield",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/bitfield.py#L419-L453 | train | 50,796 |
project-rig/rig | rig/bitfield.py | BitField.assign_fields | def assign_fields(self):
"""Assign a position & length to any fields which do not have one.
Users should typically call this method after all field values have
been assigned, otherwise fields may be fixed at an inadequate size.
"""
# We must fix fields at every level of the hierarchy separately
# (otherwise fields of children won't be allowed to overlap). Here we
# do a breadth-first iteration over the hierarchy to fix fields with
# given starting positions; then we do depth-first to fix other fields.
# Assign all fields with a fixed starting position in breadth first,
# top-down order. The breadth-first ensures that children's fixed
# position fields must fit around the fixed position fields of their
# parents.
queue = [(self.fields, {})]
while queue:
node, field_values = queue.pop(0)
# Assign all fields at this level whose position is fixed
self._assign_fields(node.fields, field_values,
assign_positions=False)
# Breadth-first search through children
for requirements, child in iteritems(node.children):
requirements = dict(requirements)
requirements.update(field_values)
queue.append((child, requirements))
# Assign all fields with movable starting positions in leaf-first,
# depth-first order. The depth first ordering for variable position
# fields ensures that parents don't allocate fields in positions which
# would collide with fixed and variable position fields their children
# have already allocated.
def recurse_assign_fields(node=self.fields, field_values={}):
# Assign fields of child nodes first (allowing them to allocate
# bits independently)
for requirements, child in iteritems(node.children):
child_field_values = dict(requirements)
child_field_values.update(field_values)
recurse_assign_fields(child, child_field_values)
# Finally, assign all remaining fields at this level in the tree
self._assign_fields(node.fields, field_values,
assign_positions=True)
recurse_assign_fields() | python | def assign_fields(self):
"""Assign a position & length to any fields which do not have one.
Users should typically call this method after all field values have
been assigned, otherwise fields may be fixed at an inadequate size.
"""
# We must fix fields at every level of the hierarchy separately
# (otherwise fields of children won't be allowed to overlap). Here we
# do a breadth-first iteration over the hierarchy to fix fields with
# given starting positions; then we do depth-first to fix other fields.
# Assign all fields with a fixed starting position in breadth first,
# top-down order. The breadth-first ensures that children's fixed
# position fields must fit around the fixed position fields of their
# parents.
queue = [(self.fields, {})]
while queue:
node, field_values = queue.pop(0)
# Assign all fields at this level whose position is fixed
self._assign_fields(node.fields, field_values,
assign_positions=False)
# Breadth-first search through children
for requirements, child in iteritems(node.children):
requirements = dict(requirements)
requirements.update(field_values)
queue.append((child, requirements))
# Assign all fields with movable starting positions in leaf-first,
# depth-first order. The depth first ordering for variable position
# fields ensures that parents don't allocate fields in positions which
# would collide with fixed and variable position fields their children
# have already allocated.
def recurse_assign_fields(node=self.fields, field_values={}):
# Assign fields of child nodes first (allowing them to allocate
# bits independently)
for requirements, child in iteritems(node.children):
child_field_values = dict(requirements)
child_field_values.update(field_values)
recurse_assign_fields(child, child_field_values)
# Finally, assign all remaining fields at this level in the tree
self._assign_fields(node.fields, field_values,
assign_positions=True)
recurse_assign_fields() | [
"def",
"assign_fields",
"(",
"self",
")",
":",
"# We must fix fields at every level of the hierarchy separately",
"# (otherwise fields of children won't be allowed to overlap). Here we",
"# do a breadth-first iteration over the hierarchy to fix fields with",
"# given starting positions; then we do... | Assign a position & length to any fields which do not have one.
Users should typically call this method after all field values have
been assigned, otherwise fields may be fixed at an inadequate size. | [
"Assign",
"a",
"position",
"&",
"length",
"to",
"any",
"fields",
"which",
"do",
"not",
"have",
"one",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/bitfield.py#L455-L501 | train | 50,797 |
project-rig/rig | rig/bitfield.py | BitField._assign_fields | def _assign_fields(self, identifiers, field_values,
assign_positions, assigned_bits=0):
"""For internal use only. Assign lengths & positions to a subset of all
potential fields with the supplied field_values.
This method will check for any assigned bits of all potential fields
but will only assign those fields whose identifiers are provided.
Parameters
----------
identifiers : iterable of identifiers
The identifiers of the fields to assign
field_values : {identifier: value, ...}
The values held by various fields (used to access the correct
identifiers)
assign_positions : bool
If False, will only assign lengths to fields whose positions are
already known. Otherwise lengths and positions will be assigned to
all fields as necessary.
assigned_bits : int
A bit mask of bits which are already allocated. (Note that this
will automatically be extended with any already-assigned potential
fields' bits.)
Returns
-------
int
Mask of which bits which are assigned to fields after fields have
been assigned.
"""
# Calculate a mask of already allocated fields' bits
for i, f in self.fields.potential_fields(field_values):
if f.length is not None and f.start_at is not None:
assigned_bits |= ((1 << f.length) - 1) << f.start_at
# Allocate all specified fields
for identifier in identifiers:
field = self.fields.get_field(identifier, field_values)
if field.length is not None and field.start_at is not None:
# Already allocated, do nothing!
pass
elif assign_positions or field.start_at is not None:
assigned_bits |= self._assign_field(assigned_bits,
identifier,
field_values)
return assigned_bits | python | def _assign_fields(self, identifiers, field_values,
assign_positions, assigned_bits=0):
"""For internal use only. Assign lengths & positions to a subset of all
potential fields with the supplied field_values.
This method will check for any assigned bits of all potential fields
but will only assign those fields whose identifiers are provided.
Parameters
----------
identifiers : iterable of identifiers
The identifiers of the fields to assign
field_values : {identifier: value, ...}
The values held by various fields (used to access the correct
identifiers)
assign_positions : bool
If False, will only assign lengths to fields whose positions are
already known. Otherwise lengths and positions will be assigned to
all fields as necessary.
assigned_bits : int
A bit mask of bits which are already allocated. (Note that this
will automatically be extended with any already-assigned potential
fields' bits.)
Returns
-------
int
Mask of which bits which are assigned to fields after fields have
been assigned.
"""
# Calculate a mask of already allocated fields' bits
for i, f in self.fields.potential_fields(field_values):
if f.length is not None and f.start_at is not None:
assigned_bits |= ((1 << f.length) - 1) << f.start_at
# Allocate all specified fields
for identifier in identifiers:
field = self.fields.get_field(identifier, field_values)
if field.length is not None and field.start_at is not None:
# Already allocated, do nothing!
pass
elif assign_positions or field.start_at is not None:
assigned_bits |= self._assign_field(assigned_bits,
identifier,
field_values)
return assigned_bits | [
"def",
"_assign_fields",
"(",
"self",
",",
"identifiers",
",",
"field_values",
",",
"assign_positions",
",",
"assigned_bits",
"=",
"0",
")",
":",
"# Calculate a mask of already allocated fields' bits",
"for",
"i",
",",
"f",
"in",
"self",
".",
"fields",
".",
"poten... | For internal use only. Assign lengths & positions to a subset of all
potential fields with the supplied field_values.
This method will check for any assigned bits of all potential fields
but will only assign those fields whose identifiers are provided.
Parameters
----------
identifiers : iterable of identifiers
The identifiers of the fields to assign
field_values : {identifier: value, ...}
The values held by various fields (used to access the correct
identifiers)
assign_positions : bool
If False, will only assign lengths to fields whose positions are
already known. Otherwise lengths and positions will be assigned to
all fields as necessary.
assigned_bits : int
A bit mask of bits which are already allocated. (Note that this
will automatically be extended with any already-assigned potential
fields' bits.)
Returns
-------
int
Mask of which bits which are assigned to fields after fields have
been assigned. | [
"For",
"internal",
"use",
"only",
".",
"Assign",
"lengths",
"&",
"positions",
"to",
"a",
"subset",
"of",
"all",
"potential",
"fields",
"with",
"the",
"supplied",
"field_values",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/bitfield.py#L857-L903 | train | 50,798 |
project-rig/rig | rig/bitfield.py | BitField._assign_field | def _assign_field(self, assigned_bits, identifier, field_values):
"""For internal use only. Assign a length and position to a field
which may have either one of these values missing.
Parameters
----------
assigned_bits : int
A bit mask of bits already in use by other fields
identifier : str
The identifier of the field to assign
field_values : {identifier: value, ...}
The values held by various fields (used to access the correct
identifier)
Returns
-------
int
Mask of which bits which are assigned to fields after this field
has been assigned.
"""
field = self.fields.get_field(identifier, field_values)
length = field.length
if length is None:
# Assign lengths based on values
length = int(log(field.max_value, 2)) + 1
start_at = field.start_at
if start_at is None:
# Force a failure if no better space is found
start_at = self.length
# Try every position until a space is found
for bit in range(0, self.length - length):
field_bits = ((1 << length) - 1) << bit
if not (assigned_bits & field_bits):
start_at = bit
assigned_bits |= field_bits
break
else:
# A start position has been forced, ensure that it can be fulfilled
field_bits = ((1 << length) - 1) << start_at
if assigned_bits & field_bits:
raise ValueError(
"{}-bit field {} with fixed position does not fit in "
"{}.".format(
field.length,
self.fields.get_field_human_readable(identifier,
field_values),
type(self).__name__
)
)
# Mark these bits as assigned
assigned_bits |= field_bits
# Check that the calculated field is within the bit field
if start_at + length <= self.length:
field.length = length
field.start_at = start_at
else:
raise ValueError(
"{}-bit field {} does not fit in {}.".format(
field.length,
self.fields.get_field_human_readable(identifier,
field_values),
type(self).__name__
)
)
return assigned_bits | python | def _assign_field(self, assigned_bits, identifier, field_values):
"""For internal use only. Assign a length and position to a field
which may have either one of these values missing.
Parameters
----------
assigned_bits : int
A bit mask of bits already in use by other fields
identifier : str
The identifier of the field to assign
field_values : {identifier: value, ...}
The values held by various fields (used to access the correct
identifier)
Returns
-------
int
Mask of which bits which are assigned to fields after this field
has been assigned.
"""
field = self.fields.get_field(identifier, field_values)
length = field.length
if length is None:
# Assign lengths based on values
length = int(log(field.max_value, 2)) + 1
start_at = field.start_at
if start_at is None:
# Force a failure if no better space is found
start_at = self.length
# Try every position until a space is found
for bit in range(0, self.length - length):
field_bits = ((1 << length) - 1) << bit
if not (assigned_bits & field_bits):
start_at = bit
assigned_bits |= field_bits
break
else:
# A start position has been forced, ensure that it can be fulfilled
field_bits = ((1 << length) - 1) << start_at
if assigned_bits & field_bits:
raise ValueError(
"{}-bit field {} with fixed position does not fit in "
"{}.".format(
field.length,
self.fields.get_field_human_readable(identifier,
field_values),
type(self).__name__
)
)
# Mark these bits as assigned
assigned_bits |= field_bits
# Check that the calculated field is within the bit field
if start_at + length <= self.length:
field.length = length
field.start_at = start_at
else:
raise ValueError(
"{}-bit field {} does not fit in {}.".format(
field.length,
self.fields.get_field_human_readable(identifier,
field_values),
type(self).__name__
)
)
return assigned_bits | [
"def",
"_assign_field",
"(",
"self",
",",
"assigned_bits",
",",
"identifier",
",",
"field_values",
")",
":",
"field",
"=",
"self",
".",
"fields",
".",
"get_field",
"(",
"identifier",
",",
"field_values",
")",
"length",
"=",
"field",
".",
"length",
"if",
"l... | For internal use only. Assign a length and position to a field
which may have either one of these values missing.
Parameters
----------
assigned_bits : int
A bit mask of bits already in use by other fields
identifier : str
The identifier of the field to assign
field_values : {identifier: value, ...}
The values held by various fields (used to access the correct
identifier)
Returns
-------
int
Mask of which bits which are assigned to fields after this field
has been assigned. | [
"For",
"internal",
"use",
"only",
".",
"Assign",
"a",
"length",
"and",
"position",
"to",
"a",
"field",
"which",
"may",
"have",
"either",
"one",
"of",
"these",
"values",
"missing",
"."
] | 3a3e053d3214899b6d68758685835de0afd5542b | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/bitfield.py#L905-L976 | train | 50,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.