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
test_suggestion_with_non_finite_values
(tmpdir)
Test that non-finite values does not alter results
Test that non-finite values does not alter results
def test_suggestion_with_non_finite_values(tmpdir): """ Test that non-finite values does not alter results """ hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) # logger file to get meta trainer = Trainer( default_root_dir=tmpdir, max_epochs=3, ...
[ "def", "test_suggestion_with_non_finite_values", "(", "tmpdir", ")", ":", "hparams", "=", "EvalModelTemplate", ".", "get_default_hparams", "(", ")", "model", "=", "EvalModelTemplate", "(", "*", "*", "hparams", ")", "# logger file to get meta", "trainer", "=", "Trainer...
[ 247, 0 ]
[ 265, 69 ]
python
en
['en', 'en', 'en']
True
test_lr_finder_fails_fast_on_bad_config
(tmpdir)
Test that tune fails if the model does not have a lr BEFORE running lr find
Test that tune fails if the model does not have a lr BEFORE running lr find
def test_lr_finder_fails_fast_on_bad_config(tmpdir): """ Test that tune fails if the model does not have a lr BEFORE running lr find """ trainer = Trainer(default_root_dir=tmpdir, max_steps=2, auto_lr_find=True) with pytest.raises(MisconfigurationException, match='should have one of these fields'): ...
[ "def", "test_lr_finder_fails_fast_on_bad_config", "(", "tmpdir", ")", ":", "trainer", "=", "Trainer", "(", "default_root_dir", "=", "tmpdir", ",", "max_steps", "=", "2", ",", "auto_lr_find", "=", "True", ")", "with", "pytest", ".", "raises", "(", "Misconfigurati...
[ 268, 0 ]
[ 272, 35 ]
python
en
['en', 'en', 'en']
True
HorovodPlugin.reduce
(self, tensor, group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = "mean")
Reduces a tensor from several distributed processes to one aggregated tensor. Args: tensor: the tensor to sync and reduce group: the process group to gather results from. Defaults to all processes (world) reduce_op: the reduction operation. Defaults to 'mean'/'avg'....
Reduces a tensor from several distributed processes to one aggregated tensor.
def reduce(self, tensor, group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = "mean"): """ Reduces a tensor from several distributed processes to one aggregated tensor. Args: tensor: the tensor to sync and reduce group: the process group to gather res...
[ "def", "reduce", "(", "self", ",", "tensor", ",", "group", ":", "Optional", "[", "Any", "]", "=", "None", ",", "reduce_op", ":", "Optional", "[", "Union", "[", "ReduceOp", ",", "str", "]", "]", "=", "\"mean\"", ")", ":", "if", "group", "is", "not",...
[ 129, 4 ]
[ 157, 50 ]
python
en
['en', 'error', 'th']
False
atomic_save
(checkpoint, filepath: str)
Saves a checkpoint atomically, avoiding the creation of incomplete checkpoints. Args: checkpoint: The object to save. Built to be used with the ``dump_checkpoint`` method, but can deal with anything which ``torch.save`` accepts. filepath: The path to which the checkpoint wil...
Saves a checkpoint atomically, avoiding the creation of incomplete checkpoints.
def atomic_save(checkpoint, filepath: str): """Saves a checkpoint atomically, avoiding the creation of incomplete checkpoints. Args: checkpoint: The object to save. Built to be used with the ``dump_checkpoint`` method, but can deal with anything which ``torch.save`` accepts. ...
[ "def", "atomic_save", "(", "checkpoint", ",", "filepath", ":", "str", ")", ":", "bytesbuffer", "=", "io", ".", "BytesIO", "(", ")", "# Can't use the new zipfile serialization for 1.6.0 because there's a bug in", "# torch.hub.load_state_dict_from_url() that prevents it from loadin...
[ 44, 0 ]
[ 64, 39 ]
python
en
['en', 'en', 'en']
True
is_block
(modules)
Check if is ResNet building block.
Check if is ResNet building block.
def is_block(modules): """Check if is ResNet building block.""" if isinstance(modules, (InvertedResidual, )): return True return False
[ "def", "is_block", "(", "modules", ")", ":", "if", "isinstance", "(", "modules", ",", "(", "InvertedResidual", ",", ")", ")", ":", "return", "True", "return", "False" ]
[ 9, 0 ]
[ 13, 16 ]
python
en
['en', 'en', 'en']
True
is_norm
(modules)
Check if is one of the norms.
Check if is one of the norms.
def is_norm(modules): """Check if is one of the norms.""" if isinstance(modules, (GroupNorm, _BatchNorm)): return True return False
[ "def", "is_norm", "(", "modules", ")", ":", "if", "isinstance", "(", "modules", ",", "(", "GroupNorm", ",", "_BatchNorm", ")", ")", ":", "return", "True", "return", "False" ]
[ 16, 0 ]
[ 20, 16 ]
python
en
['en', 'en', 'en']
True
check_norm_state
(modules, train_state)
Check if norm layer is in correct train state.
Check if norm layer is in correct train state.
def check_norm_state(modules, train_state): """Check if norm layer is in correct train state.""" for mod in modules: if isinstance(mod, _BatchNorm): if mod.training != train_state: return False return True
[ "def", "check_norm_state", "(", "modules", ",", "train_state", ")", ":", "for", "mod", "in", "modules", ":", "if", "isinstance", "(", "mod", ",", "_BatchNorm", ")", ":", "if", "mod", ".", "training", "!=", "train_state", ":", "return", "False", "return", ...
[ 23, 0 ]
[ 29, 15 ]
python
en
['en', 'en', 'en']
True
NumpyDocTestFinder._from_module
(self, module, object)
Return true if the given object is defined in the given module.
Return true if the given object is defined in the given module.
def _from_module(self, module, object): """ Return true if the given object is defined in the given module. """ if module is None: return True elif inspect.isfunction(object): return module.__dict__ is object.__globals__ elif inspect.isbuil...
[ "def", "_from_module", "(", "self", ",", "module", ",", "object", ")", ":", "if", "module", "is", "None", ":", "return", "True", "elif", "inspect", ".", "isfunction", "(", "object", ")", ":", "return", "module", ".", "__dict__", "is", "object", ".", "_...
[ 31, 4 ]
[ 57, 66 ]
python
en
['en', 'error', 'th']
False
NumpyDocTestFinder._find
(self, tests, obj, name, module, source_lines, globs, seen)
Find tests for the given object and any contained objects, and add them to `tests`.
Find tests for the given object and any contained objects, and add them to `tests`.
def _find(self, tests, obj, name, module, source_lines, globs, seen): """ Find tests for the given object and any contained objects, and add them to `tests`. """ doctest.DocTestFinder._find(self, tests, obj, name, module, source_lines, globs, ...
[ "def", "_find", "(", "self", ",", "tests", ",", "obj", ",", "name", ",", "module", ",", "source_lines", ",", "globs", ",", "seen", ")", ":", "doctest", ".", "DocTestFinder", ".", "_find", "(", "self", ",", "tests", ",", "obj", ",", "name", ",", "mo...
[ 59, 4 ]
[ 102, 43 ]
python
en
['en', 'error', 'th']
False
NumpyDoctest.set_test_context
(self, test)
Configure `test` object to set test context We set the numpy / scipy standard doctest namespace Parameters ---------- test : test object with ``globs`` dictionary defining namespace Returns ------- None Notes ----- `test` o...
Configure `test` object to set test context
def set_test_context(self, test): """ Configure `test` object to set test context We set the numpy / scipy standard doctest namespace Parameters ---------- test : test object with ``globs`` dictionary defining namespace Returns ------- None ...
[ "def", "set_test_context", "(", "self", ",", "test", ")", ":", "# set the namespace for tests", "pkg_name", "=", "get_package_name", "(", "os", ".", "path", ".", "dirname", "(", "test", ".", "filename", ")", ")", "# Each doctest should execute in an environment equiva...
[ 189, 4 ]
[ 226, 71 ]
python
en
['en', 'en', 'en']
True
NumpyTestProgram.runTests
(self)
Run Tests. Returns true on success, false on failure, and sets self.success to the same value. Because nose currently discards the test result object, but we need to return it to the user, override TestProgram.runTests to retain the result
Run Tests. Returns true on success, false on failure, and sets self.success to the same value.
def runTests(self): """Run Tests. Returns true on success, false on failure, and sets self.success to the same value. Because nose currently discards the test result object, but we need to return it to the user, override TestProgram.runTests to retain the result """ ...
[ "def", "runTests", "(", "self", ")", ":", "if", "self", ".", "testRunner", "is", "None", ":", "self", ".", "testRunner", "=", "nose", ".", "core", ".", "TextTestRunner", "(", "stream", "=", "self", ".", "config", ".", "stream", ",", "verbosity", "=", ...
[ 348, 4 ]
[ 365, 27 ]
python
en
['en', 'sm', 'en']
True
config.check_type
(self, type_name, headers=None, include_dirs=None, library_dirs=None)
Check type availability. Return True if the type can be compiled, False otherwise
Check type availability. Return True if the type can be compiled, False otherwise
def check_type(self, type_name, headers=None, include_dirs=None, library_dirs=None): """Check type availability. Return True if the type can be compiled, False otherwise""" self._check_compiler() # First check the type can be compiled body = textwrap.dedent(r""" ...
[ "def", "check_type", "(", "self", ",", "type_name", ",", "headers", "=", "None", ",", "include_dirs", "=", "None", ",", "library_dirs", "=", "None", ")", ":", "self", ".", "_check_compiler", "(", ")", "# First check the type can be compiled", "body", "=", "tex...
[ 204, 4 ]
[ 231, 17 ]
python
en
['en', 'en', 'en']
True
config.check_type_size
(self, type_name, headers=None, include_dirs=None, library_dirs=None, expected=None)
Check size of a given type.
Check size of a given type.
def check_type_size(self, type_name, headers=None, include_dirs=None, library_dirs=None, expected=None): """Check size of a given type.""" self._check_compiler() # First check the type can be compiled body = textwrap.dedent(r""" typedef %(type)s npy_check_sizeof_type; ...
[ "def", "check_type_size", "(", "self", ",", "type_name", ",", "headers", "=", "None", ",", "include_dirs", "=", "None", ",", "library_dirs", "=", "None", ",", "expected", "=", "None", ")", ":", "self", ".", "_check_compiler", "(", ")", "# First check the typ...
[ 233, 4 ]
[ 314, 18 ]
python
en
['en', 'en', 'en']
True
config.check_funcs_once
(self, funcs, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, call_args=None)
Check a list of functions at once. This is useful to speed up things, since all the functions in the funcs list will be put in one compilation unit. Arguments --------- funcs : seq list of functions to test include_dirs : seq list of header paths...
Check a list of functions at once.
def check_funcs_once(self, funcs, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, call_args=None): """Check a list of functions at once. This is useful to speed up things, since all the functions in the...
[ "def", "check_funcs_once", "(", "self", ",", "funcs", ",", "headers", "=", "None", ",", "include_dirs", "=", "None", ",", "libraries", "=", "None", ",", "library_dirs", "=", "None", ",", "decl", "=", "False", ",", "call", "=", "False", ",", "call_args", ...
[ 350, 4 ]
[ 409, 53 ]
python
en
['en', 'en', 'en']
True
config.check_inline
(self)
Return the inline keyword recognized by the compiler, empty string otherwise.
Return the inline keyword recognized by the compiler, empty string otherwise.
def check_inline(self): """Return the inline keyword recognized by the compiler, empty string otherwise.""" return check_inline(self)
[ "def", "check_inline", "(", "self", ")", ":", "return", "check_inline", "(", "self", ")" ]
[ 411, 4 ]
[ 414, 33 ]
python
en
['en', 'en', 'en']
True
config.check_restrict
(self)
Return the restrict keyword recognized by the compiler, empty string otherwise.
Return the restrict keyword recognized by the compiler, empty string otherwise.
def check_restrict(self): """Return the restrict keyword recognized by the compiler, empty string otherwise.""" return check_restrict(self)
[ "def", "check_restrict", "(", "self", ")", ":", "return", "check_restrict", "(", "self", ")" ]
[ 416, 4 ]
[ 419, 35 ]
python
en
['en', 'en', 'en']
True
config.check_compiler_gcc4
(self)
Return True if the C compiler is gcc >= 4.
Return True if the C compiler is gcc >= 4.
def check_compiler_gcc4(self): """Return True if the C compiler is gcc >= 4.""" return check_compiler_gcc4(self)
[ "def", "check_compiler_gcc4", "(", "self", ")", ":", "return", "check_compiler_gcc4", "(", "self", ")" ]
[ 421, 4 ]
[ 423, 40 ]
python
en
['en', 'la', 'en']
True
config.get_output
(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c", use_tee=None)
Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Returns the exit status code of the program and its output.
Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Returns the exit status code of the program and its output.
def get_output(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c", use_tee=None): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Returns the exit status code of the program a...
[ "def", "get_output", "(", "self", ",", "body", ",", "headers", "=", "None", ",", "include_dirs", "=", "None", ",", "libraries", "=", "None", ",", "library_dirs", "=", "None", ",", "lang", "=", "\"c\"", ",", "use_tee", "=", "None", ")", ":", "# 2008-11-...
[ 436, 4 ]
[ 495, 31 ]
python
en
['en', 'en', 'en']
True
fetch_stackexchange
(dataset, test_set_fraction=0.2, min_training_interactions=1, data_home=None, indicator_features=True, tag_features=False, download_if_missing=True)
Fetch a dataset from the `StackExchange network <http://stackexchange.com/>`_. The datasets contain users answering questions: an interaction is defined as a user answering a given question. The following datasets from the StackExchange network are available: - CrossValidated: From stats.stackex...
Fetch a dataset from the `StackExchange network <http://stackexchange.com/>`_.
def fetch_stackexchange(dataset, test_set_fraction=0.2, min_training_interactions=1, data_home=None, indicator_features=True, tag_features=False, download_if_missing=True): """ Fetch a dataset from the `StackExchange...
[ "def", "fetch_stackexchange", "(", "dataset", ",", "test_set_fraction", "=", "0.2", ",", "min_training_interactions", "=", "1", ",", "data_home", "=", "None", ",", "indicator_features", "=", "True", ",", "tag_features", "=", "False", ",", "download_if_missing", "=...
[ 9, 0 ]
[ 139, 42 ]
python
en
['en', 'error', 'th']
False
BoringModel.__init__
(self)
Testing PL Module Use as follows: - subclass - modify the behavior for what you want class TestModel(BaseTestModel): def training_step(...): # do your own thing or: model = BaseTestModel() model.training_epoch_end = None ...
Testing PL Module
def __init__(self): """ Testing PL Module Use as follows: - subclass - modify the behavior for what you want class TestModel(BaseTestModel): def training_step(...): # do your own thing or: model = BaseTestModel() mod...
[ "def", "__init__", "(", "self", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "layer", "=", "torch", ".", "nn", ".", "Linear", "(", "32", ",", "2", ")" ]
[ 64, 4 ]
[ 83, 43 ]
python
en
['en', 'error', 'th']
False
zeros_like
(a, dtype=None, order='K', subok=True, shape=None)
Return an array of zeros with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. dtype : data-type, optional Overrides the data type of the result. .. ver...
Return an array of zeros with the same shape and type as a given array.
def zeros_like(a, dtype=None, order='K', subok=True, shape=None): """ Return an array of zeros with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. dtype : data-type...
[ "def", "zeros_like", "(", "a", ",", "dtype", "=", "None", ",", "order", "=", "'K'", ",", "subok", "=", "True", ",", "shape", "=", "None", ")", ":", "res", "=", "empty_like", "(", "a", ",", "dtype", "=", "dtype", ",", "order", "=", "order", ",", ...
[ 97, 0 ]
[ 162, 14 ]
python
en
['en', 'error', 'th']
False
ones
(shape, dtype=None, order='C')
Return a new array of given shape and type, filled with ones. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. dtype : data-type, optional The desired data-type for the array, e.g., `numpy.int8`. Default is `numpy.flo...
Return a new array of given shape and type, filled with ones.
def ones(shape, dtype=None, order='C'): """ Return a new array of given shape and type, filled with ones. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. dtype : data-type, optional The desired data-type for the array, e.g...
[ "def", "ones", "(", "shape", ",", "dtype", "=", "None", ",", "order", "=", "'C'", ")", ":", "a", "=", "empty", "(", "shape", ",", "dtype", ",", "order", ")", "multiarray", ".", "copyto", "(", "a", ",", "1", ",", "casting", "=", "'unsafe'", ")", ...
[ 166, 0 ]
[ 215, 12 ]
python
en
['en', 'error', 'th']
False
ones_like
(a, dtype=None, order='K', subok=True, shape=None)
Return an array of ones with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. dtype : data-type, optional Overrides the data type of the result. .. vers...
Return an array of ones with the same shape and type as a given array.
def ones_like(a, dtype=None, order='K', subok=True, shape=None): """ Return an array of ones with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. dtype : data-type, ...
[ "def", "ones_like", "(", "a", ",", "dtype", "=", "None", ",", "order", "=", "'K'", ",", "subok", "=", "True", ",", "shape", "=", "None", ")", ":", "res", "=", "empty_like", "(", "a", ",", "dtype", "=", "dtype", ",", "order", "=", "order", ",", ...
[ 223, 0 ]
[ 286, 14 ]
python
en
['en', 'error', 'th']
False
full
(shape, fill_value, dtype=None, order='C')
Return a new array of given shape and type, filled with `fill_value`. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. fill_value : scalar Fill value. dtype : data-type, optional The desired data-type for the array...
Return a new array of given shape and type, filled with `fill_value`.
def full(shape, fill_value, dtype=None, order='C'): """ Return a new array of given shape and type, filled with `fill_value`. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. fill_value : scalar Fill value. dtype : data...
[ "def", "full", "(", "shape", ",", "fill_value", ",", "dtype", "=", "None", ",", "order", "=", "'C'", ")", ":", "if", "dtype", "is", "None", ":", "dtype", "=", "array", "(", "fill_value", ")", ".", "dtype", "a", "=", "empty", "(", "shape", ",", "d...
[ 290, 0 ]
[ 333, 12 ]
python
en
['en', 'error', 'th']
False
full_like
(a, fill_value, dtype=None, order='K', subok=True, shape=None)
Return a full array with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. fill_value : scalar Fill value. dtype : data-type, optional Overrides the d...
Return a full array with the same shape and type as a given array.
def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None): """ Return a full array with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. fill_value ...
[ "def", "full_like", "(", "a", ",", "fill_value", ",", "dtype", "=", "None", ",", "order", "=", "'K'", ",", "subok", "=", "True", ",", "shape", "=", "None", ")", ":", "res", "=", "empty_like", "(", "a", ",", "dtype", "=", "dtype", ",", "order", "=...
[ 341, 0 ]
[ 401, 14 ]
python
en
['en', 'error', 'th']
False
count_nonzero
(a, axis=None)
Counts the number of non-zero values in the array ``a``. The word "non-zero" is in reference to the Python 2.x built-in method ``__nonzero__()`` (renamed ``__bool__()`` in Python 3.x) of Python objects that tests an object's "truthfulness". For example, any number is considered truthful if it ...
Counts the number of non-zero values in the array ``a``.
def count_nonzero(a, axis=None): """ Counts the number of non-zero values in the array ``a``. The word "non-zero" is in reference to the Python 2.x built-in method ``__nonzero__()`` (renamed ``__bool__()`` in Python 3.x) of Python objects that tests an object's "truthfulness". For example, any ...
[ "def", "count_nonzero", "(", "a", ",", "axis", "=", "None", ")", ":", "if", "axis", "is", "None", ":", "return", "multiarray", ".", "count_nonzero", "(", "a", ")", "a", "=", "asanyarray", "(", "a", ")", "# TODO: this works around .astype(bool) not working prop...
[ 409, 0 ]
[ 468, 47 ]
python
en
['en', 'error', 'th']
False
isfortran
(a)
Check if the array is Fortran contiguous but *not* C contiguous. This function is obsolete and, because of changes due to relaxed stride checking, its return value for the same array may differ for versions of NumPy >= 1.10.0 and previous versions. If you only want to check if an array is Fortran ...
Check if the array is Fortran contiguous but *not* C contiguous.
def isfortran(a): """ Check if the array is Fortran contiguous but *not* C contiguous. This function is obsolete and, because of changes due to relaxed stride checking, its return value for the same array may differ for versions of NumPy >= 1.10.0 and previous versions. If you only want to check if...
[ "def", "isfortran", "(", "a", ")", ":", "return", "a", ".", "flags", ".", "fnc" ]
[ 472, 0 ]
[ 536, 22 ]
python
en
['en', 'error', 'th']
False
argwhere
(a)
Find the indices of array elements that are non-zero, grouped by element. Parameters ---------- a : array_like Input data. Returns ------- index_array : ndarray Indices of elements that are non-zero. Indices are grouped by element. See Also -------- where, non...
Find the indices of array elements that are non-zero, grouped by element.
def argwhere(a): """ Find the indices of array elements that are non-zero, grouped by element. Parameters ---------- a : array_like Input data. Returns ------- index_array : ndarray Indices of elements that are non-zero. Indices are grouped by element. See Also ...
[ "def", "argwhere", "(", "a", ")", ":", "return", "transpose", "(", "nonzero", "(", "a", ")", ")" ]
[ 544, 0 ]
[ 582, 32 ]
python
en
['en', 'error', 'th']
False
flatnonzero
(a)
Return indices that are non-zero in the flattened version of a. This is equivalent to np.nonzero(np.ravel(a))[0]. Parameters ---------- a : array_like Input data. Returns ------- res : ndarray Output array, containing the indices of the elements of `a.ravel()` ...
Return indices that are non-zero in the flattened version of a.
def flatnonzero(a): """ Return indices that are non-zero in the flattened version of a. This is equivalent to np.nonzero(np.ravel(a))[0]. Parameters ---------- a : array_like Input data. Returns ------- res : ndarray Output array, containing the indices of the elem...
[ "def", "flatnonzero", "(", "a", ")", ":", "return", "np", ".", "nonzero", "(", "np", ".", "ravel", "(", "a", ")", ")", "[", "0", "]" ]
[ 590, 0 ]
[ 627, 37 ]
python
en
['en', 'error', 'th']
False
correlate
(a, v, mode='valid')
Cross-correlation of two 1-dimensional sequences. This function computes the correlation as generally defined in signal processing texts:: c_{av}[k] = sum_n a[n+k] * conj(v[n]) with a and v sequences being zero-padded where necessary and conj being the conjugate. Parameters ----...
Cross-correlation of two 1-dimensional sequences.
def correlate(a, v, mode='valid'): """ Cross-correlation of two 1-dimensional sequences. This function computes the correlation as generally defined in signal processing texts:: c_{av}[k] = sum_n a[n+k] * conj(v[n]) with a and v sequences being zero-padded where necessary and conj being ...
[ "def", "correlate", "(", "a", ",", "v", ",", "mode", "=", "'valid'", ")", ":", "mode", "=", "_mode_from_name", "(", "mode", ")", "return", "multiarray", ".", "correlate2", "(", "a", ",", "v", ",", "mode", ")" ]
[ 646, 0 ]
[ 711, 44 ]
python
en
['en', 'error', 'th']
False
convolve
(a, v, mode='full')
Returns the discrete, linear convolution of two one-dimensional sequences. The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal [1]_. In probability theory, the sum of two independent random variables is distributed ...
Returns the discrete, linear convolution of two one-dimensional sequences.
def convolve(a, v, mode='full'): """ Returns the discrete, linear convolution of two one-dimensional sequences. The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal [1]_. In probability theory, the sum of two independ...
[ "def", "convolve", "(", "a", ",", "v", ",", "mode", "=", "'full'", ")", ":", "a", ",", "v", "=", "array", "(", "a", ",", "copy", "=", "False", ",", "ndmin", "=", "1", ")", ",", "array", "(", "v", ",", "copy", "=", "False", ",", "ndmin", "="...
[ 719, 0 ]
[ 815, 49 ]
python
en
['en', 'error', 'th']
False
outer
(a, b, out=None)
Compute the outer product of two vectors. Given two vectors, ``a = [a0, a1, ..., aM]`` and ``b = [b0, b1, ..., bN]``, the outer product [1]_ is:: [[a0*b0 a0*b1 ... a0*bN ] [a1*b0 . [ ... . [aM*b0 aM*bN ]] Parameters ---------- a : (M,) a...
Compute the outer product of two vectors.
def outer(a, b, out=None): """ Compute the outer product of two vectors. Given two vectors, ``a = [a0, a1, ..., aM]`` and ``b = [b0, b1, ..., bN]``, the outer product [1]_ is:: [[a0*b0 a0*b1 ... a0*bN ] [a1*b0 . [ ... . [aM*b0 aM*bN ]] Parame...
[ "def", "outer", "(", "a", ",", "b", ",", "out", "=", "None", ")", ":", "a", "=", "asarray", "(", "a", ")", "b", "=", "asarray", "(", "b", ")", "return", "multiply", "(", "a", ".", "ravel", "(", ")", "[", ":", ",", "newaxis", "]", ",", "b", ...
[ 823, 0 ]
[ 904, 70 ]
python
en
['en', 'error', 'th']
False
tensordot
(a, b, axes=2)
Compute tensor dot product along specified axes. Given two tensors, `a` and `b`, and an array_like object containing two array_like objects, ``(a_axes, b_axes)``, sum the products of `a`'s and `b`'s elements (components) over the axes specified by ``a_axes`` and ``b_axes``. The third argument can ...
Compute tensor dot product along specified axes.
def tensordot(a, b, axes=2): """ Compute tensor dot product along specified axes. Given two tensors, `a` and `b`, and an array_like object containing two array_like objects, ``(a_axes, b_axes)``, sum the products of `a`'s and `b`'s elements (components) over the axes specified by ``a_axes`` and...
[ "def", "tensordot", "(", "a", ",", "b", ",", "axes", "=", "2", ")", ":", "try", ":", "iter", "(", "axes", ")", "except", "Exception", ":", "axes_a", "=", "list", "(", "range", "(", "-", "axes", ",", "0", ")", ")", "axes_b", "=", "list", "(", ...
[ 912, 0 ]
[ 1098, 35 ]
python
en
['en', 'error', 'th']
False
roll
(a, shift, axis=None)
Roll array elements along a given axis. Elements that roll beyond the last position are re-introduced at the first. Parameters ---------- a : array_like Input array. shift : int or tuple of ints The number of places by which elements are shifted. If a tuple, then ...
Roll array elements along a given axis.
def roll(a, shift, axis=None): """ Roll array elements along a given axis. Elements that roll beyond the last position are re-introduced at the first. Parameters ---------- a : array_like Input array. shift : int or tuple of ints The number of places by which elements a...
[ "def", "roll", "(", "a", ",", "shift", ",", "axis", "=", "None", ")", ":", "a", "=", "asanyarray", "(", "a", ")", "if", "axis", "is", "None", ":", "return", "roll", "(", "a", ".", "ravel", "(", ")", ",", "shift", ",", "0", ")", ".", "reshape"...
[ 1106, 0 ]
[ 1203, 21 ]
python
en
['en', 'error', 'th']
False
rollaxis
(a, axis, start=0)
Roll the specified axis backwards, until it lies in a given position. This function continues to be supported for backward compatibility, but you should prefer `moveaxis`. The `moveaxis` function was added in NumPy 1.11. Parameters ---------- a : ndarray Input array. axis : in...
Roll the specified axis backwards, until it lies in a given position.
def rollaxis(a, axis, start=0): """ Roll the specified axis backwards, until it lies in a given position. This function continues to be supported for backward compatibility, but you should prefer `moveaxis`. The `moveaxis` function was added in NumPy 1.11. Parameters ---------- a : nda...
[ "def", "rollaxis", "(", "a", ",", "axis", ",", "start", "=", "0", ")", ":", "n", "=", "a", ".", "ndim", "axis", "=", "normalize_axis_index", "(", "axis", ",", "n", ")", "if", "start", "<", "0", ":", "start", "+=", "n", "msg", "=", "\"'%s' arg req...
[ 1211, 0 ]
[ 1269, 28 ]
python
en
['en', 'error', 'th']
False
normalize_axis_tuple
(axis, ndim, argname=None, allow_duplicate=False)
Normalizes an axis argument into a tuple of non-negative integer axes. This handles shorthands such as ``1`` and converts them to ``(1,)``, as well as performing the handling of negative indices covered by `normalize_axis_index`. By default, this forbids axes from being specified multiple times. ...
Normalizes an axis argument into a tuple of non-negative integer axes.
def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False): """ Normalizes an axis argument into a tuple of non-negative integer axes. This handles shorthands such as ``1`` and converts them to ``(1,)``, as well as performing the handling of negative indices covered by `normalize_axi...
[ "def", "normalize_axis_tuple", "(", "axis", ",", "ndim", ",", "argname", "=", "None", ",", "allow_duplicate", "=", "False", ")", ":", "# Optimization to speed-up the most common cases.", "if", "type", "(", "axis", ")", "not", "in", "(", "tuple", ",", "list", "...
[ 1272, 0 ]
[ 1328, 15 ]
python
en
['en', 'error', 'th']
False
moveaxis
(a, source, destination)
Move axes of an array to new positions. Other axes remain in their original order. .. versionadded:: 1.11.0 Parameters ---------- a : np.ndarray The array whose axes should be reordered. source : int or sequence of int Original positions of the axes to move. These must be...
Move axes of an array to new positions.
def moveaxis(a, source, destination): """ Move axes of an array to new positions. Other axes remain in their original order. .. versionadded:: 1.11.0 Parameters ---------- a : np.ndarray The array whose axes should be reordered. source : int or sequence of int Original...
[ "def", "moveaxis", "(", "a", ",", "source", ",", "destination", ")", ":", "try", ":", "# allow duck-array types if they define transpose", "transpose", "=", "a", ".", "transpose", "except", "AttributeError", ":", "a", "=", "asarray", "(", "a", ")", "transpose", ...
[ 1336, 0 ]
[ 1404, 17 ]
python
en
['en', 'error', 'th']
False
cross
(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None)
Return the cross product of two (arrays of) vectors. The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors are defined by the last axis of `a` and `b` by default, and these axes can have dimensions 2 or 3. ...
Return the cross product of two (arrays of) vectors.
def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): """ Return the cross product of two (arrays of) vectors. The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors are defined by the last axis of `a` an...
[ "def", "cross", "(", "a", ",", "b", ",", "axisa", "=", "-", "1", ",", "axisb", "=", "-", "1", ",", "axisc", "=", "-", "1", ",", "axis", "=", "None", ")", ":", "if", "axis", "is", "not", "None", ":", "axisa", ",", "axisb", ",", "axisc", "=",...
[ 1417, 0 ]
[ 1611, 34 ]
python
en
['en', 'error', 'th']
False
indices
(dimensions, dtype=int, sparse=False)
Return an array representing the indices of a grid. Compute an array where the subarrays contain index values 0, 1, ... varying only along the corresponding axis. Parameters ---------- dimensions : sequence of ints The shape of the grid. dtype : dtype, optional Data type o...
Return an array representing the indices of a grid.
def indices(dimensions, dtype=int, sparse=False): """ Return an array representing the indices of a grid. Compute an array where the subarrays contain index values 0, 1, ... varying only along the corresponding axis. Parameters ---------- dimensions : sequence of ints The shape of ...
[ "def", "indices", "(", "dimensions", ",", "dtype", "=", "int", ",", "sparse", "=", "False", ")", ":", "dimensions", "=", "tuple", "(", "dimensions", ")", "N", "=", "len", "(", "dimensions", ")", "shape", "=", "(", "1", ",", ")", "*", "N", "if", "...
[ 1618, 0 ]
[ 1717, 14 ]
python
en
['en', 'error', 'th']
False
fromfunction
(function, shape, **kwargs)
Construct an array by executing a function over each coordinate. The resulting array therefore has a value ``fn(x, y, z)`` at coordinate ``(x, y, z)``. Parameters ---------- function : callable The function is called with N parameters, where N is the rank of `shape`. Each par...
Construct an array by executing a function over each coordinate.
def fromfunction(function, shape, **kwargs): """ Construct an array by executing a function over each coordinate. The resulting array therefore has a value ``fn(x, y, z)`` at coordinate ``(x, y, z)``. Parameters ---------- function : callable The function is called with N parameter...
[ "def", "fromfunction", "(", "function", ",", "shape", ",", "*", "*", "kwargs", ")", ":", "dtype", "=", "kwargs", ".", "pop", "(", "'dtype'", ",", "float", ")", "args", "=", "indices", "(", "shape", ",", "dtype", "=", "dtype", ")", "return", "function...
[ 1721, 0 ]
[ 1774, 36 ]
python
en
['en', 'error', 'th']
False
isscalar
(num)
Returns True if the type of `num` is a scalar type. Parameters ---------- num : any Input argument, can be of any type and shape. Returns ------- val : bool True if `num` is a scalar type, False if it is not. See Also -------- ndim : Get the number of dimensio...
Returns True if the type of `num` is a scalar type.
def isscalar(num): """ Returns True if the type of `num` is a scalar type. Parameters ---------- num : any Input argument, can be of any type and shape. Returns ------- val : bool True if `num` is a scalar type, False if it is not. See Also -------- ndim : ...
[ "def", "isscalar", "(", "num", ")", ":", "return", "(", "isinstance", "(", "num", ",", "generic", ")", "or", "type", "(", "num", ")", "in", "ScalarType", "or", "isinstance", "(", "num", ",", "numbers", ".", "Number", ")", ")" ]
[ 1782, 0 ]
[ 1855, 47 ]
python
en
['en', 'error', 'th']
False
binary_repr
(num, width=None)
Return the binary representation of the input number as a string. For negative numbers, if width is not given, a minus sign is added to the front. If width is given, the two's complement of the number is returned, with respect to that width. In a two's-complement system negative numbers are repre...
Return the binary representation of the input number as a string.
def binary_repr(num, width=None): """ Return the binary representation of the input number as a string. For negative numbers, if width is not given, a minus sign is added to the front. If width is given, the two's complement of the number is returned, with respect to that width. In a two's-com...
[ "def", "binary_repr", "(", "num", ",", "width", "=", "None", ")", ":", "def", "warn_if_insufficient", "(", "width", ",", "binwidth", ")", ":", "if", "width", "is", "not", "None", "and", "width", "<", "binwidth", ":", "warnings", ".", "warn", "(", "\"In...
[ 1859, 0 ]
[ 1966, 55 ]
python
en
['en', 'error', 'th']
False
base_repr
(number, base=2, padding=0)
Return a string representation of a number in the given base system. Parameters ---------- number : int The value to convert. Positive and negative values are handled. base : int, optional Convert `number` to the `base` number system. The valid range is 2-36, the default va...
Return a string representation of a number in the given base system.
def base_repr(number, base=2, padding=0): """ Return a string representation of a number in the given base system. Parameters ---------- number : int The value to convert. Positive and negative values are handled. base : int, optional Convert `number` to the `base` number system...
[ "def", "base_repr", "(", "number", ",", "base", "=", "2", ",", "padding", "=", "0", ")", ":", "digits", "=", "'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'", "if", "base", ">", "len", "(", "digits", ")", ":", "raise", "ValueError", "(", "\"Bases greater than 36 not h...
[ 1970, 0 ]
[ 2023, 40 ]
python
en
['en', 'error', 'th']
False
load
(file)
Wrapper around cPickle.load which accepts either a file-like object or a filename. Note that the NumPy binary format is not based on pickle/cPickle anymore. For details on the preferred way of loading and saving files, see `load` and `save`. See Also -------- load, save
Wrapper around cPickle.load which accepts either a file-like object or a filename.
def load(file): """ Wrapper around cPickle.load which accepts either a file-like object or a filename. Note that the NumPy binary format is not based on pickle/cPickle anymore. For details on the preferred way of loading and saving files, see `load` and `save`. See Also -------- lo...
[ "def", "load", "(", "file", ")", ":", "# NumPy 1.15.0, 2017-12-10", "warnings", ".", "warn", "(", "\"np.core.numeric.load is deprecated, use pickle.load instead\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "if", "isinstance", "(", "file", ",", "typ...
[ 2026, 0 ]
[ 2047, 28 ]
python
en
['en', 'error', 'th']
False
identity
(n, dtype=None)
Return the identity array. The identity array is a square array with ones on the main diagonal. Parameters ---------- n : int Number of rows (and columns) in `n` x `n` output. dtype : data-type, optional Data-type of the output. Defaults to ``float``. Returns ---...
Return the identity array.
def identity(n, dtype=None): """ Return the identity array. The identity array is a square array with ones on the main diagonal. Parameters ---------- n : int Number of rows (and columns) in `n` x `n` output. dtype : data-type, optional Data-type of the output. Default...
[ "def", "identity", "(", "n", ",", "dtype", "=", "None", ")", ":", "from", "numpy", "import", "eye", "return", "eye", "(", "n", ",", "dtype", "=", "dtype", ")" ]
[ 2066, 0 ]
[ 2095, 30 ]
python
en
['en', 'error', 'th']
False
allclose
(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False)
Returns True if two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (`rtol` * abs(`b`)) and the absolute difference `atol` are added together to compare against the absolute difference between `a` and `b`. ...
Returns True if two arrays are element-wise equal within a tolerance.
def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): """ Returns True if two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (`rtol` * abs(`b`)) and the absolute difference `atol` are added together ...
[ "def", "allclose", "(", "a", ",", "b", ",", "rtol", "=", "1.e-5", ",", "atol", "=", "1.e-8", ",", "equal_nan", "=", "False", ")", ":", "res", "=", "all", "(", "isclose", "(", "a", ",", "b", ",", "rtol", "=", "rtol", ",", "atol", "=", "atol", ...
[ 2103, 0 ]
[ 2171, 20 ]
python
en
['en', 'error', 'th']
False
isclose
(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False)
Returns a boolean array where two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (`rtol` * abs(`b`)) and the absolute difference `atol` are added together to compare against the absolute difference bet...
Returns a boolean array where two arrays are element-wise equal within a tolerance.
def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): """ Returns a boolean array where two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (`rtol` * abs(`b`)) and the absolute difference `atol` ar...
[ "def", "isclose", "(", "a", ",", "b", ",", "rtol", "=", "1.e-5", ",", "atol", "=", "1.e-8", ",", "equal_nan", "=", "False", ")", ":", "def", "within_tol", "(", "x", ",", "y", ",", "atol", ",", "rtol", ")", ":", "with", "errstate", "(", "invalid",...
[ 2179, 0 ]
[ 2291, 23 ]
python
en
['en', 'error', 'th']
False
array_equal
(a1, a2)
True if two arrays have the same shape and elements, False otherwise. Parameters ---------- a1, a2 : array_like Input arrays. Returns ------- b : bool Returns True if the arrays are equal. See Also -------- allclose: Returns True if two arrays are element-wise...
True if two arrays have the same shape and elements, False otherwise.
def array_equal(a1, a2): """ True if two arrays have the same shape and elements, False otherwise. Parameters ---------- a1, a2 : array_like Input arrays. Returns ------- b : bool Returns True if the arrays are equal. See Also -------- allclose: Returns Tru...
[ "def", "array_equal", "(", "a1", ",", "a2", ")", ":", "try", ":", "a1", ",", "a2", "=", "asarray", "(", "a1", ")", ",", "asarray", "(", "a2", ")", "except", "Exception", ":", "return", "False", "if", "a1", ".", "shape", "!=", "a2", ".", "shape", ...
[ 2299, 0 ]
[ 2338, 40 ]
python
en
['en', 'error', 'th']
False
array_equiv
(a1, a2)
Returns True if input arrays are shape consistent and all elements equal. Shape consistent means they are either the same shape, or one input array can be broadcasted to create the same shape as the other one. Parameters ---------- a1, a2 : array_like Input arrays. Returns --...
Returns True if input arrays are shape consistent and all elements equal.
def array_equiv(a1, a2): """ Returns True if input arrays are shape consistent and all elements equal. Shape consistent means they are either the same shape, or one input array can be broadcasted to create the same shape as the other one. Parameters ---------- a1, a2 : array_like I...
[ "def", "array_equiv", "(", "a1", ",", "a2", ")", ":", "try", ":", "a1", ",", "a2", "=", "asarray", "(", "a1", ")", ",", "asarray", "(", "a2", ")", "except", "Exception", ":", "return", "False", "try", ":", "multiarray", ".", "broadcast", "(", "a1",...
[ 2346, 0 ]
[ 2390, 40 ]
python
en
['en', 'error', 'th']
False
Driver.configure
(self)
Resets the device and configures it
Resets the device and configures it
def configure(self): """Resets the device and configures it""" ################################################### # - Bit 0 - SW_RESET - software reset for accelerometer and gyro - default 0 # - Bit 2 - IF_ADD_INC - automatic register increment for multibyte access - default 1 ...
[ "def", "configure", "(", "self", ")", ":", "###################################################\r", "# - Bit 0 - SW_RESET - software reset for accelerometer and gyro - default 0\r", "# - Bit 2 - IF_ADD_INC - automatic register increment for multibyte access - default 1\r", "# - Bit 6 - BDU -...
[ 23, 4 ]
[ 78, 55 ]
python
en
['en', 'en', 'en']
True
Driver.close
(self)
Closes the I2C/SPI connection. This must be called on shutdown.
Closes the I2C/SPI connection. This must be called on shutdown.
def close(self): """Closes the I2C/SPI connection. This must be called on shutdown.""" self.ag.close() self.mag.close()
[ "def", "close", "(", "self", ")", ":", "self", ".", "ag", ".", "close", "(", ")", "self", ".", "mag", ".", "close", "(", ")" ]
[ 80, 4 ]
[ 83, 24 ]
python
en
['en', 'en', 'en']
True
Driver.read_ag_status
(self)
Returns the status byte for the accelerometer and gyroscope.
Returns the status byte for the accelerometer and gyroscope.
def read_ag_status(self) -> AGStatus: """Returns the status byte for the accelerometer and gyroscope.""" data = self.ag.read_byte(Register.STATUS_REG) return AGStatus(data)
[ "def", "read_ag_status", "(", "self", ")", "->", "AGStatus", ":", "data", "=", "self", ".", "ag", ".", "read_byte", "(", "Register", ".", "STATUS_REG", ")", "return", "AGStatus", "(", "data", ")" ]
[ 88, 4 ]
[ 91, 29 ]
python
en
['en', 'en', 'en']
True
Driver.read_ag_data
(self)
Returns the current temperature, acceleration and angular velocity values in one go. This is faster than fetching them independently. These values can be invalid unless they're read when the data is ready.
Returns the current temperature, acceleration and angular velocity values in one go. This is faster than fetching them independently. These values can be invalid unless they're read when the data is ready.
def read_ag_data(self) -> Tuple[int, List[int], List[int]]: """Returns the current temperature, acceleration and angular velocity values in one go. This is faster than fetching them independently. These values can be invalid unless they're read when the data is ready.""" data = self....
[ "def", "read_ag_data", "(", "self", ")", "->", "Tuple", "[", "int", ",", "List", "[", "int", "]", ",", "List", "[", "int", "]", "]", ":", "data", "=", "self", ".", "ag", ".", "read_bytes", "(", "Register", ".", "OUT_TEMP_L", ",", "14", ")", "temp...
[ 93, 4 ]
[ 101, 30 ]
python
en
['en', 'en', 'en']
True
Driver.read_temperature
(self)
Reads the temperature. See also read_ag_data()
Reads the temperature. See also read_ag_data()
def read_temperature(self) -> int: """Reads the temperature. See also read_ag_data()""" data = self.ag.read_bytes(Register.OUT_TEMP_L, 2) return Driver.to_int16(data)
[ "def", "read_temperature", "(", "self", ")", "->", "int", ":", "data", "=", "self", ".", "ag", ".", "read_bytes", "(", "Register", ".", "OUT_TEMP_L", ",", "2", ")", "return", "Driver", ".", "to_int16", "(", "data", ")" ]
[ 103, 4 ]
[ 106, 36 ]
python
en
['en', 'en', 'en']
True
Driver.read_acceleration
(self)
Reads the accelerations. See also read_ag_data()
Reads the accelerations. See also read_ag_data()
def read_acceleration(self) -> List[int]: """Reads the accelerations. See also read_ag_data()""" data = self.ag.read_bytes(Register.OUT_X_XL, 6) return Driver.to_vector_left_to_right_hand_rule(data)
[ "def", "read_acceleration", "(", "self", ")", "->", "List", "[", "int", "]", ":", "data", "=", "self", ".", "ag", ".", "read_bytes", "(", "Register", ".", "OUT_X_XL", ",", "6", ")", "return", "Driver", ".", "to_vector_left_to_right_hand_rule", "(", "data",...
[ 108, 4 ]
[ 111, 61 ]
python
en
['en', 'en', 'en']
True
Driver.read_gyroscope
(self)
Reads the angular velocities. See also read_ag_data()
Reads the angular velocities. See also read_ag_data()
def read_gyroscope(self) -> List[int]: """Reads the angular velocities. See also read_ag_data()""" data = self.ag.read_bytes(Register.OUT_X_G, 6) return Driver.to_vector_left_to_right_hand_rule(data)
[ "def", "read_gyroscope", "(", "self", ")", "->", "List", "[", "int", "]", ":", "data", "=", "self", ".", "ag", ".", "read_bytes", "(", "Register", ".", "OUT_X_G", ",", "6", ")", "return", "Driver", ".", "to_vector_left_to_right_hand_rule", "(", "data", "...
[ 113, 4 ]
[ 116, 61 ]
python
en
['en', 'en', 'en']
True
Driver.read_magnetometer_status
(self)
Returns the status byte for the magnetometer
Returns the status byte for the magnetometer
def read_magnetometer_status(self) -> MagnetometerStatus: """Returns the status byte for the magnetometer""" data = self.mag.read_byte(Register.STATUS_REG_M) return MagnetometerStatus(data)
[ "def", "read_magnetometer_status", "(", "self", ")", "->", "MagnetometerStatus", ":", "data", "=", "self", ".", "mag", ".", "read_byte", "(", "Register", ".", "STATUS_REG_M", ")", "return", "MagnetometerStatus", "(", "data", ")" ]
[ 121, 4 ]
[ 124, 39 ]
python
en
['en', 'en', 'en']
True
Driver.read_magnetometer
(self)
Reads the magnetometer field strengths
Reads the magnetometer field strengths
def read_magnetometer(self) -> List[int]: """Reads the magnetometer field strengths""" data = self.mag.read_bytes(Register.OUT_X_L_M, 6) return Driver.to_vector(data)
[ "def", "read_magnetometer", "(", "self", ")", "->", "List", "[", "int", "]", ":", "data", "=", "self", ".", "mag", ".", "read_bytes", "(", "Register", ".", "OUT_X_L_M", ",", "6", ")", "return", "Driver", ".", "to_vector", "(", "data", ")" ]
[ 126, 4 ]
[ 129, 37 ]
python
en
['en', 'en', 'en']
True
Driver.to_vector_left_to_right_hand_rule
(data: List[int])
Like to_vector except it converts from the left to the right hand rule by negating the x-axis.
Like to_vector except it converts from the left to the right hand rule by negating the x-axis.
def to_vector_left_to_right_hand_rule(data: List[int]) -> List[int]: """Like to_vector except it converts from the left to the right hand rule by negating the x-axis.""" return [-Driver.to_int16(data[0:2]), Driver.to_int16(data[2:4]), Driver.to_int16(data[4:6])]
[ "def", "to_vector_left_to_right_hand_rule", "(", "data", ":", "List", "[", "int", "]", ")", "->", "List", "[", "int", "]", ":", "return", "[", "-", "Driver", ".", "to_int16", "(", "data", "[", "0", ":", "2", "]", ")", ",", "Driver", ".", "to_int16", ...
[ 136, 4 ]
[ 139, 100 ]
python
en
['en', 'en', 'en']
True
Driver.to_int16
(data: List[int])
Converts little endian bytes into a signed 16-bit integer :param data: 16bit int in little endian, two's complement form :return: an integer
Converts little endian bytes into a signed 16-bit integer :param data: 16bit int in little endian, two's complement form :return: an integer
def to_int16(data: List[int]) -> int: """ Converts little endian bytes into a signed 16-bit integer :param data: 16bit int in little endian, two's complement form :return: an integer """ return int.from_bytes(data, byteorder='little', signed=True)
[ "def", "to_int16", "(", "data", ":", "List", "[", "int", "]", ")", "->", "int", ":", "return", "int", ".", "from_bytes", "(", "data", ",", "byteorder", "=", "'little'", ",", "signed", "=", "True", ")" ]
[ 142, 4 ]
[ 148, 68 ]
python
en
['en', 'ja', 'th']
False
_basic_input_validation
(preds: torch.Tensor, target: torch.Tensor, threshold: float, is_multiclass: bool)
Perform basic validation of inputs that does not require deducing any information of the type of inputs.
Perform basic validation of inputs that does not require deducing any information of the type of inputs.
def _basic_input_validation(preds: torch.Tensor, target: torch.Tensor, threshold: float, is_multiclass: bool): """ Perform basic validation of inputs that does not require deducing any information of the type of inputs. """ if target.is_floating_point(): raise ValueError("The `target` has t...
[ "def", "_basic_input_validation", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ",", "threshold", ":", "float", ",", "is_multiclass", ":", "bool", ")", ":", "if", "target", ".", "is_floating_point", "(", ")", ":", ...
[ 54, 0 ]
[ 82, 120 ]
python
en
['en', 'error', 'th']
False
_check_shape_and_type_consistency
(preds: torch.Tensor, target: torch.Tensor)
This checks that the shape and type of inputs are consistent with each other and fall into one of the allowed input types (see the documentation of docstring of ``_input_format_classification``). It does not check for consistency of number of classes, other functions take care of that. It retu...
This checks that the shape and type of inputs are consistent with each other and fall into one of the allowed input types (see the documentation of docstring of ``_input_format_classification``). It does not check for consistency of number of classes, other functions take care of that.
def _check_shape_and_type_consistency(preds: torch.Tensor, target: torch.Tensor) -> Tuple[str, int]: """ This checks that the shape and type of inputs are consistent with each other and fall into one of the allowed input types (see the documentation of docstring of ``_input_format_classification``). It ...
[ "def", "_check_shape_and_type_consistency", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ")", "->", "Tuple", "[", "str", ",", "int", "]", ":", "preds_float", "=", "preds", ".", "is_floating_point", "(", ")", "if", ...
[ 85, 0 ]
[ 144, 32 ]
python
en
['en', 'error', 'th']
False
_check_num_classes_binary
(num_classes: int, is_multiclass: bool)
This checks that the consistency of `num_classes` with the data and `is_multiclass` param for binary data.
This checks that the consistency of `num_classes` with the data and `is_multiclass` param for binary data.
def _check_num_classes_binary(num_classes: int, is_multiclass: bool): """ This checks that the consistency of `num_classes` with the data and `is_multiclass` param for binary data. """ if num_classes > 2: raise ValueError("Your data is binary, but `num_classes` is larger than 2.") if nu...
[ "def", "_check_num_classes_binary", "(", "num_classes", ":", "int", ",", "is_multiclass", ":", "bool", ")", ":", "if", "num_classes", ">", "2", ":", "raise", "ValueError", "(", "\"Your data is binary, but `num_classes` is larger than 2.\"", ")", "if", "num_classes", "...
[ 147, 0 ]
[ 165, 9 ]
python
en
['en', 'error', 'th']
False
_check_num_classes_mc
( preds: torch.Tensor, target: torch.Tensor, num_classes: int, is_multiclass: bool, implied_classes: int )
This checks that the consistency of `num_classes` with the data and `is_multiclass` param for (multi-dimensional) multi-class data.
This checks that the consistency of `num_classes` with the data and `is_multiclass` param for (multi-dimensional) multi-class data.
def _check_num_classes_mc( preds: torch.Tensor, target: torch.Tensor, num_classes: int, is_multiclass: bool, implied_classes: int ): """ This checks that the consistency of `num_classes` with the data and `is_multiclass` param for (multi-dimensional) multi-class data. """ if num_classes == 1 an...
[ "def", "_check_num_classes_mc", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ",", "num_classes", ":", "int", ",", "is_multiclass", ":", "bool", ",", "implied_classes", ":", "int", ")", ":", "if", "num_classes", "==...
[ 168, 0 ]
[ 197, 96 ]
python
en
['en', 'error', 'th']
False
_check_num_classes_ml
(num_classes: int, is_multiclass: bool, implied_classes: int)
This checks that the consistency of `num_classes` with the data and `is_multiclass` param for multi-label data.
This checks that the consistency of `num_classes` with the data and `is_multiclass` param for multi-label data.
def _check_num_classes_ml(num_classes: int, is_multiclass: bool, implied_classes: int): """ This checks that the consistency of `num_classes` with the data and `is_multiclass` param for multi-label data. """ if is_multiclass and num_classes != 2: raise ValueError( "Your have set...
[ "def", "_check_num_classes_ml", "(", "num_classes", ":", "int", ",", "is_multiclass", ":", "bool", ",", "implied_classes", ":", "int", ")", ":", "if", "is_multiclass", "and", "num_classes", "!=", "2", ":", "raise", "ValueError", "(", "\"Your have set `is_multiclas...
[ 200, 0 ]
[ 213, 108 ]
python
en
['en', 'error', 'th']
False
_check_classification_inputs
( preds: torch.Tensor, target: torch.Tensor, threshold: float, num_classes: Optional[int], is_multiclass: bool, top_k: Optional[int], )
Performs error checking on inputs for classification. This ensures that preds and target take one of the shape/type combinations that are specified in ``_input_format_classification`` docstring. It also checks the cases of over-rides with ``is_multiclass`` by checking (for multi-class and multi-dim multi-c...
Performs error checking on inputs for classification.
def _check_classification_inputs( preds: torch.Tensor, target: torch.Tensor, threshold: float, num_classes: Optional[int], is_multiclass: bool, top_k: Optional[int], ) -> str: """Performs error checking on inputs for classification. This ensures that preds and target take one of the sha...
[ "def", "_check_classification_inputs", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ",", "threshold", ":", "float", ",", "num_classes", ":", "Optional", "[", "int", "]", ",", "is_multiclass", ":", "bool", ",", "top...
[ 234, 0 ]
[ 330, 15 ]
python
en
['en', 'en', 'en']
True
_input_format_classification
( preds: torch.Tensor, target: torch.Tensor, threshold: float = 0.5, top_k: Optional[int] = None, num_classes: Optional[int] = None, is_multiclass: Optional[bool] = None, )
Convert preds and target tensors into common format. Preds and targets are supposed to fall into one of these categories (and are validated to make sure this is the case): * Both preds and target are of shape ``(N,)``, and both are integers (multi-class) * Both preds and target are of shape ``(N,)``, ...
Convert preds and target tensors into common format.
def _input_format_classification( preds: torch.Tensor, target: torch.Tensor, threshold: float = 0.5, top_k: Optional[int] = None, num_classes: Optional[int] = None, is_multiclass: Optional[bool] = None, ) -> Tuple[torch.Tensor, torch.Tensor, str]: """Convert preds and target tensors into com...
[ "def", "_input_format_classification", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ",", "threshold", ":", "float", "=", "0.5", ",", "top_k", ":", "Optional", "[", "int", "]", "=", "None", ",", "num_classes", ":"...
[ 333, 0 ]
[ 472, 42 ]
python
en
['en', 'en', 'en']
True
_reduce_stat_scores
( numerator: torch.Tensor, denominator: torch.Tensor, weights: Optional[torch.Tensor], average: str, mdmc_average: Optional[str], zero_division: int = 0, )
Reduces scores of type ``numerator/denominator`` or ``weights * (numerator/denominator)``, if ``average='weighted'``. Args: numerator: A tensor with numerator numbers. denominator: A tensor with denominator numbers. If a denominator is negative, the class will be ignored (if av...
Reduces scores of type ``numerator/denominator`` or ``weights * (numerator/denominator)``, if ``average='weighted'``.
def _reduce_stat_scores( numerator: torch.Tensor, denominator: torch.Tensor, weights: Optional[torch.Tensor], average: str, mdmc_average: Optional[str], zero_division: int = 0, ) -> torch.Tensor: """ Reduces scores of type ``numerator/denominator`` or ``weights * (numerator/denominat...
[ "def", "_reduce_stat_scores", "(", "numerator", ":", "torch", ".", "Tensor", ",", "denominator", ":", "torch", ".", "Tensor", ",", "weights", ":", "Optional", "[", "torch", ".", "Tensor", "]", ",", "average", ":", "str", ",", "mdmc_average", ":", "Optional...
[ 475, 0 ]
[ 538, 17 ]
python
en
['en', 'error', 'th']
False
test_trainer_and_stochastic_weight_avg
(tmpdir, use_callbacks, stochastic_weight_avg)
Test to ensure SWA Callback is injected when `stochastic_weight_avg` is provided to the Trainer
Test to ensure SWA Callback is injected when `stochastic_weight_avg` is provided to the Trainer
def test_trainer_and_stochastic_weight_avg(tmpdir, use_callbacks, stochastic_weight_avg): """Test to ensure SWA Callback is injected when `stochastic_weight_avg` is provided to the Trainer""" class TestModel(BoringModel): def configure_optimizers(self): optimizer = torch.optim.SGD(self.lay...
[ "def", "test_trainer_and_stochastic_weight_avg", "(", "tmpdir", ",", "use_callbacks", ",", "stochastic_weight_avg", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "configure_optimizers", "(", "self", ")", ":", "optimizer", "=", "torch", ".", ...
[ 164, 0 ]
[ 187, 93 ]
python
en
['en', 'en', 'en']
True
insertion_sort
(list,n)
sort list in assending order INPUT: list=list of values to be sorted n=size of list that contains values to be sorted OUTPUT: list of sorted values in assending order
sort list in assending order
def insertion_sort(list,n): """ sort list in assending order INPUT: list=list of values to be sorted n=size of list that contains values to be sorted OUTPUT: list of sorted values in assending order """ for i in range(0,n): key = list[i] j = i - 1 ...
[ "def", "insertion_sort", "(", "list", ",", "n", ")", ":", "for", "i", "in", "range", "(", "0", ",", "n", ")", ":", "key", "=", "list", "[", "i", "]", "j", "=", "i", "-", "1", "#Swap elements witth key iff they are", "#greater than key", "while", "j", ...
[ 13, 0 ]
[ 33, 15 ]
python
en
['en', 'error', 'th']
False
insertion_sort_desc
(list,n)
sort list in desending order INPUT: list=list of values to be sorted n=size of list that contains values to be sorted OUTPUT: list of sorted values in desending order
sort list in desending order
def insertion_sort_desc(list,n): """ sort list in desending order INPUT: list=list of values to be sorted n=size of list that contains values to be sorted OUTPUT: list of sorted values in desending order """ for i in range(0,n): key = list[i] j = i - 1 ...
[ "def", "insertion_sort_desc", "(", "list", ",", "n", ")", ":", "for", "i", "in", "range", "(", "0", ",", "n", ")", ":", "key", "=", "list", "[", "i", "]", "j", "=", "i", "-", "1", "#Swap elements witth key iff they are", "#greater than key", "while", "...
[ 36, 0 ]
[ 56, 15 ]
python
en
['en', 'error', 'th']
False
test_multi_gpu_none_backend
(tmpdir)
Make sure when using multiple GPUs the user can't use `distributed_backend = None`.
Make sure when using multiple GPUs the user can't use `distributed_backend = None`.
def test_multi_gpu_none_backend(tmpdir): """Make sure when using multiple GPUs the user can't use `distributed_backend = None`.""" tutils.set_random_master_port() trainer_options = dict( default_root_dir=tmpdir, progress_bar_refresh_rate=0, max_epochs=1, limit_train_batches=0...
[ "def", "test_multi_gpu_none_backend", "(", "tmpdir", ")", ":", "tutils", ".", "set_random_master_port", "(", ")", "trainer_options", "=", "dict", "(", "default_root_dir", "=", "tmpdir", ",", "progress_bar_refresh_rate", "=", "0", ",", "max_epochs", "=", "1", ",", ...
[ 33, 0 ]
[ 47, 53 ]
python
en
['en', 'en', 'en']
True
test_single_gpu_model
(tmpdir, gpus)
Make sure single GPU works (DP mode).
Make sure single GPU works (DP mode).
def test_single_gpu_model(tmpdir, gpus): """Make sure single GPU works (DP mode).""" trainer_options = dict( default_root_dir=tmpdir, progress_bar_refresh_rate=0, max_epochs=1, limit_train_batches=0.1, limit_val_batches=0.1, gpus=gpus ) model = BoringMode...
[ "def", "test_single_gpu_model", "(", "tmpdir", ",", "gpus", ")", ":", "trainer_options", "=", "dict", "(", "default_root_dir", "=", "tmpdir", ",", "progress_bar_refresh_rate", "=", "0", ",", "max_epochs", "=", "1", ",", "limit_train_batches", "=", "0.1", ",", ...
[ 52, 0 ]
[ 64, 49 ]
python
en
['en', 'bs', 'en']
True
test_non_blocking
()
Tests that non_blocking=True only gets passed on torch.Tensor.to, but not on other objects.
Tests that non_blocking=True only gets passed on torch.Tensor.to, but not on other objects.
def test_non_blocking(): """ Tests that non_blocking=True only gets passed on torch.Tensor.to, but not on other objects. """ trainer = Trainer() batch = torch.zeros(2, 3) with patch.object(batch, 'to', wraps=batch.to) as mocked: batch = trainer.accelerator.batch_to_device(batch, torch.device('c...
[ "def", "test_non_blocking", "(", ")", ":", "trainer", "=", "Trainer", "(", ")", "batch", "=", "torch", ".", "zeros", "(", "2", ",", "3", ")", "with", "patch", ".", "object", "(", "batch", ",", "'to'", ",", "wraps", "=", "batch", ".", "to", ")", "...
[ 309, 0 ]
[ 326, 58 ]
python
en
['en', 'en', 'en']
True
embedding_similarity
( batch: torch.Tensor, similarity: str = 'cosine', reduction: str = 'none', zero_diagonal: bool = True )
Computes representation similarity Example: >>> from pytorch_lightning.metrics.functional import embedding_similarity >>> embeddings = torch.tensor([[1., 2., 3., 4.], [1., 2., 3., 4.], [4., 5., 6., 7.]]) >>> embedding_similarity(embeddings) tensor([[0.0000, 1.0000, 0.9759], ...
Computes representation similarity
def embedding_similarity( batch: torch.Tensor, similarity: str = 'cosine', reduction: str = 'none', zero_diagonal: bool = True ) -> torch.Tensor: """ Computes representation similarity Example: >>> from pytorch_lightning.metrics.functional import embedding_similarity >>> emb...
[ "def", "embedding_similarity", "(", "batch", ":", "torch", ".", "Tensor", ",", "similarity", ":", "str", "=", "'cosine'", ",", "reduction", ":", "str", "=", "'none'", ",", "zero_diagonal", ":", "bool", "=", "True", ")", "->", "torch", ".", "Tensor", ":",...
[ 16, 0 ]
[ 58, 18 ]
python
en
['en', 'error', 'th']
False
Solution.fizzBuzz
(self, n)
:type n: int :rtype: List[str]
:type n: int :rtype: List[str]
def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ result = [] for i in range(1,n+1): if i% 3== 0 and i%5==0: result.append("FizzBuzz") elif i %3==0: result.append("Fizz") elif i% 5 == 0: result.append("Buzz") ...
[ "def", "fizzBuzz", "(", "self", ",", "n", ")", ":", "result", "=", "[", "]", "for", "i", "in", "range", "(", "1", ",", "n", "+", "1", ")", ":", "if", "i", "%", "3", "==", "0", "and", "i", "%", "5", "==", "0", ":", "result", ".", "append",...
[ 1, 3 ]
[ 16, 19 ]
python
en
['en', 'error', 'th']
False
ModelPruning.__init__
( self, pruning_fn: Union[Callable, str], parameters_to_prune: Optional[_PARAM_LIST] = None, parameter_names: Optional[List[str]] = None, use_global_unstructured: bool = True, amount: Union[int, float, Callable[[int], Union[int, float]]] = 0.5, apply_pruning: Unio...
Model pruning Callback, using PyTorch's prune utilities. This callback is responsible of pruning networks parameters during training. To learn more about pruning with PyTorch, please take a look at `this tutorial <https://pytorch.org/tutorials/intermediate/pruning_tutorial.html>`_. ...
Model pruning Callback, using PyTorch's prune utilities. This callback is responsible of pruning networks parameters during training.
def __init__( self, pruning_fn: Union[Callable, str], parameters_to_prune: Optional[_PARAM_LIST] = None, parameter_names: Optional[List[str]] = None, use_global_unstructured: bool = True, amount: Union[int, float, Callable[[int], Union[int, float]]] = 0.5, apply_p...
[ "def", "__init__", "(", "self", ",", "pruning_fn", ":", "Union", "[", "Callable", ",", "str", "]", ",", "parameters_to_prune", ":", "Optional", "[", "_PARAM_LIST", "]", "=", "None", ",", "parameter_names", ":", "Optional", "[", "List", "[", "str", "]", "...
[ 54, 4 ]
[ 216, 31 ]
python
en
['en', 'error', 'th']
False
ModelPruning.filter_parameters_to_prune
(self, parameters_to_prune: Optional[_PARAM_LIST] = None)
This function can be overridden to control which module to prune.
This function can be overridden to control which module to prune.
def filter_parameters_to_prune(self, parameters_to_prune: Optional[_PARAM_LIST] = None) -> Optional[_PARAM_LIST]: """ This function can be overridden to control which module to prune. """ return parameters_to_prune
[ "def", "filter_parameters_to_prune", "(", "self", ",", "parameters_to_prune", ":", "Optional", "[", "_PARAM_LIST", "]", "=", "None", ")", "->", "Optional", "[", "_PARAM_LIST", "]", ":", "return", "parameters_to_prune" ]
[ 218, 4 ]
[ 222, 34 ]
python
en
['en', 'error', 'th']
False
ModelPruning._create_pruning_fn
(self, pruning_fn: str, **kwargs)
This function takes `pruning_fn`, a function name. IF use_global_unstructured, pruning_fn will be resolved into its associated ``PyTorch BasePruningMethod`` ELSE, pruning_fn will be resolved into its function counterpart from `torch.nn.utils.prune`.
This function takes `pruning_fn`, a function name.
def _create_pruning_fn(self, pruning_fn: str, **kwargs) -> Union[Callable, pytorch_prune.BasePruningMethod]: """ This function takes `pruning_fn`, a function name. IF use_global_unstructured, pruning_fn will be resolved into its associated ``PyTorch BasePruningMethod`` ELSE, pruning_fn ...
[ "def", "_create_pruning_fn", "(", "self", ",", "pruning_fn", ":", "str", ",", "*", "*", "kwargs", ")", "->", "Union", "[", "Callable", ",", "pytorch_prune", ".", "BasePruningMethod", "]", ":", "if", "self", ".", "_use_global_unstructured", ":", "pruning_fn", ...
[ 224, 4 ]
[ 242, 66 ]
python
en
['en', 'error', 'th']
False
ModelPruning.make_pruning_permanent
(self)
Makes ``parameters_to_prune`` current pruning permanent.
Makes ``parameters_to_prune`` current pruning permanent.
def make_pruning_permanent(self): """ Makes ``parameters_to_prune`` current pruning permanent. """ for module, param_name in self._parameters_to_prune: try: pytorch_prune.remove(module, param_name) except ValueError: # pruning already made permanen...
[ "def", "make_pruning_permanent", "(", "self", ")", ":", "for", "module", ",", "param_name", "in", "self", ".", "_parameters_to_prune", ":", "try", ":", "pytorch_prune", ".", "remove", "(", "module", ",", "param_name", ")", "except", "ValueError", ":", "# pruni...
[ 248, 4 ]
[ 255, 20 ]
python
en
['en', 'en', 'en']
True
ModelPruning.apply_lottery_ticket_hypothesis
(self)
r""" Lottery ticket hypothesis algorithm (see page 2 of the paper): 1. Randomly initialize a neural network :math:`f(x; \theta_0)` (where :math:`\theta_0 \sim \mathcal{D}_\theta`). 2. Train the network for :math:`j` iterations, arriving at parameters :math:`\theta_j`. 3. Pru...
r""" Lottery ticket hypothesis algorithm (see page 2 of the paper):
def apply_lottery_ticket_hypothesis(self): r""" Lottery ticket hypothesis algorithm (see page 2 of the paper): 1. Randomly initialize a neural network :math:`f(x; \theta_0)` (where :math:`\theta_0 \sim \mathcal{D}_\theta`). 2. Train the network for :math:`j` iterations, arriving...
[ "def", "apply_lottery_ticket_hypothesis", "(", "self", ")", ":", "# noqa: E501", "def", "copy_param", "(", "new", ",", "old", ",", "name", ":", "str", ")", "->", "None", ":", "dst", "=", "getattr", "(", "new", ",", "name", ")", "src", "=", "getattr", "...
[ 264, 4 ]
[ 292, 43 ]
python
cy
['en', 'cy', 'hi']
False
ModelPruning.apply_pruning
(self, amount: Union[int, float])
Applies pruning to ``parameters_to_prune``.
Applies pruning to ``parameters_to_prune``.
def apply_pruning(self, amount: Union[int, float]): """ Applies pruning to ``parameters_to_prune``. """ if self._verbose: prev_stats = [self._get_pruned_stats(m, n) for m, n in self._parameters_to_prune] if self._use_global_unstructured: self._apply_global_pruning(amount...
[ "def", "apply_pruning", "(", "self", ",", "amount", ":", "Union", "[", "int", ",", "float", "]", ")", ":", "if", "self", ".", "_verbose", ":", "prev_stats", "=", "[", "self", ".", "_get_pruned_stats", "(", "m", ",", "n", ")", "for", "m", ",", "n", ...
[ 317, 4 ]
[ 329, 75 ]
python
en
['en', 'en', 'en']
True
ModelPruning.sanitize_parameters_to_prune
( pl_module: LightningModule, parameters_to_prune: Optional[_PARAM_LIST] = None, parameter_names: Optional[List[str]] = None, )
This function is responsible of sanitizing ``parameters_to_prune`` and ``parameter_names``. If ``parameters_to_prune is None``, it will be generated with all parameters of the model. Raises: MisconfigurationException: If ``parameters_to_prune`` doesn't exist in the ...
This function is responsible of sanitizing ``parameters_to_prune`` and ``parameter_names``. If ``parameters_to_prune is None``, it will be generated with all parameters of the model.
def sanitize_parameters_to_prune( pl_module: LightningModule, parameters_to_prune: Optional[_PARAM_LIST] = None, parameter_names: Optional[List[str]] = None, ) -> _PARAM_LIST: """ This function is responsible of sanitizing ``parameters_to_prune`` and ``parameter_names``. ...
[ "def", "sanitize_parameters_to_prune", "(", "pl_module", ":", "LightningModule", ",", "parameters_to_prune", ":", "Optional", "[", "_PARAM_LIST", "]", "=", "None", ",", "parameter_names", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", ")...
[ 392, 4 ]
[ 436, 34 ]
python
en
['en', 'error', 'th']
False
test_scalar_extraction
()
Confirm that extracting a value doesn't convert to python float
Confirm that extracting a value doesn't convert to python float
def test_scalar_extraction(): """Confirm that extracting a value doesn't convert to python float""" o = 1 + LD_INFO.eps a = np.array([o, o, o]) assert_equal(a[1], o)
[ "def", "test_scalar_extraction", "(", ")", ":", "o", "=", "1", "+", "LD_INFO", ".", "eps", "a", "=", "np", ".", "array", "(", "[", "o", ",", "o", ",", "o", "]", ")", "assert_equal", "(", "a", "[", "1", "]", ",", "o", ")" ]
[ 20, 0 ]
[ 24, 25 ]
python
en
['en', 'en', 'en']
True
CallbackConnector._attach_model_callbacks
(model: LightningModule, trainer)
Attaches the callbacks defined in the model. If a callback returned by the model's configure_callback method has the same type as one or several callbacks already present in the trainer callbacks list, it will replace them. In addition, all :class:`~pytorch_lightning.callbacks.model_che...
Attaches the callbacks defined in the model. If a callback returned by the model's configure_callback method has the same type as one or several callbacks already present in the trainer callbacks list, it will replace them. In addition, all :class:`~pytorch_lightning.callbacks.model_che...
def _attach_model_callbacks(model: LightningModule, trainer) -> None: """ Attaches the callbacks defined in the model. If a callback returned by the model's configure_callback method has the same type as one or several callbacks already present in the trainer callbacks list, it will repl...
[ "def", "_attach_model_callbacks", "(", "model", ":", "LightningModule", ",", "trainer", ")", "->", "None", ":", "model_callbacks", "=", "model", ".", "configure_callbacks", "(", ")", "if", "not", "model_callbacks", ":", "return", "model_callback_types", "=", "set"...
[ 126, 4 ]
[ 156, 41 ]
python
en
['en', 'error', 'th']
False
CallbackConnector._reorder_callbacks
(callbacks: List[Callback])
Moves all ModelCheckpoint callbacks to the end of the list. The sequential order within the group of checkpoint callbacks is preserved, as well as the order of all other callbacks. Args: callbacks: A list of callbacks. Return: A new list in which the last eleme...
Moves all ModelCheckpoint callbacks to the end of the list. The sequential order within the group of checkpoint callbacks is preserved, as well as the order of all other callbacks.
def _reorder_callbacks(callbacks: List[Callback]) -> List[Callback]: """ Moves all ModelCheckpoint callbacks to the end of the list. The sequential order within the group of checkpoint callbacks is preserved, as well as the order of all other callbacks. Args: callbacks: A li...
[ "def", "_reorder_callbacks", "(", "callbacks", ":", "List", "[", "Callback", "]", ")", "->", "List", "[", "Callback", "]", ":", "checkpoints", "=", "[", "c", "for", "c", "in", "callbacks", "if", "isinstance", "(", "c", ",", "ModelCheckpoint", ")", "]", ...
[ 159, 4 ]
[ 173, 44 ]
python
en
['en', 'error', 'th']
False
test_horovod_model_script
(tmpdir)
This just for testing/debugging horovod script without horovod...
This just for testing/debugging horovod script without horovod...
def test_horovod_model_script(tmpdir): """This just for testing/debugging horovod script without horovod...""" trainer_options = dict( default_root_dir=str(tmpdir), weights_save_path=str(tmpdir), gradient_clip_val=1.0, progress_bar_refresh_rate=0, max_epochs=1, li...
[ "def", "test_horovod_model_script", "(", "tmpdir", ")", ":", "trainer_options", "=", "dict", "(", "default_root_dir", "=", "str", "(", "tmpdir", ")", ",", "weights_save_path", "=", "str", "(", "tmpdir", ")", ",", "gradient_clip_val", "=", "1.0", ",", "progress...
[ 17, 0 ]
[ 29, 73 ]
python
en
['en', 'en', 'en']
True
mean_relative_error
(preds: torch.Tensor, target: torch.Tensor)
Computes mean relative error Args: pred: estimated labels target: ground truth labels Return: Tensor with mean relative error Example: >>> x = torch.tensor([0., 1, 2, 3]) >>> y = torch.tensor([0., 1, 2, 2]) >>> mean_relative_error(x, y) tensor...
Computes mean relative error
def mean_relative_error(preds: torch.Tensor, target: torch.Tensor) -> torch.Tensor: """ Computes mean relative error Args: pred: estimated labels target: ground truth labels Return: Tensor with mean relative error Example: >>> x = torch.tensor([0., 1, 2, 3]) ...
[ "def", "mean_relative_error", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "sum_rltv_error", ",", "n_obs", "=", "_mean_relative_error_update", "(", "preds", ",", "target", ")",...
[ 33, 0 ]
[ 53, 62 ]
python
en
['en', 'error', 'th']
False
r2score
( preds: torch.Tensor, target: torch.Tensor, adjusted: int = 0, multioutput: str = "uniform_average", )
r""" Computes r2 score also known as `coefficient of determination <https://en.wikipedia.org/wiki/Coefficient_of_determination>`_: .. math:: R^2 = 1 - \frac{SS_res}{SS_tot} where :math:`SS_res=\sum_i (y_i - f(x_i))^2` is the sum of residual squares, and :math:`SS_tot=\sum_i (y_i - \bar{y})^2` is t...
r""" Computes r2 score also known as `coefficient of determination <https://en.wikipedia.org/wiki/Coefficient_of_determination>`_:
def r2score( preds: torch.Tensor, target: torch.Tensor, adjusted: int = 0, multioutput: str = "uniform_average", ) -> torch.Tensor: r""" Computes r2 score also known as `coefficient of determination <https://en.wikipedia.org/wiki/Coefficient_of_determination>`_: .. math:: R^2 = 1 - \fra...
[ "def", "r2score", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ",", "adjusted", ":", "int", "=", "0", ",", "multioutput", ":", "str", "=", "\"uniform_average\"", ",", ")", "->", "torch", ".", "Tensor", ":", "...
[ 83, 0 ]
[ 130, 97 ]
python
cy
['en', 'cy', 'hi']
False
PipChecker.config_requirements
(self)
Set of configured pip dependabot directories
Set of configured pip dependabot directories
def config_requirements(self) -> set: """Set of configured pip dependabot directories""" return set( update['directory'] for update in self.dependabot_config["updates"] if update["package-ecosystem"] == "pip")
[ "def", "config_requirements", "(", "self", ")", "->", "set", ":", "return", "set", "(", "update", "[", "'directory'", "]", "for", "update", "in", "self", ".", "dependabot_config", "[", "\"updates\"", "]", "if", "update", "[", "\"package-ecosystem\"", "]", "=...
[ 35, 4 ]
[ 40, 52 ]
python
en
['en', 'lb', 'en']
True
PipChecker.dependabot_config
(self)
Parsed dependabot config
Parsed dependabot config
def dependabot_config(self) -> dict: """Parsed dependabot config""" with open(os.path.join(self.path, self.dependabot_config_path)) as f: return yaml.safe_load(f.read())
[ "def", "dependabot_config", "(", "self", ")", "->", "dict", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "self", ".", "dependabot_config_path", ")", ")", "as", "f", ":", "return", "yaml", ".", "safe_load", ...
[ 43, 4 ]
[ 46, 43 ]
python
en
['en', 'la', 'en']
True
PipChecker.requirements_dirs
(self)
Set of found directories in the repo containing requirements.txt
Set of found directories in the repo containing requirements.txt
def requirements_dirs(self) -> set: """Set of found directories in the repo containing requirements.txt""" return set( root[len(self.path):] for root, dirs, files in os.walk(self.path) if self.requirements_filename in files)
[ "def", "requirements_dirs", "(", "self", ")", "->", "set", ":", "return", "set", "(", "root", "[", "len", "(", "self", ".", "path", ")", ":", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "self", ".", "path", ")", ...
[ 53, 4 ]
[ 58, 51 ]
python
en
['en', 'en', 'en']
True
PipChecker.check_dependabot
(self)
Check that dependabot config matches requirements.txt files found in repo
Check that dependabot config matches requirements.txt files found in repo
def check_dependabot(self) -> None: """Check that dependabot config matches requirements.txt files found in repo""" missing_dirs = self.config_requirements.difference(self.requirements_dirs) missing_config = self.requirements_dirs.difference(self.config_requirements) correct = self.requi...
[ "def", "check_dependabot", "(", "self", ")", "->", "None", ":", "missing_dirs", "=", "self", ".", "config_requirements", ".", "difference", "(", "self", ".", "requirements_dirs", ")", "missing_config", "=", "self", ".", "requirements_dirs", ".", "difference", "(...
[ 64, 4 ]
[ 78, 85 ]
python
en
['en', 'en', 'en']
True
poly2leg
(pol)
Convert a polynomial to a Legendre series. Convert an array representing the coefficients of a polynomial (relative to the "standard" basis) ordered from lowest degree to highest, to an array of the coefficients of the equivalent Legendre series, ordered from lowest to highest degree. Paramet...
Convert a polynomial to a Legendre series.
def poly2leg(pol): """ Convert a polynomial to a Legendre series. Convert an array representing the coefficients of a polynomial (relative to the "standard" basis) ordered from lowest degree to highest, to an array of the coefficients of the equivalent Legendre series, ordered from lowest to hi...
[ "def", "poly2leg", "(", "pol", ")", ":", "[", "pol", "]", "=", "pu", ".", "as_series", "(", "[", "pol", "]", ")", "deg", "=", "len", "(", "pol", ")", "-", "1", "res", "=", "0", "for", "i", "in", "range", "(", "deg", ",", "-", "1", ",", "-...
[ 104, 0 ]
[ 149, 14 ]
python
en
['en', 'error', 'th']
False
leg2poly
(c)
Convert a Legendre series to a polynomial. Convert an array representing the coefficients of a Legendre series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to highest degree. Paramet...
Convert a Legendre series to a polynomial.
def leg2poly(c): """ Convert a Legendre series to a polynomial. Convert an array representing the coefficients of a Legendre series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to high...
[ "def", "leg2poly", "(", "c", ")", ":", "from", ".", "polynomial", "import", "polyadd", ",", "polysub", ",", "polymulx", "[", "c", "]", "=", "pu", ".", "as_series", "(", "[", "c", "]", ")", "n", "=", "len", "(", "c", ")", "if", "n", "<", "3", ...
[ 152, 0 ]
[ 211, 40 ]
python
en
['en', 'error', 'th']
False
legline
(off, scl)
Legendre series whose graph is a straight line. Parameters ---------- off, scl : scalars The specified line is given by ``off + scl*x``. Returns ------- y : ndarray This module's representation of the Legendre series for ``off + scl*x``. See Also -------...
Legendre series whose graph is a straight line.
def legline(off, scl): """ Legendre series whose graph is a straight line. Parameters ---------- off, scl : scalars The specified line is given by ``off + scl*x``. Returns ------- y : ndarray This module's representation of the Legendre series for ``off + scl*...
[ "def", "legline", "(", "off", ",", "scl", ")", ":", "if", "scl", "!=", "0", ":", "return", "np", ".", "array", "(", "[", "off", ",", "scl", "]", ")", "else", ":", "return", "np", ".", "array", "(", "[", "off", "]", ")" ]
[ 231, 0 ]
[ 264, 30 ]
python
en
['en', 'error', 'th']
False
legfromroots
(roots)
Generate a Legendre series with given roots. The function returns the coefficients of the polynomial .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n), in Legendre form, where the `r_n` are the roots specified in `roots`. If a zero has multiplicity n, then it must appear in `roots` n time...
Generate a Legendre series with given roots.
def legfromroots(roots): """ Generate a Legendre series with given roots. The function returns the coefficients of the polynomial .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n), in Legendre form, where the `r_n` are the roots specified in `roots`. If a zero has multiplicity n, then ...
[ "def", "legfromroots", "(", "roots", ")", ":", "return", "pu", ".", "_fromroots", "(", "legline", ",", "legmul", ",", "roots", ")" ]
[ 267, 0 ]
[ 315, 48 ]
python
en
['en', 'error', 'th']
False
legadd
(c1, c2)
Add one Legendre series to another. Returns the sum of two Legendre series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-...
Add one Legendre series to another.
def legadd(c1, c2): """ Add one Legendre series to another. Returns the sum of two Legendre series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1,...
[ "def", "legadd", "(", "c1", ",", "c2", ")", ":", "return", "pu", ".", "_add", "(", "c1", ",", "c2", ")" ]
[ 318, 0 ]
[ 357, 26 ]
python
en
['en', 'error', 'th']
False
legsub
(c1, c2)
Subtract one Legendre series from another. Returns the difference of two Legendre series `c1` - `c2`. The sequences of coefficients are from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D ar...
Subtract one Legendre series from another.
def legsub(c1, c2): """ Subtract one Legendre series from another. Returns the difference of two Legendre series `c1` - `c2`. The sequences of coefficients are from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 ...
[ "def", "legsub", "(", "c1", ",", "c2", ")", ":", "return", "pu", ".", "_sub", "(", "c1", ",", "c2", ")" ]
[ 360, 0 ]
[ 401, 26 ]
python
en
['en', 'error', 'th']
False
legmulx
(c)
Multiply a Legendre series by x. Multiply the Legendre series `c` by x, where x is the independent variable. Parameters ---------- c : array_like 1-D array of Legendre series coefficients ordered from low to high. Returns ------- out : ndarray Array representi...
Multiply a Legendre series by x.
def legmulx(c): """Multiply a Legendre series by x. Multiply the Legendre series `c` by x, where x is the independent variable. Parameters ---------- c : array_like 1-D array of Legendre series coefficients ordered from low to high. Returns ------- out : ndarray ...
[ "def", "legmulx", "(", "c", ")", ":", "# c is a trimmed copy", "[", "c", "]", "=", "pu", ".", "as_series", "(", "[", "c", "]", ")", "# The zero series needs special treatment", "if", "len", "(", "c", ")", "==", "1", "and", "c", "[", "0", "]", "==", "...
[ 404, 0 ]
[ 457, 14 ]
python
en
['en', 'en', 'en']
True