Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
test_complex_inf_nan
(dtype)
Check inf/nan formatting of complex types.
Check inf/nan formatting of complex types.
def test_complex_inf_nan(dtype): """Check inf/nan formatting of complex types.""" TESTS = { complex(np.inf, 0): "(inf+0j)", complex(0, np.inf): "infj", complex(-np.inf, 0): "(-inf+0j)", complex(0, -np.inf): "-infj", complex(np.inf, 1): "(inf+1j)", complex(1, np.in...
[ "def", "test_complex_inf_nan", "(", "dtype", ")", ":", "TESTS", "=", "{", "complex", "(", "np", ".", "inf", ",", "0", ")", ":", "\"(inf+0j)\"", ",", "complex", "(", "0", ",", "np", ".", "inf", ")", ":", "\"infj\"", ",", "complex", "(", "-", "np", ...
[ 82, 0 ]
[ 103, 38 ]
python
en
['en', 'en', 'en']
True
test_float_type_print
(tp)
Check formatting when using print
Check formatting when using print
def test_float_type_print(tp): """Check formatting when using print """ for x in [0, 1, -1, 1e20]: _test_redirected_print(float(x), tp) for x in [np.inf, -np.inf, np.nan]: _test_redirected_print(float(x), tp, _REF[x]) if tp(1e16).itemsize > 4: _test_redirected_print(float(1e16)...
[ "def", "test_float_type_print", "(", "tp", ")", ":", "for", "x", "in", "[", "0", ",", "1", ",", "-", "1", ",", "1e20", "]", ":", "_test_redirected_print", "(", "float", "(", "x", ")", ",", "tp", ")", "for", "x", "in", "[", "np", ".", "inf", ","...
[ 127, 0 ]
[ 139, 52 ]
python
en
['en', 'en', 'en']
True
test_complex_type_print
(tp)
Check formatting when using print
Check formatting when using print
def test_complex_type_print(tp): """Check formatting when using print """ # We do not create complex with inf/nan directly because the feature is # missing in python < 2.6 for x in [0, 1, -1, 1e20]: _test_redirected_print(complex(x), tp) if tp(1e16).itemsize > 8: _test_redirected_pr...
[ "def", "test_complex_type_print", "(", "tp", ")", ":", "# We do not create complex with inf/nan directly because the feature is", "# missing in python < 2.6", "for", "x", "in", "[", "0", ",", "1", ",", "-", "1", ",", "1e20", "]", ":", "_test_redirected_print", "(", "c...
[ 143, 0 ]
[ 158, 63 ]
python
en
['en', 'en', 'en']
True
test_scalar_format
()
Test the str.format method with NumPy scalar types
Test the str.format method with NumPy scalar types
def test_scalar_format(): """Test the str.format method with NumPy scalar types""" tests = [('{0}', True, np.bool_), ('{0}', False, np.bool_), ('{0:d}', 130, np.uint8), ('{0:d}', 50000, np.uint16), ('{0:d}', 3000000000, np.uint32), ('{0:d}', 1500000000...
[ "def", "test_scalar_format", "(", ")", ":", "tests", "=", "[", "(", "'{0}'", ",", "True", ",", "np", ".", "bool_", ")", ",", "(", "'{0}'", ",", "False", ",", "np", ".", "bool_", ")", ",", "(", "'{0:d}'", ",", "130", ",", "np", ".", "uint8", ")"...
[ 161, 0 ]
[ 188, 69 ]
python
en
['en', 'en', 'en']
True
parse_structure
(astr)
Return a list of tuples for each function or subroutine each tuple is the start and end of a subroutine or function to be expanded.
Return a list of tuples for each function or subroutine each tuple is the start and end of a subroutine or function to be expanded.
def parse_structure(astr): """ Return a list of tuples for each function or subroutine each tuple is the start and end of a subroutine or function to be expanded. """ spanlist = [] ind = 0 while True: m = routine_start_re.search(astr, ind) if m is None: break ...
[ "def", "parse_structure", "(", "astr", ")", ":", "spanlist", "=", "[", "]", "ind", "=", "0", "while", "True", ":", "m", "=", "routine_start_re", ".", "search", "(", "astr", ",", "ind", ")", "if", "m", "is", "None", ":", "break", "start", "=", "m", ...
[ 59, 0 ]
[ 84, 19 ]
python
en
['en', 'en', 'en']
True
unique_key
(adict)
Obtain a unique key given a dictionary.
Obtain a unique key given a dictionary.
def unique_key(adict): """ Obtain a unique key given a dictionary.""" allkeys = list(adict.keys()) done = False n = 1 while not done: newkey = '__l%s' % (n) if newkey in allkeys: n += 1 else: done = True return newkey
[ "def", "unique_key", "(", "adict", ")", ":", "allkeys", "=", "list", "(", "adict", ".", "keys", "(", ")", ")", "done", "=", "False", "n", "=", "1", "while", "not", "done", ":", "newkey", "=", "'__l%s'", "%", "(", "n", ")", "if", "newkey", "in", ...
[ 116, 0 ]
[ 127, 17 ]
python
ca
['ca', 'ca', 'en']
True
LoginView.form_valid
(self, form)
Security check complete. Log the user in.
Security check complete. Log the user in.
def form_valid(self, form): """Security check complete. Log the user in.""" remember_me = form.data.get('remember_me') if self.session_enabled: self.request.session.set_expiry(None if remember_me else 0) return super(LoginView, self).form_valid(form) expires_in ...
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "remember_me", "=", "form", ".", "data", ".", "get", "(", "'remember_me'", ")", "if", "self", ".", "session_enabled", ":", "self", ".", "request", ".", "session", ".", "set_expiry", "(", "None", ...
[ 17, 4 ]
[ 35, 23 ]
python
en
['en', 'en', 'en']
True
install.setuptools_run
(self)
The setuptools version of the .run() method. We must pull in the entire code so we can override the level used in the _getframe() call since we wrap this call by one more level.
The setuptools version of the .run() method.
def setuptools_run(self): """ The setuptools version of the .run() method. We must pull in the entire code so we can override the level used in the _getframe() call since we wrap this call by one more level. """ from distutils.command.install import install as distutils_install ...
[ "def", "setuptools_run", "(", "self", ")", ":", "from", "distutils", ".", "command", ".", "install", "import", "install", "as", "distutils_install", "# Explicit request for old-style install? Just do it", "if", "self", ".", "old_and_unmanageable", "or", "self", ".", ...
[ 25, 4 ]
[ 55, 33 ]
python
en
['en', 'et', 'en']
True
calc
(term)
input: term of type str output: returns the result of the computed term. purpose: This function is the actual calculator and the heart of the application
input: term of type str output: returns the result of the computed term. purpose: This function is the actual calculator and the heart of the application
def calc(term): """ input: term of type str output: returns the result of the computed term. purpose: This function is the actual calculator and the heart of the application """ # This part is for reading and converting arithmetic terms. term = term.replace(' ', '') term = t...
[ "def", "calc", "(", "term", ")", ":", "# This part is for reading and converting arithmetic terms.", "term", "=", "term", ".", "replace", "(", "' '", ",", "''", ")", "term", "=", "term", ".", "replace", "(", "'^'", ",", "'**'", ")", "term", "=", "term", "....
[ 32, 0 ]
[ 79, 15 ]
python
en
['en', 'error', 'th']
False
result
(term)
input: term of type str output: none purpose: passes the argument to the function calc(...) and prints the result onto console.
input: term of type str output: none purpose: passes the argument to the function calc(...) and prints the result onto console.
def result(term): """ input: term of type str output: none purpose: passes the argument to the function calc(...) and prints the result onto console. """ print("\n" + str(calc(term)))
[ "def", "result", "(", "term", ")", ":", "print", "(", "\"\\n\"", "+", "str", "(", "calc", "(", "term", ")", ")", ")" ]
[ 82, 0 ]
[ 89, 33 ]
python
en
['en', 'error', 'th']
False
main
()
main-program purpose: handles user input and prints information to the console.
main-program purpose: handles user input and prints information to the console.
def main(): """ main-program purpose: handles user input and prints information to the console. """ print("\nScientific Calculator\n\nFor Example: sin(rad(90)) + 50% * (sqrt(16)) + round(1.42^2)" + "- 12mod3\n\nEnter quit to exit") if sys.version_info.major ...
[ "def", "main", "(", ")", ":", "print", "(", "\"\\nScientific Calculator\\n\\nFor Example: sin(rad(90)) + 50% * (sqrt(16)) + round(1.42^2)\"", "+", "\"- 12mod3\\n\\nEnter quit to exit\"", ")", "if", "sys", ".", "version_info", ".", "major", ">=", "3", ":", "while", "True", ...
[ 92, 0 ]
[ 114, 21 ]
python
en
['en', 'error', 'th']
False
get_include
()
Return the directory that contains the NumPy \\*.h header files. Extension modules that need to compile against NumPy should use this function to locate the appropriate include directory. Notes ----- When using ``distutils``, for example in ``setup.py``. :: import numpy as np ...
Return the directory that contains the NumPy \\*.h header files.
def get_include(): """ Return the directory that contains the NumPy \\*.h header files. Extension modules that need to compile against NumPy should use this function to locate the appropriate include directory. Notes ----- When using ``distutils``, for example in ``setup.py``. :: ...
[ "def", "get_include", "(", ")", ":", "import", "numpy", "if", "numpy", ".", "show_config", "is", "None", ":", "# running from numpy source directory", "d", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "numpy", ".", "_...
[ 22, 0 ]
[ 49, 12 ]
python
en
['en', 'error', 'th']
False
_get_indent
(lines)
Determines the leading whitespace that could be removed from all the lines.
Determines the leading whitespace that could be removed from all the lines.
def _get_indent(lines): """ Determines the leading whitespace that could be removed from all the lines. """ indent = sys.maxsize for line in lines: content = len(line.lstrip()) if content: indent = min(indent, len(line) - content) if indent == sys.maxsize: ind...
[ "def", "_get_indent", "(", "lines", ")", ":", "indent", "=", "sys", ".", "maxsize", "for", "line", "in", "lines", ":", "content", "=", "len", "(", "line", ".", "lstrip", "(", ")", ")", "if", "content", ":", "indent", "=", "min", "(", "indent", ",",...
[ 132, 0 ]
[ 143, 17 ]
python
en
['en', 'error', 'th']
False
deprecate
(*args, **kwargs)
Issues a DeprecationWarning, adds warning to `old_name`'s docstring, rebinds ``old_name.__name__`` and returns the new function object. This function may also be used as a decorator. Parameters ---------- func : function The function to be deprecated. old_name : str, optional ...
Issues a DeprecationWarning, adds warning to `old_name`'s docstring, rebinds ``old_name.__name__`` and returns the new function object.
def deprecate(*args, **kwargs): """ Issues a DeprecationWarning, adds warning to `old_name`'s docstring, rebinds ``old_name.__name__`` and returns the new function object. This function may also be used as a decorator. Parameters ---------- func : function The function to be de...
[ "def", "deprecate", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Deprecate may be run as a function or as a decorator", "# If run as a function, we initialise the decorator class", "# and execute its __call__ method.", "if", "args", ":", "fn", "=", "args", "[", "...
[ 146, 0 ]
[ 196, 42 ]
python
en
['en', 'error', 'th']
False
byte_bounds
(a)
Returns pointers to the end-points of an array. Parameters ---------- a : ndarray Input array. It must conform to the Python-side of the array interface. Returns ------- (low, high) : tuple of 2 integers The first integer is the first byte of the array, the second ...
Returns pointers to the end-points of an array.
def byte_bounds(a): """ Returns pointers to the end-points of an array. Parameters ---------- a : ndarray Input array. It must conform to the Python-side of the array interface. Returns ------- (low, high) : tuple of 2 integers The first integer is the first byt...
[ "def", "byte_bounds", "(", "a", ")", ":", "ai", "=", "a", ".", "__array_interface__", "a_data", "=", "ai", "[", "'data'", "]", "[", "0", "]", "astrides", "=", "ai", "[", "'strides'", "]", "ashape", "=", "ai", "[", "'shape'", "]", "bytes_a", "=", "a...
[ 205, 0 ]
[ 254, 24 ]
python
en
['en', 'error', 'th']
False
who
(vardict=None)
Print the NumPy arrays in the given dictionary. If there is no dictionary passed in or `vardict` is None then returns NumPy arrays in the globals() dictionary (all NumPy arrays in the namespace). Parameters ---------- vardict : dict, optional A dictionary possibly containing ndarr...
Print the NumPy arrays in the given dictionary.
def who(vardict=None): """ Print the NumPy arrays in the given dictionary. If there is no dictionary passed in or `vardict` is None then returns NumPy arrays in the globals() dictionary (all NumPy arrays in the namespace). Parameters ---------- vardict : dict, optional A dictio...
[ "def", "who", "(", "vardict", "=", "None", ")", ":", "if", "vardict", "is", "None", ":", "frame", "=", "sys", ".", "_getframe", "(", ")", ".", "f_back", "vardict", "=", "frame", ".", "f_globals", "sta", "=", "[", "]", "cache", "=", "{", "}", "for...
[ 262, 0 ]
[ 356, 10 ]
python
en
['en', 'error', 'th']
False
_info
(obj, output=sys.stdout)
Provide information about ndarray obj. Parameters ---------- obj : ndarray Must be ndarray, not checked. output Where printed output goes. Notes ----- Copied over from the numarray module prior to its removal. Adapted somewhat as only numpy is an option now. Called...
Provide information about ndarray obj.
def _info(obj, output=sys.stdout): """Provide information about ndarray obj. Parameters ---------- obj : ndarray Must be ndarray, not checked. output Where printed output goes. Notes ----- Copied over from the numarray module prior to its removal. Adapted somewhat a...
[ "def", "_info", "(", "obj", ",", "output", "=", "sys", ".", "stdout", ")", ":", "extra", "=", "\"\"", "tic", "=", "\"\"", "bp", "=", "lambda", "x", ":", "x", "cls", "=", "getattr", "(", "obj", ",", "'__class__'", ",", "type", "(", "obj", ")", "...
[ 411, 0 ]
[ 459, 46 ]
python
cs
['en', 'cs', 'hi']
False
info
(object=None, maxwidth=76, output=sys.stdout, toplevel='numpy')
Get help information for a function, class, or module. Parameters ---------- object : object or str, optional Input object or name to get information about. If `object` is a numpy object, its docstring is given. If it is a string, available modules are searched for matching obj...
Get help information for a function, class, or module.
def info(object=None, maxwidth=76, output=sys.stdout, toplevel='numpy'): """ Get help information for a function, class, or module. Parameters ---------- object : object or str, optional Input object or name to get information about. If `object` is a numpy object, its docstring is g...
[ "def", "info", "(", "object", "=", "None", ",", "maxwidth", "=", "76", ",", "output", "=", "sys", ".", "stdout", ",", "toplevel", "=", "'numpy'", ")", ":", "global", "_namedict", ",", "_dictlist", "# Local import to speed up numpy's import time.", "import", "p...
[ 463, 0 ]
[ 665, 50 ]
python
en
['en', 'error', 'th']
False
source
(object, output=sys.stdout)
Print or write to a file the source code for a NumPy object. The source code is only returned for objects written in Python. Many functions and classes are defined in C and will therefore not return useful information. Parameters ---------- object : numpy object Input object. This...
Print or write to a file the source code for a NumPy object.
def source(object, output=sys.stdout): """ Print or write to a file the source code for a NumPy object. The source code is only returned for objects written in Python. Many functions and classes are defined in C and will therefore not return useful information. Parameters ---------- ob...
[ "def", "source", "(", "object", ",", "output", "=", "sys", ".", "stdout", ")", ":", "# Local import to speed up numpy's import time.", "import", "inspect", "try", ":", "print", "(", "\"In file: %s\\n\"", "%", "inspect", ".", "getsourcefile", "(", "object", ")", ...
[ 669, 0 ]
[ 714, 60 ]
python
en
['en', 'error', 'th']
False
lookfor
(what, module=None, import_modules=True, regenerate=False, output=None)
Do a keyword search on docstrings. A list of objects that matched the search is displayed, sorted by relevance. All given keywords need to be found in the docstring for it to be returned as a result, but the order does not matter. Parameters ---------- what : str String contai...
Do a keyword search on docstrings.
def lookfor(what, module=None, import_modules=True, regenerate=False, output=None): """ Do a keyword search on docstrings. A list of objects that matched the search is displayed, sorted by relevance. All given keywords need to be found in the docstring for it to be returned as a result,...
[ "def", "lookfor", "(", "what", ",", "module", "=", "None", ",", "import_modules", "=", "True", ",", "regenerate", "=", "False", ",", "output", "=", "None", ")", ":", "import", "pydoc", "# Cache", "cache", "=", "_lookfor_generate_cache", "(", "module", ",",...
[ 728, 0 ]
[ 854, 35 ]
python
en
['en', 'error', 'th']
False
_lookfor_generate_cache
(module, import_modules, regenerate)
Generate docstring cache for given module. Parameters ---------- module : str, None, module Module for which to generate docstring cache import_modules : bool Whether to import sub-modules in packages. regenerate : bool Re-generate the docstring cache Returns -...
Generate docstring cache for given module.
def _lookfor_generate_cache(module, import_modules, regenerate): """ Generate docstring cache for given module. Parameters ---------- module : str, None, module Module for which to generate docstring cache import_modules : bool Whether to import sub-modules in packages. rege...
[ "def", "_lookfor_generate_cache", "(", "module", ",", "import_modules", ",", "regenerate", ")", ":", "global", "_lookfor_caches", "# Local import to speed up numpy's import time.", "import", "inspect", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", ...
[ 856, 0 ]
[ 994, 16 ]
python
en
['en', 'error', 'th']
False
safe_eval
(source)
Protected string evaluation. Evaluate a string containing a Python literal expression without allowing the execution of arbitrary non-literal code. Parameters ---------- source : str The string to evaluate. Returns ------- obj : object The result of evaluating `sou...
Protected string evaluation.
def safe_eval(source): """ Protected string evaluation. Evaluate a string containing a Python literal expression without allowing the execution of arbitrary non-literal code. Parameters ---------- source : str The string to evaluate. Returns ------- obj : object ...
[ "def", "safe_eval", "(", "source", ")", ":", "# Local import to speed up numpy's import time.", "import", "ast", "return", "ast", ".", "literal_eval", "(", "source", ")" ]
[ 1093, 0 ]
[ 1138, 35 ]
python
en
['en', 'error', 'th']
False
_median_nancheck
(data, result, axis, out)
Utility function to check median result from data for NaN values at the end and return NaN in that case. Input result can also be a MaskedArray. Parameters ---------- data : array Input data to median function result : Array or MaskedArray Result of median function axis : {...
Utility function to check median result from data for NaN values at the end and return NaN in that case. Input result can also be a MaskedArray.
def _median_nancheck(data, result, axis, out): """ Utility function to check median result from data for NaN values at the end and return NaN in that case. Input result can also be a MaskedArray. Parameters ---------- data : array Input data to median function result : Array or Mask...
[ "def", "_median_nancheck", "(", "data", ",", "result", ",", "axis", ",", "out", ")", ":", "if", "data", ".", "size", "==", "0", ":", "return", "result", "data", "=", "np", ".", "moveaxis", "(", "data", ",", "axis", ",", "-", "1", ")", "n", "=", ...
[ 1141, 0 ]
[ 1177, 17 ]
python
en
['en', 'error', 'th']
False
_Deprecate.__call__
(self, func, *args, **kwargs)
Decorator call. Refer to ``decorate``.
Decorator call. Refer to ``decorate``.
def __call__(self, func, *args, **kwargs): """ Decorator call. Refer to ``decorate``. """ old_name = self.old_name new_name = self.new_name message = self.message if old_name is None: try: old_name = func.__name__ except ...
[ "def", "__call__", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "old_name", "=", "self", ".", "old_name", "new_name", "=", "self", ".", "new_name", "message", "=", "self", ".", "message", "if", "old_name", "is", "Non...
[ 74, 4 ]
[ 129, 22 ]
python
en
['en', 'error', 'th']
False
StochasticWeightAveraging.__init__
( self, swa_epoch_start: Union[int, float] = 0.8, swa_lrs: Optional[Union[float, list]] = None, annealing_epochs: int = 10, annealing_strategy: str = "cos", avg_fn: Optional[_AVG_FN] = None, device: Optional[Union[torch.device, str]] = torch.device("cpu"), )
r""" Implements the Stochastic Weight Averaging (SWA) Callback to average a model. Stochastic Weight Averaging was proposed in ``Averaging Weights Leads to Wider Optima and Better Generalization`` by Pavel Izmailov, Dmitrii Podoprikhin, Timur Garipov, Dmitry Vetrov and Andrew Gordon Wi...
r"""
def __init__( self, swa_epoch_start: Union[int, float] = 0.8, swa_lrs: Optional[Union[float, list]] = None, annealing_epochs: int = 10, annealing_strategy: str = "cos", avg_fn: Optional[_AVG_FN] = None, device: Optional[Union[torch.device, str]] = torch.device("cp...
[ "def", "__init__", "(", "self", ",", "swa_epoch_start", ":", "Union", "[", "int", ",", "float", "]", "=", "0.8", ",", "swa_lrs", ":", "Optional", "[", "Union", "[", "float", ",", "list", "]", "]", "=", "None", ",", "annealing_epochs", ":", "int", "="...
[ 37, 4 ]
[ 125, 34 ]
python
cy
['en', 'cy', 'hi']
False
StochasticWeightAveraging.reset_batch_norm_and_save_state
(self, pl_module: 'pl.LightningModule')
Adapted from https://github.com/pytorch/pytorch/blob/v1.7.1/torch/optim/swa_utils.py#L140-L154
Adapted from https://github.com/pytorch/pytorch/blob/v1.7.1/torch/optim/swa_utils.py#L140-L154
def reset_batch_norm_and_save_state(self, pl_module: 'pl.LightningModule'): """ Adapted from https://github.com/pytorch/pytorch/blob/v1.7.1/torch/optim/swa_utils.py#L140-L154 """ self.momenta = {} for module in pl_module.modules(): if not isinstance(module, nn.modules...
[ "def", "reset_batch_norm_and_save_state", "(", "self", ",", "pl_module", ":", "'pl.LightningModule'", ")", ":", "self", ".", "momenta", "=", "{", "}", "for", "module", "in", "pl_module", ".", "modules", "(", ")", ":", "if", "not", "isinstance", "(", "module"...
[ 242, 4 ]
[ 258, 43 ]
python
en
['en', 'error', 'th']
False
StochasticWeightAveraging.reset_momenta
(self)
Adapted from https://github.com/pytorch/pytorch/blob/v1.7.1/torch/optim/swa_utils.py#L164-L165
Adapted from https://github.com/pytorch/pytorch/blob/v1.7.1/torch/optim/swa_utils.py#L164-L165
def reset_momenta(self): """ Adapted from https://github.com/pytorch/pytorch/blob/v1.7.1/torch/optim/swa_utils.py#L164-L165 """ for bn_module in self.momenta.keys(): bn_module.momentum = self.momenta[bn_module]
[ "def", "reset_momenta", "(", "self", ")", ":", "for", "bn_module", "in", "self", ".", "momenta", ".", "keys", "(", ")", ":", "bn_module", ".", "momentum", "=", "self", ".", "momenta", "[", "bn_module", "]" ]
[ 260, 4 ]
[ 265, 56 ]
python
en
['en', 'error', 'th']
False
StochasticWeightAveraging.update_parameters
( average_model: 'pl.LightningModule', model: 'pl.LightningModule', n_averaged: torch.LongTensor, avg_fn: _AVG_FN )
Adapted from https://github.com/pytorch/pytorch/blob/v1.7.1/torch/optim/swa_utils.py#L104-L112
Adapted from https://github.com/pytorch/pytorch/blob/v1.7.1/torch/optim/swa_utils.py#L104-L112
def update_parameters( average_model: 'pl.LightningModule', model: 'pl.LightningModule', n_averaged: torch.LongTensor, avg_fn: _AVG_FN ): """ Adapted from https://github.com/pytorch/pytorch/blob/v1.7.1/torch/optim/swa_utils.py#L104-L112 """ for p_swa, p_model in zip(average_m...
[ "def", "update_parameters", "(", "average_model", ":", "'pl.LightningModule'", ",", "model", ":", "'pl.LightningModule'", ",", "n_averaged", ":", "torch", ".", "LongTensor", ",", "avg_fn", ":", "_AVG_FN", ")", ":", "for", "p_swa", ",", "p_model", "in", "zip", ...
[ 268, 4 ]
[ 280, 23 ]
python
en
['en', 'error', 'th']
False
StochasticWeightAveraging.avg_fn
( averaged_model_parameter: torch.Tensor, model_parameter: torch.Tensor, num_averaged: torch.LongTensor )
Adapted from https://github.com/pytorch/pytorch/blob/v1.7.1/torch/optim/swa_utils.py#L95-L97
Adapted from https://github.com/pytorch/pytorch/blob/v1.7.1/torch/optim/swa_utils.py#L95-L97
def avg_fn( averaged_model_parameter: torch.Tensor, model_parameter: torch.Tensor, num_averaged: torch.LongTensor ) -> torch.FloatTensor: """ Adapted from https://github.com/pytorch/pytorch/blob/v1.7.1/torch/optim/swa_utils.py#L95-L97 """ return averaged_model_parameter + (mo...
[ "def", "avg_fn", "(", "averaged_model_parameter", ":", "torch", ".", "Tensor", ",", "model_parameter", ":", "torch", ".", "Tensor", ",", "num_averaged", ":", "torch", ".", "LongTensor", ")", "->", "torch", ".", "FloatTensor", ":", "return", "averaged_model_param...
[ 283, 4 ]
[ 289, 107 ]
python
en
['en', 'error', 'th']
False
ndpointer
(dtype=None, ndim=None, shape=None, flags=None)
Array-checking restype/argtypes. An ndpointer instance is used to describe an ndarray in restypes and argtypes specifications. This approach is more flexible than using, for example, ``POINTER(c_double)``, since several restrictions can be specified, which are verified upon calling the ctypes fun...
Array-checking restype/argtypes.
def ndpointer(dtype=None, ndim=None, shape=None, flags=None): """ Array-checking restype/argtypes. An ndpointer instance is used to describe an ndarray in restypes and argtypes specifications. This approach is more flexible than using, for example, ``POINTER(c_double)``, since several restrictions...
[ "def", "ndpointer", "(", "dtype", "=", "None", ",", "ndim", "=", "None", ",", "shape", "=", "None", ",", "flags", "=", "None", ")", ":", "# normalize dtype to an Optional[dtype]", "if", "dtype", "is", "not", "None", ":", "dtype", "=", "_dtype", "(", "dty...
[ 230, 0 ]
[ 345, 16 ]
python
en
['en', 'error', 'th']
False
_concrete_ndptr._check_retval_
(self)
This method is called when this class is used as the .restype attribute for a shared-library function, to automatically wrap the pointer into an array.
This method is called when this class is used as the .restype attribute for a shared-library function, to automatically wrap the pointer into an array.
def _check_retval_(self): """ This method is called when this class is used as the .restype attribute for a shared-library function, to automatically wrap the pointer into an array. """ return self.contents
[ "def", "_check_retval_", "(", "self", ")", ":", "return", "self", ".", "contents" ]
[ 206, 4 ]
[ 212, 28 ]
python
en
['en', 'error', 'th']
False
_concrete_ndptr.contents
(self)
Get an ndarray viewing the data pointed to by this pointer. This mirrors the `contents` attribute of a normal ctypes pointer
Get an ndarray viewing the data pointed to by this pointer.
def contents(self): """ Get an ndarray viewing the data pointed to by this pointer. This mirrors the `contents` attribute of a normal ctypes pointer """ full_dtype = _dtype((self._dtype_, self._shape_)) full_ctype = ctypes.c_char * full_dtype.itemsize buffer = ct...
[ "def", "contents", "(", "self", ")", ":", "full_dtype", "=", "_dtype", "(", "(", "self", ".", "_dtype_", ",", "self", ".", "_shape_", ")", ")", "full_ctype", "=", "ctypes", ".", "c_char", "*", "full_dtype", ".", "itemsize", "buffer", "=", "ctypes", "."...
[ 215, 4 ]
[ 224, 67 ]
python
en
['en', 'error', 'th']
False
plugin
(output_descriptors)
Protoc plugin entry point. This defines protoc plugin and manages the stdin -> stdout flow. An api_proto_plugin is defined by the provided visitor. See http://www.expobrain.net/2015/09/13/create-a-plugin-for-google-protocol-buffer/ for further details on protoc plugin basics. Args: ...
Protoc plugin entry point.
def plugin(output_descriptors): """Protoc plugin entry point. This defines protoc plugin and manages the stdin -> stdout flow. An api_proto_plugin is defined by the provided visitor. See http://www.expobrain.net/2015/09/13/create-a-plugin-for-google-protocol-buffer/ for further detai...
[ "def", "plugin", "(", "output_descriptors", ")", ":", "request", "=", "plugin_pb2", ".", "CodeGeneratorRequest", "(", ")", "request", ".", "ParseFromString", "(", "sys", ".", "stdin", ".", "buffer", ".", "read", "(", ")", ")", "response", "=", "plugin_pb2", ...
[ 37, 0 ]
[ 93, 57 ]
python
en
['en', 'en', 'en']
True
_find_tensors
(obj)
r""" Recursively find all tensors contained in the specified object.
r""" Recursively find all tensors contained in the specified object.
def _find_tensors(obj): # pragma: no-cover r""" Recursively find all tensors contained in the specified object. """ if isinstance(obj, torch.Tensor): return [obj] if isinstance(obj, (list, tuple)): return itertools.chain(*map(_find_tensors, obj)) if isinstance(obj, dict): ...
[ "def", "_find_tensors", "(", "obj", ")", ":", "# pragma: no-cover", "if", "isinstance", "(", "obj", ",", "torch", ".", "Tensor", ")", ":", "return", "[", "obj", "]", "if", "isinstance", "(", "obj", ",", "(", "list", ",", "tuple", ")", ")", ":", "retu...
[ 47, 0 ]
[ 57, 13 ]
python
cy
['en', 'cy', 'hi']
False
LightningDistributedModule.__init__
(self, pl_module: LightningModule)
Wraps the user's LightningModule and redirects the forward call to the appropriate method, either ``training_step``, ``validation_step``, ``test_step`` or ``predict``. This class is used in combination with :class:`~torch.nn.parallel.DistributedDataParallel` as shown in the example. ...
Wraps the user's LightningModule and redirects the forward call to the appropriate method, either ``training_step``, ``validation_step``, ``test_step`` or ``predict``. This class is used in combination with :class:`~torch.nn.parallel.DistributedDataParallel` as shown in the example.
def __init__(self, pl_module: LightningModule): """ Wraps the user's LightningModule and redirects the forward call to the appropriate method, either ``training_step``, ``validation_step``, ``test_step`` or ``predict``. This class is used in combination with :class:`~torch.nn.parallel.Di...
[ "def", "__init__", "(", "self", ",", "pl_module", ":", "LightningModule", ")", ":", "super", "(", ")", ".", "__init__", "(", "pl_module", ")" ]
[ 25, 4 ]
[ 44, 35 ]
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_model = apps.get_model("sites", "Site") site_model.objects.update_or_create( id=settings.SITE_ID, defaults={"domain": "example.com", "name": "django_structlog_demo_project"}, )
[ "def", "update_site_forward", "(", "apps", ",", "schema_editor", ")", ":", "site_model", "=", "apps", ".", "get_model", "(", "\"sites\"", ",", "\"Site\"", ")", "site_model", ".", "objects", ".", "update_or_create", "(", "id", "=", "settings", ".", "SITE_ID", ...
[ 9, 0 ]
[ 15, 5 ]
python
en
['en', 'en', 'en']
True
is_pathlib_path
(obj)
Check whether obj is a pathlib.Path object. Prefer using `isinstance(obj, os_PathLike)` instead of this function.
Check whether obj is a pathlib.Path object.
def is_pathlib_path(obj): """ Check whether obj is a pathlib.Path object. Prefer using `isinstance(obj, os_PathLike)` instead of this function. """ return Path is not None and isinstance(obj, Path)
[ "def", "is_pathlib_path", "(", "obj", ")", ":", "return", "Path", "is", "not", "None", "and", "isinstance", "(", "obj", ",", "Path", ")" ]
[ 100, 0 ]
[ 106, 53 ]
python
en
['en', 'error', 'th']
False
MeanAbsoluteError.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_abs_error, n_obs = _mean_absolute_error_update(preds, target) self...
[ "def", "update", "(", "self", ",", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ")", ":", "sum_abs_error", ",", "n_obs", "=", "_mean_absolute_error_update", "(", "preds", ",", "target", ")", "self", ".", "sum_abs_error"...
[ 68, 4 ]
[ 79, 27 ]
python
en
['en', 'error', 'th']
False
MeanAbsoluteError.compute
(self)
Computes mean absolute error over state.
Computes mean absolute error over state.
def compute(self): """ Computes mean absolute error over state. """ return _mean_absolute_error_compute(self.sum_abs_error, self.total)
[ "def", "compute", "(", "self", ")", ":", "return", "_mean_absolute_error_compute", "(", "self", ".", "sum_abs_error", ",", "self", ".", "total", ")" ]
[ 81, 4 ]
[ 85, 75 ]
python
en
['en', 'error', 'th']
False
DDPSpawnPlugin.__getstate__
(self)
Makes this plugin pickleable without destroying the queue in the current process.
Makes this plugin pickleable without destroying the queue in the current process.
def __getstate__(self): """ Makes this plugin pickleable without destroying the queue in the current process. """ state = self.__dict__.copy() state["mp_queue"] = None return state
[ "def", "__getstate__", "(", "self", ")", ":", "state", "=", "self", ".", "__dict__", ".", "copy", "(", ")", "state", "[", "\"mp_queue\"", "]", "=", "None", "return", "state" ]
[ 63, 4 ]
[ 67, 20 ]
python
en
['en', 'en', 'en']
True
DDPSpawnPlugin.pre_backward
(self, closure_loss: torch.Tensor, should_accumulate: bool, optimizer: Optimizer, opt_idx: int)
Run before precision plugin executes backward
Run before precision plugin executes backward
def pre_backward(self, closure_loss: torch.Tensor, should_accumulate: bool, optimizer: Optimizer, opt_idx: int): """Run before precision plugin executes backward""" if not self.lightning_module.automatic_optimization and self.model.require_backward_grad_sync: prepare_for_backward(self.model,...
[ "def", "pre_backward", "(", "self", ",", "closure_loss", ":", "torch", ".", "Tensor", ",", "should_accumulate", ":", "bool", ",", "optimizer", ":", "Optimizer", ",", "opt_idx", ":", "int", ")", ":", "if", "not", "self", ".", "lightning_module", ".", "autom...
[ 253, 4 ]
[ 256, 58 ]
python
en
['eu', 'gl', 'en']
False
DDPSpawnPlugin.reduce
(self, tensor, group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = "mean")
Reduces a tensor from several distributed processes to one aggregated tensor. Args: tensor: the tensor to sync and reduce group: the process group to gather results from. Defaults to all processes (world) reduce_op: the reduction operation. Defaults to 'mean'/'avg'....
Reduces a tensor from several distributed processes to one aggregated tensor.
def reduce(self, tensor, group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = "mean"): """ Reduces a tensor from several distributed processes to one aggregated tensor. Args: tensor: the tensor to sync and reduce group: the process group to gather res...
[ "def", "reduce", "(", "self", ",", "tensor", ",", "group", ":", "Optional", "[", "Any", "]", "=", "None", ",", "reduce_op", ":", "Optional", "[", "Union", "[", "ReduceOp", ",", "str", "]", "]", "=", "\"mean\"", ")", ":", "if", "isinstance", "(", "t...
[ 258, 4 ]
[ 273, 21 ]
python
en
['en', 'error', 'th']
False
_demo_inputs
(input_shape=(1, 3, 64, 64))
Create a superset of inputs needed to run backbone. Args: input_shape (tuple): input batch dimensions. Default: (1, 3, 64, 64). Returns: Random input tensor with the size of input_shape.
Create a superset of inputs needed to run backbone.
def _demo_inputs(input_shape=(1, 3, 64, 64)): """Create a superset of inputs needed to run backbone. Args: input_shape (tuple): input batch dimensions. Default: (1, 3, 64, 64). Returns: Random input tensor with the size of input_shape. """ inps = np.random.random(input_s...
[ "def", "_demo_inputs", "(", "input_shape", "=", "(", "1", ",", "3", ",", "64", ",", "64", ")", ")", ":", "inps", "=", "np", ".", "random", ".", "random", "(", "input_shape", ")", "inps", "=", "torch", ".", "FloatTensor", "(", "inps", ")", "return",...
[ 55, 0 ]
[ 66, 15 ]
python
en
['en', 'en', 'en']
True
Precision.compute
(self)
Computes the precision score based on inputs passed in to ``update`` previously. Return: The shape of the returned tensor depends on the ``average`` parameter - If ``average in ['micro', 'macro', 'weighted', 'samples']``, a one-element tensor will be returned - If ...
Computes the precision score based on inputs passed in to ``update`` previously.
def compute(self) -> torch.Tensor: """ Computes the precision score based on inputs passed in to ``update`` previously. Return: The shape of the returned tensor depends on the ``average`` parameter - If ``average in ['micro', 'macro', 'weighted', 'samples']``, a one-ele...
[ "def", "compute", "(", "self", ")", "->", "torch", ".", "Tensor", ":", "tp", ",", "fp", ",", "tn", ",", "fn", "=", "self", ".", "_get_final_stats", "(", ")", "return", "_precision_compute", "(", "tp", ",", "fp", ",", "tn", ",", "fn", ",", "self", ...
[ 156, 4 ]
[ 168, 81 ]
python
en
['en', 'error', 'th']
False
Recall.compute
(self)
Computes the recall score based on inputs passed in to ``update`` previously. Return: The shape of the returned tensor depends on the ``average`` parameter - If ``average in ['micro', 'macro', 'weighted', 'samples']``, a one-element tensor will be returned - If ``a...
Computes the recall score based on inputs passed in to ``update`` previously.
def compute(self) -> torch.Tensor: """ Computes the recall score based on inputs passed in to ``update`` previously. Return: The shape of the returned tensor depends on the ``average`` parameter - If ``average in ['micro', 'macro', 'weighted', 'samples']``, a one-elemen...
[ "def", "compute", "(", "self", ")", "->", "torch", ".", "Tensor", ":", "tp", ",", "fp", ",", "tn", ",", "fn", "=", "self", ".", "_get_final_stats", "(", ")", "return", "_recall_compute", "(", "tp", ",", "fp", ",", "tn", ",", "fn", ",", "self", "....
[ 307, 4 ]
[ 319, 78 ]
python
en
['en', 'error', 'th']
False
plot_stack
(stack, init=0)
Not intended for jupyter lab.
Not intended for jupyter lab.
def plot_stack(stack, init=0): """Not intended for jupyter lab.""" fig, ax = plt.subplots() cut = stack[init].data cut = np.log(cut) img = ax.imshow(cut, cmap="gray") ax.set_title(f"slice {init}") def callback(val): ax.set_title(f"slice {val:.0f}") cut = stack[int(val)].data ...
[ "def", "plot_stack", "(", "stack", ",", "init", "=", "0", ")", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", ")", "cut", "=", "stack", "[", "init", "]", ".", "data", "cut", "=", "np", ".", "log", "(", "cut", ")", "img", "=", "ax", ...
[ 65, 0 ]
[ 86, 26 ]
python
en
['en', 'en', 'en']
True
plot_img
(img)
Not intended for jupyter lab.
Not intended for jupyter lab.
def plot_img(img): """Not intended for jupyter lab.""" _, ax = plt.subplots() img = ax.imshow(img.data[:, :], cmap="gray")
[ "def", "plot_img", "(", "img", ")", ":", "_", ",", "ax", "=", "plt", ".", "subplots", "(", ")", "img", "=", "ax", ".", "imshow", "(", "img", ".", "data", "[", ":", ",", ":", "]", ",", "cmap", "=", "\"gray\"", ")" ]
[ 88, 0 ]
[ 91, 48 ]
python
en
['en', 'en', 'en']
True
square
(x, y)
Draw white square with black outline at (x, y).
Draw white square with black outline at (x, y).
def square(x, y): "Draw white square with black outline at (x, y)." up() goto(x, y) down() color('black', 'white') begin_fill() for count in range(4): forward(50) left(90) end_fill()
[ "def", "square", "(", "x", ",", "y", ")", ":", "up", "(", ")", "goto", "(", "x", ",", "y", ")", "down", "(", ")", "color", "(", "'black'", ",", "'white'", ")", "begin_fill", "(", ")", "for", "count", "in", "range", "(", "4", ")", ":", "forwar...
[ 9, 0 ]
[ 19, 14 ]
python
en
['en', 'en', 'en']
True
index
(x, y)
Convert (x, y) coordinates to tiles index.
Convert (x, y) coordinates to tiles index.
def index(x, y): "Convert (x, y) coordinates to tiles index." return int((x + 200) // 50 + ((y + 200) // 50) * 8)
[ "def", "index", "(", "x", ",", "y", ")", ":", "return", "int", "(", "(", "x", "+", "200", ")", "//", "50", "+", "(", "(", "y", "+", "200", ")", "//", "50", ")", "*", "8", ")" ]
[ 21, 0 ]
[ 23, 55 ]
python
en
['en', 'nl', 'en']
True
xy
(count)
Convert tiles count to (x, y) coordinates.
Convert tiles count to (x, y) coordinates.
def xy(count): "Convert tiles count to (x, y) coordinates." return (count % 8) * 50 - 200, (count // 8) * 50 - 200
[ "def", "xy", "(", "count", ")", ":", "return", "(", "count", "%", "8", ")", "*", "50", "-", "200", ",", "(", "count", "//", "8", ")", "*", "50", "-", "200" ]
[ 25, 0 ]
[ 27, 58 ]
python
en
['en', 'nl', 'en']
True
tap
(x, y)
Update mark and hidden tiles based on tap.
Update mark and hidden tiles based on tap.
def tap(x, y): "Update mark and hidden tiles based on tap." spot = index(x, y) mark = state['mark'] if mark is None or mark == spot or tiles[mark] != tiles[spot]: state['mark'] = spot else: hide[spot] = False hide[mark] = False state['mark'] = None
[ "def", "tap", "(", "x", ",", "y", ")", ":", "spot", "=", "index", "(", "x", ",", "y", ")", "mark", "=", "state", "[", "'mark'", "]", "if", "mark", "is", "None", "or", "mark", "==", "spot", "or", "tiles", "[", "mark", "]", "!=", "tiles", "[", ...
[ 29, 0 ]
[ 39, 28 ]
python
en
['en', 'en', 'en']
True
draw
()
Draw image and tiles.
Draw image and tiles.
def draw(): "Draw image and tiles." clear() goto(0, 0) shape(car) stamp() for count in range(64): if hide[count]: x, y = xy(count) square(x, y) mark = state['mark'] if mark is not None and hide[mark]: x, y = xy(mark) up() goto(x ...
[ "def", "draw", "(", ")", ":", "clear", "(", ")", "goto", "(", "0", ",", "0", ")", "shape", "(", "car", ")", "stamp", "(", ")", "for", "count", "in", "range", "(", "64", ")", ":", "if", "hide", "[", "count", "]", ":", "x", ",", "y", "=", "...
[ 41, 0 ]
[ 63, 22 ]
python
en
['en', 'en', 'en']
True
_make_input
(t, requires_grad=False, device=torch.device('cpu'))
Make zero inputs for AE loss. Args: t (torch.Tensor): input requires_grad (bool): Option to use requires_grad. device: torch device Returns: torch.Tensor: zero input.
Make zero inputs for AE loss.
def _make_input(t, requires_grad=False, device=torch.device('cpu')): """Make zero inputs for AE loss. Args: t (torch.Tensor): input requires_grad (bool): Option to use requires_grad. device: torch device Returns: torch.Tensor: zero input. """ inp = torch.autograd.Var...
[ "def", "_make_input", "(", "t", ",", "requires_grad", "=", "False", ",", "device", "=", "torch", ".", "device", "(", "'cpu'", ")", ")", ":", "inp", "=", "torch", ".", "autograd", ".", "Variable", "(", "t", ",", "requires_grad", "=", "requires_grad", ")...
[ 11, 0 ]
[ 24, 14 ]
python
en
['eu', 'it', 'en']
False
MaxesOfDots.maxes_of_dots
(self, arrays)
A magical feature score for each feature in each dataset :ref:`Haxby et al., Neuron (2011) <HGC+11>`. If arrays are column-wise zscore-d before computation it results in characterizing each column in each array with sum of maximal correlations of that column with columns ...
A magical feature score for each feature in each dataset :ref:`Haxby et al., Neuron (2011) <HGC+11>`. If arrays are column-wise zscore-d before computation it results in characterizing each column in each array with sum of maximal correlations of that column with columns ...
def maxes_of_dots(self, arrays): """ A magical feature score for each feature in each dataset :ref:`Haxby et al., Neuron (2011) <HGC+11>`. If arrays are column-wise zscore-d before computation it results in characterizing each column in each array with sum of maximal corr...
[ "def", "maxes_of_dots", "(", "self", ",", "arrays", ")", ":", "feature_scores", "=", "(", "[", "0", "]", "*", "len", "(", "arrays", ")", ")", "for", "(", "i", ",", "sd", ")", "in", "enumerate", "(", "arrays", ")", ":", "for", "(", "j", ",", "sd...
[ 65, 4 ]
[ 85, 29 ]
python
en
['en', 'error', 'th']
False
plot_img
( img: Union[do.Image, str], fields: Optional[Union[str, Iterable[str]]] = None, field_color: Optional[str] = None, contrast: Optional[Union[str, Iterable[Number, Number]]] = None, invert: bool = False, log: bool = False, cmap: str = "gray", ax: Optional[mpl.axes.Axes] = None, title:...
Plots a single image with some metadata. Uses matplotlib's imshow() to display an image. It either takes a dataobject.Image or just the path to an image as mandatory argument. Optional arguments change the plot appearance. Parameters ---------- img : Union[do.Image, str] The image that...
Plots a single image with some metadata.
def plot_img( img: Union[do.Image, str], fields: Optional[Union[str, Iterable[str]]] = None, field_color: Optional[str] = None, contrast: Optional[Union[str, Iterable[Number, Number]]] = None, invert: bool = False, log: bool = False, cmap: str = "gray", ax: Optional[mpl.axes.Axes] = None...
[ "def", "plot_img", "(", "img", ":", "Union", "[", "do", ".", "Image", ",", "str", "]", ",", "fields", ":", "Optional", "[", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", "]", "=", "None", ",", "field_color", ":", "Optional", "[", "s...
[ 29, 0 ]
[ 166, 13 ]
python
en
['en', 'en', 'en']
True
Neighbourhood.create_neighbourhood
(self)
method to save project images :return:
method to save project images :return:
def create_neighbourhood(self): """ method to save project images :return: """ self.save()
[ "def", "create_neighbourhood", "(", "self", ")", ":", "self", ".", "save", "(", ")" ]
[ 26, 4 ]
[ 31, 19 ]
python
en
['en', 'error', 'th']
False
Neighbourhood.find_neighbourhood
(cls, neighbourhood_id)
method to get image by id :return:
method to get image by id :return:
def find_neighbourhood(cls, neighbourhood_id): """ method to get image by id :return: """ neighbourhood = cls.objects.filter(id=neighbourhood_id) return neighbourhood
[ "def", "find_neighbourhood", "(", "cls", ",", "neighbourhood_id", ")", ":", "neighbourhood", "=", "cls", ".", "objects", ".", "filter", "(", "id", "=", "neighbourhood_id", ")", "return", "neighbourhood" ]
[ 34, 4 ]
[ 40, 28 ]
python
en
['en', 'error', 'th']
False
Neighbourhood.update_neighbourhood
(cls)
method to update neighbourhood details :return:
method to update neighbourhood details :return:
def update_neighbourhood(cls): """ method to update neighbourhood details :return: """ info = cls.objects.all().update() info.save() return info
[ "def", "update_neighbourhood", "(", "cls", ")", ":", "info", "=", "cls", ".", "objects", ".", "all", "(", ")", ".", "update", "(", ")", "info", ".", "save", "(", ")", "return", "info" ]
[ 43, 4 ]
[ 50, 19 ]
python
en
['en', 'error', 'th']
False
Neighbourhood.delete_neighbourhood
(self)
method to delete image :return:
method to delete image :return:
def delete_neighbourhood(self): """ method to delete image :return: """ self.delete()
[ "def", "delete_neighbourhood", "(", "self", ")", ":", "self", ".", "delete", "(", ")" ]
[ 52, 4 ]
[ 57, 21 ]
python
en
['en', 'error', 'th']
False
Neighbourhood.search_business_hood
(cls, search_term)
method to search for business by neighbourhood :return:
method to search for business by neighbourhood :return:
def search_business_hood(cls, search_term): """ method to search for business by neighbourhood :return: """ business = cls.objects.filter(biz__name__icontains=search_term) return business
[ "def", "search_business_hood", "(", "cls", ",", "search_term", ")", ":", "business", "=", "cls", ".", "objects", ".", "filter", "(", "biz__name__icontains", "=", "search_term", ")", "return", "business" ]
[ 60, 4 ]
[ 66, 23 ]
python
en
['en', 'error', 'th']
False
Profile.create_profile
(sender, instance, created, **kwargs)
method to create profile :return:
method to create profile :return:
def create_profile(sender, instance, created, **kwargs): """ method to create profile :return: """ if created: Profile.objects.create(user=instance)
[ "def", "create_profile", "(", "sender", ",", "instance", ",", "created", ",", "*", "*", "kwargs", ")", ":", "if", "created", ":", "Profile", ".", "objects", ".", "create", "(", "user", "=", "instance", ")" ]
[ 85, 4 ]
[ 91, 49 ]
python
en
['en', 'error', 'th']
False
Profile.save_user_profile
(sender, instance,saved, **kwargs)
method to save profile :return:
method to save profile :return:
def save_user_profile(sender, instance,saved, **kwargs): """ method to save profile :return: """ if saved: Profile.objects.save(user=instance)
[ "def", "save_user_profile", "(", "sender", ",", "instance", ",", "saved", ",", "*", "*", "kwargs", ")", ":", "if", "saved", ":", "Profile", ".", "objects", ".", "save", "(", "user", "=", "instance", ")" ]
[ 94, 4 ]
[ 100, 47 ]
python
en
['en', 'error', 'th']
False
Business.find_business
(cls, search_biz)
method to find business by id :param business_id: :return:
method to find business by id :param business_id: :return:
def find_business(cls, search_biz): """ method to find business by id :param business_id: :return: """ business = cls.objects.filter(name=search_biz) return business
[ "def", "find_business", "(", "cls", ",", "search_biz", ")", ":", "business", "=", "cls", ".", "objects", ".", "filter", "(", "name", "=", "search_biz", ")", "return", "business" ]
[ 124, 4 ]
[ 131, 23 ]
python
en
['en', 'error', 'th']
False
Business.update_business
(cls)
method to update business details :return:
method to update business details :return:
def update_business(cls): """ method to update business details :return: """ biz = cls.objects.all().update() biz.save() return biz
[ "def", "update_business", "(", "cls", ")", ":", "biz", "=", "cls", ".", "objects", ".", "all", "(", ")", ".", "update", "(", ")", "biz", ".", "save", "(", ")", "return", "biz" ]
[ 134, 4 ]
[ 141, 18 ]
python
en
['en', 'error', 'th']
False
getFibonacciIterative
(n: int)
Calculate the fibonacci number at position n iteratively
Calculate the fibonacci number at position n iteratively
def getFibonacciIterative(n: int) -> int: """ Calculate the fibonacci number at position n iteratively """ a = 0 b = 1 for i in range(n): a, b = b, a + b return a
[ "def", "getFibonacciIterative", "(", "n", ":", "int", ")", "->", "int", ":", "a", "=", "0", "b", "=", "1", "for", "i", "in", "range", "(", "n", ")", ":", "a", ",", "b", "=", "b", ",", "a", "+", "b", "return", "a" ]
[ 6, 0 ]
[ 17, 12 ]
python
en
['en', 'error', 'th']
False
getFibonacciRecursive
(n: int)
Calculate the fibonacci number at position n recursively
Calculate the fibonacci number at position n recursively
def getFibonacciRecursive(n: int) -> int: """ Calculate the fibonacci number at position n recursively """ a = 0 b = 1 def step(n: int) -> int: nonlocal a, b if n <= 0: return a a, b = b, a + b return step(n - 1) return step(n)
[ "def", "getFibonacciRecursive", "(", "n", ":", "int", ")", "->", "int", ":", "a", "=", "0", "b", "=", "1", "def", "step", "(", "n", ":", "int", ")", "->", "int", ":", "nonlocal", "a", ",", "b", "if", "n", "<=", "0", ":", "return", "a", "a", ...
[ 20, 0 ]
[ 35, 18 ]
python
en
['en', 'error', 'th']
False
getFibonacciDynamic
(n: int,fib: list)
Calculate the fibonacci number at position n using dynamic programming to improve runtime
Calculate the fibonacci number at position n using dynamic programming to improve runtime
def getFibonacciDynamic(n: int,fib: list) -> int: ''' Calculate the fibonacci number at position n using dynamic programming to improve runtime ''' if n==0 or n==1: return n if fib[n]!=-1: return fib[n] fib[n]=getFibonacciDynamic(n-1,fib)+getFibonacciDynamic(n-2,fib) ret...
[ "def", "getFibonacciDynamic", "(", "n", ":", "int", ",", "fib", ":", "list", ")", "->", "int", ":", "if", "n", "==", "0", "or", "n", "==", "1", ":", "return", "n", "if", "fib", "[", "n", "]", "!=", "-", "1", ":", "return", "fib", "[", "n", ...
[ 38, 0 ]
[ 48, 17 ]
python
en
['en', 'error', 'th']
False
compareFibonacciCalculators
(n: int)
Interactively compare both fibonacci generators
Interactively compare both fibonacci generators
def compareFibonacciCalculators(n: int) -> None: """ Interactively compare both fibonacci generators """ startI = time.clock() resultI = getFibonacciIterative(n) endI = time.clock() startR = time.clock() resultR = getFibonacciRecursive(n) endR = time.clock() s = "{} calculting...
[ "def", "compareFibonacciCalculators", "(", "n", ":", "int", ")", "->", "None", ":", "startI", "=", "time", ".", "clock", "(", ")", "resultI", "=", "getFibonacciIterative", "(", "n", ")", "endI", "=", "time", ".", "clock", "(", ")", "startR", "=", "time...
[ 55, 0 ]
[ 74, 6 ]
python
en
['en', 'error', 'th']
False
lr_find
( trainer, model: LightningModule, train_dataloader: Optional[DataLoader] = None, val_dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None, min_lr: float = 1e-8, max_lr: float = 1, num_training: int = 100, mode: str = 'exponential', early_stop_threshold: float = 4.0, ...
r""" ``lr_find`` enables the user to do a range test of good initial learning rates, to reduce the amount of guesswork in picking a good starting learning rate. Args: model: Model to do range testing for train_dataloader: A PyTorch ``DataLoader`` with training samples. If the m...
r""" ``lr_find`` enables the user to do a range test of good initial learning rates, to reduce the amount of guesswork in picking a good starting learning rate.
def lr_find( trainer, model: LightningModule, train_dataloader: Optional[DataLoader] = None, val_dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None, min_lr: float = 1e-8, max_lr: float = 1, num_training: int = 100, mode: str = 'exponential', early_stop_threshold: float...
[ "def", "lr_find", "(", "trainer", ",", "model", ":", "LightningModule", ",", "train_dataloader", ":", "Optional", "[", "DataLoader", "]", "=", "None", ",", "val_dataloaders", ":", "Optional", "[", "Union", "[", "DataLoader", ",", "List", "[", "DataLoader", "...
[ 62, 0 ]
[ 202, 20 ]
python
cy
['en', 'cy', 'hi']
False
_LRFinder._exchange_scheduler
(self, configure_optimizers: Callable)
Decorate configure_optimizers methods such that it returns the users originally specified optimizer together with a new scheduler that that takes care of the learning rate search.
Decorate configure_optimizers methods such that it returns the users originally specified optimizer together with a new scheduler that that takes care of the learning rate search.
def _exchange_scheduler(self, configure_optimizers: Callable): """ Decorate configure_optimizers methods such that it returns the users originally specified optimizer together with a new scheduler that that takes care of the learning rate search. """ @wraps(configure_opt...
[ "def", "_exchange_scheduler", "(", "self", ",", "configure_optimizers", ":", "Callable", ")", ":", "@", "wraps", "(", "configure_optimizers", ")", "def", "func", "(", ")", ":", "# Decide the structure of the output from configure_optimizers", "# Same logic as method `init_o...
[ 264, 4 ]
[ 305, 19 ]
python
en
['en', 'en', 'en']
True
_LRFinder.plot
(self, suggest: bool = False, show: bool = False)
Plot results from lr_find run Args: suggest: if True, will mark suggested lr to use with a red point show: if True, will show figure
Plot results from lr_find run Args: suggest: if True, will mark suggested lr to use with a red point
def plot(self, suggest: bool = False, show: bool = False): """ Plot results from lr_find run Args: suggest: if True, will mark suggested lr to use with a red point show: if True, will show figure """ import matplotlib.pyplot as plt lrs = self.results["lr...
[ "def", "plot", "(", "self", ",", "suggest", ":", "bool", "=", "False", ",", "show", ":", "bool", "=", "False", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "lrs", "=", "self", ".", "results", "[", "\"lr\"", "]", "losses", "=", "sel...
[ 307, 4 ]
[ 336, 18 ]
python
en
['en', 'en', 'en']
True
_LRFinder.suggestion
(self, skip_begin: int = 10, skip_end: int = 1)
This will propose a suggestion for choice of initial learning rate as the point with the steepest negative gradient. Returns: lr: suggested initial learning rate to use skip_begin: how many samples to skip in the beginning. Prevent too naive estimates skip_end: how ...
This will propose a suggestion for choice of initial learning rate as the point with the steepest negative gradient.
def suggestion(self, skip_begin: int = 10, skip_end: int = 1): """ This will propose a suggestion for choice of initial learning rate as the point with the steepest negative gradient. Returns: lr: suggested initial learning rate to use skip_begin: how many samples to ski...
[ "def", "suggestion", "(", "self", ",", "skip_begin", ":", "int", "=", "10", ",", "skip_end", ":", "int", "=", "1", ")", ":", "try", ":", "loss", "=", "np", ".", "array", "(", "self", ".", "results", "[", "\"loss\"", "]", "[", "skip_begin", ":", "...
[ 338, 4 ]
[ 357, 36 ]
python
en
['en', 'en', 'en']
True
_LRCallback.on_batch_start
(self, trainer, pl_module)
Called before each training batch, logs the lr that will be used
Called before each training batch, logs the lr that will be used
def on_batch_start(self, trainer, pl_module): """ Called before each training batch, logs the lr that will be used """ if (trainer.batch_idx + 1) % trainer.accumulate_grad_batches != 0: return if self.progress_bar_refresh_rate and self.progress_bar is None: self.progress...
[ "def", "on_batch_start", "(", "self", ",", "trainer", ",", "pl_module", ")", ":", "if", "(", "trainer", ".", "batch_idx", "+", "1", ")", "%", "trainer", ".", "accumulate_grad_batches", "!=", "0", ":", "return", "if", "self", ".", "progress_bar_refresh_rate",...
[ 395, 4 ]
[ 403, 68 ]
python
en
['en', 'en', 'en']
True
_LRCallback.on_train_batch_end
(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx)
Called when the training batch ends, logs the calculated loss
Called when the training batch ends, logs the calculated loss
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): """ Called when the training batch ends, logs the calculated loss """ if (trainer.batch_idx + 1) % trainer.accumulate_grad_batches != 0: return if self.progress_bar: self.progres...
[ "def", "on_train_batch_end", "(", "self", ",", "trainer", ",", "pl_module", ",", "outputs", ",", "batch", ",", "batch_idx", ",", "dataloader_idx", ")", ":", "if", "(", "trainer", ".", "batch_idx", "+", "1", ")", "%", "trainer", ".", "accumulate_grad_batches"...
[ 405, 4 ]
[ 431, 41 ]
python
en
['en', 'en', 'en']
True
rot90
(m, k=1, axes=(0,1))
Rotate an array by 90 degrees in the plane specified by axes. Rotation direction is from the first towards the second axis. Parameters ---------- m : array_like Array of two or more dimensions. k : integer Number of times the array is rotated by 90 degrees. axes: (2,) arra...
Rotate an array by 90 degrees in the plane specified by axes.
def rot90(m, k=1, axes=(0,1)): """ Rotate an array by 90 degrees in the plane specified by axes. Rotation direction is from the first towards the second axis. Parameters ---------- m : array_like Array of two or more dimensions. k : integer Number of times the array is rota...
[ "def", "rot90", "(", "m", ",", "k", "=", "1", ",", "axes", "=", "(", "0", ",", "1", ")", ")", ":", "axes", "=", "tuple", "(", "axes", ")", "if", "len", "(", "axes", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"len(axes) must be 2.\"", ")...
[ 72, 0 ]
[ 155, 53 ]
python
en
['en', 'error', 'th']
False
flip
(m, axis=None)
Reverse the order of elements in an array along the given axis. The shape of the array is preserved, but the elements are reordered. .. versionadded:: 1.12.0 Parameters ---------- m : array_like Input array. axis : None or int or tuple of ints, optional Axis or axes alon...
Reverse the order of elements in an array along the given axis.
def flip(m, axis=None): """ Reverse the order of elements in an array along the given axis. The shape of the array is preserved, but the elements are reordered. .. versionadded:: 1.12.0 Parameters ---------- m : array_like Input array. axis : None or int or tuple of ints, opti...
[ "def", "flip", "(", "m", ",", "axis", "=", "None", ")", ":", "if", "not", "hasattr", "(", "m", ",", "'ndim'", ")", ":", "m", "=", "asarray", "(", "m", ")", "if", "axis", "is", "None", ":", "indexer", "=", "(", "np", ".", "s_", "[", ":", ":"...
[ 163, 0 ]
[ 253, 21 ]
python
en
['en', 'error', 'th']
False
iterable
(y)
Check whether or not an object can be iterated over. Parameters ---------- y : object Input object. Returns ------- b : bool Return ``True`` if the object has an iterator method or is a sequence and ``False`` otherwise. Examples -------- >>> np.iterable([1,...
Check whether or not an object can be iterated over.
def iterable(y): """ Check whether or not an object can be iterated over. Parameters ---------- y : object Input object. Returns ------- b : bool Return ``True`` if the object has an iterator method or is a sequence and ``False`` otherwise. Examples --------...
[ "def", "iterable", "(", "y", ")", ":", "try", ":", "iter", "(", "y", ")", "except", "TypeError", ":", "return", "False", "return", "True" ]
[ 257, 0 ]
[ 285, 15 ]
python
en
['en', 'error', 'th']
False
average
(a, axis=None, weights=None, returned=False)
Compute the weighted average along the specified axis. Parameters ---------- a : array_like Array containing data to be averaged. If `a` is not an array, a conversion is attempted. axis : None or int or tuple of ints, optional Axis or axes along which to average `a`. The d...
Compute the weighted average along the specified axis.
def average(a, axis=None, weights=None, returned=False): """ Compute the weighted average along the specified axis. Parameters ---------- a : array_like Array containing data to be averaged. If `a` is not an array, a conversion is attempted. axis : None or int or tuple of ints, ...
[ "def", "average", "(", "a", ",", "axis", "=", "None", ",", "weights", "=", "None", ",", "returned", "=", "False", ")", ":", "a", "=", "np", ".", "asanyarray", "(", "a", ")", "if", "weights", "is", "None", ":", "avg", "=", "a", ".", "mean", "(",...
[ 293, 0 ]
[ 428, 18 ]
python
en
['en', 'error', 'th']
False
asarray_chkfinite
(a, dtype=None, order=None)
Convert the input to an array, checking for NaNs or Infs. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. Success requires no NaNs or Infs....
Convert the input to an array, checking for NaNs or Infs.
def asarray_chkfinite(a, dtype=None, order=None): """Convert the input to an array, checking for NaNs or Infs. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples ...
[ "def", "asarray_chkfinite", "(", "a", ",", "dtype", "=", "None", ",", "order", "=", "None", ")", ":", "a", "=", "asarray", "(", "a", ",", "dtype", "=", "dtype", ",", "order", "=", "order", ")", "if", "a", ".", "dtype", ".", "char", "in", "typecod...
[ 432, 0 ]
[ 496, 12 ]
python
en
['en', 'en', 'en']
True
piecewise
(x, condlist, funclist, *args, **kw)
Evaluate a piecewise-defined function. Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its condition is true. Parameters ---------- x : ndarray or scalar The input domain. condlist : list of bool arrays or bool scalars ...
Evaluate a piecewise-defined function.
def piecewise(x, condlist, funclist, *args, **kw): """ Evaluate a piecewise-defined function. Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its condition is true. Parameters ---------- x : ndarray or scalar The input domain...
[ "def", "piecewise", "(", "x", ",", "condlist", ",", "funclist", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "x", "=", "asanyarray", "(", "x", ")", "n2", "=", "len", "(", "funclist", ")", "# undocumented: single condition is promoted to a list of one con...
[ 508, 0 ]
[ 626, 12 ]
python
en
['en', 'error', 'th']
False
select
(condlist, choicelist, default=0)
Return an array drawn from elements in choicelist, depending on conditions. Parameters ---------- condlist : list of bool ndarrays The list of conditions which determine from which array in `choicelist` the output elements are taken. When multiple conditions are satisfied, the ...
Return an array drawn from elements in choicelist, depending on conditions.
def select(condlist, choicelist, default=0): """ Return an array drawn from elements in choicelist, depending on conditions. Parameters ---------- condlist : list of bool ndarrays The list of conditions which determine from which array in `choicelist` the output elements are taken. ...
[ "def", "select", "(", "condlist", ",", "choicelist", ",", "default", "=", "0", ")", ":", "# Check the size of condlist and choicelist are the same, or abort.", "if", "len", "(", "condlist", ")", "!=", "len", "(", "choicelist", ")", ":", "raise", "ValueError", "(",...
[ 637, 0 ]
[ 737, 17 ]
python
en
['en', 'error', 'th']
False
copy
(a, order='K')
Return an array copy of the given object. Parameters ---------- a : array_like Input data. order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise....
Return an array copy of the given object.
def copy(a, order='K'): """ Return an array copy of the given object. Parameters ---------- a : array_like Input data. order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran con...
[ "def", "copy", "(", "a", ",", "order", "=", "'K'", ")", ":", "return", "array", "(", "a", ",", "order", "=", "order", ",", "copy", "=", "True", ")" ]
[ 745, 0 ]
[ 789, 43 ]
python
en
['en', 'error', 'th']
False
gradient
(f, *varargs, **kwargs)
Return the gradient of an N-dimensional array. The gradient is computed using second order accurate central differences in the interior points and either first or second order accurate one-sides (forward or backwards) differences at the boundaries. The returned gradient hence has the same shape as...
Return the gradient of an N-dimensional array.
def gradient(f, *varargs, **kwargs): """ Return the gradient of an N-dimensional array. The gradient is computed using second order accurate central differences in the interior points and either first or second order accurate one-sides (forward or backwards) differences at the boundaries. The r...
[ "def", "gradient", "(", "f", ",", "*", "varargs", ",", "*", "*", "kwargs", ")", ":", "f", "=", "np", ".", "asanyarray", "(", "f", ")", "N", "=", "f", ".", "ndim", "# number of dimensions", "axes", "=", "kwargs", ".", "pop", "(", "'axis'", ",", "N...
[ 801, 0 ]
[ 1139, 22 ]
python
en
['en', 'error', 'th']
False
diff
(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue)
Calculate the n-th discrete difference along the given axis. The first difference is given by ``out[i] = a[i+1] - a[i]`` along the given axis, higher differences are calculated by using `diff` recursively. Parameters ---------- a : array_like Input array n : int, optional ...
Calculate the n-th discrete difference along the given axis.
def diff(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue): """ Calculate the n-th discrete difference along the given axis. The first difference is given by ``out[i] = a[i+1] - a[i]`` along the given axis, higher differences are calculated by using `diff` recursively. Parameters -...
[ "def", "diff", "(", "a", ",", "n", "=", "1", ",", "axis", "=", "-", "1", ",", "prepend", "=", "np", ".", "_NoValue", ",", "append", "=", "np", ".", "_NoValue", ")", ":", "if", "n", "==", "0", ":", "return", "a", "if", "n", "<", "0", ":", ...
[ 1147, 0 ]
[ 1274, 12 ]
python
en
['en', 'error', 'th']
False
interp
(x, xp, fp, left=None, right=None, period=None)
One-dimensional linear interpolation. Returns the one-dimensional piecewise linear interpolant to a function with given discrete data points (`xp`, `fp`), evaluated at `x`. Parameters ---------- x : array_like The x-coordinates at which to evaluate the interpolated values. xp : 1...
One-dimensional linear interpolation.
def interp(x, xp, fp, left=None, right=None, period=None): """ One-dimensional linear interpolation. Returns the one-dimensional piecewise linear interpolant to a function with given discrete data points (`xp`, `fp`), evaluated at `x`. Parameters ---------- x : array_like The x-coo...
[ "def", "interp", "(", "x", ",", "xp", ",", "fp", ",", "left", "=", "None", ",", "right", "=", "None", ",", "period", "=", "None", ")", ":", "fp", "=", "np", ".", "asarray", "(", "fp", ")", "if", "np", ".", "iscomplexobj", "(", "fp", ")", ":",...
[ 1282, 0 ]
[ 1411, 46 ]
python
en
['en', 'error', 'th']
False
angle
(z, deg=False)
Return the angle of the complex argument. Parameters ---------- z : array_like A complex number or sequence of complex numbers. deg : bool, optional Return angle in degrees if True, radians if False (default). Returns ------- angle : ndarray or scalar The count...
Return the angle of the complex argument.
def angle(z, deg=False): """ Return the angle of the complex argument. Parameters ---------- z : array_like A complex number or sequence of complex numbers. deg : bool, optional Return angle in degrees if True, radians if False (default). Returns ------- angle : nda...
[ "def", "angle", "(", "z", ",", "deg", "=", "False", ")", ":", "z", "=", "asanyarray", "(", "z", ")", "if", "issubclass", "(", "z", ".", "dtype", ".", "type", ",", "_nx", ".", "complexfloating", ")", ":", "zimag", "=", "z", ".", "imag", "zreal", ...
[ 1419, 0 ]
[ 1463, 12 ]
python
en
['en', 'error', 'th']
False
unwrap
(p, discont=pi, axis=-1)
Unwrap by changing deltas between values to 2*pi complement. Unwrap radian phase `p` by changing absolute jumps greater than `discont` to their 2*pi complement along the given axis. Parameters ---------- p : array_like Input array. discont : float, optional Maximum discont...
Unwrap by changing deltas between values to 2*pi complement.
def unwrap(p, discont=pi, axis=-1): """ Unwrap by changing deltas between values to 2*pi complement. Unwrap radian phase `p` by changing absolute jumps greater than `discont` to their 2*pi complement along the given axis. Parameters ---------- p : array_like Input array. discon...
[ "def", "unwrap", "(", "p", ",", "discont", "=", "pi", ",", "axis", "=", "-", "1", ")", ":", "p", "=", "asarray", "(", "p", ")", "nd", "=", "p", ".", "ndim", "dd", "=", "diff", "(", "p", ",", "axis", "=", "axis", ")", "slice1", "=", "[", "...
[ 1471, 0 ]
[ 1524, 13 ]
python
en
['en', 'error', 'th']
False
sort_complex
(a)
Sort a complex array using the real part first, then the imaginary part. Parameters ---------- a : array_like Input array Returns ------- out : complex ndarray Always returns a sorted complex array. Examples -------- >>> np.sort_complex([5, 3, 6, 2, 1]) ar...
Sort a complex array using the real part first, then the imaginary part.
def sort_complex(a): """ Sort a complex array using the real part first, then the imaginary part. Parameters ---------- a : array_like Input array Returns ------- out : complex ndarray Always returns a sorted complex array. Examples -------- >>> np.sort_com...
[ "def", "sort_complex", "(", "a", ")", ":", "b", "=", "array", "(", "a", ",", "copy", "=", "True", ")", "b", ".", "sort", "(", ")", "if", "not", "issubclass", "(", "b", ".", "dtype", ".", "type", ",", "_nx", ".", "complexfloating", ")", ":", "if...
[ 1532, 0 ]
[ 1565, 16 ]
python
en
['en', 'error', 'th']
False
trim_zeros
(filt, trim='fb')
Trim the leading and/or trailing zeros from a 1-D array or sequence. Parameters ---------- filt : 1-D array or sequence Input array. trim : str, optional A string with 'f' representing trim from front and 'b' to trim from back. Default is 'fb', trim zeros from both front an...
Trim the leading and/or trailing zeros from a 1-D array or sequence.
def trim_zeros(filt, trim='fb'): """ Trim the leading and/or trailing zeros from a 1-D array or sequence. Parameters ---------- filt : 1-D array or sequence Input array. trim : str, optional A string with 'f' representing trim from front and 'b' to trim from back. Defaul...
[ "def", "trim_zeros", "(", "filt", ",", "trim", "=", "'fb'", ")", ":", "first", "=", "0", "trim", "=", "trim", ".", "upper", "(", ")", "if", "'F'", "in", "trim", ":", "for", "i", "in", "filt", ":", "if", "i", "!=", "0.", ":", "break", "else", ...
[ 1573, 0 ]
[ 1621, 27 ]
python
en
['en', 'error', 'th']
False
extract
(condition, arr)
Return the elements of an array that satisfy some condition. This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If `condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``. Note that `place` does the exact opposite of `extract`. Parameters ---------- c...
Return the elements of an array that satisfy some condition.
def extract(condition, arr): """ Return the elements of an array that satisfy some condition. This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If `condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``. Note that `place` does the exact opposite of `extract`. ...
[ "def", "extract", "(", "condition", ",", "arr", ")", ":", "return", "_nx", ".", "take", "(", "ravel", "(", "arr", ")", ",", "nonzero", "(", "ravel", "(", "condition", ")", ")", "[", "0", "]", ")" ]
[ 1628, 0 ]
[ 1676, 61 ]
python
en
['en', 'error', 'th']
False
place
(arr, mask, vals)
Change elements of an array based on conditional and input values. Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that `place` uses the first N elements of `vals`, where N is the number of True values in `mask`, while `copyto` uses the elements where `mask` is True. Note t...
Change elements of an array based on conditional and input values.
def place(arr, mask, vals): """ Change elements of an array based on conditional and input values. Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that `place` uses the first N elements of `vals`, where N is the number of True values in `mask`, while `copyto` uses the elements wh...
[ "def", "place", "(", "arr", ",", "mask", ",", "vals", ")", ":", "if", "not", "isinstance", "(", "arr", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "\"argument 1 must be numpy.ndarray, \"", "\"not {name}\"", ".", "format", "(", "name", "...
[ 1684, 0 ]
[ 1724, 35 ]
python
en
['en', 'error', 'th']
False
disp
(mesg, device=None, linefeed=True)
Display a message on a device. Parameters ---------- mesg : str Message to display. device : object Device to write message. If None, defaults to ``sys.stdout`` which is very similar to ``print``. `device` needs to have ``write()`` and ``flush()`` methods. linef...
Display a message on a device.
def disp(mesg, device=None, linefeed=True): """ Display a message on a device. Parameters ---------- mesg : str Message to display. device : object Device to write message. If None, defaults to ``sys.stdout`` which is very similar to ``print``. `device` needs to have ``w...
[ "def", "disp", "(", "mesg", ",", "device", "=", "None", ",", "linefeed", "=", "True", ")", ":", "if", "device", "is", "None", ":", "device", "=", "sys", ".", "stdout", "if", "linefeed", ":", "device", ".", "write", "(", "'%s\\n'", "%", "mesg", ")",...
[ 1727, 0 ]
[ 1766, 10 ]
python
en
['en', 'error', 'th']
False
_parse_gufunc_signature
(signature)
Parse string signatures for a generalized universal function. Arguments --------- signature : string Generalized universal function signature, e.g., ``(m,n),(n,p)->(m,p)`` for ``np.matmul``. Returns ------- Tuple of input and output core dimensions parsed from the signatur...
Parse string signatures for a generalized universal function.
def _parse_gufunc_signature(signature): """ Parse string signatures for a generalized universal function. Arguments --------- signature : string Generalized universal function signature, e.g., ``(m,n),(n,p)->(m,p)`` for ``np.matmul``. Returns ------- Tuple of input and ...
[ "def", "_parse_gufunc_signature", "(", "signature", ")", ":", "if", "not", "re", ".", "match", "(", "_SIGNATURE", ",", "signature", ")", ":", "raise", "ValueError", "(", "'not a valid gufunc signature: {}'", ".", "format", "(", "signature", ")", ")", "return", ...
[ 1777, 0 ]
[ 1797, 55 ]
python
en
['en', 'error', 'th']
False
_update_dim_sizes
(dim_sizes, arg, core_dims)
Incrementally check and update core dimension sizes for a single argument. Arguments --------- dim_sizes : Dict[str, int] Sizes of existing core dimensions. Will be updated in-place. arg : ndarray Argument to examine. core_dims : Tuple[str, ...] Core dimensions for this...
Incrementally check and update core dimension sizes for a single argument.
def _update_dim_sizes(dim_sizes, arg, core_dims): """ Incrementally check and update core dimension sizes for a single argument. Arguments --------- dim_sizes : Dict[str, int] Sizes of existing core dimensions. Will be updated in-place. arg : ndarray Argument to examine. cor...
[ "def", "_update_dim_sizes", "(", "dim_sizes", ",", "arg", ",", "core_dims", ")", ":", "if", "not", "core_dims", ":", "return", "num_core_dims", "=", "len", "(", "core_dims", ")", "if", "arg", ".", "ndim", "<", "num_core_dims", ":", "raise", "ValueError", "...
[ 1800, 0 ]
[ 1831, 33 ]
python
en
['en', 'error', 'th']
False
_parse_input_dimensions
(args, input_core_dims)
Parse broadcast and core dimensions for vectorize with a signature. Arguments --------- args : Tuple[ndarray, ...] Tuple of input arguments to examine. input_core_dims : List[Tuple[str, ...]] List of core dimensions corresponding to each input. Returns ------- broadcas...
Parse broadcast and core dimensions for vectorize with a signature.
def _parse_input_dimensions(args, input_core_dims): """ Parse broadcast and core dimensions for vectorize with a signature. Arguments --------- args : Tuple[ndarray, ...] Tuple of input arguments to examine. input_core_dims : List[Tuple[str, ...]] List of core dimensions corresp...
[ "def", "_parse_input_dimensions", "(", "args", ",", "input_core_dims", ")", ":", "broadcast_args", "=", "[", "]", "dim_sizes", "=", "{", "}", "for", "arg", ",", "core_dims", "in", "zip", "(", "args", ",", "input_core_dims", ")", ":", "_update_dim_sizes", "("...
[ 1834, 0 ]
[ 1860, 37 ]
python
en
['en', 'error', 'th']
False
_calculate_shapes
(broadcast_shape, dim_sizes, list_of_core_dims)
Helper for calculating broadcast shapes with core dimensions.
Helper for calculating broadcast shapes with core dimensions.
def _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims): """Helper for calculating broadcast shapes with core dimensions.""" return [broadcast_shape + tuple(dim_sizes[dim] for dim in core_dims) for core_dims in list_of_core_dims]
[ "def", "_calculate_shapes", "(", "broadcast_shape", ",", "dim_sizes", ",", "list_of_core_dims", ")", ":", "return", "[", "broadcast_shape", "+", "tuple", "(", "dim_sizes", "[", "dim", "]", "for", "dim", "in", "core_dims", ")", "for", "core_dims", "in", "list_o...
[ 1863, 0 ]
[ 1866, 47 ]
python
en
['en', 'en', 'en']
True
_create_arrays
(broadcast_shape, dim_sizes, list_of_core_dims, dtypes)
Helper for creating output arrays in vectorize.
Helper for creating output arrays in vectorize.
def _create_arrays(broadcast_shape, dim_sizes, list_of_core_dims, dtypes): """Helper for creating output arrays in vectorize.""" shapes = _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims) arrays = tuple(np.empty(shape, dtype=dtype) for shape, dtype in zip(shapes, dtypes)) ...
[ "def", "_create_arrays", "(", "broadcast_shape", ",", "dim_sizes", ",", "list_of_core_dims", ",", "dtypes", ")", ":", "shapes", "=", "_calculate_shapes", "(", "broadcast_shape", ",", "dim_sizes", ",", "list_of_core_dims", ")", "arrays", "=", "tuple", "(", "np", ...
[ 1869, 0 ]
[ 1874, 17 ]
python
en
['en', 'en', 'en']
True
cov
(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)
Estimate a covariance matrix, given data and weights. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`, then the covariance matrix element :math:`C_{ij}` is the covariance of :math:`x_i` and :math:`x_j`. The...
Estimate a covariance matrix, given data and weights.
def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None): """ Estimate a covariance matrix, given data and weights. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`, then t...
[ "def", "cov", "(", "m", ",", "y", "=", "None", ",", "rowvar", "=", "True", ",", "bias", "=", "False", ",", "ddof", "=", "None", ",", "fweights", "=", "None", ",", "aweights", "=", "None", ")", ":", "# Check inputs", "if", "ddof", "is", "not", "No...
[ 2245, 0 ]
[ 2455, 22 ]
python
en
['en', 'error', 'th']
False
corrcoef
(x, y=None, rowvar=True, bias=np._NoValue, ddof=np._NoValue)
Return Pearson product-moment correlation coefficients. Please refer to the documentation for `cov` for more detail. The relationship between the correlation coefficient matrix, `R`, and the covariance matrix, `C`, is .. math:: R_{ij} = \\frac{ C_{ij} } { \\sqrt{ C_{ii} * C_{jj} } } The val...
Return Pearson product-moment correlation coefficients.
def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, ddof=np._NoValue): """ Return Pearson product-moment correlation coefficients. Please refer to the documentation for `cov` for more detail. The relationship between the correlation coefficient matrix, `R`, and the covariance matrix, `C`, is ...
[ "def", "corrcoef", "(", "x", ",", "y", "=", "None", ",", "rowvar", "=", "True", ",", "bias", "=", "np", ".", "_NoValue", ",", "ddof", "=", "np", ".", "_NoValue", ")", ":", "if", "bias", "is", "not", "np", ".", "_NoValue", "or", "ddof", "is", "n...
[ 2463, 0 ]
[ 2543, 12 ]
python
en
['en', 'error', 'th']
False
blackman
(M)
Return the Blackman window. The Blackman window is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window. Parameters ---------- M : int ...
Return the Blackman window.
def blackman(M): """ Return the Blackman window. The Blackman window is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window. Parameters ...
[ "def", "blackman", "(", "M", ")", ":", "if", "M", "<", "1", ":", "return", "array", "(", "[", "]", ")", "if", "M", "==", "1", ":", "return", "ones", "(", "1", ",", "float", ")", "n", "=", "arange", "(", "0", ",", "M", ")", "return", "0.42",...
[ 2547, 0 ]
[ 2643, 68 ]
python
en
['en', 'error', 'th']
False