repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
vladsaveliev/TargQC | targqc/utilz/file_utils.py | splitext_plus | def splitext_plus(fname):
"""Split on file extensions, allowing for zipped extensions.
"""
base, ext = splitext(fname)
if ext in [".gz", ".bz2", ".zip"]:
base, ext2 = splitext(base)
ext = ext2 + ext
return base, ext | python | def splitext_plus(fname):
"""Split on file extensions, allowing for zipped extensions.
"""
base, ext = splitext(fname)
if ext in [".gz", ".bz2", ".zip"]:
base, ext2 = splitext(base)
ext = ext2 + ext
return base, ext | [
"def",
"splitext_plus",
"(",
"fname",
")",
":",
"base",
",",
"ext",
"=",
"splitext",
"(",
"fname",
")",
"if",
"ext",
"in",
"[",
"\".gz\"",
",",
"\".bz2\"",
",",
"\".zip\"",
"]",
":",
"base",
",",
"ext2",
"=",
"splitext",
"(",
"base",
")",
"ext",
"=... | Split on file extensions, allowing for zipped extensions. | [
"Split",
"on",
"file",
"extensions",
"allowing",
"for",
"zipped",
"extensions",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/file_utils.py#L745-L752 |
vladsaveliev/TargQC | targqc/utilz/file_utils.py | dots_to_empty_cells | def dots_to_empty_cells(config, tsv_fpath):
"""Put dots instead of empty cells in order to view TSV with column -t
"""
def proc_line(l, i):
while '\t\t' in l:
l = l.replace('\t\t', '\t.\t')
return l
return iterate_file(config, tsv_fpath, proc_line, suffix='dots') | python | def dots_to_empty_cells(config, tsv_fpath):
"""Put dots instead of empty cells in order to view TSV with column -t
"""
def proc_line(l, i):
while '\t\t' in l:
l = l.replace('\t\t', '\t.\t')
return l
return iterate_file(config, tsv_fpath, proc_line, suffix='dots') | [
"def",
"dots_to_empty_cells",
"(",
"config",
",",
"tsv_fpath",
")",
":",
"def",
"proc_line",
"(",
"l",
",",
"i",
")",
":",
"while",
"'\\t\\t'",
"in",
"l",
":",
"l",
"=",
"l",
".",
"replace",
"(",
"'\\t\\t'",
",",
"'\\t.\\t'",
")",
"return",
"l",
"ret... | Put dots instead of empty cells in order to view TSV with column -t | [
"Put",
"dots",
"instead",
"of",
"empty",
"cells",
"in",
"order",
"to",
"view",
"TSV",
"with",
"column",
"-",
"t"
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/file_utils.py#L843-L850 |
vladsaveliev/TargQC | targqc/utilz/file_utils.py | file_transaction | def file_transaction(work_dir, *rollback_files):
"""Wrap file generation in a transaction, moving to output if finishes.
"""
exts = {".vcf": ".idx", ".bam": ".bai", "vcf.gz": ".tbi"}
safe_fpaths, orig_names = _flatten_plus_safe(work_dir, rollback_files)
__remove_files(safe_fpaths) # remove any half... | python | def file_transaction(work_dir, *rollback_files):
"""Wrap file generation in a transaction, moving to output if finishes.
"""
exts = {".vcf": ".idx", ".bam": ".bai", "vcf.gz": ".tbi"}
safe_fpaths, orig_names = _flatten_plus_safe(work_dir, rollback_files)
__remove_files(safe_fpaths) # remove any half... | [
"def",
"file_transaction",
"(",
"work_dir",
",",
"*",
"rollback_files",
")",
":",
"exts",
"=",
"{",
"\".vcf\"",
":",
"\".idx\"",
",",
"\".bam\"",
":",
"\".bai\"",
",",
"\"vcf.gz\"",
":",
"\".tbi\"",
"}",
"safe_fpaths",
",",
"orig_names",
"=",
"_flatten_plus_sa... | Wrap file generation in a transaction, moving to output if finishes. | [
"Wrap",
"file",
"generation",
"in",
"a",
"transaction",
"moving",
"to",
"output",
"if",
"finishes",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/file_utils.py#L877-L899 |
vladsaveliev/TargQC | targqc/utilz/file_utils.py | tx_tmpdir | def tx_tmpdir(base_dir, rollback_dirpath):
"""Context manager to create and remove a transactional temporary directory.
"""
# tmp_dir_base = join(base_dir, 'tx', str(uuid.uuid4()))
# unique_attempts = 0
# while os.path.exists(tmp_dir_base):
# if unique_attempts > 5:
# break
#... | python | def tx_tmpdir(base_dir, rollback_dirpath):
"""Context manager to create and remove a transactional temporary directory.
"""
# tmp_dir_base = join(base_dir, 'tx', str(uuid.uuid4()))
# unique_attempts = 0
# while os.path.exists(tmp_dir_base):
# if unique_attempts > 5:
# break
#... | [
"def",
"tx_tmpdir",
"(",
"base_dir",
",",
"rollback_dirpath",
")",
":",
"# tmp_dir_base = join(base_dir, 'tx', str(uuid.uuid4()))",
"# unique_attempts = 0",
"# while os.path.exists(tmp_dir_base):",
"# if unique_attempts > 5:",
"# break",
"# tmp_dir_base = join(base_dir, 'tx... | Context manager to create and remove a transactional temporary directory. | [
"Context",
"manager",
"to",
"create",
"and",
"remove",
"a",
"transactional",
"temporary",
"directory",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/file_utils.py#L903-L928 |
vladsaveliev/TargQC | targqc/utilz/file_utils.py | _flatten_plus_safe | def _flatten_plus_safe(tmp_dir, rollback_files):
"""Flatten names of files and create temporary file names.
"""
tx_fpaths, orig_files = [], []
for fnames in rollback_files:
if isinstance(fnames, six.string_types):
fnames = [fnames]
for fname in fnames:
tx_file = f... | python | def _flatten_plus_safe(tmp_dir, rollback_files):
"""Flatten names of files and create temporary file names.
"""
tx_fpaths, orig_files = [], []
for fnames in rollback_files:
if isinstance(fnames, six.string_types):
fnames = [fnames]
for fname in fnames:
tx_file = f... | [
"def",
"_flatten_plus_safe",
"(",
"tmp_dir",
",",
"rollback_files",
")",
":",
"tx_fpaths",
",",
"orig_files",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"fnames",
"in",
"rollback_files",
":",
"if",
"isinstance",
"(",
"fnames",
",",
"six",
".",
"string_types",
")... | Flatten names of files and create temporary file names. | [
"Flatten",
"names",
"of",
"files",
"and",
"create",
"temporary",
"file",
"names",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/file_utils.py#L931-L943 |
vladsaveliev/TargQC | targqc/utilz/bed_utils.py | merge_overlaps | def merge_overlaps(work_dir, bed_fpath, distance=None):
"""Merge bed file intervals to avoid overlapping regions.
Overlapping regions (1:1-100, 1:90-100) cause issues with callers like FreeBayes
that don't collapse BEDs prior to using them.
"""
output_fpath = intermediate_fname(work_dir, bed_fpath, ... | python | def merge_overlaps(work_dir, bed_fpath, distance=None):
"""Merge bed file intervals to avoid overlapping regions.
Overlapping regions (1:1-100, 1:90-100) cause issues with callers like FreeBayes
that don't collapse BEDs prior to using them.
"""
output_fpath = intermediate_fname(work_dir, bed_fpath, ... | [
"def",
"merge_overlaps",
"(",
"work_dir",
",",
"bed_fpath",
",",
"distance",
"=",
"None",
")",
":",
"output_fpath",
"=",
"intermediate_fname",
"(",
"work_dir",
",",
"bed_fpath",
",",
"'merged'",
")",
"if",
"isfile",
"(",
"output_fpath",
")",
"and",
"verify_fil... | Merge bed file intervals to avoid overlapping regions.
Overlapping regions (1:1-100, 1:90-100) cause issues with callers like FreeBayes
that don't collapse BEDs prior to using them. | [
"Merge",
"bed",
"file",
"intervals",
"to",
"avoid",
"overlapping",
"regions",
".",
"Overlapping",
"regions",
"(",
"1",
":",
"1",
"-",
"100",
"1",
":",
"90",
"-",
"100",
")",
"cause",
"issues",
"with",
"callers",
"like",
"FreeBayes",
"that",
"don",
"t",
... | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/bed_utils.py#L94-L106 |
vladsaveliev/TargQC | targqc/utilz/bed_utils.py | BedFile.checkformat | def checkformat(self):
"""************************************************************************************************************************************************************
Task: checks the format of the bed file. The only requirements checked are that each line presents at least 3 tab separat... | python | def checkformat(self):
"""************************************************************************************************************************************************************
Task: checks the format of the bed file. The only requirements checked are that each line presents at least 3 tab separat... | [
"def",
"checkformat",
"(",
"self",
")",
":",
"fd",
"=",
"open_gzipsafe",
"(",
"self",
".",
"filename",
")",
"line",
"=",
"fd",
".",
"readline",
"(",
")",
"while",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"line",
"=",
"fd",
".",
"readline",
... | ************************************************************************************************************************************************************
Task: checks the format of the bed file. The only requirements checked are that each line presents at least 3 tab separated columns, the
two on... | [
"************************************************************************************************************************************************************",
"Task",
":",
"checks",
"the",
"format",
"of",
"the",
"bed",
"file",
".",
"The",
"only",
"requirements",
"checked",
"are",
"t... | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/bed_utils.py#L402-L445 |
svenkreiss/databench | databench/datastore.py | Datastore.trigger_all_callbacks | def trigger_all_callbacks(self, callbacks=None):
"""Trigger callbacks for all keys on all or a subset of subscribers.
:param Iterable callbacks: list of callbacks or none for all subscribed
:rtype: Iterable[tornado.concurrent.Future]
"""
return [ret
for key in se... | python | def trigger_all_callbacks(self, callbacks=None):
"""Trigger callbacks for all keys on all or a subset of subscribers.
:param Iterable callbacks: list of callbacks or none for all subscribed
:rtype: Iterable[tornado.concurrent.Future]
"""
return [ret
for key in se... | [
"def",
"trigger_all_callbacks",
"(",
"self",
",",
"callbacks",
"=",
"None",
")",
":",
"return",
"[",
"ret",
"for",
"key",
"in",
"self",
"for",
"ret",
"in",
"self",
".",
"trigger_callbacks",
"(",
"key",
",",
"callbacks",
"=",
"None",
")",
"]"
] | Trigger callbacks for all keys on all or a subset of subscribers.
:param Iterable callbacks: list of callbacks or none for all subscribed
:rtype: Iterable[tornado.concurrent.Future] | [
"Trigger",
"callbacks",
"for",
"all",
"keys",
"on",
"all",
"or",
"a",
"subset",
"of",
"subscribers",
"."
] | train | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/datastore.py#L63-L71 |
svenkreiss/databench | databench/datastore.py | Datastore.set | def set(self, key, value):
"""Set a value at key and return a Future.
:rtype: Iterable[tornado.concurrent.Future]
"""
value_encoded = encode(value)
if key in self.data and self.data[key] == value_encoded:
return []
self.data[key] = value_encoded
ret... | python | def set(self, key, value):
"""Set a value at key and return a Future.
:rtype: Iterable[tornado.concurrent.Future]
"""
value_encoded = encode(value)
if key in self.data and self.data[key] == value_encoded:
return []
self.data[key] = value_encoded
ret... | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"value_encoded",
"=",
"encode",
"(",
"value",
")",
"if",
"key",
"in",
"self",
".",
"data",
"and",
"self",
".",
"data",
"[",
"key",
"]",
"==",
"value_encoded",
":",
"return",
"[",
"]",
... | Set a value at key and return a Future.
:rtype: Iterable[tornado.concurrent.Future] | [
"Set",
"a",
"value",
"at",
"key",
"and",
"return",
"a",
"Future",
"."
] | train | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/datastore.py#L98-L109 |
svenkreiss/databench | databench/datastore.py | Datastore.set_state | def set_state(self, updater=None, **kwargs):
"""Update the datastore.
:param func|dict updater: (state) => state_change or dict state_change
:rtype: Iterable[tornado.concurrent.Future]
"""
if callable(updater):
state_change = updater(self)
elif updater is not... | python | def set_state(self, updater=None, **kwargs):
"""Update the datastore.
:param func|dict updater: (state) => state_change or dict state_change
:rtype: Iterable[tornado.concurrent.Future]
"""
if callable(updater):
state_change = updater(self)
elif updater is not... | [
"def",
"set_state",
"(",
"self",
",",
"updater",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"callable",
"(",
"updater",
")",
":",
"state_change",
"=",
"updater",
"(",
"self",
")",
"elif",
"updater",
"is",
"not",
"None",
":",
"state_change",
... | Update the datastore.
:param func|dict updater: (state) => state_change or dict state_change
:rtype: Iterable[tornado.concurrent.Future] | [
"Update",
"the",
"datastore",
"."
] | train | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/datastore.py#L111-L126 |
svenkreiss/databench | databench/datastore.py | Datastore.init | def init(self, key_value_pairs=None, **kwargs):
"""Initialize datastore.
Only sets values for keys that are not in the datastore already.
:param dict key_value_pairs:
A set of key value pairs to use to initialize the datastore.
:rtype: Iterable[tornado.concurrent.Future]
... | python | def init(self, key_value_pairs=None, **kwargs):
"""Initialize datastore.
Only sets values for keys that are not in the datastore already.
:param dict key_value_pairs:
A set of key value pairs to use to initialize the datastore.
:rtype: Iterable[tornado.concurrent.Future]
... | [
"def",
"init",
"(",
"self",
",",
"key_value_pairs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"key_value_pairs",
"is",
"None",
":",
"key_value_pairs",
"=",
"kwargs",
"return",
"[",
"self",
".",
"set",
"(",
"k",
",",
"v",
")",
"for",
"k",
... | Initialize datastore.
Only sets values for keys that are not in the datastore already.
:param dict key_value_pairs:
A set of key value pairs to use to initialize the datastore.
:rtype: Iterable[tornado.concurrent.Future] | [
"Initialize",
"datastore",
"."
] | train | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/datastore.py#L132-L146 |
svenkreiss/databench | databench/datastore.py | Datastore.close | def close(self):
"""Close and delete instance."""
# remove callbacks
Datastore.stores[self.domain].remove(self)
# delete data after the last instance is gone
if self.release_storage and not Datastore.stores[self.domain]:
del Datastore.global_data[self.domain]
... | python | def close(self):
"""Close and delete instance."""
# remove callbacks
Datastore.stores[self.domain].remove(self)
# delete data after the last instance is gone
if self.release_storage and not Datastore.stores[self.domain]:
del Datastore.global_data[self.domain]
... | [
"def",
"close",
"(",
"self",
")",
":",
"# remove callbacks",
"Datastore",
".",
"stores",
"[",
"self",
".",
"domain",
"]",
".",
"remove",
"(",
"self",
")",
"# delete data after the last instance is gone",
"if",
"self",
".",
"release_storage",
"and",
"not",
"Datas... | Close and delete instance. | [
"Close",
"and",
"delete",
"instance",
"."
] | train | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/datastore.py#L148-L158 |
vladsaveliev/TargQC | targqc/qualimap/runner.py | run_multisample_qualimap | def run_multisample_qualimap(output_dir, work_dir, samples, targqc_full_report):
""" 1. Generates Qualimap2 plots and put into plots_dirpath
2. Adds records to targqc_full_report.plots
"""
plots_dirpath = join(output_dir, 'plots')
individual_report_fpaths = [s.qualimap_html_fpath for s in sample... | python | def run_multisample_qualimap(output_dir, work_dir, samples, targqc_full_report):
""" 1. Generates Qualimap2 plots and put into plots_dirpath
2. Adds records to targqc_full_report.plots
"""
plots_dirpath = join(output_dir, 'plots')
individual_report_fpaths = [s.qualimap_html_fpath for s in sample... | [
"def",
"run_multisample_qualimap",
"(",
"output_dir",
",",
"work_dir",
",",
"samples",
",",
"targqc_full_report",
")",
":",
"plots_dirpath",
"=",
"join",
"(",
"output_dir",
",",
"'plots'",
")",
"individual_report_fpaths",
"=",
"[",
"s",
".",
"qualimap_html_fpath",
... | 1. Generates Qualimap2 plots and put into plots_dirpath
2. Adds records to targqc_full_report.plots | [
"1",
".",
"Generates",
"Qualimap2",
"plots",
"and",
"put",
"into",
"plots_dirpath",
"2",
".",
"Adds",
"records",
"to",
"targqc_full_report",
".",
"plots"
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/qualimap/runner.py#L97-L143 |
RI-imaging/ODTbrain | odtbrain/_postproc.py | odt_to_ri | def odt_to_ri(f, res, nm):
r"""Convert the ODT object function to refractive index
In :abbr:`ODT (Optical Diffraction Tomography)`, the object function
is defined by the Helmholtz equation
.. math::
f(\mathbf{r}) = k_\mathrm{m}^2 \left[
\left( \frac{n(\mathbf{r})}{n_\mathrm{m}} ... | python | def odt_to_ri(f, res, nm):
r"""Convert the ODT object function to refractive index
In :abbr:`ODT (Optical Diffraction Tomography)`, the object function
is defined by the Helmholtz equation
.. math::
f(\mathbf{r}) = k_\mathrm{m}^2 \left[
\left( \frac{n(\mathbf{r})}{n_\mathrm{m}} ... | [
"def",
"odt_to_ri",
"(",
"f",
",",
"res",
",",
"nm",
")",
":",
"km",
"=",
"(",
"2",
"*",
"np",
".",
"pi",
"*",
"nm",
")",
"/",
"res",
"ri",
"=",
"nm",
"*",
"np",
".",
"sqrt",
"(",
"f",
"/",
"km",
"**",
"2",
"+",
"1",
")",
"# Always take t... | r"""Convert the ODT object function to refractive index
In :abbr:`ODT (Optical Diffraction Tomography)`, the object function
is defined by the Helmholtz equation
.. math::
f(\mathbf{r}) = k_\mathrm{m}^2 \left[
\left( \frac{n(\mathbf{r})}{n_\mathrm{m}} \right)^2 - 1
\righ... | [
"r",
"Convert",
"the",
"ODT",
"object",
"function",
"to",
"refractive",
"index"
] | train | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_postproc.py#L5-L57 |
RI-imaging/ODTbrain | odtbrain/_postproc.py | opt_to_ri | def opt_to_ri(f, res, nm):
r"""Convert the OPT object function to refractive index
In :abbr:`OPT (Optical Projection Tomography)`, the object function
is computed from the raw phase data. This method converts phase data
to refractive index data.
.. math::
n(\mathbf{r}) = n_\mathrm{m} +
... | python | def opt_to_ri(f, res, nm):
r"""Convert the OPT object function to refractive index
In :abbr:`OPT (Optical Projection Tomography)`, the object function
is computed from the raw phase data. This method converts phase data
to refractive index data.
.. math::
n(\mathbf{r}) = n_\mathrm{m} +
... | [
"def",
"opt_to_ri",
"(",
"f",
",",
"res",
",",
"nm",
")",
":",
"ri",
"=",
"nm",
"+",
"f",
"/",
"(",
"2",
"*",
"np",
".",
"pi",
")",
"*",
"res",
"return",
"ri"
] | r"""Convert the OPT object function to refractive index
In :abbr:`OPT (Optical Projection Tomography)`, the object function
is computed from the raw phase data. This method converts phase data
to refractive index data.
.. math::
n(\mathbf{r}) = n_\mathrm{m} +
\frac{f(\mathbf{r}) ... | [
"r",
"Convert",
"the",
"OPT",
"object",
"function",
"to",
"refractive",
"index"
] | train | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_postproc.py#L60-L93 |
johntruckenbrodt/spatialist | spatialist/raster.py | rasterize | def rasterize(vectorobject, reference, outname=None, burn_values=1, expressions=None, nodata=0, append=False):
"""
rasterize a vector object
Parameters
----------
vectorobject: Vector
the vector object to be rasterized
reference: Raster
a reference Raster object to retrieve geo ... | python | def rasterize(vectorobject, reference, outname=None, burn_values=1, expressions=None, nodata=0, append=False):
"""
rasterize a vector object
Parameters
----------
vectorobject: Vector
the vector object to be rasterized
reference: Raster
a reference Raster object to retrieve geo ... | [
"def",
"rasterize",
"(",
"vectorobject",
",",
"reference",
",",
"outname",
"=",
"None",
",",
"burn_values",
"=",
"1",
",",
"expressions",
"=",
"None",
",",
"nodata",
"=",
"0",
",",
"append",
"=",
"False",
")",
":",
"if",
"expressions",
"is",
"None",
":... | rasterize a vector object
Parameters
----------
vectorobject: Vector
the vector object to be rasterized
reference: Raster
a reference Raster object to retrieve geo information and extent from
outname: str or None
the name of the GeoTiff output file; if None, an in-memory obj... | [
"rasterize",
"a",
"vector",
"object"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L902-L977 |
johntruckenbrodt/spatialist | spatialist/raster.py | reproject | def reproject(rasterobject, reference, outname, targetres=None, resampling='bilinear', format='GTiff'):
"""
reproject a raster file
Parameters
----------
rasterobject: Raster or str
the raster image to be reprojected
reference: Raster, Vector, str, int or osr.SpatialReference
ei... | python | def reproject(rasterobject, reference, outname, targetres=None, resampling='bilinear', format='GTiff'):
"""
reproject a raster file
Parameters
----------
rasterobject: Raster or str
the raster image to be reprojected
reference: Raster, Vector, str, int or osr.SpatialReference
ei... | [
"def",
"reproject",
"(",
"rasterobject",
",",
"reference",
",",
"outname",
",",
"targetres",
"=",
"None",
",",
"resampling",
"=",
"'bilinear'",
",",
"format",
"=",
"'GTiff'",
")",
":",
"if",
"isinstance",
"(",
"rasterobject",
",",
"str",
")",
":",
"rastero... | reproject a raster file
Parameters
----------
rasterobject: Raster or str
the raster image to be reprojected
reference: Raster, Vector, str, int or osr.SpatialReference
either a projection string or a spatial object with an attribute 'projection'
outname: str
the name of the... | [
"reproject",
"a",
"raster",
"file"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L980-L1033 |
johntruckenbrodt/spatialist | spatialist/raster.py | stack | def stack(srcfiles, dstfile, resampling, targetres, dstnodata, srcnodata=None, shapefile=None, layernames=None,
sortfun=None, separate=False, overwrite=False, compress=True, cores=4):
"""
function for mosaicking, resampling and stacking of multiple raster files into a 3D data cube
Parameters
... | python | def stack(srcfiles, dstfile, resampling, targetres, dstnodata, srcnodata=None, shapefile=None, layernames=None,
sortfun=None, separate=False, overwrite=False, compress=True, cores=4):
"""
function for mosaicking, resampling and stacking of multiple raster files into a 3D data cube
Parameters
... | [
"def",
"stack",
"(",
"srcfiles",
",",
"dstfile",
",",
"resampling",
",",
"targetres",
",",
"dstnodata",
",",
"srcnodata",
"=",
"None",
",",
"shapefile",
"=",
"None",
",",
"layernames",
"=",
"None",
",",
"sortfun",
"=",
"None",
",",
"separate",
"=",
"Fals... | function for mosaicking, resampling and stacking of multiple raster files into a 3D data cube
Parameters
----------
srcfiles: list
a list of file names or a list of lists; each sub-list is treated as a task to mosaic its containing files
dstfile: str
the destination file or a directory ... | [
"function",
"for",
"mosaicking",
"resampling",
"and",
"stacking",
"of",
"multiple",
"raster",
"files",
"into",
"a",
"3D",
"data",
"cube"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L1037-L1254 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.allstats | def allstats(self, approximate=False):
"""
Compute some basic raster statistics
Parameters
----------
approximate: bool
approximate statistics from overviews or a subset of all tiles?
Returns
-------
list of dicts
a list with a di... | python | def allstats(self, approximate=False):
"""
Compute some basic raster statistics
Parameters
----------
approximate: bool
approximate statistics from overviews or a subset of all tiles?
Returns
-------
list of dicts
a list with a di... | [
"def",
"allstats",
"(",
"self",
",",
"approximate",
"=",
"False",
")",
":",
"statcollect",
"=",
"[",
"]",
"for",
"x",
"in",
"self",
".",
"layers",
"(",
")",
":",
"try",
":",
"stats",
"=",
"x",
".",
"ComputeStatistics",
"(",
"approximate",
")",
"excep... | Compute some basic raster statistics
Parameters
----------
approximate: bool
approximate statistics from overviews or a subset of all tiles?
Returns
-------
list of dicts
a list with a dictionary of statistics for each band. Keys: `min`, `max`, `... | [
"Compute",
"some",
"basic",
"raster",
"statistics"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L256-L279 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.array | def array(self):
"""
read all raster bands into a numpy ndarray
Returns
-------
numpy.ndarray
the array containing all raster data
"""
if self.bands == 1:
return self.matrix()
else:
arr = self.raster.ReadAsArray().trans... | python | def array(self):
"""
read all raster bands into a numpy ndarray
Returns
-------
numpy.ndarray
the array containing all raster data
"""
if self.bands == 1:
return self.matrix()
else:
arr = self.raster.ReadAsArray().trans... | [
"def",
"array",
"(",
"self",
")",
":",
"if",
"self",
".",
"bands",
"==",
"1",
":",
"return",
"self",
".",
"matrix",
"(",
")",
"else",
":",
"arr",
"=",
"self",
".",
"raster",
".",
"ReadAsArray",
"(",
")",
".",
"transpose",
"(",
"1",
",",
"2",
",... | read all raster bands into a numpy ndarray
Returns
-------
numpy.ndarray
the array containing all raster data | [
"read",
"all",
"raster",
"bands",
"into",
"a",
"numpy",
"ndarray"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L281-L299 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.bandnames | def bandnames(self, names):
"""
set the names of the raster bands
Parameters
----------
names: list of str
the names to be set; must be of same length as the number of bands
Returns
-------
"""
if not isinstance(names, list):
... | python | def bandnames(self, names):
"""
set the names of the raster bands
Parameters
----------
names: list of str
the names to be set; must be of same length as the number of bands
Returns
-------
"""
if not isinstance(names, list):
... | [
"def",
"bandnames",
"(",
"self",
",",
"names",
")",
":",
"if",
"not",
"isinstance",
"(",
"names",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"'the names to be set must be of type list'",
")",
"if",
"len",
"(",
"names",
")",
"!=",
"self",
".",
"bands... | set the names of the raster bands
Parameters
----------
names: list of str
the names to be set; must be of same length as the number of bands
Returns
------- | [
"set",
"the",
"names",
"of",
"the",
"raster",
"bands"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L341-L359 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.bbox | def bbox(self, outname=None, format='ESRI Shapefile', overwrite=True):
"""
Parameters
----------
outname: str or None
the name of the file to write; If `None`, the bounding box is returned as vector object
format: str
The file format to write
overw... | python | def bbox(self, outname=None, format='ESRI Shapefile', overwrite=True):
"""
Parameters
----------
outname: str or None
the name of the file to write; If `None`, the bounding box is returned as vector object
format: str
The file format to write
overw... | [
"def",
"bbox",
"(",
"self",
",",
"outname",
"=",
"None",
",",
"format",
"=",
"'ESRI Shapefile'",
",",
"overwrite",
"=",
"True",
")",
":",
"if",
"outname",
"is",
"None",
":",
"return",
"bbox",
"(",
"self",
".",
"geo",
",",
"self",
".",
"proj4",
")",
... | Parameters
----------
outname: str or None
the name of the file to write; If `None`, the bounding box is returned as vector object
format: str
The file format to write
overwrite: bool
overwrite an already existing file?
Returns
-------... | [
"Parameters",
"----------",
"outname",
":",
"str",
"or",
"None",
"the",
"name",
"of",
"the",
"file",
"to",
"write",
";",
"If",
"None",
"the",
"bounding",
"box",
"is",
"returned",
"as",
"vector",
"object",
"format",
":",
"str",
"The",
"file",
"format",
"t... | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L361-L380 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.extract | def extract(self, px, py, radius=1, nodata=None):
"""
extract weighted average of pixels intersecting with a defined radius to a point.
Parameters
----------
px: int or float
the x coordinate in units of the Raster SRS
py: int or float
the y coord... | python | def extract(self, px, py, radius=1, nodata=None):
"""
extract weighted average of pixels intersecting with a defined radius to a point.
Parameters
----------
px: int or float
the x coordinate in units of the Raster SRS
py: int or float
the y coord... | [
"def",
"extract",
"(",
"self",
",",
"px",
",",
"py",
",",
"radius",
"=",
"1",
",",
"nodata",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"geo",
"[",
"'xmin'",
"]",
"<=",
"px",
"<=",
"self",
".",
"geo",
"[",
"'xmax'",
"]",
":",
"raise",
"... | extract weighted average of pixels intersecting with a defined radius to a point.
Parameters
----------
px: int or float
the x coordinate in units of the Raster SRS
py: int or float
the y coordinate in units of the Raster SRS
radius: int or float
... | [
"extract",
"weighted",
"average",
"of",
"pixels",
"intersecting",
"with",
"a",
"defined",
"radius",
"to",
"a",
"point",
"."
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L446-L535 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.geo | def geo(self):
"""
General image geo information.
Returns
-------
dict
a dictionary with keys `xmin`, `xmax`, `xres`, `rotation_x`, `ymin`, `ymax`, `yres`, `rotation_y`
"""
out = dict(zip(['xmin', 'xres', 'rotation_x', 'ymax', 'rotation_y', 'yres'],
... | python | def geo(self):
"""
General image geo information.
Returns
-------
dict
a dictionary with keys `xmin`, `xmax`, `xres`, `rotation_x`, `ymin`, `ymax`, `yres`, `rotation_y`
"""
out = dict(zip(['xmin', 'xres', 'rotation_x', 'ymax', 'rotation_y', 'yres'],
... | [
"def",
"geo",
"(",
"self",
")",
":",
"out",
"=",
"dict",
"(",
"zip",
"(",
"[",
"'xmin'",
",",
"'xres'",
",",
"'rotation_x'",
",",
"'ymax'",
",",
"'rotation_y'",
",",
"'yres'",
"]",
",",
"self",
".",
"raster",
".",
"GetGeoTransform",
"(",
")",
")",
... | General image geo information.
Returns
-------
dict
a dictionary with keys `xmin`, `xmax`, `xres`, `rotation_x`, `ymin`, `ymax`, `yres`, `rotation_y` | [
"General",
"image",
"geo",
"information",
"."
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L562-L577 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.is_valid | def is_valid(self):
"""
Check image integrity.
Tries to compute the checksum for each raster layer and returns False if this fails.
See this forum entry:
`How to check if image is valid? <https://lists.osgeo.org/pipermail/gdal-dev/2013-November/037520.html>`_.
Returns
... | python | def is_valid(self):
"""
Check image integrity.
Tries to compute the checksum for each raster layer and returns False if this fails.
See this forum entry:
`How to check if image is valid? <https://lists.osgeo.org/pipermail/gdal-dev/2013-November/037520.html>`_.
Returns
... | [
"def",
"is_valid",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"raster",
".",
"RasterCount",
")",
":",
"try",
":",
"checksum",
"=",
"self",
".",
"raster",
".",
"GetRasterBand",
"(",
"i",
"+",
"1",
")",
".",
"Checksum",
"(",
... | Check image integrity.
Tries to compute the checksum for each raster layer and returns False if this fails.
See this forum entry:
`How to check if image is valid? <https://lists.osgeo.org/pipermail/gdal-dev/2013-November/037520.html>`_.
Returns
-------
bool
i... | [
"Check",
"image",
"integrity",
".",
"Tries",
"to",
"compute",
"the",
"checksum",
"for",
"each",
"raster",
"layer",
"and",
"returns",
"False",
"if",
"this",
"fails",
".",
"See",
"this",
"forum",
"entry",
":",
"How",
"to",
"check",
"if",
"image",
"is",
"va... | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L590-L607 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.load | def load(self):
"""
load all raster data to internal memory arrays.
This shortens the read time of other methods like :meth:`matrix`.
"""
for i in range(1, self.bands + 1):
self.__data[i - 1] = self.matrix(i) | python | def load(self):
"""
load all raster data to internal memory arrays.
This shortens the read time of other methods like :meth:`matrix`.
"""
for i in range(1, self.bands + 1):
self.__data[i - 1] = self.matrix(i) | [
"def",
"load",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"self",
".",
"bands",
"+",
"1",
")",
":",
"self",
".",
"__data",
"[",
"i",
"-",
"1",
"]",
"=",
"self",
".",
"matrix",
"(",
"i",
")"
] | load all raster data to internal memory arrays.
This shortens the read time of other methods like :meth:`matrix`. | [
"load",
"all",
"raster",
"data",
"to",
"internal",
"memory",
"arrays",
".",
"This",
"shortens",
"the",
"read",
"time",
"of",
"other",
"methods",
"like",
":",
"meth",
":",
"matrix",
"."
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L619-L625 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.matrix | def matrix(self, band=1, mask_nan=True):
"""
read a raster band (subset) into a numpy ndarray
Parameters
----------
band: int
the band to read the matrix from; 1-based indexing
mask_nan: bool
convert nodata values to :obj:`numpy.nan`? As :obj:`num... | python | def matrix(self, band=1, mask_nan=True):
"""
read a raster band (subset) into a numpy ndarray
Parameters
----------
band: int
the band to read the matrix from; 1-based indexing
mask_nan: bool
convert nodata values to :obj:`numpy.nan`? As :obj:`num... | [
"def",
"matrix",
"(",
"self",
",",
"band",
"=",
"1",
",",
"mask_nan",
"=",
"True",
")",
":",
"mat",
"=",
"self",
".",
"__data",
"[",
"band",
"-",
"1",
"]",
"if",
"mat",
"is",
"None",
":",
"mat",
"=",
"self",
".",
"raster",
".",
"GetRasterBand",
... | read a raster band (subset) into a numpy ndarray
Parameters
----------
band: int
the band to read the matrix from; 1-based indexing
mask_nan: bool
convert nodata values to :obj:`numpy.nan`? As :obj:`numpy.nan` requires at least float values, any integer array is ... | [
"read",
"a",
"raster",
"band",
"(",
"subset",
")",
"into",
"a",
"numpy",
"ndarray"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L627-L658 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.res | def res(self):
"""
the raster resolution in x and y direction
Returns
-------
tuple
(xres, yres)
"""
return (abs(float(self.geo['xres'])), abs(float(self.geo['yres']))) | python | def res(self):
"""
the raster resolution in x and y direction
Returns
-------
tuple
(xres, yres)
"""
return (abs(float(self.geo['xres'])), abs(float(self.geo['yres']))) | [
"def",
"res",
"(",
"self",
")",
":",
"return",
"(",
"abs",
"(",
"float",
"(",
"self",
".",
"geo",
"[",
"'xres'",
"]",
")",
")",
",",
"abs",
"(",
"float",
"(",
"self",
".",
"geo",
"[",
"'yres'",
"]",
")",
")",
")"
] | the raster resolution in x and y direction
Returns
-------
tuple
(xres, yres) | [
"the",
"raster",
"resolution",
"in",
"x",
"and",
"y",
"direction"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L721-L730 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.rescale | def rescale(self, fun):
"""
perform raster computations with custom functions and assign them to the existing raster object in memory
Parameters
----------
fun: function
the custom function to compute on the data
Examples
--------
>>> with Ra... | python | def rescale(self, fun):
"""
perform raster computations with custom functions and assign them to the existing raster object in memory
Parameters
----------
fun: function
the custom function to compute on the data
Examples
--------
>>> with Ra... | [
"def",
"rescale",
"(",
"self",
",",
"fun",
")",
":",
"if",
"self",
".",
"bands",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'only single band images are currently supported'",
")",
"# load array",
"mat",
"=",
"self",
".",
"matrix",
"(",
")",
"# scale values"... | perform raster computations with custom functions and assign them to the existing raster object in memory
Parameters
----------
fun: function
the custom function to compute on the data
Examples
--------
>>> with Raster('filename') as ras:
>>> ras... | [
"perform",
"raster",
"computations",
"with",
"custom",
"functions",
"and",
"assign",
"them",
"to",
"the",
"existing",
"raster",
"object",
"in",
"memory"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L732-L757 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.write | def write(self, outname, dtype='default', format='ENVI', nodata='default', compress_tif=False, overwrite=False):
"""
write the raster object to a file.
Parameters
----------
outname: str
the file to be written
dtype: str
the data type of the writt... | python | def write(self, outname, dtype='default', format='ENVI', nodata='default', compress_tif=False, overwrite=False):
"""
write the raster object to a file.
Parameters
----------
outname: str
the file to be written
dtype: str
the data type of the writt... | [
"def",
"write",
"(",
"self",
",",
"outname",
",",
"dtype",
"=",
"'default'",
",",
"format",
"=",
"'ENVI'",
",",
"nodata",
"=",
"'default'",
",",
"compress_tif",
"=",
"False",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"os",
".",
"path",
".",
"is... | write the raster object to a file.
Parameters
----------
outname: str
the file to be written
dtype: str
the data type of the written file;
data type notations of GDAL (e.g. `Float32`) and numpy (e.g. `int8`) are supported.
format: str
... | [
"write",
"the",
"raster",
"object",
"to",
"a",
"file",
"."
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L781-L846 |
johntruckenbrodt/spatialist | spatialist/raster.py | Dtype.numpy2gdalint | def numpy2gdalint(self):
"""
create a dictionary for mapping numpy data types to GDAL data type codes
Returns
-------
dict
the type map
"""
if not hasattr(self, '__numpy2gdalint'):
tmap = {}
for group in ['int', 'u... | python | def numpy2gdalint(self):
"""
create a dictionary for mapping numpy data types to GDAL data type codes
Returns
-------
dict
the type map
"""
if not hasattr(self, '__numpy2gdalint'):
tmap = {}
for group in ['int', 'u... | [
"def",
"numpy2gdalint",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'__numpy2gdalint'",
")",
":",
"tmap",
"=",
"{",
"}",
"for",
"group",
"in",
"[",
"'int'",
",",
"'uint'",
",",
"'float'",
",",
"'complex'",
"]",
":",
"for",
"dtyp... | create a dictionary for mapping numpy data types to GDAL data type codes
Returns
-------
dict
the type map | [
"create",
"a",
"dictionary",
"for",
"mapping",
"numpy",
"data",
"types",
"to",
"GDAL",
"data",
"type",
"codes"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L1281-L1299 |
svenkreiss/databench | databench/app.py | App.static_parser | def static_parser(static):
"""Parse object describing static routes.
Might be a list, a dict or a list of dicts.
"""
if static is None:
return
if isinstance(static, dict):
static = static.items()
for group in static:
if not isinstanc... | python | def static_parser(static):
"""Parse object describing static routes.
Might be a list, a dict or a list of dicts.
"""
if static is None:
return
if isinstance(static, dict):
static = static.items()
for group in static:
if not isinstanc... | [
"def",
"static_parser",
"(",
"static",
")",
":",
"if",
"static",
"is",
"None",
":",
"return",
"if",
"isinstance",
"(",
"static",
",",
"dict",
")",
":",
"static",
"=",
"static",
".",
"items",
"(",
")",
"for",
"group",
"in",
"static",
":",
"if",
"not",... | Parse object describing static routes.
Might be a list, a dict or a list of dicts. | [
"Parse",
"object",
"describing",
"static",
"routes",
"."
] | train | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/app.py#L102-L119 |
svenkreiss/databench | databench/app.py | App.analyses_info | def analyses_info(self):
"""Add analyses from the analyses folder."""
f_config = os.path.join(self.analyses_path, 'index.yaml')
tornado.autoreload.watch(f_config)
with io.open(f_config, 'r', encoding='utf8') as f:
config = yaml.safe_load(f)
self.info.update(config... | python | def analyses_info(self):
"""Add analyses from the analyses folder."""
f_config = os.path.join(self.analyses_path, 'index.yaml')
tornado.autoreload.watch(f_config)
with io.open(f_config, 'r', encoding='utf8') as f:
config = yaml.safe_load(f)
self.info.update(config... | [
"def",
"analyses_info",
"(",
"self",
")",
":",
"f_config",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"analyses_path",
",",
"'index.yaml'",
")",
"tornado",
".",
"autoreload",
".",
"watch",
"(",
"f_config",
")",
"with",
"io",
".",
"open",
"(... | Add analyses from the analyses folder. | [
"Add",
"analyses",
"from",
"the",
"analyses",
"folder",
"."
] | train | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/app.py#L187-L201 |
svenkreiss/databench | databench/app.py | App.register_metas | def register_metas(self):
"""register metas"""
# concatenate some attributes to global lists:
aggregated = {'build': [], 'watch': []}
for attribute, values in aggregated.items():
for info in self.info['analyses'] + [self.info]:
if attribute in info:
... | python | def register_metas(self):
"""register metas"""
# concatenate some attributes to global lists:
aggregated = {'build': [], 'watch': []}
for attribute, values in aggregated.items():
for info in self.info['analyses'] + [self.info]:
if attribute in info:
... | [
"def",
"register_metas",
"(",
"self",
")",
":",
"# concatenate some attributes to global lists:",
"aggregated",
"=",
"{",
"'build'",
":",
"[",
"]",
",",
"'watch'",
":",
"[",
"]",
"}",
"for",
"attribute",
",",
"values",
"in",
"aggregated",
".",
"items",
"(",
... | register metas | [
"register",
"metas"
] | train | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/app.py#L302-L343 |
svenkreiss/databench | databench/app.py | App.build | def build(self):
"""Run the build command specified in index.yaml."""
for cmd in self.build_cmds:
log.info('building command: {}'.format(cmd))
full_cmd = 'cd {}; {}'.format(self.analyses_path, cmd)
log.debug('full command: {}'.format(full_cmd))
subprocess.... | python | def build(self):
"""Run the build command specified in index.yaml."""
for cmd in self.build_cmds:
log.info('building command: {}'.format(cmd))
full_cmd = 'cd {}; {}'.format(self.analyses_path, cmd)
log.debug('full command: {}'.format(full_cmd))
subprocess.... | [
"def",
"build",
"(",
"self",
")",
":",
"for",
"cmd",
"in",
"self",
".",
"build_cmds",
":",
"log",
".",
"info",
"(",
"'building command: {}'",
".",
"format",
"(",
"cmd",
")",
")",
"full_cmd",
"=",
"'cd {}; {}'",
".",
"format",
"(",
"self",
".",
"analyse... | Run the build command specified in index.yaml. | [
"Run",
"the",
"build",
"command",
"specified",
"in",
"index",
".",
"yaml",
"."
] | train | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/app.py#L345-L352 |
svenkreiss/databench | databench/app.py | IndexHandler.get | def get(self):
"""Render the List-of-Analyses overview page."""
return self.render(
'index.html',
databench_version=DATABENCH_VERSION,
meta_infos=self.meta_infos(),
**self.info
) | python | def get(self):
"""Render the List-of-Analyses overview page."""
return self.render(
'index.html',
databench_version=DATABENCH_VERSION,
meta_infos=self.meta_infos(),
**self.info
) | [
"def",
"get",
"(",
"self",
")",
":",
"return",
"self",
".",
"render",
"(",
"'index.html'",
",",
"databench_version",
"=",
"DATABENCH_VERSION",
",",
"meta_infos",
"=",
"self",
".",
"meta_infos",
"(",
")",
",",
"*",
"*",
"self",
".",
"info",
")"
] | Render the List-of-Analyses overview page. | [
"Render",
"the",
"List",
"-",
"of",
"-",
"Analyses",
"overview",
"page",
"."
] | train | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/app.py#L386-L393 |
MLAB-project/pymlab | examples/I2CSPI_HBSTEP.py | axis.Reset | def Reset(self):
' Reset Axis and set default parameters for H-bridge '
spi.SPI_write_byte(self.CS, 0xC0) # reset
# spi.SPI_write_byte(self.CS, 0x14) # Stall Treshold setup
# spi.SPI_write_byte(self.CS, 0xFF)
# spi.SPI_write_byte(self.CS, 0x13) # Over Current Tresho... | python | def Reset(self):
' Reset Axis and set default parameters for H-bridge '
spi.SPI_write_byte(self.CS, 0xC0) # reset
# spi.SPI_write_byte(self.CS, 0x14) # Stall Treshold setup
# spi.SPI_write_byte(self.CS, 0xFF)
# spi.SPI_write_byte(self.CS, 0x13) # Over Current Tresho... | [
"def",
"Reset",
"(",
"self",
")",
":",
"spi",
".",
"SPI_write_byte",
"(",
"self",
".",
"CS",
",",
"0xC0",
")",
"# reset",
"# spi.SPI_write_byte(self.CS, 0x14) # Stall Treshold setup",
"# spi.SPI_write_byte(self.CS, 0xFF) ",
"# spi.SPI_write_byte(self.... | Reset Axis and set default parameters for H-bridge | [
"Reset",
"Axis",
"and",
"set",
"default",
"parameters",
"for",
"H",
"-",
"bridge"
] | train | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/examples/I2CSPI_HBSTEP.py#L24-L50 |
RI-imaging/ODTbrain | odtbrain/_alg3d_bpp.py | _init_worker | def _init_worker(X, X_shape, X_dtype):
"""Initializer for pool for _mprotate"""
# Using a dictionary is not strictly necessary. You can also
# use global variables.
mprotate_dict["X"] = X
mprotate_dict["X_shape"] = X_shape
mprotate_dict["X_dtype"] = X_dtype | python | def _init_worker(X, X_shape, X_dtype):
"""Initializer for pool for _mprotate"""
# Using a dictionary is not strictly necessary. You can also
# use global variables.
mprotate_dict["X"] = X
mprotate_dict["X_shape"] = X_shape
mprotate_dict["X_dtype"] = X_dtype | [
"def",
"_init_worker",
"(",
"X",
",",
"X_shape",
",",
"X_dtype",
")",
":",
"# Using a dictionary is not strictly necessary. You can also",
"# use global variables.",
"mprotate_dict",
"[",
"\"X\"",
"]",
"=",
"X",
"mprotate_dict",
"[",
"\"X_shape\"",
"]",
"=",
"X_shape",
... | Initializer for pool for _mprotate | [
"Initializer",
"for",
"pool",
"for",
"_mprotate"
] | train | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_alg3d_bpp.py#L26-L32 |
RI-imaging/ODTbrain | odtbrain/_alg3d_bpp.py | _mprotate | def _mprotate(ang, lny, pool, order):
"""Uses multiprocessing to wrap around _rotate
4x speedup on an intel i7-3820 CPU @ 3.60GHz with 8 cores.
The function calls _rotate which accesses the `mprotate_dict`.
Data is rotated in-place.
Parameters
----------
ang: float
rotation angle ... | python | def _mprotate(ang, lny, pool, order):
"""Uses multiprocessing to wrap around _rotate
4x speedup on an intel i7-3820 CPU @ 3.60GHz with 8 cores.
The function calls _rotate which accesses the `mprotate_dict`.
Data is rotated in-place.
Parameters
----------
ang: float
rotation angle ... | [
"def",
"_mprotate",
"(",
"ang",
",",
"lny",
",",
"pool",
",",
"order",
")",
":",
"targ_args",
"=",
"list",
"(",
")",
"slsize",
"=",
"np",
".",
"int",
"(",
"np",
".",
"floor",
"(",
"lny",
"/",
"ncores",
")",
")",
"for",
"t",
"in",
"range",
"(",
... | Uses multiprocessing to wrap around _rotate
4x speedup on an intel i7-3820 CPU @ 3.60GHz with 8 cores.
The function calls _rotate which accesses the `mprotate_dict`.
Data is rotated in-place.
Parameters
----------
ang: float
rotation angle in degrees
lny: int
total number ... | [
"Uses",
"multiprocessing",
"to",
"wrap",
"around",
"_rotate"
] | train | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_alg3d_bpp.py#L35-L65 |
RI-imaging/ODTbrain | odtbrain/_alg3d_bpp.py | backpropagate_3d | def backpropagate_3d(uSin, angles, res, nm, lD=0, coords=None,
weight_angles=True, onlyreal=False,
padding=(True, True), padfac=1.75, padval=None,
intp_order=2, dtype=None,
num_cores=ncores,
save_memory=False,
... | python | def backpropagate_3d(uSin, angles, res, nm, lD=0, coords=None,
weight_angles=True, onlyreal=False,
padding=(True, True), padfac=1.75, padval=None,
intp_order=2, dtype=None,
num_cores=ncores,
save_memory=False,
... | [
"def",
"backpropagate_3d",
"(",
"uSin",
",",
"angles",
",",
"res",
",",
"nm",
",",
"lD",
"=",
"0",
",",
"coords",
"=",
"None",
",",
"weight_angles",
"=",
"True",
",",
"onlyreal",
"=",
"False",
",",
"padding",
"=",
"(",
"True",
",",
"True",
")",
","... | r"""3D backpropagation
Three-dimensional diffraction tomography reconstruction
algorithm for scattering of a plane wave
:math:`u_0(\mathbf{r}) = u_0(x,y,z)`
by a dielectric object with refractive index
:math:`n(x,y,z)`.
This method implements the 3D backpropagation algorithm
:cite:`Mueller... | [
"r",
"3D",
"backpropagation"
] | train | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_alg3d_bpp.py#L84-L547 |
RI-imaging/ODTbrain | odtbrain/util.py | compute_angle_weights_1d | def compute_angle_weights_1d(angles):
"""
Compute the weight for each angle according to the distance between its
neighbors.
Parameters
----------
angles: 1d ndarray of length A
Angles in radians
Returns
-------
weights: 1d ndarray of length A
The weights for each ang... | python | def compute_angle_weights_1d(angles):
"""
Compute the weight for each angle according to the distance between its
neighbors.
Parameters
----------
angles: 1d ndarray of length A
Angles in radians
Returns
-------
weights: 1d ndarray of length A
The weights for each ang... | [
"def",
"compute_angle_weights_1d",
"(",
"angles",
")",
":",
"# copy and modulo np.pi",
"# This is an array with values in [0, np.pi)",
"angles",
"=",
"(",
"angles",
".",
"flatten",
"(",
")",
"-",
"angles",
".",
"min",
"(",
")",
")",
"%",
"(",
"np",
".",
"pi",
... | Compute the weight for each angle according to the distance between its
neighbors.
Parameters
----------
angles: 1d ndarray of length A
Angles in radians
Returns
-------
weights: 1d ndarray of length A
The weights for each angle
Notes
-----
To compute the weights,... | [
"Compute",
"the",
"weight",
"for",
"each",
"angle",
"according",
"to",
"the",
"distance",
"between",
"its",
"neighbors",
".",
"Parameters",
"----------",
"angles",
":",
"1d",
"ndarray",
"of",
"length",
"A",
"Angles",
"in",
"radians",
"Returns",
"-------",
"wei... | train | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/util.py#L4-L35 |
MLAB-project/pymlab | src/pymlab/sensors/__init__.py | SimpleBus.initialize | def initialize(self):
"""See :meth:`pymlab.sensors.Device.initialize` for more information.
Calls `initialize()` on all devices connected to the bus.
"""
Device.initialize(self)
for child in iter(self.children.values()):
child.initialize() | python | def initialize(self):
"""See :meth:`pymlab.sensors.Device.initialize` for more information.
Calls `initialize()` on all devices connected to the bus.
"""
Device.initialize(self)
for child in iter(self.children.values()):
child.initialize() | [
"def",
"initialize",
"(",
"self",
")",
":",
"Device",
".",
"initialize",
"(",
"self",
")",
"for",
"child",
"in",
"iter",
"(",
"self",
".",
"children",
".",
"values",
"(",
")",
")",
":",
"child",
".",
"initialize",
"(",
")"
] | See :meth:`pymlab.sensors.Device.initialize` for more information.
Calls `initialize()` on all devices connected to the bus. | [
"See",
":",
"meth",
":",
"pymlab",
".",
"sensors",
".",
"Device",
".",
"initialize",
"for",
"more",
"information",
"."
] | train | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/__init__.py#L170-L177 |
MLAB-project/pymlab | src/pymlab/sensors/__init__.py | Bus.write_byte | def write_byte(self, address, value):
"""Writes the byte to unaddressed register in a device. """
LOGGER.debug("Writing byte %s to device %s!", bin(value), hex(address))
return self.driver.write_byte(address, value) | python | def write_byte(self, address, value):
"""Writes the byte to unaddressed register in a device. """
LOGGER.debug("Writing byte %s to device %s!", bin(value), hex(address))
return self.driver.write_byte(address, value) | [
"def",
"write_byte",
"(",
"self",
",",
"address",
",",
"value",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Writing byte %s to device %s!\"",
",",
"bin",
"(",
"value",
")",
",",
"hex",
"(",
"address",
")",
")",
"return",
"self",
".",
"driver",
".",
"write_... | Writes the byte to unaddressed register in a device. | [
"Writes",
"the",
"byte",
"to",
"unaddressed",
"register",
"in",
"a",
"device",
"."
] | train | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/__init__.py#L209-L212 |
MLAB-project/pymlab | src/pymlab/sensors/__init__.py | Bus.read_byte | def read_byte(self, address):
"""Reads unadressed byte from a device. """
LOGGER.debug("Reading byte from device %s!", hex(address))
return self.driver.read_byte(address) | python | def read_byte(self, address):
"""Reads unadressed byte from a device. """
LOGGER.debug("Reading byte from device %s!", hex(address))
return self.driver.read_byte(address) | [
"def",
"read_byte",
"(",
"self",
",",
"address",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Reading byte from device %s!\"",
",",
"hex",
"(",
"address",
")",
")",
"return",
"self",
".",
"driver",
".",
"read_byte",
"(",
"address",
")"
] | Reads unadressed byte from a device. | [
"Reads",
"unadressed",
"byte",
"from",
"a",
"device",
"."
] | train | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/__init__.py#L214-L217 |
MLAB-project/pymlab | src/pymlab/sensors/__init__.py | Bus.write_byte_data | def write_byte_data(self, address, register, value):
"""Write a byte value to a device's register. """
LOGGER.debug("Writing byte data %s to register %s on device %s",
bin(value), hex(register), hex(address))
return self.driver.write_byte_data(address, register, value) | python | def write_byte_data(self, address, register, value):
"""Write a byte value to a device's register. """
LOGGER.debug("Writing byte data %s to register %s on device %s",
bin(value), hex(register), hex(address))
return self.driver.write_byte_data(address, register, value) | [
"def",
"write_byte_data",
"(",
"self",
",",
"address",
",",
"register",
",",
"value",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Writing byte data %s to register %s on device %s\"",
",",
"bin",
"(",
"value",
")",
",",
"hex",
"(",
"register",
")",
",",
"hex",
... | Write a byte value to a device's register. | [
"Write",
"a",
"byte",
"value",
"to",
"a",
"device",
"s",
"register",
"."
] | train | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/__init__.py#L219-L223 |
MLAB-project/pymlab | src/pymlab/sensors/__init__.py | Bus.write_wdata | def write_wdata(self, address, register, value):
"""Write a word (two bytes) value to a device's register. """
warnings.warn("write_wdata() is deprecated and will be removed in future versions replace with write_word_data()", DeprecationWarning)
LOGGER.debug("Writing word data %s to register %s ... | python | def write_wdata(self, address, register, value):
"""Write a word (two bytes) value to a device's register. """
warnings.warn("write_wdata() is deprecated and will be removed in future versions replace with write_word_data()", DeprecationWarning)
LOGGER.debug("Writing word data %s to register %s ... | [
"def",
"write_wdata",
"(",
"self",
",",
"address",
",",
"register",
",",
"value",
")",
":",
"warnings",
".",
"warn",
"(",
"\"write_wdata() is deprecated and will be removed in future versions replace with write_word_data()\"",
",",
"DeprecationWarning",
")",
"LOGGER",
".",
... | Write a word (two bytes) value to a device's register. | [
"Write",
"a",
"word",
"(",
"two",
"bytes",
")",
"value",
"to",
"a",
"device",
"s",
"register",
"."
] | train | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/__init__.py#L298-L303 |
python-astrodynamics/spacetrack | spacetrack/aio.py | _raise_for_status | async def _raise_for_status(response):
"""Raise an appropriate error for a given response.
Arguments:
response (:py:class:`aiohttp.ClientResponse`): The API response.
Raises:
:py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate
error for the response's status.
This fu... | python | async def _raise_for_status(response):
"""Raise an appropriate error for a given response.
Arguments:
response (:py:class:`aiohttp.ClientResponse`): The API response.
Raises:
:py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate
error for the response's status.
This fu... | [
"async",
"def",
"_raise_for_status",
"(",
"response",
")",
":",
"try",
":",
"response",
".",
"raise_for_status",
"(",
")",
"except",
"aiohttp",
".",
"ClientResponseError",
"as",
"exc",
":",
"reason",
"=",
"response",
".",
"reason",
"spacetrack_error_msg",
"=",
... | Raise an appropriate error for a given response.
Arguments:
response (:py:class:`aiohttp.ClientResponse`): The API response.
Raises:
:py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate
error for the response's status.
This function was taken from the aslack project and m... | [
"Raise",
"an",
"appropriate",
"error",
"for",
"a",
"given",
"response",
"."
] | train | https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/aio.py#L349-L409 |
python-astrodynamics/spacetrack | spacetrack/aio.py | AsyncSpaceTrackClient.generic_request | async def generic_request(self, class_, iter_lines=False, iter_content=False,
controller=None, parse_types=False, **kwargs):
"""Generic Space-Track query coroutine.
The request class methods use this method internally; the public
API is as follows:
.. code... | python | async def generic_request(self, class_, iter_lines=False, iter_content=False,
controller=None, parse_types=False, **kwargs):
"""Generic Space-Track query coroutine.
The request class methods use this method internally; the public
API is as follows:
.. code... | [
"async",
"def",
"generic_request",
"(",
"self",
",",
"class_",
",",
"iter_lines",
"=",
"False",
",",
"iter_content",
"=",
"False",
",",
"controller",
"=",
"None",
",",
"parse_types",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"iter_lines",
"a... | Generic Space-Track query coroutine.
The request class methods use this method internally; the public
API is as follows:
.. code-block:: python
st.tle_publish(*args, **st)
st.basicspacedata.tle_publish(*args, **st)
st.file(*args, **st)
st.filesh... | [
"Generic",
"Space",
"-",
"Track",
"query",
"coroutine",
"."
] | train | https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/aio.py#L70-L213 |
python-astrodynamics/spacetrack | spacetrack/aio.py | AsyncSpaceTrackClient._download_predicate_data | async def _download_predicate_data(self, class_, controller):
"""Get raw predicate information for given request class, and cache for
subsequent calls.
"""
await self.authenticate()
url = ('{0}{1}/modeldef/class/{2}'
.format(self.base_url, controller, class_))
... | python | async def _download_predicate_data(self, class_, controller):
"""Get raw predicate information for given request class, and cache for
subsequent calls.
"""
await self.authenticate()
url = ('{0}{1}/modeldef/class/{2}'
.format(self.base_url, controller, class_))
... | [
"async",
"def",
"_download_predicate_data",
"(",
"self",
",",
"class_",
",",
"controller",
")",
":",
"await",
"self",
".",
"authenticate",
"(",
")",
"url",
"=",
"(",
"'{0}{1}/modeldef/class/{2}'",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"controller",... | Get raw predicate information for given request class, and cache for
subsequent calls. | [
"Get",
"raw",
"predicate",
"information",
"for",
"given",
"request",
"class",
"and",
"cache",
"for",
"subsequent",
"calls",
"."
] | train | https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/aio.py#L242-L256 |
vladsaveliev/TargQC | targqc/utilz/utils.py | get_numeric_value | def get_numeric_value(string_value):
""" parses string_value and returns only number-like part
"""
num_chars = ['.', '+', '-']
number = ''
for c in string_value:
if c.isdigit() or c in num_chars:
number += c
return number | python | def get_numeric_value(string_value):
""" parses string_value and returns only number-like part
"""
num_chars = ['.', '+', '-']
number = ''
for c in string_value:
if c.isdigit() or c in num_chars:
number += c
return number | [
"def",
"get_numeric_value",
"(",
"string_value",
")",
":",
"num_chars",
"=",
"[",
"'.'",
",",
"'+'",
",",
"'-'",
"]",
"number",
"=",
"''",
"for",
"c",
"in",
"string_value",
":",
"if",
"c",
".",
"isdigit",
"(",
")",
"or",
"c",
"in",
"num_chars",
":",
... | parses string_value and returns only number-like part | [
"parses",
"string_value",
"and",
"returns",
"only",
"number",
"-",
"like",
"part"
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/utils.py#L83-L91 |
svenkreiss/databench | databench/cli.py | main | def main(**kwargs):
"""Entry point to run databench."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--version', action='version',
version='%(prog)s {}'.format(DATABENCH_VERSION))
parser.add_argument('--log', dest='loglevel', default="INFO",
... | python | def main(**kwargs):
"""Entry point to run databench."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--version', action='version',
version='%(prog)s {}'.format(DATABENCH_VERSION))
parser.add_argument('--log', dest='loglevel', default="INFO",
... | [
"def",
"main",
"(",
"*",
"*",
"kwargs",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"action",
"=",
"'version'",
",",
"version",
"=",
"'%(prog)s... | Entry point to run databench. | [
"Entry",
"point",
"to",
"run",
"databench",
"."
] | train | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/cli.py#L16-L123 |
svenkreiss/databench | databench/cli.py | run | def run(analysis, path=None, name=None, info=None, **kwargs):
"""Run a single analysis.
:param Analysis analysis: Analysis class to run.
:param str path: Path of analysis. Can be `__file__`.
:param str name: Name of the analysis.
:param dict info: Optional entries are ``version``, ``title``,
... | python | def run(analysis, path=None, name=None, info=None, **kwargs):
"""Run a single analysis.
:param Analysis analysis: Analysis class to run.
:param str path: Path of analysis. Can be `__file__`.
:param str name: Name of the analysis.
:param dict info: Optional entries are ``version``, ``title``,
... | [
"def",
"run",
"(",
"analysis",
",",
"path",
"=",
"None",
",",
"name",
"=",
"None",
",",
"info",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'analysis'",
":",
"analysis",
",",
"'path'",
":",
"path",
",",
"'n... | Run a single analysis.
:param Analysis analysis: Analysis class to run.
:param str path: Path of analysis. Can be `__file__`.
:param str name: Name of the analysis.
:param dict info: Optional entries are ``version``, ``title``,
``readme``, ...
:param dict static: Map[url regex, root-folder]... | [
"Run",
"a",
"single",
"analysis",
"."
] | train | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/cli.py#L126-L142 |
python-astrodynamics/spacetrack | spacetrack/operators.py | _stringify_predicate_value | def _stringify_predicate_value(value):
"""Convert Python objects to Space-Track compatible strings
- Booleans (``True`` -> ``'true'``)
- Sequences (``[25544, 34602]`` -> ``'25544,34602'``)
- dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)
- ``None`` -> ``'null-val'``
"""
if isi... | python | def _stringify_predicate_value(value):
"""Convert Python objects to Space-Track compatible strings
- Booleans (``True`` -> ``'true'``)
- Sequences (``[25544, 34602]`` -> ``'25544,34602'``)
- dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)
- ``None`` -> ``'null-val'``
"""
if isi... | [
"def",
"_stringify_predicate_value",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"str",
"(",
"value",
")",
".",
"lower",
"(",
")",
"elif",
"isinstance",
"(",
"value",
",",
"Sequence",
")",
"and",
"not",
"i... | Convert Python objects to Space-Track compatible strings
- Booleans (``True`` -> ``'true'``)
- Sequences (``[25544, 34602]`` -> ``'25544,34602'``)
- dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)
- ``None`` -> ``'null-val'`` | [
"Convert",
"Python",
"objects",
"to",
"Space",
"-",
"Track",
"compatible",
"strings"
] | train | https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/operators.py#L45-L64 |
MLAB-project/pymlab | src/pymlab/utils.py | args_repr | def args_repr(*args, **kwargs):
"""
Returns human-readable string representation of both positional and
keyword arguments passed to the function.
This function uses the built-in :func:`repr()` function to convert
individual arguments to string.
>>> args_repr("a", (1, 2), some_keyword = list("a... | python | def args_repr(*args, **kwargs):
"""
Returns human-readable string representation of both positional and
keyword arguments passed to the function.
This function uses the built-in :func:`repr()` function to convert
individual arguments to string.
>>> args_repr("a", (1, 2), some_keyword = list("a... | [
"def",
"args_repr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"items",
"=",
"[",
"repr",
"(",
"a",
")",
"for",
"a",
"in",
"args",
"]",
"items",
"+=",
"[",
"\"%s = %r\"",
"%",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"... | Returns human-readable string representation of both positional and
keyword arguments passed to the function.
This function uses the built-in :func:`repr()` function to convert
individual arguments to string.
>>> args_repr("a", (1, 2), some_keyword = list("abc"))
"'a', (1, 2), some_keyword = ['a',... | [
"Returns",
"human",
"-",
"readable",
"string",
"representation",
"of",
"both",
"positional",
"and",
"keyword",
"arguments",
"passed",
"to",
"the",
"function",
"."
] | train | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/utils.py#L12-L25 |
MLAB-project/pymlab | src/pymlab/utils.py | obj_repr | def obj_repr(obj, *args, **kwargs):
"""
Returns human-readable string representation of an object given that it has
been created by calling constructor with the specified positional and
keyword arguments.
This is a convenience function to help implement custom `__repr__()`
methods. For example:... | python | def obj_repr(obj, *args, **kwargs):
"""
Returns human-readable string representation of an object given that it has
been created by calling constructor with the specified positional and
keyword arguments.
This is a convenience function to help implement custom `__repr__()`
methods. For example:... | [
"def",
"obj_repr",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cls_name",
"=",
"type",
"(",
"obj",
")",
".",
"__name__",
"return",
"\"%s(%s)\"",
"%",
"(",
"cls_name",
",",
"args_repr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs"... | Returns human-readable string representation of an object given that it has
been created by calling constructor with the specified positional and
keyword arguments.
This is a convenience function to help implement custom `__repr__()`
methods. For example:
>>> class Animal(object):
... def _... | [
"Returns",
"human",
"-",
"readable",
"string",
"representation",
"of",
"an",
"object",
"given",
"that",
"it",
"has",
"been",
"created",
"by",
"calling",
"constructor",
"with",
"the",
"specified",
"positional",
"and",
"keyword",
"arguments",
"."
] | train | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/utils.py#L28-L49 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | decode_filter | def decode_filter(text, encoding='utf-8'):
"""
decode a binary object to str and filter out non-printable characters
Parameters
----------
text: bytes
the binary object to be decoded
encoding: str
the encoding to be used
Returns
-------
str
the decoded a... | python | def decode_filter(text, encoding='utf-8'):
"""
decode a binary object to str and filter out non-printable characters
Parameters
----------
text: bytes
the binary object to be decoded
encoding: str
the encoding to be used
Returns
-------
str
the decoded a... | [
"def",
"decode_filter",
"(",
"text",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"text",
"is",
"not",
"None",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"encoding",
",",
"errors",
"=",
"'ignore'",
")",
"printable",
"=",
"set",
"(",
"string",
... | decode a binary object to str and filter out non-printable characters
Parameters
----------
text: bytes
the binary object to be decoded
encoding: str
the encoding to be used
Returns
-------
str
the decoded and filtered string | [
"decode",
"a",
"binary",
"object",
"to",
"str",
"and",
"filter",
"out",
"non",
"-",
"printable",
"characters",
"Parameters",
"----------",
"text",
":",
"bytes",
"the",
"binary",
"object",
"to",
"be",
"decoded",
"encoding",
":",
"str",
"the",
"encoding",
"to"... | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L60-L82 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | dictmerge | def dictmerge(x, y):
"""
merge two dictionaries
"""
z = x.copy()
z.update(y)
return z | python | def dictmerge(x, y):
"""
merge two dictionaries
"""
z = x.copy()
z.update(y)
return z | [
"def",
"dictmerge",
"(",
"x",
",",
"y",
")",
":",
"z",
"=",
"x",
".",
"copy",
"(",
")",
"z",
".",
"update",
"(",
"y",
")",
"return",
"z"
] | merge two dictionaries | [
"merge",
"two",
"dictionaries"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L85-L91 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | dissolve | def dissolve(inlist):
"""
list and tuple flattening
Parameters
----------
inlist: list
the list with sub-lists or tuples to be flattened
Returns
-------
list
the flattened result
Examples
--------
>>> dissolve([[1, 2], [3, 4]])
[1, 2, 3, 4]
... | python | def dissolve(inlist):
"""
list and tuple flattening
Parameters
----------
inlist: list
the list with sub-lists or tuples to be flattened
Returns
-------
list
the flattened result
Examples
--------
>>> dissolve([[1, 2], [3, 4]])
[1, 2, 3, 4]
... | [
"def",
"dissolve",
"(",
"inlist",
")",
":",
"out",
"=",
"[",
"]",
"for",
"i",
"in",
"inlist",
":",
"i",
"=",
"list",
"(",
"i",
")",
"if",
"isinstance",
"(",
"i",
",",
"tuple",
")",
"else",
"i",
"out",
".",
"extend",
"(",
"dissolve",
"(",
"i",
... | list and tuple flattening
Parameters
----------
inlist: list
the list with sub-lists or tuples to be flattened
Returns
-------
list
the flattened result
Examples
--------
>>> dissolve([[1, 2], [3, 4]])
[1, 2, 3, 4]
>>> dissolve([(1, 2, (3, ... | [
"list",
"and",
"tuple",
"flattening",
"Parameters",
"----------",
"inlist",
":",
"list",
"the",
"list",
"with",
"sub",
"-",
"lists",
"or",
"tuples",
"to",
"be",
"flattened",
"Returns",
"-------",
"list",
"the",
"flattened",
"result",
"Examples",
"--------",
">... | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L95-L121 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | finder | def finder(target, matchlist, foldermode=0, regex=False, recursive=True):
"""
function for finding files/folders in folders and their subdirectories
Parameters
----------
target: str or list of str
a directory, zip- or tar-archive or a list of them to be searched
matchlist: list
... | python | def finder(target, matchlist, foldermode=0, regex=False, recursive=True):
"""
function for finding files/folders in folders and their subdirectories
Parameters
----------
target: str or list of str
a directory, zip- or tar-archive or a list of them to be searched
matchlist: list
... | [
"def",
"finder",
"(",
"target",
",",
"matchlist",
",",
"foldermode",
"=",
"0",
",",
"regex",
"=",
"False",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"foldermode",
"not",
"in",
"[",
"0",
",",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",... | function for finding files/folders in folders and their subdirectories
Parameters
----------
target: str or list of str
a directory, zip- or tar-archive or a list of them to be searched
matchlist: list
a list of search patterns
foldermode: int
* 0: only files
* 1: fi... | [
"function",
"for",
"finding",
"files",
"/",
"folders",
"in",
"folders",
"and",
"their",
"subdirectories"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L124-L221 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | multicore | def multicore(function, cores, multiargs, **singleargs):
"""
wrapper for multicore process execution
Parameters
----------
function
individual function to be applied to each process item
cores: int
the number of subprocesses started/CPUs used;
this value is reduced in ca... | python | def multicore(function, cores, multiargs, **singleargs):
"""
wrapper for multicore process execution
Parameters
----------
function
individual function to be applied to each process item
cores: int
the number of subprocesses started/CPUs used;
this value is reduced in ca... | [
"def",
"multicore",
"(",
"function",
",",
"cores",
",",
"multiargs",
",",
"*",
"*",
"singleargs",
")",
":",
"tblib",
".",
"pickling_support",
".",
"install",
"(",
")",
"# compare the function arguments with the multi and single arguments and raise errors if mismatches occur... | wrapper for multicore process execution
Parameters
----------
function
individual function to be applied to each process item
cores: int
the number of subprocesses started/CPUs used;
this value is reduced in case the number of subprocesses is smaller
multiargs: dict
... | [
"wrapper",
"for",
"multicore",
"process",
"execution"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L224-L367 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | parse_literal | def parse_literal(x):
"""
return the smallest possible data type for a string or list of strings
Parameters
----------
x: str or list
a string to be parsed
Returns
-------
int, float or str
the parsing result
Examples
--------
>>> isinstance(parse_liter... | python | def parse_literal(x):
"""
return the smallest possible data type for a string or list of strings
Parameters
----------
x: str or list
a string to be parsed
Returns
-------
int, float or str
the parsing result
Examples
--------
>>> isinstance(parse_liter... | [
"def",
"parse_literal",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"return",
"[",
"parse_literal",
"(",
"y",
")",
"for",
"y",
"in",
"x",
"]",
"elif",
"isinstance",
"(",
"x",
",",
"(",
"bytes",
",",
"str",
")",
")",
... | return the smallest possible data type for a string or list of strings
Parameters
----------
x: str or list
a string to be parsed
Returns
-------
int, float or str
the parsing result
Examples
--------
>>> isinstance(parse_literal('1.5'), float)
True
... | [
"return",
"the",
"smallest",
"possible",
"data",
"type",
"for",
"a",
"string",
"or",
"list",
"of",
"strings"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L399-L435 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | rescale | def rescale(inlist, newrange=(0, 1)):
"""
rescale the values in a list between the values in newrange (a tuple with the new minimum and maximum)
"""
OldMax = max(inlist)
OldMin = min(inlist)
if OldMin == OldMax:
raise RuntimeError('list contains of only one unique value')
O... | python | def rescale(inlist, newrange=(0, 1)):
"""
rescale the values in a list between the values in newrange (a tuple with the new minimum and maximum)
"""
OldMax = max(inlist)
OldMin = min(inlist)
if OldMin == OldMax:
raise RuntimeError('list contains of only one unique value')
O... | [
"def",
"rescale",
"(",
"inlist",
",",
"newrange",
"=",
"(",
"0",
",",
"1",
")",
")",
":",
"OldMax",
"=",
"max",
"(",
"inlist",
")",
"OldMin",
"=",
"min",
"(",
"inlist",
")",
"if",
"OldMin",
"==",
"OldMax",
":",
"raise",
"RuntimeError",
"(",
"'list ... | rescale the values in a list between the values in newrange (a tuple with the new minimum and maximum) | [
"rescale",
"the",
"values",
"in",
"a",
"list",
"between",
"the",
"values",
"in",
"newrange",
"(",
"a",
"tuple",
"with",
"the",
"new",
"minimum",
"and",
"maximum",
")"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L462-L475 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | run | def run(cmd, outdir=None, logfile=None, inlist=None, void=True, errorpass=False, env=None):
"""
| wrapper for subprocess execution including logfile writing and command prompt piping
| this is a convenience wrapper around the :mod:`subprocess` module and calls
its class :class:`~subprocess.Popen` inte... | python | def run(cmd, outdir=None, logfile=None, inlist=None, void=True, errorpass=False, env=None):
"""
| wrapper for subprocess execution including logfile writing and command prompt piping
| this is a convenience wrapper around the :mod:`subprocess` module and calls
its class :class:`~subprocess.Popen` inte... | [
"def",
"run",
"(",
"cmd",
",",
"outdir",
"=",
"None",
",",
"logfile",
"=",
"None",
",",
"inlist",
"=",
"None",
",",
"void",
"=",
"True",
",",
"errorpass",
"=",
"False",
",",
"env",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"str",
"(",
"x",
")",
... | | wrapper for subprocess execution including logfile writing and command prompt piping
| this is a convenience wrapper around the :mod:`subprocess` module and calls
its class :class:`~subprocess.Popen` internally.
Parameters
----------
cmd: list
the command arguments
outdir: str
... | [
"|",
"wrapper",
"for",
"subprocess",
"execution",
"including",
"logfile",
"writing",
"and",
"command",
"prompt",
"piping",
"|",
"this",
"is",
"a",
"convenience",
"wrapper",
"around",
"the",
":",
"mod",
":",
"subprocess",
"module",
"and",
"calls",
"its",
"class... | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L478-L523 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | urlQueryParser | def urlQueryParser(url, querydict):
"""
parse a url query
"""
address_parse = urlparse(url)
return urlunparse(address_parse._replace(query=urlencode(querydict))) | python | def urlQueryParser(url, querydict):
"""
parse a url query
"""
address_parse = urlparse(url)
return urlunparse(address_parse._replace(query=urlencode(querydict))) | [
"def",
"urlQueryParser",
"(",
"url",
",",
"querydict",
")",
":",
"address_parse",
"=",
"urlparse",
"(",
"url",
")",
"return",
"urlunparse",
"(",
"address_parse",
".",
"_replace",
"(",
"query",
"=",
"urlencode",
"(",
"querydict",
")",
")",
")"
] | parse a url query | [
"parse",
"a",
"url",
"query"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L585-L590 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | Stack.push | def push(self, x):
"""
append items to the stack; input can be a single value or a list
"""
if isinstance(x, list):
for item in x:
self.stack.append(item)
else:
self.stack.append(x) | python | def push(self, x):
"""
append items to the stack; input can be a single value or a list
"""
if isinstance(x, list):
for item in x:
self.stack.append(item)
else:
self.stack.append(x) | [
"def",
"push",
"(",
"self",
",",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"for",
"item",
"in",
"x",
":",
"self",
".",
"stack",
".",
"append",
"(",
"item",
")",
"else",
":",
"self",
".",
"stack",
".",
"append",
"(",
... | append items to the stack; input can be a single value or a list | [
"append",
"items",
"to",
"the",
"stack",
";",
"input",
"can",
"be",
"a",
"single",
"value",
"or",
"a",
"list"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L558-L566 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | Stack.pop | def pop(self):
"""
return the last stack element and delete it from the list
"""
if not self.empty():
val = self.stack[-1]
del self.stack[-1]
return val | python | def pop(self):
"""
return the last stack element and delete it from the list
"""
if not self.empty():
val = self.stack[-1]
del self.stack[-1]
return val | [
"def",
"pop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"empty",
"(",
")",
":",
"val",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"del",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"return",
"val"
] | return the last stack element and delete it from the list | [
"return",
"the",
"last",
"stack",
"element",
"and",
"delete",
"it",
"from",
"the",
"list"
] | train | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L568-L575 |
MLAB-project/pymlab | src/pymlab/sensors/mag.py | MAG01.axes | def axes(self, offset = False):
"""returns measured value in miligauss"""
reg, self._scale = self.SCALES[self._gauss]
x = self.bus.read_int16_data(self.address, self.HMC5883L_DXRA)
if x == -4096: x = OVERFLOW
y = self.bus.read_int16_data(self.address, self.HMC5883L_DYRA)
... | python | def axes(self, offset = False):
"""returns measured value in miligauss"""
reg, self._scale = self.SCALES[self._gauss]
x = self.bus.read_int16_data(self.address, self.HMC5883L_DXRA)
if x == -4096: x = OVERFLOW
y = self.bus.read_int16_data(self.address, self.HMC5883L_DYRA)
... | [
"def",
"axes",
"(",
"self",
",",
"offset",
"=",
"False",
")",
":",
"reg",
",",
"self",
".",
"_scale",
"=",
"self",
".",
"SCALES",
"[",
"self",
".",
"_gauss",
"]",
"x",
"=",
"self",
".",
"bus",
".",
"read_int16_data",
"(",
"self",
".",
"address",
... | returns measured value in miligauss | [
"returns",
"measured",
"value",
"in",
"miligauss"
] | train | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/mag.py#L77-L93 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ToString | def _ToString(x):
"""The default default formatter!."""
# Some cross-language values for primitives. This is tested in
# jsontemplate_test.py.
if x is None:
return 'null'
if isinstance(x, six.string_types):
return x
return pprint.pformat(x) | python | def _ToString(x):
"""The default default formatter!."""
# Some cross-language values for primitives. This is tested in
# jsontemplate_test.py.
if x is None:
return 'null'
if isinstance(x, six.string_types):
return x
return pprint.pformat(x) | [
"def",
"_ToString",
"(",
"x",
")",
":",
"# Some cross-language values for primitives. This is tested in",
"# jsontemplate_test.py.",
"if",
"x",
"is",
"None",
":",
"return",
"'null'",
"if",
"isinstance",
"(",
"x",
",",
"six",
".",
"string_types",
")",
":",
"return",... | The default default formatter!. | [
"The",
"default",
"default",
"formatter!",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L705-L713 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _Pairs | def _Pairs(data):
"""dictionary -> list of pairs"""
keys = sorted(data)
return [{'@key': k, '@value': data[k]} for k in keys] | python | def _Pairs(data):
"""dictionary -> list of pairs"""
keys = sorted(data)
return [{'@key': k, '@value': data[k]} for k in keys] | [
"def",
"_Pairs",
"(",
"data",
")",
":",
"keys",
"=",
"sorted",
"(",
"data",
")",
"return",
"[",
"{",
"'@key'",
":",
"k",
",",
"'@value'",
":",
"data",
"[",
"k",
"]",
"}",
"for",
"k",
"in",
"keys",
"]"
] | dictionary -> list of pairs | [
"dictionary",
"-",
">",
"list",
"of",
"pairs"
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L741-L744 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _Pluralize | def _Pluralize(value, unused_context, args):
"""Formatter to pluralize words."""
if len(args) == 0:
s, p = '', 's'
elif len(args) == 1:
s, p = '', args[0]
elif len(args) == 2:
s, p = args
else:
# Should have been checked at compile time
raise AssertionErr... | python | def _Pluralize(value, unused_context, args):
"""Formatter to pluralize words."""
if len(args) == 0:
s, p = '', 's'
elif len(args) == 1:
s, p = '', args[0]
elif len(args) == 2:
s, p = args
else:
# Should have been checked at compile time
raise AssertionErr... | [
"def",
"_Pluralize",
"(",
"value",
",",
"unused_context",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"s",
",",
"p",
"=",
"''",
",",
"'s'",
"elif",
"len",
"(",
"args",
")",
"==",
"1",
":",
"s",
",",
"p",
"=",
"''",
... | Formatter to pluralize words. | [
"Formatter",
"to",
"pluralize",
"words",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L808-L824 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _StrftimeGm | def _StrftimeGm(value, unused_context, args):
"""Convert a timestamp in seconds to a string based on the format string.
Returns GM time.
"""
time_tuple = time.gmtime(value)
return _StrftimeHelper(args, time_tuple) | python | def _StrftimeGm(value, unused_context, args):
"""Convert a timestamp in seconds to a string based on the format string.
Returns GM time.
"""
time_tuple = time.gmtime(value)
return _StrftimeHelper(args, time_tuple) | [
"def",
"_StrftimeGm",
"(",
"value",
",",
"unused_context",
",",
"args",
")",
":",
"time_tuple",
"=",
"time",
".",
"gmtime",
"(",
"value",
")",
"return",
"_StrftimeHelper",
"(",
"args",
",",
"time_tuple",
")"
] | Convert a timestamp in seconds to a string based on the format string.
Returns GM time. | [
"Convert",
"a",
"timestamp",
"in",
"seconds",
"to",
"a",
"string",
"based",
"on",
"the",
"format",
"string",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L843-L849 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _StrftimeLocal | def _StrftimeLocal(value, unused_context, args):
"""Convert a timestamp in seconds to a string based on the format string.
Returns local time.
"""
time_tuple = time.localtime(value)
return _StrftimeHelper(args, time_tuple) | python | def _StrftimeLocal(value, unused_context, args):
"""Convert a timestamp in seconds to a string based on the format string.
Returns local time.
"""
time_tuple = time.localtime(value)
return _StrftimeHelper(args, time_tuple) | [
"def",
"_StrftimeLocal",
"(",
"value",
",",
"unused_context",
",",
"args",
")",
":",
"time_tuple",
"=",
"time",
".",
"localtime",
"(",
"value",
")",
"return",
"_StrftimeHelper",
"(",
"args",
",",
"time_tuple",
")"
] | Convert a timestamp in seconds to a string based on the format string.
Returns local time. | [
"Convert",
"a",
"timestamp",
"in",
"seconds",
"to",
"a",
"string",
"based",
"on",
"the",
"format",
"string",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L852-L858 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _TemplateExists | def _TemplateExists(unused_value, context, args):
"""Returns whether the given name is in the current Template's template group."""
try:
name = args[0]
except IndexError:
raise EvaluationError('The "template" predicate requires an argument.')
return context.HasTemplate(name) | python | def _TemplateExists(unused_value, context, args):
"""Returns whether the given name is in the current Template's template group."""
try:
name = args[0]
except IndexError:
raise EvaluationError('The "template" predicate requires an argument.')
return context.HasTemplate(name) | [
"def",
"_TemplateExists",
"(",
"unused_value",
",",
"context",
",",
"args",
")",
":",
"try",
":",
"name",
"=",
"args",
"[",
"0",
"]",
"except",
"IndexError",
":",
"raise",
"EvaluationError",
"(",
"'The \"template\" predicate requires an argument.'",
")",
"return",... | Returns whether the given name is in the current Template's template group. | [
"Returns",
"whether",
"the",
"given",
"name",
"is",
"in",
"the",
"current",
"Template",
"s",
"template",
"group",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L877-L883 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | SplitMeta | def SplitMeta(meta):
"""Split and validate metacharacters.
Example: '{}' -> ('{', '}')
This is public so the syntax highlighter and other tools can use it.
"""
n = len(meta)
if n % 2 == 1:
raise ConfigurationError(
'%r has an odd number of metacharacters' % meta)
return meta[... | python | def SplitMeta(meta):
"""Split and validate metacharacters.
Example: '{}' -> ('{', '}')
This is public so the syntax highlighter and other tools can use it.
"""
n = len(meta)
if n % 2 == 1:
raise ConfigurationError(
'%r has an odd number of metacharacters' % meta)
return meta[... | [
"def",
"SplitMeta",
"(",
"meta",
")",
":",
"n",
"=",
"len",
"(",
"meta",
")",
"if",
"n",
"%",
"2",
"==",
"1",
":",
"raise",
"ConfigurationError",
"(",
"'%r has an odd number of metacharacters'",
"%",
"meta",
")",
"return",
"meta",
"[",
":",
"n",
"//",
... | Split and validate metacharacters.
Example: '{}' -> ('{', '}')
This is public so the syntax highlighter and other tools can use it. | [
"Split",
"and",
"validate",
"metacharacters",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L900-L911 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | MakeTokenRegex | def MakeTokenRegex(meta_left, meta_right):
"""Return a (compiled) regular expression for tokenization.
Args:
meta_left, meta_right: e.g. '{' and '}'
- The regular expressions are memoized.
- This function is public so the syntax highlighter can use it.
"""
key = meta_left, meta_right
if key no... | python | def MakeTokenRegex(meta_left, meta_right):
"""Return a (compiled) regular expression for tokenization.
Args:
meta_left, meta_right: e.g. '{' and '}'
- The regular expressions are memoized.
- This function is public so the syntax highlighter can use it.
"""
key = meta_left, meta_right
if key no... | [
"def",
"MakeTokenRegex",
"(",
"meta_left",
",",
"meta_right",
")",
":",
"key",
"=",
"meta_left",
",",
"meta_right",
"if",
"key",
"not",
"in",
"_token_re_cache",
":",
"# - Need () grouping for re.split",
"# - The first character must be a non-space. This allows us to ignore",... | Return a (compiled) regular expression for tokenization.
Args:
meta_left, meta_right: e.g. '{' and '}'
- The regular expressions are memoized.
- This function is public so the syntax highlighter can use it. | [
"Return",
"a",
"(",
"compiled",
")",
"regular",
"expression",
"for",
"tokenization",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L917-L938 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _MatchDirective | def _MatchDirective(token):
"""Helper function for matching certain directives."""
# Tokens below must start with '.'
if token.startswith('.'):
token = token[1:]
else:
return None, None
if token == 'end':
return END_TOKEN, None
if token == 'alternates with':
... | python | def _MatchDirective(token):
"""Helper function for matching certain directives."""
# Tokens below must start with '.'
if token.startswith('.'):
token = token[1:]
else:
return None, None
if token == 'end':
return END_TOKEN, None
if token == 'alternates with':
... | [
"def",
"_MatchDirective",
"(",
"token",
")",
":",
"# Tokens below must start with '.'",
"if",
"token",
".",
"startswith",
"(",
"'.'",
")",
":",
"token",
"=",
"token",
"[",
"1",
":",
"]",
"else",
":",
"return",
"None",
",",
"None",
"if",
"token",
"==",
"'... | Helper function for matching certain directives. | [
"Helper",
"function",
"for",
"matching",
"certain",
"directives",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L969-L1008 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _Tokenize | def _Tokenize(template_str, meta_left, meta_right, whitespace):
"""Yields tokens, which are 2-tuples (TOKEN_TYPE, token_string)."""
trimlen = len(meta_left)
token_re = MakeTokenRegex(meta_left, meta_right)
do_strip = (whitespace == 'strip-line') # Do this outside loop
do_strip_part = False
... | python | def _Tokenize(template_str, meta_left, meta_right, whitespace):
"""Yields tokens, which are 2-tuples (TOKEN_TYPE, token_string)."""
trimlen = len(meta_left)
token_re = MakeTokenRegex(meta_left, meta_right)
do_strip = (whitespace == 'strip-line') # Do this outside loop
do_strip_part = False
... | [
"def",
"_Tokenize",
"(",
"template_str",
",",
"meta_left",
",",
"meta_right",
",",
"whitespace",
")",
":",
"trimlen",
"=",
"len",
"(",
"meta_left",
")",
"token_re",
"=",
"MakeTokenRegex",
"(",
"meta_left",
",",
"meta_right",
")",
"do_strip",
"=",
"(",
"white... | Yields tokens, which are 2-tuples (TOKEN_TYPE, token_string). | [
"Yields",
"tokens",
"which",
"are",
"2",
"-",
"tuples",
"(",
"TOKEN_TYPE",
"token_string",
")",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1011-L1103 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _CompileTemplate | def _CompileTemplate(
template_str, builder, meta='{}', format_char='|', default_formatter='str',
whitespace='smart'):
"""Compile the template string, calling methods on the 'program builder'.
Args:
template_str: The template string. It should not have any compilation
options in the ... | python | def _CompileTemplate(
template_str, builder, meta='{}', format_char='|', default_formatter='str',
whitespace='smart'):
"""Compile the template string, calling methods on the 'program builder'.
Args:
template_str: The template string. It should not have any compilation
options in the ... | [
"def",
"_CompileTemplate",
"(",
"template_str",
",",
"builder",
",",
"meta",
"=",
"'{}'",
",",
"format_char",
"=",
"'|'",
",",
"default_formatter",
"=",
"'str'",
",",
"whitespace",
"=",
"'smart'",
")",
":",
"meta_left",
",",
"meta_right",
"=",
"SplitMeta",
"... | Compile the template string, calling methods on the 'program builder'.
Args:
template_str: The template string. It should not have any compilation
options in the header -- those are parsed by FromString/FromFile
builder: The interface of _ProgramBuilder isn't fixed. Use at your own
risk.
... | [
"Compile",
"the",
"template",
"string",
"calling",
"methods",
"on",
"the",
"program",
"builder",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1106-L1250 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | FromString | def FromString(s, **kwargs):
"""Like FromFile, but takes a string."""
f = StringIO.StringIO(s)
return FromFile(f, **kwargs) | python | def FromString(s, **kwargs):
"""Like FromFile, but takes a string."""
f = StringIO.StringIO(s)
return FromFile(f, **kwargs) | [
"def",
"FromString",
"(",
"s",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
"=",
"StringIO",
".",
"StringIO",
"(",
"s",
")",
"return",
"FromFile",
"(",
"f",
",",
"*",
"*",
"kwargs",
")"
] | Like FromFile, but takes a string. | [
"Like",
"FromFile",
"but",
"takes",
"a",
"string",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1258-L1262 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | FromFile | def FromFile(f, more_formatters=lambda x: None, more_predicates=lambda x: None,
_constructor=None):
"""Parse a template from a file, using a simple file format.
This is useful when you want to include template options in a data file,
rather than in the source code.
The format is similar to HTTP... | python | def FromFile(f, more_formatters=lambda x: None, more_predicates=lambda x: None,
_constructor=None):
"""Parse a template from a file, using a simple file format.
This is useful when you want to include template options in a data file,
rather than in the source code.
The format is similar to HTTP... | [
"def",
"FromFile",
"(",
"f",
",",
"more_formatters",
"=",
"lambda",
"x",
":",
"None",
",",
"more_predicates",
"=",
"lambda",
"x",
":",
"None",
",",
"_constructor",
"=",
"None",
")",
":",
"_constructor",
"=",
"_constructor",
"or",
"Template",
"options",
"="... | Parse a template from a file, using a simple file format.
This is useful when you want to include template options in a data file,
rather than in the source code.
The format is similar to HTTP or E-mail headers. The first lines of the file
can specify template options, such as the metacharacters to use. One... | [
"Parse",
"a",
"template",
"from",
"a",
"file",
"using",
"a",
"simple",
"file",
"format",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1265-L1329 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _MakeGroupFromRootSection | def _MakeGroupFromRootSection(root_section, undefined_str):
"""Construct a dictinary { template name -> Template() instance }
Args:
root_section: _Section instance -- root of the original parse tree
"""
group = {}
for statement in root_section.Statements():
if isinstance(statement, six.stri... | python | def _MakeGroupFromRootSection(root_section, undefined_str):
"""Construct a dictinary { template name -> Template() instance }
Args:
root_section: _Section instance -- root of the original parse tree
"""
group = {}
for statement in root_section.Statements():
if isinstance(statement, six.stri... | [
"def",
"_MakeGroupFromRootSection",
"(",
"root_section",
",",
"undefined_str",
")",
":",
"group",
"=",
"{",
"}",
"for",
"statement",
"in",
"root_section",
".",
"Statements",
"(",
")",
":",
"if",
"isinstance",
"(",
"statement",
",",
"six",
".",
"string_types",
... | Construct a dictinary { template name -> Template() instance }
Args:
root_section: _Section instance -- root of the original parse tree | [
"Construct",
"a",
"dictinary",
"{",
"template",
"name",
"-",
">",
"Template",
"()",
"instance",
"}"
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1528-L1545 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | JoinTokens | def JoinTokens(tokens):
"""Join tokens (which may be a mix of unicode and str values).
See notes on unicode at the top. This function allows mixing encoded utf-8
byte string tokens with unicode tokens. (Python's default encoding is ASCII,
and we don't want to change that.)
We also want to support pure b... | python | def JoinTokens(tokens):
"""Join tokens (which may be a mix of unicode and str values).
See notes on unicode at the top. This function allows mixing encoded utf-8
byte string tokens with unicode tokens. (Python's default encoding is ASCII,
and we don't want to change that.)
We also want to support pure b... | [
"def",
"JoinTokens",
"(",
"tokens",
")",
":",
"try",
":",
"return",
"''",
".",
"join",
"(",
"tokens",
")",
"except",
"UnicodeDecodeError",
":",
"# This can still raise UnicodeDecodeError if that data isn't utf-8.",
"return",
"''",
".",
"join",
"(",
"t",
".",
"deco... | Join tokens (which may be a mix of unicode and str values).
See notes on unicode at the top. This function allows mixing encoded utf-8
byte string tokens with unicode tokens. (Python's default encoding is ASCII,
and we don't want to change that.)
We also want to support pure byte strings, so we can't get ri... | [
"Join",
"tokens",
"(",
"which",
"may",
"be",
"a",
"mix",
"of",
"unicode",
"and",
"str",
"values",
")",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1571-L1588 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _DoRepeatedSection | def _DoRepeatedSection(args, context, callback, trace):
"""{.repeated section foo}"""
block = args
items = context.PushSection(block.section_name, block.pre_formatters)
if items:
if not isinstance(items, list):
raise EvaluationError('Expected a list; got %s' % type(items))
... | python | def _DoRepeatedSection(args, context, callback, trace):
"""{.repeated section foo}"""
block = args
items = context.PushSection(block.section_name, block.pre_formatters)
if items:
if not isinstance(items, list):
raise EvaluationError('Expected a list; got %s' % type(items))
... | [
"def",
"_DoRepeatedSection",
"(",
"args",
",",
"context",
",",
"callback",
",",
"trace",
")",
":",
"block",
"=",
"args",
"items",
"=",
"context",
".",
"PushSection",
"(",
"block",
".",
"section_name",
",",
"block",
".",
"pre_formatters",
")",
"if",
"items"... | {.repeated section foo} | [
"{",
".",
"repeated",
"section",
"foo",
"}"
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1591-L1621 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _DoSection | def _DoSection(args, context, callback, trace):
"""{.section foo}"""
block = args
# If a section present and "true", push the dictionary onto the stack as the
# new context, and show it
if context.PushSection(block.section_name, block.pre_formatters):
_Execute(block.Statements(), context, ca... | python | def _DoSection(args, context, callback, trace):
"""{.section foo}"""
block = args
# If a section present and "true", push the dictionary onto the stack as the
# new context, and show it
if context.PushSection(block.section_name, block.pre_formatters):
_Execute(block.Statements(), context, ca... | [
"def",
"_DoSection",
"(",
"args",
",",
"context",
",",
"callback",
",",
"trace",
")",
":",
"block",
"=",
"args",
"# If a section present and \"true\", push the dictionary onto the stack as the",
"# new context, and show it",
"if",
"context",
".",
"PushSection",
"(",
"bloc... | {.section foo} | [
"{",
".",
"section",
"foo",
"}"
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1624-L1634 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _DoPredicates | def _DoPredicates(args, context, callback, trace):
"""{.predicate?}
Here we execute the first clause that evaluates to true, and then stop.
"""
block = args
value = context.Lookup('@')
for (predicate, args, func_type), statements in block.clauses:
if func_type == ENHANCED_FUNC:
... | python | def _DoPredicates(args, context, callback, trace):
"""{.predicate?}
Here we execute the first clause that evaluates to true, and then stop.
"""
block = args
value = context.Lookup('@')
for (predicate, args, func_type), statements in block.clauses:
if func_type == ENHANCED_FUNC:
... | [
"def",
"_DoPredicates",
"(",
"args",
",",
"context",
",",
"callback",
",",
"trace",
")",
":",
"block",
"=",
"args",
"value",
"=",
"context",
".",
"Lookup",
"(",
"'@'",
")",
"for",
"(",
"predicate",
",",
"args",
",",
"func_type",
")",
",",
"statements",... | {.predicate?}
Here we execute the first clause that evaluates to true, and then stop. | [
"{",
".",
"predicate?",
"}"
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1637-L1654 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _DoSubstitute | def _DoSubstitute(args, context, callback, trace):
"""Variable substitution, i.e. {foo}
We also implement template formatters here, i.e. {foo|template bar} as well
as {.template FOO} for templates that operate on the root of the data dict
rather than a subtree.
"""
name, formatters = args
if ... | python | def _DoSubstitute(args, context, callback, trace):
"""Variable substitution, i.e. {foo}
We also implement template formatters here, i.e. {foo|template bar} as well
as {.template FOO} for templates that operate on the root of the data dict
rather than a subtree.
"""
name, formatters = args
if ... | [
"def",
"_DoSubstitute",
"(",
"args",
",",
"context",
",",
"callback",
",",
"trace",
")",
":",
"name",
",",
"formatters",
"=",
"args",
"if",
"name",
"is",
"None",
":",
"value",
"=",
"context",
".",
"Root",
"(",
")",
"# don't use the cursor",
"else",
":",
... | Variable substitution, i.e. {foo}
We also implement template formatters here, i.e. {foo|template bar} as well
as {.template FOO} for templates that operate on the root of the data dict
rather than a subtree. | [
"Variable",
"substitution",
"i",
".",
"e",
".",
"{",
"foo",
"}"
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1664-L1722 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _Execute | def _Execute(statements, context, callback, trace):
"""Execute a bunch of template statements in a ScopedContext.
Args:
callback: Strings are "written" to this callback function.
trace: Trace object, or None
This is called in a mutually recursive fashion.
"""
# Every time we call _Execute, incre... | python | def _Execute(statements, context, callback, trace):
"""Execute a bunch of template statements in a ScopedContext.
Args:
callback: Strings are "written" to this callback function.
trace: Trace object, or None
This is called in a mutually recursive fashion.
"""
# Every time we call _Execute, incre... | [
"def",
"_Execute",
"(",
"statements",
",",
"context",
",",
"callback",
",",
"trace",
")",
":",
"# Every time we call _Execute, increase this depth",
"if",
"trace",
":",
"trace",
".",
"exec_depth",
"+=",
"1",
"for",
"i",
",",
"statement",
"in",
"enumerate",
"(",
... | Execute a bunch of template statements in a ScopedContext.
Args:
callback: Strings are "written" to this callback function.
trace: Trace object, or None
This is called in a mutually recursive fashion. | [
"Execute",
"a",
"bunch",
"of",
"template",
"statements",
"in",
"a",
"ScopedContext",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1725-L1752 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | expand | def expand(template_str, dictionary, **kwargs):
"""Free function to expands a template string with a data dictionary.
This is useful for cases where you don't care about saving the result of
compilation (similar to re.match('.*', s) vs DOT_STAR.match(s))
"""
t = Template(template_str, **kwargs)
retur... | python | def expand(template_str, dictionary, **kwargs):
"""Free function to expands a template string with a data dictionary.
This is useful for cases where you don't care about saving the result of
compilation (similar to re.match('.*', s) vs DOT_STAR.match(s))
"""
t = Template(template_str, **kwargs)
retur... | [
"def",
"expand",
"(",
"template_str",
",",
"dictionary",
",",
"*",
"*",
"kwargs",
")",
":",
"t",
"=",
"Template",
"(",
"template_str",
",",
"*",
"*",
"kwargs",
")",
"return",
"t",
".",
"expand",
"(",
"dictionary",
")"
] | Free function to expands a template string with a data dictionary.
This is useful for cases where you don't care about saving the result of
compilation (similar to re.match('.*', s) vs DOT_STAR.match(s)) | [
"Free",
"function",
"to",
"expands",
"a",
"template",
"string",
"with",
"a",
"data",
"dictionary",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1755-L1762 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _FlattenToCallback | def _FlattenToCallback(tokens, callback):
"""Takes a nested list structure and flattens it.
['a', ['b', 'c']] -> callback('a'); callback('b'); callback('c');
"""
for t in tokens:
if isinstance(t, six.string_types):
callback(t)
else:
_FlattenToCallback(t, callback) | python | def _FlattenToCallback(tokens, callback):
"""Takes a nested list structure and flattens it.
['a', ['b', 'c']] -> callback('a'); callback('b'); callback('c');
"""
for t in tokens:
if isinstance(t, six.string_types):
callback(t)
else:
_FlattenToCallback(t, callback) | [
"def",
"_FlattenToCallback",
"(",
"tokens",
",",
"callback",
")",
":",
"for",
"t",
"in",
"tokens",
":",
"if",
"isinstance",
"(",
"t",
",",
"six",
".",
"string_types",
")",
":",
"callback",
"(",
"t",
")",
"else",
":",
"_FlattenToCallback",
"(",
"t",
","... | Takes a nested list structure and flattens it.
['a', ['b', 'c']] -> callback('a'); callback('b'); callback('c'); | [
"Takes",
"a",
"nested",
"list",
"structure",
"and",
"flattens",
"it",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1768-L1777 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | execute_with_style_LEGACY | def execute_with_style_LEGACY(template, style, data, callback, body_subtree='body'):
"""OBSOLETE old API."""
try:
body_data = data[body_subtree]
except KeyError:
raise EvaluationError('Data dictionary has no subtree %r' % body_subtree)
tokens_body = []
template.execute(body_data, tok... | python | def execute_with_style_LEGACY(template, style, data, callback, body_subtree='body'):
"""OBSOLETE old API."""
try:
body_data = data[body_subtree]
except KeyError:
raise EvaluationError('Data dictionary has no subtree %r' % body_subtree)
tokens_body = []
template.execute(body_data, tok... | [
"def",
"execute_with_style_LEGACY",
"(",
"template",
",",
"style",
",",
"data",
",",
"callback",
",",
"body_subtree",
"=",
"'body'",
")",
":",
"try",
":",
"body_data",
"=",
"data",
"[",
"body_subtree",
"]",
"except",
"KeyError",
":",
"raise",
"EvaluationError"... | OBSOLETE old API. | [
"OBSOLETE",
"old",
"API",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1783-L1794 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | expand_with_style | def expand_with_style(template, style, data, body_subtree='body'):
"""Expand a data dictionary with a template AND a style.
DEPRECATED -- Remove this entire function in favor of expand(d, style=style)
A style is a Template instance that factors out the common strings in several
"body" templates.
Args:
... | python | def expand_with_style(template, style, data, body_subtree='body'):
"""Expand a data dictionary with a template AND a style.
DEPRECATED -- Remove this entire function in favor of expand(d, style=style)
A style is a Template instance that factors out the common strings in several
"body" templates.
Args:
... | [
"def",
"expand_with_style",
"(",
"template",
",",
"style",
",",
"data",
",",
"body_subtree",
"=",
"'body'",
")",
":",
"if",
"template",
".",
"has_defines",
":",
"return",
"template",
".",
"expand",
"(",
"data",
",",
"style",
"=",
"style",
")",
"else",
":... | Expand a data dictionary with a template AND a style.
DEPRECATED -- Remove this entire function in favor of expand(d, style=style)
A style is a Template instance that factors out the common strings in several
"body" templates.
Args:
template: Template instance for the inner "page content"
style: Temp... | [
"Expand",
"a",
"data",
"dictionary",
"with",
"a",
"template",
"AND",
"a",
"style",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1797-L1816 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _TemplateRegistry.LookupWithType | def LookupWithType(self, user_str):
"""
Returns:
ref: Either a template instance (itself) or _TemplateRef
"""
prefix = 'template '
ref = None # fail the lookup by default
if user_str.startswith(prefix):
name = user_str[len(prefix):]
if name == 'SELF... | python | def LookupWithType(self, user_str):
"""
Returns:
ref: Either a template instance (itself) or _TemplateRef
"""
prefix = 'template '
ref = None # fail the lookup by default
if user_str.startswith(prefix):
name = user_str[len(prefix):]
if name == 'SELF... | [
"def",
"LookupWithType",
"(",
"self",
",",
"user_str",
")",
":",
"prefix",
"=",
"'template '",
"ref",
"=",
"None",
"# fail the lookup by default",
"if",
"user_str",
".",
"startswith",
"(",
"prefix",
")",
":",
"name",
"=",
"user_str",
"[",
"len",
"(",
"prefix... | Returns:
ref: Either a template instance (itself) or _TemplateRef | [
"Returns",
":",
"ref",
":",
"Either",
"a",
"template",
"instance",
"(",
"itself",
")",
"or",
"_TemplateRef"
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L293-L308 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ProgramBuilder._GetFormatter | def _GetFormatter(self, format_str):
"""
The user's formatters are consulted first, then the default formatters.
"""
formatter, args, func_type = self.formatters.LookupWithType(format_str)
if formatter:
return formatter, args, func_type
else:
raise BadForm... | python | def _GetFormatter(self, format_str):
"""
The user's formatters are consulted first, then the default formatters.
"""
formatter, args, func_type = self.formatters.LookupWithType(format_str)
if formatter:
return formatter, args, func_type
else:
raise BadForm... | [
"def",
"_GetFormatter",
"(",
"self",
",",
"format_str",
")",
":",
"formatter",
",",
"args",
",",
"func_type",
"=",
"self",
".",
"formatters",
".",
"LookupWithType",
"(",
"format_str",
")",
"if",
"formatter",
":",
"return",
"formatter",
",",
"args",
",",
"f... | The user's formatters are consulted first, then the default formatters. | [
"The",
"user",
"s",
"formatters",
"are",
"consulted",
"first",
"then",
"the",
"default",
"formatters",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L390-L398 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ProgramBuilder._GetPredicate | def _GetPredicate(self, pred_str, test_attr=False):
"""
The user's predicates are consulted first, then the default predicates.
"""
predicate, args, func_type = self.predicates.LookupWithType(pred_str)
if predicate:
pred = predicate, args, func_type
else:
... | python | def _GetPredicate(self, pred_str, test_attr=False):
"""
The user's predicates are consulted first, then the default predicates.
"""
predicate, args, func_type = self.predicates.LookupWithType(pred_str)
if predicate:
pred = predicate, args, func_type
else:
... | [
"def",
"_GetPredicate",
"(",
"self",
",",
"pred_str",
",",
"test_attr",
"=",
"False",
")",
":",
"predicate",
",",
"args",
",",
"func_type",
"=",
"self",
".",
"predicates",
".",
"LookupWithType",
"(",
"pred_str",
")",
"if",
"predicate",
":",
"pred",
"=",
... | The user's predicates are consulted first, then the default predicates. | [
"The",
"user",
"s",
"predicates",
"are",
"consulted",
"first",
"then",
"the",
"default",
"predicates",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L400-L417 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ProgramBuilder.NewSection | def NewSection(self, token_type, section_name, pre_formatters):
"""For sections or repeated sections."""
pre_formatters = [self._GetFormatter(f) for f in pre_formatters]
# TODO: Consider getting rid of this dispatching, and turn _Do* into methods
if token_type == REPEATED_SECTIO... | python | def NewSection(self, token_type, section_name, pre_formatters):
"""For sections or repeated sections."""
pre_formatters = [self._GetFormatter(f) for f in pre_formatters]
# TODO: Consider getting rid of this dispatching, and turn _Do* into methods
if token_type == REPEATED_SECTIO... | [
"def",
"NewSection",
"(",
"self",
",",
"token_type",
",",
"section_name",
",",
"pre_formatters",
")",
":",
"pre_formatters",
"=",
"[",
"self",
".",
"_GetFormatter",
"(",
"f",
")",
"for",
"f",
"in",
"pre_formatters",
"]",
"# TODO: Consider getting rid of this dispa... | For sections or repeated sections. | [
"For",
"sections",
"or",
"repeated",
"sections",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L435-L452 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ProgramBuilder.NewOrClause | def NewOrClause(self, pred_str):
"""
{.or ...} Can appear inside predicate blocks or section blocks, with
slightly different meaning.
"""
if pred_str:
pred = self._GetPredicate(pred_str, test_attr=False)
else:
pred = None
self.current_section.NewOrClau... | python | def NewOrClause(self, pred_str):
"""
{.or ...} Can appear inside predicate blocks or section blocks, with
slightly different meaning.
"""
if pred_str:
pred = self._GetPredicate(pred_str, test_attr=False)
else:
pred = None
self.current_section.NewOrClau... | [
"def",
"NewOrClause",
"(",
"self",
",",
"pred_str",
")",
":",
"if",
"pred_str",
":",
"pred",
"=",
"self",
".",
"_GetPredicate",
"(",
"pred_str",
",",
"test_attr",
"=",
"False",
")",
"else",
":",
"pred",
"=",
"None",
"self",
".",
"current_section",
".",
... | {.or ...} Can appear inside predicate blocks or section blocks, with
slightly different meaning. | [
"{",
".",
"or",
"...",
"}",
"Can",
"appear",
"inside",
"predicate",
"blocks",
"or",
"section",
"blocks",
"with",
"slightly",
"different",
"meaning",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L454-L463 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ProgramBuilder.NewPredicateSection | def NewPredicateSection(self, pred_str, test_attr=False):
"""For chains of predicate clauses."""
pred = self._GetPredicate(pred_str, test_attr=test_attr)
block = _PredicateSection()
block.NewOrClause(pred)
self._NewSection(_DoPredicates, block) | python | def NewPredicateSection(self, pred_str, test_attr=False):
"""For chains of predicate clauses."""
pred = self._GetPredicate(pred_str, test_attr=test_attr)
block = _PredicateSection()
block.NewOrClause(pred)
self._NewSection(_DoPredicates, block) | [
"def",
"NewPredicateSection",
"(",
"self",
",",
"pred_str",
",",
"test_attr",
"=",
"False",
")",
":",
"pred",
"=",
"self",
".",
"_GetPredicate",
"(",
"pred_str",
",",
"test_attr",
"=",
"test_attr",
")",
"block",
"=",
"_PredicateSection",
"(",
")",
"block",
... | For chains of predicate clauses. | [
"For",
"chains",
"of",
"predicate",
"clauses",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L468-L474 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ScopedContext.PushSection | def PushSection(self, name, pre_formatters):
"""Given a section name, push it on the top of the stack.
Returns:
The new section, or None if there is no such section.
"""
if name == '@':
value = self.stack[-1].context
else:
value = self.stack[-1].context.get... | python | def PushSection(self, name, pre_formatters):
"""Given a section name, push it on the top of the stack.
Returns:
The new section, or None if there is no such section.
"""
if name == '@':
value = self.stack[-1].context
else:
value = self.stack[-1].context.get... | [
"def",
"PushSection",
"(",
"self",
",",
"name",
",",
"pre_formatters",
")",
":",
"if",
"name",
"==",
"'@'",
":",
"value",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"context",
"else",
":",
"value",
"=",
"self",
".",
"stack",
"[",
"-",
"1... | Given a section name, push it on the top of the stack.
Returns:
The new section, or None if there is no such section. | [
"Given",
"a",
"section",
"name",
"push",
"it",
"on",
"the",
"top",
"of",
"the",
"stack",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L598-L619 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ScopedContext.Next | def Next(self):
"""Advance to the next item in a repeated section.
Raises:
StopIteration if there are no more elements
"""
stacktop = self.stack[-1]
# Now we're iterating -- push a new mutable object onto the stack
if stacktop.index == -1:
stacktop = _... | python | def Next(self):
"""Advance to the next item in a repeated section.
Raises:
StopIteration if there are no more elements
"""
stacktop = self.stack[-1]
# Now we're iterating -- push a new mutable object onto the stack
if stacktop.index == -1:
stacktop = _... | [
"def",
"Next",
"(",
"self",
")",
":",
"stacktop",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"# Now we're iterating -- push a new mutable object onto the stack",
"if",
"stacktop",
".",
"index",
"==",
"-",
"1",
":",
"stacktop",
"=",
"_Frame",
"(",
"None",
... | Advance to the next item in a repeated section.
Raises:
StopIteration if there are no more elements | [
"Advance",
"to",
"the",
"next",
"item",
"in",
"a",
"repeated",
"section",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L624-L646 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ScopedContext._LookUpStack | def _LookUpStack(self, name):
"""Look up the stack for the given name."""
i = len(self.stack) - 1
while 1:
frame = self.stack[i]
if name == '@index':
if frame.index != -1: # -1 is undefined
return frame.index # @index is 1-based
... | python | def _LookUpStack(self, name):
"""Look up the stack for the given name."""
i = len(self.stack) - 1
while 1:
frame = self.stack[i]
if name == '@index':
if frame.index != -1: # -1 is undefined
return frame.index # @index is 1-based
... | [
"def",
"_LookUpStack",
"(",
"self",
",",
"name",
")",
":",
"i",
"=",
"len",
"(",
"self",
".",
"stack",
")",
"-",
"1",
"while",
"1",
":",
"frame",
"=",
"self",
".",
"stack",
"[",
"i",
"]",
"if",
"name",
"==",
"'@index'",
":",
"if",
"frame",
".",... | Look up the stack for the given name. | [
"Look",
"up",
"the",
"stack",
"for",
"the",
"given",
"name",
"."
] | train | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L654-L672 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.