Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
fake_print
(*args, **kwargs)
Dummy replacement for print() that does nothing
Dummy replacement for print() that does nothing
def fake_print(*args, **kwargs): """Dummy replacement for print() that does nothing""" pass
[ "def", "fake_print", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pass" ]
[ 15, 0 ]
[ 17, 8 ]
python
en
['en', 'en', 'en']
True
pytest_collect_file
(parent, path)
Collect all file suitable for use in tests
Collect all file suitable for use in tests
def pytest_collect_file(parent, path): """Collect all file suitable for use in tests""" if path.basename == "README.md": return ReadmeFile.from_parent(parent, fspath=path)
[ "def", "pytest_collect_file", "(", "parent", ",", "path", ")", ":", "if", "path", ".", "basename", "==", "\"README.md\"", ":", "return", "ReadmeFile", ".", "from_parent", "(", "parent", ",", "fspath", "=", "path", ")" ]
[ 20, 0 ]
[ 23, 58 ]
python
en
['en', 'en', 'en']
True
_with_patched_sleep
(func, *args, **kwargs)
Patch the sleep function so that it does nothing
Patch the sleep function so that it does nothing
def _with_patched_sleep(func, *args, **kwargs): """Patch the sleep function so that it does nothing""" _sleep = time.sleep time.sleep = lambda *args: None try: return func(*args, **kwargs) finally: time.sleep = _sleep
[ "def", "_with_patched_sleep", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_sleep", "=", "time", ".", "sleep", "time", ".", "sleep", "=", "lambda", "*", "args", ":", "None", "try", ":", "return", "func", "(", "*", "args", ",",...
[ 38, 0 ]
[ 45, 27 ]
python
en
['en', 'en', 'en']
True
ReadmeFile.collect
(self)
Collect all code snippets
Collect all code snippets
def collect(self): """Collect all code snippets""" raw_text = self.fspath.open().read() for idx, code in enumerate(code_rxp.findall(raw_text), 1): yield ReadmeItem.from_parent( self, name=str(idx), spec=code.strip() )
[ "def", "collect", "(", "self", ")", ":", "raw_text", "=", "self", ".", "fspath", ".", "open", "(", ")", ".", "read", "(", ")", "for", "idx", ",", "code", "in", "enumerate", "(", "code_rxp", ".", "findall", "(", "raw_text", ")", ",", "1", ")", ":"...
[ 29, 4 ]
[ 35, 13 ]
python
en
['en', 'en', 'en']
True
ReadmeItem.runtest
(self)
Run the test
Run the test
def runtest(self): """Run the test""" builtins = dict(self.builtins) byte_code = compile(self.spec, '<inline>', 'exec') _with_patched_sleep(exec, byte_code, builtins) msg, _, error = api.run(['--no-color-output', '-c', self.spec]) if error: # Ignore missing er...
[ "def", "runtest", "(", "self", ")", ":", "builtins", "=", "dict", "(", "self", ".", "builtins", ")", "byte_code", "=", "compile", "(", "self", ".", "spec", ",", "'<inline>'", ",", "'exec'", ")", "_with_patched_sleep", "(", "exec", ",", "byte_code", ",", ...
[ 61, 4 ]
[ 73, 46 ]
python
en
['en', 'gd', 'en']
True
ReadmeItem.repr_failure
(self, excinfo, **kwargs)
called when self.runtest() raises an exception.
called when self.runtest() raises an exception.
def repr_failure(self, excinfo, **kwargs): """ called when self.runtest() raises an exception. """ return ( f"Code snippet {self.name} raised an error: {excinfo.value}. " f"The executed code was: {self.spec}" )
[ "def", "repr_failure", "(", "self", ",", "excinfo", ",", "*", "*", "kwargs", ")", ":", "return", "(", "f\"Code snippet {self.name} raised an error: {excinfo.value}. \"", "f\"The executed code was: {self.spec}\"", ")" ]
[ 75, 4 ]
[ 80, 9 ]
python
en
['en', 'en', 'en']
True
ReadmeItem.reportinfo
(self)
Report some basic information on the test outcome
Report some basic information on the test outcome
def reportinfo(self): """Report some basic information on the test outcome""" return self.fspath, 0, "usecase: {}".format(self.name)
[ "def", "reportinfo", "(", "self", ")", ":", "return", "self", ".", "fspath", ",", "0", ",", "\"usecase: {}\"", ".", "format", "(", "self", ".", "name", ")" ]
[ 82, 4 ]
[ 84, 62 ]
python
en
['en', 'en', 'en']
True
wrap_qat_forward_context
( quant_cb, model: pl.core.LightningModule, func: Callable, trigger_condition: Optional[Union[Callable, int]] = None )
Decorator to wrap forward path as it is needed to quantize inputs and dequantize outputs for in/out compatibility Moreover this version has the (de)quantization conditional as it may not be needed for the training all the time
Decorator to wrap forward path as it is needed to quantize inputs and dequantize outputs for in/out compatibility Moreover this version has the (de)quantization conditional as it may not be needed for the training all the time
def wrap_qat_forward_context( quant_cb, model: pl.core.LightningModule, func: Callable, trigger_condition: Optional[Union[Callable, int]] = None ) -> Callable: """ Decorator to wrap forward path as it is needed to quantize inputs and dequantize outputs for in/out compatibility Moreover this ...
[ "def", "wrap_qat_forward_context", "(", "quant_cb", ",", "model", ":", "pl", ".", "core", ".", "LightningModule", ",", "func", ":", "Callable", ",", "trigger_condition", ":", "Optional", "[", "Union", "[", "Callable", ",", "int", "]", "]", "=", "None", ")"...
[ 30, 0 ]
[ 56, 18 ]
python
en
['en', 'error', 'th']
False
wrap_quantize_forward_context
(model: pl.core.LightningModule, func: Callable)
Decorator to wrap forward path as it is needed to quantize inputs and dequantize outputs for in/out compatibility
Decorator to wrap forward path as it is needed to quantize inputs and dequantize outputs for in/out compatibility
def wrap_quantize_forward_context(model: pl.core.LightningModule, func: Callable) -> Callable: """ Decorator to wrap forward path as it is needed to quantize inputs and dequantize outputs for in/out compatibility """ # todo: consider using registering hook before/after forward @functools.wraps(func)...
[ "def", "wrap_quantize_forward_context", "(", "model", ":", "pl", ".", "core", ".", "LightningModule", ",", "func", ":", "Callable", ")", "->", "Callable", ":", "# todo: consider using registering hook before/after forward", "@", "functools", ".", "wraps", "(", "func",...
[ 59, 0 ]
[ 71, 18 ]
python
en
['en', 'error', 'th']
False
_recursive_hasattr
(obj: Any, attribs: str, state: bool = True)
recursive check if model has some layers denoted with '.
recursive check if model has some layers denoted with '.
def _recursive_hasattr(obj: Any, attribs: str, state: bool = True) -> bool: """recursive check if model has some layers denoted with '.'""" if '.' in attribs: attrib, attribs = attribs.split('.', 1) if hasattr(obj, attrib): return _recursive_hasattr(getattr(obj, attrib), attribs, sta...
[ "def", "_recursive_hasattr", "(", "obj", ":", "Any", ",", "attribs", ":", "str", ",", "state", ":", "bool", "=", "True", ")", "->", "bool", ":", "if", "'.'", "in", "attribs", ":", "attrib", ",", "attribs", "=", "attribs", ".", "split", "(", "'.'", ...
[ 74, 0 ]
[ 81, 42 ]
python
en
['en', 'en', 'en']
True
QuantizationAwareTraining.__init__
( self, qconfig: Union[str, QConfig] = 'fbgemm', observer_type: str = "average", collect_quantization: Optional[Union[int, Callable]] = None, modules_to_fuse: Optional[Sequence] = None, input_compatible: bool = True, )
Quantization allows speeding up inference and decreasing memory requirements by performing computations and storing tensors at lower bitwidths (such as INT8 or FLOAT16) than floating point precision. We use native PyTorch API so for more information see `Quantization <https://py...
Quantization allows speeding up inference and decreasing memory requirements by performing computations and storing tensors at lower bitwidths (such as INT8 or FLOAT16) than floating point precision. We use native PyTorch API so for more information see `Quantization <https://py...
def __init__( self, qconfig: Union[str, QConfig] = 'fbgemm', observer_type: str = "average", collect_quantization: Optional[Union[int, Callable]] = None, modules_to_fuse: Optional[Sequence] = None, input_compatible: bool = True, ) -> None: """ Quantiza...
[ "def", "__init__", "(", "self", ",", "qconfig", ":", "Union", "[", "str", ",", "QConfig", "]", "=", "'fbgemm'", ",", "observer_type", ":", "str", "=", "\"average\"", ",", "collect_quantization", ":", "Optional", "[", "Union", "[", "int", ",", "Callable", ...
[ 87, 4 ]
[ 162, 31 ]
python
en
['en', 'error', 'th']
False
run_and_parse_first_match
(run_lambda, command, regex)
Runs command using run_lambda, returns the first regex match if it exists
Runs command using run_lambda, returns the first regex match if it exists
def run_and_parse_first_match(run_lambda, command, regex): """Runs command using run_lambda, returns the first regex match if it exists""" rc, out, _ = run_lambda(command) if rc != 0: return None match = re.search(regex, out) if match is None: return None return match.group(1)
[ "def", "run_and_parse_first_match", "(", "run_lambda", ",", "command", ",", "regex", ")", ":", "rc", ",", "out", ",", "_", "=", "run_lambda", "(", "command", ")", "if", "rc", "!=", "0", ":", "return", "None", "match", "=", "re", ".", "search", "(", "...
[ 35, 0 ]
[ 43, 25 ]
python
en
['en', 'lb', 'en']
True
test_model_saves_with_input_sample
(tmpdir)
Test that ONNX model saves with input sample and size is greater than 3 MB
Test that ONNX model saves with input sample and size is greater than 3 MB
def test_model_saves_with_input_sample(tmpdir): """Test that ONNX model saves with input sample and size is greater than 3 MB""" model = BoringModel() trainer = Trainer(fast_dev_run=True) trainer.fit(model) file_path = os.path.join(tmpdir, "model.onnx") input_sample = torch.randn((1, 32)) m...
[ "def", "test_model_saves_with_input_sample", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "trainer", "=", "Trainer", "(", "fast_dev_run", "=", "True", ")", "trainer", ".", "fit", "(", "model", ")", "file_path", "=", "os", ".", "path", "....
[ 26, 0 ]
[ 36, 43 ]
python
en
['en', 'en', 'en']
True
test_model_saves_on_gpu
(tmpdir)
Test that model saves on gpu
Test that model saves on gpu
def test_model_saves_on_gpu(tmpdir): """Test that model saves on gpu""" model = BoringModel() trainer = Trainer(gpus=1, fast_dev_run=True) trainer.fit(model) file_path = os.path.join(tmpdir, "model.onnx") input_sample = torch.randn((1, 32)) model.to_onnx(file_path, input_sample) assert ...
[ "def", "test_model_saves_on_gpu", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "trainer", "=", "Trainer", "(", "gpus", "=", "1", ",", "fast_dev_run", "=", "True", ")", "trainer", ".", "fit", "(", "model", ")", "file_path", "=", "os", ...
[ 40, 0 ]
[ 50, 43 ]
python
en
['en', 'ig', 'en']
True
test_model_saves_with_example_output
(tmpdir)
Test that ONNX model saves when provided with example output
Test that ONNX model saves when provided with example output
def test_model_saves_with_example_output(tmpdir): """Test that ONNX model saves when provided with example output""" model = BoringModel() trainer = Trainer(fast_dev_run=True) trainer.fit(model) file_path = os.path.join(tmpdir, "model.onnx") input_sample = torch.randn((1, 32)) model.eval() ...
[ "def", "test_model_saves_with_example_output", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "trainer", "=", "Trainer", "(", "fast_dev_run", "=", "True", ")", "trainer", ".", "fit", "(", "model", ")", "file_path", "=", "os", ".", "path", ...
[ 53, 0 ]
[ 64, 44 ]
python
en
['en', 'en', 'en']
True
test_model_saves_with_example_input_array
(tmpdir)
Test that ONNX model saves with_example_input_array and size is greater than 3 MB
Test that ONNX model saves with_example_input_array and size is greater than 3 MB
def test_model_saves_with_example_input_array(tmpdir): """Test that ONNX model saves with_example_input_array and size is greater than 3 MB""" model = BoringModel() model.example_input_array = torch.randn(5, 32) file_path = os.path.join(tmpdir, "model.onnx") model.to_onnx(file_path) assert os.p...
[ "def", "test_model_saves_with_example_input_array", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "model", ".", "example_input_array", "=", "torch", ".", "randn", "(", "5", ",", "32", ")", "file_path", "=", "os", ".", "path", ".", "join", ...
[ 67, 0 ]
[ 75, 43 ]
python
en
['en', 'en', 'en']
True
test_model_saves_on_multi_gpu
(tmpdir)
Test that ONNX model saves on a distributed backend
Test that ONNX model saves on a distributed backend
def test_model_saves_on_multi_gpu(tmpdir): """Test that ONNX model saves on a distributed backend""" tutils.set_random_master_port() trainer_options = dict( default_root_dir=tmpdir, max_epochs=1, limit_train_batches=10, limit_val_batches=10, gpus=[0, 1], acce...
[ "def", "test_model_saves_on_multi_gpu", "(", "tmpdir", ")", ":", "tutils", ".", "set_random_master_port", "(", ")", "trainer_options", "=", "dict", "(", "default_root_dir", "=", "tmpdir", ",", "max_epochs", "=", "1", ",", "limit_train_batches", "=", "10", ",", "...
[ 79, 0 ]
[ 100, 44 ]
python
en
['en', 'en', 'en']
True
test_verbose_param
(tmpdir, capsys)
Test that output is present when verbose parameter is set
Test that output is present when verbose parameter is set
def test_verbose_param(tmpdir, capsys): """Test that output is present when verbose parameter is set""" model = BoringModel() model.example_input_array = torch.randn(5, 32) file_path = os.path.join(tmpdir, "model.onnx") model.to_onnx(file_path, verbose=True) captured = capsys.readouterr() a...
[ "def", "test_verbose_param", "(", "tmpdir", ",", "capsys", ")", ":", "model", "=", "BoringModel", "(", ")", "model", ".", "example_input_array", "=", "torch", ".", "randn", "(", "5", ",", "32", ")", "file_path", "=", "os", ".", "path", ".", "join", "("...
[ 103, 0 ]
[ 111, 36 ]
python
en
['en', 'en', 'en']
True
test_error_if_no_input
(tmpdir)
Test that an error is thrown when there is no input tensor
Test that an error is thrown when there is no input tensor
def test_error_if_no_input(tmpdir): """Test that an error is thrown when there is no input tensor""" model = BoringModel() model.example_input_array = None file_path = os.path.join(tmpdir, "model.onnx") with pytest.raises( ValueError, match=r'Could not export to ONNX since neither `i...
[ "def", "test_error_if_no_input", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "model", ".", "example_input_array", "=", "None", "file_path", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "\"model.onnx\"", ")", "with", "pytest", ...
[ 114, 0 ]
[ 124, 32 ]
python
en
['en', 'en', 'en']
True
test_if_inference_output_is_valid
(tmpdir)
Test that the output inferred from ONNX model is same as from PyTorch
Test that the output inferred from ONNX model is same as from PyTorch
def test_if_inference_output_is_valid(tmpdir): """Test that the output inferred from ONNX model is same as from PyTorch""" model = BoringModel() model.example_input_array = torch.randn(5, 32) trainer = Trainer(fast_dev_run=True) trainer.fit(model) model.eval() with torch.no_grad(): ...
[ "def", "test_if_inference_output_is_valid", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "model", ".", "example_input_array", "=", "torch", ".", "randn", "(", "5", ",", "32", ")", "trainer", "=", "Trainer", "(", "fast_dev_run", "=", "True"...
[ 127, 0 ]
[ 152, 80 ]
python
en
['en', 'en', 'en']
True
add_hide_option
(options)
Mark message/enum/field/enum value as hidden. Hidden messages are ignored when generating output. Args: options: MessageOptions/EnumOptions/FieldOptions/EnumValueOptions message.
Mark message/enum/field/enum value as hidden.
def add_hide_option(options): """Mark message/enum/field/enum value as hidden. Hidden messages are ignored when generating output. Args: options: MessageOptions/EnumOptions/FieldOptions/EnumValueOptions message. """ hide_option = options.uninterpreted_option.add() hide_option.name.add(...
[ "def", "add_hide_option", "(", "options", ")", ":", "hide_option", "=", "options", ".", "uninterpreted_option", ".", "add", "(", ")", "hide_option", ".", "name", ".", "add", "(", ")", ".", "name_part", "=", "'protoxform_hide'" ]
[ 5, 0 ]
[ 14, 56 ]
python
en
['en', 'lb', 'en']
True
has_hide_option
(options)
Is message/enum/field/enum value hidden? Hidden messages are ignored when generating output. Args: options: MessageOptions/EnumOptions/FieldOptions/EnumValueOptions message. Returns: Hidden status.
Is message/enum/field/enum value hidden?
def has_hide_option(options): """Is message/enum/field/enum value hidden? Hidden messages are ignored when generating output. Args: options: MessageOptions/EnumOptions/FieldOptions/EnumValueOptions message. Returns: Hidden status. """ return any( option.name[0].name_par...
[ "def", "has_hide_option", "(", "options", ")", ":", "return", "any", "(", "option", ".", "name", "[", "0", "]", ".", "name_part", "==", "'protoxform_hide'", "for", "option", "in", "options", ".", "uninterpreted_option", ")" ]
[ 17, 0 ]
[ 28, 97 ]
python
de
['de', 'de', 'en']
True
set_versioning_annotation
(options, previous_message_type)
Set the udpa.annotations.versioning option. Used by Envoy to chain back through the message type history. Args: options: MessageOptions message. previous_message_type: string with earlier API type name for the message.
Set the udpa.annotations.versioning option.
def set_versioning_annotation(options, previous_message_type): """Set the udpa.annotations.versioning option. Used by Envoy to chain back through the message type history. Args: options: MessageOptions message. previous_message_type: string with earlier API type name for the message. "...
[ "def", "set_versioning_annotation", "(", "options", ",", "previous_message_type", ")", ":", "options", ".", "Extensions", "[", "versioning_pb2", ".", "versioning", "]", ".", "previous_message_type", "=", "previous_message_type" ]
[ 31, 0 ]
[ 40, 95 ]
python
en
['en', 'en', 'en']
True
get_versioning_annotation
(options)
Get the udpa.annotations.versioning option. Used by Envoy to chain back through the message type history. Args: options: MessageOptions message. Returns: versioning.Annotation if set otherwise None.
Get the udpa.annotations.versioning option.
def get_versioning_annotation(options): """Get the udpa.annotations.versioning option. Used by Envoy to chain back through the message type history. Args: options: MessageOptions message. Returns: versioning.Annotation if set otherwise None. """ if not options.HasExtension(vers...
[ "def", "get_versioning_annotation", "(", "options", ")", ":", "if", "not", "options", ".", "HasExtension", "(", "versioning_pb2", ".", "versioning", ")", ":", "return", "None", "return", "options", ".", "Extensions", "[", "versioning_pb2", ".", "versioning", "]"...
[ 43, 0 ]
[ 55, 56 ]
python
en
['en', 'en', 'en']
True
_new_duck_type_and_implements
()
Create a duck array type and implements functions.
Create a duck array type and implements functions.
def _new_duck_type_and_implements(): """Create a duck array type and implements functions.""" HANDLED_FUNCTIONS = {} class MyArray(object): def __array_function__(self, func, types, args, kwargs): if func not in HANDLED_FUNCTIONS: return NotImplemented if not...
[ "def", "_new_duck_type_and_implements", "(", ")", ":", "HANDLED_FUNCTIONS", "=", "{", "}", "class", "MyArray", "(", "object", ")", ":", "def", "__array_function__", "(", "self", ",", "func", ",", "types", ",", "args", ",", "kwargs", ")", ":", "if", "func",...
[ 281, 0 ]
[ 300, 32 ]
python
en
['en', 'en', 'en']
True
poly
(seq_of_zeros)
Find the coefficients of a polynomial with the given sequence of roots. Returns the coefficients of the polynomial whose leading coefficient is one for the given sequence of zeros (multiple roots must be included in the sequence as many times as their multiplicity; see Examples). A square matrix (...
Find the coefficients of a polynomial with the given sequence of roots.
def poly(seq_of_zeros): """ Find the coefficients of a polynomial with the given sequence of roots. Returns the coefficients of the polynomial whose leading coefficient is one for the given sequence of zeros (multiple roots must be included in the sequence as many times as their multiplicity; see E...
[ "def", "poly", "(", "seq_of_zeros", ")", ":", "seq_of_zeros", "=", "atleast_1d", "(", "seq_of_zeros", ")", "sh", "=", "seq_of_zeros", ".", "shape", "if", "len", "(", "sh", ")", "==", "2", "and", "sh", "[", "0", "]", "==", "sh", "[", "1", "]", "and"...
[ 46, 0 ]
[ 160, 12 ]
python
en
['en', 'error', 'th']
False
roots
(p)
Return the roots of a polynomial with coefficients given in p. The values in the rank-1 array `p` are coefficients of a polynomial. If the length of `p` is n+1 then the polynomial is described by:: p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] Parameters ---------- p : array_li...
Return the roots of a polynomial with coefficients given in p.
def roots(p): """ Return the roots of a polynomial with coefficients given in p. The values in the rank-1 array `p` are coefficients of a polynomial. If the length of `p` is n+1 then the polynomial is described by:: p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] Parameters ------...
[ "def", "roots", "(", "p", ")", ":", "# If input is scalar, this makes it an array", "p", "=", "atleast_1d", "(", "p", ")", "if", "p", ".", "ndim", "!=", "1", ":", "raise", "ValueError", "(", "\"Input must be a rank-1 array.\"", ")", "# find non-zero array entries", ...
[ 168, 0 ]
[ 250, 16 ]
python
en
['en', 'error', 'th']
False
polyint
(p, m=1, k=None)
Return an antiderivative (indefinite integral) of a polynomial. The returned order `m` antiderivative `P` of polynomial `p` satisfies :math:`\\frac{d^m}{dx^m}P(x) = p(x)` and is defined up to `m - 1` integration constants `k`. The constants determine the low-order polynomial part .. math:: \\...
Return an antiderivative (indefinite integral) of a polynomial.
def polyint(p, m=1, k=None): """ Return an antiderivative (indefinite integral) of a polynomial. The returned order `m` antiderivative `P` of polynomial `p` satisfies :math:`\\frac{d^m}{dx^m}P(x) = p(x)` and is defined up to `m - 1` integration constants `k`. The constants determine the low-order ...
[ "def", "polyint", "(", "p", ",", "m", "=", "1", ",", "k", "=", "None", ")", ":", "m", "=", "int", "(", "m", ")", "if", "m", "<", "0", ":", "raise", "ValueError", "(", "\"Order of integral must be positive (see polyder)\"", ")", "if", "k", "is", "None...
[ 258, 0 ]
[ 349, 18 ]
python
en
['en', 'error', 'th']
False
polyder
(p, m=1)
Return the derivative of the specified order of a polynomial. Parameters ---------- p : poly1d or sequence Polynomial to differentiate. A sequence is interpreted as polynomial coefficients, see `poly1d`. m : int, optional Order of differentiation (default: 1) Returns ...
Return the derivative of the specified order of a polynomial.
def polyder(p, m=1): """ Return the derivative of the specified order of a polynomial. Parameters ---------- p : poly1d or sequence Polynomial to differentiate. A sequence is interpreted as polynomial coefficients, see `poly1d`. m : int, optional Order of differentiation...
[ "def", "polyder", "(", "p", ",", "m", "=", "1", ")", ":", "m", "=", "int", "(", "m", ")", "if", "m", "<", "0", ":", "raise", "ValueError", "(", "\"Order of derivative must be positive (see polyint)\"", ")", "truepoly", "=", "isinstance", "(", "p", ",", ...
[ 357, 0 ]
[ 423, 14 ]
python
en
['en', 'error', 'th']
False
polyfit
(x, y, deg, rcond=None, full=False, w=None, cov=False)
Least squares polynomial fit. Fit a polynomial ``p(x) = p[0] * x**deg + ... + p[deg]`` of degree `deg` to points `(x, y)`. Returns a vector of coefficients `p` that minimises the squared error in the order `deg`, `deg-1`, ... `0`. The `Polynomial.fit <numpy.polynomial.polynomial.Polynomial.fit>` ...
Least squares polynomial fit.
def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): """ Least squares polynomial fit. Fit a polynomial ``p(x) = p[0] * x**deg + ... + p[deg]`` of degree `deg` to points `(x, y)`. Returns a vector of coefficients `p` that minimises the squared error in the order `deg`, `deg-1`, ... `0...
[ "def", "polyfit", "(", "x", ",", "y", ",", "deg", ",", "rcond", "=", "None", ",", "full", "=", "False", ",", "w", "=", "None", ",", "cov", "=", "False", ")", ":", "order", "=", "int", "(", "deg", ")", "+", "1", "x", "=", "NX", ".", "asarray...
[ 431, 0 ]
[ 659, 16 ]
python
en
['en', 'error', 'th']
False
polyval
(p, x)
Evaluate a polynomial at specific values. If `p` is of length N, this function returns the value: ``p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]`` If `x` is a sequence, then `p(x)` is returned for each element of `x`. If `x` is another polynomial then the composite polynomial `p(x...
Evaluate a polynomial at specific values.
def polyval(p, x): """ Evaluate a polynomial at specific values. If `p` is of length N, this function returns the value: ``p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]`` If `x` is a sequence, then `p(x)` is returned for each element of `x`. If `x` is another polynomial then the...
[ "def", "polyval", "(", "p", ",", "x", ")", ":", "p", "=", "NX", ".", "asarray", "(", "p", ")", "if", "isinstance", "(", "x", ",", "poly1d", ")", ":", "y", "=", "0", "else", ":", "x", "=", "NX", ".", "asanyarray", "(", "x", ")", "y", "=", ...
[ 667, 0 ]
[ 736, 12 ]
python
en
['en', 'error', 'th']
False
polyadd
(a1, a2)
Find the sum of two polynomials. Returns the polynomial resulting from the sum of two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree. Parameters ---------- a1, a2 : array_like or poly1d object ...
Find the sum of two polynomials.
def polyadd(a1, a2): """ Find the sum of two polynomials. Returns the polynomial resulting from the sum of two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree. Parameters ---------- a1, a2 : array_l...
[ "def", "polyadd", "(", "a1", ",", "a2", ")", ":", "truepoly", "=", "(", "isinstance", "(", "a1", ",", "poly1d", ")", "or", "isinstance", "(", "a2", ",", "poly1d", ")", ")", "a1", "=", "atleast_1d", "(", "a1", ")", "a2", "=", "atleast_1d", "(", "a...
[ 744, 0 ]
[ 802, 14 ]
python
en
['en', 'error', 'th']
False
polysub
(a1, a2)
Difference (subtraction) of two polynomials. Given two polynomials `a1` and `a2`, returns ``a1 - a2``. `a1` and `a2` can be either array_like sequences of the polynomials' coefficients (including coefficients equal to zero), or `poly1d` objects. Parameters ---------- a1, a2 : array_like o...
Difference (subtraction) of two polynomials.
def polysub(a1, a2): """ Difference (subtraction) of two polynomials. Given two polynomials `a1` and `a2`, returns ``a1 - a2``. `a1` and `a2` can be either array_like sequences of the polynomials' coefficients (including coefficients equal to zero), or `poly1d` objects. Parameters --------...
[ "def", "polysub", "(", "a1", ",", "a2", ")", ":", "truepoly", "=", "(", "isinstance", "(", "a1", ",", "poly1d", ")", "or", "isinstance", "(", "a2", ",", "poly1d", ")", ")", "a1", "=", "atleast_1d", "(", "a1", ")", "a2", "=", "atleast_1d", "(", "a...
[ 806, 0 ]
[ 850, 14 ]
python
en
['en', 'error', 'th']
False
polymul
(a1, a2)
Find the product of two polynomials. Finds the polynomial resulting from the multiplication of the two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree. Parameters ---------- a1, a2 : array_like or poly...
Find the product of two polynomials.
def polymul(a1, a2): """ Find the product of two polynomials. Finds the polynomial resulting from the multiplication of the two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree. Parameters ---------- ...
[ "def", "polymul", "(", "a1", ",", "a2", ")", ":", "truepoly", "=", "(", "isinstance", "(", "a1", ",", "poly1d", ")", "or", "isinstance", "(", "a2", ",", "poly1d", ")", ")", "a1", ",", "a2", "=", "poly1d", "(", "a1", ")", ",", "poly1d", "(", "a2...
[ 854, 0 ]
[ 907, 14 ]
python
en
['en', 'error', 'th']
False
polydiv
(u, v)
Returns the quotient and remainder of polynomial division. The input arrays are the coefficients (including any coefficients equal to zero) of the "numerator" (dividend) and "denominator" (divisor) polynomials, respectively. Parameters ---------- u : array_like or poly1d Dividend ...
Returns the quotient and remainder of polynomial division.
def polydiv(u, v): """ Returns the quotient and remainder of polynomial division. The input arrays are the coefficients (including any coefficients equal to zero) of the "numerator" (dividend) and "denominator" (divisor) polynomials, respectively. Parameters ---------- u : array_like o...
[ "def", "polydiv", "(", "u", ",", "v", ")", ":", "truepoly", "=", "(", "isinstance", "(", "u", ",", "poly1d", ")", "or", "isinstance", "(", "u", ",", "poly1d", ")", ")", "u", "=", "atleast_1d", "(", "u", ")", "+", "0.0", "v", "=", "atleast_1d", ...
[ 915, 0 ]
[ 978, 15 ]
python
en
['en', 'error', 'th']
False
mean_squared_error
(preds: torch.Tensor, target: torch.Tensor)
Computes mean squared error Args: preds: estimated labels target: ground truth labels Return: Tensor with MSE Example: >>> from pytorch_lightning.metrics.functional import mean_squared_error >>> x = torch.tensor([0., 1, 2, 3]) >>> y = torch.tensor([0.,...
Computes mean squared error
def mean_squared_error(preds: torch.Tensor, target: torch.Tensor) -> torch.Tensor: """ Computes mean squared error Args: preds: estimated labels target: ground truth labels Return: Tensor with MSE Example: >>> from pytorch_lightning.metrics.functional import mean_s...
[ "def", "mean_squared_error", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "sum_squared_error", ",", "n_obs", "=", "_mean_squared_error_update", "(", "preds", ",", "target", ")"...
[ 31, 0 ]
[ 50, 64 ]
python
en
['en', 'error', 'th']
False
parse_cmd
()
Parses the command-line arguments. libfile, deffile = parse_cmd()
Parses the command-line arguments.
def parse_cmd(): """Parses the command-line arguments. libfile, deffile = parse_cmd()""" if len(sys.argv) == 3: if sys.argv[1][-4:] == '.lib' and sys.argv[2][-4:] == '.def': libfile, deffile = sys.argv[1:] elif sys.argv[1][-4:] == '.def' and sys.argv[2][-4:] == '.lib': d...
[ "def", "parse_cmd", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "==", "3", ":", "if", "sys", ".", "argv", "[", "1", "]", "[", "-", "4", ":", "]", "==", "'.lib'", "and", "sys", ".", "argv", "[", "2", "]", "[", "-", "4", ":", ...
[ 39, 0 ]
[ 61, 27 ]
python
en
['en', 'fr', 'en']
True
getnm
(nm_cmd = ['nm', '-Cs', 'python%s.lib' % py_ver])
Returns the output of nm_cmd via a pipe. nm_output = getnam(nm_cmd = 'nm -Cs py_lib')
Returns the output of nm_cmd via a pipe.
def getnm(nm_cmd = ['nm', '-Cs', 'python%s.lib' % py_ver]): """Returns the output of nm_cmd via a pipe. nm_output = getnam(nm_cmd = 'nm -Cs py_lib')""" f = subprocess.Popen(nm_cmd, shell=True, stdout=subprocess.PIPE, universal_newlines=True) nm_output = f.stdout.read() f.stdout.close() return nm_ou...
[ "def", "getnm", "(", "nm_cmd", "=", "[", "'nm'", ",", "'-Cs'", ",", "'python%s.lib'", "%", "py_ver", "]", ")", ":", "f", "=", "subprocess", ".", "Popen", "(", "nm_cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", ...
[ 63, 0 ]
[ 70, 20 ]
python
en
['en', 'en', 'en']
True
parse_nm
(nm_output)
Returns a tuple of lists: dlist for the list of data symbols and flist for the list of function symbols. dlist, flist = parse_nm(nm_output)
Returns a tuple of lists: dlist for the list of data symbols and flist for the list of function symbols.
def parse_nm(nm_output): """Returns a tuple of lists: dlist for the list of data symbols and flist for the list of function symbols. dlist, flist = parse_nm(nm_output)""" data = DATA_RE.findall(nm_output) func = FUNC_RE.findall(nm_output) flist = [] for sym in data: if sym in func and (sym...
[ "def", "parse_nm", "(", "nm_output", ")", ":", "data", "=", "DATA_RE", ".", "findall", "(", "nm_output", ")", "func", "=", "FUNC_RE", ".", "findall", "(", "nm_output", ")", "flist", "=", "[", "]", "for", "sym", "in", "data", ":", "if", "sym", "in", ...
[ 72, 0 ]
[ 92, 23 ]
python
en
['en', 'en', 'en']
True
output_def
(dlist, flist, header, file = sys.stdout)
Outputs the final DEF file to a file defaulting to stdout. output_def(dlist, flist, header, file = sys.stdout)
Outputs the final DEF file to a file defaulting to stdout.
def output_def(dlist, flist, header, file = sys.stdout): """Outputs the final DEF file to a file defaulting to stdout. output_def(dlist, flist, header, file = sys.stdout)""" for data_sym in dlist: header = header + '\t%s DATA\n' % data_sym header = header + '\n' # blank line for func_sym in fli...
[ "def", "output_def", "(", "dlist", ",", "flist", ",", "header", ",", "file", "=", "sys", ".", "stdout", ")", ":", "for", "data_sym", "in", "dlist", ":", "header", "=", "header", "+", "'\\t%s DATA\\n'", "%", "data_sym", "header", "=", "header", "+", "'\...
[ 94, 0 ]
[ 103, 22 ]
python
en
['en', 'en', 'en']
True
test_result_reduce_ddp
()
Make sure result logging works with DDP
Make sure result logging works with DDP
def test_result_reduce_ddp(): """Make sure result logging works with DDP""" tutils.reset_seed() tutils.set_random_master_port() worldsize = 2 mp.spawn(_ddp_test_fn, args=(worldsize, ), nprocs=worldsize)
[ "def", "test_result_reduce_ddp", "(", ")", ":", "tutils", ".", "reset_seed", "(", ")", "tutils", ".", "set_random_master_port", "(", ")", "worldsize", "=", "2", "mp", ".", "spawn", "(", "_ddp_test_fn", ",", "args", "=", "(", "worldsize", ",", ")", ",", "...
[ 93, 0 ]
[ 99, 64 ]
python
en
['en', 'da', 'en']
True
is_free_format
(file)
Check if file is in free format Fortran.
Check if file is in free format Fortran.
def is_free_format(file): """Check if file is in free format Fortran.""" # f90 allows both fixed and free format, assuming fixed unless # signs of free format are detected. result = 0 with open(file, 'r') as f: line = f.readline() n = 15 # the number of non-comment lines to scan for...
[ "def", "is_free_format", "(", "file", ")", ":", "# f90 allows both fixed and free format, assuming fixed unless", "# signs of free format are detected.", "result", "=", "0", "with", "open", "(", "file", ",", "'r'", ")", "as", "f", ":", "line", "=", "f", ".", "readli...
[ 305, 0 ]
[ 325, 17 ]
python
en
['en', 'en', 'en']
True
readfortrancode
(ffile, dowithline=show, istop=1)
Read fortran codes from files and 1) Get rid of comments, line continuations, and empty lines; lower cases. 2) Call dowithline(line) on every line. 3) Recursively call itself when statement \"include '<filename>'\" is met.
Read fortran codes from files and 1) Get rid of comments, line continuations, and empty lines; lower cases. 2) Call dowithline(line) on every line. 3) Recursively call itself when statement \"include '<filename>'\" is met.
def readfortrancode(ffile, dowithline=show, istop=1): """ Read fortran codes from files and 1) Get rid of comments, line continuations, and empty lines; lower cases. 2) Call dowithline(line) on every line. 3) Recursively call itself when statement \"include '<filename>'\" is met. """ glob...
[ "def", "readfortrancode", "(", "ffile", ",", "dowithline", "=", "show", ",", "istop", "=", "1", ")", ":", "global", "gotnextfile", ",", "filepositiontext", ",", "currentfilename", ",", "sourcecodeform", ",", "strictf77", "global", "beginpattern", ",", "quiet", ...
[ 329, 0 ]
[ 534, 67 ]
python
en
['en', 'error', 'th']
False
split_by_unquoted
(line, characters)
Splits the line into (line[:i], line[i:]), where i is the index of first occurrence of one of the characters not within quotes, or len(line) if no such index exists
Splits the line into (line[:i], line[i:]), where i is the index of first occurrence of one of the characters not within quotes, or len(line) if no such index exists
def split_by_unquoted(line, characters): """ Splits the line into (line[:i], line[i:]), where i is the index of first occurrence of one of the characters not within quotes, or len(line) if no such index exists """ assert not (set('"\'') & set(characters)), "cannot split by unquoted quotes" r...
[ "def", "split_by_unquoted", "(", "line", ",", "characters", ")", ":", "assert", "not", "(", "set", "(", "'\"\\''", ")", "&", "set", "(", "characters", ")", ")", ",", "\"cannot split by unquoted quotes\"", "r", "=", "re", ".", "compile", "(", "r\"\\A(?P<befor...
[ 611, 0 ]
[ 629, 21 ]
python
en
['en', 'error', 'th']
False
crackline
(line, reset=0)
reset=-1 --- initialize reset=0 --- crack the line reset=1 --- final check if mismatch of blocks occurred Cracked data is saved in grouplist[0].
reset=-1 --- initialize reset=0 --- crack the line reset=1 --- final check if mismatch of blocks occurred
def crackline(line, reset=0): """ reset=-1 --- initialize reset=0 --- crack the line reset=1 --- final check if mismatch of blocks occurred Cracked data is saved in grouplist[0]. """ global beginpattern, groupcounter, groupname, groupcache, grouplist global filepositiontext, curren...
[ "def", "crackline", "(", "line", ",", "reset", "=", "0", ")", ":", "global", "beginpattern", ",", "groupcounter", ",", "groupname", ",", "groupcache", ",", "grouplist", "global", "filepositiontext", ",", "currentfilename", ",", "neededmodule", ",", "expectbegin"...
[ 642, 0 ]
[ 795, 36 ]
python
en
['en', 'error', 'th']
False
postcrack
(block, args=None, tab='')
TODO: function return values determine expression types if in argument list
TODO: function return values determine expression types if in argument list
def postcrack(block, args=None, tab=''): """ TODO: function return values determine expression types if in argument list """ global usermodules, onlyfunctions if isinstance(block, list): gret = [] uret = [] for g in block: setmesstext(g) ...
[ "def", "postcrack", "(", "block", ",", "args", "=", "None", ",", "tab", "=", "''", ")", ":", "global", "usermodules", ",", "onlyfunctions", "if", "isinstance", "(", "block", ",", "list", ")", ":", "gret", "=", "[", "]", "uret", "=", "[", "]", "for"...
[ 1877, 0 ]
[ 1970, 16 ]
python
en
['en', 'error', 'th']
False
test_eval_train_calls
(test_train_mock, test_eval_mock, val_train_mock, val_eval_mock, tmpdir)
Tests that only training_step can be used
Tests that only training_step can be used
def test_eval_train_calls(test_train_mock, test_eval_mock, val_train_mock, val_eval_mock, tmpdir): """ Tests that only training_step can be used """ model = BoringModel() model.validation_epoch_end = None trainer = Trainer( default_root_dir=tmpdir, limit_train_batches=2, ...
[ "def", "test_eval_train_calls", "(", "test_train_mock", ",", "test_eval_mock", ",", "val_train_mock", ",", "val_eval_mock", ",", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "model", ".", "validation_epoch_end", "=", "None", "trainer", "=", "Trainer"...
[ 23, 0 ]
[ 48, 42 ]
python
en
['en', 'error', 'th']
False
test_invalid_input_img_type
()
Test Whether the module successfully handles invalid input data type
Test Whether the module successfully handles invalid input data type
def test_invalid_input_img_type(): """Test Whether the module successfully handles invalid input data type""" invalid_dummy_input = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] with pytest.raises(TypeError): image_gradients(invalid_dummy_input)
[ "def", "test_invalid_input_img_type", "(", ")", ":", "invalid_dummy_input", "=", "[", "[", "1", ",", "2", ",", "3", "]", ",", "[", "4", ",", "5", ",", "6", "]", ",", "[", "7", ",", "8", ",", "9", "]", "]", "with", "pytest", ".", "raises", "(", ...
[ 6, 0 ]
[ 11, 44 ]
python
en
['en', 'en', 'en']
True
test_invalid_input_ndims
()
Test whether the module successfully handles invalid number of dimensions of input tensor
Test whether the module successfully handles invalid number of dimensions of input tensor
def test_invalid_input_ndims(): """ Test whether the module successfully handles invalid number of dimensions of input tensor """ BATCH_SIZE = 1 HEIGHT = 5 WIDTH = 5 CHANNELS = 1 image = torch.arange(0, BATCH_SIZE * HEIGHT * WIDTH * CHANNELS, dtype=torch.float32) image = torch....
[ "def", "test_invalid_input_ndims", "(", ")", ":", "BATCH_SIZE", "=", "1", "HEIGHT", "=", "5", "WIDTH", "=", "5", "CHANNELS", "=", "1", "image", "=", "torch", ".", "arange", "(", "0", ",", "BATCH_SIZE", "*", "HEIGHT", "*", "WIDTH", "*", "CHANNELS", ",",...
[ 14, 0 ]
[ 29, 30 ]
python
en
['en', 'error', 'th']
False
test_multi_batch_image_gradients
()
Test whether the module correctly calculates gradients for known input with non-unity batch size.Example input-output pair taken from TF's implementation of i mage-gradients
Test whether the module correctly calculates gradients for known input with non-unity batch size.Example input-output pair taken from TF's implementation of i mage-gradients
def test_multi_batch_image_gradients(): """Test whether the module correctly calculates gradients for known input with non-unity batch size.Example input-output pair taken from TF's implementation of i mage-gradients """ BATCH_SIZE = 5 HEIGHT = 5 WIDTH = 5 CHANNELS = 1 single_chann...
[ "def", "test_multi_batch_image_gradients", "(", ")", ":", "BATCH_SIZE", "=", "5", "HEIGHT", "=", "5", "WIDTH", "=", "5", "CHANNELS", "=", "1", "single_channel_img", "=", "torch", ".", "arange", "(", "0", ",", "1", "*", "HEIGHT", "*", "WIDTH", "*", "CHANN...
[ 32, 0 ]
[ 70, 53 ]
python
en
['en', 'en', 'en']
True
test_image_gradients
()
Test whether the module correctly calculates gradients for known input. Example input-output pair taken from TF's implementation of image-gradients
Test whether the module correctly calculates gradients for known input. Example input-output pair taken from TF's implementation of image-gradients
def test_image_gradients(): """Test whether the module correctly calculates gradients for known input. Example input-output pair taken from TF's implementation of image-gradients """ BATCH_SIZE = 1 HEIGHT = 5 WIDTH = 5 CHANNELS = 1 image = torch.arange(0, BATCH_SIZE * HEIGHT * WIDTH * ...
[ "def", "test_image_gradients", "(", ")", ":", "BATCH_SIZE", "=", "1", "HEIGHT", "=", "5", "WIDTH", "=", "5", "CHANNELS", "=", "1", "image", "=", "torch", ".", "arange", "(", "0", ",", "BATCH_SIZE", "*", "HEIGHT", "*", "WIDTH", "*", "CHANNELS", ",", "...
[ 73, 0 ]
[ 108, 56 ]
python
en
['en', 'en', 'en']
True
process_tex
(lines)
Remove unnecessary section titles from the LaTeX file.
Remove unnecessary section titles from the LaTeX file.
def process_tex(lines): """ Remove unnecessary section titles from the LaTeX file. """ new_lines = [] for line in lines: if (line.startswith(r'\section{numpy.') or line.startswith(r'\subsection{numpy.') or line.startswith(r'\subsubsection{numpy.') or line...
[ "def", "process_tex", "(", "lines", ")", ":", "new_lines", "=", "[", "]", "for", "line", "in", "lines", ":", "if", "(", "line", ".", "startswith", "(", "r'\\section{numpy.'", ")", "or", "line", ".", "startswith", "(", "r'\\subsection{numpy.'", ")", "or", ...
[ 43, 0 ]
[ 59, 20 ]
python
en
['en', 'error', 'th']
False
overwrite_by_env_vars
(fn: Callable)
Decorator for :class:`~pytorch_lightning.trainer.trainer.Trainer` methods for which input arguments should be moved automatically to the correct device.
Decorator for :class:`~pytorch_lightning.trainer.trainer.Trainer` methods for which input arguments should be moved automatically to the correct device.
def overwrite_by_env_vars(fn: Callable) -> Callable: """ Decorator for :class:`~pytorch_lightning.trainer.trainer.Trainer` methods for which input arguments should be moved automatically to the correct device. """ @wraps(fn) def overwrite_by_env_vars(self, *args, **kwargs): # get the c...
[ "def", "overwrite_by_env_vars", "(", "fn", ":", "Callable", ")", "->", "Callable", ":", "@", "wraps", "(", "fn", ")", "def", "overwrite_by_env_vars", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# get the class", "cls", "=", "self",...
[ 20, 0 ]
[ 43, 32 ]
python
en
['en', 'error', 'th']
False
filepath_from_subprocess_output
(output)
Convert `bytes` in the encoding used by a subprocess into a filesystem-appropriate `str`. Inherited from `exec_command`, and possibly incorrect.
Convert `bytes` in the encoding used by a subprocess into a filesystem-appropriate `str`.
def filepath_from_subprocess_output(output): """ Convert `bytes` in the encoding used by a subprocess into a filesystem-appropriate `str`. Inherited from `exec_command`, and possibly incorrect. """ mylocale = locale.getpreferredencoding(False) if mylocale is None: mylocale = 'ascii' ...
[ "def", "filepath_from_subprocess_output", "(", "output", ")", ":", "mylocale", "=", "locale", ".", "getpreferredencoding", "(", "False", ")", "if", "mylocale", "is", "None", ":", "mylocale", "=", "'ascii'", "output", "=", "output", ".", "decode", "(", "mylocal...
[ 64, 0 ]
[ 82, 17 ]
python
en
['en', 'error', 'th']
False
forward_bytes_to_stdout
(val)
Forward bytes from a subprocess call to the console, without attempting to decode them. The assumption is that the subprocess call already returned bytes in a suitable encoding.
Forward bytes from a subprocess call to the console, without attempting to decode them.
def forward_bytes_to_stdout(val): """ Forward bytes from a subprocess call to the console, without attempting to decode them. The assumption is that the subprocess call already returned bytes in a suitable encoding. """ if sys.version_info.major < 3: # python 2 has binary output any...
[ "def", "forward_bytes_to_stdout", "(", "val", ")", ":", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "# python 2 has binary output anyway", "sys", ".", "stdout", ".", "write", "(", "val", ")", "elif", "hasattr", "(", "sys", ".", "stdout", ...
[ 85, 0 ]
[ 104, 62 ]
python
en
['en', 'error', 'th']
False
find_executable
(exe, path=None, _cache={})
Return full path of a executable or None. Symbolic links are not followed.
Return full path of a executable or None.
def find_executable(exe, path=None, _cache={}): """Return full path of a executable or None. Symbolic links are not followed. """ key = exe, path try: return _cache[key] except KeyError: pass log.debug('find_executable(%r)' % exe) orig_exe = exe if path is None: ...
[ "def", "find_executable", "(", "exe", ",", "path", "=", "None", ",", "_cache", "=", "{", "}", ")", ":", "key", "=", "exe", ",", "path", "try", ":", "return", "_cache", "[", "key", "]", "except", "KeyError", ":", "pass", "log", ".", "debug", "(", ...
[ 124, 0 ]
[ 171, 15 ]
python
en
['en', 'en', 'en']
True
exec_command
(command, execute_in='', use_shell=None, use_tee=None, _with_python = 1, **env )
Return (status,output) of executed command. .. deprecated:: 1.17 Use subprocess.Popen instead Parameters ---------- command : str A concatenated string of executable and arguments. execute_in : str Before running command ``cd execute_in`` and after ``cd -``. use_sh...
Return (status,output) of executed command.
def exec_command(command, execute_in='', use_shell=None, use_tee=None, _with_python = 1, **env ): """ Return (status,output) of executed command. .. deprecated:: 1.17 Use subprocess.Popen instead Parameters ---------- command : str A concatenated string of exec...
[ "def", "exec_command", "(", "command", ",", "execute_in", "=", "''", ",", "use_shell", "=", "None", ",", "use_tee", "=", "None", ",", "_with_python", "=", "1", ",", "*", "*", "env", ")", ":", "# 2019-01-30, 1.17", "warnings", ".", "warn", "(", "'exec_com...
[ 185, 0 ]
[ 258, 13 ]
python
en
['en', 'error', 'th']
False
_exec_command
(command, use_shell=None, use_tee = None, **env)
Internal workhorse for exec_command().
Internal workhorse for exec_command().
def _exec_command(command, use_shell=None, use_tee = None, **env): """ Internal workhorse for exec_command(). """ if use_shell is None: use_shell = os.name=='posix' if use_tee is None: use_tee = os.name=='posix' if os.name == 'posix' and use_shell: # On POSIX, subprocess...
[ "def", "_exec_command", "(", "command", ",", "use_shell", "=", "None", ",", "use_tee", "=", "None", ",", "*", "*", "env", ")", ":", "if", "use_shell", "is", "None", ":", "use_shell", "=", "os", ".", "name", "==", "'posix'", "if", "use_tee", "is", "No...
[ 261, 0 ]
[ 316, 32 ]
python
en
['en', 'error', 'th']
False
_quote_arg
(arg)
Quote the argument for safe use in a shell command line.
Quote the argument for safe use in a shell command line.
def _quote_arg(arg): """ Quote the argument for safe use in a shell command line. """ # If there is a quote in the string, assume relevants parts of the # string are already quoted (e.g. '-I"C:\\Program Files\\..."') if '"' not in arg and ' ' in arg: return '"%s"' % arg return arg
[ "def", "_quote_arg", "(", "arg", ")", ":", "# If there is a quote in the string, assume relevants parts of the", "# string are already quoted (e.g. '-I\"C:\\\\Program Files\\\\...\"')", "if", "'\"'", "not", "in", "arg", "and", "' '", "in", "arg", ":", "return", "'\"%s\"'", "%...
[ 319, 0 ]
[ 327, 14 ]
python
en
['en', 'error', 'th']
False
hide_not_implemented
(comment)
Should a given type_context.Comment be hidden because it is tagged as [#not-implemented-hide:]?
Should a given type_context.Comment be hidden because it is tagged as [#not-implemented-hide:]?
def hide_not_implemented(comment): """Should a given type_context.Comment be hidden because it is tagged as [#not-implemented-hide:]?""" return annotations.NOT_IMPLEMENTED_HIDE_ANNOTATION in comment.annotations
[ "def", "hide_not_implemented", "(", "comment", ")", ":", "return", "annotations", ".", "NOT_IMPLEMENTED_HIDE_ANNOTATION", "in", "comment", ".", "annotations" ]
[ 143, 0 ]
[ 145, 77 ]
python
en
['en', 'en', 'en']
True
github_url
(text, type_context)
Obtain data plane API Github URL by path from a TypeContext. Args: type_context: type_context.TypeContext for node. Returns: A string with a corresponding data plane API GitHub Url.
Obtain data plane API Github URL by path from a TypeContext.
def github_url(text, type_context): """Obtain data plane API Github URL by path from a TypeContext. Args: type_context: type_context.TypeContext for node. Returns: A string with a corresponding data plane API GitHub Url. """ return f":repo:`{text} <api/{type_context.source_code_inf...
[ "def", "github_url", "(", "text", ",", "type_context", ")", ":", "return", "f\":repo:`{text} <api/{type_context.source_code_info.name}#L{type_context.location.span[0]}>`\"" ]
[ 148, 0 ]
[ 157, 104 ]
python
en
['en', 'en', 'en']
True
format_comment_with_annotations
(comment, type_name='')
Format a comment string with additional RST for annotations. Args: comment: comment string. type_name: optional, 'message' or 'enum' may be specified for additional message/enum specific annotations. Returns: A string with additional RST from annotations.
Format a comment string with additional RST for annotations.
def format_comment_with_annotations(comment, type_name=''): """Format a comment string with additional RST for annotations. Args: comment: comment string. type_name: optional, 'message' or 'enum' may be specified for additional message/enum specific annotations. Returns: ...
[ "def", "format_comment_with_annotations", "(", "comment", ",", "type_name", "=", "''", ")", ":", "alpha_warning", "=", "''", "if", "annotations", ".", "ALPHA_ANNOTATION", "in", "comment", ".", "annotations", ":", "experimental_warning", "=", "(", "'.. warning::\\n ...
[ 160, 0 ]
[ 186, 87 ]
python
en
['en', 'en', 'en']
True
map_lines
(f, s)
Apply a function across each line in a flat string. Args: f: A string transform function for a line. s: A string consisting of potentially multiple lines. Returns: A flat string with f applied to each line.
Apply a function across each line in a flat string.
def map_lines(f, s): """Apply a function across each line in a flat string. Args: f: A string transform function for a line. s: A string consisting of potentially multiple lines. Returns: A flat string with f applied to each line. """ return '\n'.join(f(line) for line in s....
[ "def", "map_lines", "(", "f", ",", "s", ")", ":", "return", "'\\n'", ".", "join", "(", "f", "(", "line", ")", "for", "line", "in", "s", ".", "split", "(", "'\\n'", ")", ")" ]
[ 189, 0 ]
[ 199, 55 ]
python
en
['en', 'en', 'en']
True
indent
(spaces, line)
Indent a string.
Indent a string.
def indent(spaces, line): """Indent a string.""" return ' ' * spaces + line
[ "def", "indent", "(", "spaces", ",", "line", ")", ":", "return", "' '", "*", "spaces", "+", "line" ]
[ 202, 0 ]
[ 204, 30 ]
python
en
['en', 'en', 'en']
True
indent_lines
(spaces, lines)
Indent a list of strings.
Indent a list of strings.
def indent_lines(spaces, lines): """Indent a list of strings.""" return map(functools.partial(indent, spaces), lines)
[ "def", "indent_lines", "(", "spaces", ",", "lines", ")", ":", "return", "map", "(", "functools", ".", "partial", "(", "indent", ",", "spaces", ")", ",", "lines", ")" ]
[ 207, 0 ]
[ 209, 56 ]
python
en
['en', 'en', 'en']
True
format_header
(style, text)
Format RST header. Args: style: underline style, e.g. '=', '-'. text: header text Returns: RST formatted header.
Format RST header.
def format_header(style, text): """Format RST header. Args: style: underline style, e.g. '=', '-'. text: header text Returns: RST formatted header. """ return '%s\n%s\n\n' % (text, style * len(text))
[ "def", "format_header", "(", "style", ",", "text", ")", ":", "return", "'%s\\n%s\\n\\n'", "%", "(", "text", ",", "style", "*", "len", "(", "text", ")", ")" ]
[ 220, 0 ]
[ 230, 51 ]
python
en
['en', 'sv', 'en']
True
format_extension
(extension)
Format extension metadata as RST. Args: extension: the name of the extension, e.g. com.acme.foo. Returns: RST formatted extension description.
Format extension metadata as RST.
def format_extension(extension): """Format extension metadata as RST. Args: extension: the name of the extension, e.g. com.acme.foo. Returns: RST formatted extension description. """ try: extension_metadata = EXTENSION_DB[extension] status = EXTENSION_STATUS_VALUES....
[ "def", "format_extension", "(", "extension", ")", ":", "try", ":", "extension_metadata", "=", "EXTENSION_DB", "[", "extension", "]", "status", "=", "EXTENSION_STATUS_VALUES", ".", "get", "(", "extension_metadata", ".", "get", "(", "'status'", ")", ",", "''", "...
[ 233, 0 ]
[ 257, 30 ]
python
en
['en', 'jv', 'en']
True
format_extension_category
(extension_category)
Format extension metadata as RST. Args: extension_category: the name of the extension_category, e.g. com.acme. Returns: RST formatted extension category description.
Format extension metadata as RST.
def format_extension_category(extension_category): """Format extension metadata as RST. Args: extension_category: the name of the extension_category, e.g. com.acme. Returns: RST formatted extension category description. """ try: extensions = EXTENSION_CATEGORIES[extension_c...
[ "def", "format_extension_category", "(", "extension_category", ")", ":", "try", ":", "extensions", "=", "EXTENSION_CATEGORIES", "[", "extension_category", "]", "except", "KeyError", "as", "e", ":", "raise", "ProtodocError", "(", "f\"\\n\\nUnable to find extension category...
[ 260, 0 ]
[ 274, 67 ]
python
en
['en', 'jv', 'en']
True
format_header_from_file
(style, source_code_info, proto_name, v2_link)
Format RST header based on special file level title Args: style: underline style, e.g. '=', '-'. source_code_info: SourceCodeInfo object. proto_name: If the file_level_comment does not contain a user specified title, use this as page title. Returns: RST formatted hea...
Format RST header based on special file level title
def format_header_from_file(style, source_code_info, proto_name, v2_link): """Format RST header based on special file level title Args: style: underline style, e.g. '=', '-'. source_code_info: SourceCodeInfo object. proto_name: If the file_level_comment does not contain a user specified...
[ "def", "format_header_from_file", "(", "style", ",", "source_code_info", ",", "proto_name", ",", "v2_link", ")", ":", "anchor", "=", "format_anchor", "(", "file_cross_ref_label", "(", "proto_name", ")", ")", "stripped_comment", "=", "annotations", ".", "without_anno...
[ 277, 0 ]
[ 301, 85 ]
python
en
['en', 'da', 'en']
True
format_field_type_as_json
(type_context, field)
Format FieldDescriptorProto.Type as a pseudo-JSON string. Args: type_context: contextual information for message/enum/field. field: FieldDescriptor proto. Return: RST formatted pseudo-JSON string representation of field type.
Format FieldDescriptorProto.Type as a pseudo-JSON string.
def format_field_type_as_json(type_context, field): """Format FieldDescriptorProto.Type as a pseudo-JSON string. Args: type_context: contextual information for message/enum/field. field: FieldDescriptor proto. Return: RST formatted pseudo-JSON string representation of field type. """ ...
[ "def", "format_field_type_as_json", "(", "type_context", ",", "field", ")", ":", "if", "type_name_from_fqn", "(", "field", ".", "type_name", ")", "in", "type_context", ".", "map_typenames", ":", "return", "'\"{...}\"'", "if", "field", ".", "label", "==", "field"...
[ 304, 0 ]
[ 318, 18 ]
python
en
['en', 'fy', 'en']
True
format_message_as_json
(type_context, msg)
Format a message definition DescriptorProto as a pseudo-JSON block. Args: type_context: contextual information for message/enum/field. msg: message definition DescriptorProto. Return: RST formatted pseudo-JSON string representation of message definition.
Format a message definition DescriptorProto as a pseudo-JSON block.
def format_message_as_json(type_context, msg): """Format a message definition DescriptorProto as a pseudo-JSON block. Args: type_context: contextual information for message/enum/field. msg: message definition DescriptorProto. Return: RST formatted pseudo-JSON string representation of messag...
[ "def", "format_message_as_json", "(", "type_context", ",", "msg", ")", ":", "lines", "=", "[", "]", "for", "index", ",", "field", "in", "enumerate", "(", "msg", ".", "field", ")", ":", "field_type_context", "=", "type_context", ".", "extend_field", "(", "i...
[ 321, 0 ]
[ 339, 13 ]
python
en
['pt', 'fr', 'en']
False
normalize_field_type_name
(field_fqn)
Normalize a fully qualified field type name, e.g. .envoy.foo.bar. Strips leading ENVOY_API_NAMESPACE_PREFIX and ENVOY_PREFIX. Args: field_fqn: a fully qualified type name from FieldDescriptorProto.type_name. Return: Normalized type name.
Normalize a fully qualified field type name, e.g.
def normalize_field_type_name(field_fqn): """Normalize a fully qualified field type name, e.g. .envoy.foo.bar. Strips leading ENVOY_API_NAMESPACE_PREFIX and ENVOY_PREFIX. Args: field_fqn: a fully qualified type name from FieldDescriptorProto.type_name. Return: Normalized type name. ""...
[ "def", "normalize_field_type_name", "(", "field_fqn", ")", ":", "if", "field_fqn", ".", "startswith", "(", "ENVOY_API_NAMESPACE_PREFIX", ")", ":", "return", "field_fqn", "[", "len", "(", "ENVOY_API_NAMESPACE_PREFIX", ")", ":", "]", "if", "field_fqn", ".", "startsw...
[ 342, 0 ]
[ 357, 20 ]
python
en
['en', 'en', 'en']
True
normalize_type_context_name
(type_name)
Normalize a type name, e.g. envoy.foo.bar. Strips leading ENVOY_API_NAMESPACE_PREFIX and ENVOY_PREFIX. Args: type_name: a name from a TypeContext. Return: Normalized type name.
Normalize a type name, e.g.
def normalize_type_context_name(type_name): """Normalize a type name, e.g. envoy.foo.bar. Strips leading ENVOY_API_NAMESPACE_PREFIX and ENVOY_PREFIX. Args: type_name: a name from a TypeContext. Return: Normalized type name. """ return normalize_field_type_name(qualify_type_name(ty...
[ "def", "normalize_type_context_name", "(", "type_name", ")", ":", "return", "normalize_field_type_name", "(", "qualify_type_name", "(", "type_name", ")", ")" ]
[ 360, 0 ]
[ 371, 66 ]
python
en
['en', 'en', 'pt']
True
format_field_type
(type_context, field)
Format a FieldDescriptorProto type description. Adds cross-refs for message types. TODO(htuch): Add cross-refs for enums as well. Args: type_context: contextual information for message/enum/field. field: FieldDescriptor proto. Return: RST formatted field type.
Format a FieldDescriptorProto type description.
def format_field_type(type_context, field): """Format a FieldDescriptorProto type description. Adds cross-refs for message types. TODO(htuch): Add cross-refs for enums as well. Args: type_context: contextual information for message/enum/field. field: FieldDescriptor proto. Return: ...
[ "def", "format_field_type", "(", "type_context", ",", "field", ")", ":", "if", "field", ".", "type_name", ".", "startswith", "(", "ENVOY_API_NAMESPACE_PREFIX", ")", "or", "field", ".", "type_name", ".", "startswith", "(", "ENVOY_PREFIX", ")", ":", "type_name", ...
[ 382, 0 ]
[ 440, 64 ]
python
en
['it', 'fy', 'en']
False
strip_leading_space
(s)
Remove leading space in flat comment strings.
Remove leading space in flat comment strings.
def strip_leading_space(s): """Remove leading space in flat comment strings.""" return map_lines(lambda s: s[1:], s)
[ "def", "strip_leading_space", "(", "s", ")", ":", "return", "map_lines", "(", "lambda", "s", ":", "s", "[", "1", ":", "]", ",", "s", ")" ]
[ 443, 0 ]
[ 445, 40 ]
python
en
['en', 'en', 'en']
True
file_cross_ref_label
(msg_name)
File cross reference label.
File cross reference label.
def file_cross_ref_label(msg_name): """File cross reference label.""" return 'envoy_v3_api_file_%s' % msg_name
[ "def", "file_cross_ref_label", "(", "msg_name", ")", ":", "return", "'envoy_v3_api_file_%s'", "%", "msg_name" ]
[ 448, 0 ]
[ 450, 44 ]
python
en
['fr', 'en', 'en']
True
message_cross_ref_label
(msg_name)
Message cross reference label.
Message cross reference label.
def message_cross_ref_label(msg_name): """Message cross reference label.""" return 'envoy_v3_api_msg_%s' % msg_name
[ "def", "message_cross_ref_label", "(", "msg_name", ")", ":", "return", "'envoy_v3_api_msg_%s'", "%", "msg_name" ]
[ 453, 0 ]
[ 455, 43 ]
python
en
['fr', 'en', 'en']
True
enum_cross_ref_label
(enum_name)
Enum cross reference label.
Enum cross reference label.
def enum_cross_ref_label(enum_name): """Enum cross reference label.""" return 'envoy_v3_api_enum_%s' % enum_name
[ "def", "enum_cross_ref_label", "(", "enum_name", ")", ":", "return", "'envoy_v3_api_enum_%s'", "%", "enum_name" ]
[ 458, 0 ]
[ 460, 45 ]
python
en
['en', 'en', 'en']
True
field_cross_ref_label
(field_name)
Field cross reference label.
Field cross reference label.
def field_cross_ref_label(field_name): """Field cross reference label.""" return 'envoy_v3_api_field_%s' % field_name
[ "def", "field_cross_ref_label", "(", "field_name", ")", ":", "return", "'envoy_v3_api_field_%s'", "%", "field_name" ]
[ 463, 0 ]
[ 465, 47 ]
python
en
['en', 'en', 'en']
True
enum_value_cross_ref_label
(enum_value_name)
Enum value cross reference label.
Enum value cross reference label.
def enum_value_cross_ref_label(enum_value_name): """Enum value cross reference label.""" return 'envoy_v3_api_enum_value_%s' % enum_value_name
[ "def", "enum_value_cross_ref_label", "(", "enum_value_name", ")", ":", "return", "'envoy_v3_api_enum_value_%s'", "%", "enum_value_name" ]
[ 468, 0 ]
[ 470, 57 ]
python
en
['en', 'en', 'en']
True
format_anchor
(label)
Format a label as an Envoy API RST anchor.
Format a label as an Envoy API RST anchor.
def format_anchor(label): """Format a label as an Envoy API RST anchor.""" return '.. _%s:\n\n' % label
[ "def", "format_anchor", "(", "label", ")", ":", "return", "'.. _%s:\\n\\n'", "%", "label" ]
[ 473, 0 ]
[ 475, 32 ]
python
en
['en', 'en', 'en']
True
format_field_as_definition_list_item
( outer_type_context, type_context, field, protodoc_manifest)
Format a FieldDescriptorProto as RST definition list item. Args: outer_type_context: contextual information for enclosing message. type_context: contextual information for message/enum/field. field: FieldDescriptorProto. protodoc_manifest: tools.protodoc.Manifest for proto. Ret...
Format a FieldDescriptorProto as RST definition list item.
def format_field_as_definition_list_item( outer_type_context, type_context, field, protodoc_manifest): """Format a FieldDescriptorProto as RST definition list item. Args: outer_type_context: contextual information for enclosing message. type_context: contextual information for message/e...
[ "def", "format_field_as_definition_list_item", "(", "outer_type_context", ",", "type_context", ",", "field", ",", "protodoc_manifest", ")", ":", "field_annotations", "=", "[", "]", "anchor", "=", "format_anchor", "(", "field_cross_ref_label", "(", "normalize_type_context_...
[ 504, 0 ]
[ 579, 71 ]
python
en
['en', 'lb', 'en']
True
format_message_as_definition_list
(type_context, msg, protodoc_manifest)
Format a DescriptorProto as RST definition list. Args: type_context: contextual information for message/enum/field. msg: DescriptorProto. protodoc_manifest: tools.protodoc.Manifest for proto. Returns: RST formatted definition list item.
Format a DescriptorProto as RST definition list.
def format_message_as_definition_list(type_context, msg, protodoc_manifest): """Format a DescriptorProto as RST definition list. Args: type_context: contextual information for message/enum/field. msg: DescriptorProto. protodoc_manifest: tools.protodoc.Manifest for proto. Returns: ...
[ "def", "format_message_as_definition_list", "(", "type_context", ",", "msg", ",", "protodoc_manifest", ")", ":", "type_context", ".", "oneof_fields", "=", "defaultdict", "(", "list", ")", "type_context", ".", "oneof_required", "=", "defaultdict", "(", "bool", ")", ...
[ 582, 0 ]
[ 610, 56 ]
python
en
['en', 'fr', 'en']
True
format_enum_value_as_definition_list_item
(type_context, enum_value)
Format a EnumValueDescriptorProto as RST definition list item. Args: type_context: contextual information for message/enum/field. enum_value: EnumValueDescriptorProto. Returns: RST formatted definition list item.
Format a EnumValueDescriptorProto as RST definition list item.
def format_enum_value_as_definition_list_item(type_context, enum_value): """Format a EnumValueDescriptorProto as RST definition list item. Args: type_context: contextual information for message/enum/field. enum_value: EnumValueDescriptorProto. Returns: RST formatted definition list...
[ "def", "format_enum_value_as_definition_list_item", "(", "type_context", ",", "enum_value", ")", ":", "anchor", "=", "format_anchor", "(", "enum_value_cross_ref_label", "(", "normalize_type_context_name", "(", "type_context", ".", "name", ")", ")", ")", "default_comment",...
[ 613, 0 ]
[ 631, 93 ]
python
en
['en', 'fr', 'en']
True
format_enum_as_definition_list
(type_context, enum)
Format a EnumDescriptorProto as RST definition list. Args: type_context: contextual information for message/enum/field. enum: DescriptorProto. Returns: RST formatted definition list item.
Format a EnumDescriptorProto as RST definition list.
def format_enum_as_definition_list(type_context, enum): """Format a EnumDescriptorProto as RST definition list. Args: type_context: contextual information for message/enum/field. enum: DescriptorProto. Returns: RST formatted definition list item. """ return '\n'.join( ...
[ "def", "format_enum_as_definition_list", "(", "type_context", ",", "enum", ")", ":", "return", "'\\n'", ".", "join", "(", "format_enum_value_as_definition_list_item", "(", "type_context", ".", "extend_enum_value", "(", "index", ",", "enum_value", ".", "name", ")", "...
[ 634, 0 ]
[ 647, 62 ]
python
en
['en', 'de', 'en']
True
format_proto_as_block_comment
(proto)
Format a proto as a RST block comment. Useful in debugging, not usually referenced.
Format a proto as a RST block comment.
def format_proto_as_block_comment(proto): """Format a proto as a RST block comment. Useful in debugging, not usually referenced. """ return '\n\nproto::\n\n' + map_lines(functools.partial(indent, 2), str(proto)) + '\n'
[ "def", "format_proto_as_block_comment", "(", "proto", ")", ":", "return", "'\\n\\nproto::\\n\\n'", "+", "map_lines", "(", "functools", ".", "partial", "(", "indent", ",", "2", ")", ",", "str", "(", "proto", ")", ")", "+", "'\\n'" ]
[ 650, 0 ]
[ 655, 89 ]
python
en
['en', 'en', 'en']
True
convert_inf
(x: Optional[Union[int, float]])
The tqdm doesn't support inf values. We have to convert it to None.
The tqdm doesn't support inf values. We have to convert it to None.
def convert_inf(x: Optional[Union[int, float]]) -> Optional[Union[int, float]]: """ The tqdm doesn't support inf values. We have to convert it to None. """ if x == float('inf'): return None return x
[ "def", "convert_inf", "(", "x", ":", "Optional", "[", "Union", "[", "int", ",", "float", "]", "]", ")", "->", "Optional", "[", "Union", "[", "int", ",", "float", "]", "]", ":", "if", "x", "==", "float", "(", "'inf'", ")", ":", "return", "None", ...
[ 491, 0 ]
[ 495, 12 ]
python
en
['en', 'en', 'en']
True
reset
(bar: tqdm, total: Optional[int] = None)
Resets the tqdm bar to 0 progress with a new total, unless it is disabled.
Resets the tqdm bar to 0 progress with a new total, unless it is disabled.
def reset(bar: tqdm, total: Optional[int] = None) -> None: """ Resets the tqdm bar to 0 progress with a new total, unless it is disabled. """ if not bar.disable: bar.reset(total=convert_inf(total))
[ "def", "reset", "(", "bar", ":", "tqdm", ",", "total", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "None", ":", "if", "not", "bar", ".", "disable", ":", "bar", ".", "reset", "(", "total", "=", "convert_inf", "(", "total", ")", ")" ]
[ 498, 0 ]
[ 501, 43 ]
python
en
['en', 'en', 'en']
True
tqdm.format_num
(n)
Add additional padding to the formatted numbers
Add additional padding to the formatted numbers
def format_num(n) -> str: """ Add additional padding to the formatted numbers """ should_be_padded = isinstance(n, (float, str)) if not isinstance(n, str): n = _tqdm.format_num(n) if should_be_padded and 'e' not in n: if '.' not in n and len(n) < _PAD_SIZE: ...
[ "def", "format_num", "(", "n", ")", "->", "str", ":", "should_be_padded", "=", "isinstance", "(", "n", ",", "(", "float", ",", "str", ")", ")", "if", "not", "isinstance", "(", "n", ",", "str", ")", ":", "n", "=", "_tqdm", ".", "format_num", "(", ...
[ 46, 4 ]
[ 59, 16 ]
python
en
['en', 'en', 'en']
True
ProgressBarBase.train_batch_idx
(self)
The current batch index being processed during training. Use this to update your progress bar.
The current batch index being processed during training. Use this to update your progress bar.
def train_batch_idx(self) -> int: """ The current batch index being processed during training. Use this to update your progress bar. """ return self._train_batch_idx
[ "def", "train_batch_idx", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_train_batch_idx" ]
[ 103, 4 ]
[ 108, 36 ]
python
en
['en', 'error', 'th']
False
ProgressBarBase.val_batch_idx
(self)
The current batch index being processed during validation. Use this to update your progress bar.
The current batch index being processed during validation. Use this to update your progress bar.
def val_batch_idx(self) -> int: """ The current batch index being processed during validation. Use this to update your progress bar. """ return self._val_batch_idx
[ "def", "val_batch_idx", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_val_batch_idx" ]
[ 111, 4 ]
[ 116, 34 ]
python
en
['en', 'error', 'th']
False
ProgressBarBase.test_batch_idx
(self)
The current batch index being processed during testing. Use this to update your progress bar.
The current batch index being processed during testing. Use this to update your progress bar.
def test_batch_idx(self) -> int: """ The current batch index being processed during testing. Use this to update your progress bar. """ return self._test_batch_idx
[ "def", "test_batch_idx", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_test_batch_idx" ]
[ 119, 4 ]
[ 124, 35 ]
python
en
['en', 'error', 'th']
False
ProgressBarBase.predict_batch_idx
(self)
The current batch index being processed during predicting. Use this to update your progress bar.
The current batch index being processed during predicting. Use this to update your progress bar.
def predict_batch_idx(self) -> int: """ The current batch index being processed during predicting. Use this to update your progress bar. """ return self._predict_batch_idx
[ "def", "predict_batch_idx", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_predict_batch_idx" ]
[ 127, 4 ]
[ 132, 38 ]
python
en
['en', 'error', 'th']
False
ProgressBarBase.total_train_batches
(self)
The total number of training batches during training, which may change from epoch to epoch. Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the training dataloader is of infinite size.
The total number of training batches during training, which may change from epoch to epoch. Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the training dataloader is of infinite size.
def total_train_batches(self) -> int: """ The total number of training batches during training, which may change from epoch to epoch. Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the training dataloader is of infinite size. """ ...
[ "def", "total_train_batches", "(", "self", ")", "->", "int", ":", "return", "self", ".", "trainer", ".", "num_training_batches" ]
[ 135, 4 ]
[ 141, 48 ]
python
en
['en', 'error', 'th']
False
ProgressBarBase.total_val_batches
(self)
The total number of validation batches during validation, which may change from epoch to epoch. Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the validation dataloader is of infinite size.
The total number of validation batches during validation, which may change from epoch to epoch. Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the validation dataloader is of infinite size.
def total_val_batches(self) -> int: """ The total number of validation batches during validation, which may change from epoch to epoch. Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the validation dataloader is of infinite size. """ ...
[ "def", "total_val_batches", "(", "self", ")", "->", "int", ":", "total_val_batches", "=", "0", "if", "not", "self", ".", "trainer", ".", "disable_validation", ":", "is_val_epoch", "=", "(", "self", ".", "trainer", ".", "current_epoch", ")", "%", "self", "....
[ 144, 4 ]
[ 154, 32 ]
python
en
['en', 'error', 'th']
False
ProgressBarBase.total_test_batches
(self)
The total number of testing batches during testing, which may change from epoch to epoch. Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the test dataloader is of infinite size.
The total number of testing batches during testing, which may change from epoch to epoch. Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the test dataloader is of infinite size.
def total_test_batches(self) -> int: """ The total number of testing batches during testing, which may change from epoch to epoch. Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the test dataloader is of infinite size. """ return...
[ "def", "total_test_batches", "(", "self", ")", "->", "int", ":", "return", "sum", "(", "self", ".", "trainer", ".", "num_test_batches", ")" ]
[ 157, 4 ]
[ 163, 49 ]
python
en
['en', 'error', 'th']
False
ProgressBarBase.total_predict_batches
(self)
The total number of predicting batches during testing, which may change from epoch to epoch. Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the predict dataloader is of infinite size.
The total number of predicting batches during testing, which may change from epoch to epoch. Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the predict dataloader is of infinite size.
def total_predict_batches(self) -> int: """ The total number of predicting batches during testing, which may change from epoch to epoch. Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the predict dataloader is of infinite size. """ ...
[ "def", "total_predict_batches", "(", "self", ")", "->", "int", ":", "return", "sum", "(", "self", ".", "trainer", ".", "num_predict_batches", ")" ]
[ 166, 4 ]
[ 172, 52 ]
python
en
['en', 'error', 'th']
False
ProgressBarBase.disable
(self)
You should provide a way to disable the progress bar. The :class:`~pytorch_lightning.trainer.trainer.Trainer` will call this to disable the output on processes that have a rank different from 0, e.g., in multi-node training.
You should provide a way to disable the progress bar. The :class:`~pytorch_lightning.trainer.trainer.Trainer` will call this to disable the output on processes that have a rank different from 0, e.g., in multi-node training.
def disable(self): """ You should provide a way to disable the progress bar. The :class:`~pytorch_lightning.trainer.trainer.Trainer` will call this to disable the output on processes that have a rank different from 0, e.g., in multi-node training. """ raise NotImplemented...
[ "def", "disable", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 174, 4 ]
[ 180, 33 ]
python
en
['en', 'error', 'th']
False
ProgressBarBase.enable
(self)
You should provide a way to enable the progress bar. The :class:`~pytorch_lightning.trainer.trainer.Trainer` will call this in e.g. pre-training routines like the :ref:`learning rate finder <advanced/lr_finder:Learning Rate Finder>` to temporarily enable and disable the main progress ba...
You should provide a way to enable the progress bar. The :class:`~pytorch_lightning.trainer.trainer.Trainer` will call this in e.g. pre-training routines like the :ref:`learning rate finder <advanced/lr_finder:Learning Rate Finder>` to temporarily enable and disable the main progress ba...
def enable(self): """ You should provide a way to enable the progress bar. The :class:`~pytorch_lightning.trainer.trainer.Trainer` will call this in e.g. pre-training routines like the :ref:`learning rate finder <advanced/lr_finder:Learning Rate Finder>` to temporarily enable and...
[ "def", "enable", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 182, 4 ]
[ 189, 33 ]
python
en
['en', 'error', 'th']
False
ProgressBarBase.print
(self, *args, **kwargs)
You should provide a way to print without breaking the progress bar.
You should provide a way to print without breaking the progress bar.
def print(self, *args, **kwargs): """ You should provide a way to print without breaking the progress bar. """ print(*args, **kwargs)
[ "def", "print", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "print", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 191, 4 ]
[ 195, 30 ]
python
en
['en', 'error', 'th']
False