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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
TensorTestCase.testFloorNonArray | (self) | Test floor function with non-array | Test floor function with non-array | def testFloorNonArray(self):
"Test floor function with non-array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
floor = Tensor.__dict__[self.typeStr + "Floor"]
self.assertRaises(TypeError, floor, object) | [
"def",
"testFloorNonArray",
"(",
"self",
")",
":",
"print",
"(",
"self",
".",
"typeStr",
",",
"\"... \"",
",",
"end",
"=",
"' '",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"floor",
"=",
"Tensor",
".",
"__dict__",
"[",
"self",
".",
"typeStr",
"+",
... | [
216,
4
] | [
220,
51
] | python | en | ['en', 'en', 'en'] | True |
TensorTestCase.testCeil | (self) | Test ceil function | Test ceil function | def testCeil(self):
"Test ceil function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ceil = Tensor.__dict__[self.typeStr + "Ceil"]
tensor = np.array([[[9, 8], [7, 6]],
[[5, 4], [3, 2]]], self.typeCode)
ceil(tensor, 5)
np.testing.assert_... | [
"def",
"testCeil",
"(",
"self",
")",
":",
"print",
"(",
"self",
".",
"typeStr",
",",
"\"... \"",
",",
"end",
"=",
"' '",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"ceil",
"=",
"Tensor",
".",
"__dict__",
"[",
"self",
".",
"typeStr",
"+",
"\"Ceil\... | [
223,
4
] | [
231,
73
] | python | en | ['nb', 'fr', 'en'] | False |
TensorTestCase.testCeilWrongType | (self) | Test ceil function with wrong type | Test ceil function with wrong type | def testCeilWrongType(self):
"Test ceil function with wrong type"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ceil = Tensor.__dict__[self.typeStr + "Ceil"]
tensor = np.array([[[9, 8], [7, 6]],
[[5, 4], [3, 2]]], 'c')
self.assertRaises(TypeError... | [
"def",
"testCeilWrongType",
"(",
"self",
")",
":",
"print",
"(",
"self",
".",
"typeStr",
",",
"\"... \"",
",",
"end",
"=",
"' '",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"ceil",
"=",
"Tensor",
".",
"__dict__",
"[",
"self",
".",
"typeStr",
"+",
... | [
234,
4
] | [
240,
50
] | python | en | ['en', 'en', 'en'] | True |
TensorTestCase.testCeilWrongDim | (self) | Test ceil function with wrong dimensions | Test ceil function with wrong dimensions | def testCeilWrongDim(self):
"Test ceil function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ceil = Tensor.__dict__[self.typeStr + "Ceil"]
tensor = np.array([[9, 8], [7, 6], [5, 4], [3, 2]], self.typeCode)
self.assertRaises(TypeError, ceil, tensor) | [
"def",
"testCeilWrongDim",
"(",
"self",
")",
":",
"print",
"(",
"self",
".",
"typeStr",
",",
"\"... \"",
",",
"end",
"=",
"' '",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"ceil",
"=",
"Tensor",
".",
"__dict__",
"[",
"self",
".",
"typeStr",
"+",
... | [
243,
4
] | [
248,
50
] | python | en | ['en', 'en', 'en'] | True |
TensorTestCase.testCeilNonArray | (self) | Test ceil function with non-array | Test ceil function with non-array | def testCeilNonArray(self):
"Test ceil function with non-array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ceil = Tensor.__dict__[self.typeStr + "Ceil"]
tensor = [[[9, 8], [7, 6]],
[[5, 4], [3, 2]]]
self.assertRaises(TypeError, ceil, tensor) | [
"def",
"testCeilNonArray",
"(",
"self",
")",
":",
"print",
"(",
"self",
".",
"typeStr",
",",
"\"... \"",
",",
"end",
"=",
"' '",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"ceil",
"=",
"Tensor",
".",
"__dict__",
"[",
"self",
".",
"typeStr",
"+",
... | [
251,
4
] | [
257,
50
] | python | en | ['en', 'en', 'en'] | True |
TensorTestCase.testLUSplit | (self) | Test luSplit function | Test luSplit function | def testLUSplit(self):
"Test luSplit function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
luSplit = Tensor.__dict__[self.typeStr + "LUSplit"]
lower, upper = luSplit([[[1, 1], [1, 1]],
[[1, 1], [1, 1]]])
self.assertEqual((lower == [[[1, 1... | [
"def",
"testLUSplit",
"(",
"self",
")",
":",
"print",
"(",
"self",
".",
"typeStr",
",",
"\"... \"",
",",
"end",
"=",
"' '",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"luSplit",
"=",
"Tensor",
".",
"__dict__",
"[",
"self",
".",
"typeStr",
"+",
"\... | [
260,
4
] | [
269,
68
] | python | en | ['en', 'no', 'en'] | True |
mintypecode | (typechars, typeset='GDFgdf', default='d') |
Return the character for the minimum-size type to which given types can
be safely cast.
The returned type character must represent the smallest size dtype such
that an array of the returned type can handle the data from an array of
all types in `typechars` (or if `typechars` is an array, then its
... |
Return the character for the minimum-size type to which given types can
be safely cast. | def mintypecode(typechars, typeset='GDFgdf', default='d'):
"""
Return the character for the minimum-size type to which given types can
be safely cast.
The returned type character must represent the smallest size dtype such
that an array of the returned type can handle the data from an array of
... | [
"def",
"mintypecode",
"(",
"typechars",
",",
"typeset",
"=",
"'GDFgdf'",
",",
"default",
"=",
"'d'",
")",
":",
"typecodes",
"=",
"[",
"(",
"isinstance",
"(",
"t",
",",
"str",
")",
"and",
"t",
")",
"or",
"asarray",
"(",
"t",
")",
".",
"dtype",
".",
... | [
27,
0
] | [
79,
18
] | python | en | ['en', 'error', 'th'] | False |
asfarray | (a, dtype=_nx.float_) |
Return an array converted to a float type.
Parameters
----------
a : array_like
The input array.
dtype : str or dtype object, optional
Float type code to coerce input array `a`. If `dtype` is one of the
'int' dtypes, it is replaced with float64.
Returns
-------
... |
Return an array converted to a float type. | def asfarray(a, dtype=_nx.float_):
"""
Return an array converted to a float type.
Parameters
----------
a : array_like
The input array.
dtype : str or dtype object, optional
Float type code to coerce input array `a`. If `dtype` is one of the
'int' dtypes, it is replaced... | [
"def",
"asfarray",
"(",
"a",
",",
"dtype",
"=",
"_nx",
".",
"float_",
")",
":",
"if",
"not",
"_nx",
".",
"issubdtype",
"(",
"dtype",
",",
"_nx",
".",
"inexact",
")",
":",
"dtype",
"=",
"_nx",
".",
"float_",
"return",
"asarray",
"(",
"a",
",",
"dt... | [
87,
0
] | [
116,
34
] | python | en | ['en', 'error', 'th'] | False |
real | (val) |
Return the real part of the complex argument.
Parameters
----------
val : array_like
Input array.
Returns
-------
out : ndarray or scalar
The real component of the complex argument. If `val` is real, the type
of `val` is used for the output. If `val` has complex e... |
Return the real part of the complex argument. | def real(val):
"""
Return the real part of the complex argument.
Parameters
----------
val : array_like
Input array.
Returns
-------
out : ndarray or scalar
The real component of the complex argument. If `val` is real, the type
of `val` is used for the output. ... | [
"def",
"real",
"(",
"val",
")",
":",
"try",
":",
"return",
"val",
".",
"real",
"except",
"AttributeError",
":",
"return",
"asanyarray",
"(",
"val",
")",
".",
"real"
] | [
124,
0
] | [
162,
35
] | python | en | ['en', 'error', 'th'] | False |
imag | (val) |
Return the imaginary part of the complex argument.
Parameters
----------
val : array_like
Input array.
Returns
-------
out : ndarray or scalar
The imaginary component of the complex argument. If `val` is real,
the type of `val` is used for the output. If `val` has... |
Return the imaginary part of the complex argument. | def imag(val):
"""
Return the imaginary part of the complex argument.
Parameters
----------
val : array_like
Input array.
Returns
-------
out : ndarray or scalar
The imaginary component of the complex argument. If `val` is real,
the type of `val` is used for the... | [
"def",
"imag",
"(",
"val",
")",
":",
"try",
":",
"return",
"val",
".",
"imag",
"except",
"AttributeError",
":",
"return",
"asanyarray",
"(",
"val",
")",
".",
"imag"
] | [
170,
0
] | [
205,
35
] | python | en | ['en', 'error', 'th'] | False |
iscomplex | (x) |
Returns a bool array, where True if input element is complex.
What is tested is whether the input has a non-zero imaginary part, not if
the input type is complex.
Parameters
----------
x : array_like
Input array.
Returns
-------
out : ndarray of bools
Output array... |
Returns a bool array, where True if input element is complex. | def iscomplex(x):
"""
Returns a bool array, where True if input element is complex.
What is tested is whether the input has a non-zero imaginary part, not if
the input type is complex.
Parameters
----------
x : array_like
Input array.
Returns
-------
out : ndarray of b... | [
"def",
"iscomplex",
"(",
"x",
")",
":",
"ax",
"=",
"asanyarray",
"(",
"x",
")",
"if",
"issubclass",
"(",
"ax",
".",
"dtype",
".",
"type",
",",
"_nx",
".",
"complexfloating",
")",
":",
"return",
"ax",
".",
"imag",
"!=",
"0",
"res",
"=",
"zeros",
"... | [
213,
0
] | [
246,
18
] | python | en | ['en', 'error', 'th'] | False |
isreal | (x) |
Returns a bool array, where True if input element is real.
If element has complex type with zero complex part, the return value
for that element is True.
Parameters
----------
x : array_like
Input array.
Returns
-------
out : ndarray, bool
Boolean array of same sh... |
Returns a bool array, where True if input element is real. | def isreal(x):
"""
Returns a bool array, where True if input element is real.
If element has complex type with zero complex part, the return value
for that element is True.
Parameters
----------
x : array_like
Input array.
Returns
-------
out : ndarray, bool
Bo... | [
"def",
"isreal",
"(",
"x",
")",
":",
"return",
"imag",
"(",
"x",
")",
"==",
"0"
] | [
250,
0
] | [
278,
23
] | python | en | ['en', 'error', 'th'] | False |
iscomplexobj | (x) |
Check for a complex type or an array of complex numbers.
The type of the input is checked, not the value. Even if the input
has an imaginary part equal to zero, `iscomplexobj` evaluates to True.
Parameters
----------
x : any
The input can be of any type and shape.
Returns
---... |
Check for a complex type or an array of complex numbers. | def iscomplexobj(x):
"""
Check for a complex type or an array of complex numbers.
The type of the input is checked, not the value. Even if the input
has an imaginary part equal to zero, `iscomplexobj` evaluates to True.
Parameters
----------
x : any
The input can be of any type and... | [
"def",
"iscomplexobj",
"(",
"x",
")",
":",
"try",
":",
"dtype",
"=",
"x",
".",
"dtype",
"type_",
"=",
"dtype",
".",
"type",
"except",
"AttributeError",
":",
"type_",
"=",
"asarray",
"(",
"x",
")",
".",
"dtype",
".",
"type",
"return",
"issubclass",
"(... | [
282,
0
] | [
319,
49
] | python | en | ['en', 'error', 'th'] | False |
isrealobj | (x) |
Return True if x is a not complex type or an array of complex numbers.
The type of the input is checked, not the value. So even if the input
has an imaginary part equal to zero, `isrealobj` evaluates to False
if the data type is complex.
Parameters
----------
x : any
The input can... |
Return True if x is a not complex type or an array of complex numbers. | def isrealobj(x):
"""
Return True if x is a not complex type or an array of complex numbers.
The type of the input is checked, not the value. So even if the input
has an imaginary part equal to zero, `isrealobj` evaluates to False
if the data type is complex.
Parameters
----------
x : ... | [
"def",
"isrealobj",
"(",
"x",
")",
":",
"return",
"not",
"iscomplexobj",
"(",
"x",
")"
] | [
323,
0
] | [
355,
30
] | python | en | ['en', 'error', 'th'] | False |
nan_to_num | (x, copy=True, nan=0.0, posinf=None, neginf=None) |
Replace NaN with zero and infinity with large finite numbers (default
behaviour) or with the numbers defined by the user using the `nan`,
`posinf` and/or `neginf` keywords.
If `x` is inexact, NaN is replaced by zero or by the user defined value in
`nan` keyword, infinity is replaced by the larges... |
Replace NaN with zero and infinity with large finite numbers (default
behaviour) or with the numbers defined by the user using the `nan`,
`posinf` and/or `neginf` keywords. | def nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None):
"""
Replace NaN with zero and infinity with large finite numbers (default
behaviour) or with the numbers defined by the user using the `nan`,
`posinf` and/or `neginf` keywords.
If `x` is inexact, NaN is replaced by zero or by the use... | [
"def",
"nan_to_num",
"(",
"x",
",",
"copy",
"=",
"True",
",",
"nan",
"=",
"0.0",
",",
"posinf",
"=",
"None",
",",
"neginf",
"=",
"None",
")",
":",
"x",
"=",
"_nx",
".",
"array",
"(",
"x",
",",
"subok",
"=",
"True",
",",
"copy",
"=",
"copy",
"... | [
370,
0
] | [
478,
35
] | python | en | ['en', 'error', 'th'] | False |
real_if_close | (a, tol=100) |
If complex input returns a real array if complex parts are close to zero.
"Close to zero" is defined as `tol` * (machine epsilon of the type for
`a`).
Parameters
----------
a : array_like
Input array.
tol : float
Tolerance in machine epsilons for the complex part of the el... |
If complex input returns a real array if complex parts are close to zero. | def real_if_close(a, tol=100):
"""
If complex input returns a real array if complex parts are close to zero.
"Close to zero" is defined as `tol` * (machine epsilon of the type for
`a`).
Parameters
----------
a : array_like
Input array.
tol : float
Tolerance in machine e... | [
"def",
"real_if_close",
"(",
"a",
",",
"tol",
"=",
"100",
")",
":",
"a",
"=",
"asanyarray",
"(",
"a",
")",
"if",
"not",
"issubclass",
"(",
"a",
".",
"dtype",
".",
"type",
",",
"_nx",
".",
"complexfloating",
")",
":",
"return",
"a",
"if",
"tol",
"... | [
487,
0
] | [
539,
12
] | python | en | ['en', 'error', 'th'] | False |
asscalar | (a) |
Convert an array of size 1 to its scalar equivalent.
.. deprecated:: 1.16
Deprecated, use `numpy.ndarray.item()` instead.
Parameters
----------
a : ndarray
Input array of size 1.
Returns
-------
out : scalar
Scalar representation of `a`. The output data type ... |
Convert an array of size 1 to its scalar equivalent. | def asscalar(a):
"""
Convert an array of size 1 to its scalar equivalent.
.. deprecated:: 1.16
Deprecated, use `numpy.ndarray.item()` instead.
Parameters
----------
a : ndarray
Input array of size 1.
Returns
-------
out : scalar
Scalar representation of `a... | [
"def",
"asscalar",
"(",
"a",
")",
":",
"return",
"a",
".",
"item",
"(",
")"
] | [
550,
0
] | [
574,
19
] | python | en | ['en', 'error', 'th'] | False |
typename | (char) |
Return a description for the given data type code.
Parameters
----------
char : str
Data type code.
Returns
-------
out : str
Description of the input data type code.
See Also
--------
dtype, typecodes
Examples
--------
>>> typechars = ['S1', '?',... |
Return a description for the given data type code. | def typename(char):
"""
Return a description for the given data type code.
Parameters
----------
char : str
Data type code.
Returns
-------
out : str
Description of the input data type code.
See Also
--------
dtype, typecodes
Examples
--------
... | [
"def",
"typename",
"(",
"char",
")",
":",
"return",
"_namefromtype",
"[",
"char",
"]"
] | [
603,
0
] | [
652,
30
] | python | en | ['en', 'error', 'th'] | False |
common_type | (*arrays) |
Return a scalar type which is common to the input arrays.
The return type will always be an inexact (i.e. floating point) scalar
type, even if all the arrays are integer arrays. If one of the inputs is
an integer array, the minimum precision type that is returned is a
64-bit floating point dtype.
... |
Return a scalar type which is common to the input arrays. | def common_type(*arrays):
"""
Return a scalar type which is common to the input arrays.
The return type will always be an inexact (i.e. floating point) scalar
type, even if all the arrays are integer arrays. If one of the inputs is
an integer array, the minimum precision type that is returned is a
... | [
"def",
"common_type",
"(",
"*",
"arrays",
")",
":",
"is_complex",
"=",
"False",
"precision",
"=",
"0",
"for",
"a",
"in",
"arrays",
":",
"t",
"=",
"a",
".",
"dtype",
".",
"type",
"if",
"iscomplexobj",
"(",
"a",
")",
":",
"is_complex",
"=",
"True",
"... | [
673,
0
] | [
725,
39
] | python | en | ['en', 'error', 'th'] | False |
GPUStatsMonitor._get_gpu_stats | (self, queries: List[str]) | Run nvidia-smi to get the gpu stats | Run nvidia-smi to get the gpu stats | def _get_gpu_stats(self, queries: List[str]) -> List[List[float]]:
"""Run nvidia-smi to get the gpu stats"""
gpu_query = ','.join(queries)
format = 'csv,nounits,noheader'
result = subprocess.run(
[shutil.which('nvidia-smi'), f'--query-gpu={gpu_query}', f'--format={format}', f... | [
"def",
"_get_gpu_stats",
"(",
"self",
",",
"queries",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"List",
"[",
"float",
"]",
"]",
":",
"gpu_query",
"=",
"','",
".",
"join",
"(",
"queries",
")",
"format",
"=",
"'csv,nounits,noheader'",
"result... | [
154,
4
] | [
174,
20
] | python | en | ['en', 'mt', 'en'] | True |
GPUStatsMonitor._parse_gpu_stats | (gpu_ids: str, stats: List[List[float]], keys: List[Tuple[str, str]]) | Parse the gpu stats into a loggable dict | Parse the gpu stats into a loggable dict | def _parse_gpu_stats(gpu_ids: str, stats: List[List[float]], keys: List[Tuple[str, str]]) -> Dict[str, float]:
"""Parse the gpu stats into a loggable dict"""
logs = {}
for i, gpu_id in enumerate(gpu_ids.split(',')):
for j, (x, unit) in enumerate(keys):
logs[f'gpu_id: ... | [
"def",
"_parse_gpu_stats",
"(",
"gpu_ids",
":",
"str",
",",
"stats",
":",
"List",
"[",
"List",
"[",
"float",
"]",
"]",
",",
"keys",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"float",
"]",
"... | [
177,
4
] | [
183,
19
] | python | en | ['en', 'en', 'en'] | True |
GPUStatsMonitor._get_gpu_stat_keys | (self) | Get the GPU stats keys | Get the GPU stats keys | def _get_gpu_stat_keys(self) -> List[Tuple[str, str]]:
"""Get the GPU stats keys"""
stat_keys = []
if self._log_stats.gpu_utilization:
stat_keys.append(('utilization.gpu', '%'))
if self._log_stats.memory_utilization:
stat_keys.extend([('memory.used', 'MB'), ('me... | [
"def",
"_get_gpu_stat_keys",
"(",
"self",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
":",
"stat_keys",
"=",
"[",
"]",
"if",
"self",
".",
"_log_stats",
".",
"gpu_utilization",
":",
"stat_keys",
".",
"append",
"(",
"(",
"'utilizat... | [
185,
4
] | [
195,
24
] | python | en | ['en', 'mt', 'en'] | True |
GPUStatsMonitor._get_gpu_device_stat_keys | (self) | Get the device stats keys | Get the device stats keys | def _get_gpu_device_stat_keys(self) -> List[Tuple[str, str]]:
"""Get the device stats keys"""
stat_keys = []
if self._log_stats.fan_speed:
stat_keys.append(('fan.speed', '%'))
if self._log_stats.temperature:
stat_keys.extend([('temperature.gpu', '°C'), ('tempera... | [
"def",
"_get_gpu_device_stat_keys",
"(",
"self",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
":",
"stat_keys",
"=",
"[",
"]",
"if",
"self",
".",
"_log_stats",
".",
"fan_speed",
":",
"stat_keys",
".",
"append",
"(",
"(",
"'fan.spe... | [
197,
4
] | [
207,
24
] | python | en | ['en', 'en', 'en'] | True |
DDPShardedPlugin._optim_state_dict | (self, optimizer) |
Retrieves state dict only on rank 0, which contains the entire optimizer state after calling
:meth:`consolidate_state_dict`.
|
Retrieves state dict only on rank 0, which contains the entire optimizer state after calling
:meth:`consolidate_state_dict`.
| def _optim_state_dict(self, optimizer):
"""
Retrieves state dict only on rank 0, which contains the entire optimizer state after calling
:meth:`consolidate_state_dict`.
"""
return optimizer.state_dict() | [
"def",
"_optim_state_dict",
"(",
"self",
",",
"optimizer",
")",
":",
"return",
"optimizer",
".",
"state_dict",
"(",
")"
] | [
49,
4
] | [
54,
37
] | python | en | ['en', 'error', 'th'] | False |
EvalHook.after_train_epoch | (self, runner) | Called after every training epoch to evaluate the results. | Called after every training epoch to evaluate the results. | def after_train_epoch(self, runner):
"""Called after every training epoch to evaluate the results."""
if not self.every_n_epochs(runner, self.interval):
return
current_ckpt_path = osp.join(runner.work_dir,
f'epoch_{runner.epoch + 1}.pth')
... | [
"def",
"after_train_epoch",
"(",
"self",
",",
"runner",
")",
":",
"if",
"not",
"self",
".",
"every_n_epochs",
"(",
"runner",
",",
"self",
".",
"interval",
")",
":",
"return",
"current_ckpt_path",
"=",
"osp",
".",
"join",
"(",
"runner",
".",
"work_dir",
"... | [
83,
4
] | [
108,
48
] | python | en | ['en', 'en', 'en'] | True |
EvalHook.evaluate | (self, runner, results) |
Evaluate the results.
Args:
runner (:obj:`mmcv.Runner`): The underlined training runner.
results (list): Output results.
|
Evaluate the results. | def evaluate(self, runner, results):
"""
Evaluate the results.
Args:
runner (:obj:`mmcv.Runner`): The underlined training runner.
results (list): Output results.
"""
eval_res = self.dataloader.dataset.evaluate(
results, runner.work_dir, logger... | [
"def",
"evaluate",
"(",
"self",
",",
"runner",
",",
"results",
")",
":",
"eval_res",
"=",
"self",
".",
"dataloader",
".",
"dataset",
".",
"evaluate",
"(",
"results",
",",
"runner",
".",
"work_dir",
",",
"logger",
"=",
"runner",
".",
"logger",
",",
"*",... | [
110,
4
] | [
126,
19
] | python | en | ['en', 'error', 'th'] | False |
DistEvalHook.after_train_epoch | (self, runner) | Called after each training epoch to evaluate the model. | Called after each training epoch to evaluate the model. | def after_train_epoch(self, runner):
"""Called after each training epoch to evaluate the model."""
if not self.every_n_epochs(runner, self.interval):
return
current_ckpt_path = osp.join(runner.work_dir,
f'epoch_{runner.epoch + 1}.pth')
js... | [
"def",
"after_train_epoch",
"(",
"self",
",",
"runner",
")",
":",
"if",
"not",
"self",
".",
"every_n_epochs",
"(",
"runner",
",",
"self",
".",
"interval",
")",
":",
"return",
"current_ckpt_path",
"=",
"osp",
".",
"join",
"(",
"runner",
".",
"work_dir",
"... | [
154,
4
] | [
186,
52
] | python | en | ['en', 'en', 'en'] | True |
process_mmdet_results | (mmdet_results, cat_id=0) | Process mmdet results, and return a list of bboxes.
:param mmdet_results:
:param cat_id: category id (default: 0 for human)
:return: a list of detected bounding boxes
| Process mmdet results, and return a list of bboxes. | def process_mmdet_results(mmdet_results, cat_id=0):
"""Process mmdet results, and return a list of bboxes.
:param mmdet_results:
:param cat_id: category id (default: 0 for human)
:return: a list of detected bounding boxes
"""
if isinstance(mmdet_results, tuple):
det_results = mmdet_resu... | [
"def",
"process_mmdet_results",
"(",
"mmdet_results",
",",
"cat_id",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"mmdet_results",
",",
"tuple",
")",
":",
"det_results",
"=",
"mmdet_results",
"[",
"0",
"]",
"else",
":",
"det_results",
"=",
"mmdet_results",
"... | [
9,
0
] | [
20,
30
] | python | en | ['en', 'en', 'en'] | True |
main | () | Visualize the demo images.
Using mmdet to detect the human.
| Visualize the demo images. | def main():
"""Visualize the demo images.
Using mmdet to detect the human.
"""
parser = ArgumentParser()
parser.add_argument('det_config', help='Config file for detection')
parser.add_argument('det_checkpoint', help='Checkpoint file for detection')
parser.add_argument('pose_config', help='C... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'det_config'",
",",
"help",
"=",
"'Config file for detection'",
")",
"parser",
".",
"add_argument",
"(",
"'det_checkpoint'",
",",
"help",
"=",
"'Check... | [
23,
0
] | [
111,
26
] | python | en | ['en', 'en', 'en'] | True |
get_best_models | (
X: np.ndarray,
t: np.ndarray,
models: list = HpModels.select_models(),
cv: int = 10,
train_size: float = 0.8,
scoring: dict = {
"accuracy": "accuracy",
"recall": "recall",
"specificity": make_scorer(recall_score, pos_label=0),
"precision": "precision",
"... | Return the best models generated with random hyperparameters using the arguments as training hyperparameters.
:param X: Characteristic matrix numpy array of the dataset which will be evaluated
:type X: np.ndarray
:param t: Vector labels numpy array of the dataset which will be evaluated
:type t: np.nda... | Return the best models generated with random hyperparameters using the arguments as training hyperparameters. | def get_best_models(
X: np.ndarray,
t: np.ndarray,
models: list = HpModels.select_models(),
cv: int = 10,
train_size: float = 0.8,
scoring: dict = {
"accuracy": "accuracy",
"recall": "recall",
"specificity": make_scorer(recall_score, pos_label=0),
"precision": "pr... | [
"def",
"get_best_models",
"(",
"X",
":",
"np",
".",
"ndarray",
",",
"t",
":",
"np",
".",
"ndarray",
",",
"models",
":",
"list",
"=",
"HpModels",
".",
"select_models",
"(",
")",
",",
"cv",
":",
"int",
"=",
"10",
",",
"train_size",
":",
"float",
"=",... | [
15,
0
] | [
114,
56
] | python | en | ['en', 'en', 'en'] | True |
get_results | (best_models: tuple, best_DNN: tuple) | Get the best models and best neural network and returns a pandas Dataframe with the metric results.
:param best_models: Tuple with the best models
:type best_models: tuple
:param best_DNN: Tuple with the best neural network
:type best_DNN: tuple
:return: A pandas Dataframe with the metric results
... | Get the best models and best neural network and returns a pandas Dataframe with the metric results. | def get_results(best_models: tuple, best_DNN: tuple) -> pd.DataFrame:
"""Get the best models and best neural network and returns a pandas Dataframe with the metric results.
:param best_models: Tuple with the best models
:type best_models: tuple
:param best_DNN: Tuple with the best neural network
:t... | [
"def",
"get_results",
"(",
"best_models",
":",
"tuple",
",",
"best_DNN",
":",
"tuple",
")",
"->",
"pd",
".",
"DataFrame",
":",
"best_models",
"=",
"best_models",
"[",
"0",
"]",
"best_DNN",
"=",
"best_DNN",
"[",
"0",
"]",
"metrics",
"=",
"best_DNN",
"[",
... | [
117,
0
] | [
154,
18
] | python | en | ['en', 'en', 'en'] | True |
analize_performance_DNN | (
best_DNN: tuple,
) | Get the best DNN model and returns the results and the numpy arrays with the test values and predicted values.
:param best_DNN: Tuple with the best neural network
:type best_DNN: tuple
:return: A tuple with the numpy arrays with the test values and predicted values
:rtype: tuple
| Get the best DNN model and returns the results and the numpy arrays with the test values and predicted values. | def analize_performance_DNN(
best_DNN: tuple,
) -> tuple:
"""Get the best DNN model and returns the results and the numpy arrays with the test values and predicted values.
:param best_DNN: Tuple with the best neural network
:type best_DNN: tuple
:return: A tuple with the numpy arrays with the test ... | [
"def",
"analize_performance_DNN",
"(",
"best_DNN",
":",
"tuple",
",",
")",
"->",
"tuple",
":",
"X_test",
",",
"t_test",
"=",
"best_DNN",
"[",
"1",
"]",
"n_classes",
"=",
"len",
"(",
"np",
".",
"unique",
"(",
"t_test",
")",
")",
"t_test_bin",
"=",
"to_c... | [
157,
0
] | [
178,
55
] | python | en | ['en', 'en', 'en'] | True |
analize_performance_models | (
best_models: tuple, X: np.ndarray, t: np.ndarray
) | Get the best models and dataset values and returns the models trained and the numpy arrays with the test values and predicted values.
:param best_models: Tuple with the best models
:type best_models: tuple
:param X: Characteristic matrix numpy array of the dataset which will be evaluated
:type X: np.nd... | Get the best models and dataset values and returns the models trained and the numpy arrays with the test values and predicted values. | def analize_performance_models(
best_models: tuple, X: np.ndarray, t: np.ndarray
) -> tuple:
"""Get the best models and dataset values and returns the models trained and the numpy arrays with the test values and predicted values.
:param best_models: Tuple with the best models
:type best_models: tuple
... | [
"def",
"analize_performance_models",
"(",
"best_models",
":",
"tuple",
",",
"X",
":",
"np",
".",
"ndarray",
",",
"t",
":",
"np",
".",
"ndarray",
")",
"->",
"tuple",
":",
"train_size",
"=",
"best_models",
"[",
"1",
"]",
"best_models",
"=",
"best_models",
... | [
181,
0
] | [
208,
55
] | python | en | ['en', 'en', 'en'] | True |
get_hyperparams | (model: BaseEstimator, tag: str) | Wrapp the get_hyperparameters function in hyperparametersTunning module.
Return a pandas DataFrame with the hyperparameters of the given model.
:param model: Model to get hyperparameters
:type model: BaseEstimator
:param tag: Name of the model to get hyperparameters
:type tag: str
:return: A p... | Wrapp the get_hyperparameters function in hyperparametersTunning module. | def get_hyperparams(model: BaseEstimator, tag: str) -> pd.DataFrame:
"""Wrapp the get_hyperparameters function in hyperparametersTunning module.
Return a pandas DataFrame with the hyperparameters of the given model.
:param model: Model to get hyperparameters
:type model: BaseEstimator
:param tag: ... | [
"def",
"get_hyperparams",
"(",
"model",
":",
"BaseEstimator",
",",
"tag",
":",
"str",
")",
"->",
"pd",
".",
"DataFrame",
":",
"return",
"HpModels",
".",
"get_hyperparameters",
"(",
"model",
",",
"tag",
")"
] | [
211,
0
] | [
223,
51
] | python | en | ['en', 'af', 'en'] | True |
get_hyperparams_DNN | (
model: Sequential,
) | Wrapp the get_hyperparams function in hyperparametersDNN module.
Return the hyperparams of the model passed as an argument.
:param model: A keras.models.Sequential neural network model
:type model: keras.models.Sequential
:return: A tuple with a pandas Dataframe with the hyperparameters of the neural ... | Wrapp the get_hyperparams function in hyperparametersDNN module. | def get_hyperparams_DNN(
model: Sequential,
) -> tuple((pd.DataFrame, pd.DataFrame)):
"""Wrapp the get_hyperparams function in hyperparametersDNN module.
Return the hyperparams of the model passed as an argument.
:param model: A keras.models.Sequential neural network model
:type model: keras.model... | [
"def",
"get_hyperparams_DNN",
"(",
"model",
":",
"Sequential",
",",
")",
"->",
"tuple",
"(",
"(",
"pd",
".",
"DataFrame",
",",
"pd",
".",
"DataFrame",
")",
")",
":",
"return",
"HpDNN",
".",
"get_hyperparams",
"(",
"model",
")"
] | [
226,
0
] | [
238,
39
] | python | en | ['en', 'en', 'en'] | True |
is_square_free | (factors) |
This functions takes a list of prime factors as input.
returns True if the factors are square free.
|
This functions takes a list of prime factors as input.
returns True if the factors are square free.
| def is_square_free(factors):
'''
This functions takes a list of prime factors as input.
returns True if the factors are square free.
'''
for i in factors:
if factors.count(i) > 1:
return False
return True | [
"def",
"is_square_free",
"(",
"factors",
")",
":",
"for",
"i",
"in",
"factors",
":",
"if",
"factors",
".",
"count",
"(",
"i",
")",
">",
"1",
":",
"return",
"False",
"return",
"True"
] | [
0,
0
] | [
8,
15
] | python | en | ['en', 'error', 'th'] | False |
prime_factors | (n) |
Returns prime factors of n as a list.
|
Returns prime factors of n as a list.
| def prime_factors(n):
'''
Returns prime factors of n as a list.
'''
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors | [
"def",
"prime_factors",
"(",
"n",
")",
":",
"i",
"=",
"2",
"factors",
"=",
"[",
"]",
"while",
"i",
"*",
"i",
"<=",
"n",
":",
"if",
"n",
"%",
"i",
":",
"i",
"+=",
"1",
"else",
":",
"n",
"//=",
"i",
"factors",
".",
"append",
"(",
"i",
")",
... | [
11,
0
] | [
25,
18
] | python | en | ['en', 'error', 'th'] | False |
mobius_function | (n) |
Defines Mobius function
|
Defines Mobius function
| def mobius_function(n):
'''
Defines Mobius function
'''
factors = prime_factors(n)
if is_square_free(factors):
if len(factors) % 2 == 0:
return 1
elif len(factors) % 2 != 0:
return -1
else:
return 0 | [
"def",
"mobius_function",
"(",
"n",
")",
":",
"factors",
"=",
"prime_factors",
"(",
"n",
")",
"if",
"is_square_free",
"(",
"factors",
")",
":",
"if",
"len",
"(",
"factors",
")",
"%",
"2",
"==",
"0",
":",
"return",
"1",
"elif",
"len",
"(",
"factors",
... | [
28,
0
] | [
39,
16
] | python | en | ['en', 'error', 'th'] | False |
_format_summary_table | (total_parameters: int, trainable_parameters: int, model_size: float, *cols) |
Takes in a number of arrays, each specifying a column in
the summary table, and combines them all into one big
string defining the summary table that are nicely formatted.
|
Takes in a number of arrays, each specifying a column in
the summary table, and combines them all into one big
string defining the summary table that are nicely formatted.
| def _format_summary_table(total_parameters: int, trainable_parameters: int, model_size: float, *cols) -> str:
"""
Takes in a number of arrays, each specifying a column in
the summary table, and combines them all into one big
string defining the summary table that are nicely formatted.
"""
n_rows... | [
"def",
"_format_summary_table",
"(",
"total_parameters",
":",
"int",
",",
"trainable_parameters",
":",
"int",
",",
"model_size",
":",
"float",
",",
"*",
"cols",
")",
"->",
"str",
":",
"n_rows",
"=",
"len",
"(",
"cols",
"[",
"0",
"]",
"[",
"1",
"]",
")"... | [
301,
0
] | [
340,
18
] | python | en | ['en', 'error', 'th'] | False |
get_memory_profile | (mode: str) | Get a profile of the current memory usage.
Args:
mode: There are two modes:
- 'all' means return memory for all gpus
- 'min_max' means return memory for max and min
Return:
A dictionary in which the keys are device ids as integers and
values are memory usage a... | Get a profile of the current memory usage. | def get_memory_profile(mode: str) -> Union[Dict[str, int], Dict[int, int]]:
""" Get a profile of the current memory usage.
Args:
mode: There are two modes:
- 'all' means return memory for all gpus
- 'min_max' means return memory for max and min
Return:
A dictionary... | [
"def",
"get_memory_profile",
"(",
"mode",
":",
"str",
")",
"->",
"Union",
"[",
"Dict",
"[",
"str",
",",
"int",
"]",
",",
"Dict",
"[",
"int",
",",
"int",
"]",
"]",
":",
"memory_map",
"=",
"get_gpu_memory_map",
"(",
")",
"if",
"mode",
"==",
"\"min_max\... | [
343,
0
] | [
368,
21
] | python | en | ['en', 'en', 'en'] | True |
get_gpu_memory_map | () |
Get the current gpu usage.
Return:
A dictionary in which the keys are device ids as integers and
values are memory usage as integers in MB.
|
Get the current gpu usage. | def get_gpu_memory_map() -> Dict[str, int]:
"""
Get the current gpu usage.
Return:
A dictionary in which the keys are device ids as integers and
values are memory usage as integers in MB.
"""
result = subprocess.run(
[shutil.which("nvidia-smi"), "--query-gpu=memory.used", "-... | [
"def",
"get_gpu_memory_map",
"(",
")",
"->",
"Dict",
"[",
"str",
",",
"int",
"]",
":",
"result",
"=",
"subprocess",
".",
"run",
"(",
"[",
"shutil",
".",
"which",
"(",
"\"nvidia-smi\"",
")",
",",
"\"--query-gpu=memory.used\"",
",",
"\"--format=csv,nounits,nohea... | [
371,
0
] | [
391,
25
] | python | en | ['en', 'error', 'th'] | False |
get_human_readable_count | (number: int) |
Abbreviates an integer number with K, M, B, T for thousands, millions,
billions and trillions, respectively.
Examples:
>>> get_human_readable_count(123)
'123 '
>>> get_human_readable_count(1234) # (one thousand)
'1.2 K'
>>> get_human_readable_count(2e6) # (two m... |
Abbreviates an integer number with K, M, B, T for thousands, millions,
billions and trillions, respectively. | def get_human_readable_count(number: int) -> str:
"""
Abbreviates an integer number with K, M, B, T for thousands, millions,
billions and trillions, respectively.
Examples:
>>> get_human_readable_count(123)
'123 '
>>> get_human_readable_count(1234) # (one thousand)
'1.... | [
"def",
"get_human_readable_count",
"(",
"number",
":",
"int",
")",
"->",
"str",
":",
"assert",
"number",
">=",
"0",
"labels",
"=",
"PARAMETER_NUM_UNITS",
"num_digits",
"=",
"int",
"(",
"np",
".",
"floor",
"(",
"np",
".",
"log10",
"(",
"number",
")",
")",... | [
398,
0
] | [
435,
43
] | python | en | ['en', 'error', 'th'] | False |
LayerSummary._register_hook | (self) |
Registers a hook on the module that computes the input- and output size(s) on the first forward pass.
If the hook is called, it will remove itself from the from the module, meaning that
recursive models will only record their input- and output shapes once.
Return:
A handle ... |
Registers a hook on the module that computes the input- and output size(s) on the first forward pass.
If the hook is called, it will remove itself from the from the module, meaning that
recursive models will only record their input- and output shapes once. | def _register_hook(self) -> RemovableHandle:
"""
Registers a hook on the module that computes the input- and output size(s) on the first forward pass.
If the hook is called, it will remove itself from the from the module, meaning that
recursive models will only record their input- and ou... | [
"def",
"_register_hook",
"(",
"self",
")",
"->",
"RemovableHandle",
":",
"def",
"hook",
"(",
"module",
",",
"inp",
",",
"out",
")",
":",
"if",
"len",
"(",
"inp",
")",
"==",
"1",
":",
"inp",
"=",
"inp",
"[",
"0",
"]",
"self",
".",
"_in_size",
"=",... | [
73,
4
] | [
90,
55
] | python | en | ['en', 'error', 'th'] | False |
LayerSummary.detach_hook | (self) |
Removes the forward hook if it was not already removed in the forward pass.
Will be called after the summary is created.
|
Removes the forward hook if it was not already removed in the forward pass.
Will be called after the summary is created.
| def detach_hook(self):
"""
Removes the forward hook if it was not already removed in the forward pass.
Will be called after the summary is created.
"""
if self._hook_handle is not None:
self._hook_handle.remove() | [
"def",
"detach_hook",
"(",
"self",
")",
":",
"if",
"self",
".",
"_hook_handle",
"is",
"not",
"None",
":",
"self",
".",
"_hook_handle",
".",
"remove",
"(",
")"
] | [
92,
4
] | [
98,
38
] | python | en | ['en', 'error', 'th'] | False |
LayerSummary.layer_type | (self) | Returns the class name of the module. | Returns the class name of the module. | def layer_type(self) -> str:
""" Returns the class name of the module. """
return str(self._module.__class__.__name__) | [
"def",
"layer_type",
"(",
"self",
")",
"->",
"str",
":",
"return",
"str",
"(",
"self",
".",
"_module",
".",
"__class__",
".",
"__name__",
")"
] | [
109,
4
] | [
111,
51
] | python | en | ['en', 'en', 'en'] | True |
LayerSummary.num_parameters | (self) | Returns the number of parameters in this module. | Returns the number of parameters in this module. | def num_parameters(self) -> int:
""" Returns the number of parameters in this module. """
return sum(np.prod(p.shape) for p in self._module.parameters()) | [
"def",
"num_parameters",
"(",
"self",
")",
"->",
"int",
":",
"return",
"sum",
"(",
"np",
".",
"prod",
"(",
"p",
".",
"shape",
")",
"for",
"p",
"in",
"self",
".",
"_module",
".",
"parameters",
"(",
")",
")"
] | [
114,
4
] | [
116,
71
] | python | en | ['en', 'en', 'en'] | True |
ModelSummary._forward_example_input | (self) | Run the example input through each layer to get input- and output sizes. | Run the example input through each layer to get input- and output sizes. | def _forward_example_input(self) -> None:
""" Run the example input through each layer to get input- and output sizes. """
model = self._model
trainer = self._model.trainer
input_ = model.example_input_array
input_ = model._apply_batch_transfer_handler(input_, model.device)
... | [
"def",
"_forward_example_input",
"(",
"self",
")",
"->",
"None",
":",
"model",
"=",
"self",
".",
"_model",
"trainer",
"=",
"self",
".",
"_model",
".",
"trainer",
"input_",
"=",
"model",
".",
"example_input_array",
"input_",
"=",
"model",
".",
"_apply_batch_t... | [
242,
4
] | [
263,
25
] | python | en | ['en', 'en', 'en'] | True |
ModelSummary.__str__ | (self) |
Makes a summary listing with:
Layer Name, Layer Type, Number of Parameters, Input Sizes, Output Sizes, Model Size
|
Makes a summary listing with: | def __str__(self):
"""
Makes a summary listing with:
Layer Name, Layer Type, Number of Parameters, Input Sizes, Output Sizes, Model Size
"""
arrays = [
[" ", list(map(str, range(len(self._layer_summary))))],
["Name", self.layer_names],
["Type"... | [
"def",
"__str__",
"(",
"self",
")",
":",
"arrays",
"=",
"[",
"[",
"\" \"",
",",
"list",
"(",
"map",
"(",
"str",
",",
"range",
"(",
"len",
"(",
"self",
".",
"_layer_summary",
")",
")",
")",
")",
"]",
",",
"[",
"\"Name\"",
",",
"self",
".",
"laye... | [
265,
4
] | [
284,
97
] | python | en | ['en', 'error', 'th'] | False |
to_filename | (classname: str) |
maps mock class name (in C++ codes) to filenames under the Envoy naming convention.
e.g. map "MockAdminStream" to "admin_stream"
Args:
classname: mock class name from source
Returns:
corresponding file name
|
maps mock class name (in C++ codes) to filenames under the Envoy naming convention.
e.g. map "MockAdminStream" to "admin_stream" | def to_filename(classname: str) -> str:
"""
maps mock class name (in C++ codes) to filenames under the Envoy naming convention.
e.g. map "MockAdminStream" to "admin_stream"
Args:
classname: mock class name from source
Returns:
corresponding file name
"""
filename = classnam... | [
"def",
"to_filename",
"(",
"classname",
":",
"str",
")",
"->",
"str",
":",
"filename",
"=",
"classname",
".",
"replace",
"(",
"\"Mock\"",
",",
"\"\"",
",",
"1",
")",
"# Remove only first \"Mock\"",
"ret",
"=",
"\"\"",
"for",
"index",
",",
"val",
"in",
"e... | [
14,
0
] | [
31,
22
] | python | en | ['en', 'error', 'th'] | False |
get_directives | (translation_unit: Type[TranslationUnit]) |
"extracts" all header includes statements and other directives from the target source code file
for instance:
foo.h:
#pragma once
#include "a.h"
#include "b.h"
int foo(){
}
this function should return
'#pragma once\n#include "a.h"\n#include "b.h"'
... |
"extracts" all header includes statements and other directives from the target source code file | def get_directives(translation_unit: Type[TranslationUnit]) -> str:
"""
"extracts" all header includes statements and other directives from the target source code file
for instance:
foo.h:
#pragma once
#include "a.h"
#include "b.h"
int foo(){
}
this func... | [
"def",
"get_directives",
"(",
"translation_unit",
":",
"Type",
"[",
"TranslationUnit",
"]",
")",
"->",
"str",
":",
"cursor",
"=",
"translation_unit",
".",
"cursor",
"for",
"descendant",
"in",
"cursor",
".",
"walk_preorder",
"(",
")",
":",
"if",
"descendant",
... | [
34,
0
] | [
68,
13
] | python | en | ['en', 'error', 'th'] | False |
cursors_in_same_file | (cursor: Cursor) |
get all child cursors which are pointing to the same file as the input cursor
Args:
cursor: cursor of parsing result of target source code by libclang
Returns:
a list of cursor
|
get all child cursors which are pointing to the same file as the input cursor | def cursors_in_same_file(cursor: Cursor) -> List[Cursor]:
"""
get all child cursors which are pointing to the same file as the input cursor
Args:
cursor: cursor of parsing result of target source code by libclang
Returns:
a list of cursor
"""
cursors = []
for descendant in ... | [
"def",
"cursors_in_same_file",
"(",
"cursor",
":",
"Cursor",
")",
"->",
"List",
"[",
"Cursor",
"]",
":",
"cursors",
"=",
"[",
"]",
"for",
"descendant",
"in",
"cursor",
".",
"walk_preorder",
"(",
")",
":",
"# We don't want Cursors from files other than the input fi... | [
71,
0
] | [
92,
18
] | python | en | ['en', 'error', 'th'] | False |
class_definitions | (cursor: Cursor) |
extracts all class definitions in the file pointed by cursor. (typical mocks.h)
Args:
cursor: cursor of parsing result of target source code by libclang
Returns:
a list of cursor, each pointing to a class definition.
|
extracts all class definitions in the file pointed by cursor. (typical mocks.h) | def class_definitions(cursor: Cursor) -> List[Cursor]:
"""
extracts all class definitions in the file pointed by cursor. (typical mocks.h)
Args:
cursor: cursor of parsing result of target source code by libclang
Returns:
a list of cursor, each pointing to a class definition.
"""
... | [
"def",
"class_definitions",
"(",
"cursor",
":",
"Cursor",
")",
"->",
"List",
"[",
"Cursor",
"]",
":",
"cursors",
"=",
"cursors_in_same_file",
"(",
"cursor",
")",
"class_cursors",
"=",
"[",
"]",
"for",
"descendant",
"in",
"cursors",
":",
"# check if descendant ... | [
95,
0
] | [
117,
24
] | python | en | ['en', 'error', 'th'] | False |
class_implementations | (cursor: Cursor) |
extracts all class implementation in the file pointed by cursor. (typical mocks.cc)
Args:
cursor: cursor of parsing result of target source code by libclang
Returns:
a list of cursor, each pointing to a class implementation.
|
extracts all class implementation in the file pointed by cursor. (typical mocks.cc) | def class_implementations(cursor: Cursor) -> List[Cursor]:
"""
extracts all class implementation in the file pointed by cursor. (typical mocks.cc)
Args:
cursor: cursor of parsing result of target source code by libclang
Returns:
a list of cursor, each pointing to a class implementation... | [
"def",
"class_implementations",
"(",
"cursor",
":",
"Cursor",
")",
"->",
"List",
"[",
"Cursor",
"]",
":",
"cursors",
"=",
"cursors_in_same_file",
"(",
"cursor",
")",
"impl_cursors",
"=",
"[",
"]",
"for",
"descendant",
"in",
"cursors",
":",
"if",
"descendant"... | [
120,
0
] | [
140,
23
] | python | en | ['en', 'error', 'th'] | False |
extract_definition | (cursor: Cursor, classnames: List[str]) |
extracts class definition source code pointed by the cursor parameter.
and find dependent mock classes by naming look up.
Args:
cursor: libclang cursor pointing to the target mock class definition.
classnames: all mock class names defined in the definition header that needs to be
... |
extracts class definition source code pointed by the cursor parameter.
and find dependent mock classes by naming look up. | def extract_definition(cursor: Cursor, classnames: List[str]) -> Tuple[str, str, List[str]]:
"""
extracts class definition source code pointed by the cursor parameter.
and find dependent mock classes by naming look up.
Args:
cursor: libclang cursor pointing to the target mock class definition.
... | [
"def",
"extract_definition",
"(",
"cursor",
":",
"Cursor",
",",
"classnames",
":",
"List",
"[",
"str",
"]",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
",",
"List",
"[",
"str",
"]",
"]",
":",
"filename",
"=",
"cursor",
".",
"location",
".",
"file",
... | [
143,
0
] | [
179,
39
] | python | en | ['en', 'error', 'th'] | False |
get_implline | (cursor: Cursor) |
finds the first line of implementation source code for class method pointed by the cursor
parameter.
Args:
cursor: libclang cursor pointing to the target mock class definition.
Returns:
an integer, the line number of the first line of the corresponding method implementation
co... |
finds the first line of implementation source code for class method pointed by the cursor
parameter. | def get_implline(cursor: Cursor) -> int:
"""
finds the first line of implementation source code for class method pointed by the cursor
parameter.
Args:
cursor: libclang cursor pointing to the target mock class definition.
Returns:
an integer, the line number of the first line of th... | [
"def",
"get_implline",
"(",
"cursor",
":",
"Cursor",
")",
"->",
"int",
":",
"return",
"cursor",
".",
"extent",
".",
"start",
".",
"line",
"-",
"1"
] | [
182,
0
] | [
204,
39
] | python | en | ['en', 'error', 'th'] | False |
extract_implementations | (impl_cursors: List[Cursor], source_code: str) |
extracts method function body for each cursor in list impl_cursors from source code
groups those function bodies with class name to help generating the divided {classname}.cc
returns a dict maps class name to the concatenation of all its member methods implementations.
Args:
impl_cursors: list... |
extracts method function body for each cursor in list impl_cursors from source code
groups those function bodies with class name to help generating the divided {classname}.cc
returns a dict maps class name to the concatenation of all its member methods implementations. | def extract_implementations(impl_cursors: List[Cursor], source_code: str) -> Dict[str, str]:
"""
extracts method function body for each cursor in list impl_cursors from source code
groups those function bodies with class name to help generating the divided {classname}.cc
returns a dict maps class name t... | [
"def",
"extract_implementations",
"(",
"impl_cursors",
":",
"List",
"[",
"Cursor",
"]",
",",
"source_code",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"classname_to_impl",
"=",
"dict",
"(",
")",
"for",
"i",
",",
"cursor",
"in",
"e... | [
207,
0
] | [
244,
28
] | python | en | ['en', 'error', 'th'] | False |
get_enclosing_namespace | (defn: Cursor) |
retrieves all enclosing namespaces for the class pointed by defn.
this is necessary to construct the mock class header
e.g.:
defn is pointing MockClass in the follow source code:
namespace Envoy {
namespace Server {
class MockClass2 {...}
namespace Configuration {
class MockClass {... |
retrieves all enclosing namespaces for the class pointed by defn.
this is necessary to construct the mock class header
e.g.:
defn is pointing MockClass in the follow source code: | def get_enclosing_namespace(defn: Cursor) -> Tuple[str, str]:
"""
retrieves all enclosing namespaces for the class pointed by defn.
this is necessary to construct the mock class header
e.g.:
defn is pointing MockClass in the follow source code:
namespace Envoy {
namespace Server {
class... | [
"def",
"get_enclosing_namespace",
"(",
"defn",
":",
"Cursor",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"namespace_prefix",
"=",
"\"\"",
"namespace_suffix",
"=",
"\"\"",
"parent_cursor",
"=",
"defn",
".",
"semantic_parent",
"while",
"parent_cursor",
... | [
247,
0
] | [
284,
45
] | python | en | ['en', 'error', 'th'] | False |
main | (args) |
divides the monolithic mock file into different mock class files.
|
divides the monolithic mock file into different mock class files.
| def main(args):
"""
divides the monolithic mock file into different mock class files.
"""
decl_filename = args["decl"]
impl_filename = args["impl"]
idx = Index.create()
impl_translation_unit = TranslationUnit.from_source(
impl_filename, options=TranslationUnit.PARSE_SKIP_FUNCTION_BOD... | [
"def",
"main",
"(",
"args",
")",
":",
"decl_filename",
"=",
"args",
"[",
"\"decl\"",
"]",
"impl_filename",
"=",
"args",
"[",
"\"impl\"",
"]",
"idx",
"=",
"Index",
".",
"create",
"(",
")",
"impl_translation_unit",
"=",
"TranslationUnit",
".",
"from_source",
... | [
314,
0
] | [
348,
63
] | python | en | ['en', 'error', 'th'] | False |
TestMedian.test_docstring_examples | (self) | test the examples given in the docstring of ma.median | test the examples given in the docstring of ma.median | def test_docstring_examples(self):
"test the examples given in the docstring of ma.median"
x = array(np.arange(8), mask=[0]*4 + [1]*4)
assert_equal(np.ma.median(x), 1.5)
assert_equal(np.ma.median(x).shape, (), "shape mismatch")
assert_(type(np.ma.median(x)) is not MaskedArray)
... | [
"def",
"test_docstring_examples",
"(",
"self",
")",
":",
"x",
"=",
"array",
"(",
"np",
".",
"arange",
"(",
"8",
")",
",",
"mask",
"=",
"[",
"0",
"]",
"*",
"4",
"+",
"[",
"1",
"]",
"*",
"4",
")",
"assert_equal",
"(",
"np",
".",
"ma",
".",
"med... | [
720,
4
] | [
733,
42
] | python | en | ['en', 'en', 'en'] | True |
TensorRunningAccum.reset | (self) | Empty the accumulator. | Empty the accumulator. | def reset(self) -> None:
"""Empty the accumulator."""
self.__init__(self.window_length) | [
"def",
"reset",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"__init__",
"(",
"self",
".",
"window_length",
")"
] | [
55,
4
] | [
57,
41
] | python | en | ['en', 'la', 'en'] | True |
TensorRunningAccum.last | (self) | Get the last added element. | Get the last added element. | def last(self):
"""Get the last added element."""
if self.last_idx is not None:
return self.memory[self.last_idx] | [
"def",
"last",
"(",
"self",
")",
":",
"if",
"self",
".",
"last_idx",
"is",
"not",
"None",
":",
"return",
"self",
".",
"memory",
"[",
"self",
".",
"last_idx",
"]"
] | [
59,
4
] | [
62,
45
] | python | en | ['en', 'en', 'en'] | True |
TensorRunningAccum.append | (self, x) | Add an element to the accumulator. | Add an element to the accumulator. | def append(self, x):
"""Add an element to the accumulator."""
if self.memory is None:
self.memory = torch.zeros(self.window_length, *x.shape)
# ensure same device and type
if self.memory.device != x.device or self.memory.type() != x.type():
x = x.to(self.memory)
... | [
"def",
"append",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"memory",
"is",
"None",
":",
"self",
".",
"memory",
"=",
"torch",
".",
"zeros",
"(",
"self",
".",
"window_length",
",",
"*",
"x",
".",
"shape",
")",
"# ensure same device and type",
... | [
64,
4
] | [
84,
31
] | python | en | ['en', 'en', 'en'] | True |
TensorRunningAccum.mean | (self) | Get mean value from stored elements. | Get mean value from stored elements. | def mean(self):
"""Get mean value from stored elements."""
return self._agg_memory('mean') | [
"def",
"mean",
"(",
"self",
")",
":",
"return",
"self",
".",
"_agg_memory",
"(",
"'mean'",
")"
] | [
86,
4
] | [
88,
39
] | python | en | ['en', 'en', 'en'] | True |
TensorRunningAccum.max | (self) | Get maximal value from stored elements. | Get maximal value from stored elements. | def max(self):
"""Get maximal value from stored elements."""
return self._agg_memory('max') | [
"def",
"max",
"(",
"self",
")",
":",
"return",
"self",
".",
"_agg_memory",
"(",
"'max'",
")"
] | [
90,
4
] | [
92,
38
] | python | en | ['en', 'en', 'en'] | True |
TensorRunningAccum.min | (self) | Get minimal value from stored elements. | Get minimal value from stored elements. | def min(self):
"""Get minimal value from stored elements."""
return self._agg_memory('min') | [
"def",
"min",
"(",
"self",
")",
":",
"return",
"self",
".",
"_agg_memory",
"(",
"'min'",
")"
] | [
94,
4
] | [
96,
38
] | python | en | ['en', 'en', 'en'] | True |
PredictionCollection.to_disk | (self) | Write predictions to file(s).
| Write predictions to file(s).
| def to_disk(self) -> None:
"""Write predictions to file(s).
"""
for filepath, predictions in self.predictions.items():
fs = get_filesystem(filepath)
# normalize local filepaths only
if fs.protocol == "file":
filepath = os.path.realpath(filepath... | [
"def",
"to_disk",
"(",
"self",
")",
"->",
"None",
":",
"for",
"filepath",
",",
"predictions",
"in",
"self",
".",
"predictions",
".",
"items",
"(",
")",
":",
"fs",
"=",
"get_filesystem",
"(",
"filepath",
")",
"# normalize local filepaths only",
"if",
"fs",
... | [
148,
4
] | [
178,
39
] | python | en | ['en', 'en', 'en'] | True |
CycleIterator.__init__ | (self, loader: Any, length: Optional[int] = None) |
Args:
loader: the loader to restart for cyclic (and optionally infinite) sampling
length: the number of batches to sample (with restarted loaders if necessary) before raising StopIteration
if None: infinite
| def __init__(self, loader: Any, length: Optional[int] = None):
"""
Args:
loader: the loader to restart for cyclic (and optionally infinite) sampling
length: the number of batches to sample (with restarted loaders if necessary) before raising StopIteration
if None... | [
"def",
"__init__",
"(",
"self",
",",
"loader",
":",
"Any",
",",
"length",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
":",
"if",
"length",
"is",
"None",
":",
"length",
"=",
"float",
"(",
"'inf'",
")",
"self",
".",
"length",
"=",
"length",
... | [
186,
4
] | [
201,
24
] | python | en | ['en', 'error', 'th'] | False | |
CycleIterator.__iter__ | (self) |
Creates the internal iterator and returns self
Returns:
CycleIterator: self
|
Creates the internal iterator and returns self | def __iter__(self) -> Any:
"""
Creates the internal iterator and returns self
Returns:
CycleIterator: self
"""
self.counter = 0
self._loader_iter = iter(self.loader)
return self | [
"def",
"__iter__",
"(",
"self",
")",
"->",
"Any",
":",
"self",
".",
"counter",
"=",
"0",
"self",
".",
"_loader_iter",
"=",
"iter",
"(",
"self",
".",
"loader",
")",
"return",
"self"
] | [
203,
4
] | [
213,
19
] | python | en | ['en', 'error', 'th'] | False |
CycleIterator.__next__ | (self) |
Fetches the next batch from internal dataloader and restarts
it if necessary
Returns:
Any: the resulting batch
Raises:
StopIteration: if more then :attr:`length` batches have been returned
|
Fetches the next batch from internal dataloader and restarts
it if necessary | def __next__(self) -> Any:
"""
Fetches the next batch from internal dataloader and restarts
it if necessary
Returns:
Any: the resulting batch
Raises:
StopIteration: if more then :attr:`length` batches have been returned
"""
# Note: if se... | [
"def",
"__next__",
"(",
"self",
")",
"->",
"Any",
":",
"# Note: if self.length is `inf`, then the iterator will never stop",
"if",
"self",
".",
"counter",
">=",
"self",
".",
"__len__",
"(",
")",
":",
"raise",
"StopIteration",
"try",
":",
"return",
"next",
"(",
"... | [
215,
4
] | [
239,
29
] | python | en | ['en', 'error', 'th'] | False |
CombinedDataset.__init__ | (self, datasets: Union[Sequence, Mapping], mode: str = 'min_size') |
Args:
datasets: a sequence/mapping datasets. Can be a collections of torch.utils.Dataset,
Iterable or even None.
mode: whether to use the minimum number of batches in all samples or the maximum
number of batches in all samples.
| def __init__(self, datasets: Union[Sequence, Mapping], mode: str = 'min_size'):
"""
Args:
datasets: a sequence/mapping datasets. Can be a collections of torch.utils.Dataset,
Iterable or even None.
mode: whether to use the minimum number of batches in all samples ... | [
"def",
"__init__",
"(",
"self",
",",
"datasets",
":",
"Union",
"[",
"Sequence",
",",
"Mapping",
"]",
",",
"mode",
":",
"str",
"=",
"'min_size'",
")",
":",
"self",
".",
"datasets",
"=",
"datasets",
"if",
"mode",
"not",
"in",
"self",
".",
"COMPUTE_FUNCS"... | [
251,
4
] | [
267,
24
] | python | en | ['en', 'error', 'th'] | False | |
CombinedDataset._calc_num_data | (datasets: Union[Sequence, Mapping], mode: str) |
Compute the length of `CombinedDataset` according to the `mode`.
Args:
datasets: a sequence/mapping datasets. Can be a collections of torch.utils.data.Dataset,
Iterable or even None.
mode: Determine `CombinedDataset`'s length is the maximum or minimum of
... |
Compute the length of `CombinedDataset` according to the `mode`. | def _calc_num_data(datasets: Union[Sequence, Mapping], mode: str) -> Union[int, float]:
"""
Compute the length of `CombinedDataset` according to the `mode`.
Args:
datasets: a sequence/mapping datasets. Can be a collections of torch.utils.data.Dataset,
Iterable or eve... | [
"def",
"_calc_num_data",
"(",
"datasets",
":",
"Union",
"[",
"Sequence",
",",
"Mapping",
"]",
",",
"mode",
":",
"str",
")",
"->",
"Union",
"[",
"int",
",",
"float",
"]",
":",
"if",
"mode",
"not",
"in",
"CombinedDataset",
".",
"COMPUTE_FUNCS",
".",
"key... | [
278,
4
] | [
307,
21
] | python | en | ['en', 'error', 'th'] | False |
CombinedDataset.__len__ | (self) | Return the minimum length of the datasets. | Return the minimum length of the datasets. | def __len__(self) -> int:
"""Return the minimum length of the datasets."""
return self._calc_num_data(self.datasets, self.mode) | [
"def",
"__len__",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_calc_num_data",
"(",
"self",
".",
"datasets",
",",
"self",
".",
"mode",
")"
] | [
309,
4
] | [
311,
60
] | python | en | ['en', 'en', 'en'] | True |
CombinedLoader.__init__ | (self, loaders: Any, mode: str = 'min_size') |
Args:
loaders: the loaders to sample from. Can be all kind of collection
mode: the mode. Supported are 'min_size' which stops if the shortest loader is exhausted and
'max_size_cycle' which stops if the longest loader is exhausted and cycles through the smaller ones.
... | def __init__(self, loaders: Any, mode: str = 'min_size'):
"""
Args:
loaders: the loaders to sample from. Can be all kind of collection
mode: the mode. Supported are 'min_size' which stops if the shortest loader is exhausted and
'max_size_cycle' which stops if the... | [
"def",
"__init__",
"(",
"self",
",",
"loaders",
":",
"Any",
",",
"mode",
":",
"str",
"=",
"'min_size'",
")",
":",
"self",
".",
"loaders",
"=",
"loaders",
"datasets",
"=",
"apply_to_collection",
"(",
"self",
".",
"loaders",
",",
"Iterable",
",",
"getattr"... | [
341,
4
] | [
364,
47
] | python | en | ['en', 'error', 'th'] | False | |
CombinedLoader.sampler | (self) | Return a collections of samplers extracting from loaders. | Return a collections of samplers extracting from loaders. | def sampler(self) -> Union[Iterable, Sequence, Mapping]:
"""Return a collections of samplers extracting from loaders."""
return apply_to_collection(self.loaders, Iterable, getattr, 'sampler', None, wrong_dtype=(Sequence, Mapping)) | [
"def",
"sampler",
"(",
"self",
")",
"->",
"Union",
"[",
"Iterable",
",",
"Sequence",
",",
"Mapping",
"]",
":",
"return",
"apply_to_collection",
"(",
"self",
".",
"loaders",
",",
"Iterable",
",",
"getattr",
",",
"'sampler'",
",",
"None",
",",
"wrong_dtype",... | [
367,
4
] | [
369,
117
] | python | en | ['en', 'en', 'en'] | True |
CombinedLoader._wrap_loaders_max_size_cycle | (self) |
Wraps all loaders to make sure they are cycled until the longest loader is exhausted
Returns:
the wrapped loaders
|
Wraps all loaders to make sure they are cycled until the longest loader is exhausted | def _wrap_loaders_max_size_cycle(self) -> Any:
"""
Wraps all loaders to make sure they are cycled until the longest loader is exhausted
Returns:
the wrapped loaders
"""
all_lengths = apply_to_collection(self.loaders, Iterable, get_len, wrong_dtype=(Sequence, Mapping... | [
"def",
"_wrap_loaders_max_size_cycle",
"(",
"self",
")",
"->",
"Any",
":",
"all_lengths",
"=",
"apply_to_collection",
"(",
"self",
".",
"loaders",
",",
"Iterable",
",",
"get_len",
",",
"wrong_dtype",
"=",
"(",
"Sequence",
",",
"Mapping",
")",
")",
"if",
"isi... | [
371,
4
] | [
401,
92
] | python | en | ['en', 'error', 'th'] | False |
CombinedLoader.__iter__ | (self) |
Create and return an iterator, `CombinedLoaderIterator`, for the combined loader.
|
Create and return an iterator, `CombinedLoaderIterator`, for the combined loader.
| def __iter__(self) -> Any:
"""
Create and return an iterator, `CombinedLoaderIterator`, for the combined loader.
"""
return CombinedLoaderIterator(self.loaders) | [
"def",
"__iter__",
"(",
"self",
")",
"->",
"Any",
":",
"return",
"CombinedLoaderIterator",
"(",
"self",
".",
"loaders",
")"
] | [
403,
4
] | [
407,
51
] | python | en | ['en', 'error', 'th'] | False |
CombinedLoader._calc_num_batches | (loaders: Any) |
Compute the length (aka the number of batches) of `CombinedLoader`.
Args:
loaders: a collections of loaders.
Returns:
length: the minimum length of loaders
|
Compute the length (aka the number of batches) of `CombinedLoader`. | def _calc_num_batches(loaders: Any) -> Union[int, float]:
"""
Compute the length (aka the number of batches) of `CombinedLoader`.
Args:
loaders: a collections of loaders.
Returns:
length: the minimum length of loaders
"""
all_lengths = apply_to_... | [
"def",
"_calc_num_batches",
"(",
"loaders",
":",
"Any",
")",
"->",
"Union",
"[",
"int",
",",
"float",
"]",
":",
"all_lengths",
"=",
"apply_to_collection",
"(",
"loaders",
",",
"Iterable",
",",
"get_len",
",",
"wrong_dtype",
"=",
"(",
"Sequence",
",",
"Mapp... | [
410,
4
] | [
427,
58
] | python | en | ['en', 'error', 'th'] | False |
CombinedLoaderIterator.__init__ | (self, loaders: Any) |
Args:
loaders: the loaders to sample from. Can be all kind of collection
| def __init__(self, loaders: Any):
"""
Args:
loaders: the loaders to sample from. Can be all kind of collection
"""
self.loaders = loaders
self._loader_iters = None | [
"def",
"__init__",
"(",
"self",
",",
"loaders",
":",
"Any",
")",
":",
"self",
".",
"loaders",
"=",
"loaders",
"self",
".",
"_loader_iters",
"=",
"None"
] | [
438,
4
] | [
446,
33
] | python | en | ['en', 'error', 'th'] | False | |
CombinedLoaderIterator.loader_iters | (self) |
Get the `_loader_iters` and create one if it is None.
|
Get the `_loader_iters` and create one if it is None.
| def loader_iters(self) -> Any:
"""
Get the `_loader_iters` and create one if it is None.
"""
if self._loader_iters is None:
self._loader_iters = self.create_loader_iters(self.loaders)
return self._loader_iters | [
"def",
"loader_iters",
"(",
"self",
")",
"->",
"Any",
":",
"if",
"self",
".",
"_loader_iters",
"is",
"None",
":",
"self",
".",
"_loader_iters",
"=",
"self",
".",
"create_loader_iters",
"(",
"self",
".",
"loaders",
")",
"return",
"self",
".",
"_loader_iters... | [
449,
4
] | [
456,
33
] | python | en | ['en', 'error', 'th'] | False |
CombinedLoaderIterator.__next__ | (self) |
Fetches the next batch from multiple data loaders
Returns:
a collections of batch data
|
Fetches the next batch from multiple data loaders | def __next__(self) -> Any:
"""
Fetches the next batch from multiple data loaders
Returns:
a collections of batch data
"""
return self.request_next_batch(self.loader_iters) | [
"def",
"__next__",
"(",
"self",
")",
"->",
"Any",
":",
"return",
"self",
".",
"request_next_batch",
"(",
"self",
".",
"loader_iters",
")"
] | [
461,
4
] | [
469,
57
] | python | en | ['en', 'error', 'th'] | False |
CombinedLoaderIterator.request_next_batch | (loader_iters: Union[Iterator, Sequence, Mapping]) |
Return the batch of data from multiple iterators.
Args:
loader_iters: a collections of iterators
Returns
Any: a collections of batch data
|
Return the batch of data from multiple iterators. | def request_next_batch(loader_iters: Union[Iterator, Sequence, Mapping]) -> Any:
"""
Return the batch of data from multiple iterators.
Args:
loader_iters: a collections of iterators
Returns
Any: a collections of batch data
"""
return apply_to_co... | [
"def",
"request_next_batch",
"(",
"loader_iters",
":",
"Union",
"[",
"Iterator",
",",
"Sequence",
",",
"Mapping",
"]",
")",
"->",
"Any",
":",
"return",
"apply_to_collection",
"(",
"loader_iters",
",",
"Iterator",
",",
"next",
")"
] | [
472,
4
] | [
483,
64
] | python | en | ['en', 'error', 'th'] | False |
CombinedLoaderIterator.create_loader_iters | (
loaders: Union[Any, Iterator, Sequence, Mapping]
) |
Create and return a collection of iterators from loaders.
Args:
loaders: a collections of loaders
Returns
a collections of iterators
|
Create and return a collection of iterators from loaders. | def create_loader_iters(
loaders: Union[Any, Iterator, Sequence, Mapping]
) -> Union[Any, Iterator, Sequence, Mapping]:
"""
Create and return a collection of iterators from loaders.
Args:
loaders: a collections of loaders
Returns
a collections of ite... | [
"def",
"create_loader_iters",
"(",
"loaders",
":",
"Union",
"[",
"Any",
",",
"Iterator",
",",
"Sequence",
",",
"Mapping",
"]",
")",
"->",
"Union",
"[",
"Any",
",",
"Iterator",
",",
"Sequence",
",",
"Mapping",
"]",
":",
"# dataloaders are Iterable but not Seque... | [
486,
4
] | [
500,
92
] | python | en | ['en', 'error', 'th'] | False |
python_scalar_to_tensor | (data: Any, device: torch.device = torch.device("cpu")) | Converts a Python scalar number to a torch tensor and places it on the given device. | Converts a Python scalar number to a torch tensor and places it on the given device. | def python_scalar_to_tensor(data: Any, device: torch.device = torch.device("cpu")) -> Any:
""" Converts a Python scalar number to a torch tensor and places it on the given device. """
if isinstance(data, numbers.Number):
data = torch.tensor([data], device=device)
return data | [
"def",
"python_scalar_to_tensor",
"(",
"data",
":",
"Any",
",",
"device",
":",
"torch",
".",
"device",
"=",
"torch",
".",
"device",
"(",
"\"cpu\"",
")",
")",
"->",
"Any",
":",
"if",
"isinstance",
"(",
"data",
",",
"numbers",
".",
"Number",
")",
":",
... | [
88,
0
] | [
92,
15
] | python | en | ['en', 'en', 'en'] | True |
unsqueeze_scalar_tensor | (data: Any) | Un-squeezes a 0-dim tensor. | Un-squeezes a 0-dim tensor. | def unsqueeze_scalar_tensor(data: Any) -> Any:
""" Un-squeezes a 0-dim tensor. """
if isinstance(data, torch.Tensor) and data.dim() == 0:
data = data.unsqueeze(0)
return data | [
"def",
"unsqueeze_scalar_tensor",
"(",
"data",
":",
"Any",
")",
"->",
"Any",
":",
"if",
"isinstance",
"(",
"data",
",",
"torch",
".",
"Tensor",
")",
"and",
"data",
".",
"dim",
"(",
")",
"==",
"0",
":",
"data",
"=",
"data",
".",
"unsqueeze",
"(",
"0... | [
95,
0
] | [
99,
15
] | python | en | ['en', 'fr', 'it'] | False |
bin_search | (min_limit, max_limit, depth, func, params, is_int=False) | Implement generic binary search algorithm
:param min_limit: The minimum range limit
:type min_limit: int or float (must set is_int if integer)
:param max_limit: The maximum range limit
:type max_limit: int or float
:param depth: The recursion depth limit
:type depth: int
:param func: Functi... | Implement generic binary search algorithm | def bin_search(min_limit, max_limit, depth, func, params, is_int=False):
"""Implement generic binary search algorithm
:param min_limit: The minimum range limit
:type min_limit: int or float (must set is_int if integer)
:param max_limit: The maximum range limit
:type max_limit: int or float
:par... | [
"def",
"bin_search",
"(",
"min_limit",
",",
"max_limit",
",",
"depth",
",",
"func",
",",
"params",
",",
"is_int",
"=",
"False",
")",
":",
"new_val",
"=",
"(",
"float",
"(",
"max_limit",
")",
"+",
"float",
"(",
"min_limit",
")",
")",
"/",
"2.0",
"para... | [
32,
0
] | [
73,
78
] | python | en | ['en', 'en', 'en'] | True |
example_rtc_trim | (chip, logger, time_period_s=10, max_iterations=10) | Example of a trimming a chips RTC using a linear search. Just an example, use the methods provided in the M0N0S2 class to trim the RTC instead
| Example of a trimming a chips RTC using a linear search. Just an example, use the methods provided in the M0N0S2 class to trim the RTC instead
| def example_rtc_trim(chip, logger, time_period_s=10, max_iterations=10):
"""Example of a trimming a chips RTC using a linear search. Just an example, use the methods provided in the M0N0S2 class to trim the RTC instead
"""
# PCSM cannot be read, so using model value (the PoR value unless changed
# previ... | [
"def",
"example_rtc_trim",
"(",
"chip",
",",
"logger",
",",
"time_period_s",
"=",
"10",
",",
"max_iterations",
"=",
"10",
")",
":",
"# PCSM cannot be read, so using model value (the PoR value unless changed",
"# previously by this script). ",
"logger",
".",
"info",
"(",
"... | [
75,
0
] | [
103,
46
] | python | en | ['en', 'en', 'en'] | True |
derive_adp_port | (logger) | Automatically derive the ADP port (only works on MacOS (perhaps Linux) and with the Demoboard
:param logger: The logger object
:type logger: logger.Logger object
:return: The full ADP port path
:rtype: str
| Automatically derive the ADP port (only works on MacOS (perhaps Linux) and with the Demoboard | def derive_adp_port(logger):
"""Automatically derive the ADP port (only works on MacOS (perhaps Linux) and with the Demoboard
:param logger: The logger object
:type logger: logger.Logger object
:return: The full ADP port path
:rtype: str
"""
logger.warning("Auto ADP port - Mac (many linux) ... | [
"def",
"derive_adp_port",
"(",
"logger",
")",
":",
"logger",
".",
"warning",
"(",
"\"Auto ADP port - Mac (many linux) ONLY!\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"'/dev'",
")",
":",
"raise",
"IOError",
"(",
"\"Could not open /dev directory. T... | [
106,
0
] | [
125,
44
] | python | en | ['en', 'en', 'en'] | True |
setup_logger | (logger, level, log_filepath, prefix=None) | Sets up and returns a logger object
:param logger: The logger object for logging messages to the console
and file
:type logger: logging.Logger object
:param level: The minimum log level to print to the console
:type level: str (one of "DEBUG", "INFO", "WARN", "ERROR")
:param log_... | Sets up and returns a logger object | def setup_logger(logger, level, log_filepath, prefix=None):
"""Sets up and returns a logger object
:param logger: The logger object for logging messages to the console
and file
:type logger: logging.Logger object
:param level: The minimum log level to print to the console
:type l... | [
"def",
"setup_logger",
"(",
"logger",
",",
"level",
",",
"log_filepath",
",",
"prefix",
"=",
"None",
")",
":",
"prefix",
"=",
"\"(\"",
"+",
"str",
"(",
"prefix",
")",
"+",
"\") \"",
"if",
"prefix",
"else",
"\"\"",
"temp_logger",
"=",
"logger",
"temp_log_... | [
127,
0
] | [
163,
22
] | python | en | ['en', 'en', 'en'] | True |
process_adp_tx_params | (tx_params) | Takes the parameter text from ADP TX params section and converts to dictionary
:param tx_params: The parameter text from the ADP TX parameter section
:type tx_params: str
:return: Result dictionary with the keys and values
:rtype: dict
| Takes the parameter text from ADP TX params section and converts to dictionary | def process_adp_tx_params(tx_params):
"""Takes the parameter text from ADP TX params section and converts to dictionary
:param tx_params: The parameter text from the ADP TX parameter section
:type tx_params: str
:return: Result dictionary with the keys and values
:rtype: dict
"""
# input is... | [
"def",
"process_adp_tx_params",
"(",
"tx_params",
")",
":",
"# input is a string - convert to dict",
"def",
"is_int",
"(",
"value",
")",
":",
"try",
":",
"int",
"(",
"value",
",",
"0",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False",
"tx_... | [
165,
0
] | [
184,
14
] | python | en | ['en', 'en', 'en'] | True |
AudioReader.demoboard_audio | (self, tx_name, tx_params, tx_payload) | Decodes the audio data and parameters received via the ADP TX. Saves audio data in a WAVE file.
:param tx_name: The name of the transaction
:type tx_name: str
:param tx_params: The raw text from the parameter part of the ADP TX
:type tx_params: str
:param tx_payload: The... | Decodes the audio data and parameters received via the ADP TX. Saves audio data in a WAVE file.
:param tx_name: The name of the transaction
:type tx_name: str
:param tx_params: The raw text from the parameter part of the ADP TX
:type tx_params: str
:param tx_payload: The... | def demoboard_audio(self, tx_name, tx_params, tx_payload):
"""Decodes the audio data and parameters received via the ADP TX. Saves audio data in a WAVE file.
:param tx_name: The name of the transaction
:type tx_name: str
:param tx_params: The raw text from the parameter part of ... | [
"def",
"demoboard_audio",
"(",
"self",
",",
"tx_name",
",",
"tx_params",
",",
"tx_payload",
")",
":",
"audio_frame",
"=",
"[",
"]",
"tx_params",
"=",
"process_adp_tx_params",
"(",
"tx_params",
")",
"sample_freq_hz",
"=",
"8000",
"print",
"(",
"tx_params",
")",... | [
193,
4
] | [
249,
24
] | python | en | ['en', 'en', 'en'] | True |
PSNR.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
"""
sum_squared_error, n_obs = _psnr_update(preds, target, dim=self.dim)
if... | [
"def",
"update",
"(",
"self",
",",
"preds",
":",
"torch",
".",
"Tensor",
",",
"target",
":",
"torch",
".",
"Tensor",
")",
":",
"sum_squared_error",
",",
"n_obs",
"=",
"_psnr_update",
"(",
"preds",
",",
"target",
",",
"dim",
"=",
"self",
".",
"dim",
"... | [
105,
4
] | [
124,
36
] | python | en | ['en', 'error', 'th'] | False |
PSNR.compute | (self) |
Compute peak signal-to-noise ratio over state.
|
Compute peak signal-to-noise ratio over state.
| def compute(self):
"""
Compute peak signal-to-noise ratio over state.
"""
if self.data_range is not None:
data_range = self.data_range
else:
data_range = self.max_target - self.min_target
if self.dim is None:
sum_squared_error = self.s... | [
"def",
"compute",
"(",
"self",
")",
":",
"if",
"self",
".",
"data_range",
"is",
"not",
"None",
":",
"data_range",
"=",
"self",
".",
"data_range",
"else",
":",
"data_range",
"=",
"self",
".",
"max_target",
"-",
"self",
".",
"min_target",
"if",
"self",
"... | [
126,
4
] | [
141,
108
] | python | en | ['en', 'error', 'th'] | False |
specificity | (y_true: np.ndarray, y_pred: np.ndarray) | Define the specifity metric to implement in keras models.
:param y_true: Numpy array containing the true values
:type y_true: np.ndarray
:param y_pred: Numpy array containing the predicted values
:type y_pred: np.ndarray
:return: A float number with the value of the metric calculated
:rtype: fl... | Define the specifity metric to implement in keras models. | def specificity(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""Define the specifity metric to implement in keras models.
:param y_true: Numpy array containing the true values
:type y_true: np.ndarray
:param y_pred: Numpy array containing the predicted values
:type y_pred: np.ndarray
:retu... | [
"def",
"specificity",
"(",
"y_true",
":",
"np",
".",
"ndarray",
",",
"y_pred",
":",
"np",
".",
"ndarray",
")",
"->",
"float",
":",
"true_negatives",
"=",
"K",
".",
"sum",
"(",
"K",
".",
"round",
"(",
"K",
".",
"clip",
"(",
"(",
"1",
"-",
"y_true"... | [
6,
0
] | [
18,
62
] | python | en | ['en', 'en', 'en'] | True |
f1_score | (y_true: np.ndarray, y_pred: np.ndarray) | Define the f1_score metric to implement in keras models.
:param y_true: Numpy array containing the true values
:type y_true: np.ndarray
:param y_pred: Numpy array containing the predicted values
:type y_pred: np.ndarray
:return: A float number with the value of the metric calculated
:rtype: flo... | Define the f1_score metric to implement in keras models. | def f1_score(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""Define the f1_score metric to implement in keras models.
:param y_true: Numpy array containing the true values
:type y_true: np.ndarray
:param y_pred: Numpy array containing the predicted values
:type y_pred: np.ndarray
:return: ... | [
"def",
"f1_score",
"(",
"y_true",
":",
"np",
".",
"ndarray",
",",
"y_pred",
":",
"np",
".",
"ndarray",
")",
"->",
"float",
":",
"true_positives",
"=",
"K",
".",
"sum",
"(",
"K",
".",
"round",
"(",
"K",
".",
"clip",
"(",
"y_true",
"*",
"y_pred",
"... | [
21,
0
] | [
36,
60
] | python | en | ['en', 'en', 'en'] | True |
_count_ngram | (ngram_input_list: List[str], n_gram: int) |
Counting how many times each word appears in a given text with ngram
Args:
ngram_input_list: A list of translated text or reference texts
n_gram: gram value ranged 1 to 4
Return:
ngram_counter: a collections.Counter object of ngram
|
Counting how many times each word appears in a given text with ngram | def _count_ngram(ngram_input_list: List[str], n_gram: int) -> Counter:
"""
Counting how many times each word appears in a given text with ngram
Args:
ngram_input_list: A list of translated text or reference texts
n_gram: gram value ranged 1 to 4
Return:
ngram_counter: a collect... | [
"def",
"_count_ngram",
"(",
"ngram_input_list",
":",
"List",
"[",
"str",
"]",
",",
"n_gram",
":",
"int",
")",
"->",
"Counter",
":",
"ngram_counter",
"=",
"Counter",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n_gram",
"+",
"1",
")",
":",
"... | [
24,
0
] | [
43,
24
] | python | en | ['en', 'error', 'th'] | False |
bleu_score | (
translate_corpus: Sequence[str],
reference_corpus: Sequence[str],
n_gram: int = 4,
smooth: bool = False
) |
Calculate BLEU score of machine translated text with one or more references
Args:
translate_corpus: An iterable of machine translated corpus
reference_corpus: An iterable of iterables of reference corpus
n_gram: Gram value ranged from 1 to 4 (Default 4)
smooth: Whether or not t... |
Calculate BLEU score of machine translated text with one or more references | def bleu_score(
translate_corpus: Sequence[str],
reference_corpus: Sequence[str],
n_gram: int = 4,
smooth: bool = False
) -> torch.Tensor:
"""
Calculate BLEU score of machine translated text with one or more references
Args:
translate_corpus: An iterable of machine translated corpus... | [
"def",
"bleu_score",
"(",
"translate_corpus",
":",
"Sequence",
"[",
"str",
"]",
",",
"reference_corpus",
":",
"Sequence",
"[",
"str",
"]",
",",
"n_gram",
":",
"int",
"=",
"4",
",",
"smooth",
":",
"bool",
"=",
"False",
")",
"->",
"torch",
".",
"Tensor",... | [
46,
0
] | [
113,
15
] | python | en | ['en', 'error', 'th'] | False |
test_default_args | (mock_argparse, tmpdir) | Tests default argument parser for Trainer | Tests default argument parser for Trainer | def test_default_args(mock_argparse, tmpdir):
"""Tests default argument parser for Trainer"""
mock_argparse.return_value = Namespace(**Trainer.default_attributes())
# logger file to get meta
logger = tutils.get_default_logger(tmpdir)
parser = ArgumentParser(add_help=False)
args = parser.parse_... | [
"def",
"test_default_args",
"(",
"mock_argparse",
",",
"tmpdir",
")",
":",
"mock_argparse",
".",
"return_value",
"=",
"Namespace",
"(",
"*",
"*",
"Trainer",
".",
"default_attributes",
"(",
")",
")",
"# logger file to get meta",
"logger",
"=",
"tutils",
".",
"get... | [
28,
0
] | [
43,
34
] | python | da | ['da', 'da', 'en'] | True |
test_add_argparse_args_redefined | (cli_args) | Redefines some default Trainer arguments via the cli and
tests the Trainer initialization correctness.
| Redefines some default Trainer arguments via the cli and
tests the Trainer initialization correctness.
| def test_add_argparse_args_redefined(cli_args):
"""Redefines some default Trainer arguments via the cli and
tests the Trainer initialization correctness.
"""
parser = ArgumentParser(add_help=False)
parser = Trainer.add_argparse_args(parent_parser=parser)
args = parser.parse_args(cli_args)
... | [
"def",
"test_add_argparse_args_redefined",
"(",
"cli_args",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"add_help",
"=",
"False",
")",
"parser",
"=",
"Trainer",
".",
"add_argparse_args",
"(",
"parent_parser",
"=",
"parser",
")",
"args",
"=",
"parser",
".",
... | [
47,
0
] | [
66,
39
] | python | en | ['en', 'en', 'en'] | True |
test_add_argparse_via_argument_group | (cli_args) | Simple test ensuring that passing an argument group still works | Simple test ensuring that passing an argument group still works | def test_add_argparse_via_argument_group(cli_args):
"""Simple test ensuring that passing an argument group still works"""
parser = ArgumentParser(add_help=False)
parser = Trainer.add_argparse_args(parser.add_argument_group(title="pl.Trainer args"))
args = parser.parse_args(cli_args)
assert Trainer.f... | [
"def",
"test_add_argparse_via_argument_group",
"(",
"cli_args",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"add_help",
"=",
"False",
")",
"parser",
"=",
"Trainer",
".",
"add_argparse_args",
"(",
"parser",
".",
"add_argument_group",
"(",
"title",
"=",
"\"pl.Tr... | [
70,
0
] | [
75,
43
] | python | en | ['en', 'en', 'en'] | True |
test_get_init_arguments_and_types | () | Asserts a correctness of the `get_init_arguments_and_types` Trainer classmethod. | Asserts a correctness of the `get_init_arguments_and_types` Trainer classmethod. | def test_get_init_arguments_and_types():
"""Asserts a correctness of the `get_init_arguments_and_types` Trainer classmethod."""
args = argparse.get_init_arguments_and_types(Trainer)
parameters = inspect.signature(Trainer).parameters
assert len(parameters) == len(args)
for arg in args:
assert... | [
"def",
"test_get_init_arguments_and_types",
"(",
")",
":",
"args",
"=",
"argparse",
".",
"get_init_arguments_and_types",
"(",
"Trainer",
")",
"parameters",
"=",
"inspect",
".",
"signature",
"(",
"Trainer",
")",
".",
"parameters",
"assert",
"len",
"(",
"parameters"... | [
78,
0
] | [
88,
39
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.