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
TrainerCallbackHookMixin.on_load_checkpoint
(self, checkpoint)
Called when loading a model checkpoint.
Called when loading a model checkpoint.
def on_load_checkpoint(self, checkpoint): """Called when loading a model checkpoint.""" callback_states = checkpoint.get('callbacks') # Todo: the `callback_states` are dropped with TPUSpawn as they # can't be saved using `xm.save` # https://github.com/pytorch/xla/issues/2773 ...
[ "def", "on_load_checkpoint", "(", "self", ",", "checkpoint", ")", ":", "callback_states", "=", "checkpoint", ".", "get", "(", "'callbacks'", ")", "# Todo: the `callback_states` are dropped with TPUSpawn as they", "# can't be saved using `xm.save`", "# https://github.com/pytorch/x...
[ 209, 4 ]
[ 220, 54 ]
python
en
['en', 'en', 'en']
True
TrainerCallbackHookMixin.on_after_backward
(self)
Called after loss.backward() and before optimizers do anything.
Called after loss.backward() and before optimizers do anything.
def on_after_backward(self): """ Called after loss.backward() and before optimizers do anything. """ for callback in self.callbacks: callback.on_after_backward(self, self.lightning_module)
[ "def", "on_after_backward", "(", "self", ")", ":", "for", "callback", "in", "self", ".", "callbacks", ":", "callback", ".", "on_after_backward", "(", "self", ",", "self", ".", "lightning_module", ")" ]
[ 222, 4 ]
[ 227, 67 ]
python
en
['en', 'error', 'th']
False
TrainerCallbackHookMixin.on_before_zero_grad
(self, optimizer)
Called after optimizer.step() and before optimizer.zero_grad().
Called after optimizer.step() and before optimizer.zero_grad().
def on_before_zero_grad(self, optimizer): """ Called after optimizer.step() and before optimizer.zero_grad(). """ for callback in self.callbacks: callback.on_before_zero_grad(self, self.lightning_module, optimizer)
[ "def", "on_before_zero_grad", "(", "self", ",", "optimizer", ")", ":", "for", "callback", "in", "self", ".", "callbacks", ":", "callback", ".", "on_before_zero_grad", "(", "self", ",", "self", ".", "lightning_module", ",", "optimizer", ")" ]
[ 229, 4 ]
[ 234, 80 ]
python
en
['en', 'error', 'th']
False
TestArray2String.test_basic
(self)
Basic test of array2string.
Basic test of array2string.
def test_basic(self): """Basic test of array2string.""" a = np.arange(3) assert_(np.array2string(a) == '[0 1 2]') assert_(np.array2string(a, max_line_width=4, legacy='1.13') == '[0 1\n 2]') assert_(np.array2string(a, max_line_width=4) == '[0\n 1\n 2]')
[ "def", "test_basic", "(", "self", ")", ":", "a", "=", "np", ".", "arange", "(", "3", ")", "assert_", "(", "np", ".", "array2string", "(", "a", ")", "==", "'[0 1 2]'", ")", "assert_", "(", "np", ".", "array2string", "(", "a", ",", "max_line_width", ...
[ 210, 4 ]
[ 215, 70 ]
python
en
['en', 'no', 'en']
True
TestArray2String.test_format_function
(self)
Test custom format function for each element in array.
Test custom format function for each element in array.
def test_format_function(self): """Test custom format function for each element in array.""" def _format_function(x): if np.abs(x) < 1: return '.' elif np.abs(x) < 2: return 'o' else: return 'O' x = np.arange(3)...
[ "def", "test_format_function", "(", "self", ")", ":", "def", "_format_function", "(", "x", ")", ":", "if", "np", ".", "abs", "(", "x", ")", "<", "1", ":", "return", "'.'", "elif", "np", ".", "abs", "(", "x", ")", "<", "2", ":", "return", "'o'", ...
[ 226, 4 ]
[ 268, 34 ]
python
en
['en', 'en', 'en']
True
test_sharded_ddp_choice
(tmpdir, accelerator)
Test to ensure that plugin is correctly chosen
Test to ensure that plugin is correctly chosen
def test_sharded_ddp_choice(tmpdir, accelerator): """ Test to ensure that plugin is correctly chosen """ class CB(Callback): def on_fit_start(self, trainer, pl_module): if accelerator == 'ddp_sharded': assert isinstance(trainer.accelerator.training_type_plugin, ...
[ "def", "test_sharded_ddp_choice", "(", "tmpdir", ",", "accelerator", ")", ":", "class", "CB", "(", "Callback", ")", ":", "def", "on_fit_start", "(", "self", ",", "trainer", ",", "pl_module", ")", ":", "if", "accelerator", "==", "'ddp_sharded'", ":", "assert"...
[ 16, 0 ]
[ 38, 26 ]
python
en
['en', 'error', 'th']
False
test_invalid_apex_sharded
(tmpdir)
Test to ensure that we raise an error when we try to use apex and sharded
Test to ensure that we raise an error when we try to use apex and sharded
def test_invalid_apex_sharded(tmpdir): """ Test to ensure that we raise an error when we try to use apex and sharded """ model = BoringModel() with pytest.raises(MisconfigurationException, match='Sharded Plugin is not supported with Apex AMP'): trainer = Trainer( fast_dev_ru...
[ "def", "test_invalid_apex_sharded", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "with", "pytest", ".", "raises", "(", "MisconfigurationException", ",", "match", "=", "'Sharded Plugin is not supported with Apex AMP'", ")", ":", "trainer", "=", "Tr...
[ 43, 0 ]
[ 57, 26 ]
python
en
['en', 'error', 'th']
False
test_ddp_choice_sharded_amp
(tmpdir, accelerator)
Test to ensure that plugin native amp plugin is correctly chosen when using sharded
Test to ensure that plugin native amp plugin is correctly chosen when using sharded
def test_ddp_choice_sharded_amp(tmpdir, accelerator): """ Test to ensure that plugin native amp plugin is correctly chosen when using sharded """ class CB(Callback): def on_fit_start(self, trainer, pl_module): if accelerator == 'ddp_sharded': assert isinstance(t...
[ "def", "test_ddp_choice_sharded_amp", "(", "tmpdir", ",", "accelerator", ")", ":", "class", "CB", "(", "Callback", ")", ":", "def", "on_fit_start", "(", "self", ",", "trainer", ",", "pl_module", ")", ":", "if", "accelerator", "==", "'ddp_sharded'", ":", "ass...
[ 64, 0 ]
[ 88, 26 ]
python
en
['en', 'error', 'th']
False
test_ddp_sharded_plugin_checkpoint_cpu
(tmpdir)
Test to ensure that checkpoint is saved correctly
Test to ensure that checkpoint is saved correctly
def test_ddp_sharded_plugin_checkpoint_cpu(tmpdir): """ Test to ensure that checkpoint is saved correctly """ model = BoringModel() trainer = Trainer( accelerator='ddp_sharded_spawn', num_processes=2, fast_dev_run=True, ) trainer.fit(model) checkpoint_path =...
[ "def", "test_ddp_sharded_plugin_checkpoint_cpu", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "trainer", "=", "Trainer", "(", "accelerator", "=", "'ddp_sharded_spawn'", ",", "num_processes", "=", "2", ",", "fast_dev_run", "=", "True", ",", ")"...
[ 93, 0 ]
[ 112, 60 ]
python
en
['en', 'error', 'th']
False
test_ddp_sharded_plugin_checkpoint_multi_gpu
(tmpdir)
Test to ensure that checkpoint is saved correctly when using multiple GPUs
Test to ensure that checkpoint is saved correctly when using multiple GPUs
def test_ddp_sharded_plugin_checkpoint_multi_gpu(tmpdir): """ Test to ensure that checkpoint is saved correctly when using multiple GPUs """ model = BoringModel() trainer = Trainer( gpus=2, accelerator='ddp_sharded_spawn', fast_dev_run=True, ) trainer.fit(model) ...
[ "def", "test_ddp_sharded_plugin_checkpoint_multi_gpu", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "trainer", "=", "Trainer", "(", "gpus", "=", "2", ",", "accelerator", "=", "'ddp_sharded_spawn'", ",", "fast_dev_run", "=", "True", ",", ")", ...
[ 118, 0 ]
[ 137, 60 ]
python
en
['en', 'error', 'th']
False
test_ddp_sharded_plugin_finetune
(tmpdir)
Test to ensure that we can save and restart training (simulate fine-tuning)
Test to ensure that we can save and restart training (simulate fine-tuning)
def test_ddp_sharded_plugin_finetune(tmpdir): """ Test to ensure that we can save and restart training (simulate fine-tuning) """ model = BoringModel() trainer = Trainer( gpus=2, accelerator='ddp_sharded_spawn', fast_dev_run=True, ) trainer.fit(model) checkpo...
[ "def", "test_ddp_sharded_plugin_finetune", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "trainer", "=", "Trainer", "(", "gpus", "=", "2", ",", "accelerator", "=", "'ddp_sharded_spawn'", ",", "fast_dev_run", "=", "True", ",", ")", "trainer", ...
[ 143, 0 ]
[ 160, 28 ]
python
en
['en', 'error', 'th']
False
test_ddp_sharded_plugin_resume_from_checkpoint
(tmpdir)
Test to ensure that resuming from checkpoint works
Test to ensure that resuming from checkpoint works
def test_ddp_sharded_plugin_resume_from_checkpoint(tmpdir): """ Test to ensure that resuming from checkpoint works """ model = BoringModel() trainer = Trainer( accelerator='ddp_sharded_spawn', num_processes=2, fast_dev_run=True, ) trainer.fit(model) checkpoi...
[ "def", "test_ddp_sharded_plugin_resume_from_checkpoint", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "trainer", "=", "Trainer", "(", "accelerator", "=", "'ddp_sharded_spawn'", ",", "num_processes", "=", "2", ",", "fast_dev_run", "=", "True", ",...
[ 165, 0 ]
[ 190, 22 ]
python
en
['en', 'error', 'th']
False
test_ddp_sharded_plugin_resume_from_checkpoint_downsize_gpus
(tmpdir)
Test to ensure that resuming from checkpoint works when downsizing number of GPUS
Test to ensure that resuming from checkpoint works when downsizing number of GPUS
def test_ddp_sharded_plugin_resume_from_checkpoint_downsize_gpus(tmpdir): """ Test to ensure that resuming from checkpoint works when downsizing number of GPUS """ model = BoringModel() trainer = Trainer( accelerator='ddp_sharded_spawn', fast_dev_run=True, gpus=2, ) ...
[ "def", "test_ddp_sharded_plugin_resume_from_checkpoint_downsize_gpus", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "trainer", "=", "Trainer", "(", "accelerator", "=", "'ddp_sharded_spawn'", ",", "fast_dev_run", "=", "True", ",", "gpus", "=", "2",...
[ 198, 0 ]
[ 223, 22 ]
python
en
['en', 'error', 'th']
False
test_ddp_sharded_plugin_resume_from_checkpoint_gpu_to_cpu
(tmpdir)
Test to ensure that resuming from checkpoint works when going from GPUs- > CPU
Test to ensure that resuming from checkpoint works when going from GPUs- > CPU
def test_ddp_sharded_plugin_resume_from_checkpoint_gpu_to_cpu(tmpdir): """ Test to ensure that resuming from checkpoint works when going from GPUs- > CPU """ model = BoringModel() trainer = Trainer( accelerator='ddp_sharded_spawn', gpus=1, fast_dev_run=True, ) tr...
[ "def", "test_ddp_sharded_plugin_resume_from_checkpoint_gpu_to_cpu", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "trainer", "=", "Trainer", "(", "accelerator", "=", "'ddp_sharded_spawn'", ",", "gpus", "=", "1", ",", "fast_dev_run", "=", "True", ...
[ 229, 0 ]
[ 254, 22 ]
python
en
['en', 'error', 'th']
False
test_ddp_sharded_plugin_test
(tmpdir)
Test to ensure we can use test without fit
Test to ensure we can use test without fit
def test_ddp_sharded_plugin_test(tmpdir): """ Test to ensure we can use test without fit """ model = BoringModel() trainer = Trainer( accelerator='ddp_sharded_spawn', num_processes=2, fast_dev_run=True, ) trainer.test(model)
[ "def", "test_ddp_sharded_plugin_test", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "trainer", "=", "Trainer", "(", "accelerator", "=", "'ddp_sharded_spawn'", ",", "num_processes", "=", "2", ",", "fast_dev_run", "=", "True", ",", ")", "train...
[ 262, 0 ]
[ 273, 23 ]
python
en
['en', 'error', 'th']
False
test_ddp_sharded_plugin_test_multigpu
(tmpdir)
Test to ensure we can use test without fit
Test to ensure we can use test without fit
def test_ddp_sharded_plugin_test_multigpu(tmpdir): """ Test to ensure we can use test without fit """ model = BoringModel() trainer = Trainer( accelerator='ddp_sharded_spawn', gpus=2, fast_dev_run=True, ) trainer.test(model)
[ "def", "test_ddp_sharded_plugin_test_multigpu", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "trainer", "=", "Trainer", "(", "accelerator", "=", "'ddp_sharded_spawn'", ",", "gpus", "=", "2", ",", "fast_dev_run", "=", "True", ",", ")", "train...
[ 279, 0 ]
[ 290, 23 ]
python
en
['en', 'error', 'th']
False
test__training_step__flow_dict
(tmpdir)
Tests that only training_step can be used
Tests that only training_step can be used
def test__training_step__flow_dict(tmpdir): """ Tests that only training_step can be used """ class TestModel(DeterministicModel): def training_step(self, batch, batch_idx): acc = self.step(batch, batch_idx) acc = acc + batch_idx self.training_step_called = ...
[ "def", "test__training_step__flow_dict", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "DeterministicModel", ")", ":", "def", "training_step", "(", "self", ",", "batch", ",", "batch_idx", ")", ":", "acc", "=", "self", ".", "step", "(", "batch", ",", ...
[ 27, 0 ]
[ 59, 46 ]
python
en
['en', 'error', 'th']
False
test__training_step__tr_step_end__flow_dict
(tmpdir)
Tests that only training_step can be used
Tests that only training_step can be used
def test__training_step__tr_step_end__flow_dict(tmpdir): """ Tests that only training_step can be used """ class TestModel(DeterministicModel): def training_step(self, batch, batch_idx): acc = self.step(batch, batch_idx) acc = acc + batch_idx self.training_s...
[ "def", "test__training_step__tr_step_end__flow_dict", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "DeterministicModel", ")", ":", "def", "training_step", "(", "self", ",", "batch", ",", "batch_idx", ")", ":", "acc", "=", "self", ".", "step", "(", "batc...
[ 63, 0 ]
[ 102, 46 ]
python
en
['en', 'error', 'th']
False
test__training_step__epoch_end__flow_dict
(tmpdir)
Tests that only training_step can be used
Tests that only training_step can be used
def test__training_step__epoch_end__flow_dict(tmpdir): """ Tests that only training_step can be used """ class TestModel(DeterministicModel): def training_step(self, batch, batch_idx): acc = self.step(batch, batch_idx) acc = acc + batch_idx self.training_st...
[ "def", "test__training_step__epoch_end__flow_dict", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "DeterministicModel", ")", ":", "def", "training_step", "(", "self", ",", "batch", ",", "batch_idx", ")", ":", "acc", "=", "self", ".", "step", "(", "batch"...
[ 106, 0 ]
[ 151, 42 ]
python
en
['en', 'error', 'th']
False
test__training_step__step_end__epoch_end__flow_dict
(tmpdir)
Tests that only training_step can be used
Tests that only training_step can be used
def test__training_step__step_end__epoch_end__flow_dict(tmpdir): """ Tests that only training_step can be used """ class TestModel(DeterministicModel): def training_step(self, batch, batch_idx): acc = self.step(batch, batch_idx) acc = acc + batch_idx self.t...
[ "def", "test__training_step__step_end__epoch_end__flow_dict", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "DeterministicModel", ")", ":", "def", "training_step", "(", "self", ",", "batch", ",", "batch_idx", ")", ":", "acc", "=", "self", ".", "step", "(",...
[ 155, 0 ]
[ 206, 42 ]
python
en
['en', 'error', 'th']
False
Settings.setOptions
(self)
Método para receber algumas configurações do jogo de um arquivo .json. Caso o arquivo não exista, será criado um com as configurações padrões.
Método para receber algumas configurações do jogo de um arquivo .json. Caso o arquivo não exista, será criado um com as configurações padrões.
def setOptions(self): """ Método para receber algumas configurações do jogo de um arquivo .json. Caso o arquivo não exista, será criado um com as configurações padrões. """ # Alguns atributos que podem ser alterados attributes = "window_fullscreen,window_width,window_he...
[ "def", "setOptions", "(", "self", ")", ":", "# Alguns atributos que podem ser alterados", "attributes", "=", "\"window_fullscreen,window_width,window_height\"", ".", "split", "(", "','", ")", "# Tenta abrir o arquivo parar leitura", "try", ":", "file", "=", "open", "(", "...
[ 64, 4 ]
[ 106, 24 ]
python
en
['en', 'error', 'th']
False
ParallelPlugin.configure_sync_batchnorm
(model: LightningModule)
Add global batchnorm for a model spread across multiple GPUs and nodes. Override to synchronize batchnorm between specific process groups instead of the whole world or use a different sync_bn like `apex`'s version. Args: model: pointer to current :class:`LightningModule`. ...
Add global batchnorm for a model spread across multiple GPUs and nodes.
def configure_sync_batchnorm(model: LightningModule) -> LightningModule: """ Add global batchnorm for a model spread across multiple GPUs and nodes. Override to synchronize batchnorm between specific process groups instead of the whole world or use a different sync_bn like `apex`'s vers...
[ "def", "configure_sync_batchnorm", "(", "model", ":", "LightningModule", ")", "->", "LightningModule", ":", "model", "=", "torch", ".", "nn", ".", "SyncBatchNorm", ".", "convert_sync_batchnorm", "(", "model", ")", "return", "model" ]
[ 93, 4 ]
[ 107, 20 ]
python
en
['en', 'error', 'th']
False
ParallelPlugin.block_backward_sync
(self)
Blocks ddp sync gradients behaviour on backwards pass. This is useful for skipping sync when accumulating gradients, reducing communication overhead Returns: context manager with sync behaviour off
Blocks ddp sync gradients behaviour on backwards pass. This is useful for skipping sync when accumulating gradients, reducing communication overhead Returns: context manager with sync behaviour off
def block_backward_sync(self): """ Blocks ddp sync gradients behaviour on backwards pass. This is useful for skipping sync when accumulating gradients, reducing communication overhead Returns: context manager with sync behaviour off """ if isinstance(self.model, Distribut...
[ "def", "block_backward_sync", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "model", ",", "DistributedDataParallel", ")", ":", "with", "self", ".", "model", ".", "no_sync", "(", ")", ":", "yield", "None", "else", ":", "yield", "None" ]
[ 110, 4 ]
[ 120, 22 ]
python
en
['en', 'error', 'th']
False
_min_int
(low, high)
get small int that fits the range
get small int that fits the range
def _min_int(low, high): """ get small int that fits the range """ if high <= i1.max and low >= i1.min: return int8 if high <= i2.max and low >= i2.min: return int16 if high <= i4.max and low >= i4.min: return int32 return int64
[ "def", "_min_int", "(", "low", ",", "high", ")", ":", "if", "high", "<=", "i1", ".", "max", "and", "low", ">=", "i1", ".", "min", ":", "return", "int8", "if", "high", "<=", "i2", ".", "max", "and", "low", ">=", "i2", ".", "min", ":", "return", ...
[ 32, 0 ]
[ 40, 16 ]
python
en
['en', 'en', 'en']
True
fliplr
(m)
Flip array in the left/right direction. Flip the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before. Parameters ---------- m : array_like Input array, must be at least 2-D. Returns ------- f : ndarray ...
Flip array in the left/right direction.
def fliplr(m): """ Flip array in the left/right direction. Flip the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before. Parameters ---------- m : array_like Input array, must be at least 2-D. Returns ------- ...
[ "def", "fliplr", "(", "m", ")", ":", "m", "=", "asanyarray", "(", "m", ")", "if", "m", ".", "ndim", "<", "2", ":", "raise", "ValueError", "(", "\"Input must be >= 2-d.\"", ")", "return", "m", "[", ":", ",", ":", ":", "-", "1", "]" ]
[ 48, 0 ]
[ 95, 21 ]
python
en
['en', 'error', 'th']
False
flipud
(m)
Flip array in the up/down direction. Flip the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before. Parameters ---------- m : array_like Input array. Returns ------- out : array_like A view of `m` with th...
Flip array in the up/down direction.
def flipud(m): """ Flip array in the up/down direction. Flip the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before. Parameters ---------- m : array_like Input array. Returns ------- out : array_like ...
[ "def", "flipud", "(", "m", ")", ":", "m", "=", "asanyarray", "(", "m", ")", "if", "m", ".", "ndim", "<", "1", ":", "raise", "ValueError", "(", "\"Input must be >= 1-d.\"", ")", "return", "m", "[", ":", ":", "-", "1", ",", "...", "]" ]
[ 99, 0 ]
[ 150, 23 ]
python
en
['en', 'error', 'th']
False
eye
(N, M=None, k=0, dtype=float, order='C')
Return a 2-D array with ones on the diagonal and zeros elsewhere. Parameters ---------- N : int Number of rows in the output. M : int, optional Number of columns in the output. If None, defaults to `N`. k : int, optional Index of the diagonal: 0 (the default) refers to the ma...
Return a 2-D array with ones on the diagonal and zeros elsewhere.
def eye(N, M=None, k=0, dtype=float, order='C'): """ Return a 2-D array with ones on the diagonal and zeros elsewhere. Parameters ---------- N : int Number of rows in the output. M : int, optional Number of columns in the output. If None, defaults to `N`. k : int, optional ...
[ "def", "eye", "(", "N", ",", "M", "=", "None", ",", "k", "=", "0", ",", "dtype", "=", "float", ",", "order", "=", "'C'", ")", ":", "if", "M", "is", "None", ":", "M", "=", "N", "m", "=", "zeros", "(", "(", "N", ",", "M", ")", ",", "dtype...
[ 154, 0 ]
[ 208, 12 ]
python
en
['en', 'error', 'th']
False
diag
(v, k=0)
Extract a diagonal or construct a diagonal array. See the more detailed documentation for ``numpy.diagonal`` if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are using. Parameters ...
Extract a diagonal or construct a diagonal array.
def diag(v, k=0): """ Extract a diagonal or construct a diagonal array. See the more detailed documentation for ``numpy.diagonal`` if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you ar...
[ "def", "diag", "(", "v", ",", "k", "=", "0", ")", ":", "v", "=", "asanyarray", "(", "v", ")", "s", "=", "v", ".", "shape", "if", "len", "(", "s", ")", "==", "1", ":", "n", "=", "s", "[", "0", "]", "+", "abs", "(", "k", ")", "res", "="...
[ 216, 0 ]
[ 284, 52 ]
python
en
['en', 'error', 'th']
False
diagflat
(v, k=0)
Create a two-dimensional array with the flattened input as a diagonal. Parameters ---------- v : array_like Input data, which is flattened and set as the `k`-th diagonal of the output. k : int, optional Diagonal to set; 0, the default, corresponds to the "main" diagonal, ...
Create a two-dimensional array with the flattened input as a diagonal.
def diagflat(v, k=0): """ Create a two-dimensional array with the flattened input as a diagonal. Parameters ---------- v : array_like Input data, which is flattened and set as the `k`-th diagonal of the output. k : int, optional Diagonal to set; 0, the default, correspon...
[ "def", "diagflat", "(", "v", ",", "k", "=", "0", ")", ":", "try", ":", "wrap", "=", "v", ".", "__array_wrap__", "except", "AttributeError", ":", "wrap", "=", "None", "v", "=", "asarray", "(", "v", ")", ".", "ravel", "(", ")", "s", "=", "len", "...
[ 288, 0 ]
[ 344, 20 ]
python
en
['en', 'error', 'th']
False
tri
(N, M=None, k=0, dtype=float)
An array with ones at and below the given diagonal and zeros elsewhere. Parameters ---------- N : int Number of rows in the array. M : int, optional Number of columns in the array. By default, `M` is taken equal to `N`. k : int, optional The sub-diagonal at and ...
An array with ones at and below the given diagonal and zeros elsewhere.
def tri(N, M=None, k=0, dtype=float): """ An array with ones at and below the given diagonal and zeros elsewhere. Parameters ---------- N : int Number of rows in the array. M : int, optional Number of columns in the array. By default, `M` is taken equal to `N`. k : i...
[ "def", "tri", "(", "N", ",", "M", "=", "None", ",", "k", "=", "0", ",", "dtype", "=", "float", ")", ":", "if", "M", "is", "None", ":", "M", "=", "N", "m", "=", "greater_equal", ".", "outer", "(", "arange", "(", "N", ",", "dtype", "=", "_min...
[ 348, 0 ]
[ 394, 12 ]
python
en
['en', 'error', 'th']
False
tril
(m, k=0)
Lower triangle of an array. Return a copy of an array with elements above the `k`-th diagonal zeroed. Parameters ---------- m : array_like, shape (M, N) Input array. k : int, optional Diagonal above which to zero elements. `k = 0` (the default) is the main diagonal, `...
Lower triangle of an array.
def tril(m, k=0): """ Lower triangle of an array. Return a copy of an array with elements above the `k`-th diagonal zeroed. Parameters ---------- m : array_like, shape (M, N) Input array. k : int, optional Diagonal above which to zero elements. `k = 0` (the default) is the...
[ "def", "tril", "(", "m", ",", "k", "=", "0", ")", ":", "m", "=", "asanyarray", "(", "m", ")", "mask", "=", "tri", "(", "*", "m", ".", "shape", "[", "-", "2", ":", "]", ",", "k", "=", "k", ",", "dtype", "=", "bool", ")", "return", "where",...
[ 402, 0 ]
[ 437, 44 ]
python
en
['en', 'error', 'th']
False
triu
(m, k=0)
Upper triangle of an array. Return a copy of a matrix with the elements below the `k`-th diagonal zeroed. Please refer to the documentation for `tril` for further details. See Also -------- tril : lower triangle of an array Examples -------- >>> np.triu([[1,2,3],[4,5,6],[7,8...
Upper triangle of an array.
def triu(m, k=0): """ Upper triangle of an array. Return a copy of a matrix with the elements below the `k`-th diagonal zeroed. Please refer to the documentation for `tril` for further details. See Also -------- tril : lower triangle of an array Examples -------- >>> np.t...
[ "def", "triu", "(", "m", ",", "k", "=", "0", ")", ":", "m", "=", "asanyarray", "(", "m", ")", "mask", "=", "tri", "(", "*", "m", ".", "shape", "[", "-", "2", ":", "]", ",", "k", "=", "k", "-", "1", ",", "dtype", "=", "bool", ")", "retur...
[ 441, 0 ]
[ 466, 44 ]
python
en
['en', 'error', 'th']
False
vander
(x, N=None, increasing=False)
Generate a Vandermonde matrix. The columns of the output matrix are powers of the input vector. The order of the powers is determined by the `increasing` boolean argument. Specifically, when `increasing` is False, the `i`-th output column is the input vector raised element-wise to the power of ``N...
Generate a Vandermonde matrix.
def vander(x, N=None, increasing=False): """ Generate a Vandermonde matrix. The columns of the output matrix are powers of the input vector. The order of the powers is determined by the `increasing` boolean argument. Specifically, when `increasing` is False, the `i`-th output column is the inpu...
[ "def", "vander", "(", "x", ",", "N", "=", "None", ",", "increasing", "=", "False", ")", ":", "x", "=", "asarray", "(", "x", ")", "if", "x", ".", "ndim", "!=", "1", ":", "raise", "ValueError", "(", "\"x must be a one-dimensional array or sequence.\"", ")"...
[ 475, 0 ]
[ 562, 12 ]
python
en
['en', 'error', 'th']
False
histogram2d
(x, y, bins=10, range=None, normed=None, weights=None, density=None)
Compute the bi-dimensional histogram of two data samples. Parameters ---------- x : array_like, shape (N,) An array containing the x coordinates of the points to be histogrammed. y : array_like, shape (N,) An array containing the y coordinates of the points to be hi...
Compute the bi-dimensional histogram of two data samples.
def histogram2d(x, y, bins=10, range=None, normed=None, weights=None, density=None): """ Compute the bi-dimensional histogram of two data samples. Parameters ---------- x : array_like, shape (N,) An array containing the x coordinates of the points to be histogrammed....
[ "def", "histogram2d", "(", "x", ",", "y", ",", "bins", "=", "10", ",", "range", "=", "None", ",", "normed", "=", "None", ",", "weights", "=", "None", ",", "density", "=", "None", ")", ":", "from", "numpy", "import", "histogramdd", "try", ":", "N", ...
[ 584, 0 ]
[ 715, 35 ]
python
en
['en', 'error', 'th']
False
mask_indices
(n, mask_func, k=0)
Return the indices to access (n, n) arrays, given a masking function. Assume `mask_func` is a function that, for a square array a of size ``(n, n)`` with a possible offset argument `k`, when called as ``mask_func(a, k)`` returns a new array with zeros in certain locations (functions like `triu` or...
Return the indices to access (n, n) arrays, given a masking function.
def mask_indices(n, mask_func, k=0): """ Return the indices to access (n, n) arrays, given a masking function. Assume `mask_func` is a function that, for a square array a of size ``(n, n)`` with a possible offset argument `k`, when called as ``mask_func(a, k)`` returns a new array with zeros in cer...
[ "def", "mask_indices", "(", "n", ",", "mask_func", ",", "k", "=", "0", ")", ":", "m", "=", "ones", "(", "(", "n", ",", "n", ")", ",", "int", ")", "a", "=", "mask_func", "(", "m", ",", "k", ")", "return", "nonzero", "(", "a", "!=", "0", ")" ...
[ 719, 0 ]
[ 786, 26 ]
python
en
['en', 'error', 'th']
False
tril_indices
(n, k=0, m=None)
Return the indices for the lower-triangle of an (n, m) array. Parameters ---------- n : int The row dimension of the arrays for which the returned indices will be valid. k : int, optional Diagonal offset (see `tril` for details). m : int, optional .. versionadde...
Return the indices for the lower-triangle of an (n, m) array.
def tril_indices(n, k=0, m=None): """ Return the indices for the lower-triangle of an (n, m) array. Parameters ---------- n : int The row dimension of the arrays for which the returned indices will be valid. k : int, optional Diagonal offset (see `tril` for details). ...
[ "def", "tril_indices", "(", "n", ",", "k", "=", "0", ",", "m", "=", "None", ")", ":", "return", "nonzero", "(", "tri", "(", "n", ",", "m", ",", "k", "=", "k", ",", "dtype", "=", "bool", ")", ")" ]
[ 790, 0 ]
[ 867, 46 ]
python
en
['en', 'error', 'th']
False
tril_indices_from
(arr, k=0)
Return the indices for the lower-triangle of arr. See `tril_indices` for full details. Parameters ---------- arr : array_like The indices will be valid for square arrays whose dimensions are the same as arr. k : int, optional Diagonal offset (see `tril` for details). ...
Return the indices for the lower-triangle of arr.
def tril_indices_from(arr, k=0): """ Return the indices for the lower-triangle of arr. See `tril_indices` for full details. Parameters ---------- arr : array_like The indices will be valid for square arrays whose dimensions are the same as arr. k : int, optional Dia...
[ "def", "tril_indices_from", "(", "arr", ",", "k", "=", "0", ")", ":", "if", "arr", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "\"input array must be 2-d\"", ")", "return", "tril_indices", "(", "arr", ".", "shape", "[", "-", "2", "]", ",",...
[ 875, 0 ]
[ 900, 60 ]
python
en
['en', 'error', 'th']
False
triu_indices
(n, k=0, m=None)
Return the indices for the upper-triangle of an (n, m) array. Parameters ---------- n : int The size of the arrays for which the returned indices will be valid. k : int, optional Diagonal offset (see `triu` for details). m : int, optional .. versionadded:: 1.9.0...
Return the indices for the upper-triangle of an (n, m) array.
def triu_indices(n, k=0, m=None): """ Return the indices for the upper-triangle of an (n, m) array. Parameters ---------- n : int The size of the arrays for which the returned indices will be valid. k : int, optional Diagonal offset (see `triu` for details). m : int,...
[ "def", "triu_indices", "(", "n", ",", "k", "=", "0", ",", "m", "=", "None", ")", ":", "return", "nonzero", "(", "~", "tri", "(", "n", ",", "m", ",", "k", "=", "k", "-", "1", ",", "dtype", "=", "bool", ")", ")" ]
[ 904, 0 ]
[ 983, 49 ]
python
en
['en', 'error', 'th']
False
triu_indices_from
(arr, k=0)
Return the indices for the upper-triangle of arr. See `triu_indices` for full details. Parameters ---------- arr : ndarray, shape(N, N) The indices will be valid for square arrays. k : int, optional Diagonal offset (see `triu` for details). Returns ------- triu_in...
Return the indices for the upper-triangle of arr.
def triu_indices_from(arr, k=0): """ Return the indices for the upper-triangle of arr. See `triu_indices` for full details. Parameters ---------- arr : ndarray, shape(N, N) The indices will be valid for square arrays. k : int, optional Diagonal offset (see `triu` for detail...
[ "def", "triu_indices_from", "(", "arr", ",", "k", "=", "0", ")", ":", "if", "arr", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "\"input array must be 2-d\"", ")", "return", "triu_indices", "(", "arr", ".", "shape", "[", "-", "2", "]", ",",...
[ 987, 0 ]
[ 1016, 60 ]
python
en
['en', 'error', 'th']
False
ediff1d
(ary, to_end=None, to_begin=None)
The differences between consecutive elements of an array. Parameters ---------- ary : array_like If necessary, will be flattened before the differences are taken. to_end : array_like, optional Number(s) to append at the end of the returned differences. to_begin : array_like, op...
The differences between consecutive elements of an array.
def ediff1d(ary, to_end=None, to_begin=None): """ The differences between consecutive elements of an array. Parameters ---------- ary : array_like If necessary, will be flattened before the differences are taken. to_end : array_like, optional Number(s) to append at the end of th...
[ "def", "ediff1d", "(", "ary", ",", "to_end", "=", "None", ",", "to_begin", "=", "None", ")", ":", "# force a 1d array", "ary", "=", "np", ".", "asanyarray", "(", "ary", ")", ".", "ravel", "(", ")", "# enforce propagation of the dtype of input", "# ary to retur...
[ 50, 0 ]
[ 134, 17 ]
python
en
['en', 'error', 'th']
False
_unpack_tuple
(x)
Unpacks one-element tuples for use as return values
Unpacks one-element tuples for use as return values
def _unpack_tuple(x): """ Unpacks one-element tuples for use as return values """ if len(x) == 1: return x[0] else: return x
[ "def", "_unpack_tuple", "(", "x", ")", ":", "if", "len", "(", "x", ")", "==", "1", ":", "return", "x", "[", "0", "]", "else", ":", "return", "x" ]
[ 137, 0 ]
[ 142, 16 ]
python
en
['en', 'en', 'en']
True
unique
(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)
Find the unique elements of an array. Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements: * the indices of the input array that give the unique values * the indices of the unique array that reconstruct the input array * the numb...
Find the unique elements of an array.
def unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None): """ Find the unique elements of an array. Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements: * the indices of the input array that ...
[ "def", "unique", "(", "ar", ",", "return_index", "=", "False", ",", "return_inverse", "=", "False", ",", "return_counts", "=", "False", ",", "axis", "=", "None", ")", ":", "ar", "=", "np", ".", "asanyarray", "(", "ar", ")", "if", "axis", "is", "None"...
[ 151, 0 ]
[ 293, 32 ]
python
en
['en', 'error', 'th']
False
_unique1d
(ar, return_index=False, return_inverse=False, return_counts=False)
Find the unique elements of an array, ignoring shape.
Find the unique elements of an array, ignoring shape.
def _unique1d(ar, return_index=False, return_inverse=False, return_counts=False): """ Find the unique elements of an array, ignoring shape. """ ar = np.asanyarray(ar).flatten() optional_indices = return_index or return_inverse if optional_indices: perm = ar.argsort(kind='...
[ "def", "_unique1d", "(", "ar", ",", "return_index", "=", "False", ",", "return_inverse", "=", "False", ",", "return_counts", "=", "False", ")", ":", "ar", "=", "np", ".", "asanyarray", "(", "ar", ")", ".", "flatten", "(", ")", "optional_indices", "=", ...
[ 296, 0 ]
[ 326, 14 ]
python
en
['en', 'error', 'th']
False
intersect1d
(ar1, ar2, assume_unique=False, return_indices=False)
Find the intersection of two arrays. Return the sorted, unique values that are in both of the input arrays. Parameters ---------- ar1, ar2 : array_like Input arrays. Will be flattened if not already 1D. assume_unique : bool If True, the input arrays are both assumed to be uniq...
Find the intersection of two arrays.
def intersect1d(ar1, ar2, assume_unique=False, return_indices=False): """ Find the intersection of two arrays. Return the sorted, unique values that are in both of the input arrays. Parameters ---------- ar1, ar2 : array_like Input arrays. Will be flattened if not already 1D. assum...
[ "def", "intersect1d", "(", "ar1", ",", "ar2", ",", "assume_unique", "=", "False", ",", "return_indices", "=", "False", ")", ":", "ar1", "=", "np", ".", "asanyarray", "(", "ar1", ")", "ar2", "=", "np", ".", "asanyarray", "(", "ar2", ")", "if", "not", ...
[ 335, 0 ]
[ 428, 20 ]
python
en
['en', 'error', 'th']
False
setxor1d
(ar1, ar2, assume_unique=False)
Find the set exclusive-or of two arrays. Return the sorted, unique values that are in only one (not both) of the input arrays. Parameters ---------- ar1, ar2 : array_like Input arrays. assume_unique : bool If True, the input arrays are both assumed to be unique, which ...
Find the set exclusive-or of two arrays.
def setxor1d(ar1, ar2, assume_unique=False): """ Find the set exclusive-or of two arrays. Return the sorted, unique values that are in only one (not both) of the input arrays. Parameters ---------- ar1, ar2 : array_like Input arrays. assume_unique : bool If True, the in...
[ "def", "setxor1d", "(", "ar1", ",", "ar2", ",", "assume_unique", "=", "False", ")", ":", "if", "not", "assume_unique", ":", "ar1", "=", "unique", "(", "ar1", ")", "ar2", "=", "unique", "(", "ar2", ")", "aux", "=", "np", ".", "concatenate", "(", "("...
[ 436, 0 ]
[ 475, 36 ]
python
en
['en', 'error', 'th']
False
in1d
(ar1, ar2, assume_unique=False, invert=False)
Test whether each element of a 1-D array is also present in a second array. Returns a boolean array the same length as `ar1` that is True where an element of `ar1` is in `ar2` and False otherwise. We recommend using :func:`isin` instead of `in1d` for new code. Parameters ---------- ar1 :...
Test whether each element of a 1-D array is also present in a second array.
def in1d(ar1, ar2, assume_unique=False, invert=False): """ Test whether each element of a 1-D array is also present in a second array. Returns a boolean array the same length as `ar1` that is True where an element of `ar1` is in `ar2` and False otherwise. We recommend using :func:`isin` instead of...
[ "def", "in1d", "(", "ar1", ",", "ar2", ",", "assume_unique", "=", "False", ",", "invert", "=", "False", ")", ":", "# Ravel both arrays, behavior for the first array could be different", "ar1", "=", "np", ".", "asarray", "(", "ar1", ")", ".", "ravel", "(", ")",...
[ 483, 0 ]
[ 592, 27 ]
python
en
['en', 'error', 'th']
False
isin
(element, test_elements, assume_unique=False, invert=False)
Calculates `element in test_elements`, broadcasting over `element` only. Returns a boolean array of the same shape as `element` that is True where an element of `element` is in `test_elements` and False otherwise. Parameters ---------- element : array_like Input array. test_element...
Calculates `element in test_elements`, broadcasting over `element` only. Returns a boolean array of the same shape as `element` that is True where an element of `element` is in `test_elements` and False otherwise.
def isin(element, test_elements, assume_unique=False, invert=False): """ Calculates `element in test_elements`, broadcasting over `element` only. Returns a boolean array of the same shape as `element` that is True where an element of `element` is in `test_elements` and False otherwise. Parameters ...
[ "def", "isin", "(", "element", ",", "test_elements", ",", "assume_unique", "=", "False", ",", "invert", "=", "False", ")", ":", "element", "=", "np", ".", "asarray", "(", "element", ")", "return", "in1d", "(", "element", ",", "test_elements", ",", "assum...
[ 600, 0 ]
[ 695, 53 ]
python
en
['en', 'error', 'th']
False
union1d
(ar1, ar2)
Find the union of two arrays. Return the unique, sorted array of values that are in either of the two input arrays. Parameters ---------- ar1, ar2 : array_like Input arrays. They are flattened if they are not already 1D. Returns ------- union1d : ndarray Unique, s...
Find the union of two arrays.
def union1d(ar1, ar2): """ Find the union of two arrays. Return the unique, sorted array of values that are in either of the two input arrays. Parameters ---------- ar1, ar2 : array_like Input arrays. They are flattened if they are not already 1D. Returns ------- union...
[ "def", "union1d", "(", "ar1", ",", "ar2", ")", ":", "return", "unique", "(", "np", ".", "concatenate", "(", "(", "ar1", ",", "ar2", ")", ",", "axis", "=", "None", ")", ")" ]
[ 703, 0 ]
[ 736, 56 ]
python
en
['en', 'error', 'th']
False
setdiff1d
(ar1, ar2, assume_unique=False)
Find the set difference of two arrays. Return the unique values in `ar1` that are not in `ar2`. Parameters ---------- ar1 : array_like Input array. ar2 : array_like Input comparison array. assume_unique : bool If True, the input arrays are both assumed to be unique...
Find the set difference of two arrays.
def setdiff1d(ar1, ar2, assume_unique=False): """ Find the set difference of two arrays. Return the unique values in `ar1` that are not in `ar2`. Parameters ---------- ar1 : array_like Input array. ar2 : array_like Input comparison array. assume_unique : bool If...
[ "def", "setdiff1d", "(", "ar1", ",", "ar2", ",", "assume_unique", "=", "False", ")", ":", "if", "assume_unique", ":", "ar1", "=", "np", ".", "asarray", "(", "ar1", ")", ".", "ravel", "(", ")", "else", ":", "ar1", "=", "unique", "(", "ar1", ")", "...
[ 744, 0 ]
[ 785, 63 ]
python
en
['en', 'error', 'th']
False
test_backward_count_simple
(torch_backward, num_steps)
Test that backward is called exactly once per step.
Test that backward is called exactly once per step.
def test_backward_count_simple(torch_backward, num_steps): """ Test that backward is called exactly once per step. """ model = EvalModelTemplate() trainer = Trainer(max_steps=num_steps) trainer.fit(model) assert torch_backward.call_count == num_steps torch_backward.reset_mock() trainer.tes...
[ "def", "test_backward_count_simple", "(", "torch_backward", ",", "num_steps", ")", ":", "model", "=", "EvalModelTemplate", "(", ")", "trainer", "=", "Trainer", "(", "max_steps", "=", "num_steps", ")", "trainer", ".", "fit", "(", "model", ")", "assert", "torch_...
[ 10, 0 ]
[ 20, 41 ]
python
en
['en', 'en', 'en']
True
test_backward_count_with_grad_accumulation
(torch_backward)
Test that backward is called the correct number of times when accumulating gradients.
Test that backward is called the correct number of times when accumulating gradients.
def test_backward_count_with_grad_accumulation(torch_backward): """ Test that backward is called the correct number of times when accumulating gradients. """ model = EvalModelTemplate() trainer = Trainer(max_epochs=1, limit_train_batches=6, accumulate_grad_batches=2) trainer.fit(model) assert torch_...
[ "def", "test_backward_count_with_grad_accumulation", "(", "torch_backward", ")", ":", "model", "=", "EvalModelTemplate", "(", ")", "trainer", "=", "Trainer", "(", "max_epochs", "=", "1", ",", "limit_train_batches", "=", "6", ",", "accumulate_grad_batches", "=", "2",...
[ 24, 0 ]
[ 35, 42 ]
python
en
['en', 'en', 'en']
True
test_backward_count_with_closure
(torch_backward)
Using a closure (e.g. with LBFGS) should lead to no extra backward calls.
Using a closure (e.g. with LBFGS) should lead to no extra backward calls.
def test_backward_count_with_closure(torch_backward): """ Using a closure (e.g. with LBFGS) should lead to no extra backward calls. """ model = EvalModelTemplate() model.configure_optimizers = model.configure_optimizers__lbfgs trainer = Trainer(max_steps=5) trainer.fit(model) assert torch_backwa...
[ "def", "test_backward_count_with_closure", "(", "torch_backward", ")", ":", "model", "=", "EvalModelTemplate", "(", ")", "model", ".", "configure_optimizers", "=", "model", ".", "configure_optimizers__lbfgs", "trainer", "=", "Trainer", "(", "max_steps", "=", "5", ")...
[ 39, 0 ]
[ 51, 42 ]
python
en
['en', 'en', 'en']
True
_load_requirements
(path_dir: str, file_name: str = 'requirements.txt', comment_char: str = '#')
Load requirements from a file >>> _load_requirements(_PROJECT_ROOT) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ['numpy...', 'torch...', ...]
Load requirements from a file
def _load_requirements(path_dir: str, file_name: str = 'requirements.txt', comment_char: str = '#') -> List[str]: """Load requirements from a file >>> _load_requirements(_PROJECT_ROOT) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ['numpy...', 'torch...', ...] """ with open(os.path.join(path_dir, fil...
[ "def", "_load_requirements", "(", "path_dir", ":", "str", ",", "file_name", ":", "str", "=", "'requirements.txt'", ",", "comment_char", ":", "str", "=", "'#'", ")", "->", "List", "[", "str", "]", ":", "with", "open", "(", "os", ".", "path", ".", "join"...
[ 21, 0 ]
[ 39, 15 ]
python
en
['en', 'en', 'en']
True
_load_readme_description
(path_dir: str, homepage: str = __homepage__, version: str = __version__)
Load readme as decribtion >>> _load_readme_description(_PROJECT_ROOT) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE '<div align="center">...'
Load readme as decribtion
def _load_readme_description(path_dir: str, homepage: str = __homepage__, version: str = __version__) -> str: """Load readme as decribtion >>> _load_readme_description(_PROJECT_ROOT) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE '<div align="center">...' """ path_readme = os.path.join(path_dir, "READ...
[ "def", "_load_readme_description", "(", "path_dir", ":", "str", ",", "homepage", ":", "str", "=", "__homepage__", ",", "version", ":", "str", "=", "__version__", ")", "->", "str", ":", "path_readme", "=", "os", ".", "path", ".", "join", "(", "path_dir", ...
[ 42, 0 ]
[ 80, 15 ]
python
en
['pt', 'fr', 'en']
False
_merge
(old, new)
Concatenate two environment paths avoiding repeats. Here `old` is the environment string before the base class initialize function is called and `new` is the string after the call. The new string will be a fixed string if it is not obtained from the current environment, or the same as the old string if...
Concatenate two environment paths avoiding repeats.
def _merge(old, new): """Concatenate two environment paths avoiding repeats. Here `old` is the environment string before the base class initialize function is called and `new` is the string after the call. The new string will be a fixed string if it is not obtained from the current environment, or ...
[ "def", "_merge", "(", "old", ",", "new", ")", ":", "if", "not", "new", "or", "new", "in", "old", ":", "return", "old", "if", "not", "old", "or", "old", "in", "new", ":", "return", "new", "if", "new", "in", "old", ":", "return", "old", "# Neither ...
[ 7, 0 ]
[ 38, 31 ]
python
en
['en', 'en', 'en']
True
iter_struct_object_dtypes
()
Iterates over a few complex dtypes and object pattern which fill the array with a given object (defaults to a singleton). Yields ------ dtype : dtype pattern : tuple Structured tuple for use with `np.array`. count : int Number of objects stored in the dtype. singleton :...
Iterates over a few complex dtypes and object pattern which fill the array with a given object (defaults to a singleton).
def iter_struct_object_dtypes(): """ Iterates over a few complex dtypes and object pattern which fill the array with a given object (defaults to a singleton). Yields ------ dtype : dtype pattern : tuple Structured tuple for use with `np.array`. count : int Number of obje...
[ "def", "iter_struct_object_dtypes", "(", ")", ":", "obj", "=", "object", "(", ")", "dt", "=", "np", ".", "dtype", "(", "[", "(", "'b'", ",", "'O'", ",", "(", "2", ",", "3", ")", ")", "]", ")", "p", "=", "(", "[", "[", "obj", "]", "*", "3", ...
[ 551, 0 ]
[ 585, 68 ]
python
en
['en', 'error', 'th']
False
TestBuiltin.test_run
(self, t)
Only test hash runs at all.
Only test hash runs at all.
def test_run(self, t): """Only test hash runs at all.""" dt = np.dtype(t) hash(dt)
[ "def", "test_run", "(", "self", ",", "t", ")", ":", "dt", "=", "np", ".", "dtype", "(", "t", ")", "hash", "(", "dt", ")" ]
[ 28, 4 ]
[ 31, 16 ]
python
en
['en', 'en', 'en']
True
TestRecord.test_equivalent_record
(self)
Test whether equivalent record dtypes hash the same.
Test whether equivalent record dtypes hash the same.
def test_equivalent_record(self): """Test whether equivalent record dtypes hash the same.""" a = np.dtype([('yo', int)]) b = np.dtype([('yo', int)]) assert_dtype_equal(a, b)
[ "def", "test_equivalent_record", "(", "self", ")", ":", "a", "=", "np", ".", "dtype", "(", "[", "(", "'yo'", ",", "int", ")", "]", ")", "b", "=", "np", ".", "dtype", "(", "[", "(", "'yo'", ",", "int", ")", "]", ")", "assert_dtype_equal", "(", "...
[ 149, 4 ]
[ 153, 32 ]
python
en
['en', 'en', 'en']
True
TestRecord.test_not_lists
(self)
Test if an appropriate exception is raised when passing bad values to the dtype constructor.
Test if an appropriate exception is raised when passing bad values to the dtype constructor.
def test_not_lists(self): """Test if an appropriate exception is raised when passing bad values to the dtype constructor. """ assert_raises(TypeError, np.dtype, dict(names={'A', 'B'}, formats=['f8', 'i4'])) assert_raises(TypeError, np.dtype, ...
[ "def", "test_not_lists", "(", "self", ")", ":", "assert_raises", "(", "TypeError", ",", "np", ".", "dtype", ",", "dict", "(", "names", "=", "{", "'A'", ",", "'B'", "}", ",", "formats", "=", "[", "'f8'", ",", "'i4'", "]", ")", ")", "assert_raises", ...
[ 198, 4 ]
[ 205, 67 ]
python
en
['en', 'en', 'en']
True
TestSubarray.test_equivalent_record
(self)
Test whether equivalent subarray dtypes hash the same.
Test whether equivalent subarray dtypes hash the same.
def test_equivalent_record(self): """Test whether equivalent subarray dtypes hash the same.""" a = np.dtype((int, (2, 3))) b = np.dtype((int, (2, 3))) assert_dtype_equal(a, b)
[ "def", "test_equivalent_record", "(", "self", ")", ":", "a", "=", "np", ".", "dtype", "(", "(", "int", ",", "(", "2", ",", "3", ")", ")", ")", "b", "=", "np", ".", "dtype", "(", "(", "int", ",", "(", "2", ",", "3", ")", ")", ")", "assert_dt...
[ 431, 4 ]
[ 435, 32 ]
python
en
['en', 'en', 'en']
True
TestSubarray.test_nonequivalent_record
(self)
Test whether different subarray dtypes hash differently.
Test whether different subarray dtypes hash differently.
def test_nonequivalent_record(self): """Test whether different subarray dtypes hash differently.""" a = np.dtype((int, (2, 3))) b = np.dtype((int, (3, 2))) assert_dtype_not_equal(a, b) a = np.dtype((int, (2, 3))) b = np.dtype((int, (2, 2))) assert_dtype_not_equal...
[ "def", "test_nonequivalent_record", "(", "self", ")", ":", "a", "=", "np", ".", "dtype", "(", "(", "int", ",", "(", "2", ",", "3", ")", ")", ")", "b", "=", "np", ".", "dtype", "(", "(", "int", ",", "(", "3", ",", "2", ")", ")", ")", "assert...
[ 437, 4 ]
[ 449, 36 ]
python
en
['en', 'en', 'en']
True
TestSubarray.test_shape_equal
(self)
Test some data types that are equal
Test some data types that are equal
def test_shape_equal(self): """Test some data types that are equal""" assert_dtype_equal(np.dtype('f8'), np.dtype(('f8', tuple()))) # FutureWarning during deprecation period; after it is passed this # should instead check that "(1)f8" == "1f8" == ("f8", 1). with pytest.warns(Futu...
[ "def", "test_shape_equal", "(", "self", ")", ":", "assert_dtype_equal", "(", "np", ".", "dtype", "(", "'f8'", ")", ",", "np", ".", "dtype", "(", "(", "'f8'", ",", "tuple", "(", ")", ")", ")", ")", "# FutureWarning during deprecation period; after it is passed ...
[ 451, 4 ]
[ 461, 52 ]
python
en
['en', 'en', 'en']
True
TestSubarray.test_shape_simple
(self)
Test some simple cases that shouldn't be equal
Test some simple cases that shouldn't be equal
def test_shape_simple(self): """Test some simple cases that shouldn't be equal""" assert_dtype_not_equal(np.dtype('f8'), np.dtype(('f8', (1,)))) assert_dtype_not_equal(np.dtype(('f8', (1,))), np.dtype(('f8', (1, 1)))) assert_dtype_not_equal(np.dtype(('f4', (3, 2))), np.dtype(('f4', (2, 3...
[ "def", "test_shape_simple", "(", "self", ")", ":", "assert_dtype_not_equal", "(", "np", ".", "dtype", "(", "'f8'", ")", ",", "np", ".", "dtype", "(", "(", "'f8'", ",", "(", "1", ",", ")", ")", ")", ")", "assert_dtype_not_equal", "(", "np", ".", "dtyp...
[ 463, 4 ]
[ 467, 82 ]
python
en
['en', 'en', 'en']
True
TestSubarray.test_shape_monster
(self)
Test some more complicated cases that shouldn't be equal
Test some more complicated cases that shouldn't be equal
def test_shape_monster(self): """Test some more complicated cases that shouldn't be equal""" assert_dtype_not_equal( np.dtype(([('a', 'f4', (2, 1)), ('b', 'f8', (1, 3))], (2, 2))), np.dtype(([('a', 'f4', (1, 2)), ('b', 'f8', (1, 3))], (2, 2)))) assert_dtype_not_equal( ...
[ "def", "test_shape_monster", "(", "self", ")", ":", "assert_dtype_not_equal", "(", "np", ".", "dtype", "(", "(", "[", "(", "'a'", ",", "'f4'", ",", "(", "2", ",", "1", ")", ")", ",", "(", "'b'", ",", "'f8'", ",", "(", "1", ",", "3", ")", ")", ...
[ 469, 4 ]
[ 482, 87 ]
python
en
['en', 'en', 'en']
True
TestFromCTypes.test_pairs
(self, pair)
Check that np.dtype('x,y') matches [np.dtype('x'), np.dtype('y')] Example: np.dtype('d,I') -> dtype([('f0', '<f8'), ('f1', '<u4')])
Check that np.dtype('x,y') matches [np.dtype('x'), np.dtype('y')] Example: np.dtype('d,I') -> dtype([('f0', '<f8'), ('f1', '<u4')])
def test_pairs(self, pair): """ Check that np.dtype('x,y') matches [np.dtype('x'), np.dtype('y')] Example: np.dtype('d,I') -> dtype([('f0', '<f8'), ('f1', '<u4')]) """ # gh-5645: check that np.dtype('i,L') can be used pair_type = np.dtype('{},{}'.format(*pair)) ex...
[ "def", "test_pairs", "(", "self", ",", "pair", ")", ":", "# gh-5645: check that np.dtype('i,L') can be used", "pair_type", "=", "np", ".", "dtype", "(", "'{},{}'", ".", "format", "(", "*", "pair", ")", ")", "expected", "=", "np", ".", "dtype", "(", "[", "(...
[ 1272, 4 ]
[ 1280, 41 ]
python
en
['en', 'error', 'th']
False
User.hash_password
(self, password)
hash user password :return: string
hash user password :return: string
def hash_password(self, password): """ hash user password :return: string """ return pwd_context.encrypt(password + app.config['LOGIN_SECRET_KEY'])
[ "def", "hash_password", "(", "self", ",", "password", ")", ":", "return", "pwd_context", ".", "encrypt", "(", "password", "+", "app", ".", "config", "[", "'LOGIN_SECRET_KEY'", "]", ")" ]
[ 41, 4 ]
[ 46, 77 ]
python
en
['en', 'error', 'th']
False
User.verify_password
(self, password)
get user password from db and hash it then ruturn. :return: string
get user password from db and hash it then ruturn. :return: string
def verify_password(self, password): """ get user password from db and hash it then ruturn. :return: string """ return pwd_context.verify( password + app.config['LOGIN_SECRET_KEY'], self.password)
[ "def", "verify_password", "(", "self", ",", "password", ")", ":", "return", "pwd_context", ".", "verify", "(", "password", "+", "app", ".", "config", "[", "'LOGIN_SECRET_KEY'", "]", ",", "self", ".", "password", ")" ]
[ 48, 4 ]
[ 54, 69 ]
python
en
['en', 'error', 'th']
False
User.encode_login_auth_token
(self)
Generates the auth token for login :return: string
Generates the auth token for login :return: string
def encode_login_auth_token(self): """ Generates the auth token for login :return: string """ try: payload = { 'exp': datetime.datetime.now() + datetime.timedelta(hours=6, seconds=0), 'iat': datetime.datetime.now(), ...
[ "def", "encode_login_auth_token", "(", "self", ")", ":", "try", ":", "payload", "=", "{", "'exp'", ":", "datetime", ".", "datetime", ".", "now", "(", ")", "+", "datetime", ".", "timedelta", "(", "hours", "=", "6", ",", "seconds", "=", "0", ")", ",", ...
[ 56, 4 ]
[ 76, 20 ]
python
en
['en', 'error', 'th']
False
User.decode_login_auth_token
(auth_token)
Decodes the auth token for login :param auth_token: :return: integer|string
Decodes the auth token for login :param auth_token: :return: integer|string
def decode_login_auth_token(auth_token): """ Decodes the auth token for login :param auth_token: :return: integer|string """ try: payload = jwt.decode(auth_token, app.config['LOGIN_SECRET_KEY']) user = User.query.filter_by(email=payload['sub']).fir...
[ "def", "decode_login_auth_token", "(", "auth_token", ")", ":", "try", ":", "payload", "=", "jwt", ".", "decode", "(", "auth_token", ",", "app", ".", "config", "[", "'LOGIN_SECRET_KEY'", "]", ")", "user", "=", "User", ".", "query", ".", "filter_by", "(", ...
[ 79, 4 ]
[ 92, 56 ]
python
en
['en', 'error', 'th']
False
User.encode_api_auth_token
(self)
Generates the auth token for api :return: string
Generates the auth token for api :return: string
def encode_api_auth_token(self): """ Generates the auth token for api :return: string """ try: payload = { 'exp': datetime.datetime.now() + datetime.timedelta(hours=6, seconds=0), 'iat': datetime.datetime.now(), ...
[ "def", "encode_api_auth_token", "(", "self", ")", ":", "try", ":", "payload", "=", "{", "'exp'", ":", "datetime", ".", "datetime", ".", "now", "(", ")", "+", "datetime", ".", "timedelta", "(", "hours", "=", "6", ",", "seconds", "=", "0", ")", ",", ...
[ 94, 4 ]
[ 114, 20 ]
python
en
['en', 'error', 'th']
False
User.decode_api_auth_token
(auth_token)
Decodes the auth token for api :param auth_token: :return: integer|string
Decodes the auth token for api :param auth_token: :return: integer|string
def decode_api_auth_token(auth_token): """ Decodes the auth token for api :param auth_token: :return: integer|string """ try: payload = jwt.decode(auth_token, app.config['API_SECRET_KEY']) user = User.query.filter_by(email=payload['sub']).first() ...
[ "def", "decode_api_auth_token", "(", "auth_token", ")", ":", "try", ":", "payload", "=", "jwt", ".", "decode", "(", "auth_token", ",", "app", ".", "config", "[", "'API_SECRET_KEY'", "]", ")", "user", "=", "User", ".", "query", ".", "filter_by", "(", "ema...
[ 117, 4 ]
[ 130, 56 ]
python
en
['en', 'error', 'th']
False
User.renew_last_login_date
(self)
record user last login time :return: None
record user last login time :return: None
def renew_last_login_date(self): """ record user last login time :return: None """ self.last_login = datetime.datetime.now() db.session.commit()
[ "def", "renew_last_login_date", "(", "self", ")", ":", "self", ".", "last_login", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "db", ".", "session", ".", "commit", "(", ")" ]
[ 132, 4 ]
[ 138, 27 ]
python
en
['en', 'error', 'th']
False
User.renew_api_token
(self, api_token)
record user new api token :return: None
record user new api token :return: None
def renew_api_token(self, api_token): """ record user new api token :return: None """ self.api_token = api_token db.session.commit()
[ "def", "renew_api_token", "(", "self", ",", "api_token", ")", ":", "self", ".", "api_token", "=", "api_token", "db", ".", "session", ".", "commit", "(", ")" ]
[ 140, 4 ]
[ 146, 27 ]
python
en
['en', 'error', 'th']
False
test_lightning_hasattr
(tmpdir)
Test that the lightning_hasattr works in all cases
Test that the lightning_hasattr works in all cases
def test_lightning_hasattr(tmpdir): """Test that the lightning_hasattr works in all cases""" model1, model2, model3, model4, model5, model6, model7 = models = _get_test_cases() assert lightning_hasattr(model1, 'learning_rate'), \ 'lightning_hasattr failed to find namespace variable' assert light...
[ "def", "test_lightning_hasattr", "(", "tmpdir", ")", ":", "model1", ",", "model2", ",", "model3", ",", "model4", ",", "model5", ",", "model6", ",", "model7", "=", "models", "=", "_get_test_cases", "(", ")", "assert", "lightning_hasattr", "(", "model1", ",", ...
[ 76, 0 ]
[ 95, 62 ]
python
en
['en', 'en', 'en']
True
test_lightning_getattr
(tmpdir)
Test that the lightning_getattr works in all cases
Test that the lightning_getattr works in all cases
def test_lightning_getattr(tmpdir): """Test that the lightning_getattr works in all cases""" models = _get_test_cases() for i, m in enumerate(models[:3]): value = lightning_getattr(m, 'learning_rate') assert value == i, 'attribute not correctly extracted' model5, model6, model7 = models...
[ "def", "test_lightning_getattr", "(", "tmpdir", ")", ":", "models", "=", "_get_test_cases", "(", ")", "for", "i", ",", "m", "in", "enumerate", "(", "models", "[", ":", "3", "]", ")", ":", "value", "=", "lightning_getattr", "(", "m", ",", "'learning_rate'...
[ 98, 0 ]
[ 118, 55 ]
python
en
['en', 'en', 'en']
True
test_lightning_setattr
(tmpdir)
Test that the lightning_setattr works in all cases
Test that the lightning_setattr works in all cases
def test_lightning_setattr(tmpdir): """Test that the lightning_setattr works in all cases""" models = _get_test_cases() for m in models[:3]: lightning_setattr(m, 'learning_rate', 10) assert lightning_getattr(m, 'learning_rate') == 10, \ 'attribute not correctly set' model5, ...
[ "def", "test_lightning_setattr", "(", "tmpdir", ")", ":", "models", "=", "_get_test_cases", "(", ")", "for", "m", "in", "models", "[", ":", "3", "]", ":", "lightning_setattr", "(", "m", ",", "'learning_rate'", ",", "10", ")", "assert", "lightning_getattr", ...
[ 121, 0 ]
[ 145, 61 ]
python
en
['en', 'no', 'en']
True
_convert_batchnorm
(module)
Convert the syncBNs into normal BN3ds.
Convert the syncBNs into normal BN3ds.
def _convert_batchnorm(module): """Convert the syncBNs into normal BN3ds.""" module_output = module if isinstance(module, torch.nn.SyncBatchNorm): module_output = torch.nn.BatchNorm3d(module.num_features, module.eps, module.momentum, module.affine, ...
[ "def", "_convert_batchnorm", "(", "module", ")", ":", "module_output", "=", "module", "if", "isinstance", "(", "module", ",", "torch", ".", "nn", ".", "SyncBatchNorm", ")", ":", "module_output", "=", "torch", ".", "nn", ".", "BatchNorm3d", "(", "module", "...
[ 21, 0 ]
[ 40, 24 ]
python
en
['en', 'en', 'en']
True
pytorch2onnx
(model, input_shape, opset_version=11, show=False, output_file='tmp.onnx', verify=False)
Convert pytorch model to onnx model. Args: model (:obj:`nn.Module`): The pytorch model to be exported. input_shape (tuple[int]): The input tensor shape of the model. opset_version (int): Opset version of onnx used. Default: 11. show (bool): Determines whether to print the onnx model...
Convert pytorch model to onnx model.
def pytorch2onnx(model, input_shape, opset_version=11, show=False, output_file='tmp.onnx', verify=False): """Convert pytorch model to onnx model. Args: model (:obj:`nn.Module`): The pytorch model to be exported. ...
[ "def", "pytorch2onnx", "(", "model", ",", "input_shape", ",", "opset_version", "=", "11", ",", "show", "=", "False", ",", "output_file", "=", "'tmp.onnx'", ",", "verify", "=", "False", ")", ":", "model", ".", "cpu", "(", ")", ".", "eval", "(", ")", "...
[ 43, 0 ]
[ 99, 71 ]
python
en
['en', 'en', 'en']
True
__RandomState_ctor
()
Return a RandomState instance. This function exists solely to assist (un)pickling. Note that the state of the RandomState returned here is irrelevant, as this function's entire purpose is to return a newly allocated RandomState whose state pickle can set. Consequently the RandomState returned by this...
Return a RandomState instance.
def __RandomState_ctor(): """Return a RandomState instance. This function exists solely to assist (un)pickling. Note that the state of the RandomState returned here is irrelevant, as this function's entire purpose is to return a newly allocated RandomState whose state pickle can set. Consequently...
[ "def", "__RandomState_ctor", "(", ")", ":", "return", "RandomState", "(", "seed", "=", "0", ")" ]
[ 197, 0 ]
[ 210, 30 ]
python
en
['en', 'da', 'en']
True
main
()
Kafka code generator script ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Generates C++ code from Kafka protocol specification for Kafka codec. Usage: launcher.py MESSAGE_TYPE OUTPUT_FILES INPUT_FILES where: MESSAGE_TYPE : 'request' or 'response' OUTPUT_FILES : location of 'requests.h'/'responses.h', ...
Kafka code generator script ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Generates C++ code from Kafka protocol specification for Kafka codec.
def main(): """ Kafka code generator script ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Generates C++ code from Kafka protocol specification for Kafka codec. Usage: launcher.py MESSAGE_TYPE OUTPUT_FILES INPUT_FILES where: MESSAGE_TYPE : 'request' or 'response' OUTPUT_FILES : location of 'requests.h'/'responses.h...
[ "def", "main", "(", ")", ":", "type", "=", "sys", ".", "argv", "[", "1", "]", "main_header_file", "=", "os", ".", "path", ".", "abspath", "(", "sys", ".", "argv", "[", "2", "]", ")", "resolver_cc_file", "=", "os", ".", "path", ".", "abspath", "("...
[ 9, 0 ]
[ 46, 78 ]
python
en
['en', 'error', 'th']
False
get_expansion
(block, expansion=None)
Get the expansion of a residual block. The block expansion will be obtained by the following order: 1. If ``expansion`` is given, just return it. 2. If ``block`` has the attribute ``expansion``, then return ``block.expansion``. 3. Return the default value according the the block type: 1 ...
Get the expansion of a residual block.
def get_expansion(block, expansion=None): """Get the expansion of a residual block. The block expansion will be obtained by the following order: 1. If ``expansion`` is given, just return it. 2. If ``block`` has the attribute ``expansion``, then return ``block.expansion``. 3. Return the defa...
[ "def", "get_expansion", "(", "block", ",", "expansion", "=", "None", ")", ":", "if", "isinstance", "(", "expansion", ",", "int", ")", ":", "assert", "expansion", ">", "0", "elif", "expansion", "is", "None", ":", "if", "hasattr", "(", "block", ",", "'ex...
[ 273, 0 ]
[ 305, 20 ]
python
en
['en', 'en', 'en']
True
BasicBlock.norm1
(self)
nn.Module: the normalization layer named "norm1"
nn.Module: the normalization layer named "norm1"
def norm1(self): """nn.Module: the normalization layer named "norm1" """ return getattr(self, self.norm1_name)
[ "def", "norm1", "(", "self", ")", ":", "return", "getattr", "(", "self", ",", "self", ".", "norm1_name", ")" ]
[ 90, 4 ]
[ 92, 45 ]
python
en
['en', 'en', 'en']
True
BasicBlock.norm2
(self)
nn.Module: the normalization layer named "norm2"
nn.Module: the normalization layer named "norm2"
def norm2(self): """nn.Module: the normalization layer named "norm2" """ return getattr(self, self.norm2_name)
[ "def", "norm2", "(", "self", ")", ":", "return", "getattr", "(", "self", ",", "self", ".", "norm2_name", ")" ]
[ 95, 4 ]
[ 97, 45 ]
python
en
['en', 'en', 'en']
True
BasicBlock.forward
(self, x)
Forward function.
Forward function.
def forward(self, x): """Forward function.""" def _inner_forward(x): identity = x out = self.conv1(x) out = self.norm1(out) out = self.relu(out) out = self.conv2(out) out = self.norm2(out) if self.downsample is not N...
[ "def", "forward", "(", "self", ",", "x", ")", ":", "def", "_inner_forward", "(", "x", ")", ":", "identity", "=", "x", "out", "=", "self", ".", "conv1", "(", "x", ")", "out", "=", "self", ".", "norm1", "(", "out", ")", "out", "=", "self", ".", ...
[ 99, 4 ]
[ 126, 18 ]
python
en
['en', 'cy', 'en']
False
Bottleneck.norm1
(self)
nn.Module: the normalization layer named "norm1"
nn.Module: the normalization layer named "norm1"
def norm1(self): """nn.Module: the normalization layer named "norm1" """ return getattr(self, self.norm1_name)
[ "def", "norm1", "(", "self", ")", ":", "return", "getattr", "(", "self", ",", "self", ".", "norm1_name", ")" ]
[ 225, 4 ]
[ 227, 45 ]
python
en
['en', 'en', 'en']
True
Bottleneck.norm2
(self)
nn.Module: the normalization layer named "norm2"
nn.Module: the normalization layer named "norm2"
def norm2(self): """nn.Module: the normalization layer named "norm2" """ return getattr(self, self.norm2_name)
[ "def", "norm2", "(", "self", ")", ":", "return", "getattr", "(", "self", ",", "self", ".", "norm2_name", ")" ]
[ 230, 4 ]
[ 232, 45 ]
python
en
['en', 'en', 'en']
True
Bottleneck.norm3
(self)
nn.Module: the normalization layer named "norm3"
nn.Module: the normalization layer named "norm3"
def norm3(self): """nn.Module: the normalization layer named "norm3" """ return getattr(self, self.norm3_name)
[ "def", "norm3", "(", "self", ")", ":", "return", "getattr", "(", "self", ",", "self", ".", "norm3_name", ")" ]
[ 235, 4 ]
[ 237, 45 ]
python
en
['en', 'en', 'en']
True
Bottleneck.forward
(self, x)
Forward function.
Forward function.
def forward(self, x): """Forward function.""" def _inner_forward(x): identity = x out = self.conv1(x) out = self.norm1(out) out = self.relu(out) out = self.conv2(out) out = self.norm2(out) out = self.relu(out) ...
[ "def", "forward", "(", "self", ",", "x", ")", ":", "def", "_inner_forward", "(", "x", ")", ":", "identity", "=", "x", "out", "=", "self", ".", "conv1", "(", "x", ")", "out", "=", "self", ".", "norm1", "(", "out", ")", "out", "=", "self", ".", ...
[ 239, 4 ]
[ 270, 18 ]
python
en
['en', 'cy', 'en']
False
test_setstate
(self)
Verify that datetime dtype __setstate__ can handle bad arguments
Verify that datetime dtype __setstate__ can handle bad arguments
def test_setstate(self): "Verify that datetime dtype __setstate__ can handle bad arguments" dt = np.dtype('>M8[us]') assert_raises(ValueError, dt.__setstate__, (4, '>', None, None, None, -1, -1, 0, 1)) assert_(dt.__reduce__()[2] == np.dtype('>M8[us]').__reduce__()[2]) assert_rais...
[ "def", "test_setstate", "(", "self", ")", ":", "dt", "=", "np", ".", "dtype", "(", "'>M8[us]'", ")", "assert_raises", "(", "ValueError", ",", "dt", ".", "__setstate__", ",", "(", "4", ",", "'>'", ",", "None", ",", "None", ",", "None", ",", "-", "1"...
[ 667, 4 ]
[ 673, 74 ]
python
en
['en', 'en', 'en']
True
AveragePrecision.update
(self, preds: torch.Tensor, target: torch.Tensor)
Update state with predictions and targets. Args: preds: Predictions from model target: Ground truth values
Update state with predictions and targets.
def update(self, preds: torch.Tensor, target: torch.Tensor): """ Update state with predictions and targets. Args: preds: Predictions from model target: Ground truth values """ preds, target, num_classes, pos_label = _average_precision_update( ...
[ "def", "update", "(", "self", ",", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ")", ":", "preds", ",", "target", ",", "num_classes", ",", "pos_label", "=", "_average_precision_update", "(", "preds", ",", "target", ",...
[ 96, 4 ]
[ 110, 34 ]
python
en
['en', 'error', 'th']
False
AveragePrecision.compute
(self)
Compute the average precision score Returns: tensor with average precision. If multiclass will return list of such tensors, one for each class
Compute the average precision score
def compute(self) -> Union[torch.Tensor, List[torch.Tensor]]: """ Compute the average precision score Returns: tensor with average precision. If multiclass will return list of such tensors, one for each class """ preds = torch.cat(self.preds, dim=0) ...
[ "def", "compute", "(", "self", ")", "->", "Union", "[", "torch", ".", "Tensor", ",", "List", "[", "torch", ".", "Tensor", "]", "]", ":", "preds", "=", "torch", ".", "cat", "(", "self", ".", "preds", ",", "dim", "=", "0", ")", "target", "=", "to...
[ 112, 4 ]
[ 123, 90 ]
python
en
['en', 'error', 'th']
False
linkcode_resolve
(domain, info)
Determine the URL corresponding to Python object
Determine the URL corresponding to Python object
def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object """ if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for pa...
[ "def", "linkcode_resolve", "(", "domain", ",", "info", ")", ":", "if", "domain", "!=", "'py'", ":", "return", "None", "modname", "=", "info", "[", "'module'", "]", "fullname", "=", "info", "[", "'fullname'", "]", "submod", "=", "sys", ".", "modules", "...
[ 310, 0 ]
[ 364, 43 ]
python
en
['en', 'error', 'th']
False
CustomNotImplementedErrorDataloader.__len__
(self)
raise NotImplementedError
raise NotImplementedError
def __len__(self): """raise NotImplementedError""" raise NotImplementedError
[ "def", "__len__", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 41, 4 ]
[ 43, 33 ]
python
en
['en', 'de', 'en']
False
test_lightning_optimizer
(tmpdir)
Test that optimizer are correctly wrapped by our LightningOptimizer
Test that optimizer are correctly wrapped by our LightningOptimizer
def test_lightning_optimizer(tmpdir): """ Test that optimizer are correctly wrapped by our LightningOptimizer """ class TestModel(BoringModel): def configure_optimizers(self): optimizer = torch.optim.SGD(self.layer.parameters(), lr=0.1) lr_scheduler = torch.optim.lr_sch...
[ "def", "test_lightning_optimizer", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "configure_optimizers", "(", "self", ")", ":", "optimizer", "=", "torch", ".", "optim", ".", "SGD", "(", "self", ".", "layer", ".", "para...
[ 23, 0 ]
[ 47, 66 ]
python
en
['en', 'error', 'th']
False
test_lightning_optimizer_from_user
(tmpdir)
Test that the user can use our LightningOptimizer. Not recommended.
Test that the user can use our LightningOptimizer. Not recommended.
def test_lightning_optimizer_from_user(tmpdir): """ Test that the user can use our LightningOptimizer. Not recommended. """ class TestModel(BoringModel): def configure_optimizers(self): optimizer = torch.optim.Adam(self.layer.parameters(), lr=0.1) optimizer = LightningO...
[ "def", "test_lightning_optimizer_from_user", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "configure_optimizers", "(", "self", ")", ":", "optimizer", "=", "torch", ".", "optim", ".", "Adam", "(", "self", ".", "layer", "...
[ 50, 0 ]
[ 75, 66 ]
python
en
['en', 'error', 'th']
False
test_lightning_optimizer_manual_optimization
(mock_sgd_step, mock_adam_step, tmpdir)
Test that the user can use our LightningOptimizer. Not recommended for now.
Test that the user can use our LightningOptimizer. Not recommended for now.
def test_lightning_optimizer_manual_optimization(mock_sgd_step, mock_adam_step, tmpdir): """ Test that the user can use our LightningOptimizer. Not recommended for now. """ class TestModel(BoringModel): def __init__(self): super().__init__() self.automatic_optimization ...
[ "def", "test_lightning_optimizer_manual_optimization", "(", "mock_sgd_step", ",", "mock_adam_step", ",", "tmpdir", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "__init__", "(", "self", ")", ":", "super", "(", ")", ".", "__init__", "(", ...
[ 80, 0 ]
[ 131, 46 ]
python
en
['en', 'error', 'th']
False
test_lightning_optimizer_manual_optimization_and_accumulated_gradients
(mock_sgd_step, mock_adam_step, tmpdir)
Test that the user can use our LightningOptimizer. Not recommended.
Test that the user can use our LightningOptimizer. Not recommended.
def test_lightning_optimizer_manual_optimization_and_accumulated_gradients(mock_sgd_step, mock_adam_step, tmpdir): """ Test that the user can use our LightningOptimizer. Not recommended. """ class TestModel(BoringModel): def __init__(self): super().__init__() self.autom...
[ "def", "test_lightning_optimizer_manual_optimization_and_accumulated_gradients", "(", "mock_sgd_step", ",", "mock_adam_step", ",", "tmpdir", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "__init__", "(", "self", ")", ":", "super", "(", ")", "....
[ 136, 0 ]
[ 186, 46 ]
python
en
['en', 'error', 'th']
False
test_lightning_optimizer_automatic_optimization
(tmpdir)
Test lightning optimize works with in automatic_optimization
Test lightning optimize works with in automatic_optimization
def test_lightning_optimizer_automatic_optimization(tmpdir): """ Test lightning optimize works with in automatic_optimization """ class TestModel(BoringModel): def training_step(self, batch, batch_idx, optimizer_idx=None): output = self.layer(batch) loss = self.loss(bat...
[ "def", "test_lightning_optimizer_automatic_optimization", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "training_step", "(", "self", ",", "batch", ",", "batch_idx", ",", "optimizer_idx", "=", "None", ")", ":", "output", "="...
[ 239, 0 ]
[ 280, 22 ]
python
en
['en', 'error', 'th']
False
test_lightning_optimizer_automatic_optimization_optimizer_zero_grad
(tmpdir)
Test lightning optimize works with optimizer_zero_grad overrides in automatic_optimization
Test lightning optimize works with optimizer_zero_grad overrides in automatic_optimization
def test_lightning_optimizer_automatic_optimization_optimizer_zero_grad(tmpdir): """ Test lightning optimize works with optimizer_zero_grad overrides in automatic_optimization """ with patch("torch.optim.Adam.zero_grad") as adam_zero_grad, \ patch("torch.optim.SGD.zero_grad") as sgd_zero_gr...
[ "def", "test_lightning_optimizer_automatic_optimization_optimizer_zero_grad", "(", "tmpdir", ")", ":", "with", "patch", "(", "\"torch.optim.Adam.zero_grad\"", ")", "as", "adam_zero_grad", ",", "patch", "(", "\"torch.optim.SGD.zero_grad\"", ")", "as", "sgd_zero_grad", ":", "...
[ 283, 0 ]
[ 328, 45 ]
python
en
['en', 'error', 'th']
False
_binary_clf_curve
( preds: torch.Tensor, target: torch.Tensor, sample_weights: Optional[Sequence] = None, pos_label: int = 1., )
adapted from https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
adapted from https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
def _binary_clf_curve( preds: torch.Tensor, target: torch.Tensor, sample_weights: Optional[Sequence] = None, pos_label: int = 1., ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ adapted from https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py """ ...
[ "def", "_binary_clf_curve", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ",", "sample_weights", ":", "Optional", "[", "Sequence", "]", "=", "None", ",", "pos_label", ":", "int", "=", "1.", ",", ")", "->", "Tupl...
[ 21, 0 ]
[ 61, 42 ]
python
en
['en', 'error', 'th']
False