repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Cognexa/cxflow | cxflow/hooks/compute_stats.py | ComputeStats.after_epoch | def after_epoch(self, epoch_data: EpochData, **kwargs) -> None:
"""
Compute the specified aggregations and save them to the given epoch data.
:param epoch_data: epoch data to be processed
"""
self._save_stats(epoch_data)
super().after_epoch(epoch_data=epoch_data, **kwarg... | python | def after_epoch(self, epoch_data: EpochData, **kwargs) -> None:
"""
Compute the specified aggregations and save them to the given epoch data.
:param epoch_data: epoch data to be processed
"""
self._save_stats(epoch_data)
super().after_epoch(epoch_data=epoch_data, **kwarg... | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
",",
"**",
"kwargs",
")",
"->",
"None",
":",
"self",
".",
"_save_stats",
"(",
"epoch_data",
")",
"super",
"(",
")",
".",
"after_epoch",
"(",
"epoch_data",
"=",
"epoch_data",
",",
"**... | Compute the specified aggregations and save them to the given epoch data.
:param epoch_data: epoch data to be processed | [
"Compute",
"the",
"specified",
"aggregations",
"and",
"save",
"them",
"to",
"the",
"given",
"epoch",
"data",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/compute_stats.py#L106-L113 | train |
Cognexa/cxflow | cxflow/utils/training_trace.py | TrainingTrace.from_file | def from_file(filepath: str):
"""
Load training trace from the given ``filepath``.
:param filepath: training trace file path
:return: training trace
"""
trace = TrainingTrace()
trace._trace = load_config(filepath)
return trace | python | def from_file(filepath: str):
"""
Load training trace from the given ``filepath``.
:param filepath: training trace file path
:return: training trace
"""
trace = TrainingTrace()
trace._trace = load_config(filepath)
return trace | [
"def",
"from_file",
"(",
"filepath",
":",
"str",
")",
":",
"trace",
"=",
"TrainingTrace",
"(",
")",
"trace",
".",
"_trace",
"=",
"load_config",
"(",
"filepath",
")",
"return",
"trace"
] | Load training trace from the given ``filepath``.
:param filepath: training trace file path
:return: training trace | [
"Load",
"training",
"trace",
"from",
"the",
"given",
"filepath",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/training_trace.py#L85-L94 | train |
Cognexa/cxflow | cxflow/hooks/check.py | Check.after_epoch | def after_epoch(self, epoch_id: int, epoch_data: EpochData):
"""
Check termination conditions.
:param epoch_id: number of the processed epoch
:param epoch_data: epoch data to be checked
:raise KeyError: if the stream of variable was not found in ``epoch_data``
:raise Typ... | python | def after_epoch(self, epoch_id: int, epoch_data: EpochData):
"""
Check termination conditions.
:param epoch_id: number of the processed epoch
:param epoch_data: epoch data to be checked
:raise KeyError: if the stream of variable was not found in ``epoch_data``
:raise Typ... | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"epoch_data",
":",
"EpochData",
")",
":",
"if",
"self",
".",
"_stream",
"not",
"in",
"epoch_data",
":",
"raise",
"KeyError",
"(",
"'The hook could not determine whether the threshold was exceeded a... | Check termination conditions.
:param epoch_id: number of the processed epoch
:param epoch_data: epoch data to be checked
:raise KeyError: if the stream of variable was not found in ``epoch_data``
:raise TypeError: if the monitored variable is not a scalar or scalar ``mean`` aggregation
... | [
"Check",
"termination",
"conditions",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/check.py#L43-L76 | train |
Cognexa/cxflow | cxflow/cli/train.py | train | def train(config_path: str, cl_arguments: Iterable[str], output_root: str) -> None:
"""
Load config and start the training.
:param config_path: path to configuration file
:param cl_arguments: additional command line arguments which will update the configuration
:param output_root: output root in wh... | python | def train(config_path: str, cl_arguments: Iterable[str], output_root: str) -> None:
"""
Load config and start the training.
:param config_path: path to configuration file
:param cl_arguments: additional command line arguments which will update the configuration
:param output_root: output root in wh... | [
"def",
"train",
"(",
"config_path",
":",
"str",
",",
"cl_arguments",
":",
"Iterable",
"[",
"str",
"]",
",",
"output_root",
":",
"str",
")",
"->",
"None",
":",
"config",
"=",
"None",
"try",
":",
"config_path",
"=",
"find_config",
"(",
"config_path",
")",
... | Load config and start the training.
:param config_path: path to configuration file
:param cl_arguments: additional command line arguments which will update the configuration
:param output_root: output root in which the training directory will be created | [
"Load",
"config",
"and",
"start",
"the",
"training",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/train.py#L11-L29 | train |
Cognexa/cxflow | cxflow/cli/eval.py | evaluate | def evaluate(model_path: str, stream_name: str, config_path: Optional[str], cl_arguments: Iterable[str],
output_root: str) -> None:
"""
Evaluate the given model on the specified data stream.
Configuration is updated by the respective predict.stream_name section, in particular:
- hooks ... | python | def evaluate(model_path: str, stream_name: str, config_path: Optional[str], cl_arguments: Iterable[str],
output_root: str) -> None:
"""
Evaluate the given model on the specified data stream.
Configuration is updated by the respective predict.stream_name section, in particular:
- hooks ... | [
"def",
"evaluate",
"(",
"model_path",
":",
"str",
",",
"stream_name",
":",
"str",
",",
"config_path",
":",
"Optional",
"[",
"str",
"]",
",",
"cl_arguments",
":",
"Iterable",
"[",
"str",
"]",
",",
"output_root",
":",
"str",
")",
"->",
"None",
":",
"conf... | Evaluate the given model on the specified data stream.
Configuration is updated by the respective predict.stream_name section, in particular:
- hooks section is entirely replaced
- model and dataset sections are updated
:param model_path: path to the model to be evaluated
:param stream_nam... | [
"Evaluate",
"the",
"given",
"model",
"on",
"the",
"specified",
"data",
"stream",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/eval.py#L12-L57 | train |
Cognexa/cxflow | cxflow/cli/eval.py | predict | def predict(config_path: str, restore_from: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None:
"""
Run prediction from the specified config path.
If the config contains a ``predict`` section:
- override hooks with ``predict.hooks`` if present
- update dataset, model and ... | python | def predict(config_path: str, restore_from: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None:
"""
Run prediction from the specified config path.
If the config contains a ``predict`` section:
- override hooks with ``predict.hooks`` if present
- update dataset, model and ... | [
"def",
"predict",
"(",
"config_path",
":",
"str",
",",
"restore_from",
":",
"Optional",
"[",
"str",
"]",
",",
"cl_arguments",
":",
"Iterable",
"[",
"str",
"]",
",",
"output_root",
":",
"str",
")",
"->",
"None",
":",
"config",
"=",
"None",
"try",
":",
... | Run prediction from the specified config path.
If the config contains a ``predict`` section:
- override hooks with ``predict.hooks`` if present
- update dataset, model and main loop sections if the respective sections are present
:param config_path: path to the config file or the directory in ... | [
"Run",
"prediction",
"from",
"the",
"specified",
"config",
"path",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/eval.py#L60-L99 | train |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop._create_epoch_data | def _create_epoch_data(self, streams: Optional[Iterable[str]]=None) -> EpochData:
"""Create empty epoch data double dict."""
if streams is None:
streams = [self._train_stream_name] + self._extra_streams
return OrderedDict([(stream_name, OrderedDict()) for stream_name in streams]) | python | def _create_epoch_data(self, streams: Optional[Iterable[str]]=None) -> EpochData:
"""Create empty epoch data double dict."""
if streams is None:
streams = [self._train_stream_name] + self._extra_streams
return OrderedDict([(stream_name, OrderedDict()) for stream_name in streams]) | [
"def",
"_create_epoch_data",
"(",
"self",
",",
"streams",
":",
"Optional",
"[",
"Iterable",
"[",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"EpochData",
":",
"if",
"streams",
"is",
"None",
":",
"streams",
"=",
"[",
"self",
".",
"_train_stream_name",
"]",
... | Create empty epoch data double dict. | [
"Create",
"empty",
"epoch",
"data",
"double",
"dict",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L96-L100 | train |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop._check_sources | def _check_sources(self, batch: Dict[str, object]) -> None:
"""
Check for unused and missing sources.
:param batch: batch to be checked
:raise ValueError: if a source is missing or unused and ``self._on_unused_sources`` is set to ``error``
"""
unused_sources = [source fo... | python | def _check_sources(self, batch: Dict[str, object]) -> None:
"""
Check for unused and missing sources.
:param batch: batch to be checked
:raise ValueError: if a source is missing or unused and ``self._on_unused_sources`` is set to ``error``
"""
unused_sources = [source fo... | [
"def",
"_check_sources",
"(",
"self",
",",
"batch",
":",
"Dict",
"[",
"str",
",",
"object",
"]",
")",
"->",
"None",
":",
"unused_sources",
"=",
"[",
"source",
"for",
"source",
"in",
"batch",
".",
"keys",
"(",
")",
"if",
"source",
"not",
"in",
"self",... | Check for unused and missing sources.
:param batch: batch to be checked
:raise ValueError: if a source is missing or unused and ``self._on_unused_sources`` is set to ``error`` | [
"Check",
"for",
"unused",
"and",
"missing",
"sources",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L102-L125 | train |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop.train_by_stream | def train_by_stream(self, stream: StreamWrapper) -> None:
"""
Train the model with the given stream.
:param stream: stream to train with
"""
self._run_epoch(stream=stream, train=True) | python | def train_by_stream(self, stream: StreamWrapper) -> None:
"""
Train the model with the given stream.
:param stream: stream to train with
"""
self._run_epoch(stream=stream, train=True) | [
"def",
"train_by_stream",
"(",
"self",
",",
"stream",
":",
"StreamWrapper",
")",
"->",
"None",
":",
"self",
".",
"_run_epoch",
"(",
"stream",
"=",
"stream",
",",
"train",
"=",
"True",
")"
] | Train the model with the given stream.
:param stream: stream to train with | [
"Train",
"the",
"model",
"with",
"the",
"given",
"stream",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L182-L188 | train |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop.evaluate_stream | def evaluate_stream(self, stream: StreamWrapper) -> None:
"""
Evaluate the given stream.
:param stream: stream to be evaluated
:param stream_name: stream name
"""
self._run_epoch(stream=stream, train=False) | python | def evaluate_stream(self, stream: StreamWrapper) -> None:
"""
Evaluate the given stream.
:param stream: stream to be evaluated
:param stream_name: stream name
"""
self._run_epoch(stream=stream, train=False) | [
"def",
"evaluate_stream",
"(",
"self",
",",
"stream",
":",
"StreamWrapper",
")",
"->",
"None",
":",
"self",
".",
"_run_epoch",
"(",
"stream",
"=",
"stream",
",",
"train",
"=",
"False",
")"
] | Evaluate the given stream.
:param stream: stream to be evaluated
:param stream_name: stream name | [
"Evaluate",
"the",
"given",
"stream",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L190-L197 | train |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop._run_zeroth_epoch | def _run_zeroth_epoch(self, streams: Iterable[str]) -> None:
"""
Run zeroth epoch on the specified streams.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
:param streams: stream names to be evaluated
"""
for stream_name in streams:
with... | python | def _run_zeroth_epoch(self, streams: Iterable[str]) -> None:
"""
Run zeroth epoch on the specified streams.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
:param streams: stream names to be evaluated
"""
for stream_name in streams:
with... | [
"def",
"_run_zeroth_epoch",
"(",
"self",
",",
"streams",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"for",
"stream_name",
"in",
"streams",
":",
"with",
"self",
".",
"get_stream",
"(",
"stream_name",
")",
"as",
"stream",
":",
"self",
".",
... | Run zeroth epoch on the specified streams.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
:param streams: stream names to be evaluated | [
"Run",
"zeroth",
"epoch",
"on",
"the",
"specified",
"streams",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L222-L237 | train |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop.run_training | def run_training(self, trace: Optional[TrainingTrace]=None) -> None:
"""
Run the main loop in the training mode.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch_profile`
"""
for stream_name in [se... | python | def run_training(self, trace: Optional[TrainingTrace]=None) -> None:
"""
Run the main loop in the training mode.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch_profile`
"""
for stream_name in [se... | [
"def",
"run_training",
"(",
"self",
",",
"trace",
":",
"Optional",
"[",
"TrainingTrace",
"]",
"=",
"None",
")",
"->",
"None",
":",
"for",
"stream_name",
"in",
"[",
"self",
".",
"_train_stream_name",
"]",
"+",
"self",
".",
"_extra_streams",
":",
"self",
"... | Run the main loop in the training mode.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch_profile` | [
"Run",
"the",
"main",
"loop",
"in",
"the",
"training",
"mode",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L262-L310 | train |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop.run_evaluation | def run_evaluation(self, stream_name: str) -> None:
"""
Run the main loop with the given stream in the prediction mode.
:param stream_name: name of the stream to be evaluated
"""
def prediction():
logging.info('Running prediction')
self._run_zeroth_epoch(... | python | def run_evaluation(self, stream_name: str) -> None:
"""
Run the main loop with the given stream in the prediction mode.
:param stream_name: name of the stream to be evaluated
"""
def prediction():
logging.info('Running prediction')
self._run_zeroth_epoch(... | [
"def",
"run_evaluation",
"(",
"self",
",",
"stream_name",
":",
"str",
")",
"->",
"None",
":",
"def",
"prediction",
"(",
")",
":",
"logging",
".",
"info",
"(",
"'Running prediction'",
")",
"self",
".",
"_run_zeroth_epoch",
"(",
"[",
"stream_name",
"]",
")",... | Run the main loop with the given stream in the prediction mode.
:param stream_name: name of the stream to be evaluated | [
"Run",
"the",
"main",
"loop",
"with",
"the",
"given",
"stream",
"in",
"the",
"prediction",
"mode",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L312-L322 | train |
Cognexa/cxflow | cxflow/models/ensemble.py | major_vote | def major_vote(all_votes: Iterable[Iterable[Hashable]]) -> Iterable[Hashable]:
"""
For the given iterable of object iterations, return an iterable of the most common object at each position of the
inner iterations.
E.g.: for [[1, 2], [1, 3], [2, 3]] the return value would be [1, 3] as 1 and 3 are the m... | python | def major_vote(all_votes: Iterable[Iterable[Hashable]]) -> Iterable[Hashable]:
"""
For the given iterable of object iterations, return an iterable of the most common object at each position of the
inner iterations.
E.g.: for [[1, 2], [1, 3], [2, 3]] the return value would be [1, 3] as 1 and 3 are the m... | [
"def",
"major_vote",
"(",
"all_votes",
":",
"Iterable",
"[",
"Iterable",
"[",
"Hashable",
"]",
"]",
")",
"->",
"Iterable",
"[",
"Hashable",
"]",
":",
"return",
"[",
"Counter",
"(",
"votes",
")",
".",
"most_common",
"(",
")",
"[",
"0",
"]",
"[",
"0",
... | For the given iterable of object iterations, return an iterable of the most common object at each position of the
inner iterations.
E.g.: for [[1, 2], [1, 3], [2, 3]] the return value would be [1, 3] as 1 and 3 are the most common objects
at the first and second positions respectively.
:param all_vote... | [
"For",
"the",
"given",
"iterable",
"of",
"object",
"iterations",
"return",
"an",
"iterable",
"of",
"the",
"most",
"common",
"object",
"at",
"each",
"position",
"of",
"the",
"inner",
"iterations",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/models/ensemble.py#L17-L28 | train |
Cognexa/cxflow | cxflow/models/ensemble.py | Ensemble._load_models | def _load_models(self) -> None:
"""Maybe load all the models to be assembled together and save them to the ``self._models`` attribute."""
if self._models is None:
logging.info('Loading %d models', len(self._model_paths))
def load_model(model_path: str):
logging.d... | python | def _load_models(self) -> None:
"""Maybe load all the models to be assembled together and save them to the ``self._models`` attribute."""
if self._models is None:
logging.info('Loading %d models', len(self._model_paths))
def load_model(model_path: str):
logging.d... | [
"def",
"_load_models",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_models",
"is",
"None",
":",
"logging",
".",
"info",
"(",
"'Loading %d models'",
",",
"len",
"(",
"self",
".",
"_model_paths",
")",
")",
"def",
"load_model",
"(",
"model_path... | Maybe load all the models to be assembled together and save them to the ``self._models`` attribute. | [
"Maybe",
"load",
"all",
"the",
"models",
"to",
"be",
"assembled",
"together",
"and",
"save",
"them",
"to",
"the",
"self",
".",
"_models",
"attribute",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/models/ensemble.py#L113-L129 | train |
Cognexa/cxflow | cxflow/models/ensemble.py | Ensemble.run | def run(self, batch: Batch, train: bool=False, stream: StreamWrapper=None) -> Batch:
"""
Run feed-forward pass with the given batch using all the models, aggregate and return the results.
.. warning::
:py:class:`Ensemble` can not be trained.
:param batch: batch to be proces... | python | def run(self, batch: Batch, train: bool=False, stream: StreamWrapper=None) -> Batch:
"""
Run feed-forward pass with the given batch using all the models, aggregate and return the results.
.. warning::
:py:class:`Ensemble` can not be trained.
:param batch: batch to be proces... | [
"def",
"run",
"(",
"self",
",",
"batch",
":",
"Batch",
",",
"train",
":",
"bool",
"=",
"False",
",",
"stream",
":",
"StreamWrapper",
"=",
"None",
")",
"->",
"Batch",
":",
"if",
"train",
":",
"raise",
"ValueError",
"(",
"'Ensemble model cannot be trained.'"... | Run feed-forward pass with the given batch using all the models, aggregate and return the results.
.. warning::
:py:class:`Ensemble` can not be trained.
:param batch: batch to be processed
:param train: ``True`` if this batch should be used for model update, ``False`` otherwise
... | [
"Run",
"feed",
"-",
"forward",
"pass",
"with",
"the",
"given",
"batch",
"using",
"all",
"the",
"models",
"aggregate",
"and",
"return",
"the",
"results",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/models/ensemble.py#L141-L172 | train |
Cognexa/cxflow | cxflow/utils/reflection.py | get_attribute | def get_attribute(module_name: str, attribute_name: str):
"""
Get the specified module attribute. It most cases, it will be a class or function.
:param module_name: module name
:param attribute_name: attribute name
:return: module attribute
"""
assert isinstance(module_name, str)
assert... | python | def get_attribute(module_name: str, attribute_name: str):
"""
Get the specified module attribute. It most cases, it will be a class or function.
:param module_name: module name
:param attribute_name: attribute name
:return: module attribute
"""
assert isinstance(module_name, str)
assert... | [
"def",
"get_attribute",
"(",
"module_name",
":",
"str",
",",
"attribute_name",
":",
"str",
")",
":",
"assert",
"isinstance",
"(",
"module_name",
",",
"str",
")",
"assert",
"isinstance",
"(",
"attribute_name",
",",
"str",
")",
"_module",
"=",
"importlib",
"."... | Get the specified module attribute. It most cases, it will be a class or function.
:param module_name: module name
:param attribute_name: attribute name
:return: module attribute | [
"Get",
"the",
"specified",
"module",
"attribute",
".",
"It",
"most",
"cases",
"it",
"will",
"be",
"a",
"class",
"or",
"function",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/reflection.py#L28-L40 | train |
Cognexa/cxflow | cxflow/utils/reflection.py | create_object | def create_object(module_name: str, class_name: str, args: Iterable=(), kwargs: Dict[str, Any]=_EMPTY_DICT):
"""
Create an object instance of the given class from the given module.
Args and kwargs are passed to the constructor.
This mimics the following code:
.. code-block:: python
from m... | python | def create_object(module_name: str, class_name: str, args: Iterable=(), kwargs: Dict[str, Any]=_EMPTY_DICT):
"""
Create an object instance of the given class from the given module.
Args and kwargs are passed to the constructor.
This mimics the following code:
.. code-block:: python
from m... | [
"def",
"create_object",
"(",
"module_name",
":",
"str",
",",
"class_name",
":",
"str",
",",
"args",
":",
"Iterable",
"=",
"(",
")",
",",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"_EMPTY_DICT",
")",
":",
"return",
"get_attribute",
"(",
... | Create an object instance of the given class from the given module.
Args and kwargs are passed to the constructor.
This mimics the following code:
.. code-block:: python
from module import class
return class(*args, **kwargs)
:param module_name: module name
:param class_name: clas... | [
"Create",
"an",
"object",
"instance",
"of",
"the",
"given",
"class",
"from",
"the",
"given",
"module",
".",
"Args",
"and",
"kwargs",
"are",
"passed",
"to",
"the",
"constructor",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/reflection.py#L43-L61 | train |
Cognexa/cxflow | cxflow/utils/reflection.py | list_submodules | def list_submodules(module_name: str) -> List[str]: # pylint: disable=invalid-sequence-index
"""
List full names of all the submodules in the given module.
:param module_name: name of the module of which the submodules will be listed
"""
_module = importlib.import_module(module_name)
return [... | python | def list_submodules(module_name: str) -> List[str]: # pylint: disable=invalid-sequence-index
"""
List full names of all the submodules in the given module.
:param module_name: name of the module of which the submodules will be listed
"""
_module = importlib.import_module(module_name)
return [... | [
"def",
"list_submodules",
"(",
"module_name",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"_module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"return",
"[",
"module_name",
"+",
"'.'",
"+",
"submodule_name",
"for",
"_",
",",... | List full names of all the submodules in the given module.
:param module_name: name of the module of which the submodules will be listed | [
"List",
"full",
"names",
"of",
"all",
"the",
"submodules",
"in",
"the",
"given",
"module",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/reflection.py#L64-L71 | train |
Cognexa/cxflow | cxflow/utils/reflection.py | find_class_module | def find_class_module(module_name: str, class_name: str) \
-> Tuple[List[str], List[Tuple[str, Exception]]]: # pylint: disable=invalid-sequence-index
"""
Find sub-modules of the given module that contain the given class.
Moreover, return a list of sub-modules that could not be imported as a list ... | python | def find_class_module(module_name: str, class_name: str) \
-> Tuple[List[str], List[Tuple[str, Exception]]]: # pylint: disable=invalid-sequence-index
"""
Find sub-modules of the given module that contain the given class.
Moreover, return a list of sub-modules that could not be imported as a list ... | [
"def",
"find_class_module",
"(",
"module_name",
":",
"str",
",",
"class_name",
":",
"str",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"List",
"[",
"Tuple",
"[",
"str",
",",
"Exception",
"]",
"]",
"]",
":",
"matched_submodules",
"=",
"[",
... | Find sub-modules of the given module that contain the given class.
Moreover, return a list of sub-modules that could not be imported as a list of (sub-module name, Exception) tuples.
:param module_name: name of the module to be searched
:param class_name: searched class name
:return: a tuple of sub-mo... | [
"Find",
"sub",
"-",
"modules",
"of",
"the",
"given",
"module",
"that",
"contain",
"the",
"given",
"class",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/reflection.py#L74-L94 | train |
Cognexa/cxflow | cxflow/utils/reflection.py | get_class_module | def get_class_module(module_name: str, class_name: str) -> Optional[str]:
"""
Get a sub-module of the given module which has the given class.
This method wraps `utils.reflection.find_class_module method` with the following behavior:
- raise error when multiple sub-modules with different classes with t... | python | def get_class_module(module_name: str, class_name: str) -> Optional[str]:
"""
Get a sub-module of the given module which has the given class.
This method wraps `utils.reflection.find_class_module method` with the following behavior:
- raise error when multiple sub-modules with different classes with t... | [
"def",
"get_class_module",
"(",
"module_name",
":",
"str",
",",
"class_name",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"matched_modules",
",",
"erroneous_modules",
"=",
"find_class_module",
"(",
"module_name",
",",
"class_name",
")",
"for",
"su... | Get a sub-module of the given module which has the given class.
This method wraps `utils.reflection.find_class_module method` with the following behavior:
- raise error when multiple sub-modules with different classes with the same name are found
- return None when no sub-module is found
- warn about ... | [
"Get",
"a",
"sub",
"-",
"module",
"of",
"the",
"given",
"module",
"which",
"has",
"the",
"given",
"class",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/reflection.py#L97-L133 | train |
Cognexa/cxflow | cxflow/datasets/stream_wrapper.py | StreamWrapper._get_stream | def _get_stream(self) -> Iterator:
"""Possibly create and return raw dataset stream iterator."""
if self._stream is None:
self._stream = iter(self._get_stream_fn())
return self._stream | python | def _get_stream(self) -> Iterator:
"""Possibly create and return raw dataset stream iterator."""
if self._stream is None:
self._stream = iter(self._get_stream_fn())
return self._stream | [
"def",
"_get_stream",
"(",
"self",
")",
"->",
"Iterator",
":",
"if",
"self",
".",
"_stream",
"is",
"None",
":",
"self",
".",
"_stream",
"=",
"iter",
"(",
"self",
".",
"_get_stream_fn",
"(",
")",
")",
"return",
"self",
".",
"_stream"
] | Possibly create and return raw dataset stream iterator. | [
"Possibly",
"create",
"and",
"return",
"raw",
"dataset",
"stream",
"iterator",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/stream_wrapper.py#L78-L82 | train |
Cognexa/cxflow | cxflow/datasets/stream_wrapper.py | StreamWrapper._enqueue_batches | def _enqueue_batches(self, stop_event: Event) -> None:
"""
Enqueue all the stream batches. If specified, stop after ``epoch_size`` batches.
.. note::
Signal the epoch end with ``None``.
Stop when:
- ``stop_event`` is risen
- stream ends and epoch size is not... | python | def _enqueue_batches(self, stop_event: Event) -> None:
"""
Enqueue all the stream batches. If specified, stop after ``epoch_size`` batches.
.. note::
Signal the epoch end with ``None``.
Stop when:
- ``stop_event`` is risen
- stream ends and epoch size is not... | [
"def",
"_enqueue_batches",
"(",
"self",
",",
"stop_event",
":",
"Event",
")",
"->",
"None",
":",
"while",
"True",
":",
"self",
".",
"_stream",
"=",
"self",
".",
"_get_stream",
"(",
")",
"while",
"True",
":",
"with",
"self",
".",
"_semaphore",
":",
"pas... | Enqueue all the stream batches. If specified, stop after ``epoch_size`` batches.
.. note::
Signal the epoch end with ``None``.
Stop when:
- ``stop_event`` is risen
- stream ends and epoch size is not set
- specified number of batches is enqueued
.. note::
... | [
"Enqueue",
"all",
"the",
"stream",
"batches",
".",
"If",
"specified",
"stop",
"after",
"epoch_size",
"batches",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/stream_wrapper.py#L92-L138 | train |
Cognexa/cxflow | cxflow/datasets/stream_wrapper.py | StreamWrapper._dequeue_batch | def _dequeue_batch(self) -> Optional[Batch]:
"""
Return a single batch from queue or ``None`` signaling epoch end.
:raise ChildProcessError: if the enqueueing thread ended unexpectedly
"""
if self._enqueueing_thread is None:
raise ValueError('StreamWrapper `{}` with ... | python | def _dequeue_batch(self) -> Optional[Batch]:
"""
Return a single batch from queue or ``None`` signaling epoch end.
:raise ChildProcessError: if the enqueueing thread ended unexpectedly
"""
if self._enqueueing_thread is None:
raise ValueError('StreamWrapper `{}` with ... | [
"def",
"_dequeue_batch",
"(",
"self",
")",
"->",
"Optional",
"[",
"Batch",
"]",
":",
"if",
"self",
".",
"_enqueueing_thread",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'StreamWrapper `{}` with buffer of size `{}` was used outside with-resource environment.'",
".",
... | Return a single batch from queue or ``None`` signaling epoch end.
:raise ChildProcessError: if the enqueueing thread ended unexpectedly | [
"Return",
"a",
"single",
"batch",
"from",
"queue",
"or",
"None",
"signaling",
"epoch",
"end",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/stream_wrapper.py#L140-L167 | train |
Cognexa/cxflow | cxflow/datasets/stream_wrapper.py | StreamWrapper._next_batch | def _next_batch(self) -> Optional[Batch]:
"""
Return a single batch or ``None`` signaling epoch end.
.. note::
Signal the epoch end with ``None``.
Stop when:
- stream ends and epoch size is not set
- specified number of batches is returned
:return: ... | python | def _next_batch(self) -> Optional[Batch]:
"""
Return a single batch or ``None`` signaling epoch end.
.. note::
Signal the epoch end with ``None``.
Stop when:
- stream ends and epoch size is not set
- specified number of batches is returned
:return: ... | [
"def",
"_next_batch",
"(",
"self",
")",
"->",
"Optional",
"[",
"Batch",
"]",
":",
"if",
"self",
".",
"_epoch_limit_reached",
"(",
")",
":",
"self",
".",
"_batch_count",
"=",
"0",
"return",
"None",
"try",
":",
"batch",
"=",
"next",
"(",
"self",
".",
"... | Return a single batch or ``None`` signaling epoch end.
.. note::
Signal the epoch end with ``None``.
Stop when:
- stream ends and epoch size is not set
- specified number of batches is returned
:return: a single batch or ``None`` signaling epoch end | [
"Return",
"a",
"single",
"batch",
"or",
"None",
"signaling",
"epoch",
"end",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/stream_wrapper.py#L169-L197 | train |
Cognexa/cxflow | cxflow/datasets/stream_wrapper.py | StreamWrapper._start_thread | def _start_thread(self):
"""Start an enqueueing thread."""
self._stopping_event = Event()
self._enqueueing_thread = Thread(target=self._enqueue_batches, args=(self._stopping_event,))
self._enqueueing_thread.start() | python | def _start_thread(self):
"""Start an enqueueing thread."""
self._stopping_event = Event()
self._enqueueing_thread = Thread(target=self._enqueue_batches, args=(self._stopping_event,))
self._enqueueing_thread.start() | [
"def",
"_start_thread",
"(",
"self",
")",
":",
"self",
".",
"_stopping_event",
"=",
"Event",
"(",
")",
"self",
".",
"_enqueueing_thread",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"_enqueue_batches",
",",
"args",
"=",
"(",
"self",
".",
"_stopping_eve... | Start an enqueueing thread. | [
"Start",
"an",
"enqueueing",
"thread",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/stream_wrapper.py#L199-L203 | train |
Cognexa/cxflow | cxflow/datasets/stream_wrapper.py | StreamWrapper._stop_thread | def _stop_thread(self):
"""Stop the enqueueing thread. Keep the queue content and stream state."""
self._stopping_event.set()
queue_content = []
try: # give the enqueueing thread chance to put a batch to the queue and check the stopping event
while True:
queu... | python | def _stop_thread(self):
"""Stop the enqueueing thread. Keep the queue content and stream state."""
self._stopping_event.set()
queue_content = []
try: # give the enqueueing thread chance to put a batch to the queue and check the stopping event
while True:
queu... | [
"def",
"_stop_thread",
"(",
"self",
")",
":",
"self",
".",
"_stopping_event",
".",
"set",
"(",
")",
"queue_content",
"=",
"[",
"]",
"try",
":",
"while",
"True",
":",
"queue_content",
".",
"append",
"(",
"self",
".",
"_queue",
".",
"get_nowait",
"(",
")... | Stop the enqueueing thread. Keep the queue content and stream state. | [
"Stop",
"the",
"enqueueing",
"thread",
".",
"Keep",
"the",
"queue",
"content",
"and",
"stream",
"state",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/stream_wrapper.py#L205-L221 | train |
Cognexa/cxflow | cxflow/hooks/save.py | SaveEvery._after_n_epoch | def _after_n_epoch(self, epoch_id: int, **_) -> None:
"""
Save the model every ``n_epochs`` epoch.
:param epoch_id: number of the processed epoch
"""
SaveEvery.save_model(model=self._model, name_suffix=str(epoch_id), on_failure=self._on_save_failure) | python | def _after_n_epoch(self, epoch_id: int, **_) -> None:
"""
Save the model every ``n_epochs`` epoch.
:param epoch_id: number of the processed epoch
"""
SaveEvery.save_model(model=self._model, name_suffix=str(epoch_id), on_failure=self._on_save_failure) | [
"def",
"_after_n_epoch",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"**",
"_",
")",
"->",
"None",
":",
"SaveEvery",
".",
"save_model",
"(",
"model",
"=",
"self",
".",
"_model",
",",
"name_suffix",
"=",
"str",
"(",
"epoch_id",
")",
",",
"on_failure"... | Save the model every ``n_epochs`` epoch.
:param epoch_id: number of the processed epoch | [
"Save",
"the",
"model",
"every",
"n_epochs",
"epoch",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/save.py#L47-L53 | train |
Cognexa/cxflow | cxflow/hooks/save.py | SaveEvery.save_model | def save_model(model: AbstractModel, name_suffix: str, on_failure: str) -> None:
"""
Save the given model with the given name_suffix. On failure, take the specified action.
:param model: the model to be saved
:param name_suffix: name to be used for saving
:param on_failure: acti... | python | def save_model(model: AbstractModel, name_suffix: str, on_failure: str) -> None:
"""
Save the given model with the given name_suffix. On failure, take the specified action.
:param model: the model to be saved
:param name_suffix: name to be used for saving
:param on_failure: acti... | [
"def",
"save_model",
"(",
"model",
":",
"AbstractModel",
",",
"name_suffix",
":",
"str",
",",
"on_failure",
":",
"str",
")",
"->",
"None",
":",
"try",
":",
"logging",
".",
"debug",
"(",
"'Saving the model'",
")",
"save_path",
"=",
"model",
".",
"save",
"... | Save the given model with the given name_suffix. On failure, take the specified action.
:param model: the model to be saved
:param name_suffix: name to be used for saving
:param on_failure: action to be taken on failure; one of :py:attr:`SAVE_FAILURE_ACTIONS`
:raise IOError: on save fai... | [
"Save",
"the",
"given",
"model",
"with",
"the",
"given",
"name_suffix",
".",
"On",
"failure",
"take",
"the",
"specified",
"action",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/save.py#L56-L73 | train |
Cognexa/cxflow | cxflow/hooks/save.py | SaveBest._get_value | def _get_value(self, epoch_data: EpochData) -> float:
"""
Retrieve the value of the monitored variable from the given epoch data.
:param epoch_data: epoch data which determine whether the model will be saved or not
:raise KeyError: if any of the specified stream, variable or aggregation... | python | def _get_value(self, epoch_data: EpochData) -> float:
"""
Retrieve the value of the monitored variable from the given epoch data.
:param epoch_data: epoch data which determine whether the model will be saved or not
:raise KeyError: if any of the specified stream, variable or aggregation... | [
"def",
"_get_value",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
")",
"->",
"float",
":",
"if",
"self",
".",
"_stream_name",
"not",
"in",
"epoch_data",
":",
"raise",
"KeyError",
"(",
"'Stream `{}` was not found in the epoch data.\\nAvailable streams are `{}`.'",
... | Retrieve the value of the monitored variable from the given epoch data.
:param epoch_data: epoch data which determine whether the model will be saved or not
:raise KeyError: if any of the specified stream, variable or aggregation is not present in the ``epoch_data``
:raise TypeError: if the var... | [
"Retrieve",
"the",
"value",
"of",
"the",
"monitored",
"variable",
"from",
"the",
"given",
"epoch",
"data",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/save.py#L129-L160 | train |
Cognexa/cxflow | cxflow/hooks/save.py | SaveBest._is_value_better | def _is_value_better(self, new_value: float) -> bool:
"""
Test if the new value is better than the best so far.
:param new_value: current value of the objective function
"""
if self._best_value is None:
return True
if self._condition == 'min':
ret... | python | def _is_value_better(self, new_value: float) -> bool:
"""
Test if the new value is better than the best so far.
:param new_value: current value of the objective function
"""
if self._best_value is None:
return True
if self._condition == 'min':
ret... | [
"def",
"_is_value_better",
"(",
"self",
",",
"new_value",
":",
"float",
")",
"->",
"bool",
":",
"if",
"self",
".",
"_best_value",
"is",
"None",
":",
"return",
"True",
"if",
"self",
".",
"_condition",
"==",
"'min'",
":",
"return",
"new_value",
"<",
"self"... | Test if the new value is better than the best so far.
:param new_value: current value of the objective function | [
"Test",
"if",
"the",
"new",
"value",
"is",
"better",
"than",
"the",
"best",
"so",
"far",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/save.py#L162-L173 | train |
Cognexa/cxflow | cxflow/hooks/save.py | SaveBest.after_epoch | def after_epoch(self, epoch_data: EpochData, **_) -> None:
"""
Save the model if the new value of the monitored variable is better than the best value so far.
:param epoch_data: epoch data to be processed
"""
new_value = self._get_value(epoch_data)
if self._is_value_bet... | python | def after_epoch(self, epoch_data: EpochData, **_) -> None:
"""
Save the model if the new value of the monitored variable is better than the best value so far.
:param epoch_data: epoch data to be processed
"""
new_value = self._get_value(epoch_data)
if self._is_value_bet... | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
",",
"**",
"_",
")",
"->",
"None",
":",
"new_value",
"=",
"self",
".",
"_get_value",
"(",
"epoch_data",
")",
"if",
"self",
".",
"_is_value_better",
"(",
"new_value",
")",
":",
"self"... | Save the model if the new value of the monitored variable is better than the best value so far.
:param epoch_data: epoch data to be processed | [
"Save",
"the",
"model",
"if",
"the",
"new",
"value",
"of",
"the",
"monitored",
"variable",
"is",
"better",
"than",
"the",
"best",
"value",
"so",
"far",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/save.py#L175-L185 | train |
Cognexa/cxflow | cxflow/hooks/show_progress.py | print_progress_bar | def print_progress_bar(done: int, total: int, prefix: str = '', suffix: str = '') -> None:
"""
Print a progressbar with the given prefix and suffix, without newline at the end.
param done: current step in computation
param total: total count of steps in computation
param prefix: info text displayed... | python | def print_progress_bar(done: int, total: int, prefix: str = '', suffix: str = '') -> None:
"""
Print a progressbar with the given prefix and suffix, without newline at the end.
param done: current step in computation
param total: total count of steps in computation
param prefix: info text displayed... | [
"def",
"print_progress_bar",
"(",
"done",
":",
"int",
",",
"total",
":",
"int",
",",
"prefix",
":",
"str",
"=",
"''",
",",
"suffix",
":",
"str",
"=",
"''",
")",
"->",
"None",
":",
"percent",
"=",
"'{0:.1f}'",
".",
"format",
"(",
"100",
"*",
"(",
... | Print a progressbar with the given prefix and suffix, without newline at the end.
param done: current step in computation
param total: total count of steps in computation
param prefix: info text displayed before the progress bar
param suffix: info text displayed after the progress bar | [
"Print",
"a",
"progressbar",
"with",
"the",
"given",
"prefix",
"and",
"suffix",
"without",
"newline",
"at",
"the",
"end",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/show_progress.py#L14-L39 | train |
Cognexa/cxflow | cxflow/hooks/show_progress.py | ShowProgress.after_epoch | def after_epoch(self, **_) -> None:
"""
Reset progress counters. Save ``total_batch_count`` after the 1st epoch.
"""
if not self._total_batch_count_saved:
self._total_batch_count = self._current_batch_count.copy()
self._total_batch_count_saved = True
self.... | python | def after_epoch(self, **_) -> None:
"""
Reset progress counters. Save ``total_batch_count`` after the 1st epoch.
"""
if not self._total_batch_count_saved:
self._total_batch_count = self._current_batch_count.copy()
self._total_batch_count_saved = True
self.... | [
"def",
"after_epoch",
"(",
"self",
",",
"**",
"_",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"_total_batch_count_saved",
":",
"self",
".",
"_total_batch_count",
"=",
"self",
".",
"_current_batch_count",
".",
"copy",
"(",
")",
"self",
".",
"_total_b... | Reset progress counters. Save ``total_batch_count`` after the 1st epoch. | [
"Reset",
"progress",
"counters",
".",
"Save",
"total_batch_count",
"after",
"the",
"1st",
"epoch",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/show_progress.py#L134-L144 | train |
Cognexa/cxflow | cxflow/hooks/log_profile.py | LogProfile.after_epoch_profile | def after_epoch_profile(self, epoch_id, profile: TimeProfile, train_stream_name: str, extra_streams: Iterable[str]) -> None:
"""
Summarize and log the given epoch profile.
The profile is expected to contain at least:
- ``read_data_train``, ``eval_batch_train`` and ``after_batch_hook... | python | def after_epoch_profile(self, epoch_id, profile: TimeProfile, train_stream_name: str, extra_streams: Iterable[str]) -> None:
"""
Summarize and log the given epoch profile.
The profile is expected to contain at least:
- ``read_data_train``, ``eval_batch_train`` and ``after_batch_hook... | [
"def",
"after_epoch_profile",
"(",
"self",
",",
"epoch_id",
",",
"profile",
":",
"TimeProfile",
",",
"train_stream_name",
":",
"str",
",",
"extra_streams",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"read_data_total",
"=",
"0",
"eval_total",
"... | Summarize and log the given epoch profile.
The profile is expected to contain at least:
- ``read_data_train``, ``eval_batch_train`` and ``after_batch_hooks_train`` entries produced by the train
stream (if train stream name is `train`)
- ``after_epoch_hooks`` entry
... | [
"Summarize",
"and",
"log",
"the",
"given",
"epoch",
"profile",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/log_profile.py#L27-L54 | train |
Cognexa/cxflow | cxflow/utils/confusion_matrix.py | confusion_matrix | def confusion_matrix(expected: np.ndarray, predicted: np.ndarray, num_classes: int) -> np.ndarray:
"""
Calculate and return confusion matrix for the predicted and expected labels
:param expected: array of expected classes (integers) with shape `[num_of_data]`
:param predicted: array of predicted classe... | python | def confusion_matrix(expected: np.ndarray, predicted: np.ndarray, num_classes: int) -> np.ndarray:
"""
Calculate and return confusion matrix for the predicted and expected labels
:param expected: array of expected classes (integers) with shape `[num_of_data]`
:param predicted: array of predicted classe... | [
"def",
"confusion_matrix",
"(",
"expected",
":",
"np",
".",
"ndarray",
",",
"predicted",
":",
"np",
".",
"ndarray",
",",
"num_classes",
":",
"int",
")",
"->",
"np",
".",
"ndarray",
":",
"assert",
"np",
".",
"issubclass_",
"(",
"expected",
".",
"dtype",
... | Calculate and return confusion matrix for the predicted and expected labels
:param expected: array of expected classes (integers) with shape `[num_of_data]`
:param predicted: array of predicted classes (integers) with shape `[num_of_data]`
:param num_classes: number of classification classes
:return: c... | [
"Calculate",
"and",
"return",
"confusion",
"matrix",
"for",
"the",
"predicted",
"and",
"expected",
"labels"
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/confusion_matrix.py#L4-L22 | train |
Cognexa/cxflow | cxflow/cli/grid_search.py | _build_grid_search_commands | def _build_grid_search_commands(script: str, params: typing.Iterable[str]) -> typing.Iterable[typing.List[str]]:
"""
Build all grid search parameter configurations.
:param script: String of command prefix, e.g. ``cxflow train -v -o log``.
:param params: Iterable collection of strings in standard **cxfl... | python | def _build_grid_search_commands(script: str, params: typing.Iterable[str]) -> typing.Iterable[typing.List[str]]:
"""
Build all grid search parameter configurations.
:param script: String of command prefix, e.g. ``cxflow train -v -o log``.
:param params: Iterable collection of strings in standard **cxfl... | [
"def",
"_build_grid_search_commands",
"(",
"script",
":",
"str",
",",
"params",
":",
"typing",
".",
"Iterable",
"[",
"str",
"]",
")",
"->",
"typing",
".",
"Iterable",
"[",
"typing",
".",
"List",
"[",
"str",
"]",
"]",
":",
"param_space",
"=",
"OrderedDict... | Build all grid search parameter configurations.
:param script: String of command prefix, e.g. ``cxflow train -v -o log``.
:param params: Iterable collection of strings in standard **cxflow** param form, e.g. ``'numerical_param=[1, 2]'``
or ``'text_param=["hello", "cio"]'``. | [
"Build",
"all",
"grid",
"search",
"parameter",
"configurations",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/grid_search.py#L13-L41 | train |
Cognexa/cxflow | cxflow/cli/grid_search.py | grid_search | def grid_search(script: str, params: typing.Iterable[str], dry_run: bool=False) -> None:
"""
Build all grid search parameter configurations and optionally run them.
:param script: String of command prefix, e.g. ``cxflow train -v -o log``.
:param params: Iterable collection of strings in standard **cxfl... | python | def grid_search(script: str, params: typing.Iterable[str], dry_run: bool=False) -> None:
"""
Build all grid search parameter configurations and optionally run them.
:param script: String of command prefix, e.g. ``cxflow train -v -o log``.
:param params: Iterable collection of strings in standard **cxfl... | [
"def",
"grid_search",
"(",
"script",
":",
"str",
",",
"params",
":",
"typing",
".",
"Iterable",
"[",
"str",
"]",
",",
"dry_run",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"commands",
"=",
"_build_grid_search_commands",
"(",
"script",
"=",
"scrip... | Build all grid search parameter configurations and optionally run them.
:param script: String of command prefix, e.g. ``cxflow train -v -o log``.
:param params: Iterable collection of strings in standard **cxflow** param form, e.g. ``'numerical_param=[1, 2]'``
or ``'text_param=["hello", "cio... | [
"Build",
"all",
"grid",
"search",
"parameter",
"configurations",
"and",
"optionally",
"run",
"them",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/grid_search.py#L44-L66 | train |
Cognexa/cxflow | cxflow/datasets/base_dataset.py | BaseDataset.stream_info | def stream_info(self) -> None:
"""Check and report source names, dtypes and shapes of all the streams available."""
stream_names = [stream_name for stream_name in dir(self)
if 'stream' in stream_name and stream_name != 'stream_info']
logging.info('Found %s stream candidat... | python | def stream_info(self) -> None:
"""Check and report source names, dtypes and shapes of all the streams available."""
stream_names = [stream_name for stream_name in dir(self)
if 'stream' in stream_name and stream_name != 'stream_info']
logging.info('Found %s stream candidat... | [
"def",
"stream_info",
"(",
"self",
")",
"->",
"None",
":",
"stream_names",
"=",
"[",
"stream_name",
"for",
"stream_name",
"in",
"dir",
"(",
"self",
")",
"if",
"'stream'",
"in",
"stream_name",
"and",
"stream_name",
"!=",
"'stream_info'",
"]",
"logging",
".",
... | Check and report source names, dtypes and shapes of all the streams available. | [
"Check",
"and",
"report",
"source",
"names",
"dtypes",
"and",
"shapes",
"of",
"all",
"the",
"streams",
"available",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/base_dataset.py#L52-L86 | train |
Cognexa/cxflow | cxflow/cli/util.py | find_config | def find_config(config_path: str) -> str:
"""
Derive configuration file path from the given path and check its existence.
The given path is expected to be either
1. path to the file
2. path to a dir, in such case the path is joined with ``CXF_CONFIG_FILE``
:param config_path: path to the conf... | python | def find_config(config_path: str) -> str:
"""
Derive configuration file path from the given path and check its existence.
The given path is expected to be either
1. path to the file
2. path to a dir, in such case the path is joined with ``CXF_CONFIG_FILE``
:param config_path: path to the conf... | [
"def",
"find_config",
"(",
"config_path",
":",
"str",
")",
"->",
"str",
":",
"if",
"path",
".",
"isdir",
"(",
"config_path",
")",
":",
"config_path",
"=",
"path",
".",
"join",
"(",
"config_path",
",",
"CXF_CONFIG_FILE",
")",
"assert",
"path",
".",
"exist... | Derive configuration file path from the given path and check its existence.
The given path is expected to be either
1. path to the file
2. path to a dir, in such case the path is joined with ``CXF_CONFIG_FILE``
:param config_path: path to the configuration file or its parent directory
:return: va... | [
"Derive",
"configuration",
"file",
"path",
"from",
"the",
"given",
"path",
"and",
"check",
"its",
"existence",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/util.py#L8-L23 | train |
Cognexa/cxflow | cxflow/cli/util.py | fallback | def fallback(message: str, ex: Exception) -> None:
"""
Fallback procedure when a cli command fails.
:param message: message to be logged
:param ex: Exception which caused the failure
"""
logging.error('%s', message)
logging.exception('%s', ex)
sys.exit(1) | python | def fallback(message: str, ex: Exception) -> None:
"""
Fallback procedure when a cli command fails.
:param message: message to be logged
:param ex: Exception which caused the failure
"""
logging.error('%s', message)
logging.exception('%s', ex)
sys.exit(1) | [
"def",
"fallback",
"(",
"message",
":",
"str",
",",
"ex",
":",
"Exception",
")",
"->",
"None",
":",
"logging",
".",
"error",
"(",
"'%s'",
",",
"message",
")",
"logging",
".",
"exception",
"(",
"'%s'",
",",
"ex",
")",
"sys",
".",
"exit",
"(",
"1",
... | Fallback procedure when a cli command fails.
:param message: message to be logged
:param ex: Exception which caused the failure | [
"Fallback",
"procedure",
"when",
"a",
"cli",
"command",
"fails",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/util.py#L40-L49 | train |
Cognexa/cxflow | cxflow/datasets/downloadable_dataset.py | DownloadableDataset._configure_dataset | def _configure_dataset(self, data_root: str=None, download_urls: Iterable[str]=None, **kwargs) -> None:
"""
Save the passed values and use them as a default property implementation.
:param data_root: directory to which the files will be downloaded
:param download_urls: list of URLs to b... | python | def _configure_dataset(self, data_root: str=None, download_urls: Iterable[str]=None, **kwargs) -> None:
"""
Save the passed values and use them as a default property implementation.
:param data_root: directory to which the files will be downloaded
:param download_urls: list of URLs to b... | [
"def",
"_configure_dataset",
"(",
"self",
",",
"data_root",
":",
"str",
"=",
"None",
",",
"download_urls",
":",
"Iterable",
"[",
"str",
"]",
"=",
"None",
",",
"**",
"kwargs",
")",
"->",
"None",
":",
"self",
".",
"_data_root",
"=",
"data_root",
"self",
... | Save the passed values and use them as a default property implementation.
:param data_root: directory to which the files will be downloaded
:param download_urls: list of URLs to be downloaded | [
"Save",
"the",
"passed",
"values",
"and",
"use",
"them",
"as",
"a",
"default",
"property",
"implementation",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/downloadable_dataset.py#L23-L31 | train |
Cognexa/cxflow | cxflow/cli/resume.py | resume | def resume(config_path: str, restore_from: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None:
"""
Load config from the directory specified and start the training.
:param config_path: path to the config file or the directory in which it is stored
:param restore_from: backend-specific... | python | def resume(config_path: str, restore_from: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None:
"""
Load config from the directory specified and start the training.
:param config_path: path to the config file or the directory in which it is stored
:param restore_from: backend-specific... | [
"def",
"resume",
"(",
"config_path",
":",
"str",
",",
"restore_from",
":",
"Optional",
"[",
"str",
"]",
",",
"cl_arguments",
":",
"Iterable",
"[",
"str",
"]",
",",
"output_root",
":",
"str",
")",
"->",
"None",
":",
"config",
"=",
"None",
"try",
":",
... | Load config from the directory specified and start the training.
:param config_path: path to the config file or the directory in which it is stored
:param restore_from: backend-specific path to the already trained model to be restored from.
If ``None`` is passed, it is inferred from th... | [
"Load",
"config",
"from",
"the",
"directory",
"specified",
"and",
"start",
"the",
"training",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/resume.py#L11-L35 | train |
Cognexa/cxflow | cxflow/hooks/abstract_hook.py | AbstractHook.after_epoch_profile | def after_epoch_profile(self, epoch_id: int, profile: TimeProfile, train_stream_name: str, extra_streams: Iterable[str]) -> None:
"""
After epoch profile event.
This event provides opportunity to process time profile of the finished epoch.
:param epoch_id: finished epoch id
:pa... | python | def after_epoch_profile(self, epoch_id: int, profile: TimeProfile, train_stream_name: str, extra_streams: Iterable[str]) -> None:
"""
After epoch profile event.
This event provides opportunity to process time profile of the finished epoch.
:param epoch_id: finished epoch id
:pa... | [
"def",
"after_epoch_profile",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"profile",
":",
"TimeProfile",
",",
"train_stream_name",
":",
"str",
",",
"extra_streams",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"pass"
] | After epoch profile event.
This event provides opportunity to process time profile of the finished epoch.
:param epoch_id: finished epoch id
:param profile: dictionary of lists of event timings that were measured during the epoch
:param extra_streams: enumeration of additional stream n... | [
"After",
"epoch",
"profile",
"event",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/abstract_hook.py#L84-L94 | train |
Cognexa/cxflow | cxflow/utils/yaml.py | load_yaml | def load_yaml(yaml_file: str) -> Any:
"""
Load YAML from file.
:param yaml_file: path to YAML file
:return: content of the YAML as dict/list
"""
with open(yaml_file, 'r') as file:
return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader) | python | def load_yaml(yaml_file: str) -> Any:
"""
Load YAML from file.
:param yaml_file: path to YAML file
:return: content of the YAML as dict/list
"""
with open(yaml_file, 'r') as file:
return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader) | [
"def",
"load_yaml",
"(",
"yaml_file",
":",
"str",
")",
"->",
"Any",
":",
"with",
"open",
"(",
"yaml_file",
",",
"'r'",
")",
"as",
"file",
":",
"return",
"ruamel",
".",
"yaml",
".",
"load",
"(",
"file",
",",
"ruamel",
".",
"yaml",
".",
"RoundTripLoade... | Load YAML from file.
:param yaml_file: path to YAML file
:return: content of the YAML as dict/list | [
"Load",
"YAML",
"from",
"file",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/yaml.py#L11-L19 | train |
Cognexa/cxflow | cxflow/utils/yaml.py | yaml_to_file | def yaml_to_file(data: Mapping, output_dir: str, name: str) -> str:
"""
Save the given object to the given path in YAML.
:param data: dict/list to be dumped
:param output_dir: target output directory
:param name: target filename
:return: target path
"""
dumped_config_f = path.join(outpu... | python | def yaml_to_file(data: Mapping, output_dir: str, name: str) -> str:
"""
Save the given object to the given path in YAML.
:param data: dict/list to be dumped
:param output_dir: target output directory
:param name: target filename
:return: target path
"""
dumped_config_f = path.join(outpu... | [
"def",
"yaml_to_file",
"(",
"data",
":",
"Mapping",
",",
"output_dir",
":",
"str",
",",
"name",
":",
"str",
")",
"->",
"str",
":",
"dumped_config_f",
"=",
"path",
".",
"join",
"(",
"output_dir",
",",
"name",
")",
"with",
"open",
"(",
"dumped_config_f",
... | Save the given object to the given path in YAML.
:param data: dict/list to be dumped
:param output_dir: target output directory
:param name: target filename
:return: target path | [
"Save",
"the",
"given",
"object",
"to",
"the",
"given",
"path",
"in",
"YAML",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/yaml.py#L22-L34 | train |
Cognexa/cxflow | cxflow/utils/yaml.py | yaml_to_str | def yaml_to_str(data: Mapping) -> str:
"""
Return the given given config as YAML str.
:param data: configuration dict
:return: given configuration as yaml str
"""
return yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper) | python | def yaml_to_str(data: Mapping) -> str:
"""
Return the given given config as YAML str.
:param data: configuration dict
:return: given configuration as yaml str
"""
return yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper) | [
"def",
"yaml_to_str",
"(",
"data",
":",
"Mapping",
")",
"->",
"str",
":",
"return",
"yaml",
".",
"dump",
"(",
"data",
",",
"Dumper",
"=",
"ruamel",
".",
"yaml",
".",
"RoundTripDumper",
")"
] | Return the given given config as YAML str.
:param data: configuration dict
:return: given configuration as yaml str | [
"Return",
"the",
"given",
"given",
"config",
"as",
"YAML",
"str",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/yaml.py#L37-L44 | train |
Cognexa/cxflow | cxflow/utils/yaml.py | reload | def reload(data: Any) -> Any:
"""
Dump and load yaml data.
This is useful to avoid many anchor parsing bugs. When you edit a yaml config, reload it to make sure
the changes are propagated to anchor expansions.
:param data: data to be reloaded
:return: reloaded data
"""
return yaml.load(... | python | def reload(data: Any) -> Any:
"""
Dump and load yaml data.
This is useful to avoid many anchor parsing bugs. When you edit a yaml config, reload it to make sure
the changes are propagated to anchor expansions.
:param data: data to be reloaded
:return: reloaded data
"""
return yaml.load(... | [
"def",
"reload",
"(",
"data",
":",
"Any",
")",
"->",
"Any",
":",
"return",
"yaml",
".",
"load",
"(",
"yaml",
".",
"dump",
"(",
"data",
",",
"Dumper",
"=",
"ruamel",
".",
"yaml",
".",
"RoundTripDumper",
")",
",",
"Loader",
"=",
"ruamel",
".",
"yaml"... | Dump and load yaml data.
This is useful to avoid many anchor parsing bugs. When you edit a yaml config, reload it to make sure
the changes are propagated to anchor expansions.
:param data: data to be reloaded
:return: reloaded data | [
"Dump",
"and",
"load",
"yaml",
"data",
".",
"This",
"is",
"useful",
"to",
"avoid",
"many",
"anchor",
"parsing",
"bugs",
".",
"When",
"you",
"edit",
"a",
"yaml",
"config",
"reload",
"it",
"to",
"make",
"sure",
"the",
"changes",
"are",
"propagated",
"to",
... | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/yaml.py#L58-L67 | train |
Cognexa/cxflow | cxflow/hooks/stop_on_nan.py | StopOnNaN._is_nan | def _is_nan(self, variable: str, data) -> bool:
"""
Recursively search passed data and find NaNs.
:param variable: name of variable to be checked
:param data: data object (dict, list, scalar)
:return: `True` if there is a NaN value in the data; `False` otherwise.
:raise ... | python | def _is_nan(self, variable: str, data) -> bool:
"""
Recursively search passed data and find NaNs.
:param variable: name of variable to be checked
:param data: data object (dict, list, scalar)
:return: `True` if there is a NaN value in the data; `False` otherwise.
:raise ... | [
"def",
"_is_nan",
"(",
"self",
",",
"variable",
":",
"str",
",",
"data",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"data",
",",
"np",
".",
"ndarray",
")",
"or",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"return",
"any",
"(",
"np",
... | Recursively search passed data and find NaNs.
:param variable: name of variable to be checked
:param data: data object (dict, list, scalar)
:return: `True` if there is a NaN value in the data; `False` otherwise.
:raise ValueError: if the variable value is of unsupported type and ``on_un... | [
"Recursively",
"search",
"passed",
"data",
"and",
"find",
"NaNs",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/stop_on_nan.py#L60-L81 | train |
Cognexa/cxflow | cxflow/hooks/stop_on_nan.py | StopOnNaN._check_nan | def _check_nan(self, epoch_data: EpochData) -> None:
"""
Raise an exception when some of the monitored data is NaN.
:param epoch_data: epoch data checked
:raise KeyError: if the specified variable is not found in the stream
:raise ValueError: if the variable value is of unsuppor... | python | def _check_nan(self, epoch_data: EpochData) -> None:
"""
Raise an exception when some of the monitored data is NaN.
:param epoch_data: epoch data checked
:raise KeyError: if the specified variable is not found in the stream
:raise ValueError: if the variable value is of unsuppor... | [
"def",
"_check_nan",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
")",
"->",
"None",
":",
"for",
"stream_name",
"in",
"epoch_data",
".",
"keys",
"(",
")",
":",
"stream_data",
"=",
"epoch_data",
"[",
"stream_name",
"]",
"variables",
"=",
"self",
".",
... | Raise an exception when some of the monitored data is NaN.
:param epoch_data: epoch data checked
:raise KeyError: if the specified variable is not found in the stream
:raise ValueError: if the variable value is of unsupported type and ``self._on_unknown_type`` is set to ``error`` | [
"Raise",
"an",
"exception",
"when",
"some",
"of",
"the",
"monitored",
"data",
"is",
"NaN",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/stop_on_nan.py#L83-L101 | train |
Cognexa/cxflow | cxflow/hooks/stop_on_nan.py | StopOnNaN.after_epoch | def after_epoch(self, epoch_data: EpochData, **kwargs) -> None:
"""
If initialized to check after each epoch, stop the training once the epoch data contains a monitored
variable equal to NaN.
:param epoch_data: epoch data to be checked
"""
if self._after_epoch:
... | python | def after_epoch(self, epoch_data: EpochData, **kwargs) -> None:
"""
If initialized to check after each epoch, stop the training once the epoch data contains a monitored
variable equal to NaN.
:param epoch_data: epoch data to be checked
"""
if self._after_epoch:
... | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
",",
"**",
"kwargs",
")",
"->",
"None",
":",
"if",
"self",
".",
"_after_epoch",
":",
"self",
".",
"_check_nan",
"(",
"epoch_data",
")"
] | If initialized to check after each epoch, stop the training once the epoch data contains a monitored
variable equal to NaN.
:param epoch_data: epoch data to be checked | [
"If",
"initialized",
"to",
"check",
"after",
"each",
"epoch",
"stop",
"the",
"training",
"once",
"the",
"epoch",
"data",
"contains",
"a",
"monitored",
"variable",
"equal",
"to",
"NaN",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/stop_on_nan.py#L103-L112 | train |
Cognexa/cxflow | cxflow/hooks/stop_on_nan.py | StopOnNaN.after_batch | def after_batch(self, stream_name: str, batch_data) -> None:
"""
If initialized to check after each batch, stop the training once the batch data contains a monitored
variable equal to NaN.
:param stream_name: name of the stream to be checked
:param batch_data: batch data to be c... | python | def after_batch(self, stream_name: str, batch_data) -> None:
"""
If initialized to check after each batch, stop the training once the batch data contains a monitored
variable equal to NaN.
:param stream_name: name of the stream to be checked
:param batch_data: batch data to be c... | [
"def",
"after_batch",
"(",
"self",
",",
"stream_name",
":",
"str",
",",
"batch_data",
")",
"->",
"None",
":",
"if",
"self",
".",
"_after_batch",
":",
"self",
".",
"_check_nan",
"(",
"{",
"stream_name",
":",
"batch_data",
"}",
")"
] | If initialized to check after each batch, stop the training once the batch data contains a monitored
variable equal to NaN.
:param stream_name: name of the stream to be checked
:param batch_data: batch data to be checked | [
"If",
"initialized",
"to",
"check",
"after",
"each",
"batch",
"stop",
"the",
"training",
"once",
"the",
"batch",
"data",
"contains",
"a",
"monitored",
"variable",
"equal",
"to",
"NaN",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/stop_on_nan.py#L114-L124 | train |
Cognexa/cxflow | cxflow/hooks/every_n_epoch.py | EveryNEpoch.after_epoch | def after_epoch(self, epoch_id: int, **kwargs) -> None:
"""
Call ``_after_n_epoch`` method every ``n_epochs`` epoch.
:param epoch_id: number of the processed epoch
"""
if epoch_id % self._n_epochs == 0:
self._after_n_epoch(epoch_id=epoch_id, **kwargs) | python | def after_epoch(self, epoch_id: int, **kwargs) -> None:
"""
Call ``_after_n_epoch`` method every ``n_epochs`` epoch.
:param epoch_id: number of the processed epoch
"""
if epoch_id % self._n_epochs == 0:
self._after_n_epoch(epoch_id=epoch_id, **kwargs) | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"**",
"kwargs",
")",
"->",
"None",
":",
"if",
"epoch_id",
"%",
"self",
".",
"_n_epochs",
"==",
"0",
":",
"self",
".",
"_after_n_epoch",
"(",
"epoch_id",
"=",
"epoch_id",
",",
"**",
... | Call ``_after_n_epoch`` method every ``n_epochs`` epoch.
:param epoch_id: number of the processed epoch | [
"Call",
"_after_n_epoch",
"method",
"every",
"n_epochs",
"epoch",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/every_n_epoch.py#L33-L40 | train |
Cognexa/cxflow | cxflow/cli/ls.py | humanize_filesize | def humanize_filesize(filesize: int) -> Tuple[str, str]:
"""Return human readable pair of size and unit from the given filesize in bytes."""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if filesize < 1024.0:
return '{:3.1f}'.format(filesize), unit+'B'
filesize /= 1024.0 | python | def humanize_filesize(filesize: int) -> Tuple[str, str]:
"""Return human readable pair of size and unit from the given filesize in bytes."""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if filesize < 1024.0:
return '{:3.1f}'.format(filesize), unit+'B'
filesize /= 1024.0 | [
"def",
"humanize_filesize",
"(",
"filesize",
":",
"int",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"for",
"unit",
"in",
"[",
"''",
",",
"'K'",
",",
"'M'",
",",
"'G'",
",",
"'T'",
",",
"'P'",
",",
"'E'",
",",
"'Z'",
"]",
":",
"if",
... | Return human readable pair of size and unit from the given filesize in bytes. | [
"Return",
"human",
"readable",
"pair",
"of",
"size",
"and",
"unit",
"from",
"the",
"given",
"filesize",
"in",
"bytes",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L35-L40 | train |
Cognexa/cxflow | cxflow/cli/ls.py | is_train_dir | def is_train_dir(dir_: str) -> bool:
"""Test if the given dir contains training artifacts."""
return path.exists(path.join(dir_, CXF_CONFIG_FILE)) and \
path.exists(path.join(dir_, CXF_TRACE_FILE)) and \
path.exists(path.join(dir_, CXF_LOG_FILE)) | python | def is_train_dir(dir_: str) -> bool:
"""Test if the given dir contains training artifacts."""
return path.exists(path.join(dir_, CXF_CONFIG_FILE)) and \
path.exists(path.join(dir_, CXF_TRACE_FILE)) and \
path.exists(path.join(dir_, CXF_LOG_FILE)) | [
"def",
"is_train_dir",
"(",
"dir_",
":",
"str",
")",
"->",
"bool",
":",
"return",
"path",
".",
"exists",
"(",
"path",
".",
"join",
"(",
"dir_",
",",
"CXF_CONFIG_FILE",
")",
")",
"and",
"path",
".",
"exists",
"(",
"path",
".",
"join",
"(",
"dir_",
"... | Test if the given dir contains training artifacts. | [
"Test",
"if",
"the",
"given",
"dir",
"contains",
"training",
"artifacts",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L43-L47 | train |
Cognexa/cxflow | cxflow/cli/ls.py | _print_trainings_long | def _print_trainings_long(trainings: Iterable[Tuple[str, dict, TrainingTrace]]) -> None:
"""
Print a plain table with the details of the given trainings.
:param trainings: iterable of tuples (train_dir, configuration dict, trace)
"""
long_table = []
for train_dir, config, trace in trainings:
... | python | def _print_trainings_long(trainings: Iterable[Tuple[str, dict, TrainingTrace]]) -> None:
"""
Print a plain table with the details of the given trainings.
:param trainings: iterable of tuples (train_dir, configuration dict, trace)
"""
long_table = []
for train_dir, config, trace in trainings:
... | [
"def",
"_print_trainings_long",
"(",
"trainings",
":",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"dict",
",",
"TrainingTrace",
"]",
"]",
")",
"->",
"None",
":",
"long_table",
"=",
"[",
"]",
"for",
"train_dir",
",",
"config",
",",
"trace",
"in",
"trainin... | Print a plain table with the details of the given trainings.
:param trainings: iterable of tuples (train_dir, configuration dict, trace) | [
"Print",
"a",
"plain",
"table",
"with",
"the",
"details",
"of",
"the",
"given",
"trainings",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L89-L114 | train |
Cognexa/cxflow | cxflow/cli/ls.py | _ls_print_listing | def _ls_print_listing(dir_: str, recursive: bool, all_: bool, long: bool) -> List[Tuple[str, dict, TrainingTrace]]:
"""
Print names of the train dirs contained in the given dir.
:param dir_: dir to be listed
:param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option)
... | python | def _ls_print_listing(dir_: str, recursive: bool, all_: bool, long: bool) -> List[Tuple[str, dict, TrainingTrace]]:
"""
Print names of the train dirs contained in the given dir.
:param dir_: dir to be listed
:param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option)
... | [
"def",
"_ls_print_listing",
"(",
"dir_",
":",
"str",
",",
"recursive",
":",
"bool",
",",
"all_",
":",
"bool",
",",
"long",
":",
"bool",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"dict",
",",
"TrainingTrace",
"]",
"]",
":",
"all_trainings",
"=... | Print names of the train dirs contained in the given dir.
:param dir_: dir to be listed
:param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option)
:param all_: include train dirs with no epochs done (--all option)
:param long: list more details including model name, ... | [
"Print",
"names",
"of",
"the",
"train",
"dirs",
"contained",
"in",
"the",
"given",
"dir",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L117-L152 | train |
Cognexa/cxflow | cxflow/cli/ls.py | _ls_print_summary | def _ls_print_summary(all_trainings: List[Tuple[str, dict, TrainingTrace]]) -> None:
"""
Print trainings summary.
In particular print tables summarizing the number of trainings with
- particular model names
- particular combinations of models and datasets
:param all_trainings: a list of... | python | def _ls_print_summary(all_trainings: List[Tuple[str, dict, TrainingTrace]]) -> None:
"""
Print trainings summary.
In particular print tables summarizing the number of trainings with
- particular model names
- particular combinations of models and datasets
:param all_trainings: a list of... | [
"def",
"_ls_print_summary",
"(",
"all_trainings",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"dict",
",",
"TrainingTrace",
"]",
"]",
")",
"->",
"None",
":",
"counts_by_name",
"=",
"defaultdict",
"(",
"int",
")",
"counts_by_classes",
"=",
"defaultdict",
"(",... | Print trainings summary.
In particular print tables summarizing the number of trainings with
- particular model names
- particular combinations of models and datasets
:param all_trainings: a list of training tuples (train_dir, configuration dict, trace) | [
"Print",
"trainings",
"summary",
".",
"In",
"particular",
"print",
"tables",
"summarizing",
"the",
"number",
"of",
"trainings",
"with",
"-",
"particular",
"model",
"names",
"-",
"particular",
"combinations",
"of",
"models",
"and",
"datasets"
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L155-L179 | train |
Cognexa/cxflow | cxflow/cli/ls.py | list_train_dirs | def list_train_dirs(dir_: str, recursive: bool, all_: bool, long: bool, verbose: bool) -> None:
"""
List training dirs contained in the given dir with options and outputs similar to the regular `ls` command.
The function is accessible through cxflow CLI `cxflow ls`.
:param dir_: dir to be listed
:p... | python | def list_train_dirs(dir_: str, recursive: bool, all_: bool, long: bool, verbose: bool) -> None:
"""
List training dirs contained in the given dir with options and outputs similar to the regular `ls` command.
The function is accessible through cxflow CLI `cxflow ls`.
:param dir_: dir to be listed
:p... | [
"def",
"list_train_dirs",
"(",
"dir_",
":",
"str",
",",
"recursive",
":",
"bool",
",",
"all_",
":",
"bool",
",",
"long",
":",
"bool",
",",
"verbose",
":",
"bool",
")",
"->",
"None",
":",
"if",
"verbose",
":",
"long",
"=",
"True",
"if",
"dir_",
"=="... | List training dirs contained in the given dir with options and outputs similar to the regular `ls` command.
The function is accessible through cxflow CLI `cxflow ls`.
:param dir_: dir to be listed
:param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option)
:param all_... | [
"List",
"training",
"dirs",
"contained",
"in",
"the",
"given",
"dir",
"with",
"options",
"and",
"outputs",
"similar",
"to",
"the",
"regular",
"ls",
"command",
".",
"The",
"function",
"is",
"accessible",
"through",
"cxflow",
"CLI",
"cxflow",
"ls",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L203-L238 | train |
Cognexa/cxflow | cxflow/hooks/accumulate_variables.py | AccumulateVariables.after_batch | def after_batch(self, stream_name: str, batch_data: Batch):
"""
Extend the accumulated variables with the given batch data.
:param stream_name: stream name; e.g. ``train`` or any other...
:param batch_data: batch data = stream sources + model outputs
:raise KeyError: if the vari... | python | def after_batch(self, stream_name: str, batch_data: Batch):
"""
Extend the accumulated variables with the given batch data.
:param stream_name: stream name; e.g. ``train`` or any other...
:param batch_data: batch data = stream sources + model outputs
:raise KeyError: if the vari... | [
"def",
"after_batch",
"(",
"self",
",",
"stream_name",
":",
"str",
",",
"batch_data",
":",
"Batch",
")",
":",
"for",
"variable",
"in",
"self",
".",
"_variables",
":",
"if",
"variable",
"in",
"batch_data",
":",
"value",
"=",
"batch_data",
"[",
"variable",
... | Extend the accumulated variables with the given batch data.
:param stream_name: stream name; e.g. ``train`` or any other...
:param batch_data: batch data = stream sources + model outputs
:raise KeyError: if the variables to be aggregated are missing
:raise TypeError: if the variable val... | [
"Extend",
"the",
"accumulated",
"variables",
"with",
"the",
"given",
"batch",
"data",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/accumulate_variables.py#L40-L57 | train |
Cognexa/cxflow | cxflow/cli/dataset.py | invoke_dataset_method | def invoke_dataset_method(config_path: str, method_name: str, output_root: str, cl_arguments: Iterable[str]) -> None:
"""
Create the specified dataset and invoke its specified method.
:param config_path: path to the config file or the directory in which it is stored
:param method_name: name of the meth... | python | def invoke_dataset_method(config_path: str, method_name: str, output_root: str, cl_arguments: Iterable[str]) -> None:
"""
Create the specified dataset and invoke its specified method.
:param config_path: path to the config file or the directory in which it is stored
:param method_name: name of the meth... | [
"def",
"invoke_dataset_method",
"(",
"config_path",
":",
"str",
",",
"method_name",
":",
"str",
",",
"output_root",
":",
"str",
",",
"cl_arguments",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"config",
"=",
"dataset",
"=",
"method",
"=",
"... | Create the specified dataset and invoke its specified method.
:param config_path: path to the config file or the directory in which it is stored
:param method_name: name of the method to be invoked on the specified dataset
:param cl_arguments: additional command line arguments which will update the configu... | [
"Create",
"the",
"specified",
"dataset",
"and",
"invoke",
"its",
"specified",
"method",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/dataset.py#L11-L44 | train |
Cognexa/cxflow | cxflow/utils/misc.py | CaughtInterrupts._signal_handler | def _signal_handler(self, *_) -> None:
"""
On the first signal, increase the ``self._num_signals`` counter.
Call ``sys.exit`` on any subsequent signal.
"""
if self._num_signals == 0:
logging.warning('Interrupt signal caught - training will be terminated')
... | python | def _signal_handler(self, *_) -> None:
"""
On the first signal, increase the ``self._num_signals`` counter.
Call ``sys.exit`` on any subsequent signal.
"""
if self._num_signals == 0:
logging.warning('Interrupt signal caught - training will be terminated')
... | [
"def",
"_signal_handler",
"(",
"self",
",",
"*",
"_",
")",
"->",
"None",
":",
"if",
"self",
".",
"_num_signals",
"==",
"0",
":",
"logging",
".",
"warning",
"(",
"'Interrupt signal caught - training will be terminated'",
")",
"logging",
".",
"warning",
"(",
"'A... | On the first signal, increase the ``self._num_signals`` counter.
Call ``sys.exit`` on any subsequent signal. | [
"On",
"the",
"first",
"signal",
"increase",
"the",
"self",
".",
"_num_signals",
"counter",
".",
"Call",
"sys",
".",
"exit",
"on",
"any",
"subsequent",
"signal",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/misc.py#L95-L106 | train |
Cognexa/cxflow | cxflow/cli/common.py | create_output_dir | def create_output_dir(config: dict, output_root: str, default_model_name: str='Unnamed') -> str:
"""
Create output_dir under the given ``output_root`` and
- dump the given config to YAML file under this dir
- register a file logger logging to a file under this dir
:param config: config to b... | python | def create_output_dir(config: dict, output_root: str, default_model_name: str='Unnamed') -> str:
"""
Create output_dir under the given ``output_root`` and
- dump the given config to YAML file under this dir
- register a file logger logging to a file under this dir
:param config: config to b... | [
"def",
"create_output_dir",
"(",
"config",
":",
"dict",
",",
"output_root",
":",
"str",
",",
"default_model_name",
":",
"str",
"=",
"'Unnamed'",
")",
"->",
"str",
":",
"logging",
".",
"info",
"(",
"'Creating output dir'",
")",
"model_name",
"=",
"default_model... | Create output_dir under the given ``output_root`` and
- dump the given config to YAML file under this dir
- register a file logger logging to a file under this dir
:param config: config to be dumped
:param output_root: dir wherein output_dir shall be created
:param default_model_name: name ... | [
"Create",
"output_dir",
"under",
"the",
"given",
"output_root",
"and",
"-",
"dump",
"the",
"given",
"config",
"to",
"YAML",
"file",
"under",
"this",
"dir",
"-",
"register",
"a",
"file",
"logger",
"logging",
"to",
"a",
"file",
"under",
"this",
"dir"
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/common.py#L21-L63 | train |
Cognexa/cxflow | cxflow/cli/common.py | create_dataset | def create_dataset(config: dict, output_dir: Optional[str]=None) -> AbstractDataset:
"""
Create a dataset object according to the given config.
Dataset config section and the `output_dir` are passed to the constructor in a single YAML-encoded string.
:param config: config dict with dataset config
... | python | def create_dataset(config: dict, output_dir: Optional[str]=None) -> AbstractDataset:
"""
Create a dataset object according to the given config.
Dataset config section and the `output_dir` are passed to the constructor in a single YAML-encoded string.
:param config: config dict with dataset config
... | [
"def",
"create_dataset",
"(",
"config",
":",
"dict",
",",
"output_dir",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"AbstractDataset",
":",
"logging",
".",
"info",
"(",
"'Creating dataset'",
")",
"dataset_config",
"=",
"make_simple",
"(",
"conf... | Create a dataset object according to the given config.
Dataset config section and the `output_dir` are passed to the constructor in a single YAML-encoded string.
:param config: config dict with dataset config
:param output_dir: path to the training output dir or None
:return: dataset object | [
"Create",
"a",
"dataset",
"object",
"according",
"to",
"the",
"given",
"config",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/common.py#L66-L90 | train |
Cognexa/cxflow | cxflow/cli/common.py | create_model | def create_model(config: dict, output_dir: Optional[str], dataset: AbstractDataset,
restore_from: Optional[str]=None) -> AbstractModel:
"""
Create a model object either from scratch of from the checkpoint in ``resume_dir``.
Cxflow allows the following scenarios
1. Create model: leave ... | python | def create_model(config: dict, output_dir: Optional[str], dataset: AbstractDataset,
restore_from: Optional[str]=None) -> AbstractModel:
"""
Create a model object either from scratch of from the checkpoint in ``resume_dir``.
Cxflow allows the following scenarios
1. Create model: leave ... | [
"def",
"create_model",
"(",
"config",
":",
"dict",
",",
"output_dir",
":",
"Optional",
"[",
"str",
"]",
",",
"dataset",
":",
"AbstractDataset",
",",
"restore_from",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"AbstractModel",
":",
"logging",
... | Create a model object either from scratch of from the checkpoint in ``resume_dir``.
Cxflow allows the following scenarios
1. Create model: leave ``restore_from=None`` and specify ``class``;
2. Restore model: specify ``restore_from`` which is a backend-specific path to (a directory with) the saved model.
... | [
"Create",
"a",
"model",
"object",
"either",
"from",
"scratch",
"of",
"from",
"the",
"checkpoint",
"in",
"resume_dir",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/common.py#L93-L146 | train |
Cognexa/cxflow | cxflow/cli/prune.py | _prune_subdirs | def _prune_subdirs(dir_: str) -> None:
"""
Delete all subdirs in training log dirs.
:param dir_: dir with training log dirs
"""
for logdir in [path.join(dir_, f) for f in listdir(dir_) if is_train_dir(path.join(dir_, f))]:
for subdir in [path.join(logdir, f) for f in listdir(logdir) if path... | python | def _prune_subdirs(dir_: str) -> None:
"""
Delete all subdirs in training log dirs.
:param dir_: dir with training log dirs
"""
for logdir in [path.join(dir_, f) for f in listdir(dir_) if is_train_dir(path.join(dir_, f))]:
for subdir in [path.join(logdir, f) for f in listdir(logdir) if path... | [
"def",
"_prune_subdirs",
"(",
"dir_",
":",
"str",
")",
"->",
"None",
":",
"for",
"logdir",
"in",
"[",
"path",
".",
"join",
"(",
"dir_",
",",
"f",
")",
"for",
"f",
"in",
"listdir",
"(",
"dir_",
")",
"if",
"is_train_dir",
"(",
"path",
".",
"join",
... | Delete all subdirs in training log dirs.
:param dir_: dir with training log dirs | [
"Delete",
"all",
"subdirs",
"in",
"training",
"log",
"dirs",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/prune.py#L23-L31 | train |
Cognexa/cxflow | cxflow/cli/prune.py | _prune | def _prune(dir_: str, epochs: int) -> None:
"""
Delete all training dirs with incomplete training artifacts or with less than specified epochs done.
:param dir_: dir with training log dirs
:param epochs: minimum number of finished epochs to keep the training logs
:return: number of log dirs pruned
... | python | def _prune(dir_: str, epochs: int) -> None:
"""
Delete all training dirs with incomplete training artifacts or with less than specified epochs done.
:param dir_: dir with training log dirs
:param epochs: minimum number of finished epochs to keep the training logs
:return: number of log dirs pruned
... | [
"def",
"_prune",
"(",
"dir_",
":",
"str",
",",
"epochs",
":",
"int",
")",
"->",
"None",
":",
"for",
"logdir",
"in",
"[",
"path",
".",
"join",
"(",
"dir_",
",",
"f",
")",
"for",
"f",
"in",
"listdir",
"(",
"dir_",
")",
"if",
"path",
".",
"isdir",... | Delete all training dirs with incomplete training artifacts or with less than specified epochs done.
:param dir_: dir with training log dirs
:param epochs: minimum number of finished epochs to keep the training logs
:return: number of log dirs pruned | [
"Delete",
"all",
"training",
"dirs",
"with",
"incomplete",
"training",
"artifacts",
"or",
"with",
"less",
"than",
"specified",
"epochs",
"done",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/prune.py#L34-L52 | train |
Cognexa/cxflow | cxflow/cli/prune.py | prune_train_dirs | def prune_train_dirs(dir_: str, epochs: int, subdirs: bool) -> None:
"""
Prune training log dirs contained in the given dir. The function is accessible through cxflow CLI `cxflow prune`.
:param dir_: dir to be pruned
:param epochs: minimum number of finished epochs to keep the training logs
:param ... | python | def prune_train_dirs(dir_: str, epochs: int, subdirs: bool) -> None:
"""
Prune training log dirs contained in the given dir. The function is accessible through cxflow CLI `cxflow prune`.
:param dir_: dir to be pruned
:param epochs: minimum number of finished epochs to keep the training logs
:param ... | [
"def",
"prune_train_dirs",
"(",
"dir_",
":",
"str",
",",
"epochs",
":",
"int",
",",
"subdirs",
":",
"bool",
")",
"->",
"None",
":",
"if",
"dir_",
"==",
"CXF_DEFAULT_LOG_DIR",
"and",
"not",
"path",
".",
"exists",
"(",
"CXF_DEFAULT_LOG_DIR",
")",
":",
"pri... | Prune training log dirs contained in the given dir. The function is accessible through cxflow CLI `cxflow prune`.
:param dir_: dir to be pruned
:param epochs: minimum number of finished epochs to keep the training logs
:param subdirs: delete subdirs in training log dirs | [
"Prune",
"training",
"log",
"dirs",
"contained",
"in",
"the",
"given",
"dir",
".",
"The",
"function",
"is",
"accessible",
"through",
"cxflow",
"CLI",
"cxflow",
"prune",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/prune.py#L55-L75 | train |
Cognexa/cxflow | cxflow/models/sequence.py | Sequence.output_names | def output_names(self) -> Iterable[str]:
"""List of model output names."""
self._load_models()
return chain.from_iterable(map(lambda m: m.output_names, self._models)) | python | def output_names(self) -> Iterable[str]:
"""List of model output names."""
self._load_models()
return chain.from_iterable(map(lambda m: m.output_names, self._models)) | [
"def",
"output_names",
"(",
"self",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"self",
".",
"_load_models",
"(",
")",
"return",
"chain",
".",
"from_iterable",
"(",
"map",
"(",
"lambda",
"m",
":",
"m",
".",
"output_names",
",",
"self",
".",
"_models",... | List of model output names. | [
"List",
"of",
"model",
"output",
"names",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/models/sequence.py#L89-L92 | train |
Cognexa/cxflow | cxflow/models/sequence.py | Sequence.run | def run(self, batch: Batch, train: bool=False, stream: StreamWrapper=None) -> Batch:
"""
Run all the models in-order and return accumulated outputs.
N-th model is fed with the original inputs and outputs of all the models that were run before it.
.. warning::
:py:class:`Seq... | python | def run(self, batch: Batch, train: bool=False, stream: StreamWrapper=None) -> Batch:
"""
Run all the models in-order and return accumulated outputs.
N-th model is fed with the original inputs and outputs of all the models that were run before it.
.. warning::
:py:class:`Seq... | [
"def",
"run",
"(",
"self",
",",
"batch",
":",
"Batch",
",",
"train",
":",
"bool",
"=",
"False",
",",
"stream",
":",
"StreamWrapper",
"=",
"None",
")",
"->",
"Batch",
":",
"if",
"train",
":",
"raise",
"ValueError",
"(",
"'Ensemble model cannot be trained.'"... | Run all the models in-order and return accumulated outputs.
N-th model is fed with the original inputs and outputs of all the models that were run before it.
.. warning::
:py:class:`Sequence` model can not be trained.
:param batch: batch to be processed
:param train: ``Tru... | [
"Run",
"all",
"the",
"models",
"in",
"-",
"order",
"and",
"return",
"accumulated",
"outputs",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/models/sequence.py#L94-L118 | train |
Cognexa/cxflow | cxflow/hooks/log_variables.py | LogVariables._log_variables | def _log_variables(self, epoch_data: EpochData):
"""
Log variables from the epoch data.
.. warning::
At the moment, only scalars and dicts of scalars are properly formatted and logged.
Other value types are ignored by default.
One may set ``on_unknown_type`` to ... | python | def _log_variables(self, epoch_data: EpochData):
"""
Log variables from the epoch data.
.. warning::
At the moment, only scalars and dicts of scalars are properly formatted and logged.
Other value types are ignored by default.
One may set ``on_unknown_type`` to ... | [
"def",
"_log_variables",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
")",
":",
"for",
"stream_name",
"in",
"epoch_data",
".",
"keys",
"(",
")",
":",
"stream_data",
"=",
"epoch_data",
"[",
"stream_name",
"]",
"variables",
"=",
"self",
".",
"_variables",... | Log variables from the epoch data.
.. warning::
At the moment, only scalars and dicts of scalars are properly formatted and logged.
Other value types are ignored by default.
One may set ``on_unknown_type`` to ``str`` in order to log all the variables anyways.
:param ep... | [
"Log",
"variables",
"from",
"the",
"epoch",
"data",
"."
] | dd609e6b0bd854424a8f86781dd77801a13038f9 | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/log_variables.py#L56-L96 | train |
hall-lab/svtyper | svtyper/parsers.py | SplitRead.get_reference_end_from_cigar | def get_reference_end_from_cigar(reference_start, cigar):
'''
This returns the coordinate just past the last aligned base.
This matches the behavior of pysam's reference_end method
'''
reference_end = reference_start
# iterate through cigartuple
for i in ... | python | def get_reference_end_from_cigar(reference_start, cigar):
'''
This returns the coordinate just past the last aligned base.
This matches the behavior of pysam's reference_end method
'''
reference_end = reference_start
# iterate through cigartuple
for i in ... | [
"def",
"get_reference_end_from_cigar",
"(",
"reference_start",
",",
"cigar",
")",
":",
"reference_end",
"=",
"reference_start",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"cigar",
")",
")",
":",
"k",
",",
"n",
"=",
"cigar",
"[",
"i",
"]",
"if",
"k",
... | This returns the coordinate just past the last aligned base.
This matches the behavior of pysam's reference_end method | [
"This",
"returns",
"the",
"coordinate",
"just",
"past",
"the",
"last",
"aligned",
"base",
".",
"This",
"matches",
"the",
"behavior",
"of",
"pysam",
"s",
"reference_end",
"method"
] | 5fc30763fd3025793ee712a563de800c010f6bea | https://github.com/hall-lab/svtyper/blob/5fc30763fd3025793ee712a563de800c010f6bea/svtyper/parsers.py#L1089-L1101 | train |
hall-lab/svtyper | svtyper/parsers.py | SplitRead.set_order_by_clip | def set_order_by_clip(self, a, b):
'''
Determine which SplitPiece is the leftmost based
on the side of the longest clipping operation
'''
if self.is_left_clip(a.cigar):
self.query_left = b
self.query_right = a
else:
self.query_left = a
... | python | def set_order_by_clip(self, a, b):
'''
Determine which SplitPiece is the leftmost based
on the side of the longest clipping operation
'''
if self.is_left_clip(a.cigar):
self.query_left = b
self.query_right = a
else:
self.query_left = a
... | [
"def",
"set_order_by_clip",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"self",
".",
"is_left_clip",
"(",
"a",
".",
"cigar",
")",
":",
"self",
".",
"query_left",
"=",
"b",
"self",
".",
"query_right",
"=",
"a",
"else",
":",
"self",
".",
"query_... | Determine which SplitPiece is the leftmost based
on the side of the longest clipping operation | [
"Determine",
"which",
"SplitPiece",
"is",
"the",
"leftmost",
"based",
"on",
"the",
"side",
"of",
"the",
"longest",
"clipping",
"operation"
] | 5fc30763fd3025793ee712a563de800c010f6bea | https://github.com/hall-lab/svtyper/blob/5fc30763fd3025793ee712a563de800c010f6bea/svtyper/parsers.py#L1230-L1240 | train |
uber/tchannel-python | tchannel/tornado/request.py | Request._is_streaming_request | def _is_streaming_request(self):
"""check request is stream request or not"""
arg2 = self.argstreams[1]
arg3 = self.argstreams[2]
return not (isinstance(arg2, InMemStream) and
isinstance(arg3, InMemStream) and
((arg2.auto_close and arg3.auto_close)... | python | def _is_streaming_request(self):
"""check request is stream request or not"""
arg2 = self.argstreams[1]
arg3 = self.argstreams[2]
return not (isinstance(arg2, InMemStream) and
isinstance(arg3, InMemStream) and
((arg2.auto_close and arg3.auto_close)... | [
"def",
"_is_streaming_request",
"(",
"self",
")",
":",
"arg2",
"=",
"self",
".",
"argstreams",
"[",
"1",
"]",
"arg3",
"=",
"self",
".",
"argstreams",
"[",
"2",
"]",
"return",
"not",
"(",
"isinstance",
"(",
"arg2",
",",
"InMemStream",
")",
"and",
"isins... | check request is stream request or not | [
"check",
"request",
"is",
"stream",
"request",
"or",
"not"
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/request.py#L155-L163 | train |
uber/tchannel-python | tchannel/tornado/request.py | Request.should_retry_on_error | def should_retry_on_error(self, error):
"""rules for retry
:param error:
ProtocolException that returns from Server
"""
if self.is_streaming_request:
# not retry for streaming request
return False
retry_flag = self.headers.get('re', retry.DE... | python | def should_retry_on_error(self, error):
"""rules for retry
:param error:
ProtocolException that returns from Server
"""
if self.is_streaming_request:
# not retry for streaming request
return False
retry_flag = self.headers.get('re', retry.DE... | [
"def",
"should_retry_on_error",
"(",
"self",
",",
"error",
")",
":",
"if",
"self",
".",
"is_streaming_request",
":",
"return",
"False",
"retry_flag",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'re'",
",",
"retry",
".",
"DEFAULT",
")",
"if",
"retry_flag... | rules for retry
:param error:
ProtocolException that returns from Server | [
"rules",
"for",
"retry"
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/request.py#L165-L196 | train |
uber/tchannel-python | tchannel/sync/thrift.py | client_for | def client_for(service, service_module, thrift_service_name=None):
"""Build a synchronous client class for the given Thrift service.
The generated class accepts a TChannelSyncClient and an optional
hostport as initialization arguments.
Given ``CommentService`` defined in ``comment.thrift`` and registe... | python | def client_for(service, service_module, thrift_service_name=None):
"""Build a synchronous client class for the given Thrift service.
The generated class accepts a TChannelSyncClient and an optional
hostport as initialization arguments.
Given ``CommentService`` defined in ``comment.thrift`` and registe... | [
"def",
"client_for",
"(",
"service",
",",
"service_module",
",",
"thrift_service_name",
"=",
"None",
")",
":",
"assert",
"service_module",
",",
"'service_module is required'",
"service",
"=",
"service",
"or",
"''",
"if",
"not",
"thrift_service_name",
":",
"thrift_se... | Build a synchronous client class for the given Thrift service.
The generated class accepts a TChannelSyncClient and an optional
hostport as initialization arguments.
Given ``CommentService`` defined in ``comment.thrift`` and registered
with Hyperbahn under the name "comment", here's how this might be ... | [
"Build",
"a",
"synchronous",
"client",
"class",
"for",
"the",
"given",
"Thrift",
"service",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/sync/thrift.py#L27-L106 | train |
uber/tchannel-python | tchannel/sync/thrift.py | generate_method | def generate_method(method_name):
"""Generate a method for a given Thrift service.
Uses the provided TChannelSyncClient's threadloop in order
to convert RPC calls to concurrent.futures
:param method_name: Method being called.
:return: A method that invokes the RPC using TChannelSyncClient
"""
... | python | def generate_method(method_name):
"""Generate a method for a given Thrift service.
Uses the provided TChannelSyncClient's threadloop in order
to convert RPC calls to concurrent.futures
:param method_name: Method being called.
:return: A method that invokes the RPC using TChannelSyncClient
"""
... | [
"def",
"generate_method",
"(",
"method_name",
")",
":",
"def",
"call",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"threadloop",
".",
"is_ready",
"(",
")",
":",
"self",
".",
"threadloop",
".",
"start",
"(",... | Generate a method for a given Thrift service.
Uses the provided TChannelSyncClient's threadloop in order
to convert RPC calls to concurrent.futures
:param method_name: Method being called.
:return: A method that invokes the RPC using TChannelSyncClient | [
"Generate",
"a",
"method",
"for",
"a",
"given",
"Thrift",
"service",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/sync/thrift.py#L109-L131 | train |
uber/tchannel-python | tchannel/tornado/stream.py | read_full | def read_full(stream):
"""Read the full contents of the given stream into memory.
:return:
A future containing the complete stream contents.
"""
assert stream, "stream is required"
chunks = []
chunk = yield stream.read()
while chunk:
chunks.append(chunk)
chunk = yi... | python | def read_full(stream):
"""Read the full contents of the given stream into memory.
:return:
A future containing the complete stream contents.
"""
assert stream, "stream is required"
chunks = []
chunk = yield stream.read()
while chunk:
chunks.append(chunk)
chunk = yi... | [
"def",
"read_full",
"(",
"stream",
")",
":",
"assert",
"stream",
",",
"\"stream is required\"",
"chunks",
"=",
"[",
"]",
"chunk",
"=",
"yield",
"stream",
".",
"read",
"(",
")",
"while",
"chunk",
":",
"chunks",
".",
"append",
"(",
"chunk",
")",
"chunk",
... | Read the full contents of the given stream into memory.
:return:
A future containing the complete stream contents. | [
"Read",
"the",
"full",
"contents",
"of",
"the",
"given",
"stream",
"into",
"memory",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/stream.py#L37-L52 | train |
uber/tchannel-python | tchannel/tornado/stream.py | maybe_stream | def maybe_stream(s):
"""Ensure that the given argument is a stream."""
if isinstance(s, Stream):
return s
if s is None:
stream = InMemStream()
stream.close() # we don't intend to write anything
return stream
if isinstance(s, unicode):
s = s.encode('utf-8')
... | python | def maybe_stream(s):
"""Ensure that the given argument is a stream."""
if isinstance(s, Stream):
return s
if s is None:
stream = InMemStream()
stream.close() # we don't intend to write anything
return stream
if isinstance(s, unicode):
s = s.encode('utf-8')
... | [
"def",
"maybe_stream",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"Stream",
")",
":",
"return",
"s",
"if",
"s",
"is",
"None",
":",
"stream",
"=",
"InMemStream",
"(",
")",
"stream",
".",
"close",
"(",
")",
"return",
"stream",
"if",
"isin... | Ensure that the given argument is a stream. | [
"Ensure",
"that",
"the",
"given",
"argument",
"is",
"a",
"stream",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/stream.py#L259-L280 | train |
uber/tchannel-python | tchannel/tornado/message_factory.py | build_raw_error_message | def build_raw_error_message(protocol_exception):
"""build protocol level error message based on Error object"""
message = ErrorMessage(
id=protocol_exception.id,
code=protocol_exception.code,
tracing=protocol_exception.tracing,
description=protocol_exception.description,
)
... | python | def build_raw_error_message(protocol_exception):
"""build protocol level error message based on Error object"""
message = ErrorMessage(
id=protocol_exception.id,
code=protocol_exception.code,
tracing=protocol_exception.tracing,
description=protocol_exception.description,
)
... | [
"def",
"build_raw_error_message",
"(",
"protocol_exception",
")",
":",
"message",
"=",
"ErrorMessage",
"(",
"id",
"=",
"protocol_exception",
".",
"id",
",",
"code",
"=",
"protocol_exception",
".",
"code",
",",
"tracing",
"=",
"protocol_exception",
".",
"tracing",
... | build protocol level error message based on Error object | [
"build",
"protocol",
"level",
"error",
"message",
"based",
"on",
"Error",
"object"
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L49-L58 | train |
uber/tchannel-python | tchannel/tornado/message_factory.py | MessageFactory.build_raw_request_message | def build_raw_request_message(self, request, args, is_completed=False):
"""build protocol level message based on request and args.
request object contains meta information about outgoing request.
args are the currently chunk data from argstreams
is_completed tells the flags of the messa... | python | def build_raw_request_message(self, request, args, is_completed=False):
"""build protocol level message based on request and args.
request object contains meta information about outgoing request.
args are the currently chunk data from argstreams
is_completed tells the flags of the messa... | [
"def",
"build_raw_request_message",
"(",
"self",
",",
"request",
",",
"args",
",",
"is_completed",
"=",
"False",
")",
":",
"request",
".",
"flags",
"=",
"FlagsType",
".",
"none",
"if",
"is_completed",
"else",
"FlagsType",
".",
"fragment",
"if",
"request",
".... | build protocol level message based on request and args.
request object contains meta information about outgoing request.
args are the currently chunk data from argstreams
is_completed tells the flags of the message
:param request: Request
:param args: array of arg streams
... | [
"build",
"protocol",
"level",
"message",
"based",
"on",
"request",
"and",
"args",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L76-L113 | train |
uber/tchannel-python | tchannel/tornado/message_factory.py | MessageFactory.build_raw_response_message | def build_raw_response_message(self, response, args, is_completed=False):
"""build protocol level message based on response and args.
response object contains meta information about outgoing response.
args are the currently chunk data from argstreams
is_completed tells the flags of the ... | python | def build_raw_response_message(self, response, args, is_completed=False):
"""build protocol level message based on response and args.
response object contains meta information about outgoing response.
args are the currently chunk data from argstreams
is_completed tells the flags of the ... | [
"def",
"build_raw_response_message",
"(",
"self",
",",
"response",
",",
"args",
",",
"is_completed",
"=",
"False",
")",
":",
"response",
".",
"flags",
"=",
"FlagsType",
".",
"none",
"if",
"is_completed",
"else",
"FlagsType",
".",
"fragment",
"if",
"response",
... | build protocol level message based on response and args.
response object contains meta information about outgoing response.
args are the currently chunk data from argstreams
is_completed tells the flags of the message
:param response: Response
:param args: array of arg streams
... | [
"build",
"protocol",
"level",
"message",
"based",
"on",
"response",
"and",
"args",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L115-L151 | train |
uber/tchannel-python | tchannel/tornado/message_factory.py | MessageFactory.build_request | def build_request(self, message):
"""Build inbound request object from protocol level message info.
It is allowed to take incompleted CallRequestMessage. Therefore the
created request may not contain whole three arguments.
:param message: CallRequestMessage
:return: request obj... | python | def build_request(self, message):
"""Build inbound request object from protocol level message info.
It is allowed to take incompleted CallRequestMessage. Therefore the
created request may not contain whole three arguments.
:param message: CallRequestMessage
:return: request obj... | [
"def",
"build_request",
"(",
"self",
",",
"message",
")",
":",
"args",
"=",
"self",
".",
"prepare_args",
"(",
"message",
")",
"req",
"=",
"Request",
"(",
"flags",
"=",
"message",
".",
"flags",
",",
"ttl",
"=",
"message",
".",
"ttl",
"/",
"1000.0",
",... | Build inbound request object from protocol level message info.
It is allowed to take incompleted CallRequestMessage. Therefore the
created request may not contain whole three arguments.
:param message: CallRequestMessage
:return: request object | [
"Build",
"inbound",
"request",
"object",
"from",
"protocol",
"level",
"message",
"info",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L172-L195 | train |
uber/tchannel-python | tchannel/tornado/message_factory.py | MessageFactory.build_response | def build_response(self, message):
"""Build response object from protocol level message info
It is allowed to take incompleted CallResponseMessage. Therefore the
created request may not contain whole three arguments.
:param message: CallResponseMessage
:return: response object
... | python | def build_response(self, message):
"""Build response object from protocol level message info
It is allowed to take incompleted CallResponseMessage. Therefore the
created request may not contain whole three arguments.
:param message: CallResponseMessage
:return: response object
... | [
"def",
"build_response",
"(",
"self",
",",
"message",
")",
":",
"args",
"=",
"self",
".",
"prepare_args",
"(",
"message",
")",
"res",
"=",
"Response",
"(",
"flags",
"=",
"message",
".",
"flags",
",",
"code",
"=",
"message",
".",
"code",
",",
"headers",... | Build response object from protocol level message info
It is allowed to take incompleted CallResponseMessage. Therefore the
created request may not contain whole three arguments.
:param message: CallResponseMessage
:return: response object | [
"Build",
"response",
"object",
"from",
"protocol",
"level",
"message",
"info"
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L197-L218 | train |
uber/tchannel-python | tchannel/tornado/message_factory.py | MessageFactory.build | def build(self, message):
"""buffer all the streaming messages based on the
message id. Reconstruct all fragments together.
:param message:
incoming message
:return: next complete message or None if streaming
is not done
"""
context = None
... | python | def build(self, message):
"""buffer all the streaming messages based on the
message id. Reconstruct all fragments together.
:param message:
incoming message
:return: next complete message or None if streaming
is not done
"""
context = None
... | [
"def",
"build",
"(",
"self",
",",
"message",
")",
":",
"context",
"=",
"None",
"if",
"message",
".",
"message_type",
"in",
"[",
"Types",
".",
"CALL_REQ",
",",
"Types",
".",
"CALL_RES",
"]",
":",
"self",
".",
"verify_message",
"(",
"message",
")",
"cont... | buffer all the streaming messages based on the
message id. Reconstruct all fragments together.
:param message:
incoming message
:return: next complete message or None if streaming
is not done | [
"buffer",
"all",
"the",
"streaming",
"messages",
"based",
"on",
"the",
"message",
"id",
".",
"Reconstruct",
"all",
"fragments",
"together",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L226-L309 | train |
uber/tchannel-python | tchannel/tornado/message_factory.py | MessageFactory.fragment | def fragment(self, message):
"""Fragment message based on max payload size
note: if the message doesn't need to fragment,
it will return a list which only contains original
message itself.
:param message: raw message
:return: list of messages whose sizes <= max
... | python | def fragment(self, message):
"""Fragment message based on max payload size
note: if the message doesn't need to fragment,
it will return a list which only contains original
message itself.
:param message: raw message
:return: list of messages whose sizes <= max
... | [
"def",
"fragment",
"(",
"self",
",",
"message",
")",
":",
"if",
"message",
".",
"message_type",
"in",
"[",
"Types",
".",
"CALL_RES",
",",
"Types",
".",
"CALL_REQ",
",",
"Types",
".",
"CALL_REQ_CONTINUE",
",",
"Types",
".",
"CALL_RES_CONTINUE",
"]",
":",
... | Fragment message based on max payload size
note: if the message doesn't need to fragment,
it will return a list which only contains original
message itself.
:param message: raw message
:return: list of messages whose sizes <= max
payload size | [
"Fragment",
"message",
"based",
"on",
"max",
"payload",
"size"
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L311-L345 | train |
uber/tchannel-python | tchannel/tornado/message_factory.py | MessageFactory.verify_message | def verify_message(self, message):
"""Verify the checksum of the message."""
if verify_checksum(
message,
self.in_checksum.get(message.id, 0),
):
self.in_checksum[message.id] = message.checksum[1]
if message.flags == FlagsType.none:
... | python | def verify_message(self, message):
"""Verify the checksum of the message."""
if verify_checksum(
message,
self.in_checksum.get(message.id, 0),
):
self.in_checksum[message.id] = message.checksum[1]
if message.flags == FlagsType.none:
... | [
"def",
"verify_message",
"(",
"self",
",",
"message",
")",
":",
"if",
"verify_checksum",
"(",
"message",
",",
"self",
".",
"in_checksum",
".",
"get",
"(",
"message",
".",
"id",
",",
"0",
")",
",",
")",
":",
"self",
".",
"in_checksum",
"[",
"message",
... | Verify the checksum of the message. | [
"Verify",
"the",
"checksum",
"of",
"the",
"message",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L359-L374 | train |
uber/tchannel-python | tchannel/rw.py | chain | def chain(*rws):
"""Build a ReadWriter from the given list of ReadWriters.
.. code-block:: python
chain(
number(1),
number(8),
len_prefixed_string(number(2)),
) # == n1:1 n2:8 s~2
Reads/writes from the given ReadWriters in-order. Returns lists of value... | python | def chain(*rws):
"""Build a ReadWriter from the given list of ReadWriters.
.. code-block:: python
chain(
number(1),
number(8),
len_prefixed_string(number(2)),
) # == n1:1 n2:8 s~2
Reads/writes from the given ReadWriters in-order. Returns lists of value... | [
"def",
"chain",
"(",
"*",
"rws",
")",
":",
"assert",
"rws",
"is",
"not",
"None",
"if",
"len",
"(",
"rws",
")",
"==",
"1",
"and",
"isinstance",
"(",
"rws",
"[",
"0",
"]",
",",
"list",
")",
":",
"rws",
"=",
"rws",
"[",
"0",
"]",
"return",
"Chai... | Build a ReadWriter from the given list of ReadWriters.
.. code-block:: python
chain(
number(1),
number(8),
len_prefixed_string(number(2)),
) # == n1:1 n2:8 s~2
Reads/writes from the given ReadWriters in-order. Returns lists of values
in the same order ... | [
"Build",
"a",
"ReadWriter",
"from",
"the",
"given",
"list",
"of",
"ReadWriters",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/rw.py#L82-L103 | train |
uber/tchannel-python | tchannel/rw.py | ReadWriter.take | def take(self, stream, num):
"""Read the given number of bytes from the stream.
:param stream:
stream to read from
:param num:
number of bytes to read
:raises ReadError:
if the stream did not yield the exact number of bytes expected
"""
... | python | def take(self, stream, num):
"""Read the given number of bytes from the stream.
:param stream:
stream to read from
:param num:
number of bytes to read
:raises ReadError:
if the stream did not yield the exact number of bytes expected
"""
... | [
"def",
"take",
"(",
"self",
",",
"stream",
",",
"num",
")",
":",
"s",
"=",
"stream",
".",
"read",
"(",
"num",
")",
"slen",
"=",
"len",
"(",
"s",
")",
"if",
"slen",
"!=",
"num",
":",
"raise",
"ReadError",
"(",
"\"Expected %d bytes but got %d bytes.\"",
... | Read the given number of bytes from the stream.
:param stream:
stream to read from
:param num:
number of bytes to read
:raises ReadError:
if the stream did not yield the exact number of bytes expected | [
"Read",
"the",
"given",
"number",
"of",
"bytes",
"from",
"the",
"stream",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/rw.py#L266-L282 | train |
uber/tchannel-python | tchannel/thrift/reflection.py | get_service_methods | def get_service_methods(iface):
"""Get a list of methods defined in the interface for a Thrift service.
:param iface:
The Thrift-generated Iface class defining the interface for the
service.
:returns:
A set containing names of the methods defined for the service.
"""
methods... | python | def get_service_methods(iface):
"""Get a list of methods defined in the interface for a Thrift service.
:param iface:
The Thrift-generated Iface class defining the interface for the
service.
:returns:
A set containing names of the methods defined for the service.
"""
methods... | [
"def",
"get_service_methods",
"(",
"iface",
")",
":",
"methods",
"=",
"inspect",
".",
"getmembers",
"(",
"iface",
",",
"predicate",
"=",
"inspect",
".",
"ismethod",
")",
"return",
"set",
"(",
"name",
"for",
"(",
"name",
",",
"method",
")",
"in",
"methods... | Get a list of methods defined in the interface for a Thrift service.
:param iface:
The Thrift-generated Iface class defining the interface for the
service.
:returns:
A set containing names of the methods defined for the service. | [
"Get",
"a",
"list",
"of",
"methods",
"defined",
"in",
"the",
"interface",
"for",
"a",
"Thrift",
"service",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/thrift/reflection.py#L27-L40 | train |
uber/tchannel-python | tchannel/deprecate.py | deprecate | def deprecate(message):
"""Loudly prints warning."""
warnings.simplefilter('default')
warnings.warn(message, category=DeprecationWarning)
warnings.resetwarnings() | python | def deprecate(message):
"""Loudly prints warning."""
warnings.simplefilter('default')
warnings.warn(message, category=DeprecationWarning)
warnings.resetwarnings() | [
"def",
"deprecate",
"(",
"message",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"'default'",
")",
"warnings",
".",
"warn",
"(",
"message",
",",
"category",
"=",
"DeprecationWarning",
")",
"warnings",
".",
"resetwarnings",
"(",
")"
] | Loudly prints warning. | [
"Loudly",
"prints",
"warning",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/deprecate.py#L29-L33 | train |
uber/tchannel-python | tchannel/deprecate.py | deprecated | def deprecated(message):
"""Warn every time a fn is called."""
def decorator(fn):
@functools.wraps(fn)
def new_fn(*args, **kwargs):
deprecate(message)
return fn(*args, **kwargs)
return new_fn
return decorator | python | def deprecated(message):
"""Warn every time a fn is called."""
def decorator(fn):
@functools.wraps(fn)
def new_fn(*args, **kwargs):
deprecate(message)
return fn(*args, **kwargs)
return new_fn
return decorator | [
"def",
"deprecated",
"(",
"message",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"new_fn",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"deprecate",
"(",
"message",
")",
"return",
"f... | Warn every time a fn is called. | [
"Warn",
"every",
"time",
"a",
"fn",
"is",
"called",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/deprecate.py#L36-L44 | train |
uber/tchannel-python | tchannel/thrift/rw.py | load | def load(path, service=None, hostport=None, module_name=None):
"""Loads the Thrift file at the specified path.
The file is compiled in-memory and a Python module containing the result
is returned. It may be used with ``TChannel.thrift``. For example,
.. code-block:: python
from tchannel impor... | python | def load(path, service=None, hostport=None, module_name=None):
"""Loads the Thrift file at the specified path.
The file is compiled in-memory and a Python module containing the result
is returned. It may be used with ``TChannel.thrift``. For example,
.. code-block:: python
from tchannel impor... | [
"def",
"load",
"(",
"path",
",",
"service",
"=",
"None",
",",
"hostport",
"=",
"None",
",",
"module_name",
"=",
"None",
")",
":",
"if",
"not",
"path",
".",
"endswith",
"(",
"'.thrift'",
")",
":",
"service",
",",
"path",
"=",
"path",
",",
"service",
... | Loads the Thrift file at the specified path.
The file is compiled in-memory and a Python module containing the result
is returned. It may be used with ``TChannel.thrift``. For example,
.. code-block:: python
from tchannel import TChannel, thrift
# Load our server's interface definition.
... | [
"Loads",
"the",
"Thrift",
"file",
"at",
"the",
"specified",
"path",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/thrift/rw.py#L40-L154 | train |
uber/tchannel-python | tchannel/net.py | interface_ip | def interface_ip(interface):
"""Determine the IP assigned to us by the given network interface."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(
fcntl.ioctl(
sock.fileno(), 0x8915, struct.pack('256s', interface[:15])
)[20:24]
) | python | def interface_ip(interface):
"""Determine the IP assigned to us by the given network interface."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(
fcntl.ioctl(
sock.fileno(), 0x8915, struct.pack('256s', interface[:15])
)[20:24]
) | [
"def",
"interface_ip",
"(",
"interface",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"return",
"socket",
".",
"inet_ntoa",
"(",
"fcntl",
".",
"ioctl",
"(",
"sock",
".",
"fileno",
... | Determine the IP assigned to us by the given network interface. | [
"Determine",
"the",
"IP",
"assigned",
"to",
"us",
"by",
"the",
"given",
"network",
"interface",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/net.py#L31-L38 | train |
uber/tchannel-python | tchannel/thrift/client.py | client_for | def client_for(service, service_module, thrift_service_name=None):
"""Build a client class for the given Thrift service.
The generated class accepts a TChannel and an optional hostport as
initialization arguments.
Given ``CommentService`` defined in ``comment.thrift`` and registered with
Hyperbahn... | python | def client_for(service, service_module, thrift_service_name=None):
"""Build a client class for the given Thrift service.
The generated class accepts a TChannel and an optional hostport as
initialization arguments.
Given ``CommentService`` defined in ``comment.thrift`` and registered with
Hyperbahn... | [
"def",
"client_for",
"(",
"service",
",",
"service_module",
",",
"thrift_service_name",
"=",
"None",
")",
":",
"assert",
"service_module",
",",
"'service_module is required'",
"service",
"=",
"service",
"or",
"''",
"if",
"not",
"thrift_service_name",
":",
"thrift_se... | Build a client class for the given Thrift service.
The generated class accepts a TChannel and an optional hostport as
initialization arguments.
Given ``CommentService`` defined in ``comment.thrift`` and registered with
Hyperbahn under the name "comment", here's how this may be used:
.. code-block... | [
"Build",
"a",
"client",
"class",
"for",
"the",
"given",
"Thrift",
"service",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/thrift/client.py#L48-L114 | train |
uber/tchannel-python | tchannel/thrift/client.py | generate_method | def generate_method(service_module, service_name, method_name):
"""Generate a method for the given Thrift service.
:param service_module:
Thrift-generated service module
:param service_name:
Name of the Thrift service
:param method_name:
Method being called
"""
assert se... | python | def generate_method(service_module, service_name, method_name):
"""Generate a method for the given Thrift service.
:param service_module:
Thrift-generated service module
:param service_name:
Name of the Thrift service
:param method_name:
Method being called
"""
assert se... | [
"def",
"generate_method",
"(",
"service_module",
",",
"service_name",
",",
"method_name",
")",
":",
"assert",
"service_module",
"assert",
"service_name",
"assert",
"method_name",
"args_type",
"=",
"getattr",
"(",
"service_module",
",",
"method_name",
"+",
"'_args'",
... | Generate a method for the given Thrift service.
:param service_module:
Thrift-generated service module
:param service_name:
Name of the Thrift service
:param method_name:
Method being called | [
"Generate",
"a",
"method",
"for",
"the",
"given",
"Thrift",
"service",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/thrift/client.py#L117-L242 | train |
uber/tchannel-python | tchannel/tornado/peer.py | Peer.connect | def connect(self):
"""Get a connection to this peer.
If an connection to the peer already exists (either incoming or
outgoing), that's returned. Otherwise, a new outgoing connection to
this peer is created.
:return:
A future containing a connection to this host.
... | python | def connect(self):
"""Get a connection to this peer.
If an connection to the peer already exists (either incoming or
outgoing), that's returned. Otherwise, a new outgoing connection to
this peer is created.
:return:
A future containing a connection to this host.
... | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"connections",
":",
"future",
"=",
"gen",
".",
"Future",
"(",
")",
"future",
".",
"set_result",
"(",
"self",
".",
"connections",
"[",
"0",
"]",
")",
"return",
"future",
"if",
"self",
".",
... | Get a connection to this peer.
If an connection to the peer already exists (either incoming or
outgoing), that's returned. Otherwise, a new outgoing connection to
this peer is created.
:return:
A future containing a connection to this host. | [
"Get",
"a",
"connection",
"to",
"this",
"peer",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L135-L174 | train |
uber/tchannel-python | tchannel/tornado/peer.py | Peer.register_outgoing_conn | def register_outgoing_conn(self, conn):
"""Add outgoing connection into the heap."""
assert conn, "conn is required"
conn.set_outbound_pending_change_callback(self._on_conn_change)
self.connections.append(conn)
self._set_on_close_cb(conn)
self._on_conn_change() | python | def register_outgoing_conn(self, conn):
"""Add outgoing connection into the heap."""
assert conn, "conn is required"
conn.set_outbound_pending_change_callback(self._on_conn_change)
self.connections.append(conn)
self._set_on_close_cb(conn)
self._on_conn_change() | [
"def",
"register_outgoing_conn",
"(",
"self",
",",
"conn",
")",
":",
"assert",
"conn",
",",
"\"conn is required\"",
"conn",
".",
"set_outbound_pending_change_callback",
"(",
"self",
".",
"_on_conn_change",
")",
"self",
".",
"connections",
".",
"append",
"(",
"conn... | Add outgoing connection into the heap. | [
"Add",
"outgoing",
"connection",
"into",
"the",
"heap",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L188-L194 | train |
uber/tchannel-python | tchannel/tornado/peer.py | Peer.register_incoming_conn | def register_incoming_conn(self, conn):
"""Add incoming connection into the heap."""
assert conn, "conn is required"
conn.set_outbound_pending_change_callback(self._on_conn_change)
self.connections.appendleft(conn)
self._set_on_close_cb(conn)
self._on_conn_change() | python | def register_incoming_conn(self, conn):
"""Add incoming connection into the heap."""
assert conn, "conn is required"
conn.set_outbound_pending_change_callback(self._on_conn_change)
self.connections.appendleft(conn)
self._set_on_close_cb(conn)
self._on_conn_change() | [
"def",
"register_incoming_conn",
"(",
"self",
",",
"conn",
")",
":",
"assert",
"conn",
",",
"\"conn is required\"",
"conn",
".",
"set_outbound_pending_change_callback",
"(",
"self",
".",
"_on_conn_change",
")",
"self",
".",
"connections",
".",
"appendleft",
"(",
"... | Add incoming connection into the heap. | [
"Add",
"incoming",
"connection",
"into",
"the",
"heap",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L196-L202 | train |
uber/tchannel-python | tchannel/tornado/peer.py | Peer.outgoing_connections | def outgoing_connections(self):
"""Returns a list of all outgoing connections for this peer."""
# Outgoing connections are on the right
return list(
dropwhile(lambda c: c.direction != OUTGOING, self.connections)
) | python | def outgoing_connections(self):
"""Returns a list of all outgoing connections for this peer."""
# Outgoing connections are on the right
return list(
dropwhile(lambda c: c.direction != OUTGOING, self.connections)
) | [
"def",
"outgoing_connections",
"(",
"self",
")",
":",
"return",
"list",
"(",
"dropwhile",
"(",
"lambda",
"c",
":",
"c",
".",
"direction",
"!=",
"OUTGOING",
",",
"self",
".",
"connections",
")",
")"
] | Returns a list of all outgoing connections for this peer. | [
"Returns",
"a",
"list",
"of",
"all",
"outgoing",
"connections",
"for",
"this",
"peer",
"."
] | ee08cce6234f24fd2373774988186dd374306c43 | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L215-L221 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.