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
options
(url, **kwargs)
r"""Sends an OPTIONS request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response
r"""Sends an OPTIONS request.
def options(url, **kwargs): r"""Sends an OPTIONS request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request('options', url, **kwargs)
[ "def", "options", "(", "url", ",", "*", "*", "kwargs", ")", ":", "return", "request", "(", "'options'", ",", "url", ",", "*", "*", "kwargs", ")" ]
[ 77, 0 ]
[ 86, 44 ]
python
en
['en', 'en', 'en']
True
head
(url, **kwargs)
r"""Sends a HEAD request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. If `allow_redirects` is not provided, it will be set to `False` (as opposed to the default :meth:`request` behavior). :return: :class:`Response <Respo...
r"""Sends a HEAD request.
def head(url, **kwargs): r"""Sends a HEAD request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. If `allow_redirects` is not provided, it will be set to `False` (as opposed to the default :meth:`request` behavior). :re...
[ "def", "head", "(", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "False", ")", "return", "request", "(", "'head'", ",", "url", ",", "*", "*", "kwargs", ")" ]
[ 89, 0 ]
[ 101, 41 ]
python
en
['en', 'co', 'en']
True
post
(url, data=None, json=None, **kwargs)
r"""Sends a POST request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kw...
r"""Sends a POST request.
def post(url, data=None, json=None, **kwargs): r"""Sends a POST request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in ...
[ "def", "post", "(", "url", ",", "data", "=", "None", ",", "json", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "request", "(", "'post'", ",", "url", ",", "data", "=", "data", ",", "json", "=", "json", ",", "*", "*", "kwargs", ")" ]
[ 104, 0 ]
[ 116, 63 ]
python
en
['en', 'en', 'en']
True
put
(url, data=None, **kwargs)
r"""Sends a PUT request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwa...
r"""Sends a PUT request.
def put(url, data=None, **kwargs): r"""Sends a PUT request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of t...
[ "def", "put", "(", "url", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "request", "(", "'put'", ",", "url", ",", "data", "=", "data", ",", "*", "*", "kwargs", ")" ]
[ 119, 0 ]
[ 131, 51 ]
python
en
['en', 'co', 'en']
True
patch
(url, data=None, **kwargs)
r"""Sends a PATCH request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*k...
r"""Sends a PATCH request.
def patch(url, data=None, **kwargs): r"""Sends a PATCH request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body ...
[ "def", "patch", "(", "url", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "request", "(", "'patch'", ",", "url", ",", "data", "=", "data", ",", "*", "*", "kwargs", ")" ]
[ 134, 0 ]
[ 146, 53 ]
python
en
['en', 'co', 'en']
True
delete
(url, **kwargs)
r"""Sends a DELETE request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response
r"""Sends a DELETE request.
def delete(url, **kwargs): r"""Sends a DELETE request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request('delete', url, **kwargs)
[ "def", "delete", "(", "url", ",", "*", "*", "kwargs", ")", ":", "return", "request", "(", "'delete'", ",", "url", ",", "*", "*", "kwargs", ")" ]
[ 149, 0 ]
[ 158, 43 ]
python
en
['en', 'it', 'en']
True
split_and_convert_string
(string_tensor)
Splits and converts string tensor into dense float tensor. Given string tensor, splits string by delimiter, converts to and returns dense float tensor. Args: string_tensor: tf.string tensor. Returns: tf.float64 tensor split along delimiter.
Splits and converts string tensor into dense float tensor.
def split_and_convert_string(string_tensor): """Splits and converts string tensor into dense float tensor. Given string tensor, splits string by delimiter, converts to and returns dense float tensor. Args: string_tensor: tf.string tensor. Returns: tf.float64 tensor split along delimiter. """ # ...
[ "def", "split_and_convert_string", "(", "string_tensor", ")", ":", "# Split string tensor into a sparse tensor based on delimiter", "split_string", "=", "tf", ".", "string_split", "(", "source", "=", "tf", ".", "expand_dims", "(", "input", "=", "string_tensor", ",", "ax...
[ 4, 0 ]
[ 38, 28 ]
python
en
['en', 'en', 'en']
True
convert_sequences_from_strings_to_floats
(features, column_list, seq_len)
Converts sequences from single strings to a sequence of floats. Given features dictionary and feature column names list, convert features from strings to a sequence of floats. Args: features: Dictionary of tensors of our features as tf.strings. column_list: List of column names of our features. seq_...
Converts sequences from single strings to a sequence of floats.
def convert_sequences_from_strings_to_floats(features, column_list, seq_len): """Converts sequences from single strings to a sequence of floats. Given features dictionary and feature column names list, convert features from strings to a sequence of floats. Args: features: Dictionary of tensors of our feat...
[ "def", "convert_sequences_from_strings_to_floats", "(", "features", ",", "column_list", ",", "seq_len", ")", ":", "for", "column", "in", "column_list", ":", "features", "[", "column", "]", "=", "split_and_convert_string", "(", "features", "[", "column", "]", ")", ...
[ 41, 0 ]
[ 60, 17 ]
python
en
['en', 'en', 'en']
True
decode_csv
(value_column, mode, batch_size, params)
Decodes CSV file into tensors. Given single string tensor, sequence length, and number of features, returns features dictionary of tensors and labels tensor. Args: value_column: tf.string tensor of shape () compromising entire line of CSV file. mode: The estimator ModeKeys. Can be TRAIN or EVAL. ...
Decodes CSV file into tensors.
def decode_csv(value_column, mode, batch_size, params): """Decodes CSV file into tensors. Given single string tensor, sequence length, and number of features, returns features dictionary of tensors and labels tensor. Args: value_column: tf.string tensor of shape () compromising entire line of CSV fi...
[ "def", "decode_csv", "(", "value_column", ",", "mode", ",", "batch_size", ",", "params", ")", ":", "if", "(", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", "or", "(", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", ...
[ 63, 0 ]
[ 113, 27 ]
python
en
['en', 'en', 'pt']
True
read_dataset
(filename, mode, batch_size, params)
Reads CSV time series dataset using tf.data, doing necessary preprocessing. Given filename, mode, batch size and other parameters, read CSV dataset using Dataset API, apply necessary preprocessing, and return an input function to the Estimator API. Args: filename: The file pattern that we want to read int...
Reads CSV time series dataset using tf.data, doing necessary preprocessing.
def read_dataset(filename, mode, batch_size, params): """Reads CSV time series dataset using tf.data, doing necessary preprocessing. Given filename, mode, batch size and other parameters, read CSV dataset using Dataset API, apply necessary preprocessing, and return an input function to the Estimator API. Ar...
[ "def", "read_dataset", "(", "filename", ",", "mode", ",", "batch_size", ",", "params", ")", ":", "def", "_input_fn", "(", ")", ":", "\"\"\"Wrapper input function to be used by Estimator API to get data tensors.\n\n Returns:\n Batched dataset object of dictionary of feature ...
[ 116, 0 ]
[ 171, 18 ]
python
en
['en', 'en', 'en']
True
Node.iter_fields
(self, exclude=None, only=None)
This method iterates over all fields that are defined and yields ``(key, value)`` tuples. Per default all fields are returned, but it's possible to limit that to some fields by providing the `only` parameter or to exclude some using the `exclude` parameter. Both should be sets or tuple...
This method iterates over all fields that are defined and yields ``(key, value)`` tuples. Per default all fields are returned, but it's possible to limit that to some fields by providing the `only` parameter or to exclude some using the `exclude` parameter. Both should be sets or tuple...
def iter_fields(self, exclude=None, only=None): """This method iterates over all fields that are defined and yields ``(key, value)`` tuples. Per default all fields are returned, but it's possible to limit that to some fields by providing the `only` parameter or to exclude some using the...
[ "def", "iter_fields", "(", "self", ",", "exclude", "=", "None", ",", "only", "=", "None", ")", ":", "for", "name", "in", "self", ".", "fields", ":", "if", "(", "exclude", "is", "only", "is", "None", ")", "or", "(", "exclude", "is", "not", "None", ...
[ 147, 4 ]
[ 161, 24 ]
python
en
['en', 'en', 'en']
True
Node.iter_child_nodes
(self, exclude=None, only=None)
Iterates over all direct child nodes of the node. This iterates over all fields and yields the values of they are nodes. If the value of a field is a list all the nodes in that list are returned.
Iterates over all direct child nodes of the node. This iterates over all fields and yields the values of they are nodes. If the value of a field is a list all the nodes in that list are returned.
def iter_child_nodes(self, exclude=None, only=None): """Iterates over all direct child nodes of the node. This iterates over all fields and yields the values of they are nodes. If the value of a field is a list all the nodes in that list are returned. """ for field, item in sel...
[ "def", "iter_child_nodes", "(", "self", ",", "exclude", "=", "None", ",", "only", "=", "None", ")", ":", "for", "field", ",", "item", "in", "self", ".", "iter_fields", "(", "exclude", ",", "only", ")", ":", "if", "isinstance", "(", "item", ",", "list...
[ 163, 4 ]
[ 174, 26 ]
python
en
['en', 'en', 'en']
True
Node.find
(self, node_type)
Find the first node of a given type. If no such node exists the return value is `None`.
Find the first node of a given type. If no such node exists the return value is `None`.
def find(self, node_type): """Find the first node of a given type. If no such node exists the return value is `None`. """ for result in self.find_all(node_type): return result
[ "def", "find", "(", "self", ",", "node_type", ")", ":", "for", "result", "in", "self", ".", "find_all", "(", "node_type", ")", ":", "return", "result" ]
[ 176, 4 ]
[ 181, 25 ]
python
en
['en', 'en', 'en']
True
Node.find_all
(self, node_type)
Find all the nodes of a given type. If the type is a tuple, the check is performed for any of the tuple items.
Find all the nodes of a given type. If the type is a tuple, the check is performed for any of the tuple items.
def find_all(self, node_type): """Find all the nodes of a given type. If the type is a tuple, the check is performed for any of the tuple items. """ for child in self.iter_child_nodes(): if isinstance(child, node_type): yield child for result in c...
[ "def", "find_all", "(", "self", ",", "node_type", ")", ":", "for", "child", "in", "self", ".", "iter_child_nodes", "(", ")", ":", "if", "isinstance", "(", "child", ",", "node_type", ")", ":", "yield", "child", "for", "result", "in", "child", ".", "find...
[ 183, 4 ]
[ 191, 28 ]
python
en
['en', 'en', 'en']
True
Node.set_ctx
(self, ctx)
Reset the context of a node and all child nodes. Per default the parser will all generate nodes that have a 'load' context as it's the most common one. This method is used in the parser to set assignment targets and other nodes to a store context.
Reset the context of a node and all child nodes. Per default the parser will all generate nodes that have a 'load' context as it's the most common one. This method is used in the parser to set assignment targets and other nodes to a store context.
def set_ctx(self, ctx): """Reset the context of a node and all child nodes. Per default the parser will all generate nodes that have a 'load' context as it's the most common one. This method is used in the parser to set assignment targets and other nodes to a store context. """...
[ "def", "set_ctx", "(", "self", ",", "ctx", ")", ":", "todo", "=", "deque", "(", "[", "self", "]", ")", "while", "todo", ":", "node", "=", "todo", ".", "popleft", "(", ")", "if", "'ctx'", "in", "node", ".", "fields", ":", "node", ".", "ctx", "="...
[ 193, 4 ]
[ 205, 19 ]
python
en
['en', 'en', 'en']
True
Node.set_lineno
(self, lineno, override=False)
Set the line numbers of the node and children.
Set the line numbers of the node and children.
def set_lineno(self, lineno, override=False): """Set the line numbers of the node and children.""" todo = deque([self]) while todo: node = todo.popleft() if 'lineno' in node.attributes: if node.lineno is None or override: node.lineno = ...
[ "def", "set_lineno", "(", "self", ",", "lineno", ",", "override", "=", "False", ")", ":", "todo", "=", "deque", "(", "[", "self", "]", ")", "while", "todo", ":", "node", "=", "todo", ".", "popleft", "(", ")", "if", "'lineno'", "in", "node", ".", ...
[ 207, 4 ]
[ 216, 19 ]
python
en
['en', 'en', 'en']
True
Node.set_environment
(self, environment)
Set the environment for all nodes.
Set the environment for all nodes.
def set_environment(self, environment): """Set the environment for all nodes.""" todo = deque([self]) while todo: node = todo.popleft() node.environment = environment todo.extend(node.iter_child_nodes()) return self
[ "def", "set_environment", "(", "self", ",", "environment", ")", ":", "todo", "=", "deque", "(", "[", "self", "]", ")", "while", "todo", ":", "node", "=", "todo", ".", "popleft", "(", ")", "node", ".", "environment", "=", "environment", "todo", ".", "...
[ 218, 4 ]
[ 225, 19 ]
python
en
['en', 'en', 'en']
True
Expr.as_const
(self, eval_ctx=None)
Return the value of the expression as constant or raise :exc:`Impossible` if this was not possible. An :class:`EvalContext` can be provided, if none is given a default context is created which requires the nodes to have an attached environment. .. versionchanged:: 2.4 ...
Return the value of the expression as constant or raise :exc:`Impossible` if this was not possible.
def as_const(self, eval_ctx=None): """Return the value of the expression as constant or raise :exc:`Impossible` if this was not possible. An :class:`EvalContext` can be provided, if none is given a default context is created which requires the nodes to have an attached environme...
[ "def", "as_const", "(", "self", ",", "eval_ctx", "=", "None", ")", ":", "raise", "Impossible", "(", ")" ]
[ 396, 4 ]
[ 407, 26 ]
python
en
['en', 'en', 'en']
True
Expr.can_assign
(self)
Check if it's possible to assign something to this node.
Check if it's possible to assign something to this node.
def can_assign(self): """Check if it's possible to assign something to this node.""" return False
[ "def", "can_assign", "(", "self", ")", ":", "return", "False" ]
[ 409, 4 ]
[ 411, 20 ]
python
en
['en', 'en', 'en']
True
Const.from_untrusted
(cls, value, lineno=None, environment=None)
Return a const object if the value is representable as constant value in the generated code, otherwise it will raise an `Impossible` exception.
Return a const object if the value is representable as constant value in the generated code, otherwise it will raise an `Impossible` exception.
def from_untrusted(cls, value, lineno=None, environment=None): """Return a const object if the value is representable as constant value in the generated code, otherwise it will raise an `Impossible` exception. """ from .compiler import has_safe_repr if not has_safe_repr(v...
[ "def", "from_untrusted", "(", "cls", ",", "value", ",", "lineno", "=", "None", ",", "environment", "=", "None", ")", ":", "from", ".", "compiler", "import", "has_safe_repr", "if", "not", "has_safe_repr", "(", "value", ")", ":", "raise", "Impossible", "(", ...
[ 503, 4 ]
[ 511, 65 ]
python
en
['en', 'en', 'en']
True
with_metaclass
(meta, *bases)
Create a base class with a metaclass.
Create a base class with a metaclass.
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a # dummy metaclass for one level of class instantiation that replaces # itself with the actual metaclass. class metaclass(type): def __new__(cls, nam...
[ "def", "with_metaclass", "(", "meta", ",", "*", "bases", ")", ":", "# This requires a bit of explanation: the basic idea is to make a", "# dummy metaclass for one level of class instantiation that replaces", "# itself with the actual metaclass.", "class", "metaclass", "(", "type", ")...
[ 84, 0 ]
[ 92, 61 ]
python
en
['en', 'en', 'en']
True
action
(function=None, *, permissions=None, description=None)
Conveniently add attributes to an action function:: @admin.action( permissions=['publish'], description='Mark selected stories as published', ) def make_published(self, request, queryset): queryset.update(status='p') This is equivalent to setting so...
Conveniently add attributes to an action function::
def action(function=None, *, permissions=None, description=None): """ Conveniently add attributes to an action function:: @admin.action( permissions=['publish'], description='Mark selected stories as published', ) def make_published(self, request, queryset): ...
[ "def", "action", "(", "function", "=", "None", ",", "*", ",", "permissions", "=", "None", ",", "description", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "if", "permissions", "is", "not", "None", ":", "func", ".", "allowed_permiss...
[ 0, 0 ]
[ 28, 34 ]
python
en
['en', 'error', 'th']
False
display
(function=None, *, boolean=None, ordering=None, description=None, empty_value=None)
Conveniently add attributes to a display function:: @admin.display( boolean=True, ordering='-publish_date', description='Is Published?', ) def is_published(self, obj): return obj.publish_date is not None This is equivalent to setting som...
Conveniently add attributes to a display function::
def display(function=None, *, boolean=None, ordering=None, description=None, empty_value=None): """ Conveniently add attributes to a display function:: @admin.display( boolean=True, ordering='-publish_date', description='Is Published?', ) def is_publi...
[ "def", "display", "(", "function", "=", "None", ",", "*", ",", "boolean", "=", "None", ",", "ordering", "=", "None", ",", "description", "=", "None", ",", "empty_value", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "if", "boolean...
[ 31, 0 ]
[ 70, 34 ]
python
en
['en', 'error', 'th']
False
register
(*models, site=None)
Register the given model(s) classes and wrapped ModelAdmin class with admin site: @register(Author) class AuthorAdmin(admin.ModelAdmin): pass The `site` kwarg is an admin site to use instead of the default admin site.
Register the given model(s) classes and wrapped ModelAdmin class with admin site:
def register(*models, site=None): """ Register the given model(s) classes and wrapped ModelAdmin class with admin site: @register(Author) class AuthorAdmin(admin.ModelAdmin): pass The `site` kwarg is an admin site to use instead of the default admin site. """ from django.contri...
[ "def", "register", "(", "*", "models", ",", "site", "=", "None", ")", ":", "from", "django", ".", "contrib", ".", "admin", "import", "ModelAdmin", "from", "django", ".", "contrib", ".", "admin", ".", "sites", "import", "AdminSite", ",", "site", "as", "...
[ 73, 0 ]
[ 102, 31 ]
python
en
['en', 'error', 'th']
False
_check_dist_requires_python
( dist: Distribution, version_info: Tuple[int, int, int], ignore_requires_python: bool = False, )
Check whether the given Python version is compatible with a distribution's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the giv...
Check whether the given Python version is compatible with a distribution's "Requires-Python" value.
def _check_dist_requires_python( dist: Distribution, version_info: Tuple[int, int, int], ignore_requires_python: bool = False, ) -> None: """ Check whether the given Python version is compatible with a distribution's "Requires-Python" value. :param version_info: A 3-tuple of ints representi...
[ "def", "_check_dist_requires_python", "(", "dist", ":", "Distribution", ",", "version_info", ":", "Tuple", "[", "int", ",", "int", ",", "int", "]", ",", "ignore_requires_python", ":", "bool", "=", "False", ",", ")", "->", "None", ":", "requires_python", "=",...
[ 51, 0 ]
[ 96, 5 ]
python
en
['en', 'error', 'th']
False
Resolver.resolve
( self, root_reqs: List[InstallRequirement], check_supported_wheels: bool )
Resolve what operations need to be done As a side-effect of this method, the packages (and their dependencies) are downloaded, unpacked and prepared for installation. This preparation is done by ``pip.operations.prepare``. Once PyPI has static dependency metadata available, it would be...
Resolve what operations need to be done
def resolve( self, root_reqs: List[InstallRequirement], check_supported_wheels: bool ) -> RequirementSet: """Resolve what operations need to be done As a side-effect of this method, the packages (and their dependencies) are downloaded, unpacked and prepared for installation. This ...
[ "def", "resolve", "(", "self", ",", "root_reqs", ":", "List", "[", "InstallRequirement", "]", ",", "check_supported_wheels", ":", "bool", ")", "->", "RequirementSet", ":", "requirement_set", "=", "RequirementSet", "(", "check_supported_wheels", "=", "check_supported...
[ 144, 4 ]
[ 179, 30 ]
python
en
['en', 'en', 'en']
True
Resolver._set_req_to_reinstall
(self, req: InstallRequirement)
Set a requirement to be installed.
Set a requirement to be installed.
def _set_req_to_reinstall(self, req: InstallRequirement) -> None: """ Set a requirement to be installed. """ # Don't uninstall the conflict if doing a user install and the # conflict is not a user install. if not self.use_user_site or dist_in_usersite(req.satisfied_by): ...
[ "def", "_set_req_to_reinstall", "(", "self", ",", "req", ":", "InstallRequirement", ")", "->", "None", ":", "# Don't uninstall the conflict if doing a user install and the", "# conflict is not a user install.", "if", "not", "self", ".", "use_user_site", "or", "dist_in_usersit...
[ 190, 4 ]
[ 198, 31 ]
python
en
['en', 'error', 'th']
False
Resolver._check_skip_installed
( self, req_to_install: InstallRequirement )
Check if req_to_install should be skipped. This will check if the req is installed, and whether we should upgrade or reinstall it, taking into account all the relevant user options. After calling this req_to_install will only have satisfied_by set to None if the req_to_install is to be...
Check if req_to_install should be skipped.
def _check_skip_installed( self, req_to_install: InstallRequirement ) -> Optional[str]: """Check if req_to_install should be skipped. This will check if the req is installed, and whether we should upgrade or reinstall it, taking into account all the relevant user options. A...
[ "def", "_check_skip_installed", "(", "self", ",", "req_to_install", ":", "InstallRequirement", ")", "->", "Optional", "[", "str", "]", ":", "if", "self", ".", "ignore_installed", ":", "return", "None", "req_to_install", ".", "check_if_exists", "(", "self", ".", ...
[ 200, 4 ]
[ 252, 19 ]
python
en
['en', 'en', 'en']
True
Resolver._populate_link
(self, req: InstallRequirement)
Ensure that if a link can be found for this, that it is found. Note that req.link may still be None - if the requirement is already installed and not needed to be upgraded based on the return value of _is_upgrade_allowed(). If preparer.require_hashes is True, don't use the wheel cache,...
Ensure that if a link can be found for this, that it is found.
def _populate_link(self, req: InstallRequirement) -> None: """Ensure that if a link can be found for this, that it is found. Note that req.link may still be None - if the requirement is already installed and not needed to be upgraded based on the return value of _is_upgrade_allowed(). ...
[ "def", "_populate_link", "(", "self", ",", "req", ":", "InstallRequirement", ")", "->", "None", ":", "if", "req", ".", "link", "is", "None", ":", "req", ".", "link", "=", "self", ".", "_find_requirement_link", "(", "req", ")", "if", "self", ".", "wheel...
[ 276, 4 ]
[ 303, 39 ]
python
en
['en', 'en', 'en']
True
Resolver._get_dist_for
(self, req: InstallRequirement)
Takes a InstallRequirement and returns a single AbstractDist \ representing a prepared variant of the same.
Takes a InstallRequirement and returns a single AbstractDist \ representing a prepared variant of the same.
def _get_dist_for(self, req: InstallRequirement) -> Distribution: """Takes a InstallRequirement and returns a single AbstractDist \ representing a prepared variant of the same. """ if req.editable: return self.preparer.prepare_editable_requirement(req) # satisfied_by...
[ "def", "_get_dist_for", "(", "self", ",", "req", ":", "InstallRequirement", ")", "->", "Distribution", ":", "if", "req", ".", "editable", ":", "return", "self", ".", "preparer", ".", "prepare_editable_requirement", "(", "req", ")", "# satisfied_by is only evaluate...
[ 305, 4 ]
[ 349, 19 ]
python
en
['en', 'en', 'en']
True
Resolver._resolve_one
( self, requirement_set: RequirementSet, req_to_install: InstallRequirement, )
Prepare a single requirements file. :return: A list of additional InstallRequirements to also install.
Prepare a single requirements file.
def _resolve_one( self, requirement_set: RequirementSet, req_to_install: InstallRequirement, ) -> List[InstallRequirement]: """Prepare a single requirements file. :return: A list of additional InstallRequirements to also install. """ # Tell user what we are d...
[ "def", "_resolve_one", "(", "self", ",", "requirement_set", ":", "RequirementSet", ",", "req_to_install", ":", "InstallRequirement", ",", ")", "->", "List", "[", "InstallRequirement", "]", ":", "# Tell user what we are doing for this requirement:", "# obtain (editable), ski...
[ 351, 4 ]
[ 423, 24 ]
python
en
['en', 'it', 'en']
True
Resolver.get_installation_order
( self, req_set: RequirementSet )
Create the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no other guarantees.
Create the installation order.
def get_installation_order( self, req_set: RequirementSet ) -> List[InstallRequirement]: """Create the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no other ...
[ "def", "get_installation_order", "(", "self", ",", "req_set", ":", "RequirementSet", ")", "->", "List", "[", "InstallRequirement", "]", ":", "# The current implementation, which we may change at any point", "# installs the user specified things in the order given, except when", "# ...
[ 425, 4 ]
[ 452, 20 ]
python
en
['en', 'en', 'en']
True
_add_doc
(func, doc)
Add documentation to a function.
Add documentation to a function.
def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc
[ "def", "_add_doc", "(", "func", ",", "doc", ")", ":", "func", ".", "__doc__", "=", "doc" ]
[ 79, 0 ]
[ 81, 22 ]
python
en
['en', 'en', 'en']
True
_import_module
(name)
Import module, returning the module after the last dot.
Import module, returning the module after the last dot.
def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name]
[ "def", "_import_module", "(", "name", ")", ":", "__import__", "(", "name", ")", "return", "sys", ".", "modules", "[", "name", "]" ]
[ 84, 0 ]
[ 87, 28 ]
python
en
['en', 'en', 'en']
True
add_move
(move)
Add an item to six.moves.
Add an item to six.moves.
def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move)
[ "def", "add_move", "(", "move", ")", ":", "setattr", "(", "_MovedItems", ",", "move", ".", "name", ",", "move", ")" ]
[ 509, 0 ]
[ 511, 41 ]
python
en
['en', 'en', 'en']
True
remove_move
(name)
Remove item from six.moves.
Remove item from six.moves.
def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,))
[ "def", "remove_move", "(", "name", ")", ":", "try", ":", "delattr", "(", "_MovedItems", ",", "name", ")", "except", "AttributeError", ":", "try", ":", "del", "moves", ".", "__dict__", "[", "name", "]", "except", "KeyError", ":", "raise", "AttributeError", ...
[ 514, 0 ]
[ 522, 62 ]
python
en
['en', 'en', 'en']
True
with_metaclass
(meta, *bases)
Create a base class with a metaclass.
Create a base class with a metaclass.
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, na...
[ "def", "with_metaclass", "(", "meta", ",", "*", "bases", ")", ":", "# This requires a bit of explanation: the basic idea is to make a dummy", "# metaclass for one level of class instantiation that replaces itself with", "# the actual metaclass.", "class", "metaclass", "(", "type", ")...
[ 855, 0 ]
[ 876, 61 ]
python
en
['en', 'en', 'en']
True
add_metaclass
(metaclass)
Class decorator for creating a class with a metaclass.
Class decorator for creating a class with a metaclass.
def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slo...
[ "def", "add_metaclass", "(", "metaclass", ")", ":", "def", "wrapper", "(", "cls", ")", ":", "orig_vars", "=", "cls", ".", "__dict__", ".", "copy", "(", ")", "slots", "=", "orig_vars", ".", "get", "(", "'__slots__'", ")", "if", "slots", "is", "not", "...
[ 879, 0 ]
[ 894, 18 ]
python
en
['en', 'en', 'en']
True
ensure_binary
(s, encoding='utf-8', errors='strict')
Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes`
Coerce **s** to six.binary_type.
def ensure_binary(s, encoding='utf-8', errors='strict'): """Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, binary_type): return s ...
[ "def", "ensure_binary", "(", "s", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "if", "isinstance", "(", "s", ",", "binary_type", ")", ":", "return", "s", "if", "isinstance", "(", "s", ",", "text_type", ")", ":", "return", ...
[ 897, 0 ]
[ 912, 56 ]
python
en
['en', 'sn', 'en']
True
ensure_str
(s, encoding='utf-8', errors='strict')
Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str`
Coerce *s* to `str`.
def ensure_str(s, encoding='utf-8', errors='strict'): """Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ # Optimization: Fast return for the common case. if type(s) is s...
[ "def", "ensure_str", "(", "s", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "# Optimization: Fast return for the common case.", "if", "type", "(", "s", ")", "is", "str", ":", "return", "s", "if", "PY2", "and", "isinstance", "(",...
[ 915, 0 ]
[ 935, 12 ]
python
en
['en', 'sl', 'en']
True
ensure_text
(s, encoding='utf-8', errors='strict')
Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str`
Coerce *s* to six.text_type.
def ensure_text(s, encoding='utf-8', errors='strict'): """Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encodin...
[ "def", "ensure_text", "(", "s", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "if", "isinstance", "(", "s", ",", "binary_type", ")", ":", "return", "s", ".", "decode", "(", "encoding", ",", "errors", ")", "elif", "isinstanc...
[ 938, 0 ]
[ 954, 60 ]
python
en
['en', 'sr', 'en']
True
python_2_unicode_compatible
(klass)
A class decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class.
A class decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing.
def python_2_unicode_compatible(klass): """ A class decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if ...
[ "def", "python_2_unicode_compatible", "(", "klass", ")", ":", "if", "PY2", ":", "if", "'__str__'", "not", "in", "klass", ".", "__dict__", ":", "raise", "ValueError", "(", "\"@python_2_unicode_compatible cannot be applied \"", "\"to %s because it doesn't define __str__().\""...
[ 957, 0 ]
[ 972, 16 ]
python
en
['en', 'error', 'th']
False
_SixMetaPathImporter.is_package
(self, fullname)
Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451)
Return true, if the named module is a package.
def is_package(self, fullname): """ Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451) """ return hasattr(self.__get_module(fullname), "__path__")
[ "def", "is_package", "(", "self", ",", "fullname", ")", ":", "return", "hasattr", "(", "self", ".", "__get_module", "(", "fullname", ")", ",", "\"__path__\"", ")" ]
[ 218, 4 ]
[ 225, 63 ]
python
en
['en', 'error', 'th']
False
_SixMetaPathImporter.get_code
(self, fullname)
Return None Required, if is_package is implemented
Return None
def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None
[ "def", "get_code", "(", "self", ",", "fullname", ")", ":", "self", ".", "__get_module", "(", "fullname", ")", "# eventually raises ImportError", "return", "None" ]
[ 227, 4 ]
[ 232, 19 ]
python
en
['en', 'co', 'en']
False
find_commands
(management_dir)
Given a path to a management directory, return a list of all the command names that are available.
Given a path to a management directory, return a list of all the command names that are available.
def find_commands(management_dir): """ Given a path to a management directory, return a list of all the command names that are available. """ command_dir = os.path.join(management_dir, 'commands') return [name for _, name, is_pkg in pkgutil.iter_modules([command_dir]) if not is_pkg a...
[ "def", "find_commands", "(", "management_dir", ")", ":", "command_dir", "=", "os", ".", "path", ".", "join", "(", "management_dir", ",", "'commands'", ")", "return", "[", "name", "for", "_", ",", "name", ",", "is_pkg", "in", "pkgutil", ".", "iter_modules",...
[ 22, 0 ]
[ 29, 55 ]
python
en
['en', 'error', 'th']
False
load_command_class
(app_name, name)
Given a command name and an application name, return the Command class instance. Allow all errors raised by the import process (ImportError, AttributeError) to propagate.
Given a command name and an application name, return the Command class instance. Allow all errors raised by the import process (ImportError, AttributeError) to propagate.
def load_command_class(app_name, name): """ Given a command name and an application name, return the Command class instance. Allow all errors raised by the import process (ImportError, AttributeError) to propagate. """ module = import_module('%s.management.commands.%s' % (app_name, name)) re...
[ "def", "load_command_class", "(", "app_name", ",", "name", ")", ":", "module", "=", "import_module", "(", "'%s.management.commands.%s'", "%", "(", "app_name", ",", "name", ")", ")", "return", "module", ".", "Command", "(", ")" ]
[ 32, 0 ]
[ 39, 27 ]
python
en
['en', 'error', 'th']
False
get_commands
()
Return a dictionary mapping command names to their callback applications. Look for a management.commands package in django.core, and in each installed application -- if a commands package exists, register all commands in that package. Core commands are always included. If a settings module has be...
Return a dictionary mapping command names to their callback applications.
def get_commands(): """ Return a dictionary mapping command names to their callback applications. Look for a management.commands package in django.core, and in each installed application -- if a commands package exists, register all commands in that package. Core commands are always included. ...
[ "def", "get_commands", "(", ")", ":", "commands", "=", "{", "name", ":", "'django.core'", "for", "name", "in", "find_commands", "(", "__path__", "[", "0", "]", ")", "}", "if", "not", "settings", ".", "configured", ":", "return", "commands", "for", "app_c...
[ 43, 0 ]
[ 74, 19 ]
python
en
['en', 'error', 'th']
False
call_command
(command_name, *args, **options)
Call the given command, with the given options and args/kwargs. This is the primary API you should use for calling specific commands. `command_name` may be a string or a command object. Using a string is preferred unless the command object is required for further processing or testing. Some ...
Call the given command, with the given options and args/kwargs.
def call_command(command_name, *args, **options): """ Call the given command, with the given options and args/kwargs. This is the primary API you should use for calling specific commands. `command_name` may be a string or a command object. Using a string is preferred unless the command object is r...
[ "def", "call_command", "(", "command_name", ",", "*", "args", ",", "*", "*", "options", ")", ":", "if", "isinstance", "(", "command_name", ",", "BaseCommand", ")", ":", "# Command object passed in.", "command", "=", "command_name", "command_name", "=", "command"...
[ 77, 0 ]
[ 180, 45 ]
python
en
['en', 'error', 'th']
False
execute_from_command_line
(argv=None)
Run a ManagementUtility.
Run a ManagementUtility.
def execute_from_command_line(argv=None): """Run a ManagementUtility.""" utility = ManagementUtility(argv) utility.execute()
[ "def", "execute_from_command_line", "(", "argv", "=", "None", ")", ":", "utility", "=", "ManagementUtility", "(", "argv", ")", "utility", ".", "execute", "(", ")" ]
[ 415, 0 ]
[ 418, 21 ]
python
en
['es', 'lb', 'en']
False
ManagementUtility.main_help_text
(self, commands_only=False)
Return the script's main help text, as a string.
Return the script's main help text, as a string.
def main_help_text(self, commands_only=False): """Return the script's main help text, as a string.""" if commands_only: usage = sorted(get_commands()) else: usage = [ "", "Type '%s help <subcommand>' for help on a specific subcommand." % se...
[ "def", "main_help_text", "(", "self", ",", "commands_only", "=", "False", ")", ":", "if", "commands_only", ":", "usage", "=", "sorted", "(", "get_commands", "(", ")", ")", "else", ":", "usage", "=", "[", "\"\"", ",", "\"Type '%s help <subcommand>' for help on ...
[ 194, 4 ]
[ 225, 31 ]
python
en
['en', 'gd', 'en']
True
ManagementUtility.fetch_command
(self, subcommand)
Try to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "django-admin" or "manage.py") if it can't be found.
Try to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "django-admin" or "manage.py") if it can't be found.
def fetch_command(self, subcommand): """ Try to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "django-admin" or "manage.py") if it can't be found. """ # Get commands outside of try block to prevent swallo...
[ "def", "fetch_command", "(", "self", ",", "subcommand", ")", ":", "# Get commands outside of try block to prevent swallowing exceptions", "commands", "=", "get_commands", "(", ")", "try", ":", "app_name", "=", "commands", "[", "subcommand", "]", "except", "KeyError", ...
[ 227, 4 ]
[ 257, 20 ]
python
en
['en', 'error', 'th']
False
ManagementUtility.autocomplete
(self)
Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used ...
Output completion suggestions for BASH.
def autocomplete(self): """ Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BA...
[ "def", "autocomplete", "(", "self", ")", ":", "# Don't complete if user hasn't sourced bash_completion file.", "if", "'DJANGO_AUTO_COMPLETE'", "not", "in", "os", ".", "environ", ":", "return", "cwords", "=", "os", ".", "environ", "[", "'COMP_WORDS'", "]", ".", "spli...
[ 259, 4 ]
[ 331, 19 ]
python
en
['en', 'error', 'th']
False
ManagementUtility.execute
(self)
Given the command-line arguments, figure out which subcommand is being run, create a parser appropriate to that command, and run it.
Given the command-line arguments, figure out which subcommand is being run, create a parser appropriate to that command, and run it.
def execute(self): """ Given the command-line arguments, figure out which subcommand is being run, create a parser appropriate to that command, and run it. """ try: subcommand = self.argv[1] except IndexError: subcommand = 'help' # Display help if...
[ "def", "execute", "(", "self", ")", ":", "try", ":", "subcommand", "=", "self", ".", "argv", "[", "1", "]", "except", "IndexError", ":", "subcommand", "=", "'help'", "# Display help if no arguments were given.", "# Preprocess options to extract --settings and --pythonpa...
[ 333, 4 ]
[ 412, 67 ]
python
en
['en', 'error', 'th']
False
command_translate
(bot, user, channel, args)
Transliterates text with Google Translate to English. Usage: translate <text>.
Transliterates text with Google Translate to English. Usage: translate <text>.
def command_translate(bot, user, channel, args): """Transliterates text with Google Translate to English. Usage: translate <text>.""" gtrans = requests.post(gturl, data=gtbody % args, headers=gtheaders) json = gtrans.json() translated = json["sentences"][0]["trans"] bot.say(channel, "From " + js...
[ "def", "command_translate", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "gtrans", "=", "requests", ".", "post", "(", "gturl", ",", "data", "=", "gtbody", "%", "args", ",", "headers", "=", "gtheaders", ")", "json", "=", "gtrans", "...
[ 24, 0 ]
[ 30, 63 ]
python
en
['en', 'en', 'en']
True
command_transliterate
(bot, user, channel, args)
Transliterates text with Google Translate to English. Usage: transliterate <text>.
Transliterates text with Google Translate to English. Usage: transliterate <text>.
def command_transliterate(bot, user, channel, args): """Transliterates text with Google Translate to English. Usage: transliterate <text>.""" gtrans = requests.post(gturl, data=gtbody % args, headers=gtheaders) json = gtrans.json() transliterated = json["sentences"][0]["src_translit"] if transli...
[ "def", "command_transliterate", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "gtrans", "=", "requests", ".", "post", "(", "gturl", ",", "data", "=", "gtbody", "%", "args", ",", "headers", "=", "gtheaders", ")", "json", "=", "gtrans",...
[ 33, 0 ]
[ 42, 71 ]
python
en
['en', 'en', 'en']
True
Timestamp.__init__
(self, seconds, nanoseconds=0)
Initialize a Timestamp object. :param int seconds: Number of seconds since the UNIX epoch (00:00:00 UTC Jan 1 1970, minus leap seconds). May be negative. :param int nanoseconds: Number of nanoseconds to add to `seconds` to get fractional time. Maximum is...
Initialize a Timestamp object.
def __init__(self, seconds, nanoseconds=0): """Initialize a Timestamp object. :param int seconds: Number of seconds since the UNIX epoch (00:00:00 UTC Jan 1 1970, minus leap seconds). May be negative. :param int nanoseconds: Number of nanoseconds to add to `...
[ "def", "__init__", "(", "self", ",", "seconds", ",", "nanoseconds", "=", "0", ")", ":", "if", "not", "isinstance", "(", "seconds", ",", "int_types", ")", ":", "raise", "TypeError", "(", "\"seconds must be an interger\"", ")", "if", "not", "isinstance", "(", ...
[ 44, 4 ]
[ 66, 38 ]
python
en
['en', 'en', 'en']
True
Timestamp.__repr__
(self)
String representation of Timestamp.
String representation of Timestamp.
def __repr__(self): """String representation of Timestamp.""" return "Timestamp(seconds={0}, nanoseconds={1})".format( self.seconds, self.nanoseconds )
[ "def", "__repr__", "(", "self", ")", ":", "return", "\"Timestamp(seconds={0}, nanoseconds={1})\"", ".", "format", "(", "self", ".", "seconds", ",", "self", ".", "nanoseconds", ")" ]
[ 68, 4 ]
[ 72, 9 ]
python
en
['en', 'kk', 'en']
True
Timestamp.__eq__
(self, other)
Check for equality with another Timestamp object
Check for equality with another Timestamp object
def __eq__(self, other): """Check for equality with another Timestamp object""" if type(other) is self.__class__: return ( self.seconds == other.seconds and self.nanoseconds == other.nanoseconds ) return False
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "type", "(", "other", ")", "is", "self", ".", "__class__", ":", "return", "(", "self", ".", "seconds", "==", "other", ".", "seconds", "and", "self", ".", "nanoseconds", "==", "other", ".", ...
[ 74, 4 ]
[ 80, 20 ]
python
en
['en', 'en', 'en']
True
Timestamp.__ne__
(self, other)
not-equals method (see :func:`__eq__()`)
not-equals method (see :func:`__eq__()`)
def __ne__(self, other): """not-equals method (see :func:`__eq__()`)""" return not self.__eq__(other)
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "return", "not", "self", ".", "__eq__", "(", "other", ")" ]
[ 82, 4 ]
[ 84, 37 ]
python
en
['en', 'en', 'en']
True
Timestamp.from_bytes
(b)
Unpack bytes into a `Timestamp` object. Used for pure-Python msgpack unpacking. :param b: Payload from msgpack ext message with code -1 :type b: bytes :returns: Timestamp object unpacked from msgpack ext payload :rtype: Timestamp
Unpack bytes into a `Timestamp` object.
def from_bytes(b): """Unpack bytes into a `Timestamp` object. Used for pure-Python msgpack unpacking. :param b: Payload from msgpack ext message with code -1 :type b: bytes :returns: Timestamp object unpacked from msgpack ext payload :rtype: Timestamp """ ...
[ "def", "from_bytes", "(", "b", ")", ":", "if", "len", "(", "b", ")", "==", "4", ":", "seconds", "=", "struct", ".", "unpack", "(", "\"!L\"", ",", "b", ")", "[", "0", "]", "nanoseconds", "=", "0", "elif", "len", "(", "b", ")", "==", "8", ":", ...
[ 90, 4 ]
[ 114, 46 ]
python
en
['pt', 'en', 'en']
True
Timestamp.to_bytes
(self)
Pack this Timestamp object into bytes. Used for pure-Python msgpack packing. :returns data: Payload for EXT message with code -1 (timestamp type) :rtype: bytes
Pack this Timestamp object into bytes.
def to_bytes(self): """Pack this Timestamp object into bytes. Used for pure-Python msgpack packing. :returns data: Payload for EXT message with code -1 (timestamp type) :rtype: bytes """ if (self.seconds >> 34) == 0: # seconds is non-negative and fits in 34 bits ...
[ "def", "to_bytes", "(", "self", ")", ":", "if", "(", "self", ".", "seconds", ">>", "34", ")", "==", "0", ":", "# seconds is non-negative and fits in 34 bits", "data64", "=", "self", ".", "nanoseconds", "<<", "34", "|", "self", ".", "seconds", "if", "data64...
[ 116, 4 ]
[ 135, 19 ]
python
en
['en', 'en', 'en']
True
Timestamp.from_unix
(unix_sec)
Create a Timestamp from posix timestamp in seconds. :param unix_float: Posix timestamp in seconds. :type unix_float: int or float.
Create a Timestamp from posix timestamp in seconds.
def from_unix(unix_sec): """Create a Timestamp from posix timestamp in seconds. :param unix_float: Posix timestamp in seconds. :type unix_float: int or float. """ seconds = int(unix_sec // 1) nanoseconds = int((unix_sec % 1) * 10 ** 9) return Timestamp(seconds, n...
[ "def", "from_unix", "(", "unix_sec", ")", ":", "seconds", "=", "int", "(", "unix_sec", "//", "1", ")", "nanoseconds", "=", "int", "(", "(", "unix_sec", "%", "1", ")", "*", "10", "**", "9", ")", "return", "Timestamp", "(", "seconds", ",", "nanoseconds...
[ 138, 4 ]
[ 146, 46 ]
python
en
['en', 'en', 'en']
True
Timestamp.to_unix
(self)
Get the timestamp as a floating-point value. :returns: posix timestamp :rtype: float
Get the timestamp as a floating-point value.
def to_unix(self): """Get the timestamp as a floating-point value. :returns: posix timestamp :rtype: float """ return self.seconds + self.nanoseconds / 1e9
[ "def", "to_unix", "(", "self", ")", ":", "return", "self", ".", "seconds", "+", "self", ".", "nanoseconds", "/", "1e9" ]
[ 148, 4 ]
[ 154, 52 ]
python
en
['en', 'en', 'en']
True
Timestamp.from_unix_nano
(unix_ns)
Create a Timestamp from posix timestamp in nanoseconds. :param int unix_ns: Posix timestamp in nanoseconds. :rtype: Timestamp
Create a Timestamp from posix timestamp in nanoseconds.
def from_unix_nano(unix_ns): """Create a Timestamp from posix timestamp in nanoseconds. :param int unix_ns: Posix timestamp in nanoseconds. :rtype: Timestamp """ return Timestamp(*divmod(unix_ns, 10 ** 9))
[ "def", "from_unix_nano", "(", "unix_ns", ")", ":", "return", "Timestamp", "(", "*", "divmod", "(", "unix_ns", ",", "10", "**", "9", ")", ")" ]
[ 157, 4 ]
[ 163, 51 ]
python
en
['en', 'en', 'en']
True
Timestamp.to_unix_nano
(self)
Get the timestamp as a unixtime in nanoseconds. :returns: posix timestamp in nanoseconds :rtype: int
Get the timestamp as a unixtime in nanoseconds.
def to_unix_nano(self): """Get the timestamp as a unixtime in nanoseconds. :returns: posix timestamp in nanoseconds :rtype: int """ return self.seconds * 10 ** 9 + self.nanoseconds
[ "def", "to_unix_nano", "(", "self", ")", ":", "return", "self", ".", "seconds", "*", "10", "**", "9", "+", "self", ".", "nanoseconds" ]
[ 165, 4 ]
[ 171, 56 ]
python
en
['en', 'en', 'en']
True
Timestamp.to_datetime
(self)
Get the timestamp as a UTC datetime. Python 2 is not supported. :rtype: datetime.
Get the timestamp as a UTC datetime.
def to_datetime(self): """Get the timestamp as a UTC datetime. Python 2 is not supported. :rtype: datetime. """ return datetime.datetime.fromtimestamp(0, _utc) + datetime.timedelta( seconds=self.to_unix() )
[ "def", "to_datetime", "(", "self", ")", ":", "return", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "0", ",", "_utc", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "self", ".", "to_unix", "(", ")", ")" ]
[ 173, 4 ]
[ 182, 9 ]
python
en
['en', 'en', 'en']
True
Timestamp.from_datetime
(dt)
Create a Timestamp from datetime with tzinfo. Python 2 is not supported. :rtype: Timestamp
Create a Timestamp from datetime with tzinfo.
def from_datetime(dt): """Create a Timestamp from datetime with tzinfo. Python 2 is not supported. :rtype: Timestamp """ return Timestamp.from_unix(dt.timestamp())
[ "def", "from_datetime", "(", "dt", ")", ":", "return", "Timestamp", ".", "from_unix", "(", "dt", ".", "timestamp", "(", ")", ")" ]
[ 185, 4 ]
[ 192, 50 ]
python
en
['en', 'en', 'en']
True
_make_catapult
(C, x, y)
Builds a catapult.
Builds a catapult.
def _make_catapult(C, x, y): """Builds a catapult.""" # Base of the catapult. base = C.add('static standingsticks ', scale=0.1) \ .set_bottom(y * C.scene.height) \ .set_center_x(x * C.scene.width) # Hinge and top line. bar_center_x = base.left + (base.right - base.left) / ...
[ "def", "_make_catapult", "(", "C", ",", "x", ",", "y", ")", ":", "# Base of the catapult.", "base", "=", "C", ".", "add", "(", "'static standingsticks '", ",", "scale", "=", "0.1", ")", ".", "set_bottom", "(", "y", "*", "C", ".", "scene", ".", "height"...
[ 45, 0 ]
[ 67, 25 ]
python
en
['en', 'en', 'en']
True
salted_hmac
(key_salt, value, secret=None, *, algorithm='sha1')
Return the HMAC of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY). Default algorithm is SHA1, but any algorithm name supported by hashlib can be passed. A different key_salt should be passed in for every application of HMAC.
Return the HMAC of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY). Default algorithm is SHA1, but any algorithm name supported by hashlib can be passed.
def salted_hmac(key_salt, value, secret=None, *, algorithm='sha1'): """ Return the HMAC of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY). Default algorithm is SHA1, but any algorithm name supported by hashlib can be passed. A different key_salt sh...
[ "def", "salted_hmac", "(", "key_salt", ",", "value", ",", "secret", "=", "None", ",", "*", ",", "algorithm", "=", "'sha1'", ")", ":", "if", "secret", "is", "None", ":", "secret", "=", "settings", ".", "SECRET_KEY", "key_salt", "=", "force_bytes", "(", ...
[ 18, 0 ]
[ 45, 66 ]
python
en
['en', 'error', 'th']
False
get_random_string
(length=NOT_PROVIDED, allowed_chars=RANDOM_STRING_CHARS)
Return a securely generated random string. The bit length of the returned value can be calculated with the formula: log_2(len(allowed_chars)^length) For example, with default `allowed_chars` (26+26+10), this gives: * length: 12, bit length =~ 71 bits * length: 22, bit length =~ 131 bi...
Return a securely generated random string.
def get_random_string(length=NOT_PROVIDED, allowed_chars=RANDOM_STRING_CHARS): """ Return a securely generated random string. The bit length of the returned value can be calculated with the formula: log_2(len(allowed_chars)^length) For example, with default `allowed_chars` (26+26+10), this giv...
[ "def", "get_random_string", "(", "length", "=", "NOT_PROVIDED", ",", "allowed_chars", "=", "RANDOM_STRING_CHARS", ")", ":", "if", "length", "is", "NOT_PROVIDED", ":", "warnings", ".", "warn", "(", "'Not providing a length argument is deprecated.'", ",", "RemovedInDjango...
[ 54, 0 ]
[ 71, 72 ]
python
en
['en', 'error', 'th']
False
constant_time_compare
(val1, val2)
Return True if the two strings are equal, False otherwise.
Return True if the two strings are equal, False otherwise.
def constant_time_compare(val1, val2): """Return True if the two strings are equal, False otherwise.""" return secrets.compare_digest(force_bytes(val1), force_bytes(val2))
[ "def", "constant_time_compare", "(", "val1", ",", "val2", ")", ":", "return", "secrets", ".", "compare_digest", "(", "force_bytes", "(", "val1", ")", ",", "force_bytes", "(", "val2", ")", ")" ]
[ 74, 0 ]
[ 76, 71 ]
python
en
['en', 'en', 'en']
True
pbkdf2
(password, salt, iterations, dklen=0, digest=None)
Return the hash of password using pbkdf2.
Return the hash of password using pbkdf2.
def pbkdf2(password, salt, iterations, dklen=0, digest=None): """Return the hash of password using pbkdf2.""" if digest is None: digest = hashlib.sha256 dklen = dklen or None password = force_bytes(password) salt = force_bytes(salt) return hashlib.pbkdf2_hmac(digest().name, password, sal...
[ "def", "pbkdf2", "(", "password", ",", "salt", ",", "iterations", ",", "dklen", "=", "0", ",", "digest", "=", "None", ")", ":", "if", "digest", "is", "None", ":", "digest", "=", "hashlib", ".", "sha256", "dklen", "=", "dklen", "or", "None", "password...
[ 79, 0 ]
[ 86, 80 ]
python
en
['en', 'la', 'en']
True
ConditionalGetMiddleware.needs_etag
(self, response)
Return True if an ETag header should be added to response.
Return True if an ETag header should be added to response.
def needs_etag(self, response): """Return True if an ETag header should be added to response.""" cache_control_headers = cc_delim_re.split(response.get('Cache-Control', '')) return all(header.lower() != 'no-store' for header in cache_control_headers)
[ "def", "needs_etag", "(", "self", ",", "response", ")", ":", "cache_control_headers", "=", "cc_delim_re", ".", "split", "(", "response", ".", "get", "(", "'Cache-Control'", ",", "''", ")", ")", "return", "all", "(", "header", ".", "lower", "(", ")", "!="...
[ 37, 4 ]
[ 40, 84 ]
python
en
['en', 'en', 'en']
True
pretty_name
(name)
Convert 'first_name' to 'First name'.
Convert 'first_name' to 'First name'.
def pretty_name(name): """Convert 'first_name' to 'First name'.""" if not name: return '' return name.replace('_', ' ').capitalize()
[ "def", "pretty_name", "(", "name", ")", ":", "if", "not", "name", ":", "return", "''", "return", "name", ".", "replace", "(", "'_'", ",", "' '", ")", ".", "capitalize", "(", ")" ]
[ 10, 0 ]
[ 14, 46 ]
python
en
['en', 'en', 'en']
True
flatatt
(attrs)
Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. In the case of a boolean value, the key will appear without a value. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary ...
Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. In the case of a boolean value, the key will appear without a value. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary ...
def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. In the case of a boolean value, the key will appear without a value. It is assumed that the keys do not need to be XML-escaped...
[ "def", "flatatt", "(", "attrs", ")", ":", "key_value_attrs", "=", "[", "]", "boolean_attrs", "=", "[", "]", "for", "attr", ",", "value", "in", "attrs", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "if", "val...
[ 17, 0 ]
[ 40, 5 ]
python
en
['en', 'error', 'th']
False
from_current_timezone
(value)
When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes.
When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes.
def from_current_timezone(value): """ When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes. """ if settings.USE_TZ and value is not None and timezone.is_naive(value): current_timezone = timezone.get_current_timezone() try: ...
[ "def", "from_current_timezone", "(", "value", ")", ":", "if", "settings", ".", "USE_TZ", "and", "value", "is", "not", "None", "and", "timezone", ".", "is_naive", "(", "value", ")", ":", "current_timezone", "=", "timezone", ".", "get_current_timezone", "(", "...
[ 155, 0 ]
[ 177, 16 ]
python
en
['en', 'error', 'th']
False
to_current_timezone
(value)
When time zone support is enabled, convert aware datetimes to naive datetimes in the current time zone for display.
When time zone support is enabled, convert aware datetimes to naive datetimes in the current time zone for display.
def to_current_timezone(value): """ When time zone support is enabled, convert aware datetimes to naive datetimes in the current time zone for display. """ if settings.USE_TZ and value is not None and timezone.is_aware(value): return timezone.make_naive(value) return value
[ "def", "to_current_timezone", "(", "value", ")", ":", "if", "settings", ".", "USE_TZ", "and", "value", "is", "not", "None", "and", "timezone", ".", "is_aware", "(", "value", ")", ":", "return", "timezone", ".", "make_naive", "(", "value", ")", "return", ...
[ 180, 0 ]
[ 187, 16 ]
python
en
['en', 'error', 'th']
False
SessionMiddleware.process_response
(self, request, response)
If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied.
If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied.
def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied. """ try: acce...
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "try", ":", "accessed", "=", "request", ".", "session", ".", "accessed", "modified", "=", "request", ".", "session", ".", "modified", "empty", "=", "request", ".", "session"...
[ 23, 4 ]
[ 76, 23 ]
python
en
['en', 'error', 'th']
False
Bucket.reset
(self)
Resets the bucket (unloads the bytecode).
Resets the bucket (unloads the bytecode).
def reset(self): """Resets the bucket (unloads the bytecode).""" self.code = None
[ "def", "reset", "(", "self", ")", ":", "self", ".", "code", "=", "None" ]
[ 74, 4 ]
[ 76, 24 ]
python
en
['en', 'en', 'en']
True
Bucket.load_bytecode
(self, f)
Loads bytecode from a file or file like object.
Loads bytecode from a file or file like object.
def load_bytecode(self, f): """Loads bytecode from a file or file like object.""" # make sure the magic header is correct magic = f.read(len(bc_magic)) if magic != bc_magic: self.reset() return # the source code of the file changed, we need to reload ...
[ "def", "load_bytecode", "(", "self", ",", "f", ")", ":", "# make sure the magic header is correct", "magic", "=", "f", ".", "read", "(", "len", "(", "bc_magic", ")", ")", "if", "magic", "!=", "bc_magic", ":", "self", ".", "reset", "(", ")", "return", "# ...
[ 78, 4 ]
[ 95, 18 ]
python
en
['en', 'en', 'en']
True
Bucket.write_bytecode
(self, f)
Dump the bytecode into the file or file like object passed.
Dump the bytecode into the file or file like object passed.
def write_bytecode(self, f): """Dump the bytecode into the file or file like object passed.""" if self.code is None: raise TypeError('can\'t write empty bucket') f.write(bc_magic) pickle.dump(self.checksum, f, 2) marshal_dump(self.code, f)
[ "def", "write_bytecode", "(", "self", ",", "f", ")", ":", "if", "self", ".", "code", "is", "None", ":", "raise", "TypeError", "(", "'can\\'t write empty bucket'", ")", "f", ".", "write", "(", "bc_magic", ")", "pickle", ".", "dump", "(", "self", ".", "c...
[ 97, 4 ]
[ 103, 34 ]
python
en
['en', 'en', 'en']
True
Bucket.bytecode_from_string
(self, string)
Load bytecode from a string.
Load bytecode from a string.
def bytecode_from_string(self, string): """Load bytecode from a string.""" self.load_bytecode(BytesIO(string))
[ "def", "bytecode_from_string", "(", "self", ",", "string", ")", ":", "self", ".", "load_bytecode", "(", "BytesIO", "(", "string", ")", ")" ]
[ 105, 4 ]
[ 107, 43 ]
python
en
['en', 'en', 'en']
True
Bucket.bytecode_to_string
(self)
Return the bytecode as string.
Return the bytecode as string.
def bytecode_to_string(self): """Return the bytecode as string.""" out = BytesIO() self.write_bytecode(out) return out.getvalue()
[ "def", "bytecode_to_string", "(", "self", ")", ":", "out", "=", "BytesIO", "(", ")", "self", ".", "write_bytecode", "(", "out", ")", "return", "out", ".", "getvalue", "(", ")" ]
[ 109, 4 ]
[ 113, 29 ]
python
en
['en', 'no', 'en']
True
BytecodeCache.load_bytecode
(self, bucket)
Subclasses have to override this method to load bytecode into a bucket. If they are not able to find code in the cache for the bucket, it must not do anything.
Subclasses have to override this method to load bytecode into a bucket. If they are not able to find code in the cache for the bucket, it must not do anything.
def load_bytecode(self, bucket): """Subclasses have to override this method to load bytecode into a bucket. If they are not able to find code in the cache for the bucket, it must not do anything. """ raise NotImplementedError()
[ "def", "load_bytecode", "(", "self", ",", "bucket", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 145, 4 ]
[ 150, 35 ]
python
en
['en', 'en', 'en']
True
BytecodeCache.dump_bytecode
(self, bucket)
Subclasses have to override this method to write the bytecode from a bucket back to the cache. If it unable to do so it must not fail silently but raise an exception.
Subclasses have to override this method to write the bytecode from a bucket back to the cache. If it unable to do so it must not fail silently but raise an exception.
def dump_bytecode(self, bucket): """Subclasses have to override this method to write the bytecode from a bucket back to the cache. If it unable to do so it must not fail silently but raise an exception. """ raise NotImplementedError()
[ "def", "dump_bytecode", "(", "self", ",", "bucket", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 152, 4 ]
[ 157, 35 ]
python
en
['en', 'en', 'en']
True
BytecodeCache.clear
(self)
Clears the cache. This method is not used by Jinja2 but should be implemented to allow applications to clear the bytecode cache used by a particular environment.
Clears the cache. This method is not used by Jinja2 but should be implemented to allow applications to clear the bytecode cache used by a particular environment.
def clear(self): """Clears the cache. This method is not used by Jinja2 but should be implemented to allow applications to clear the bytecode cache used by a particular environment. """
[ "def", "clear", "(", "self", ")", ":" ]
[ 159, 4 ]
[ 163, 11 ]
python
en
['en', 'en', 'en']
True
BytecodeCache.get_cache_key
(self, name, filename=None)
Returns the unique hash key for this template name.
Returns the unique hash key for this template name.
def get_cache_key(self, name, filename=None): """Returns the unique hash key for this template name.""" hash = sha1(name.encode('utf-8')) if filename is not None: filename = '|' + filename if isinstance(filename, text_type): filename = filename.encode('utf...
[ "def", "get_cache_key", "(", "self", ",", "name", ",", "filename", "=", "None", ")", ":", "hash", "=", "sha1", "(", "name", ".", "encode", "(", "'utf-8'", ")", ")", "if", "filename", "is", "not", "None", ":", "filename", "=", "'|'", "+", "filename", ...
[ 165, 4 ]
[ 173, 31 ]
python
en
['en', 'en', 'en']
True
BytecodeCache.get_source_checksum
(self, source)
Returns a checksum for the source.
Returns a checksum for the source.
def get_source_checksum(self, source): """Returns a checksum for the source.""" return sha1(source.encode('utf-8')).hexdigest()
[ "def", "get_source_checksum", "(", "self", ",", "source", ")", ":", "return", "sha1", "(", "source", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")" ]
[ 175, 4 ]
[ 177, 55 ]
python
en
['en', 'en', 'en']
True
BytecodeCache.get_bucket
(self, environment, name, filename, source)
Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`.
Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`.
def get_bucket(self, environment, name, filename, source): """Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`. """ key = self.get_cache_key(name, filename) checksum = self.get_source_checksum(source) bucket = Bucket(en...
[ "def", "get_bucket", "(", "self", ",", "environment", ",", "name", ",", "filename", ",", "source", ")", ":", "key", "=", "self", ".", "get_cache_key", "(", "name", ",", "filename", ")", "checksum", "=", "self", ".", "get_source_checksum", "(", "source", ...
[ 179, 4 ]
[ 187, 21 ]
python
en
['en', 'en', 'en']
True
BytecodeCache.set_bucket
(self, bucket)
Put the bucket into the cache.
Put the bucket into the cache.
def set_bucket(self, bucket): """Put the bucket into the cache.""" self.dump_bytecode(bucket)
[ "def", "set_bucket", "(", "self", ",", "bucket", ")", ":", "self", ".", "dump_bytecode", "(", "bucket", ")" ]
[ 189, 4 ]
[ 191, 34 ]
python
en
['en', 'en', 'en']
True
Towers.__init__
(self, height=1, rods=None, moves=0, verbose=False)
:param int height: The height of the towers (ie: max number of disks each one rod can hold). :param Rods rods: An existing :class:`Rods` instance to use with this :class:`Towers` (the heights must match). :param int moves: The number of moves alre...
:param int height: The height of the towers (ie: max number of disks each one rod can hold). :param Rods rods: An existing :class:`Rods` instance to use with this :class:`Towers` (the heights must match). :param int moves: The number of moves alre...
def __init__(self, height=1, rods=None, moves=0, verbose=False): """ :param int height: The height of the towers (ie: max number of disks each one rod can hold). :param Rods rods: An existing :class:`Rods` instance to use with this :class:`Towers` (the heights must ...
[ "def", "__init__", "(", "self", ",", "height", "=", "1", ",", "rods", "=", "None", ",", "moves", "=", "0", ",", "verbose", "=", "False", ")", ":", "validate_height", "(", "height", ")", "validate_rods", "(", "rods", ")", "validate_moves", "(", "moves",...
[ 43, 4 ]
[ 60, 37 ]
python
en
['en', 'error', 'th']
False
Towers.to_json
(self)
Return a json serializable representation of this instance. :rtype: object
Return a json serializable representation of this instance.
def to_json(self): """ Return a json serializable representation of this instance. :rtype: object """ return { 'height': self.height, 'verbose': self.verbose, 'moves': self.moves, 'rods': self._rods.to_json(), }
[ "def", "to_json", "(", "self", ")", ":", "return", "{", "'height'", ":", "self", ".", "height", ",", "'verbose'", ":", "self", ".", "verbose", ",", "'moves'", ":", "self", ".", "moves", ",", "'rods'", ":", "self", ".", "_rods", ".", "to_json", "(", ...
[ 62, 4 ]
[ 73, 9 ]
python
en
['en', 'error', 'th']
False
Towers.from_json
(cls, d)
Return a class instance from a json serializable representation. :param str|dict d: The json or decoded-json from which to create a new instance. :rtype: Towers :raises: See :class:`Towers`.__new__.
Return a class instance from a json serializable representation.
def from_json(cls, d): """ Return a class instance from a json serializable representation. :param str|dict d: The json or decoded-json from which to create a new instance. :rtype: Towers :raises: See :class:`Towers`.__new__. """ ...
[ "def", "from_json", "(", "cls", ",", "d", ")", ":", "if", "isinstance", "(", "d", ",", "six", ".", "string_types", ")", ":", "d", "=", "json", ".", "loads", "(", "d", ")", "return", "cls", "(", "height", "=", "d", ".", "pop", "(", "'height'", "...
[ 76, 4 ]
[ 94, 9 ]
python
en
['en', 'error', 'th']
False
Towers.context
(self, reset_on_success=True, reset_on_error=False)
Create a temp context for performing moves. The state of this instance will be reset at context exit. :param bool reset_on_success: Reset this instance's state on exit from the context if no error occurred. Default = True. :param bool reset_on_error: ...
Create a temp context for performing moves. The state of this instance will be reset at context exit.
def context(self, reset_on_success=True, reset_on_error=False): """ Create a temp context for performing moves. The state of this instance will be reset at context exit. :param bool reset_on_success: Reset this instance's state on exit from the context if no error occurred. ...
[ "def", "context", "(", "self", ",", "reset_on_success", "=", "True", ",", "reset_on_error", "=", "False", ")", ":", "self", ".", "validate_start", "(", ")", "verbose", "=", "self", ".", "verbose", "moves", "=", "self", ".", "moves", "rods", "=", "self", ...
[ 97, 4 ]
[ 128, 49 ]
python
en
['en', 'error', 'th']
False
Towers.__bool__
(self)
A Towers is considered True if it's state is completed. :rtype: bool
A Towers is considered True if it's state is completed.
def __bool__(self): """ A Towers is considered True if it's state is completed. :rtype: bool """ return self.__nonzero__()
[ "def", "__bool__", "(", "self", ")", ":", "return", "self", ".", "__nonzero__", "(", ")" ]
[ 130, 4 ]
[ 137, 33 ]
python
en
['en', 'error', 'th']
False
Towers.__nonzero__
(self)
A Towers is considered non-zero if it's state is completed. :rtype: bool
A Towers is considered non-zero if it's state is completed.
def __nonzero__(self): """ A Towers is considered non-zero if it's state is completed. :rtype: bool """ try: self.validate_end() return True except Exception: return False
[ "def", "__nonzero__", "(", "self", ")", ":", "try", ":", "self", ".", "validate_end", "(", ")", "return", "True", "except", "Exception", ":", "return", "False" ]
[ 139, 4 ]
[ 150, 24 ]
python
en
['en', 'error', 'th']
False
Towers.__copy__
(self)
Return a shallow copy of this instance. :rtype: :class:`Towers`
Return a shallow copy of this instance.
def __copy__(self): """ Return a shallow copy of this instance. :rtype: :class:`Towers` """ return Towers( height=self.height, rods=self._rods, moves=self.moves, verbose=self.verbose, )
[ "def", "__copy__", "(", "self", ")", ":", "return", "Towers", "(", "height", "=", "self", ".", "height", ",", "rods", "=", "self", ".", "_rods", ",", "moves", "=", "self", ".", "moves", ",", "verbose", "=", "self", ".", "verbose", ",", ")" ]
[ 152, 4 ]
[ 164, 9 ]
python
en
['en', 'error', 'th']
False
Towers.__deepcopy__
(self, *d)
Return a deep copy of this instance. :param dict d: Memoisation dict. :rtype: :class:`Towers`
Return a deep copy of this instance.
def __deepcopy__(self, *d): """ Return a deep copy of this instance. :param dict d: Memoisation dict. :rtype: :class:`Towers` """ return Towers.from_json(self.to_json())
[ "def", "__deepcopy__", "(", "self", ",", "*", "d", ")", ":", "return", "Towers", ".", "from_json", "(", "self", ".", "to_json", "(", ")", ")" ]
[ 166, 4 ]
[ 175, 47 ]
python
en
['en', 'error', 'th']
False
Towers.__eq__
(self, other)
Compare Towers instances for equivalence. :param Towers other: The other :class:`Towers` to compare. :rtype: bool
Compare Towers instances for equivalence.
def __eq__(self, other): """ Compare Towers instances for equivalence. :param Towers other: The other :class:`Towers` to compare. :rtype: bool """ if isinstance(other, Towers): if other.height == self.height: if other._...
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Towers", ")", ":", "if", "other", ".", "height", "==", "self", ".", "height", ":", "if", "other", ".", "_rods", "==", "self", ".", "_rods", ":", "return",...
[ 177, 4 ]
[ 189, 31 ]
python
en
['en', 'error', 'th']
False
Towers.__getitem__
(self, index)
Get the :class:`Rod` at the given index. :param int index: The index to get the :class:`Rod` at. :rtype: Rod
Get the :class:`Rod` at the given index.
def __getitem__(self, index): """ Get the :class:`Rod` at the given index. :param int index: The index to get the :class:`Rod` at. :rtype: Rod """ return self._rods[index]
[ "def", "__getitem__", "(", "self", ",", "index", ")", ":", "return", "self", ".", "_rods", "[", "index", "]" ]
[ 191, 4 ]
[ 200, 32 ]
python
en
['en', 'error', 'th']
False