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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
Random.vonmisesvariate | (self, mu, kappa) | Circular data distribution.
mu is the mean angle, expressed in radians between 0 and 2*pi, and
kappa is the concentration parameter, which must be greater than or
equal to zero. If kappa is equal to zero, this distribution reduces
to a uniform random angle over the range 0 to 2*pi.
... | Circular data distribution. | def vonmisesvariate(self, mu, kappa):
"""Circular data distribution.
mu is the mean angle, expressed in radians between 0 and 2*pi, and
kappa is the concentration parameter, which must be greater than or
equal to zero. If kappa is equal to zero, this distribution reduces
to a u... | [
"def",
"vonmisesvariate",
"(",
"self",
",",
"mu",
",",
"kappa",
")",
":",
"# mu: mean angle (in radians between 0 and 2*pi)",
"# kappa: concentration parameter kappa (>= 0)",
"# if kappa = 0 generate uniform random angle",
"# Based upon an algorithm published in: Fisher, N.I.,",
"# \"... | [
452,
4
] | [
496,
20
] | python | en | ['it', 'su', 'en'] | False |
Random.gammavariate | (self, alpha, beta) | Gamma distribution. Not the gamma function!
Conditions on the parameters are alpha > 0 and beta > 0.
The probability distribution function is:
x ** (alpha - 1) * math.exp(-x / beta)
pdf(x) = --------------------------------------
math.gamma(alpha)... | Gamma distribution. Not the gamma function! | def gammavariate(self, alpha, beta):
"""Gamma distribution. Not the gamma function!
Conditions on the parameters are alpha > 0 and beta > 0.
The probability distribution function is:
x ** (alpha - 1) * math.exp(-x / beta)
pdf(x) = ------------------------------... | [
"def",
"gammavariate",
"(",
"self",
",",
"alpha",
",",
"beta",
")",
":",
"# alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2",
"# Warning: a few older sources define the gamma distribution in terms",
"# of alpha > -1.0",
"if",
"alpha",
"<=",
"0.0",
"or",
"beta",... | [
500,
4
] | [
568,
27
] | python | en | ['en', 'en', 'en'] | True |
Random.gauss | (self, mu, sigma) | Gaussian distribution.
mu is the mean, and sigma is the standard deviation. This is
slightly faster than the normalvariate() function.
Not thread-safe without a lock around calls.
| Gaussian distribution. | def gauss(self, mu, sigma):
"""Gaussian distribution.
mu is the mean, and sigma is the standard deviation. This is
slightly faster than the normalvariate() function.
Not thread-safe without a lock around calls.
"""
# When x and y are two variables from [0, 1), unifor... | [
"def",
"gauss",
"(",
"self",
",",
"mu",
",",
"sigma",
")",
":",
"# When x and y are two variables from [0, 1), uniformly",
"# distributed, then",
"#",
"# cos(2*pi*x)*sqrt(-2*log(1-y))",
"# sin(2*pi*x)*sqrt(-2*log(1-y))",
"#",
"# are two *independent* variables with normal distr... | [
572,
4
] | [
609,
27
] | python | en | ['nl', 'zh-Latn', 'en'] | False |
Random.betavariate | (self, alpha, beta) | Beta distribution.
Conditions on the parameters are alpha > 0 and beta > 0.
Returned values range between 0 and 1.
| Beta distribution. | def betavariate(self, alpha, beta):
"""Beta distribution.
Conditions on the parameters are alpha > 0 and beta > 0.
Returned values range between 0 and 1.
"""
# This version due to Janne Sinkkonen, and matches all the std
# texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta... | [
"def",
"betavariate",
"(",
"self",
",",
"alpha",
",",
"beta",
")",
":",
"# This version due to Janne Sinkkonen, and matches all the std",
"# texts (e.g., Knuth Vol 2 Ed 3 pg 134 \"the beta distribution\").",
"y",
"=",
"self",
".",
"gammavariate",
"(",
"alpha",
",",
"1.0",
"... | [
625,
4
] | [
639,
57
] | python | ceb | ['it', 'ceb', 'en'] | False |
Random.paretovariate | (self, alpha) | Pareto distribution. alpha is the shape parameter. | Pareto distribution. alpha is the shape parameter. | def paretovariate(self, alpha):
"""Pareto distribution. alpha is the shape parameter."""
# Jain, pg. 495
u = 1.0 - self.random()
return 1.0 / u ** (1.0/alpha) | [
"def",
"paretovariate",
"(",
"self",
",",
"alpha",
")",
":",
"# Jain, pg. 495",
"u",
"=",
"1.0",
"-",
"self",
".",
"random",
"(",
")",
"return",
"1.0",
"/",
"u",
"**",
"(",
"1.0",
"/",
"alpha",
")"
] | [
643,
4
] | [
648,
37
] | python | en | ['en', 'fr', 'en'] | True |
Random.weibullvariate | (self, alpha, beta) | Weibull distribution.
alpha is the scale parameter and beta is the shape parameter.
| Weibull distribution. | def weibullvariate(self, alpha, beta):
"""Weibull distribution.
alpha is the scale parameter and beta is the shape parameter.
"""
# Jain, pg. 499; bug fix courtesy Bill Arms
u = 1.0 - self.random()
return alpha * (-_log(u)) ** (1.0/beta) | [
"def",
"weibullvariate",
"(",
"self",
",",
"alpha",
",",
"beta",
")",
":",
"# Jain, pg. 499; bug fix courtesy Bill Arms",
"u",
"=",
"1.0",
"-",
"self",
".",
"random",
"(",
")",
"return",
"alpha",
"*",
"(",
"-",
"_log",
"(",
"u",
")",
")",
"**",
"(",
"1... | [
652,
4
] | [
661,
47
] | python | en | ['sv', 'ny', 'en'] | False |
SystemRandom.random | (self) | Get the next random number in the range [0.0, 1.0). | Get the next random number in the range [0.0, 1.0). | def random(self):
"""Get the next random number in the range [0.0, 1.0)."""
return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF | [
"def",
"random",
"(",
"self",
")",
":",
"return",
"(",
"int",
".",
"from_bytes",
"(",
"_urandom",
"(",
"7",
")",
",",
"'big'",
")",
">>",
"3",
")",
"*",
"RECIP_BPF"
] | [
673,
4
] | [
675,
68
] | python | en | ['en', 'en', 'en'] | True |
SystemRandom.getrandbits | (self, k) | getrandbits(k) -> x. Generates an int with k random bits. | getrandbits(k) -> x. Generates an int with k random bits. | def getrandbits(self, k):
"""getrandbits(k) -> x. Generates an int with k random bits."""
if k <= 0:
raise ValueError('number of bits must be greater than zero')
if k != int(k):
raise TypeError('number of bits should be an integer')
numbytes = (k + 7) // 8 ... | [
"def",
"getrandbits",
"(",
"self",
",",
"k",
")",
":",
"if",
"k",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'number of bits must be greater than zero'",
")",
"if",
"k",
"!=",
"int",
"(",
"k",
")",
":",
"raise",
"TypeError",
"(",
"'number of bits should be... | [
677,
4
] | [
685,
38
] | python | en | ['en', 'ca', 'en'] | True |
SystemRandom.seed | (self, *args, **kwds) | Stub method. Not used for a system random number generator. | Stub method. Not used for a system random number generator. | def seed(self, *args, **kwds):
"Stub method. Not used for a system random number generator."
return None | [
"def",
"seed",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"None"
] | [
687,
4
] | [
689,
19
] | python | en | ['en', 'en', 'en'] | True |
SystemRandom._notimplemented | (self, *args, **kwds) | Method should not be called for a system random number generator. | Method should not be called for a system random number generator. | def _notimplemented(self, *args, **kwds):
"Method should not be called for a system random number generator."
raise NotImplementedError('System entropy source does not have state.') | [
"def",
"_notimplemented",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"raise",
"NotImplementedError",
"(",
"'System entropy source does not have state.'",
")"
] | [
691,
4
] | [
693,
79
] | python | en | ['en', 'en', 'en'] | True |
gen_random_resource_name | (resource="", timestamp=True) | Generate random resource name using uuid and timestamp.
Input fields are usually limited to 255 or 80 characters hence their
provide enough space for quite long resource names, but it might be
the case that maximum field length is quite restricted, it is then
necessary to consider using shorter resourc... | Generate random resource name using uuid and timestamp. | def gen_random_resource_name(resource="", timestamp=True):
"""Generate random resource name using uuid and timestamp.
Input fields are usually limited to 255 or 80 characters hence their
provide enough space for quite long resource names, but it might be
the case that maximum field length is quite rest... | [
"def",
"gen_random_resource_name",
"(",
"resource",
"=",
"\"\"",
",",
"timestamp",
"=",
"True",
")",
":",
"fields",
"=",
"[",
"\"horizon\"",
"]",
"if",
"resource",
":",
"fields",
".",
"append",
"(",
"resource",
")",
"if",
"timestamp",
":",
"tstamp",
"=",
... | [
60,
0
] | [
76,
27
] | python | en | ['en', 'en', 'en'] | True |
gen_temporary_file | (name='', suffix='.qcow2', size=10485760) | Generate temporary file with provided parameters.
:param name: file name except the extension /suffix
:param suffix: file extension/suffix
:param size: size of the file to create, bytes are generated randomly
:return: path to the generated file
| Generate temporary file with provided parameters. | def gen_temporary_file(name='', suffix='.qcow2', size=10485760):
"""Generate temporary file with provided parameters.
:param name: file name except the extension /suffix
:param suffix: file extension/suffix
:param size: size of the file to create, bytes are generated randomly
:return: path to the g... | [
"def",
"gen_temporary_file",
"(",
"name",
"=",
"''",
",",
"suffix",
"=",
"'.qcow2'",
",",
"size",
"=",
"10485760",
")",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"prefix",
"=",
"name",
",",
"suffix",
"=",
"suffix",
")",
"as",
"tmp_file",
"... | [
80,
0
] | [
90,
27
] | python | en | ['en', 'en', 'en'] | True |
is_archive_file | (name) | Return True if `name` is a considered as an archive file. | Return True if `name` is a considered as an archive file. | def is_archive_file(name):
# type: (str) -> bool
"""Return True if `name` is a considered as an archive file."""
ext = splitext(name)[1].lower()
if ext in ARCHIVE_EXTENSIONS:
return True
return False | [
"def",
"is_archive_file",
"(",
"name",
")",
":",
"# type: (str) -> bool",
"ext",
"=",
"splitext",
"(",
"name",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"if",
"ext",
"in",
"ARCHIVE_EXTENSIONS",
":",
"return",
"True",
"return",
"False"
] | [
48,
0
] | [
54,
16
] | python | en | ['en', 'en', 'en'] | True |
parse_editable | (editable_req) | Parses an editable requirement into:
- a requirement name
- an URL
- extras
- editable options
Accepted requirements:
svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir
.[some_extra]
| Parses an editable requirement into:
- a requirement name
- an URL
- extras
- editable options
Accepted requirements:
svn+http://blahblah | def parse_editable(editable_req):
# type: (str) -> Tuple[Optional[str], str, Set[str]]
"""Parses an editable requirement into:
- a requirement name
- an URL
- extras
- editable options
Accepted requirements:
svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version... | [
"def",
"parse_editable",
"(",
"editable_req",
")",
":",
"# type: (str) -> Tuple[Optional[str], str, Set[str]]",
"url",
"=",
"editable_req",
"# If a file path is specified with extras, strip off the extras.",
"url_no_extras",
",",
"extras",
"=",
"_strip_extras",
"(",
"url",
")",
... | [
77,
0
] | [
149,
35
] | python | en | ['en', 'en', 'en'] | True |
deduce_helpful_msg | (req) | Returns helpful msg in case requirements file does not exist,
or cannot be parsed.
:params req: Requirements file path
| Returns helpful msg in case requirements file does not exist,
or cannot be parsed. | def deduce_helpful_msg(req):
# type: (str) -> str
"""Returns helpful msg in case requirements file does not exist,
or cannot be parsed.
:params req: Requirements file path
"""
msg = ""
if os.path.exists(req):
msg = " It does exist."
# Try to parse and check if it is a requir... | [
"def",
"deduce_helpful_msg",
"(",
"req",
")",
":",
"# type: (str) -> str",
"msg",
"=",
"\"\"",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"req",
")",
":",
"msg",
"=",
"\" It does exist.\"",
"# Try to parse and check if it is a requirements file.",
"try",
":",
"w... | [
152,
0
] | [
180,
14
] | python | en | ['en', 'en', 'en'] | True |
_looks_like_path | (name) | Checks whether the string "looks like" a path on the filesystem.
This does not check whether the target actually exists, only judge from the
appearance.
Returns true if any of the following conditions is true:
* a path separator is found (either os.path.sep or os.path.altsep);
* a dot is found (wh... | Checks whether the string "looks like" a path on the filesystem. | def _looks_like_path(name):
# type: (str) -> bool
"""Checks whether the string "looks like" a path on the filesystem.
This does not check whether the target actually exists, only judge from the
appearance.
Returns true if any of the following conditions is true:
* a path separator is found (ei... | [
"def",
"_looks_like_path",
"(",
"name",
")",
":",
"# type: (str) -> bool",
"if",
"os",
".",
"path",
".",
"sep",
"in",
"name",
":",
"return",
"True",
"if",
"os",
".",
"path",
".",
"altsep",
"is",
"not",
"None",
"and",
"os",
".",
"path",
".",
"altsep",
... | [
246,
0
] | [
263,
16
] | python | en | ['en', 'en', 'en'] | True |
_get_url_from_path | (path, name) |
First, it checks whether a provided path is an installable directory
(e.g. it has a setup.py). If it is, returns the path.
If false, check if the path is an archive file (such as a .whl).
The function checks if the path is a file. If false, if the path has
an @, it will treat it as a PEP 440 URL r... |
First, it checks whether a provided path is an installable directory
(e.g. it has a setup.py). If it is, returns the path. | def _get_url_from_path(path, name):
# type: (str, str) -> Optional[str]
"""
First, it checks whether a provided path is an installable directory
(e.g. it has a setup.py). If it is, returns the path.
If false, check if the path is an archive file (such as a .whl).
The function checks if the path... | [
"def",
"_get_url_from_path",
"(",
"path",
",",
"name",
")",
":",
"# type: (str, str) -> Optional[str]",
"if",
"_looks_like_path",
"(",
"name",
")",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"if",
"is_installable_dir",
"(",
"path",
")",
"... | [
266,
0
] | [
297,
28
] | python | en | ['en', 'error', 'th'] | False |
install_req_from_line | (
name, # type: str
comes_from=None, # type: Optional[Union[str, InstallRequirement]]
use_pep517=None, # type: Optional[bool]
isolated=False, # type: bool
options=None, # type: Optional[Dict[str, Any]]
constraint=False, # type: bool
line_source=None, # type: Optional[str]
user_sup... | Creates an InstallRequirement from a name, which might be a
requirement, directory containing 'setup.py', filename, or URL.
:param line_source: An optional string describing where the line is from,
for logging purposes in case of an error.
| Creates an InstallRequirement from a name, which might be a
requirement, directory containing 'setup.py', filename, or URL. | def install_req_from_line(
name, # type: str
comes_from=None, # type: Optional[Union[str, InstallRequirement]]
use_pep517=None, # type: Optional[bool]
isolated=False, # type: bool
options=None, # type: Optional[Dict[str, Any]]
constraint=False, # type: bool
line_source=None, # type: O... | [
"def",
"install_req_from_line",
"(",
"name",
",",
"# type: str",
"comes_from",
"=",
"None",
",",
"# type: Optional[Union[str, InstallRequirement]]",
"use_pep517",
"=",
"None",
",",
"# type: Optional[bool]",
"isolated",
"=",
"False",
",",
"# type: bool",
"options",
"=",
... | [
391,
0
] | [
419,
5
] | python | en | ['en', 'en', 'en'] | True |
dispatch_hook | (key, hooks, hook_data, **kwargs) | Dispatches a hook dictionary on a given piece of data. | Dispatches a hook dictionary on a given piece of data. | def dispatch_hook(key, hooks, hook_data, **kwargs):
"""Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or {}
hooks = hooks.get(key)
if hooks:
if hasattr(hooks, '__call__'):
hooks = [hooks]
for hook in hooks:
_hook_data = hook(hook_data, **k... | [
"def",
"dispatch_hook",
"(",
"key",
",",
"hooks",
",",
"hook_data",
",",
"*",
"*",
"kwargs",
")",
":",
"hooks",
"=",
"hooks",
"or",
"{",
"}",
"hooks",
"=",
"hooks",
".",
"get",
"(",
"key",
")",
"if",
"hooks",
":",
"if",
"hasattr",
"(",
"hooks",
"... | [
22,
0
] | [
33,
20
] | python | en | ['en', 'en', 'en'] | True |
TestArgComplete.test_remove_dir_prefix | (self) | this is not compatible with compgen but it is with bash itself:
ls /usr/<TAB>
| this is not compatible with compgen but it is with bash itself:
ls /usr/<TAB>
| def test_remove_dir_prefix(self):
"""this is not compatible with compgen but it is with bash itself:
ls /usr/<TAB>
"""
from _pytest._argcomplete import FastFilesCompleter
ffc = FastFilesCompleter()
fc = FilesCompleter()
for x in '/usr/'.split():
assert... | [
"def",
"test_remove_dir_prefix",
"(",
"self",
")",
":",
"from",
"_pytest",
".",
"_argcomplete",
"import",
"FastFilesCompleter",
"ffc",
"=",
"FastFilesCompleter",
"(",
")",
"fc",
"=",
"FilesCompleter",
"(",
")",
"for",
"x",
"in",
"'/usr/'",
".",
"split",
"(",
... | [
89,
4
] | [
97,
66
] | python | en | ['en', 'en', 'en'] | True |
PackageIndex.__init__ | (self, url=None) |
Initialise an instance.
:param url: The URL of the index. If not specified, the URL for PyPI is
used.
|
Initialise an instance. | def __init__(self, url=None):
"""
Initialise an instance.
:param url: The URL of the index. If not specified, the URL for PyPI is
used.
"""
self.url = url or DEFAULT_INDEX
self.read_configuration()
scheme, netloc, path, params, query, frag = u... | [
"def",
"__init__",
"(",
"self",
",",
"url",
"=",
"None",
")",
":",
"self",
".",
"url",
"=",
"url",
"or",
"DEFAULT_INDEX",
"self",
".",
"read_configuration",
"(",
")",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"frag",
"="... | [
35,
4
] | [
62,
24
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex._get_pypirc_command | (self) |
Get the distutils command for interacting with PyPI configurations.
:return: the command.
|
Get the distutils command for interacting with PyPI configurations.
:return: the command.
| def _get_pypirc_command(self):
"""
Get the distutils command for interacting with PyPI configurations.
:return: the command.
"""
from distutils.core import Distribution
from distutils.config import PyPIRCCommand
d = Distribution()
return PyPIRCCommand(d) | [
"def",
"_get_pypirc_command",
"(",
"self",
")",
":",
"from",
"distutils",
".",
"core",
"import",
"Distribution",
"from",
"distutils",
".",
"config",
"import",
"PyPIRCCommand",
"d",
"=",
"Distribution",
"(",
")",
"return",
"PyPIRCCommand",
"(",
"d",
")"
] | [
64,
4
] | [
72,
31
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex.read_configuration | (self) |
Read the PyPI access configuration as supported by distutils, getting
PyPI to do the actual work. This populates ``username``, ``password``,
``realm`` and ``url`` attributes from the configuration.
|
Read the PyPI access configuration as supported by distutils, getting
PyPI to do the actual work. This populates ``username``, ``password``,
``realm`` and ``url`` attributes from the configuration.
| def read_configuration(self):
"""
Read the PyPI access configuration as supported by distutils, getting
PyPI to do the actual work. This populates ``username``, ``password``,
``realm`` and ``url`` attributes from the configuration.
"""
# get distutils to do the work
... | [
"def",
"read_configuration",
"(",
"self",
")",
":",
"# get distutils to do the work",
"c",
"=",
"self",
".",
"_get_pypirc_command",
"(",
")",
"c",
".",
"repository",
"=",
"self",
".",
"url",
"cfg",
"=",
"c",
".",
"_read_pypirc",
"(",
")",
"self",
".",
"use... | [
74,
4
] | [
87,
50
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex.save_configuration | (self) |
Save the PyPI access configuration. You must have set ``username`` and
``password`` attributes before calling this method.
Again, distutils is used to do the actual work.
|
Save the PyPI access configuration. You must have set ``username`` and
``password`` attributes before calling this method. | def save_configuration(self):
"""
Save the PyPI access configuration. You must have set ``username`` and
``password`` attributes before calling this method.
Again, distutils is used to do the actual work.
"""
self.check_credentials()
# get distutils to do the wor... | [
"def",
"save_configuration",
"(",
"self",
")",
":",
"self",
".",
"check_credentials",
"(",
")",
"# get distutils to do the work",
"c",
"=",
"self",
".",
"_get_pypirc_command",
"(",
")",
"c",
".",
"_store_pypirc",
"(",
"self",
".",
"username",
",",
"self",
".",... | [
89,
4
] | [
99,
53
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex.check_credentials | (self) |
Check that ``username`` and ``password`` have been set, and raise an
exception if not.
|
Check that ``username`` and ``password`` have been set, and raise an
exception if not.
| def check_credentials(self):
"""
Check that ``username`` and ``password`` have been set, and raise an
exception if not.
"""
if self.username is None or self.password is None:
raise DistlibException('username and password must be set')
pm = HTTPPasswordMgr()
... | [
"def",
"check_credentials",
"(",
"self",
")",
":",
"if",
"self",
".",
"username",
"is",
"None",
"or",
"self",
".",
"password",
"is",
"None",
":",
"raise",
"DistlibException",
"(",
"'username and password must be set'",
")",
"pm",
"=",
"HTTPPasswordMgr",
"(",
"... | [
101,
4
] | [
111,
56
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex.register | (self, metadata) |
Register a distribution on PyPI, using the provided metadata.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the distribution to be
registered.
:return: The HTTP response received from PyPI upon su... |
Register a distribution on PyPI, using the provided metadata. | def register(self, metadata):
"""
Register a distribution on PyPI, using the provided metadata.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the distribution to be
registered.
:return: The... | [
"def",
"register",
"(",
"self",
",",
"metadata",
")",
":",
"self",
".",
"check_credentials",
"(",
")",
"metadata",
".",
"validate",
"(",
")",
"d",
"=",
"metadata",
".",
"todict",
"(",
")",
"d",
"[",
"':action'",
"]",
"=",
"'verify'",
"request",
"=",
... | [
113,
4
] | [
131,
41
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex._reader | (self, name, stream, outbuf) |
Thread runner for reading lines of from a subprocess into a buffer.
:param name: The logical name of the stream (used for logging only).
:param stream: The stream to read from. This will typically a pipe
connected to the output stream of a subprocess.
:param outb... |
Thread runner for reading lines of from a subprocess into a buffer. | def _reader(self, name, stream, outbuf):
"""
Thread runner for reading lines of from a subprocess into a buffer.
:param name: The logical name of the stream (used for logging only).
:param stream: The stream to read from. This will typically a pipe
connected to th... | [
"def",
"_reader",
"(",
"self",
",",
"name",
",",
"stream",
",",
"outbuf",
")",
":",
"while",
"True",
":",
"s",
"=",
"stream",
".",
"readline",
"(",
")",
"if",
"not",
"s",
":",
"break",
"s",
"=",
"s",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"rs... | [
133,
4
] | [
149,
22
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex.get_sign_command | (self, filename, signer, sign_password,
keystore=None) |
Return a suitable command for signing a file.
:param filename: The pathname to the file to be signed.
:param signer: The identifier of the signer of the file.
:param sign_password: The passphrase for the signer's
private key used for signing.
:para... |
Return a suitable command for signing a file. | def get_sign_command(self, filename, signer, sign_password,
keystore=None):
"""
Return a suitable command for signing a file.
:param filename: The pathname to the file to be signed.
:param signer: The identifier of the signer of the file.
:param sign_pas... | [
"def",
"get_sign_command",
"(",
"self",
",",
"filename",
",",
"signer",
",",
"sign_password",
",",
"keystore",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"self",
".",
"gpg",
",",
"'--status-fd'",
",",
"'2'",
",",
"'--no-tty'",
"]",
"if",
"keystore",
"is",
... | [
151,
4
] | [
178,
22
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex.run_command | (self, cmd, input_data=None) |
Run a command in a child process , passing it any input data specified.
:param cmd: The command to run.
:param input_data: If specified, this must be a byte string containing
data to be sent to the child process.
:return: A tuple consisting of the subprocess'... |
Run a command in a child process , passing it any input data specified. | def run_command(self, cmd, input_data=None):
"""
Run a command in a child process , passing it any input data specified.
:param cmd: The command to run.
:param input_data: If specified, this must be a byte string containing
data to be sent to the child process... | [
"def",
"run_command",
"(",
"self",
",",
"cmd",
",",
"input_data",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"'stdout'",
":",
"subprocess",
".",
"PIPE",
",",
"'stderr'",
":",
"subprocess",
".",
"PIPE",
",",
"}",
"if",
"input_data",
"is",
"not",
"None",... | [
180,
4
] | [
213,
43
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex.sign_file | (self, filename, signer, sign_password, keystore=None) |
Sign a file.
:param filename: The pathname to the file to be signed.
:param signer: The identifier of the signer of the file.
:param sign_password: The passphrase for the signer's
private key used for signing.
:param keystore: The path to a directo... |
Sign a file. | def sign_file(self, filename, signer, sign_password, keystore=None):
"""
Sign a file.
:param filename: The pathname to the file to be signed.
:param signer: The identifier of the signer of the file.
:param sign_password: The passphrase for the signer's
... | [
"def",
"sign_file",
"(",
"self",
",",
"filename",
",",
"signer",
",",
"sign_password",
",",
"keystore",
"=",
"None",
")",
":",
"cmd",
",",
"sig_file",
"=",
"self",
".",
"get_sign_command",
"(",
"filename",
",",
"signer",
",",
"sign_password",
",",
"keystor... | [
215,
4
] | [
236,
23
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex.upload_file | (self, metadata, filename, signer=None, sign_password=None,
filetype='sdist', pyversion='source', keystore=None) |
Upload a release file to the index.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the file to be uploaded.
:param filename: The pathname of the file to be uploaded.
:param signer: The identifier of the signer of t... |
Upload a release file to the index. | def upload_file(self, metadata, filename, signer=None, sign_password=None,
filetype='sdist', pyversion='source', keystore=None):
"""
Upload a release file to the index.
:param metadata: A :class:`Metadata` instance defining at least a name
and versio... | [
"def",
"upload_file",
"(",
"self",
",",
"metadata",
",",
"filename",
",",
"signer",
"=",
"None",
",",
"sign_password",
"=",
"None",
",",
"filetype",
"=",
"'sdist'",
",",
"pyversion",
"=",
"'source'",
",",
"keystore",
"=",
"None",
")",
":",
"self",
".",
... | [
238,
4
] | [
293,
41
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex.upload_documentation | (self, metadata, doc_dir) |
Upload documentation to the index.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the documentation to be
uploaded.
:param doc_dir: The pathname of the directory which contains the
... |
Upload documentation to the index. | def upload_documentation(self, metadata, doc_dir):
"""
Upload documentation to the index.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the documentation to be
uploaded.
:param doc_dir: The... | [
"def",
"upload_documentation",
"(",
"self",
",",
"metadata",
",",
"doc_dir",
")",
":",
"self",
".",
"check_credentials",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"doc_dir",
")",
":",
"raise",
"DistlibException",
"(",
"'not a directory: %r... | [
295,
4
] | [
321,
41
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex.get_verify_command | (self, signature_filename, data_filename,
keystore=None) |
Return a suitable command for verifying a file.
:param signature_filename: The pathname to the file containing the
signature.
:param data_filename: The pathname to the file containing the
signed data.
:param keystore: The... |
Return a suitable command for verifying a file. | def get_verify_command(self, signature_filename, data_filename,
keystore=None):
"""
Return a suitable command for verifying a file.
:param signature_filename: The pathname to the file containing the
signature.
:param data_fil... | [
"def",
"get_verify_command",
"(",
"self",
",",
"signature_filename",
",",
"data_filename",
",",
"keystore",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"self",
".",
"gpg",
",",
"'--status-fd'",
",",
"'2'",
",",
"'--no-tty'",
"]",
"if",
"keystore",
"is",
"None"... | [
323,
4
] | [
345,
18
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex.verify_signature | (self, signature_filename, data_filename,
keystore=None) |
Verify a signature for a file.
:param signature_filename: The pathname to the file containing the
signature.
:param data_filename: The pathname to the file containing the
signed data.
:param keystore: The path to a direct... |
Verify a signature for a file. | def verify_signature(self, signature_filename, data_filename,
keystore=None):
"""
Verify a signature for a file.
:param signature_filename: The pathname to the file containing the
signature.
:param data_filename: The pathname t... | [
"def",
"verify_signature",
"(",
"self",
",",
"signature_filename",
",",
"data_filename",
",",
"keystore",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"gpg",
":",
"raise",
"DistlibException",
"(",
"'verification unavailable because gpg '",
"'unavailable'",
")",
... | [
347,
4
] | [
370,
22
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex.download_file | (self, url, destfile, digest=None, reporthook=None) |
This is a convenience method for downloading a file from an URL.
Normally, this will be a file from the index, though currently
no check is made for this (i.e. a file can be downloaded from
anywhere).
The method is just like the :func:`urlretrieve` function in the
stand... |
This is a convenience method for downloading a file from an URL.
Normally, this will be a file from the index, though currently
no check is made for this (i.e. a file can be downloaded from
anywhere). | def download_file(self, url, destfile, digest=None, reporthook=None):
"""
This is a convenience method for downloading a file from an URL.
Normally, this will be a file from the index, though currently
no check is made for this (i.e. a file can be downloaded from
anywhere).
... | [
"def",
"download_file",
"(",
"self",
",",
"url",
",",
"destfile",
",",
"digest",
"=",
"None",
",",
"reporthook",
"=",
"None",
")",
":",
"if",
"digest",
"is",
"None",
":",
"digester",
"=",
"None",
"logger",
".",
"debug",
"(",
"'No digest specified'",
")",... | [
372,
4
] | [
447,
55
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex.send_request | (self, req) |
Send a standard library :class:`Request` to PyPI and return its
response.
:param req: The request to send.
:return: The HTTP response from PyPI (a standard library HTTPResponse).
|
Send a standard library :class:`Request` to PyPI and return its
response. | def send_request(self, req):
"""
Send a standard library :class:`Request` to PyPI and return its
response.
:param req: The request to send.
:return: The HTTP response from PyPI (a standard library HTTPResponse).
"""
handlers = []
if self.password_handler:... | [
"def",
"send_request",
"(",
"self",
",",
"req",
")",
":",
"handlers",
"=",
"[",
"]",
"if",
"self",
".",
"password_handler",
":",
"handlers",
".",
"append",
"(",
"self",
".",
"password_handler",
")",
"if",
"self",
".",
"ssl_verifier",
":",
"handlers",
"."... | [
449,
4
] | [
463,
31
] | python | en | ['en', 'error', 'th'] | False |
PackageIndex.encode_request | (self, fields, files) |
Encode fields and files for posting to an HTTP server.
:param fields: The fields to send as a list of (fieldname, value)
tuples.
:param files: The files to send as a list of (fieldname, filename,
file_bytes) tuple.
|
Encode fields and files for posting to an HTTP server. | def encode_request(self, fields, files):
"""
Encode fields and files for posting to an HTTP server.
:param fields: The fields to send as a list of (fieldname, value)
tuples.
:param files: The files to send as a list of (fieldname, filename,
f... | [
"def",
"encode_request",
"(",
"self",
",",
"fields",
",",
"files",
")",
":",
"# Adapted from packaging, which in turn was adapted from",
"# http://code.activestate.com/recipes/146306",
"parts",
"=",
"[",
"]",
"boundary",
"=",
"self",
".",
"boundary",
"for",
"k",
",",
... | [
465,
4
] | [
506,
47
] | python | en | ['en', 'error', 'th'] | False |
ExtractAngularTestCase.test_attr_value | (self) | Should not translate tags with translate as the value of an attr. | Should not translate tags with translate as the value of an attr. | def test_attr_value(self):
"""Should not translate tags with translate as the value of an attr."""
buf = StringIO('<html><div id="translate">hello world!</div></html>')
messages = list(extract_angular(buf, [], [], {}))
self.assertEqual([], messages) | [
"def",
"test_attr_value",
"(",
"self",
")",
":",
"buf",
"=",
"StringIO",
"(",
"'<html><div id=\"translate\">hello world!</div></html>'",
")",
"messages",
"=",
"list",
"(",
"extract_angular",
"(",
"buf",
",",
"[",
"]",
",",
"[",
"]",
",",
"{",
"}",
")",
")",
... | [
45,
4
] | [
50,
38
] | python | en | ['en', 'en', 'en'] | True |
ExtractAngularTestCase.test_attr_value_plus_directive | (self) | Unless they also have a translate directive. | Unless they also have a translate directive. | def test_attr_value_plus_directive(self):
"""Unless they also have a translate directive."""
buf = StringIO(
'<html><div id="translate" translate>hello world!</div></html>')
messages = list(extract_angular(buf, [], [], {}))
self.assertEqual([(1, 'gettext', 'hello world!', []... | [
"def",
"test_attr_value_plus_directive",
"(",
"self",
")",
":",
"buf",
"=",
"StringIO",
"(",
"'<html><div id=\"translate\" translate>hello world!</div></html>'",
")",
"messages",
"=",
"list",
"(",
"extract_angular",
"(",
"buf",
",",
"[",
"]",
",",
"[",
"]",
",",
"... | [
52,
4
] | [
58,
72
] | python | en | ['en', 'en', 'en'] | True |
TestAdminRouters.test_router_create_admin | (self) | tests the router creation and deletion functionalities:
* creates a new router for public network
* verifies the router appears in the routers table as active
* edits router name
* checks router name was updated properly
* deletes the newly created router
* verifies the ... | tests the router creation and deletion functionalities: | def test_router_create_admin(self):
"""tests the router creation and deletion functionalities:
* creates a new router for public network
* verifies the router appears in the routers table as active
* edits router name
* checks router name was updated properly
* deletes t... | [
"def",
"test_router_create_admin",
"(",
"self",
")",
":",
"routers_page",
"=",
"self",
".",
"home_pg",
".",
"go_to_project_network_routerspage",
"(",
")",
"routers_page",
".",
"create_router",
"(",
"self",
".",
"ROUTER_NAME",
")",
"self",
".",
"assertTrue",
"(",
... | [
166,
4
] | [
206,
72
] | python | en | ['en', 'en', 'en'] | True |
DataTableTests.test_table_instantiation | (self) | Tests everything that happens when the table is instantiated. | Tests everything that happens when the table is instantiated. | def test_table_instantiation(self):
"""Tests everything that happens when the table is instantiated."""
self.table = MyTable(self.request, TEST_DATA)
# Properties defined on the table
self.assertEqual(TEST_DATA, self.table.data)
self.assertEqual("my_table", self.table.name)
... | [
"def",
"test_table_instantiation",
"(",
"self",
")",
":",
"self",
".",
"table",
"=",
"MyTable",
"(",
"self",
".",
"request",
",",
"TEST_DATA",
")",
"# Properties defined on the table",
"self",
".",
"assertEqual",
"(",
"TEST_DATA",
",",
"self",
".",
"table",
".... | [
414,
4
] | [
469,
78
] | python | en | ['en', 'en', 'en'] | True |
FormsetTableTests.test_populate | (self) | Create a FormsetDataTable and populate it with data. | Create a FormsetDataTable and populate it with data. | def test_populate(self):
"""Create a FormsetDataTable and populate it with data."""
class TableForm(forms.Form):
name = forms.CharField()
value = forms.IntegerField()
TableFormset = forms.formsets.formset_factory(TableForm, extra=0)
class Table(table_formset.Fo... | [
"def",
"test_populate",
"(",
"self",
")",
":",
"class",
"TableForm",
"(",
"forms",
".",
"Form",
")",
":",
"name",
"=",
"forms",
".",
"CharField",
"(",
")",
"value",
"=",
"forms",
".",
"IntegerField",
"(",
")",
"TableFormset",
"=",
"forms",
".",
"formse... | [
1427,
4
] | [
1452,
47
] | python | en | ['en', 'en', 'en'] | True |
UniversalDetector.reset | (self) |
Reset the UniversalDetector and all of its probers back to their
initial states. This is called by ``__init__``, so you only need to
call this directly in between analyses of different documents.
|
Reset the UniversalDetector and all of its probers back to their
initial states. This is called by ``__init__``, so you only need to
call this directly in between analyses of different documents.
| def reset(self):
"""
Reset the UniversalDetector and all of its probers back to their
initial states. This is called by ``__init__``, so you only need to
call this directly in between analyses of different documents.
"""
self.result = {'encoding': None, 'confidence': 0.0... | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"result",
"=",
"{",
"'encoding'",
":",
"None",
",",
"'confidence'",
":",
"0.0",
",",
"'language'",
":",
"None",
"}",
"self",
".",
"done",
"=",
"False",
"self",
".",
"_got_data",
"=",
"False",
"self"... | [
93,
4
] | [
108,
26
] | python | en | ['en', 'error', 'th'] | False |
UniversalDetector.feed | (self, byte_str) |
Takes a chunk of a document and feeds it through all of the relevant
charset probers.
After calling ``feed``, you can check the value of the ``done``
attribute to see if you need to continue feeding the
``UniversalDetector`` more data, or if it has made a prediction
(in... |
Takes a chunk of a document and feeds it through all of the relevant
charset probers. | def feed(self, byte_str):
"""
Takes a chunk of a document and feeds it through all of the relevant
charset probers.
After calling ``feed``, you can check the value of the ``done``
attribute to see if you need to continue feeding the
``UniversalDetector`` more data, or if... | [
"def",
"feed",
"(",
"self",
",",
"byte_str",
")",
":",
"if",
"self",
".",
"done",
":",
"return",
"if",
"not",
"len",
"(",
"byte_str",
")",
":",
"return",
"if",
"not",
"isinstance",
"(",
"byte_str",
",",
"bytearray",
")",
":",
"byte_str",
"=",
"bytear... | [
110,
4
] | [
217,
42
] | python | en | ['en', 'error', 'th'] | False |
UniversalDetector.close | (self) |
Stop analyzing the current document and come up with a final
prediction.
:returns: The ``result`` attribute, a ``dict`` with the keys
`encoding`, `confidence`, and `language`.
|
Stop analyzing the current document and come up with a final
prediction. | def close(self):
"""
Stop analyzing the current document and come up with a final
prediction.
:returns: The ``result`` attribute, a ``dict`` with the keys
`encoding`, `confidence`, and `language`.
"""
# Don't bother with checks if we're already done
... | [
"def",
"close",
"(",
"self",
")",
":",
"# Don't bother with checks if we're already done",
"if",
"self",
".",
"done",
":",
"return",
"self",
".",
"result",
"self",
".",
"done",
"=",
"True",
"if",
"not",
"self",
".",
"_got_data",
":",
"self",
".",
"logger",
... | [
219,
4
] | [
285,
26
] | python | en | ['en', 'error', 'th'] | False |
ParallaxHighSpeedContinuousServoMotor.map_speed_to_pwm_us | (self, speed: Real) |
The map of PWM signal to speed for this servo looks like a sigmoid function. See page 3 of the documentation:
https://www.parallax.com/sites/default/files/downloads/900-00025-High-Speed-CR-Servo-Guide-v1.1.pdf
|
The map of PWM signal to speed for this servo looks like a sigmoid function. See page 3 of the documentation:
https://www.parallax.com/sites/default/files/downloads/900-00025-High-Speed-CR-Servo-Guide-v1.1.pdf
| def map_speed_to_pwm_us(self, speed: Real) -> Real:
"""
The map of PWM signal to speed for this servo looks like a sigmoid function. See page 3 of the documentation:
https://www.parallax.com/sites/default/files/downloads/900-00025-High-Speed-CR-Servo-Guide-v1.1.pdf
"""
full_cw_p... | [
"def",
"map_speed_to_pwm_us",
"(",
"self",
",",
"speed",
":",
"Real",
")",
"->",
"Real",
":",
"full_cw_point",
"=",
"Point",
"(",
"1",
",",
"self",
".",
"full_cw_pwm_us",
")",
"near_full_cw_point",
"=",
"Point",
"(",
"0.88",
",",
"1420",
")",
"high_dead_po... | [
24,
4
] | [
49,
39
] | python | en | ['en', 'error', 'th'] | False |
ActorState._env_set_curr_policy | (self) |
Most environments do not need to know index of the policy that currently collects experience.
But in rare cases it is necessary. Originally was implemented for DMLab to properly manage the level cache.
|
Most environments do not need to know index of the policy that currently collects experience.
But in rare cases it is necessary. Originally was implemented for DMLab to properly manage the level cache.
| def _env_set_curr_policy(self):
"""
Most environments do not need to know index of the policy that currently collects experience.
But in rare cases it is necessary. Originally was implemented for DMLab to properly manage the level cache.
"""
set_attr_if_exists(self.env.unwrapped,... | [
"def",
"_env_set_curr_policy",
"(",
"self",
")",
":",
"set_attr_if_exists",
"(",
"self",
".",
"env",
".",
"unwrapped",
",",
"'curr_policy_idx'",
",",
"self",
".",
"curr_policy_id",
")"
] | [
82,
4
] | [
87,
86
] | python | en | ['en', 'error', 'th'] | False |
ActorState._on_new_policy | (self, new_policy_id) | Called when the new policy is sampled for this actor. | Called when the new policy is sampled for this actor. | def _on_new_policy(self, new_policy_id):
"""Called when the new policy is sampled for this actor."""
self.curr_policy_id = new_policy_id
# we're switching to a different policy - reset the rnn hidden state
self._reset_rnn_state()
if self.cfg.with_pbt and self.pbt_reward_shaping[... | [
"def",
"_on_new_policy",
"(",
"self",
",",
"new_policy_id",
")",
":",
"self",
".",
"curr_policy_id",
"=",
"new_policy_id",
"# we're switching to a different policy - reset the rnn hidden state",
"self",
".",
"_reset_rnn_state",
"(",
")",
"if",
"self",
".",
"cfg",
".",
... | [
89,
4
] | [
96,
112
] | python | en | ['en', 'en', 'en'] | True |
ActorState.set_trajectory_data | (self, data, traj_buffer_idx, rollout_step) |
Write a dictionary of data into a trajectory buffer at the specific location (rollout_step).
:param data: any sub-dictionary of the full per-step data, e.g. just observation, observation and action, etc.
:param traj_buffer_idx: index of the trajectory buffer we're currently using on this worke... |
Write a dictionary of data into a trajectory buffer at the specific location (rollout_step). | def set_trajectory_data(self, data, traj_buffer_idx, rollout_step):
"""
Write a dictionary of data into a trajectory buffer at the specific location (rollout_step).
:param data: any sub-dictionary of the full per-step data, e.g. just observation, observation and action, etc.
:param traj... | [
"def",
"set_trajectory_data",
"(",
"self",
",",
"data",
",",
"traj_buffer_idx",
",",
"rollout_step",
")",
":",
"index",
"=",
"(",
"traj_buffer_idx",
",",
"rollout_step",
")",
"self",
".",
"traj_tensors",
".",
"set_data",
"(",
"index",
",",
"data",
")"
] | [
98,
4
] | [
109,
47
] | python | en | ['en', 'error', 'th'] | False |
ActorState.curr_actions | (self) |
:return: the latest set of actions for this actor, calculated by the policy worker for the last observation
|
:return: the latest set of actions for this actor, calculated by the policy worker for the last observation
| def curr_actions(self):
"""
:return: the latest set of actions for this actor, calculated by the policy worker for the last observation
"""
if self.integer_actions:
actions = self.last_actions.type(torch.int32).numpy()
else:
actions = self.last_actions.num... | [
"def",
"curr_actions",
"(",
"self",
")",
":",
"if",
"self",
".",
"integer_actions",
":",
"actions",
"=",
"self",
".",
"last_actions",
".",
"type",
"(",
"torch",
".",
"int32",
")",
".",
"numpy",
"(",
")",
"else",
":",
"actions",
"=",
"self",
".",
"las... | [
114,
4
] | [
125,
22
] | python | en | ['en', 'error', 'th'] | False |
ActorState.record_env_step | (self, reward, done, info, traj_buffer_idx, rollout_step) |
Policy inputs (obs) and policy outputs (actions, values, ...) for the current rollout step
are already added to the trajectory buffer
the only job remaining is to add auxiliary data: rewards, done flags, etc.
:param reward: last reward from the env step
:param done: last value ... |
Policy inputs (obs) and policy outputs (actions, values, ...) for the current rollout step
are already added to the trajectory buffer
the only job remaining is to add auxiliary data: rewards, done flags, etc. | def record_env_step(self, reward, done, info, traj_buffer_idx, rollout_step):
"""
Policy inputs (obs) and policy outputs (actions, values, ...) for the current rollout step
are already added to the trajectory buffer
the only job remaining is to add auxiliary data: rewards, done flags, et... | [
"def",
"record_env_step",
"(",
"self",
",",
"reward",
",",
"done",
",",
"info",
",",
"traj_buffer_idx",
",",
"rollout_step",
")",
":",
"self",
".",
"traj_tensors",
"[",
"'rewards'",
"]",
"[",
"traj_buffer_idx",
",",
"rollout_step",
"]",
"[",
"0",
"]",
"=",... | [
127,
4
] | [
151,
83
] | python | en | ['en', 'error', 'th'] | False |
ActorState.finalize_trajectory | (self, rollout_step) |
Do some postprocessing after we finished the entire rollout.
The key thing to notice here: we never change the policy that generates the actions in the middle of the
rollout! The policy index (in PBT scenarios) is only changed between rollouts.
This means that a little bit of experience... |
Do some postprocessing after we finished the entire rollout.
The key thing to notice here: we never change the policy that generates the actions in the middle of the
rollout! The policy index (in PBT scenarios) is only changed between rollouts.
This means that a little bit of experience... | def finalize_trajectory(self, rollout_step):
"""
Do some postprocessing after we finished the entire rollout.
The key thing to notice here: we never change the policy that generates the actions in the middle of the
rollout! The policy index (in PBT scenarios) is only changed between roll... | [
"def",
"finalize_trajectory",
"(",
"self",
",",
"rollout_step",
")",
":",
"t_id",
"=",
"f'{self.curr_policy_id}_{self.worker_idx}_{self.split_idx}_{self.env_idx}_{self.agent_idx}_{self.num_trajectories}'",
"traj_dict",
"=",
"dict",
"(",
"t_id",
"=",
"t_id",
",",
"length",
"="... | [
153,
4
] | [
187,
24
] | python | en | ['en', 'error', 'th'] | False |
ActorState.update_rnn_state | (self, done) | If we encountered an episode boundary, reset rnn states to their default values. | If we encountered an episode boundary, reset rnn states to their default values. | def update_rnn_state(self, done):
"""If we encountered an episode boundary, reset rnn states to their default values."""
if done:
self._reset_rnn_state() | [
"def",
"update_rnn_state",
"(",
"self",
",",
"done",
")",
":",
"if",
"done",
":",
"self",
".",
"_reset_rnn_state",
"(",
")"
] | [
189,
4
] | [
192,
35
] | python | en | ['en', 'en', 'en'] | True |
VectorEnvRunner.__init__ | (self, cfg, num_envs, worker_idx, split_idx, num_agents, shared_buffers, pbt_reward_shaping) |
Ctor.
:param cfg: global system config (all CLI params)
:param num_envs: number of envs to run in this vector runner
:param worker_idx: idx of the parent worker
:param split_idx: index of the environment group in double-buffered sampling (either 0 or 1). Always 0 when
d... |
Ctor. | def __init__(self, cfg, num_envs, worker_idx, split_idx, num_agents, shared_buffers, pbt_reward_shaping):
"""
Ctor.
:param cfg: global system config (all CLI params)
:param num_envs: number of envs to run in this vector runner
:param worker_idx: idx of the parent worker
... | [
"def",
"__init__",
"(",
"self",
",",
"cfg",
",",
"num_envs",
",",
"worker_idx",
",",
"split_idx",
",",
"num_agents",
",",
"shared_buffers",
",",
"pbt_reward_shaping",
")",
":",
"self",
".",
"cfg",
"=",
"cfg",
"self",
".",
"num_envs",
"=",
"num_envs",
"self... | [
224,
4
] | [
262,
79
] | python | en | ['en', 'error', 'th'] | False |
VectorEnvRunner.init | (self) |
Actually instantiate the env instances.
Also creates ActorState objects that hold the state of individual actors in (potentially) multi-agent envs.
|
Actually instantiate the env instances.
Also creates ActorState objects that hold the state of individual actors in (potentially) multi-agent envs.
| def init(self):
"""
Actually instantiate the env instances.
Also creates ActorState objects that hold the state of individual actors in (potentially) multi-agent envs.
"""
for env_i in range(self.num_envs):
vector_idx = self.split_idx * self.num_envs + env_i
... | [
"def",
"init",
"(",
"self",
")",
":",
"for",
"env_i",
"in",
"range",
"(",
"self",
".",
"num_envs",
")",
":",
"vector_idx",
"=",
"self",
".",
"split_idx",
"*",
"self",
".",
"num_envs",
"+",
"env_i",
"# global env id within the entire system",
"env_id",
"=",
... | [
264,
4
] | [
299,
60
] | python | en | ['en', 'error', 'th'] | False |
VectorEnvRunner._process_policy_outputs | (self, policy_id) |
Process the latest data from the policy worker (for policy = policy_id).
Policy outputs currently include new RNN states, actions, values, logprobs, etc. See shared_buffers.py
for the full list of outputs.
As a performance optimization, all these tensors are squished together into a si... |
Process the latest data from the policy worker (for policy = policy_id).
Policy outputs currently include new RNN states, actions, values, logprobs, etc. See shared_buffers.py
for the full list of outputs. | def _process_policy_outputs(self, policy_id):
"""
Process the latest data from the policy worker (for policy = policy_id).
Policy outputs currently include new RNN states, actions, values, logprobs, etc. See shared_buffers.py
for the full list of outputs.
As a performance optimi... | [
"def",
"_process_policy_outputs",
"(",
"self",
",",
"policy_id",
")",
":",
"all_actors_ready",
"=",
"True",
"for",
"env_i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"envs",
")",
")",
":",
"for",
"agent_i",
"in",
"range",
"(",
"self",
".",
"num_agents... | [
301,
4
] | [
352,
31
] | python | en | ['en', 'error', 'th'] | False |
VectorEnvRunner._process_rewards | (self, rewards, env_i) |
Pretty self-explanatory, here we record the episode reward and apply the optional clipping and
scaling of rewards.
|
Pretty self-explanatory, here we record the episode reward and apply the optional clipping and
scaling of rewards.
| def _process_rewards(self, rewards, env_i):
"""
Pretty self-explanatory, here we record the episode reward and apply the optional clipping and
scaling of rewards.
"""
for agent_i, r in enumerate(rewards):
self.actor_states[env_i][agent_i].last_episode_reward += r
... | [
"def",
"_process_rewards",
"(",
"self",
",",
"rewards",
",",
"env_i",
")",
":",
"for",
"agent_i",
",",
"r",
"in",
"enumerate",
"(",
"rewards",
")",
":",
"self",
".",
"actor_states",
"[",
"env_i",
"]",
"[",
"agent_i",
"]",
".",
"last_episode_reward",
"+="... | [
354,
4
] | [
366,
22
] | python | en | ['en', 'error', 'th'] | False |
VectorEnvRunner._process_env_step | (self, new_obs, rewards, dones, infos, env_i) |
Process step outputs from a single environment in the vector.
:param new_obs: latest observations from the env
:param env_i: index of the environment in the vector
:return: episodic stats, not empty only on the episode boundary
|
Process step outputs from a single environment in the vector. | def _process_env_step(self, new_obs, rewards, dones, infos, env_i):
"""
Process step outputs from a single environment in the vector.
:param new_obs: latest observations from the env
:param env_i: index of the environment in the vector
:return: episodic stats, not empty only on ... | [
"def",
"_process_env_step",
"(",
"self",
",",
"new_obs",
",",
"rewards",
",",
"dones",
",",
"infos",
",",
"env_i",
")",
":",
"episodic_stats",
"=",
"[",
"]",
"env_actor_states",
"=",
"self",
".",
"actor_states",
"[",
"env_i",
"]",
"rewards",
"=",
"self",
... | [
368,
4
] | [
396,
29
] | python | en | ['en', 'error', 'th'] | False |
VectorEnvRunner._finalize_trajectories | (self) |
Do some postprocessing when we're done with the rollout.
Also see comments in actor_state.finalize_trajectory (IMPORTANT)
|
Do some postprocessing when we're done with the rollout.
Also see comments in actor_state.finalize_trajectory (IMPORTANT)
| def _finalize_trajectories(self):
"""
Do some postprocessing when we're done with the rollout.
Also see comments in actor_state.finalize_trajectory (IMPORTANT)
"""
rollouts = []
for env_i in range(self.num_envs):
for agent_i in range(self.num_agents):
... | [
"def",
"_finalize_trajectories",
"(",
"self",
")",
":",
"rollouts",
"=",
"[",
"]",
"for",
"env_i",
"in",
"range",
"(",
"self",
".",
"num_envs",
")",
":",
"for",
"agent_i",
"in",
"range",
"(",
"self",
".",
"num_agents",
")",
":",
"actor_state",
"=",
"se... | [
398,
4
] | [
413,
76
] | python | en | ['en', 'error', 'th'] | False |
VectorEnvRunner._format_policy_request | (self) |
Format data that allows us to request new actions from policies that control the agents in all the envs.
Note how the data required is basically just indices of envs and agents, as well as location of the step
data in the shared rollout buffer. This is enough for the policy worker to find the s... |
Format data that allows us to request new actions from policies that control the agents in all the envs.
Note how the data required is basically just indices of envs and agents, as well as location of the step
data in the shared rollout buffer. This is enough for the policy worker to find the s... | def _format_policy_request(self):
"""
Format data that allows us to request new actions from policies that control the agents in all the envs.
Note how the data required is basically just indices of envs and agents, as well as location of the step
data in the shared rollout buffer. This ... | [
"def",
"_format_policy_request",
"(",
"self",
")",
":",
"policy_request",
"=",
"dict",
"(",
")",
"for",
"env_i",
"in",
"range",
"(",
"self",
".",
"num_envs",
")",
":",
"for",
"agent_i",
"in",
"range",
"(",
"self",
".",
"num_agents",
")",
":",
"actor_stat... | [
415,
4
] | [
439,
29
] | python | en | ['en', 'error', 'th'] | False |
VectorEnvRunner._prepare_next_step | (self) |
Write environment outputs to shared memory so policy workers can calculate actions for the next step.
Note how we temporary hold obs and rnn_states in local variables before writing them into shared memory.
We could not do the memory write right away because for that we need the memory location... |
Write environment outputs to shared memory so policy workers can calculate actions for the next step.
Note how we temporary hold obs and rnn_states in local variables before writing them into shared memory.
We could not do the memory write right away because for that we need the memory location... | def _prepare_next_step(self):
"""
Write environment outputs to shared memory so policy workers can calculate actions for the next step.
Note how we temporary hold obs and rnn_states in local variables before writing them into shared memory.
We could not do the memory write right away bec... | [
"def",
"_prepare_next_step",
"(",
"self",
")",
":",
"for",
"env_i",
"in",
"range",
"(",
"self",
".",
"num_envs",
")",
":",
"for",
"agent_i",
"in",
"range",
"(",
"self",
".",
"num_agents",
")",
":",
"actor_state",
"=",
"self",
".",
"actor_states",
"[",
... | [
441,
4
] | [
458,
103
] | python | en | ['en', 'error', 'th'] | False |
VectorEnvRunner.reset | (self, report_queue) |
Do the very first reset for all environments in a vector. Populate shared memory with initial obs.
Note that this is called only once, at the very beginning of training. After this the envs should auto-reset.
:param report_queue: we use report queue to monitor reset progress (see appo.py). Thi... |
Do the very first reset for all environments in a vector. Populate shared memory with initial obs.
Note that this is called only once, at the very beginning of training. After this the envs should auto-reset. | def reset(self, report_queue):
"""
Do the very first reset for all environments in a vector. Populate shared memory with initial obs.
Note that this is called only once, at the very beginning of training. After this the envs should auto-reset.
:param report_queue: we use report queue to... | [
"def",
"reset",
"(",
"self",
",",
"report_queue",
")",
":",
"for",
"env_i",
",",
"e",
"in",
"enumerate",
"(",
"self",
".",
"envs",
")",
":",
"observations",
"=",
"e",
".",
"reset",
"(",
")",
"if",
"self",
".",
"cfg",
".",
"decorrelate_envs_on_one_worke... | [
460,
4
] | [
492,
29
] | python | en | ['en', 'error', 'th'] | False |
VectorEnvRunner.advance_rollouts | (self, data, timing) |
Main function in VectorEnvRunner. Does one step of simulation (if all actions for all actors are available).
:param data: incoming data from policy workers (policy outputs), including new actions
:param timing: this is just for profiling
:return: same as reset(), return a set of reques... |
Main function in VectorEnvRunner. Does one step of simulation (if all actions for all actors are available). | def advance_rollouts(self, data, timing):
"""
Main function in VectorEnvRunner. Does one step of simulation (if all actions for all actors are available).
:param data: incoming data from policy workers (policy outputs), including new actions
:param timing: this is just for profiling
... | [
"def",
"advance_rollouts",
"(",
"self",
",",
"data",
",",
"timing",
")",
":",
"with",
"timing",
".",
"add_time",
"(",
"'save_policy_outputs'",
")",
":",
"policy_id",
"=",
"data",
"[",
"'policy_id'",
"]",
"all_actors_ready",
"=",
"self",
".",
"_process_policy_o... | [
494,
4
] | [
539,
64
] | python | en | ['en', 'error', 'th'] | False |
VectorEnvRunner.wait_for_traj_buffers | (self) |
In very rare cases the learner might not have freed the shared memory buffer by the time we need it.
Here we wait until the learner is done with it.
|
In very rare cases the learner might not have freed the shared memory buffer by the time we need it.
Here we wait until the learner is done with it.
| def wait_for_traj_buffers(self):
"""
In very rare cases the learner might not have freed the shared memory buffer by the time we need it.
Here we wait until the learner is done with it.
"""
print_warning = True
while self.traj_tensors_available[:, :, self.traj_buffer_idx... | [
"def",
"wait_for_traj_buffers",
"(",
"self",
")",
":",
"print_warning",
"=",
"True",
"while",
"self",
".",
"traj_tensors_available",
"[",
":",
",",
":",
",",
"self",
".",
"traj_buffer_idx",
"]",
".",
"min",
"(",
")",
"==",
"0",
":",
"if",
"print_warning",
... | [
541,
4
] | [
555,
29
] | python | en | ['en', 'error', 'th'] | False |
ActorWorker.__init__ | (
self, cfg, obs_space, action_space, num_agents, worker_idx, shared_buffers,
task_queue, policy_queues, report_queue, learner_queues,
) |
Actor.
:param cfg: global config (all CLI params)
:param obs_space: observation space (spaces) of the environment
:param action_space: action space(s)
:param num_agents: number of agents per env (all env should have the same number of agents right now,
although it shoul... |
Actor. | def __init__(
self, cfg, obs_space, action_space, num_agents, worker_idx, shared_buffers,
task_queue, policy_queues, report_queue, learner_queues,
):
"""
Actor.
:param cfg: global config (all CLI params)
:param obs_space: observation space (spaces) of the environment... | [
"def",
"__init__",
"(",
"self",
",",
"cfg",
",",
"obs_space",
",",
"action_space",
",",
"num_agents",
",",
"worker_idx",
",",
"shared_buffers",
",",
"task_queue",
",",
"policy_queues",
",",
"report_queue",
",",
"learner_queues",
",",
")",
":",
"super",
"(",
... | [
580,
4
] | [
632,
28
] | python | en | ['en', 'error', 'th'] | False |
ActorWorker._init | (self) |
Initialize env runners, that actually do all the work. Also we're doing some utility stuff here, e.g.
setting process affinity (this is a performance optimization).
|
Initialize env runners, that actually do all the work. Also we're doing some utility stuff here, e.g.
setting process affinity (this is a performance optimization).
| def _init(self):
"""
Initialize env runners, that actually do all the work. Also we're doing some utility stuff here, e.g.
setting process affinity (this is a performance optimization).
"""
log.info('Initializing envs for env runner %d...', self.worker_idx)
if self.cfg.... | [
"def",
"_init",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Initializing envs for env runner %d...'",
",",
"self",
".",
"worker_idx",
")",
"if",
"self",
".",
"cfg",
".",
"force_envs_single_thread",
":",
"from",
"threadpoolctl",
"import",
"threadpool_limits",... | [
634,
4
] | [
657,
47
] | python | en | ['en', 'error', 'th'] | False |
ActorWorker._enqueue_policy_request | (self, split_idx, policy_inputs) | Distribute action requests to their corresponding queues. | Distribute action requests to their corresponding queues. | def _enqueue_policy_request(self, split_idx, policy_inputs):
"""Distribute action requests to their corresponding queues."""
for policy_id, requests in policy_inputs.items():
policy_request = (self.worker_idx, split_idx, requests)
self.policy_queues[policy_id].put(policy_request... | [
"def",
"_enqueue_policy_request",
"(",
"self",
",",
"split_idx",
",",
"policy_inputs",
")",
":",
"for",
"policy_id",
",",
"requests",
"in",
"policy_inputs",
".",
"items",
"(",
")",
":",
"policy_request",
"=",
"(",
"self",
".",
"worker_idx",
",",
"split_idx",
... | [
665,
4
] | [
670,
61
] | python | en | ['en', 'en', 'en'] | True |
ActorWorker._enqueue_complete_rollouts | (self, split_idx, complete_rollouts) | Send complete rollouts from VectorEnv to the learner. | Send complete rollouts from VectorEnv to the learner. | def _enqueue_complete_rollouts(self, split_idx, complete_rollouts):
"""Send complete rollouts from VectorEnv to the learner."""
if self.cfg.sampler_only:
return
rollouts = complete_rollouts['rollouts']
traj_buffer_idx = complete_rollouts['traj_buffer_idx']
# mark th... | [
"def",
"_enqueue_complete_rollouts",
"(",
"self",
",",
"split_idx",
",",
"complete_rollouts",
")",
":",
"if",
"self",
".",
"cfg",
".",
"sampler_only",
":",
"return",
"rollouts",
"=",
"complete_rollouts",
"[",
"'rollouts'",
"]",
"traj_buffer_idx",
"=",
"complete_ro... | [
672,
4
] | [
697,
74
] | python | en | ['en', 'en', 'en'] | True |
ActorWorker._handle_reset | (self) |
Reset all envs, one split at a time (double-buffering), and send requests to policy workers to get
actions for the very first env step.
|
Reset all envs, one split at a time (double-buffering), and send requests to policy workers to get
actions for the very first env step.
| def _handle_reset(self):
"""
Reset all envs, one split at a time (double-buffering), and send requests to policy workers to get
actions for the very first env step.
"""
for split_idx, env_runner in enumerate(self.env_runners):
policy_inputs = env_runner.reset(self.rep... | [
"def",
"_handle_reset",
"(",
"self",
")",
":",
"for",
"split_idx",
",",
"env_runner",
"in",
"enumerate",
"(",
"self",
".",
"env_runners",
")",
":",
"policy_inputs",
"=",
"env_runner",
".",
"reset",
"(",
"self",
".",
"report_queue",
")",
"self",
".",
"_enqu... | [
703,
4
] | [
713,
67
] | python | en | ['en', 'error', 'th'] | False |
ActorWorker._advance_rollouts | (self, data, timing) |
Process incoming request from policy worker. Use the data (policy outputs, actions) to advance the simulation
by one step on the corresponding VectorEnvRunner.
If we successfully managed to advance the simulation, send requests to policy workers to get actions for the
next step. If we ... |
Process incoming request from policy worker. Use the data (policy outputs, actions) to advance the simulation
by one step on the corresponding VectorEnvRunner. | def _advance_rollouts(self, data, timing):
"""
Process incoming request from policy worker. Use the data (policy outputs, actions) to advance the simulation
by one step on the corresponding VectorEnvRunner.
If we successfully managed to advance the simulation, send requests to policy wo... | [
"def",
"_advance_rollouts",
"(",
"self",
",",
"data",
",",
"timing",
")",
":",
"split_idx",
"=",
"data",
"[",
"'split_idx'",
"]",
"runner",
"=",
"self",
".",
"env_runners",
"[",
"split_idx",
"]",
"policy_request",
",",
"complete_rollouts",
",",
"episodic_stats... | [
715,
4
] | [
753,
46
] | python | en | ['en', 'error', 'th'] | False |
ActorWorker._process_pbt_task | (self, pbt_task) | Save the latest version of reward shaping from PBT, we later propagate this to envs. | Save the latest version of reward shaping from PBT, we later propagate this to envs. | def _process_pbt_task(self, pbt_task):
"""Save the latest version of reward shaping from PBT, we later propagate this to envs."""
task_type, data = pbt_task
if task_type == PbtTask.UPDATE_REWARD_SCHEME:
policy_id, new_reward_shaping_scheme = data
self.reward_shaping[poli... | [
"def",
"_process_pbt_task",
"(",
"self",
",",
"pbt_task",
")",
":",
"task_type",
",",
"data",
"=",
"pbt_task",
"if",
"task_type",
"==",
"PbtTask",
".",
"UPDATE_REWARD_SCHEME",
":",
"policy_id",
",",
"new_reward_shaping_scheme",
"=",
"data",
"self",
".",
"reward_... | [
755,
4
] | [
761,
70
] | python | en | ['en', 'en', 'en'] | True |
ActorWorker._run | (self) |
Main loop of the actor worker (rollout worker).
Process tasks (mainly ROLLOUT_STEP) until we get the termination signal, which usually means end of training.
Currently there is no mechanism to restart dead workers if something bad happens during training. We can only
retry on the initia... |
Main loop of the actor worker (rollout worker).
Process tasks (mainly ROLLOUT_STEP) until we get the termination signal, which usually means end of training.
Currently there is no mechanism to restart dead workers if something bad happens during training. We can only
retry on the initia... | def _run(self):
"""
Main loop of the actor worker (rollout worker).
Process tasks (mainly ROLLOUT_STEP) until we get the termination signal, which usually means end of training.
Currently there is no mechanism to restart dead workers if something bad happens during training. We can only
... | [
"def",
"_run",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Initializing vector env runner %d...'",
",",
"self",
".",
"worker_idx",
")",
"# workers should ignore Ctrl+C because the termination is handled in the event loop by a special msg",
"signal",
".",
"signal",
"(",
... | [
763,
4
] | [
842,
13
] | python | en | ['en', 'error', 'th'] | False |
VolumeSnapshotsFilterAction.filter | (self, table, snapshots, filter_string) | Naive case-insensitive search. | Naive case-insensitive search. | def filter(self, table, snapshots, filter_string):
"""Naive case-insensitive search."""
query = filter_string.lower()
return [snapshot for snapshot in snapshots
if query in snapshot.name.lower()] | [
"def",
"filter",
"(",
"self",
",",
"table",
",",
"snapshots",
",",
"filter_string",
")",
":",
"query",
"=",
"filter_string",
".",
"lower",
"(",
")",
"return",
"[",
"snapshot",
"for",
"snapshot",
"in",
"snapshots",
"if",
"query",
"in",
"snapshot",
".",
"n... | [
220,
4
] | [
224,
50
] | python | en | ['en', 'it', 'en'] | True |
wrap_text | (text, width) | wrap_text(text : string, width : int) -> [string]
Split 'text' into multiple lines of no more than 'width' characters
each, and return the list of strings that results.
| wrap_text(text : string, width : int) -> [string] | def wrap_text(text, width):
"""wrap_text(text : string, width : int) -> [string]
Split 'text' into multiple lines of no more than 'width' characters
each, and return the list of strings that results.
"""
if text is None:
return []
if len(text) <= width:
return [text]
text =... | [
"def",
"wrap_text",
"(",
"text",
",",
"width",
")",
":",
"if",
"text",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"len",
"(",
"text",
")",
"<=",
"width",
":",
"return",
"[",
"text",
"]",
"text",
"=",
"text",
".",
"expandtabs",
"(",
")",
"text",... | [
374,
0
] | [
425,
16
] | python | en | ['en', 'en', 'en'] | True |
translate_longopt | (opt) | Convert a long option name to a valid Python identifier by
changing "-" to "_".
| Convert a long option name to a valid Python identifier by
changing "-" to "_".
| def translate_longopt(opt):
"""Convert a long option name to a valid Python identifier by
changing "-" to "_".
"""
return opt.translate(longopt_xlate) | [
"def",
"translate_longopt",
"(",
"opt",
")",
":",
"return",
"opt",
".",
"translate",
"(",
"longopt_xlate",
")"
] | [
428,
0
] | [
432,
39
] | python | en | ['en', 'en', 'en'] | True |
FancyGetopt.has_option | (self, long_option) | Return true if the option table for this parser has an
option with long name 'long_option'. | Return true if the option table for this parser has an
option with long name 'long_option'. | def has_option(self, long_option):
"""Return true if the option table for this parser has an
option with long name 'long_option'."""
return long_option in self.option_index | [
"def",
"has_option",
"(",
"self",
",",
"long_option",
")",
":",
"return",
"long_option",
"in",
"self",
".",
"option_index"
] | [
98,
4
] | [
101,
47
] | python | en | ['en', 'en', 'en'] | True |
FancyGetopt.get_attr_name | (self, long_option) | Translate long option name 'long_option' to the form it
has as an attribute of some object: ie., translate hyphens
to underscores. | Translate long option name 'long_option' to the form it
has as an attribute of some object: ie., translate hyphens
to underscores. | def get_attr_name(self, long_option):
"""Translate long option name 'long_option' to the form it
has as an attribute of some object: ie., translate hyphens
to underscores."""
return long_option.translate(longopt_xlate) | [
"def",
"get_attr_name",
"(",
"self",
",",
"long_option",
")",
":",
"return",
"long_option",
".",
"translate",
"(",
"longopt_xlate",
")"
] | [
103,
4
] | [
107,
51
] | python | en | ['en', 'en', 'en'] | True |
FancyGetopt.set_aliases | (self, alias) | Set the aliases for this option parser. | Set the aliases for this option parser. | def set_aliases(self, alias):
"""Set the aliases for this option parser."""
self._check_alias_dict(alias, "alias")
self.alias = alias | [
"def",
"set_aliases",
"(",
"self",
",",
"alias",
")",
":",
"self",
".",
"_check_alias_dict",
"(",
"alias",
",",
"\"alias\"",
")",
"self",
".",
"alias",
"=",
"alias"
] | [
119,
4
] | [
122,
26
] | python | en | ['en', 'en', 'en'] | True |
FancyGetopt.set_negative_aliases | (self, negative_alias) | Set the negative aliases for this option parser.
'negative_alias' should be a dictionary mapping option names to
option names, both the key and value must already be defined
in the option table. | Set the negative aliases for this option parser.
'negative_alias' should be a dictionary mapping option names to
option names, both the key and value must already be defined
in the option table. | def set_negative_aliases(self, negative_alias):
"""Set the negative aliases for this option parser.
'negative_alias' should be a dictionary mapping option names to
option names, both the key and value must already be defined
in the option table."""
self._check_alias_dict(negative... | [
"def",
"set_negative_aliases",
"(",
"self",
",",
"negative_alias",
")",
":",
"self",
".",
"_check_alias_dict",
"(",
"negative_alias",
",",
"\"negative alias\"",
")",
"self",
".",
"negative_alias",
"=",
"negative_alias"
] | [
124,
4
] | [
130,
44
] | python | en | ['en', 'en', 'en'] | True |
FancyGetopt._grok_option_table | (self) | Populate the various data structures that keep tabs on the
option table. Called by 'getopt()' before it can do anything
worthwhile.
| Populate the various data structures that keep tabs on the
option table. Called by 'getopt()' before it can do anything
worthwhile.
| def _grok_option_table(self):
"""Populate the various data structures that keep tabs on the
option table. Called by 'getopt()' before it can do anything
worthwhile.
"""
self.long_opts = []
self.short_opts = []
self.short2long.clear()
self.repeat = {}
... | [
"def",
"_grok_option_table",
"(",
"self",
")",
":",
"self",
".",
"long_opts",
"=",
"[",
"]",
"self",
".",
"short_opts",
"=",
"[",
"]",
"self",
".",
"short2long",
".",
"clear",
"(",
")",
"self",
".",
"repeat",
"=",
"{",
"}",
"for",
"option",
"in",
"... | [
132,
4
] | [
207,
48
] | python | en | ['en', 'en', 'en'] | True |
FancyGetopt.getopt | (self, args=None, object=None) | Parse command-line options in args. Store as attributes on object.
If 'args' is None or not supplied, uses 'sys.argv[1:]'. If
'object' is None or not supplied, creates a new OptionDummy
object, stores option values there, and returns a tuple (args,
object). If 'object' is supplied, it... | Parse command-line options in args. Store as attributes on object. | def getopt(self, args=None, object=None):
"""Parse command-line options in args. Store as attributes on object.
If 'args' is None or not supplied, uses 'sys.argv[1:]'. If
'object' is None or not supplied, creates a new OptionDummy
object, stores option values there, and returns a tuple... | [
"def",
"getopt",
"(",
"self",
",",
"args",
"=",
"None",
",",
"object",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"if",
"object",
"is",
"None",
":",
"object",
"=",
"OptionDummy",
... | [
209,
4
] | [
268,
23
] | python | en | ['en', 'en', 'en'] | True |
FancyGetopt.get_option_order | (self) | Returns the list of (option, value) tuples processed by the
previous run of 'getopt()'. Raises RuntimeError if
'getopt()' hasn't been called yet.
| Returns the list of (option, value) tuples processed by the
previous run of 'getopt()'. Raises RuntimeError if
'getopt()' hasn't been called yet.
| def get_option_order(self):
"""Returns the list of (option, value) tuples processed by the
previous run of 'getopt()'. Raises RuntimeError if
'getopt()' hasn't been called yet.
"""
if self.option_order is None:
raise RuntimeError("'getopt()' hasn't been called yet")
... | [
"def",
"get_option_order",
"(",
"self",
")",
":",
"if",
"self",
".",
"option_order",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"'getopt()' hasn't been called yet\"",
")",
"else",
":",
"return",
"self",
".",
"option_order"
] | [
270,
4
] | [
278,
36
] | python | en | ['en', 'en', 'en'] | True |
FancyGetopt.generate_help | (self, header=None) | Generate help text (a list of strings, one per suggested line of
output) from the option table for this FancyGetopt object.
| Generate help text (a list of strings, one per suggested line of
output) from the option table for this FancyGetopt object.
| def generate_help(self, header=None):
"""Generate help text (a list of strings, one per suggested line of
output) from the option table for this FancyGetopt object.
"""
# Blithely assume the option table is good: probably wouldn't call
# 'generate_help()' unless you've already ca... | [
"def",
"generate_help",
"(",
"self",
",",
"header",
"=",
"None",
")",
":",
"# Blithely assume the option table is good: probably wouldn't call",
"# 'generate_help()' unless you've already called 'getopt()'.",
"# First pass: determine maximum length of long option names",
"max_opt",
"=",
... | [
280,
4
] | [
357,
20
] | python | en | ['en', 'en', 'en'] | True |
OptionDummy.__init__ | (self, options=[]) | Create a new OptionDummy instance. The attributes listed in
'options' will be initialized to None. | Create a new OptionDummy instance. The attributes listed in
'options' will be initialized to None. | def __init__(self, options=[]):
"""Create a new OptionDummy instance. The attributes listed in
'options' will be initialized to None."""
for opt in options:
setattr(self, opt, None) | [
"def",
"__init__",
"(",
"self",
",",
"options",
"=",
"[",
"]",
")",
":",
"for",
"opt",
"in",
"options",
":",
"setattr",
"(",
"self",
",",
"opt",
",",
"None",
")"
] | [
439,
4
] | [
443,
36
] | python | en | ['en', 'en', 'en'] | True |
WrapperFunctionTransformer.__init__ | (self, str_repr, func_transformer) | Create WrapperFunctionTransformer object.
Args:
str_repr (str): text used in str method
func_transformer (sklearn.preprocessing.FunctionTransformer): FunctionTransformer that is used for
fit/transform
| Create WrapperFunctionTransformer object. | def __init__(self, str_repr, func_transformer):
"""Create WrapperFunctionTransformer object.
Args:
str_repr (str): text used in str method
func_transformer (sklearn.preprocessing.FunctionTransformer): FunctionTransformer that is used for
fit/transform
"""... | [
"def",
"__init__",
"(",
"self",
",",
"str_repr",
",",
"func_transformer",
")",
":",
"self",
".",
"str_repr",
"=",
"str_repr",
"self",
".",
"transformer",
"=",
"func_transformer"
] | [
18,
4
] | [
27,
43
] | python | en | ['en', 'en', 'en'] | True |
WrapperFunctionTransformer.fit | (self, *args, **kwargs) | Call fit on transformer attribute. | Call fit on transformer attribute. | def fit(self, *args, **kwargs):
"""Call fit on transformer attribute."""
self.transformer.fit(*args, **kwargs)
return self | [
"def",
"fit",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"transformer",
".",
"fit",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self"
] | [
29,
4
] | [
32,
19
] | python | en | ['en', 'en', 'en'] | True |
WrapperFunctionTransformer.fit_transform | (self, *args, **kwargs) | Call fit_transform on transformer attribute. | Call fit_transform on transformer attribute. | def fit_transform(self, *args, **kwargs):
"""Call fit_transform on transformer attribute."""
return self.transformer.fit_transform(*args, **kwargs) | [
"def",
"fit_transform",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"transformer",
".",
"fit_transform",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
34,
4
] | [
36,
62
] | python | en | ['en', 'en', 'en'] | True |
WrapperFunctionTransformer.get_params | (self, *args, **kwargs) | Call get_params on transformer attribute. | Call get_params on transformer attribute. | def get_params(self, *args, **kwargs):
"""Call get_params on transformer attribute."""
return self.transformer.get_params(*args, **kwargs) | [
"def",
"get_params",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"transformer",
".",
"get_params",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
38,
4
] | [
40,
59
] | python | en | ['en', 'en', 'en'] | True |
WrapperFunctionTransformer.inverse_transform | (self, *args, **kwargs) | Call inverse_transformer on transformer attribute. | Call inverse_transformer on transformer attribute. | def inverse_transform(self, *args, **kwargs):
"""Call inverse_transformer on transformer attribute."""
return self.transformer.inverse_transform(*args, **kwargs) | [
"def",
"inverse_transform",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"transformer",
".",
"inverse_transform",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
42,
4
] | [
44,
66
] | python | en | ['en', 'it', 'en'] | True |
WrapperFunctionTransformer.set_params | (self, **kwargs) | Call set_params on transformer attribute. | Call set_params on transformer attribute. | def set_params(self, **kwargs):
"""Call set_params on transformer attribute."""
self.transformer.set_params(**kwargs)
return self | [
"def",
"set_params",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"transformer",
".",
"set_params",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self"
] | [
46,
4
] | [
49,
19
] | python | en | ['en', 'en', 'en'] | True |
WrapperFunctionTransformer.transform | (self, *args, **kwargs) | Call transform on transformer attribute. | Call transform on transformer attribute. | def transform(self, *args, **kwargs):
"""Call transform on transformer attribute."""
return self.transformer.transform(*args, **kwargs) | [
"def",
"transform",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"transformer",
".",
"transform",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
51,
4
] | [
53,
58
] | python | en | ['en', 'hmn', 'en'] | True |
WrapperFunctionTransformer.__str__ | (self) | Return str of str_repr attribute.
Returns:
str
| Return str of str_repr attribute. | def __str__(self):
"""Return str of str_repr attribute.
Returns:
str
"""
return str(self.str_repr) | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"str",
"(",
"self",
".",
"str_repr",
")"
] | [
55,
4
] | [
61,
33
] | python | en | ['en', 'sl', 'en'] | True |
Transformer.__init__ | (self,
categorical_features,
numerical_features,
target_type,
random_state=None,
classification_pos_label=None
) | Create Transformer object.
Set default transformers for X and y depending on provided categorical and numerical features lists and
target type.
Args:
categorical_features (list): list of categorical features names
numerical_features (list): list of numerical features na... | Create Transformer object. | def __init__(self,
categorical_features,
numerical_features,
target_type,
random_state=None,
classification_pos_label=None
):
"""Create Transformer object.
Set default transformers for X and y dependin... | [
"def",
"__init__",
"(",
"self",
",",
"categorical_features",
",",
"numerical_features",
",",
"target_type",
",",
"random_state",
"=",
"None",
",",
"classification_pos_label",
"=",
"None",
")",
":",
"self",
".",
"categorical_features",
"=",
"categorical_features",
"s... | [
117,
4
] | [
147,
59
] | python | en | ['en', 'en', 'en'] | True |
Transformer.fit | (self, X) | Fit preprocessor_X with X data.
Args:
X (pandas.DataFrame, numpy.ndarray, scipy.csr_matrix): feature space to fit the transformer
Returns:
self
| Fit preprocessor_X with X data. | def fit(self, X):
"""Fit preprocessor_X with X data.
Args:
X (pandas.DataFrame, numpy.ndarray, scipy.csr_matrix): feature space to fit the transformer
Returns:
self
"""
self.preprocessor_X = self.preprocessor_X.fit(X)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"preprocessor_X",
"=",
"self",
".",
"preprocessor_X",
".",
"fit",
"(",
"X",
")",
"return",
"self"
] | [
149,
4
] | [
159,
19
] | python | en | ['en', 'en', 'en'] | True |
Transformer.transform | (self, X) | Transform X with fitted preprocessor_X.
Args:
X (pandas.DataFrame, numpy.ndarray, scipy.csr_matrix): feature space to transform with the transformer
Returns:
numpy.ndarray, scipy.csr_matrix: transformed X
| Transform X with fitted preprocessor_X. | def transform(self, X):
"""Transform X with fitted preprocessor_X.
Args:
X (pandas.DataFrame, numpy.ndarray, scipy.csr_matrix): feature space to transform with the transformer
Returns:
numpy.ndarray, scipy.csr_matrix: transformed X
"""
transformed = self... | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"transformed",
"=",
"self",
".",
"preprocessor_X",
".",
"transform",
"(",
"X",
")",
"return",
"transformed"
] | [
161,
4
] | [
171,
26
] | python | en | ['en', 'en', 'en'] | True |
Transformer.fit_transform | (self, X) | Fit data and then transform it with preprocessor_X.
Args:
X (pandas.DataFrame, numpy.ndarray, scipy.csr_matrix): feature space to fit and transform the transformer
Returns:
numpy.ndarray, scipy.csr_matrix: transformed X
| Fit data and then transform it with preprocessor_X. | def fit_transform(self, X):
"""Fit data and then transform it with preprocessor_X.
Args:
X (pandas.DataFrame, numpy.ndarray, scipy.csr_matrix): feature space to fit and transform the transformer
Returns:
numpy.ndarray, scipy.csr_matrix: transformed X
"""
... | [
"def",
"fit_transform",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"fit",
"(",
"X",
")",
"return",
"self",
".",
"transform",
"(",
"X",
")"
] | [
173,
4
] | [
183,
32
] | python | en | ['en', 'en', 'en'] | True |
Transformer.fit_y | (self, y) | Fit preprocessor_y with y data.
Args:
y (pandas.Series, numpy.ndarray): feature space to fit the transformer
Returns:
self
| Fit preprocessor_y with y data. | def fit_y(self, y):
"""Fit preprocessor_y with y data.
Args:
y (pandas.Series, numpy.ndarray): feature space to fit the transformer
Returns:
self
"""
self.preprocessor_y = self.preprocessor_y.fit(y)
return self | [
"def",
"fit_y",
"(",
"self",
",",
"y",
")",
":",
"self",
".",
"preprocessor_y",
"=",
"self",
".",
"preprocessor_y",
".",
"fit",
"(",
"y",
")",
"return",
"self"
] | [
185,
4
] | [
195,
19
] | python | en | ['en', 'es', 'en'] | True |
Transformer.transform_y | (self, y) | Transform y with fitted preprocessor_y.
Args:
y (pandas.Series, numpy.ndarray): feature space to transform with the transformer
Returns:
numpy.ndarray: transformed y
| Transform y with fitted preprocessor_y. | def transform_y(self, y):
"""Transform y with fitted preprocessor_y.
Args:
y (pandas.Series, numpy.ndarray): feature space to transform with the transformer
Returns:
numpy.ndarray: transformed y
"""
transformed = self.preprocessor_y.transform(y)
... | [
"def",
"transform_y",
"(",
"self",
",",
"y",
")",
":",
"transformed",
"=",
"self",
".",
"preprocessor_y",
".",
"transform",
"(",
"y",
")",
"return",
"transformed"
] | [
197,
4
] | [
207,
26
] | python | en | ['en', 'cy', 'en'] | True |
Transformer.fit_transform_y | (self, y) | Fit data and then transform it with preprocessor_y.
Args:
y (pandas.Series, numpy.ndarray): feature space to fit the transformer
Returns:
numpy.ndarray: transformed y
| Fit data and then transform it with preprocessor_y. | def fit_transform_y(self, y):
"""Fit data and then transform it with preprocessor_y.
Args:
y (pandas.Series, numpy.ndarray): feature space to fit the transformer
Returns:
numpy.ndarray: transformed y
"""
self.fit_y(y)
return self.transform_y(y) | [
"def",
"fit_transform_y",
"(",
"self",
",",
"y",
")",
":",
"self",
".",
"fit_y",
"(",
"y",
")",
"return",
"self",
".",
"transform_y",
"(",
"y",
")"
] | [
209,
4
] | [
219,
34
] | python | en | ['en', 'en', 'en'] | True |
Transformer.set_custom_preprocessor_X | (self, categorical_transformers=None, numerical_transformers=None) | Set preprocessors for categorical and numerical features in X to be used later on in the process (e.g. with
fit or transform calls).
Both lists of transformers are optional - only one type of custom transformers can be set, the other one left
will be set to default transformers. If none of the ... | Set preprocessors for categorical and numerical features in X to be used later on in the process (e.g. with
fit or transform calls). | def set_custom_preprocessor_X(self, categorical_transformers=None, numerical_transformers=None):
"""Set preprocessors for categorical and numerical features in X to be used later on in the process (e.g. with
fit or transform calls).
Both lists of transformers are optional - only one type of cus... | [
"def",
"set_custom_preprocessor_X",
"(",
"self",
",",
"categorical_transformers",
"=",
"None",
",",
"numerical_transformers",
"=",
"None",
")",
":",
"if",
"categorical_transformers",
":",
"self",
".",
"categorical_transformers",
"=",
"categorical_transformers",
"if",
"n... | [
221,
4
] | [
237,
59
] | 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.