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
formatargspec
(args, varargs=None, varkw=None, defaults=None, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), join=joinseq)
Format an argument spec from the 4 values returned by getargspec. The first four arguments are (args, varargs, varkw, defaults). The other four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional functi...
Format an argument spec from the 4 values returned by getargspec.
def formatargspec(args, varargs=None, varkw=None, defaults=None, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), join=joinseq): """Format...
[ "def", "formatargspec", "(", "args", ",", "varargs", "=", "None", ",", "varkw", "=", "None", ",", "defaults", "=", "None", ",", "formatarg", "=", "str", ",", "formatvarargs", "=", "lambda", "name", ":", "'*'", "+", "name", ",", "formatvarkw", "=", "lam...
[ 141, 0 ]
[ 167, 39 ]
python
en
['en', 'en', 'en']
True
formatargvalues
(args, varargs, varkw, locals, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), join=joinseq)
Format an argument spec from the 4 values returned by getargvalues. The first four arguments are (args, varargs, varkw, locals). The next four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional functio...
Format an argument spec from the 4 values returned by getargvalues.
def formatargvalues(args, varargs, varkw, locals, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), join=joinseq): """Format an a...
[ "def", "formatargvalues", "(", "args", ",", "varargs", ",", "varkw", ",", "locals", ",", "formatarg", "=", "str", ",", "formatvarargs", "=", "lambda", "name", ":", "'*'", "+", "name", ",", "formatvarkw", "=", "lambda", "name", ":", "'**'", "+", "name", ...
[ 169, 0 ]
[ 192, 39 ]
python
en
['en', 'en', 'en']
True
TestSubclassing.test_subclass_items
(self)
test that getter and setter go via baseclass
test that getter and setter go via baseclass
def test_subclass_items(self): """test that getter and setter go via baseclass""" x = np.arange(5) xcsub = ComplicatedSubArray(x) mxcsub = masked_array(xcsub, mask=[True, False, True, False, False]) # getter should return a ComplicatedSubArray, even for single item # fir...
[ "def", "test_subclass_items", "(", "self", ")", ":", "x", "=", "np", ".", "arange", "(", "5", ")", "xcsub", "=", "ComplicatedSubArray", "(", "x", ")", "mxcsub", "=", "masked_array", "(", "xcsub", ",", "mask", "=", "[", "True", ",", "False", ",", "Tru...
[ 267, 4 ]
[ 302, 37 ]
python
en
['en', 'en', 'en']
True
TestSubclassing.test_subclass_repr
(self)
test that repr uses the name of the subclass and 'array' for np.ndarray
test that repr uses the name of the subclass and 'array' for np.ndarray
def test_subclass_repr(self): """test that repr uses the name of the subclass and 'array' for np.ndarray""" x = np.arange(5) mx = masked_array(x, mask=[True, False, True, False, False]) assert_startswith(repr(mx), 'masked_array') xsub = SubArray(x) mxsub = masked_...
[ "def", "test_subclass_repr", "(", "self", ")", ":", "x", "=", "np", ".", "arange", "(", "5", ")", "mx", "=", "masked_array", "(", "x", ",", "mask", "=", "[", "True", ",", "False", ",", "True", ",", "False", ",", "False", "]", ")", "assert_startswit...
[ 315, 4 ]
[ 324, 74 ]
python
en
['en', 'en', 'en']
True
TestSubclassing.test_subclass_str
(self)
test str with subclass that has overridden str, setitem
test str with subclass that has overridden str, setitem
def test_subclass_str(self): """test str with subclass that has overridden str, setitem""" # first without override x = np.arange(5) xsub = SubArray(x) mxsub = masked_array(xsub, mask=[True, False, True, False, False]) assert_equal(str(mxsub), '[-- 1 -- 3 4]') xc...
[ "def", "test_subclass_str", "(", "self", ")", ":", "# first without override", "x", "=", "np", ".", "arange", "(", "5", ")", "xsub", "=", "SubArray", "(", "x", ")", "mxsub", "=", "masked_array", "(", "xsub", ",", "mask", "=", "[", "True", ",", "False",...
[ 326, 4 ]
[ 338, 69 ]
python
en
['en', 'en', 'en']
True
test_torchscript_input_output
(modelclass)
Test that scripted LightningModule forward works.
Test that scripted LightningModule forward works.
def test_torchscript_input_output(modelclass): """ Test that scripted LightningModule forward works. """ model = modelclass() if isinstance(model, BoringModel): model.example_input_array = torch.randn(5, 32) script = model.to_torchscript() assert isinstance(script, torch.jit.ScriptModule) ...
[ "def", "test_torchscript_input_output", "(", "modelclass", ")", ":", "model", "=", "modelclass", "(", ")", "if", "isinstance", "(", "model", ",", "BoringModel", ")", ":", "model", ".", "example_input_array", "=", "torch", ".", "randn", "(", "5", ",", "32", ...
[ 28, 0 ]
[ 43, 54 ]
python
en
['en', 'da', 'en']
True
test_torchscript_example_input_output_trace
(modelclass)
Test that traced LightningModule forward works with example_input_array
Test that traced LightningModule forward works with example_input_array
def test_torchscript_example_input_output_trace(modelclass): """ Test that traced LightningModule forward works with example_input_array """ model = modelclass() if isinstance(model, BoringModel): model.example_input_array = torch.randn(5, 32) script = model.to_torchscript(method='trace') ...
[ "def", "test_torchscript_example_input_output_trace", "(", "modelclass", ")", ":", "model", "=", "modelclass", "(", ")", "if", "isinstance", "(", "model", ",", "BoringModel", ")", ":", "model", ".", "example_input_array", "=", "torch", ".", "randn", "(", "5", ...
[ 51, 0 ]
[ 66, 54 ]
python
en
['en', 'en', 'en']
True
test_torchscript_input_output_trace
()
Test that traced LightningModule forward works with example_inputs
Test that traced LightningModule forward works with example_inputs
def test_torchscript_input_output_trace(): """ Test that traced LightningModule forward works with example_inputs """ model = BoringModel() example_inputs = torch.randn(1, 32) script = model.to_torchscript(example_inputs=example_inputs, method='trace') assert isinstance(script, torch.jit.ScriptModul...
[ "def", "test_torchscript_input_output_trace", "(", ")", ":", "model", "=", "BoringModel", "(", ")", "example_inputs", "=", "torch", ".", "randn", "(", "1", ",", "32", ")", "script", "=", "model", ".", "to_torchscript", "(", "example_inputs", "=", "example_inpu...
[ 69, 0 ]
[ 81, 54 ]
python
en
['en', 'en', 'en']
True
test_torchscript_device
(device)
Test that scripted module is on the correct device.
Test that scripted module is on the correct device.
def test_torchscript_device(device): """ Test that scripted module is on the correct device. """ model = BoringModel().to(device) model.example_input_array = torch.randn(5, 32) script = model.to_torchscript() assert next(script.parameters()).device == device script_output = script(model.example...
[ "def", "test_torchscript_device", "(", "device", ")", ":", "model", "=", "BoringModel", "(", ")", ".", "to", "(", "device", ")", "model", ".", "example_input_array", "=", "torch", ".", "randn", "(", "5", ",", "32", ")", "script", "=", "model", ".", "to...
[ 86, 0 ]
[ 94, 41 ]
python
en
['en', 'en', 'en']
True
test_torchscript_retain_training_state
()
Test that torchscript export does not alter the training mode of original model.
Test that torchscript export does not alter the training mode of original model.
def test_torchscript_retain_training_state(): """ Test that torchscript export does not alter the training mode of original model. """ model = BoringModel() model.train(True) script = model.to_torchscript() assert model.training assert not script.training model.train(False) _ = model.to_...
[ "def", "test_torchscript_retain_training_state", "(", ")", ":", "model", "=", "BoringModel", "(", ")", "model", ".", "train", "(", "True", ")", "script", "=", "model", ".", "to_torchscript", "(", ")", "assert", "model", ".", "training", "assert", "not", "scr...
[ 97, 0 ]
[ 107, 30 ]
python
en
['en', 'en', 'en']
True
test_torchscript_properties
(tmpdir, modelclass)
Test that scripted LightningModule has unnecessary methods removed.
Test that scripted LightningModule has unnecessary methods removed.
def test_torchscript_properties(tmpdir, modelclass): """ Test that scripted LightningModule has unnecessary methods removed. """ model = modelclass() model.datamodule = MNISTDataModule(tmpdir) script = model.to_torchscript() assert not hasattr(script, "datamodule") assert not hasattr(model, "bat...
[ "def", "test_torchscript_properties", "(", "tmpdir", ",", "modelclass", ")", ":", "model", "=", "modelclass", "(", ")", "model", ".", "datamodule", "=", "MNISTDataModule", "(", "tmpdir", ")", "script", "=", "model", ".", "to_torchscript", "(", ")", "assert", ...
[ 115, 0 ]
[ 123, 63 ]
python
en
['en', 'en', 'en']
True
test_torchscript_save_load
(tmpdir, modelclass)
Test that scripted LightningModule is correctly saved and can be loaded.
Test that scripted LightningModule is correctly saved and can be loaded.
def test_torchscript_save_load(tmpdir, modelclass): """ Test that scripted LightningModule is correctly saved and can be loaded. """ model = modelclass() output_file = str(tmpdir / "model.pt") script = model.to_torchscript(file_path=output_file) loaded_script = torch.jit.load(output_file) assert...
[ "def", "test_torchscript_save_load", "(", "tmpdir", ",", "modelclass", ")", ":", "model", "=", "modelclass", "(", ")", "output_file", "=", "str", "(", "tmpdir", "/", "\"model.pt\"", ")", "script", "=", "model", ".", "to_torchscript", "(", "file_path", "=", "...
[ 135, 0 ]
[ 141, 86 ]
python
en
['en', 'en', 'en']
True
test_torchcript_invalid_method
(tmpdir)
Test that an error is thrown with invalid torchscript method
Test that an error is thrown with invalid torchscript method
def test_torchcript_invalid_method(tmpdir): """Test that an error is thrown with invalid torchscript method""" model = BoringModel() model.train(True) with pytest.raises(ValueError, match="only supports 'script' or 'trace'"): model.to_torchscript(method='temp')
[ "def", "test_torchcript_invalid_method", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "model", ".", "train", "(", "True", ")", "with", "pytest", ".", "raises", "(", "ValueError", ",", "match", "=", "\"only supports 'script' or 'trace'\"", ")",...
[ 144, 0 ]
[ 150, 43 ]
python
en
['en', 'en', 'en']
True
test_torchscript_with_no_input
(tmpdir)
Test that an error is thrown when there is no input tensor
Test that an error is thrown when there is no input tensor
def test_torchscript_with_no_input(tmpdir): """Test that an error is thrown when there is no input tensor""" model = BoringModel() model.example_input_array = None with pytest.raises(ValueError, match='requires either `example_inputs` or `model.example_input_array`'): model.to_torchscript(metho...
[ "def", "test_torchscript_with_no_input", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "model", ".", "example_input_array", "=", "None", "with", "pytest", ".", "raises", "(", "ValueError", ",", "match", "=", "'requires either `example_inputs` or `m...
[ 153, 0 ]
[ 159, 44 ]
python
en
['en', 'en', 'en']
True
upgraded_package
(type_desc)
Determine upgrade package for a type.
Determine upgrade package for a type.
def upgraded_package(type_desc): """Determine upgrade package for a type.""" if type_desc.next_version_package: return type_desc.next_version_package for pattern, repl in TYPE_UPGRADE_REGEXES: s = re.sub(pattern, repl, type_desc.qualified_package) if s != type_desc.qualified_package...
[ "def", "upgraded_package", "(", "type_desc", ")", ":", "if", "type_desc", ".", "next_version_package", ":", "return", "type_desc", ".", "next_version_package", "for", "pattern", ",", "repl", "in", "TYPE_UPGRADE_REGEXES", ":", "s", "=", "re", ".", "sub", "(", "...
[ 46, 0 ]
[ 55, 80 ]
python
en
['en', 'en', 'en']
True
upgraded_type
(type_name, type_desc)
Determine upgraded type name.
Determine upgraded type name.
def upgraded_type(type_name, type_desc): """Determine upgraded type name.""" _upgraded_package = upgraded_package(type_desc) return type_name.replace(type_desc.qualified_package, _upgraded_package)
[ "def", "upgraded_type", "(", "type_name", ",", "type_desc", ")", ":", "_upgraded_package", "=", "upgraded_package", "(", "type_desc", ")", "return", "type_name", ".", "replace", "(", "type_desc", ".", "qualified_package", ",", "_upgraded_package", ")" ]
[ 58, 0 ]
[ 61, 76 ]
python
en
['en', 'sr', 'en']
True
upgraded_path
(proto_path, upgraded_package)
Determine upgraded API .proto path.
Determine upgraded API .proto path.
def upgraded_path(proto_path, upgraded_package): """Determine upgraded API .proto path.""" return '/'.join([upgraded_package.replace('.', '/'), proto_path.split('/')[-1]])
[ "def", "upgraded_path", "(", "proto_path", ",", "upgraded_package", ")", ":", "return", "'/'", ".", "join", "(", "[", "upgraded_package", ".", "replace", "(", "'.'", ",", "'/'", ")", ",", "proto_path", ".", "split", "(", "'/'", ")", "[", "-", "1", "]",...
[ 64, 0 ]
[ 66, 84 ]
python
en
['en', 'sr', 'en']
True
load_types
(path)
Load a tools.type_whisperer.Types proto from the filesystem. Args: path: filesystem path for a file in text proto format. Returns: tools.type_whisperer.Types proto loaded from path.
Load a tools.type_whisperer.Types proto from the filesystem.
def load_types(path): """Load a tools.type_whisperer.Types proto from the filesystem. Args: path: filesystem path for a file in text proto format. Returns: tools.type_whisperer.Types proto loaded from path. """ types = Types() with open(path, 'r') as f: text_format.Merg...
[ "def", "load_types", "(", "path", ")", ":", "types", "=", "Types", "(", ")", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "text_format", ".", "Merge", "(", "f", ".", "read", "(", ")", ",", "types", ")", "return", "types" ]
[ 79, 0 ]
[ 91, 16 ]
python
en
['en', 'en', 'en']
True
next_version_upgrade
(type_name, type_map, next_version_upgrade_memo, visited=None)
Does a given type require upgrade between major version? Performs depth-first search through type dependency graph for any upgraded types that will force type_name to be upgraded. Args: type_name: fully qualified type name. type_map: map from type name to tools.type_whisperer.TypeDescripti...
Does a given type require upgrade between major version?
def next_version_upgrade(type_name, type_map, next_version_upgrade_memo, visited=None): """Does a given type require upgrade between major version? Performs depth-first search through type dependency graph for any upgraded types that will force type_name to be upgraded. Args: type_name: fully ...
[ "def", "next_version_upgrade", "(", "type_name", ",", "type_map", ",", "next_version_upgrade_memo", ",", "visited", "=", "None", ")", ":", "if", "not", "visited", ":", "visited", "=", "set", "(", "[", "]", ")", "# Ignore non-API types.", "if", "not", "type_nam...
[ 94, 0 ]
[ 132, 25 ]
python
en
['en', 'en', 'en']
True
_del_column
(tensor: torch.Tensor, index: int)
Delete the column at index.
Delete the column at index.
def _del_column(tensor: torch.Tensor, index: int): """ Delete the column at index.""" return torch.cat([tensor[:, :index], tensor[:, (index + 1):]], 1)
[ "def", "_del_column", "(", "tensor", ":", "torch", ".", "Tensor", ",", "index", ":", "int", ")", ":", "return", "torch", ".", "cat", "(", "[", "tensor", "[", ":", ",", ":", "index", "]", ",", "tensor", "[", ":", ",", "(", "index", "+", "1", ")"...
[ 20, 0 ]
[ 23, 69 ]
python
en
['en', 'la', 'en']
True
_stat_scores
( preds: torch.Tensor, target: torch.Tensor, reduce: str = "micro", )
Calculate the number of tp, fp, tn, fn. Args: preds: An ``(N, C)`` or ``(N, C, X)`` tensor of predictions (0 or 1) target: An ``(N, C)`` or ``(N, C, X)`` tensor of true labels (0 or 1) reduce: One of ``'micro'``, ``'macro'``, ``'samples'`` Return: ...
Calculate the number of tp, fp, tn, fn.
def _stat_scores( preds: torch.Tensor, target: torch.Tensor, reduce: str = "micro", ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """Calculate the number of tp, fp, tn, fn. Args: preds: An ``(N, C)`` or ``(N, C, X)`` tensor of predictions (0 or 1) t...
[ "def", "_stat_scores", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ",", "reduce", ":", "str", "=", "\"micro\"", ",", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", ",", "torch"...
[ 26, 0 ]
[ 72, 53 ]
python
en
['en', 'en', 'en']
True
stat_scores
( preds: torch.Tensor, target: torch.Tensor, reduce: str = "micro", mdmc_reduce: Optional[str] = None, num_classes: Optional[int] = None, top_k: Optional[int] = None, threshold: float = 0.5, is_multiclass: Optional[bool] = None, ignore_index: Optional[int] = None, )
Computes the number of true positives, false positives, true negatives, false negatives. Related to `Type I and Type II errors <https://en.wikipedia.org/wiki/Type_I_and_type_II_errors>`__ and the `confusion matrix <https://en.wikipedia.org/wiki/Confusion_matrix#Table_of_confusion>`__. The reduction method ...
Computes the number of true positives, false positives, true negatives, false negatives. Related to `Type I and Type II errors <https://en.wikipedia.org/wiki/Type_I_and_type_II_errors>`__ and the `confusion matrix <https://en.wikipedia.org/wiki/Confusion_matrix#Table_of_confusion>`__.
def stat_scores( preds: torch.Tensor, target: torch.Tensor, reduce: str = "micro", mdmc_reduce: Optional[str] = None, num_classes: Optional[int] = None, top_k: Optional[int] = None, threshold: float = 0.5, is_multiclass: Optional[bool] = None, ignore_index: Optional[int] = None, ) ->...
[ "def", "stat_scores", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ",", "reduce", ":", "str", "=", "\"micro\"", ",", "mdmc_reduce", ":", "Optional", "[", "str", "]", "=", "None", ",", "num_classes", ":", "Optio...
[ 138, 0 ]
[ 282, 47 ]
python
en
['en', 'en', 'en']
True
ssim
( preds: torch.Tensor, target: torch.Tensor, kernel_size: Sequence[int] = (11, 11), sigma: Sequence[float] = (1.5, 1.5), reduction: str = "elementwise_mean", data_range: Optional[float] = None, k1: float = 0.01, k2: float = 0.03, )
Computes Structual Similarity Index Measure Args: preds: estimated image target: ground truth image kernel_size: size of the gaussian kernel (default: (11, 11)) sigma: Standard deviation of the gaussian kernel (default: (1.5, 1.5)) reduction: a method to reduce metric s...
Computes Structual Similarity Index Measure
def ssim( preds: torch.Tensor, target: torch.Tensor, kernel_size: Sequence[int] = (11, 11), sigma: Sequence[float] = (1.5, 1.5), reduction: str = "elementwise_mean", data_range: Optional[float] = None, k1: float = 0.01, k2: float = 0.03, ) -> torch.Tensor: """ Computes Structual ...
[ "def", "ssim", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ",", "kernel_size", ":", "Sequence", "[", "int", "]", "=", "(", "11", ",", "11", ")", ",", "sigma", ":", "Sequence", "[", "float", "]", "=", "("...
[ 114, 0 ]
[ 153, 90 ]
python
en
['en', 'error', 'th']
False
test_submodules_device_and_dtype
(dst_device, dst_dtype)
Test that the device and dtype property updates propagate through mixed nesting of regular nn.Modules and the special modules of type DeviceDtypeModuleMixin (e.g. Metric or LightningModule).
Test that the device and dtype property updates propagate through mixed nesting of regular nn.Modules and the special modules of type DeviceDtypeModuleMixin (e.g. Metric or LightningModule).
def test_submodules_device_and_dtype(dst_device, dst_dtype): """ Test that the device and dtype property updates propagate through mixed nesting of regular nn.Modules and the special modules of type DeviceDtypeModuleMixin (e.g. Metric or LightningModule). """ model = TopModule() assert model.de...
[ "def", "test_submodules_device_and_dtype", "(", "dst_device", ",", "dst_dtype", ")", ":", "model", "=", "TopModule", "(", ")", "assert", "model", ".", "device", "==", "torch", ".", "device", "(", "'cpu'", ")", "model", "=", "model", ".", "to", "(", "device...
[ 60, 0 ]
[ 74, 64 ]
python
en
['en', 'error', 'th']
False
mean_squared_log_error
(preds: torch.Tensor, target: torch.Tensor)
Computes mean squared log error Args: preds: estimated labels target: ground truth labels Return: Tensor with RMSLE Example: >>> from pytorch_lightning.metrics.functional import mean_squared_log_error >>> x = torch.tensor([0., 1, 2, 3]) >>> y = torch.t...
Computes mean squared log error
def mean_squared_log_error(preds: torch.Tensor, target: torch.Tensor) -> torch.Tensor: """ Computes mean squared log error Args: preds: estimated labels target: ground truth labels Return: Tensor with RMSLE Example: >>> from pytorch_lightning.metrics.functional imp...
[ "def", "mean_squared_log_error", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "sum_squared_log_error", ",", "n_obs", "=", "_mean_squared_log_error_update", "(", "preds", ",", "ta...
[ 31, 0 ]
[ 50, 72 ]
python
en
['en', 'error', 'th']
False
english_lower
(s)
Apply English case rules to convert ASCII strings to all lower case. This is an internal utility function to replace calls to str.lower() such that we can avoid changing behavior with changing locales. In particular, Turkish has distinct dotted and dotless variants of the Latin letter "I" in both lowe...
Apply English case rules to convert ASCII strings to all lower case.
def english_lower(s): """ Apply English case rules to convert ASCII strings to all lower case. This is an internal utility function to replace calls to str.lower() such that we can avoid changing behavior with changing locales. In particular, Turkish has distinct dotted and dotless variants of the Lati...
[ "def", "english_lower", "(", "s", ")", ":", "lowered", "=", "s", ".", "translate", "(", "LOWER_TABLE", ")", "return", "lowered" ]
[ 15, 0 ]
[ 40, 18 ]
python
en
['en', 'en', 'en']
True
english_upper
(s)
Apply English case rules to convert ASCII strings to all upper case. This is an internal utility function to replace calls to str.upper() such that we can avoid changing behavior with changing locales. In particular, Turkish has distinct dotted and dotless variants of the Latin letter "I" in both lowe...
Apply English case rules to convert ASCII strings to all upper case.
def english_upper(s): """ Apply English case rules to convert ASCII strings to all upper case. This is an internal utility function to replace calls to str.upper() such that we can avoid changing behavior with changing locales. In particular, Turkish has distinct dotted and dotless variants of the Lati...
[ "def", "english_upper", "(", "s", ")", ":", "uppered", "=", "s", ".", "translate", "(", "UPPER_TABLE", ")", "return", "uppered" ]
[ 43, 0 ]
[ 68, 18 ]
python
en
['en', 'en', 'en']
True
english_capitalize
(s)
Apply English case rules to convert the first character of an ASCII string to upper case. This is an internal utility function to replace calls to str.capitalize() such that we can avoid changing behavior with changing locales. Parameters ---------- s : str Returns ------- capita...
Apply English case rules to convert the first character of an ASCII string to upper case.
def english_capitalize(s): """ Apply English case rules to convert the first character of an ASCII string to upper case. This is an internal utility function to replace calls to str.capitalize() such that we can avoid changing behavior with changing locales. Parameters ---------- s : str ...
[ "def", "english_capitalize", "(", "s", ")", ":", "if", "s", ":", "return", "english_upper", "(", "s", "[", "0", "]", ")", "+", "s", "[", "1", ":", "]", "else", ":", "return", "s" ]
[ 71, 0 ]
[ 99, 16 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testLength
(self)
Test length function
Test length function
def testLength(self): "Test length function" print(self.typeStr, "... ", end=' ', file=sys.stderr) length = Vector.__dict__[self.typeStr + "Length"] self.assertEqual(length([5, 12, 0]), 13)
[ "def", "testLength", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "length", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", "\"L...
[ 27, 4 ]
[ 31, 48 ]
python
en
['fr', 'en', 'en']
True
VectorTestCase.testLengthBadList
(self)
Test length function with bad list
Test length function with bad list
def testLengthBadList(self): "Test length function with bad list" print(self.typeStr, "... ", end=' ', file=sys.stderr) length = Vector.__dict__[self.typeStr + "Length"] self.assertRaises(BadListError, length, [5, "twelve", 0])
[ "def", "testLengthBadList", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "length", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+",...
[ 34, 4 ]
[ 38, 65 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testLengthWrongSize
(self)
Test length function with wrong size
Test length function with wrong size
def testLengthWrongSize(self): "Test length function with wrong size" print(self.typeStr, "... ", end=' ', file=sys.stderr) length = Vector.__dict__[self.typeStr + "Length"] self.assertRaises(TypeError, length, [5, 12])
[ "def", "testLengthWrongSize", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "length", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+...
[ 41, 4 ]
[ 45, 53 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testLengthWrongDim
(self)
Test length function with wrong dimensions
Test length function with wrong dimensions
def testLengthWrongDim(self): "Test length function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) length = Vector.__dict__[self.typeStr + "Length"] self.assertRaises(TypeError, length, [[1, 2], [3, 4]])
[ "def", "testLengthWrongDim", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "length", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+"...
[ 48, 4 ]
[ 52, 62 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testLengthNonContainer
(self)
Test length function with non-container
Test length function with non-container
def testLengthNonContainer(self): "Test length function with non-container" print(self.typeStr, "... ", end=' ', file=sys.stderr) length = Vector.__dict__[self.typeStr + "Length"] self.assertRaises(TypeError, length, None)
[ "def", "testLengthNonContainer", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "length", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", ...
[ 55, 4 ]
[ 59, 50 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testProd
(self)
Test prod function
Test prod function
def testProd(self): "Test prod function" print(self.typeStr, "... ", end=' ', file=sys.stderr) prod = Vector.__dict__[self.typeStr + "Prod"] self.assertEqual(prod([1, 2, 3, 4]), 24)
[ "def", "testProd", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "prod", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", "\"Prod\...
[ 62, 4 ]
[ 66, 48 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testProdBadList
(self)
Test prod function with bad list
Test prod function with bad list
def testProdBadList(self): "Test prod function with bad list" print(self.typeStr, "... ", end=' ', file=sys.stderr) prod = Vector.__dict__[self.typeStr + "Prod"] self.assertRaises(BadListError, prod, [[1, "two"], ["e", "pi"]])
[ "def", "testProdBadList", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "prod", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", "...
[ 69, 4 ]
[ 73, 72 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testProdWrongDim
(self)
Test prod function with wrong dimensions
Test prod function with wrong dimensions
def testProdWrongDim(self): "Test prod function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) prod = Vector.__dict__[self.typeStr + "Prod"] self.assertRaises(TypeError, prod, [[1, 2], [8, 9]])
[ "def", "testProdWrongDim", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "prod", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", ...
[ 76, 4 ]
[ 80, 60 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testProdNonContainer
(self)
Test prod function with non-container
Test prod function with non-container
def testProdNonContainer(self): "Test prod function with non-container" print(self.typeStr, "... ", end=' ', file=sys.stderr) prod = Vector.__dict__[self.typeStr + "Prod"] self.assertRaises(TypeError, prod, None)
[ "def", "testProdNonContainer", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "prod", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+"...
[ 83, 4 ]
[ 87, 48 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testSum
(self)
Test sum function
Test sum function
def testSum(self): "Test sum function" print(self.typeStr, "... ", end=' ', file=sys.stderr) sum = Vector.__dict__[self.typeStr + "Sum"] self.assertEqual(sum([5, 6, 7, 8]), 26)
[ "def", "testSum", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "sum", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", "\"Sum\"",...
[ 90, 4 ]
[ 94, 47 ]
python
de
['de', 'la', 'en']
False
VectorTestCase.testSumBadList
(self)
Test sum function with bad list
Test sum function with bad list
def testSumBadList(self): "Test sum function with bad list" print(self.typeStr, "... ", end=' ', file=sys.stderr) sum = Vector.__dict__[self.typeStr + "Sum"] self.assertRaises(BadListError, sum, [3, 4, 5, "pi"])
[ "def", "testSumBadList", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "sum", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", "\"...
[ 97, 4 ]
[ 101, 61 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testSumWrongDim
(self)
Test sum function with wrong dimensions
Test sum function with wrong dimensions
def testSumWrongDim(self): "Test sum function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) sum = Vector.__dict__[self.typeStr + "Sum"] self.assertRaises(TypeError, sum, [[3, 4], [5, 6]])
[ "def", "testSumWrongDim", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "sum", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", "\...
[ 104, 4 ]
[ 108, 59 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testSumNonContainer
(self)
Test sum function with non-container
Test sum function with non-container
def testSumNonContainer(self): "Test sum function with non-container" print(self.typeStr, "... ", end=' ', file=sys.stderr) sum = Vector.__dict__[self.typeStr + "Sum"] self.assertRaises(TypeError, sum, True)
[ "def", "testSumNonContainer", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "sum", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", ...
[ 111, 4 ]
[ 115, 47 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testReverse
(self)
Test reverse function
Test reverse function
def testReverse(self): "Test reverse function" print(self.typeStr, "... ", end=' ', file=sys.stderr) reverse = Vector.__dict__[self.typeStr + "Reverse"] vector = np.array([1, 2, 4], self.typeCode) reverse(vector) self.assertEqual((vector == [4, 2, 1]).all(), True)
[ "def", "testReverse", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "reverse", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", "\...
[ 118, 4 ]
[ 124, 59 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testReverseWrongDim
(self)
Test reverse function with wrong dimensions
Test reverse function with wrong dimensions
def testReverseWrongDim(self): "Test reverse function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) reverse = Vector.__dict__[self.typeStr + "Reverse"] vector = np.array([[1, 2], [3, 4]], self.typeCode) self.assertRaises(TypeError, reverse, vector)
[ "def", "testReverseWrongDim", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "reverse", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "...
[ 127, 4 ]
[ 132, 53 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testReverseWrongSize
(self)
Test reverse function with wrong size
Test reverse function with wrong size
def testReverseWrongSize(self): "Test reverse function with wrong size" print(self.typeStr, "... ", end=' ', file=sys.stderr) reverse = Vector.__dict__[self.typeStr + "Reverse"] vector = np.array([9, 8, 7, 6, 5, 4], self.typeCode) self.assertRaises(TypeError, reverse, vector)
[ "def", "testReverseWrongSize", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "reverse", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", ...
[ 135, 4 ]
[ 140, 53 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testReverseWrongType
(self)
Test reverse function with wrong type
Test reverse function with wrong type
def testReverseWrongType(self): "Test reverse function with wrong type" print(self.typeStr, "... ", end=' ', file=sys.stderr) reverse = Vector.__dict__[self.typeStr + "Reverse"] vector = np.array([1, 2, 4], 'c') self.assertRaises(TypeError, reverse, vector)
[ "def", "testReverseWrongType", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "reverse", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", ...
[ 143, 4 ]
[ 148, 53 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testReverseNonArray
(self)
Test reverse function with non-array
Test reverse function with non-array
def testReverseNonArray(self): "Test reverse function with non-array" print(self.typeStr, "... ", end=' ', file=sys.stderr) reverse = Vector.__dict__[self.typeStr + "Reverse"] self.assertRaises(TypeError, reverse, [2, 4, 6])
[ "def", "testReverseNonArray", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "reverse", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "...
[ 151, 4 ]
[ 155, 56 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testOnes
(self)
Test ones function
Test ones function
def testOnes(self): "Test ones function" print(self.typeStr, "... ", end=' ', file=sys.stderr) ones = Vector.__dict__[self.typeStr + "Ones"] vector = np.zeros(5, self.typeCode) ones(vector) np.testing.assert_array_equal(vector, np.array([1, 1, 1, 1, 1]))
[ "def", "testOnes", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "ones", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", "\"Ones\...
[ 158, 4 ]
[ 164, 72 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testOnesWrongDim
(self)
Test ones function with wrong dimensions
Test ones function with wrong dimensions
def testOnesWrongDim(self): "Test ones function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) ones = Vector.__dict__[self.typeStr + "Ones"] vector = np.zeros((5, 5), self.typeCode) self.assertRaises(TypeError, ones, vector)
[ "def", "testOnesWrongDim", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "ones", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", ...
[ 167, 4 ]
[ 172, 50 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testOnesWrongType
(self)
Test ones function with wrong type
Test ones function with wrong type
def testOnesWrongType(self): "Test ones function with wrong type" print(self.typeStr, "... ", end=' ', file=sys.stderr) ones = Vector.__dict__[self.typeStr + "Ones"] vector = np.zeros((5, 5), 'c') self.assertRaises(TypeError, ones, vector)
[ "def", "testOnesWrongType", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "ones", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", ...
[ 175, 4 ]
[ 180, 50 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testOnesNonArray
(self)
Test ones function with non-array
Test ones function with non-array
def testOnesNonArray(self): "Test ones function with non-array" print(self.typeStr, "... ", end=' ', file=sys.stderr) ones = Vector.__dict__[self.typeStr + "Ones"] self.assertRaises(TypeError, ones, [2, 4, 6, 8])
[ "def", "testOnesNonArray", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "ones", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", ...
[ 183, 4 ]
[ 187, 56 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testZeros
(self)
Test zeros function
Test zeros function
def testZeros(self): "Test zeros function" print(self.typeStr, "... ", end=' ', file=sys.stderr) zeros = Vector.__dict__[self.typeStr + "Zeros"] vector = np.ones(5, self.typeCode) zeros(vector) np.testing.assert_array_equal(vector, np.array([0, 0, 0, 0, 0]))
[ "def", "testZeros", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "zeros", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", "\"Zer...
[ 190, 4 ]
[ 196, 72 ]
python
de
['eu', 'de', 'en']
False
VectorTestCase.testZerosWrongDim
(self)
Test zeros function with wrong dimensions
Test zeros function with wrong dimensions
def testZerosWrongDim(self): "Test zeros function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) zeros = Vector.__dict__[self.typeStr + "Zeros"] vector = np.ones((5, 5), self.typeCode) self.assertRaises(TypeError, zeros, vector)
[ "def", "testZerosWrongDim", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "zeros", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", ...
[ 199, 4 ]
[ 204, 51 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testZerosWrongType
(self)
Test zeros function with wrong type
Test zeros function with wrong type
def testZerosWrongType(self): "Test zeros function with wrong type" print(self.typeStr, "... ", end=' ', file=sys.stderr) zeros = Vector.__dict__[self.typeStr + "Zeros"] vector = np.ones(6, 'c') self.assertRaises(TypeError, zeros, vector)
[ "def", "testZerosWrongType", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "zeros", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+",...
[ 207, 4 ]
[ 212, 51 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testZerosNonArray
(self)
Test zeros function with non-array
Test zeros function with non-array
def testZerosNonArray(self): "Test zeros function with non-array" print(self.typeStr, "... ", end=' ', file=sys.stderr) zeros = Vector.__dict__[self.typeStr + "Zeros"] self.assertRaises(TypeError, zeros, [1, 3, 5, 7, 9])
[ "def", "testZerosNonArray", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "zeros", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", ...
[ 215, 4 ]
[ 219, 60 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testEOSplit
(self)
Test eoSplit function
Test eoSplit function
def testEOSplit(self): "Test eoSplit function" print(self.typeStr, "... ", end=' ', file=sys.stderr) eoSplit = Vector.__dict__[self.typeStr + "EOSplit"] even, odd = eoSplit([1, 2, 3]) self.assertEqual((even == [1, 0, 3]).all(), True) self.assertEqual((odd == [0, 2, 0]).a...
[ "def", "testEOSplit", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "eoSplit", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", "\...
[ 222, 4 ]
[ 228, 57 ]
python
de
['de', 'sr', 'ur']
False
VectorTestCase.testTwos
(self)
Test twos function
Test twos function
def testTwos(self): "Test twos function" print(self.typeStr, "... ", end=' ', file=sys.stderr) twos = Vector.__dict__[self.typeStr + "Twos"] vector = twos(5) self.assertEqual((vector == [2, 2, 2, 2, 2]).all(), True)
[ "def", "testTwos", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "twos", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", "\"Twos\...
[ 231, 4 ]
[ 236, 65 ]
python
en
['es', 'en', 'en']
True
VectorTestCase.testTwosNonInt
(self)
Test twos function with non-integer dimension
Test twos function with non-integer dimension
def testTwosNonInt(self): "Test twos function with non-integer dimension" print(self.typeStr, "... ", end=' ', file=sys.stderr) twos = Vector.__dict__[self.typeStr + "Twos"] self.assertRaises(TypeError, twos, 5.0)
[ "def", "testTwosNonInt", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "twos", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", "\...
[ 239, 4 ]
[ 243, 47 ]
python
en
['cy', 'en', 'en']
True
VectorTestCase.testThrees
(self)
Test threes function
Test threes function
def testThrees(self): "Test threes function" print(self.typeStr, "... ", end=' ', file=sys.stderr) threes = Vector.__dict__[self.typeStr + "Threes"] vector = threes(6) self.assertEqual((vector == [3, 3, 3, 3, 3, 3]).all(), True)
[ "def", "testThrees", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "threes", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", "\"T...
[ 246, 4 ]
[ 251, 68 ]
python
en
['en', 'en', 'en']
True
VectorTestCase.testThreesNonInt
(self)
Test threes function with non-integer dimension
Test threes function with non-integer dimension
def testThreesNonInt(self): "Test threes function with non-integer dimension" print(self.typeStr, "... ", end=' ', file=sys.stderr) threes = Vector.__dict__[self.typeStr + "Threes"] self.assertRaises(TypeError, threes, "threes")
[ "def", "testThreesNonInt", "(", "self", ")", ":", "print", "(", "self", ".", "typeStr", ",", "\"... \"", ",", "end", "=", "' '", ",", "file", "=", "sys", ".", "stderr", ")", "threes", "=", "Vector", ".", "__dict__", "[", "self", ".", "typeStr", "+", ...
[ 254, 4 ]
[ 258, 54 ]
python
en
['en', 'en', 'en']
True
ModelCheckpoint.on_pretrain_routine_start
(self, trainer, pl_module)
When pretrain routine starts we build the ckpt dir on the fly
When pretrain routine starts we build the ckpt dir on the fly
def on_pretrain_routine_start(self, trainer, pl_module): """ When pretrain routine starts we build the ckpt dir on the fly """ self.__resolve_ckpt_dir(trainer) self.save_function = trainer.save_checkpoint
[ "def", "on_pretrain_routine_start", "(", "self", ",", "trainer", ",", "pl_module", ")", ":", "self", ".", "__resolve_ckpt_dir", "(", "trainer", ")", "self", ".", "save_function", "=", "trainer", ".", "save_checkpoint" ]
[ 200, 4 ]
[ 205, 52 ]
python
en
['en', 'error', 'th']
False
ModelCheckpoint.on_validation_end
(self, trainer, pl_module)
checkpoints can be saved at the end of the val loop
checkpoints can be saved at the end of the val loop
def on_validation_end(self, trainer, pl_module): """ checkpoints can be saved at the end of the val loop """ self.save_checkpoint(trainer, pl_module)
[ "def", "on_validation_end", "(", "self", ",", "trainer", ",", "pl_module", ")", ":", "self", ".", "save_checkpoint", "(", "trainer", ",", "pl_module", ")" ]
[ 207, 4 ]
[ 211, 48 ]
python
en
['en', 'error', 'th']
False
ModelCheckpoint.save_checkpoint
(self, trainer, pl_module)
Performs the main logic around saving a checkpoint. This method runs on all ranks, it is the responsibility of `self.save_function` to handle correct behaviour in distributed training, i.e., saving only on rank 0.
Performs the main logic around saving a checkpoint. This method runs on all ranks, it is the responsibility of `self.save_function` to handle correct behaviour in distributed training, i.e., saving only on rank 0.
def save_checkpoint(self, trainer, pl_module): """ Performs the main logic around saving a checkpoint. This method runs on all ranks, it is the responsibility of `self.save_function` to handle correct behaviour in distributed training, i.e., saving only on rank 0. """ epo...
[ "def", "save_checkpoint", "(", "self", ",", "trainer", ",", "pl_module", ")", ":", "epoch", "=", "trainer", ".", "current_epoch", "global_step", "=", "trainer", ".", "global_step", "if", "(", "trainer", ".", "fast_dev_run", "# disable checkpointing with fast_dev_run...
[ 226, 4 ]
[ 261, 74 ]
python
en
['en', 'error', 'th']
False
ModelCheckpoint.format_checkpoint_name
(self, epoch: int, step: int, metrics: Dict[str, Any], ver: Optional[int] = None)
Generate a filename according to the defined template. Example:: >>> tmpdir = os.path.dirname(__file__) >>> ckpt = ModelCheckpoint(dirpath=tmpdir, filename='{epoch}') >>> os.path.basename(ckpt.format_checkpoint_name(0, 1, metrics={})) 'epoch=0.ckpt' ...
Generate a filename according to the defined template.
def format_checkpoint_name(self, epoch: int, step: int, metrics: Dict[str, Any], ver: Optional[int] = None) -> str: """Generate a filename according to the defined template. Example:: >>> tmpdir = os.path.dirname(__file__) >>> ckpt = ModelCheckpoint(dirpath=tmpdir, filename='{e...
[ "def", "format_checkpoint_name", "(", "self", ",", "epoch", ":", "int", ",", "step", ":", "int", ",", "metrics", ":", "Dict", "[", "str", ",", "Any", "]", ",", "ver", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "str", ":", "filename",...
[ 389, 4 ]
[ 417, 83 ]
python
en
['en', 'en', 'en']
True
ModelCheckpoint.__resolve_ckpt_dir
(self, trainer)
Determines model checkpoint save directory at runtime. References attributes from the trainer's logger to determine where to save checkpoints. The base path for saving weights is set in this priority: 1. Checkpoint callback's path (if passed in) 2. The default_root_dir from t...
Determines model checkpoint save directory at runtime. References attributes from the trainer's logger to determine where to save checkpoints. The base path for saving weights is set in this priority:
def __resolve_ckpt_dir(self, trainer): """ Determines model checkpoint save directory at runtime. References attributes from the trainer's logger to determine where to save checkpoints. The base path for saving weights is set in this priority: 1. Checkpoint callback's path (if ...
[ "def", "__resolve_ckpt_dir", "(", "self", ",", "trainer", ")", ":", "# Todo: required argument `pl_module` is not used", "if", "self", ".", "dirpath", "is", "not", "None", ":", "return", "# short circuit", "if", "trainer", ".", "logger", "is", "not", "None", ":", ...
[ 419, 4 ]
[ 458, 58 ]
python
en
['en', 'error', 'th']
False
ModelCheckpoint.to_yaml
(self, filepath: Optional[Union[str, Path]] = None)
Saves the `best_k_models` dict containing the checkpoint paths with the corresponding scores to a YAML file.
Saves the `best_k_models` dict containing the checkpoint paths with the corresponding scores to a YAML file.
def to_yaml(self, filepath: Optional[Union[str, Path]] = None): """ Saves the `best_k_models` dict containing the checkpoint paths with the corresponding scores to a YAML file. """ best_k = {k: v.item() for k, v in self.best_k_models.items()} if filepath is None: ...
[ "def", "to_yaml", "(", "self", ",", "filepath", ":", "Optional", "[", "Union", "[", "str", ",", "Path", "]", "]", "=", "None", ")", ":", "best_k", "=", "{", "k", ":", "v", ".", "item", "(", ")", "for", "k", ",", "v", "in", "self", ".", "best_...
[ 612, 4 ]
[ 621, 33 ]
python
en
['en', 'error', 'th']
False
ModelCheckpoint.file_exists
(self, filepath: Union[str, Path], trainer)
Checks if a file exists on rank 0 and broadcasts the result to all other ranks, preventing the internal state to diverge between ranks.
Checks if a file exists on rank 0 and broadcasts the result to all other ranks, preventing the internal state to diverge between ranks.
def file_exists(self, filepath: Union[str, Path], trainer) -> bool: """ Checks if a file exists on rank 0 and broadcasts the result to all other ranks, preventing the internal state to diverge between ranks. """ exists = self._fs.exists(filepath) exists = trainer.training...
[ "def", "file_exists", "(", "self", ",", "filepath", ":", "Union", "[", "str", ",", "Path", "]", ",", "trainer", ")", "->", "bool", ":", "exists", "=", "self", ".", "_fs", ".", "exists", "(", "filepath", ")", "exists", "=", "trainer", ".", "training_t...
[ 623, 4 ]
[ 630, 21 ]
python
en
['en', 'error', 'th']
False
log_request
(req: 'flask_request', res: str)
Log details of the web request and the results.
Log details of the web request and the results.
def log_request(req: 'flask_request', res: str) -> None: """Log details of the web request and the results.""" # raise Exception("Something awful just happened.") with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """insert into log (phrase, letters, ip, browser_string, r...
[ "def", "log_request", "(", "req", ":", "'flask_request'", ",", "res", ":", "str", ")", "->", "None", ":", "# raise Exception(\"Something awful just happened.\")", "with", "UseDatabase", "(", "app", ".", "config", "[", "'dbconfig'", "]", ")", "as", "cursor", ":",...
[ 30, 0 ]
[ 44, 37 ]
python
en
['en', 'en', 'en']
True
do_search
()
Extract the posted data; perform the search; return results.
Extract the posted data; perform the search; return results.
def do_search() -> 'html': """Extract the posted data; perform the search; return results.""" phrase = request.form['phrase'] letters = request.form['letters'] title = 'Here are your results:' results = str(search4letters(phrase, letters)) try: log_request(request, results) except Ex...
[ "def", "do_search", "(", ")", "->", "'html'", ":", "phrase", "=", "request", ".", "form", "[", "'phrase'", "]", "letters", "=", "request", ".", "form", "[", "'letters'", "]", "title", "=", "'Here are your results:'", "results", "=", "str", "(", "search4let...
[ 48, 0 ]
[ 62, 48 ]
python
en
['en', 'en', 'en']
True
entry_page
()
Display this webapp's HTML form.
Display this webapp's HTML form.
def entry_page() -> 'html': """Display this webapp's HTML form.""" return render_template('entry.html', the_title='Welcome to search4letters on the web!')
[ "def", "entry_page", "(", ")", "->", "'html'", ":", "return", "render_template", "(", "'entry.html'", ",", "the_title", "=", "'Welcome to search4letters on the web!'", ")" ]
[ 67, 0 ]
[ 70, 77 ]
python
en
['en', 'en', 'en']
True
view_the_log
()
Display the contents of the log file as a HTML table.
Display the contents of the log file as a HTML table.
def view_the_log() -> 'html': """Display the contents of the log file as a HTML table.""" try: with UseDatabase(app.config['dbconfig']) as cursor: _SQL = """select phrase, letters, ip, browser_string, results from log""" cursor.execute(_SQL) conten...
[ "def", "view_the_log", "(", ")", "->", "'html'", ":", "try", ":", "with", "UseDatabase", "(", "app", ".", "config", "[", "'dbconfig'", "]", ")", "as", "cursor", ":", "_SQL", "=", "\"\"\"select phrase, letters, ip, browser_string, results\n from log\...
[ 75, 0 ]
[ 95, 18 ]
python
en
['en', 'en', 'en']
True
ExplainedVariance.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 = _explained_variance_update(preds, target) self.y_pred.a...
[ "def", "update", "(", "self", ",", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ")", ":", "preds", ",", "target", "=", "_explained_variance_update", "(", "preds", ",", "target", ")", "self", ".", "y_pred", ".", "app...
[ 106, 4 ]
[ 116, 29 ]
python
en
['en', 'error', 'th']
False
ExplainedVariance.compute
(self)
Computes explained variance over state.
Computes explained variance over state.
def compute(self): """ Computes explained variance over state. """ preds = torch.cat(self.y_pred, dim=0) target = torch.cat(self.y, dim=0) return _explained_variance_compute(preds, target, self.multioutput)
[ "def", "compute", "(", "self", ")", ":", "preds", "=", "torch", ".", "cat", "(", "self", ".", "y_pred", ",", "dim", "=", "0", ")", "target", "=", "torch", ".", "cat", "(", "self", ".", "y", ",", "dim", "=", "0", ")", "return", "_explained_varianc...
[ 118, 4 ]
[ 124, 75 ]
python
en
['en', 'error', 'th']
False
test__validation_step__log
(tmpdir)
Tests that validation_step can log
Tests that validation_step can log
def test__validation_step__log(tmpdir): """ Tests that validation_step can log """ class TestModel(DeterministicModel): def training_step(self, batch, batch_idx): acc = self.step(batch, batch_idx) acc = acc + batch_idx self.log('a', acc, on_step=True, on_epo...
[ "def", "test__validation_step__log", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "DeterministicModel", ")", ":", "def", "training_step", "(", "self", ",", "batch", ",", "batch_idx", ")", ":", "acc", "=", "self", ".", "step", "(", "batch", ",", "bat...
[ 35, 0 ]
[ 92, 50 ]
python
en
['en', 'error', 'th']
False
test__validation_step__step_end__epoch_end__log
(tmpdir)
Tests that validation_step can log
Tests that validation_step can log
def test__validation_step__step_end__epoch_end__log(tmpdir): """ Tests that validation_step can log """ class TestModel(DeterministicModel): def training_step(self, batch, batch_idx): acc = self.step(batch, batch_idx) acc = acc + batch_idx self.log('a', acc)...
[ "def", "test__validation_step__step_end__epoch_end__log", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "DeterministicModel", ")", ":", "def", "training_step", "(", "self", ",", "batch", ",", "batch_idx", ")", ":", "acc", "=", "self", ".", "step", "(", "...
[ 96, 0 ]
[ 172, 50 ]
python
en
['en', 'error', 'th']
False
test_eval_epoch_logging
(tmpdir, batches, log_interval, max_epochs)
Tests that only training_step can be used
Tests that only training_step can be used
def test_eval_epoch_logging(tmpdir, batches, log_interval, max_epochs): """ Tests that only training_step can be used """ class TestModel(BoringModel): def validation_epoch_end(self, outputs): self.log('c', torch.tensor(2), on_epoch=True, prog_bar=True, logger=True) sel...
[ "def", "test_eval_epoch_logging", "(", "tmpdir", ",", "batches", ",", "log_interval", ",", "max_epochs", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "validation_epoch_end", "(", "self", ",", "outputs", ")", ":", "self", ".", "log", "...
[ 177, 0 ]
[ 222, 65 ]
python
en
['en', 'error', 'th']
False
test_eval_float_logging
(tmpdir)
Tests that only training_step can be used
Tests that only training_step can be used
def test_eval_float_logging(tmpdir): """ Tests that only training_step can be used """ class TestModel(BoringModel): def validation_step(self, batch, batch_idx): output = self.layer(batch) loss = self.loss(batch, output) self.log('a', 12.0) retur...
[ "def", "test_eval_float_logging", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "validation_step", "(", "self", ",", "batch", ",", "batch_idx", ")", ":", "output", "=", "self", ".", "layer", "(", "batch", ")", "loss", ...
[ 226, 0 ]
[ 257, 52 ]
python
en
['en', 'error', 'th']
False
test_eval_logging_auto_reduce
(tmpdir)
Tests that only training_step can be used
Tests that only training_step can be used
def test_eval_logging_auto_reduce(tmpdir): """ Tests that only training_step can be used """ seed_everything(1234) class TestModel(BoringModel): def on_pretrain_routine_end(self) -> None: self.seen_vals = [] self.manual_epoch_end_mean = None def on_validati...
[ "def", "test_eval_logging_auto_reduce", "(", "tmpdir", ")", ":", "seed_everything", "(", "1234", ")", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "on_pretrain_routine_end", "(", "self", ")", "->", "None", ":", "self", ".", "seen_vals", "=", "[",...
[ 261, 0 ]
[ 322, 31 ]
python
en
['en', 'error', 'th']
False
test_eval_epoch_only_logging
(tmpdir, batches, log_interval, max_epochs)
Tests that only test_epoch_end can be used to log, and we return them in the results.
Tests that only test_epoch_end can be used to log, and we return them in the results.
def test_eval_epoch_only_logging(tmpdir, batches, log_interval, max_epochs): """ Tests that only test_epoch_end can be used to log, and we return them in the results. """ class TestModel(BoringModel): def test_epoch_end(self, outputs): self.log('c', torch.tensor(2), on_epoch=True, ...
[ "def", "test_eval_epoch_only_logging", "(", "tmpdir", ",", "batches", ",", "log_interval", ",", "max_epochs", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "test_epoch_end", "(", "self", ",", "outputs", ")", ":", "self", ".", "log", "(...
[ 326, 0 ]
[ 355, 48 ]
python
en
['en', 'error', 'th']
False
test_log_works_in_val_callback
(tmpdir)
Tests that log can be called within callback
Tests that log can be called within callback
def test_log_works_in_val_callback(tmpdir): """ Tests that log can be called within callback """ class TestCallback(callbacks.Callback): # helpers count = 1 choices = [False, True] # used to compute expected values callback_funcs_called = collections.defaultdict...
[ "def", "test_log_works_in_val_callback", "(", "tmpdir", ")", ":", "class", "TestCallback", "(", "callbacks", ".", "Callback", ")", ":", "# helpers", "count", "=", "1", "choices", "=", "[", "False", ",", "True", "]", "# used to compute expected values", "callback_f...
[ 435, 0 ]
[ 637, 81 ]
python
en
['en', 'error', 'th']
False
test_log_works_in_test_callback
(tmpdir)
Tests that log can be called within callback
Tests that log can be called within callback
def test_log_works_in_test_callback(tmpdir): """ Tests that log can be called within callback """ class TestCallback(callbacks.Callback): # helpers count = 1 choices = [False, True] # used to compute expected values callback_funcs_called = collections.defaultdi...
[ "def", "test_log_works_in_test_callback", "(", "tmpdir", ")", ":", "class", "TestCallback", "(", "callbacks", ".", "Callback", ")", ":", "# helpers", "count", "=", "1", "choices", "=", "[", "False", ",", "True", "]", "# used to compute expected values", "callback_...
[ 641, 0 ]
[ 828, 81 ]
python
en
['en', 'error', 'th']
False
test_validation_step_log_with_tensorboard
(mock_log_metrics, tmpdir)
This tests make sure we properly log_metrics to loggers
This tests make sure we properly log_metrics to loggers
def test_validation_step_log_with_tensorboard(mock_log_metrics, tmpdir): """ This tests make sure we properly log_metrics to loggers """ class ExtendedModel(BoringModel): val_losses = [] def training_step(self, batch, batch_idx): output = self.layer(batch) loss...
[ "def", "test_validation_step_log_with_tensorboard", "(", "mock_log_metrics", ",", "tmpdir", ")", ":", "class", "ExtendedModel", "(", "BoringModel", ")", ":", "val_losses", "=", "[", "]", "def", "training_step", "(", "self", ",", "batch", ",", "batch_idx", ")", "...
[ 833, 0 ]
[ 936, 58 ]
python
en
['en', 'error', 'th']
False
_sk_roc_curve
(y_true, probas_pred, num_classes=1)
Adjusted comparison function that can also handles multiclass
Adjusted comparison function that can also handles multiclass
def _sk_roc_curve(y_true, probas_pred, num_classes=1): """ Adjusted comparison function that can also handles multiclass """ if num_classes == 1: return sk_roc_curve(y_true, probas_pred, drop_intermediate=False) fpr, tpr, thresholds = [], [], [] for i in range(num_classes): y_true_temp ...
[ "def", "_sk_roc_curve", "(", "y_true", ",", "probas_pred", ",", "num_classes", "=", "1", ")", ":", "if", "num_classes", "==", "1", ":", "return", "sk_roc_curve", "(", "y_true", ",", "probas_pred", ",", "drop_intermediate", "=", "False", ")", "fpr", ",", "t...
[ 17, 0 ]
[ 30, 31 ]
python
en
['en', 'en', 'en']
True
MNISTDataModule.__init__
( self, data_dir: str = _DATASETS_PATH, val_split: int = 5000, num_workers: int = 16, normalize: bool = False, seed: int = 42, batch_size: int = 32, *args, **kwargs, )
Args: data_dir: where to save/load the data val_split: how many of the training images to use for the validation split num_workers: how many workers to use for loading data normalize: If true applies image normalize
Args: data_dir: where to save/load the data val_split: how many of the training images to use for the validation split num_workers: how many workers to use for loading data normalize: If true applies image normalize
def __init__( self, data_dir: str = _DATASETS_PATH, val_split: int = 5000, num_workers: int = 16, normalize: bool = False, seed: int = 42, batch_size: int = 32, *args, **kwargs, ): """ Args: data_dir: where to save/l...
[ "def", "__init__", "(", "self", ",", "data_dir", ":", "str", "=", "_DATASETS_PATH", ",", "val_split", ":", "int", "=", "5000", ",", "num_workers", ":", "int", "=", "16", ",", "normalize", ":", "bool", "=", "False", ",", "seed", ":", "int", "=", "42",...
[ 39, 4 ]
[ 75, 54 ]
python
en
['en', 'error', 'th']
False
MNISTDataModule.prepare_data
(self)
Saves MNIST files to `data_dir`
Saves MNIST files to `data_dir`
def prepare_data(self): """Saves MNIST files to `data_dir`""" MNIST(self.data_dir, train=True, download=True) MNIST(self.data_dir, train=False, download=True)
[ "def", "prepare_data", "(", "self", ")", ":", "MNIST", "(", "self", ".", "data_dir", ",", "train", "=", "True", ",", "download", "=", "True", ")", "MNIST", "(", "self", ".", "data_dir", ",", "train", "=", "False", ",", "download", "=", "True", ")" ]
[ 81, 4 ]
[ 84, 56 ]
python
en
['en', 'en', 'en']
True
MNISTDataModule.setup
(self, stage: Optional[str] = None)
Split the train and valid dataset
Split the train and valid dataset
def setup(self, stage: Optional[str] = None): """Split the train and valid dataset""" extra = dict(transform=self.default_transforms) if self.default_transforms else {} dataset = MNIST(self.data_dir, train=True, download=False, **extra) train_length = len(dataset) self.dataset_tr...
[ "def", "setup", "(", "self", ",", "stage", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "extra", "=", "dict", "(", "transform", "=", "self", ".", "default_transforms", ")", "if", "self", ".", "default_transforms", "else", "{", "}", "dataset...
[ 86, 4 ]
[ 91, 117 ]
python
en
['en', 'en', 'en']
True
MNISTDataModule.train_dataloader
(self)
MNIST train set removes a subset to use for validation
MNIST train set removes a subset to use for validation
def train_dataloader(self): """MNIST train set removes a subset to use for validation""" loader = DataLoader( self.dataset_train, batch_size=self.batch_size, shuffle=True, num_workers=self.num_workers, drop_last=True, pin_memory=Tru...
[ "def", "train_dataloader", "(", "self", ")", ":", "loader", "=", "DataLoader", "(", "self", ".", "dataset_train", ",", "batch_size", "=", "self", ".", "batch_size", ",", "shuffle", "=", "True", ",", "num_workers", "=", "self", ".", "num_workers", ",", "dro...
[ 93, 4 ]
[ 103, 21 ]
python
en
['en', 'en', 'en']
True
MNISTDataModule.val_dataloader
(self)
MNIST val set uses a subset of the training set for validation
MNIST val set uses a subset of the training set for validation
def val_dataloader(self): """MNIST val set uses a subset of the training set for validation""" loader = DataLoader( self.dataset_val, batch_size=self.batch_size, shuffle=False, num_workers=self.num_workers, drop_last=True, pin_memor...
[ "def", "val_dataloader", "(", "self", ")", ":", "loader", "=", "DataLoader", "(", "self", ".", "dataset_val", ",", "batch_size", "=", "self", ".", "batch_size", ",", "shuffle", "=", "False", ",", "num_workers", "=", "self", ".", "num_workers", ",", "drop_l...
[ 105, 4 ]
[ 115, 21 ]
python
en
['en', 'en', 'en']
True
MNISTDataModule.test_dataloader
(self)
MNIST test set uses the test split
MNIST test set uses the test split
def test_dataloader(self): """MNIST test set uses the test split""" extra = dict(transform=self.test_transforms) if self.test_transforms else {} dataset = MNIST(self.data_dir, train=False, download=False, **extra) loader = DataLoader( dataset, batch_size=self.batc...
[ "def", "test_dataloader", "(", "self", ")", ":", "extra", "=", "dict", "(", "transform", "=", "self", ".", "test_transforms", ")", "if", "self", ".", "test_transforms", "else", "{", "}", "dataset", "=", "MNIST", "(", "self", ".", "data_dir", ",", "train"...
[ 117, 4 ]
[ 129, 21 ]
python
en
['en', 'et', 'en']
True
JWTBearerTokenGenerator.generate
(self, grant_type, client, user=None, scope=None, expires_in=None)
Generate a bearer token for OAuth 2.0 authorization token endpoint. :param client: the client that making the request. :param grant_type: current requested grant_type. :param user: current authorized user. :param expires_in: if provided, use this value as expires_in. :param scope...
Generate a bearer token for OAuth 2.0 authorization token endpoint. :param client: the client that making the request. :param grant_type: current requested grant_type. :param user: current authorized user. :param expires_in: if provided, use this value as expires_in. :param scope...
def generate(self, grant_type, client, user=None, scope=None, expires_in=None): """Generate a bearer token for OAuth 2.0 authorization token endpoint. :param client: the client that making the request. :param grant_type: current requested grant_type. :param user: current authorized user....
[ "def", "generate", "(", "self", ",", "grant_type", ",", "client", ",", "user", "=", "None", ",", "scope", "=", "None", ",", "expires_in", "=", "None", ")", ":", "if", "not", "expires_in", ":", "expires_in", "=", "self", ".", "DEFAULT_EXPIRES_IN", "token_...
[ 68, 4 ]
[ 93, 20 ]
python
en
['no', 'en', 'en']
True
check_dir
(module, module_name=None)
Returns a mapping of all objects with the wrong __module__ attribute.
Returns a mapping of all objects with the wrong __module__ attribute.
def check_dir(module, module_name=None): """Returns a mapping of all objects with the wrong __module__ attribute.""" if module_name is None: module_name = module.__name__ results = {} for name in dir(module): item = getattr(module, name) if (hasattr(item, '__module__') and hasatt...
[ "def", "check_dir", "(", "module", ",", "module_name", "=", "None", ")", ":", "if", "module_name", "is", "None", ":", "module_name", "=", "module", ".", "__name__", "results", "=", "{", "}", "for", "name", "in", "dir", "(", "module", ")", ":", "item", ...
[ 11, 0 ]
[ 21, 18 ]
python
en
['en', 'en', 'en']
True
_patches
(*args, prefix: str = "")
Takes a list of module/class paths to patch and an optional prefix The prefix is used to prefix all of the paths The patches are applied in a nested set of context managers. The yields (mocks) are yielded as a tuple.
Takes a list of module/class paths to patch and an optional prefix
def _patches(*args, prefix: str = "") -> ContextManager: """Takes a list of module/class paths to patch and an optional prefix The prefix is used to prefix all of the paths The patches are applied in a nested set of context managers. The yields (mocks) are yielded as a tuple. """ patched = [...
[ "def", "_patches", "(", "*", "args", ",", "prefix", ":", "str", "=", "\"\"", ")", "->", "ContextManager", ":", "patched", "=", "[", "]", "prefix", "=", "f\"{prefix}.\"", "if", "prefix", "else", "\"\"", "for", "arg", "in", "args", ":", "if", "isinstance...
[ 17, 0 ]
[ 35, 27 ]
python
en
['en', 'en', 'en']
True
Accuracy.update
(self, preds: torch.Tensor, target: torch.Tensor)
Update state with predictions and targets. See :ref:`extensions/metrics:input types` for more information on input types. Args: preds: Predictions from model (probabilities, or labels) target: Ground truth labels
Update state with predictions and targets. See :ref:`extensions/metrics:input types` for more information on input types.
def update(self, preds: torch.Tensor, target: torch.Tensor): """ Update state with predictions and targets. See :ref:`extensions/metrics:input types` for more information on input types. Args: preds: Predictions from model (probabilities, or labels) target: Groun...
[ "def", "update", "(", "self", ",", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ")", ":", "correct", ",", "total", "=", "_accuracy_update", "(", "preds", ",", "target", ",", "threshold", "=", "self", ".", "threshold...
[ 127, 4 ]
[ 142, 27 ]
python
en
['en', 'error', 'th']
False
Accuracy.compute
(self)
Computes accuracy based on inputs passed in to ``update`` previously.
Computes accuracy based on inputs passed in to ``update`` previously.
def compute(self) -> torch.Tensor: """ Computes accuracy based on inputs passed in to ``update`` previously. """ return _accuracy_compute(self.correct, self.total)
[ "def", "compute", "(", "self", ")", "->", "torch", ".", "Tensor", ":", "return", "_accuracy_compute", "(", "self", ".", "correct", ",", "self", ".", "total", ")" ]
[ 144, 4 ]
[ 148, 58 ]
python
en
['en', 'error', 'th']
False
update_site_forward
(apps, schema_editor)
Set site domain and name.
Set site domain and name.
def update_site_forward(apps, schema_editor): """Set site domain and name.""" Site = apps.get_model('sites', 'Site') Site.objects.update_or_create( id=settings.SITE_ID, defaults={ 'domain': 'vonprios.co', 'name': 'jingram' } )
[ "def", "update_site_forward", "(", "apps", ",", "schema_editor", ")", ":", "Site", "=", "apps", ".", "get_model", "(", "'sites'", ",", "'Site'", ")", "Site", ".", "objects", ".", "update_or_create", "(", "id", "=", "settings", ".", "SITE_ID", ",", "default...
[ 9, 0 ]
[ 18, 5 ]
python
en
['en', 'en', 'en']
True
update_site_backward
(apps, schema_editor)
Revert site domain and name to default.
Revert site domain and name to default.
def update_site_backward(apps, schema_editor): """Revert site domain and name to default.""" Site = apps.get_model('sites', 'Site') Site.objects.update_or_create( id=settings.SITE_ID, defaults={ 'domain': 'example.com', 'name': 'example.com' } )
[ "def", "update_site_backward", "(", "apps", ",", "schema_editor", ")", ":", "Site", "=", "apps", ".", "get_model", "(", "'sites'", ",", "'Site'", ")", "Site", ".", "objects", ".", "update_or_create", "(", "id", "=", "settings", ".", "SITE_ID", ",", "defaul...
[ 21, 0 ]
[ 30, 5 ]
python
en
['en', 'en', 'en']
True
Vid2Scene.detect
(self, frame)
Detect objects in the frame and write to self.objs
Detect objects in the frame and write to self.objs
def detect(self, frame): """Detect objects in the frame and write to self.objs""" height, width, channels = frame.shape if self.debug: print("debug, detect: frame info", height, width, channels) blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), ...
[ "def", "detect", "(", "self", ",", "frame", ")", ":", "height", ",", "width", ",", "channels", "=", "frame", ".", "shape", "if", "self", ".", "debug", ":", "print", "(", "\"debug, detect: frame info\"", ",", "height", ",", "width", ",", "channels", ")", ...
[ 173, 4 ]
[ 230, 20 ]
python
en
['en', 'en', 'en']
True
auto_fp16
(apply_to=None, out_fp32=False)
Decorator to enable fp16 training automatically. This decorator is useful when you write custom modules and want to support mixed precision training. If inputs arguments are fp32 tensors, they will be converted to fp16 automatically. Arguments other than fp32 tensors are ignored. Args: app...
Decorator to enable fp16 training automatically.
def auto_fp16(apply_to=None, out_fp32=False): """Decorator to enable fp16 training automatically. This decorator is useful when you write custom modules and want to support mixed precision training. If inputs arguments are fp32 tensors, they will be converted to fp16 automatically. Arguments other than...
[ "def", "auto_fp16", "(", "apply_to", "=", "None", ",", "out_fp32", "=", "False", ")", ":", "def", "auto_fp16_wrapper", "(", "old_func", ")", ":", "@", "functools", ".", "wraps", "(", "old_func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", ...
[ 8, 0 ]
[ 84, 28 ]
python
en
['en', 'en', 'en']
True
force_fp32
(apply_to=None, out_fp16=False)
Decorator to convert input arguments to fp32 in force. This decorator is useful when you write custom modules and want to support mixed precision training. If there are some inputs that must be processed in fp32 mode, then this decorator can handle it. If inputs arguments are fp16 tensors, they will be...
Decorator to convert input arguments to fp32 in force.
def force_fp32(apply_to=None, out_fp16=False): """Decorator to convert input arguments to fp32 in force. This decorator is useful when you write custom modules and want to support mixed precision training. If there are some inputs that must be processed in fp32 mode, then this decorator can handle it. ...
[ "def", "force_fp32", "(", "apply_to", "=", "None", ",", "out_fp16", "=", "False", ")", ":", "def", "force_fp32_wrapper", "(", "old_func", ")", ":", "@", "functools", ".", "wraps", "(", "old_func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*"...
[ 87, 0 ]
[ 163, 29 ]
python
en
['en', 'en', 'en']
True
ModuleTester.assert_array_compare
(self, comparison, x, y, err_msg='', header='', fill_value=True)
Assert that a comparison of two masked arrays is satisfied elementwise.
Assert that a comparison of two masked arrays is satisfied elementwise.
def assert_array_compare(self, comparison, x, y, err_msg='', header='', fill_value=True): """ Assert that a comparison of two masked arrays is satisfied elementwise. """ xf = self.filled(x) yf = self.filled(y) m = self.mask_or(self.getmask(x), se...
[ "def", "assert_array_compare", "(", "self", ",", "comparison", ",", "x", ",", "y", ",", "err_msg", "=", "''", ",", "header", "=", "''", ",", "fill_value", "=", "True", ")", ":", "xf", "=", "self", ".", "filled", "(", "x", ")", "yf", "=", "self", ...
[ 52, 4 ]
[ 106, 33 ]
python
en
['en', 'error', 'th']
False
ModuleTester.assert_array_equal
(self, x, y, err_msg='')
Checks the elementwise equality of two masked arrays.
Checks the elementwise equality of two masked arrays.
def assert_array_equal(self, x, y, err_msg=''): """ Checks the elementwise equality of two masked arrays. """ self.assert_array_compare(self.equal, x, y, err_msg=err_msg, header='Arrays are not equal')
[ "def", "assert_array_equal", "(", "self", ",", "x", ",", "y", ",", "err_msg", "=", "''", ")", ":", "self", ".", "assert_array_compare", "(", "self", ".", "equal", ",", "x", ",", "y", ",", "err_msg", "=", "err_msg", ",", "header", "=", "'Arrays are not ...
[ 108, 4 ]
[ 114, 64 ]
python
en
['en', 'error', 'th']
False