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
FormMixin.form_valid
(self, form)
If the form is valid, redirect to the supplied URL.
If the form is valid, redirect to the supplied URL.
def form_valid(self, form): """ If the form is valid, redirect to the supplied URL. """ return HttpResponseRedirect(self.get_success_url())
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "return", "HttpResponseRedirect", "(", "self", ".", "get_success_url", "(", ")", ")" ]
[ 74, 4 ]
[ 78, 59 ]
python
en
['en', 'error', 'th']
False
FormMixin.form_invalid
(self, form)
If the form is invalid, re-render the context data with the data-filled form and errors.
If the form is invalid, re-render the context data with the data-filled form and errors.
def form_invalid(self, form): """ If the form is invalid, re-render the context data with the data-filled form and errors. """ return self.render_to_response(self.get_context_data(form=form))
[ "def", "form_invalid", "(", "self", ",", "form", ")", ":", "return", "self", ".", "render_to_response", "(", "self", ".", "get_context_data", "(", "form", "=", "form", ")", ")" ]
[ 80, 4 ]
[ 85, 72 ]
python
en
['en', 'error', 'th']
False
FormMixin.get_context_data
(self, **kwargs)
Insert the form into the context dict.
Insert the form into the context dict.
def get_context_data(self, **kwargs): """ Insert the form into the context dict. """ if 'form' not in kwargs: kwargs['form'] = self.get_form() return super(FormMixin, self).get_context_data(**kwargs)
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "'form'", "not", "in", "kwargs", ":", "kwargs", "[", "'form'", "]", "=", "self", ".", "get_form", "(", ")", "return", "super", "(", "FormMixin", ",", "self", ")", ".", ...
[ 87, 4 ]
[ 93, 64 ]
python
en
['en', 'error', 'th']
False
ModelFormMixin.get_form_class
(self)
Returns the form class to use in this view.
Returns the form class to use in this view.
def get_form_class(self): """ Returns the form class to use in this view. """ if self.fields is not None and self.form_class: raise ImproperlyConfigured( "Specifying both 'fields' and 'form_class' is not permitted." ) if self.form_class: ...
[ "def", "get_form_class", "(", "self", ")", ":", "if", "self", ".", "fields", "is", "not", "None", "and", "self", ".", "form_class", ":", "raise", "ImproperlyConfigured", "(", "\"Specifying both 'fields' and 'form_class' is not permitted.\"", ")", "if", "self", ".", ...
[ 102, 4 ]
[ 131, 75 ]
python
en
['en', 'error', 'th']
False
ModelFormMixin.get_form_kwargs
(self)
Returns the keyword arguments for instantiating the form.
Returns the keyword arguments for instantiating the form.
def get_form_kwargs(self): """ Returns the keyword arguments for instantiating the form. """ kwargs = super(ModelFormMixin, self).get_form_kwargs() if hasattr(self, 'object'): kwargs.update({'instance': self.object}) return kwargs
[ "def", "get_form_kwargs", "(", "self", ")", ":", "kwargs", "=", "super", "(", "ModelFormMixin", ",", "self", ")", ".", "get_form_kwargs", "(", ")", "if", "hasattr", "(", "self", ",", "'object'", ")", ":", "kwargs", ".", "update", "(", "{", "'instance'", ...
[ 133, 4 ]
[ 140, 21 ]
python
en
['en', 'error', 'th']
False
ModelFormMixin.get_success_url
(self)
Returns the supplied URL.
Returns the supplied URL.
def get_success_url(self): """ Returns the supplied URL. """ if self.success_url: url = self.success_url.format(**self.object.__dict__) else: try: url = self.object.get_absolute_url() except AttributeError: raise...
[ "def", "get_success_url", "(", "self", ")", ":", "if", "self", ".", "success_url", ":", "url", "=", "self", ".", "success_url", ".", "format", "(", "*", "*", "self", ".", "object", ".", "__dict__", ")", "else", ":", "try", ":", "url", "=", "self", ...
[ 142, 4 ]
[ 155, 18 ]
python
en
['en', 'error', 'th']
False
ModelFormMixin.form_valid
(self, form)
If the form is valid, save the associated model.
If the form is valid, save the associated model.
def form_valid(self, form): """ If the form is valid, save the associated model. """ self.object = form.save() return super(ModelFormMixin, self).form_valid(form)
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "self", ".", "object", "=", "form", ".", "save", "(", ")", "return", "super", "(", "ModelFormMixin", ",", "self", ")", ".", "form_valid", "(", "form", ")" ]
[ 157, 4 ]
[ 162, 59 ]
python
en
['en', 'error', 'th']
False
ProcessFormView.get
(self, request, *args, **kwargs)
Handles GET requests and instantiates a blank version of the form.
Handles GET requests and instantiates a blank version of the form.
def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates a blank version of the form. """ return self.render_to_response(self.get_context_data())
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "render_to_response", "(", "self", ".", "get_context_data", "(", ")", ")" ]
[ 169, 4 ]
[ 173, 63 ]
python
en
['en', 'error', 'th']
False
ProcessFormView.post
(self, request, *args, **kwargs)
Handles POST requests, instantiating a form instance with the passed POST variables and then checked for validity.
Handles POST requests, instantiating a form instance with the passed POST variables and then checked for validity.
def post(self, request, *args, **kwargs): """ Handles POST requests, instantiating a form instance with the passed POST variables and then checked for validity. """ form = self.get_form() if form.is_valid(): return self.form_valid(form) else: ...
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "form", "=", "self", ".", "get_form", "(", ")", "if", "form", ".", "is_valid", "(", ")", ":", "return", "self", ".", "form_valid", "(", "form", ")", ...
[ 175, 4 ]
[ 184, 42 ]
python
en
['en', 'error', 'th']
False
DeletionMixin.delete
(self, request, *args, **kwargs)
Calls the delete() method on the fetched object and then redirects to the success URL.
Calls the delete() method on the fetched object and then redirects to the success URL.
def delete(self, request, *args, **kwargs): """ Calls the delete() method on the fetched object and then redirects to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.delete() return HttpResponseRedirect...
[ "def", "delete", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "success_url", "=", "self", ".", "get_success_url", "(", ")", "self", ".", "object", ...
[ 256, 4 ]
[ 264, 48 ]
python
en
['en', 'error', 'th']
False
EuclideanDistance.distance
(self, x, y)
Computes distance measure between vectors x and y. Returns float.
Computes distance measure between vectors x and y. Returns float.
def distance(self, x, y): """ Computes distance measure between vectors x and y. Returns float. """ if scipy.sparse.issparse(x): return numpy.linalg.norm((x-y).toarray().ravel()) else: return numpy.linalg.norm(x-y)
[ "def", "distance", "(", "self", ",", "x", ",", "y", ")", ":", "if", "scipy", ".", "sparse", ".", "issparse", "(", "x", ")", ":", "return", "numpy", ".", "linalg", ".", "norm", "(", "(", "x", "-", "y", ")", ".", "toarray", "(", ")", ".", "rave...
[ 31, 4 ]
[ 38, 41 ]
python
en
['en', 'error', 'th']
False
clean_ipv6_address
(ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address."))
Cleans an IPv6 address string. Validity is checked by calling is_valid_ipv6_address() - if an invalid address is passed, ValidationError is raised. Replaces the longest continuous zero-sequence with "::" and removes leading zeroes and makes sure all hextets are lowercase. Args: ip_st...
Cleans an IPv6 address string.
def clean_ipv6_address(ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.")): """ Cleans an IPv6 address string. Validity is checked by calling is_valid_ipv6_address() - if an invalid address is passed, ValidationError is raised. Replaces the longe...
[ "def", "clean_ipv6_address", "(", "ip_str", ",", "unpack_ipv4", "=", "False", ",", "error_message", "=", "_", "(", "\"This is not a valid IPv6 address.\"", ")", ")", ":", "best_doublecolon_start", "=", "-", "1", "best_doublecolon_len", "=", "0", "doublecolon_start", ...
[ 10, 0 ]
[ 89, 25 ]
python
en
['en', 'error', 'th']
False
_sanitize_ipv4_mapping
(ip_str)
Sanitize IPv4 mapping in an expanded IPv6 address. This converts ::ffff:0a0a:0a0a to ::ffff:10.10.10.10. If there is nothing to sanitize, returns an unchanged string. Args: ip_str: A string, the expanded IPv6 address. Returns: The sanitized output string, if applicable.
Sanitize IPv4 mapping in an expanded IPv6 address.
def _sanitize_ipv4_mapping(ip_str): """ Sanitize IPv4 mapping in an expanded IPv6 address. This converts ::ffff:0a0a:0a0a to ::ffff:10.10.10.10. If there is nothing to sanitize, returns an unchanged string. Args: ip_str: A string, the expanded IPv6 address. Returns: The sa...
[ "def", "_sanitize_ipv4_mapping", "(", "ip_str", ")", ":", "if", "not", "ip_str", ".", "lower", "(", ")", ".", "startswith", "(", "'0000:0000:0000:0000:0000:ffff:'", ")", ":", "# not an ipv4 mapping", "return", "ip_str", "hextets", "=", "ip_str", ".", "split", "(...
[ 92, 0 ]
[ 126, 17 ]
python
en
['en', 'error', 'th']
False
_unpack_ipv4
(ip_str)
Unpack an IPv4 address that was mapped in a compressed IPv6 address. This converts 0000:0000:0000:0000:0000:ffff:10.10.10.10 to 10.10.10.10. If there is nothing to sanitize, returns None. Args: ip_str: A string, the expanded IPv6 address. Returns: The unpacked IPv4 address, or No...
Unpack an IPv4 address that was mapped in a compressed IPv6 address.
def _unpack_ipv4(ip_str): """ Unpack an IPv4 address that was mapped in a compressed IPv6 address. This converts 0000:0000:0000:0000:0000:ffff:10.10.10.10 to 10.10.10.10. If there is nothing to sanitize, returns None. Args: ip_str: A string, the expanded IPv6 address. Returns: ...
[ "def", "_unpack_ipv4", "(", "ip_str", ")", ":", "if", "not", "ip_str", ".", "lower", "(", ")", ".", "startswith", "(", "'0000:0000:0000:0000:0000:ffff:'", ")", ":", "return", "None", "return", "ip_str", ".", "rsplit", "(", "':'", ",", "1", ")", "[", "1",...
[ 129, 0 ]
[ 145, 35 ]
python
en
['en', 'error', 'th']
False
is_valid_ipv6_address
(ip_str)
Ensure we have a valid IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A boolean, True if this is a valid IPv6 address.
Ensure we have a valid IPv6 address.
def is_valid_ipv6_address(ip_str): """ Ensure we have a valid IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A boolean, True if this is a valid IPv6 address. """ from django.core.validators import validate_ipv4_address symbols_re = re.compile(r'^[0-9a-fA-...
[ "def", "is_valid_ipv6_address", "(", "ip_str", ")", ":", "from", "django", ".", "core", ".", "validators", "import", "validate_ipv4_address", "symbols_re", "=", "re", ".", "compile", "(", "r'^[0-9a-fA-F:.]+$'", ")", "if", "not", "symbols_re", ".", "match", "(", ...
[ 148, 0 ]
[ 213, 15 ]
python
en
['en', 'error', 'th']
False
_explode_shorthand_ip_string
(ip_str)
Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address.
Expand a shortened IPv6 address.
def _explode_shorthand_ip_string(ip_str): """ Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address. """ if not _is_shorthand_ip(ip_str): # We've already got a longhand ip_str. return ip_str ...
[ "def", "_explode_shorthand_ip_string", "(", "ip_str", ")", ":", "if", "not", "_is_shorthand_ip", "(", "ip_str", ")", ":", "# We've already got a longhand ip_str.", "return", "ip_str", "hextet", "=", "ip_str", ".", "split", "(", "'::'", ")", "# If there is a ::, we nee...
[ 216, 0 ]
[ 256, 27 ]
python
en
['en', 'error', 'th']
False
_is_shorthand_ip
(ip_str)
Determine if the address is shortened. Args: ip_str: A string, the IPv6 address. Returns: A boolean, True if the address is shortened.
Determine if the address is shortened.
def _is_shorthand_ip(ip_str): """Determine if the address is shortened. Args: ip_str: A string, the IPv6 address. Returns: A boolean, True if the address is shortened. """ if ip_str.count('::') == 1: return True if any(len(x) < 4 for x in ip_str.split(':')): ret...
[ "def", "_is_shorthand_ip", "(", "ip_str", ")", ":", "if", "ip_str", ".", "count", "(", "'::'", ")", "==", "1", ":", "return", "True", "if", "any", "(", "len", "(", "x", ")", "<", "4", "for", "x", "in", "ip_str", ".", "split", "(", "':'", ")", "...
[ 259, 0 ]
[ 272, 16 ]
python
en
['en', 'en', 'en']
True
random_result
(*kwargs)
Random objective.
Random objective.
def random_result(*kwargs): """Random objective.""" return round(random.random(),3) * 100
[ "def", "random_result", "(", "*", "kwargs", ")", ":", "return", "round", "(", "random", ".", "random", "(", ")", ",", "3", ")", "*", "100" ]
[ 19, 0 ]
[ 22, 41 ]
python
en
['en', 'mg', 'en']
False
Schedule.silent_delete
(self)
If we are told to prevent_teardown of schedules, then keep them but do not leave them activated, or system will be swamped quickly
If we are told to prevent_teardown of schedules, then keep them but do not leave them activated, or system will be swamped quickly
def silent_delete(self): """If we are told to prevent_teardown of schedules, then keep them but do not leave them activated, or system will be swamped quickly""" try: if not config.prevent_teardown: return self.delete() else: self.patch(ena...
[ "def", "silent_delete", "(", "self", ")", ":", "try", ":", "if", "not", "config", ".", "prevent_teardown", ":", "return", "self", ".", "delete", "(", ")", "else", ":", "self", ".", "patch", "(", "enabled", "=", "False", ")", "except", "(", "exc", "."...
[ 15, 4 ]
[ 24, 16 ]
python
en
['en', 'en', 'en']
True
main
()
Main driver.
Main driver.
def main(): """ Main driver. """ args = parse_args() reporter = Reporter() repo_url = get_repo_url(args.repo_url) check_labels(reporter, repo_url) reporter.report()
[ "def", "main", "(", ")", ":", "args", "=", "parse_args", "(", ")", "reporter", "=", "Reporter", "(", ")", "repo_url", "=", "get_repo_url", "(", "args", ".", "repo_url", ")", "check_labels", "(", "reporter", ",", "repo_url", ")", "reporter", ".", "report"...
[ 58, 0 ]
[ 67, 21 ]
python
en
['en', 'error', 'th']
False
parse_args
()
Parse command-line arguments.
Parse command-line arguments.
def parse_args(): """ Parse command-line arguments. """ parser = ArgumentParser(description="""Check repository settings.""") parser.add_argument('-r', '--repo', default=None, dest='repo_url', help='repository URL') parser....
[ "def", "parse_args", "(", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "\"\"\"Check repository settings.\"\"\"", ")", "parser", ".", "add_argument", "(", "'-r'", ",", "'--repo'", ",", "default", "=", "None", ",", "dest", "=", "'repo_url'",...
[ 70, 0 ]
[ 89, 15 ]
python
en
['en', 'error', 'th']
False
get_repo_url
(repo_url)
Figure out which repository to query.
Figure out which repository to query.
def get_repo_url(repo_url): """ Figure out which repository to query. """ # Explicitly specified. if repo_url is not None: return repo_url # Guess. cmd = 'git remote -v' p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True, universal_newlines=True, e...
[ "def", "get_repo_url", "(", "repo_url", ")", ":", "# Explicitly specified.", "if", "repo_url", "is", "not", "None", ":", "return", "repo_url", "# Guess.", "cmd", "=", "'git remote -v'", "p", "=", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdin", ...
[ 92, 0 ]
[ 121, 14 ]
python
en
['en', 'error', 'th']
False
check_labels
(reporter, repo_url)
Check labels in repository.
Check labels in repository.
def check_labels(reporter, repo_url): """ Check labels in repository. """ actual = get_labels(repo_url) extra = set(actual.keys()) - set(EXPECTED.keys()) reporter.check(not extra, None, 'Extra label(s) in repository {0}: {1}', repo_url, ...
[ "def", "check_labels", "(", "reporter", ",", "repo_url", ")", ":", "actual", "=", "get_labels", "(", "repo_url", ")", "extra", "=", "set", "(", "actual", ".", "keys", "(", ")", ")", "-", "set", "(", "EXPECTED", ".", "keys", "(", ")", ")", "reporter",...
[ 124, 0 ]
[ 148, 68 ]
python
en
['en', 'error', 'th']
False
get_labels
(repo_url)
Get actual labels from repository.
Get actual labels from repository.
def get_labels(repo_url): """ Get actual labels from repository. """ m = P_REPO_URL.match(repo_url) require( m, 'repository URL {0} does not match expected pattern'.format(repo_url)) username = m.group(1) require(username, 'empty username in repository URL {0}'.format(repo_url)) ...
[ "def", "get_labels", "(", "repo_url", ")", ":", "m", "=", "P_REPO_URL", ".", "match", "(", "repo_url", ")", "require", "(", "m", ",", "'repository URL {0} does not match expected pattern'", ".", "format", "(", "repo_url", ")", ")", "username", "=", "m", ".", ...
[ 151, 0 ]
[ 175, 17 ]
python
en
['en', 'error', 'th']
False
DatabaseOperations.date_interval_sql
(self, timedelta)
NUMTODSINTERVAL converts number to INTERVAL DAY TO SECOND literal.
NUMTODSINTERVAL converts number to INTERVAL DAY TO SECOND literal.
def date_interval_sql(self, timedelta): """ NUMTODSINTERVAL converts number to INTERVAL DAY TO SECOND literal. """ return "NUMTODSINTERVAL(%06f, 'SECOND')" % (timedelta.total_seconds()), []
[ "def", "date_interval_sql", "(", "self", ",", "timedelta", ")", ":", "return", "\"NUMTODSINTERVAL(%06f, 'SECOND')\"", "%", "(", "timedelta", ".", "total_seconds", "(", ")", ")", ",", "[", "]" ]
[ 97, 4 ]
[ 101, 82 ]
python
en
['en', 'error', 'th']
False
DatabaseOperations.adapt_datefield_value
(self, value)
Transform a date value to an object compatible with what is expected by the backend driver for date columns. The default implementation transforms the date to text, but that is not necessary for Oracle.
Transform a date value to an object compatible with what is expected by the backend driver for date columns. The default implementation transforms the date to text, but that is not necessary for Oracle.
def adapt_datefield_value(self, value): """ Transform a date value to an object compatible with what is expected by the backend driver for date columns. The default implementation transforms the date to text, but that is not necessary for Oracle. """ return value
[ "def", "adapt_datefield_value", "(", "self", ",", "value", ")", ":", "return", "value" ]
[ 453, 4 ]
[ 460, 20 ]
python
en
['en', 'error', 'th']
False
DatabaseOperations.adapt_datetimefield_value
(self, value)
Transform a datetime value to an object compatible with what is expected by the backend driver for datetime columns. If naive datetime is passed assumes that is in UTC. Normally Django models.DateTimeField makes sure that if USE_TZ is True passed datetime is timezone aware. ...
Transform a datetime value to an object compatible with what is expected by the backend driver for datetime columns.
def adapt_datetimefield_value(self, value): """ Transform a datetime value to an object compatible with what is expected by the backend driver for datetime columns. If naive datetime is passed assumes that is in UTC. Normally Django models.DateTimeField makes sure that if USE_TZ...
[ "def", "adapt_datetimefield_value", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "# Expression values are adapted by the database.", "if", "hasattr", "(", "value", ",", "'resolve_expression'", ")", ":", "return", "value", ...
[ 462, 4 ]
[ 486, 51 ]
python
en
['en', 'error', 'th']
False
user_passes_test
(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME)
Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes.
Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes.
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. ...
[ "def", "user_passes_test", "(", "test_func", ",", "login_url", "=", "None", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ")", ":", "def", "decorator", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs",...
[ 11, 0 ]
[ 36, 20 ]
python
en
['en', 'error', 'th']
False
login_required
(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None)
Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary.
Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary.
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=lo...
[ "def", "login_required", "(", "function", "=", "None", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ",", "login_url", "=", "None", ")", ":", "actual_decorator", "=", "user_passes_test", "(", "lambda", "u", ":", "u", ".", "is_authenticated", ",", "logi...
[ 39, 0 ]
[ 51, 27 ]
python
en
['en', 'error', 'th']
False
permission_required
(perm, login_url=None, raise_exception=False)
Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised.
Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised.
def permission_required(perm, login_url=None, raise_exception=False): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised. """ d...
[ "def", "permission_required", "(", "perm", ",", "login_url", "=", "None", ",", "raise_exception", "=", "False", ")", ":", "def", "check_perms", "(", "user", ")", ":", "if", "isinstance", "(", "perm", ",", "six", ".", "string_types", ")", ":", "perms", "=...
[ 54, 0 ]
[ 74, 61 ]
python
en
['en', 'error', 'th']
False
initial_password
(email: str)
Given an email address, returns the initial password for that account, as created by populate_db.
Given an email address, returns the initial password for that account, as created by populate_db.
def initial_password(email: str) -> Optional[str]: """Given an email address, returns the initial password for that account, as created by populate_db.""" if settings.INITIAL_PASSWORD_SALT is not None: encoded_key = (settings.INITIAL_PASSWORD_SALT + email).encode("utf-8") digest = hashlib.s...
[ "def", "initial_password", "(", "email", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "if", "settings", ".", "INITIAL_PASSWORD_SALT", "is", "not", "None", ":", "encoded_key", "=", "(", "settings", ".", "INITIAL_PASSWORD_SALT", "+", "email", ")", ...
[ 7, 0 ]
[ 17, 19 ]
python
en
['en', 'en', 'en']
True
Color3DLUT.generate
(cls, size, callback, channels=3, target_mode=None)
Generates new LUT using provided callback. :param size: Size of the table. Passed to the constructor. :param callback: Function with three parameters which correspond three color channels. Will be called ``size**3`` times with values from 0.0 to 1.0 and...
Generates new LUT using provided callback.
def generate(cls, size, callback, channels=3, target_mode=None): """Generates new LUT using provided callback. :param size: Size of the table. Passed to the constructor. :param callback: Function with three parameters which correspond three color channels. Will be calle...
[ "def", "generate", "(", "cls", ",", "size", ",", "callback", ",", "channels", "=", "3", ",", "target_mode", "=", "None", ")", ":", "size1D", ",", "size2D", ",", "size3D", "=", "cls", ".", "_check_size", "(", "size", ")", "if", "channels", "not", "in"...
[ 425, 4 ]
[ 457, 9 ]
python
en
['en', 'zu', 'en']
True
Color3DLUT.transform
(self, callback, with_normals=False, channels=None, target_mode=None)
Transforms the table values using provided callback and returns a new LUT with altered values. :param callback: A function which takes old lookup table values and returns a new set of values. The number of arguments which function should take is ...
Transforms the table values using provided callback and returns a new LUT with altered values.
def transform(self, callback, with_normals=False, channels=None, target_mode=None): """Transforms the table values using provided callback and returns a new LUT with altered values. :param callback: A function which takes old lookup table values and returns a new set of...
[ "def", "transform", "(", "self", ",", "callback", ",", "with_normals", "=", "False", ",", "channels", "=", "None", ",", "target_mode", "=", "None", ")", ":", "if", "channels", "not", "in", "(", "None", ",", "3", ",", "4", ")", ":", "raise", "ValueErr...
[ 459, 4 ]
[ 510, 9 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up the Sunpower sensors.
Set up the Sunpower sensors.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Sunpower sensors.""" sunpower_state = hass.data[DOMAIN][config_entry.entry_id] _LOGGER.error("Sunpower_state: %s", sunpower_state) coordinator = sunpower_state[SUNPOWER_COORDINATOR] sunpower_data = coordinator.data ...
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "sunpower_state", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "_LOGGER", ".", "error", "(", "\"Sunpower_sta...
[ 23, 0 ]
[ 50, 38 ]
python
en
['en', 'lb', 'en']
True
SunPowerPVSState.name
(self)
Device Name.
Device Name.
def name(self): """Device Name.""" return "System State"
[ "def", "name", "(", "self", ")", ":", "return", "\"System State\"" ]
[ 57, 4 ]
[ 59, 29 ]
python
en
['en', 'en', 'en']
False
SunPowerPVSState.device_class
(self)
Device Class.
Device Class.
def device_class(self): """Device Class.""" return DEVICE_CLASS_POWER
[ "def", "device_class", "(", "self", ")", ":", "return", "DEVICE_CLASS_POWER" ]
[ 62, 4 ]
[ 64, 33 ]
python
en
['en', 'zh', 'en']
False
SunPowerPVSState.unique_id
(self)
Device Uniqueid.
Device Uniqueid.
def unique_id(self): """Device Uniqueid.""" return f"{self.base_unique_id}_pvs_state"
[ "def", "unique_id", "(", "self", ")", ":", "return", "f\"{self.base_unique_id}_pvs_state\"" ]
[ 67, 4 ]
[ 69, 49 ]
python
fr
['fr', 'fr', 'en']
False
SunPowerPVSState.state
(self)
Get the current value
Get the current value
def state(self): """Get the current value""" return self.coordinator.data[PVS_DEVICE_TYPE][self.base_unique_id][PVS_STATE]
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "coordinator", ".", "data", "[", "PVS_DEVICE_TYPE", "]", "[", "self", ".", "base_unique_id", "]", "[", "PVS_STATE", "]" ]
[ 72, 4 ]
[ 74, 85 ]
python
en
['en', 'en', 'en']
True
SunPowerPVSState.is_on
(self)
Return true if the binary sensor is on.
Return true if the binary sensor is on.
def is_on(self): """Return true if the binary sensor is on.""" return self.state == WORKING_STATE
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "state", "==", "WORKING_STATE" ]
[ 77, 4 ]
[ 79, 42 ]
python
en
['en', 'fy', 'en']
True
SunPowerMeterState.name
(self)
Device Name.
Device Name.
def name(self): """Device Name.""" return "System State"
[ "def", "name", "(", "self", ")", ":", "return", "\"System State\"" ]
[ 86, 4 ]
[ 88, 29 ]
python
en
['en', 'en', 'en']
False
SunPowerMeterState.device_class
(self)
Device Class.
Device Class.
def device_class(self): """Device Class.""" return DEVICE_CLASS_POWER
[ "def", "device_class", "(", "self", ")", ":", "return", "DEVICE_CLASS_POWER" ]
[ 91, 4 ]
[ 93, 33 ]
python
en
['en', 'zh', 'en']
False
SunPowerMeterState.unique_id
(self)
Device Uniqueid.
Device Uniqueid.
def unique_id(self): """Device Uniqueid.""" return f"{self.base_unique_id}_meter_state"
[ "def", "unique_id", "(", "self", ")", ":", "return", "f\"{self.base_unique_id}_meter_state\"" ]
[ 96, 4 ]
[ 98, 51 ]
python
fr
['fr', 'fr', 'en']
False
SunPowerMeterState.state
(self)
Get the current value
Get the current value
def state(self): """Get the current value""" return self.coordinator.data[METER_DEVICE_TYPE][self.base_unique_id][METER_STATE]
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "coordinator", ".", "data", "[", "METER_DEVICE_TYPE", "]", "[", "self", ".", "base_unique_id", "]", "[", "METER_STATE", "]" ]
[ 101, 4 ]
[ 103, 89 ]
python
en
['en', 'en', 'en']
True
SunPowerMeterState.is_on
(self)
Return true if the binary sensor is on.
Return true if the binary sensor is on.
def is_on(self): """Return true if the binary sensor is on.""" return self.state == WORKING_STATE
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "state", "==", "WORKING_STATE" ]
[ 106, 4 ]
[ 108, 42 ]
python
en
['en', 'fy', 'en']
True
SunPowerInverterState.name
(self)
Device Name.
Device Name.
def name(self): """Device Name.""" return "System State"
[ "def", "name", "(", "self", ")", ":", "return", "\"System State\"" ]
[ 115, 4 ]
[ 117, 29 ]
python
en
['en', 'en', 'en']
False
SunPowerInverterState.device_class
(self)
Device Class.
Device Class.
def device_class(self): """Device Class.""" return DEVICE_CLASS_POWER
[ "def", "device_class", "(", "self", ")", ":", "return", "DEVICE_CLASS_POWER" ]
[ 120, 4 ]
[ 122, 33 ]
python
en
['en', 'zh', 'en']
False
SunPowerInverterState.unique_id
(self)
Device Uniqueid.
Device Uniqueid.
def unique_id(self): """Device Uniqueid.""" return f"{self.base_unique_id}_inverter_state"
[ "def", "unique_id", "(", "self", ")", ":", "return", "f\"{self.base_unique_id}_inverter_state\"" ]
[ 125, 4 ]
[ 127, 54 ]
python
fr
['fr', 'fr', 'en']
False
SunPowerInverterState.state
(self)
Get the current value
Get the current value
def state(self): """Get the current value""" return self.coordinator.data[INVERTER_DEVICE_TYPE][self.base_unique_id][INVERTER_STATE]
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "coordinator", ".", "data", "[", "INVERTER_DEVICE_TYPE", "]", "[", "self", ".", "base_unique_id", "]", "[", "INVERTER_STATE", "]" ]
[ 130, 4 ]
[ 132, 95 ]
python
en
['en', 'en', 'en']
True
SunPowerInverterState.is_on
(self)
Return true if the binary sensor is on.
Return true if the binary sensor is on.
def is_on(self): """Return true if the binary sensor is on.""" return self.state == WORKING_STATE
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "state", "==", "WORKING_STATE" ]
[ 135, 4 ]
[ 137, 42 ]
python
en
['en', 'fy', 'en']
True
DummyImageTransform.resize
(self, size)
Change the image size, stretching the transform to make it fit the new size.
Change the image size, stretching the transform to make it fit the new size.
def resize(self, size): """ Change the image size, stretching the transform to make it fit the new size. """ self._check_size(size) clone = self.clone() clone.operations.append(('resize', size)) clone.size = size return clone
[ "def", "resize", "(", "self", ",", "size", ")", ":", "self", ".", "_check_size", "(", "size", ")", "clone", "=", "self", ".", "clone", "(", ")", "clone", ".", "operations", ".", "append", "(", "(", "'resize'", ",", "size", ")", ")", "clone", ".", ...
[ 29, 4 ]
[ 37, 20 ]
python
en
['en', 'error', 'th']
False
DummyImageTransform.crop
(self, rect)
Crop the image to the specified rect.
Crop the image to the specified rect.
def crop(self, rect): """ Crop the image to the specified rect. """ self._check_size(tuple(rect.size)) clone = self.clone() clone.operations.append(('crop', tuple(rect))) clone.size = tuple(rect.size) return clone
[ "def", "crop", "(", "self", ",", "rect", ")", ":", "self", ".", "_check_size", "(", "tuple", "(", "rect", ".", "size", ")", ")", "clone", "=", "self", ".", "clone", "(", ")", "clone", ".", "operations", ".", "append", "(", "(", "'crop'", ",", "tu...
[ 39, 4 ]
[ 47, 20 ]
python
en
['en', 'error', 'th']
False
TestWebpFormatConversion.test_webp_convert_to_png
(self)
by default, webp images will be converted to png
by default, webp images will be converted to png
def test_webp_convert_to_png(self): """by default, webp images will be converted to png""" fil = Filter(spec='width-400') image = Image.objects.create( title="Test image", file=get_test_image_file_webp(), ) out = fil.run(image, BytesIO()) self.as...
[ "def", "test_webp_convert_to_png", "(", "self", ")", ":", "fil", "=", "Filter", "(", "spec", "=", "'width-400'", ")", "image", "=", "Image", ".", "objects", ".", "create", "(", "title", "=", "\"Test image\"", ",", "file", "=", "get_test_image_file_webp", "("...
[ 786, 4 ]
[ 796, 48 ]
python
en
['en', 'en', 'en']
True
TestWebpFormatConversion.test_override_webp_convert_to_png
(self)
WAGTAILIMAGES_FORMAT_CONVERSIONS can be overridden to disable webp conversion
WAGTAILIMAGES_FORMAT_CONVERSIONS can be overridden to disable webp conversion
def test_override_webp_convert_to_png(self): """WAGTAILIMAGES_FORMAT_CONVERSIONS can be overridden to disable webp conversion""" fil = Filter(spec='width-400') image = Image.objects.create( title="Test image", file=get_test_image_file_webp(), ) out = fil....
[ "def", "test_override_webp_convert_to_png", "(", "self", ")", ":", "fil", "=", "Filter", "(", "spec", "=", "'width-400'", ")", "image", "=", "Image", ".", "objects", ".", "create", "(", "title", "=", "\"Test image\"", ",", "file", "=", "get_test_image_file_web...
[ 801, 4 ]
[ 811, 49 ]
python
en
['en', 'en', 'sw']
True
Command.get_new_strings
( self, old_strings: Mapping[str, str], translation_strings: List[str], locale: str )
Missing strings are removed, new strings are added and already translated strings are not touched.
Missing strings are removed, new strings are added and already translated strings are not touched.
def get_new_strings( self, old_strings: Mapping[str, str], translation_strings: List[str], locale: str ) -> Dict[str, str]: """ Missing strings are removed, new strings are added and already translated strings are not touched. """ new_strings = {} # Dict[str, str] ...
[ "def", "get_new_strings", "(", "self", ",", "old_strings", ":", "Mapping", "[", "str", ",", "str", "]", ",", "translation_strings", ":", "List", "[", "str", "]", ",", "locale", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "new_str...
[ 249, 4 ]
[ 264, 26 ]
python
en
['en', 'error', 'th']
False
default_key_func
(key, key_prefix, version)
Default function to generate keys. Constructs the key used by all other methods. By default it prepends the `key_prefix'. KEY_FUNCTION can be used to specify an alternate function with custom key making behavior.
Default function to generate keys.
def default_key_func(key, key_prefix, version): """ Default function to generate keys. Constructs the key used by all other methods. By default it prepends the `key_prefix'. KEY_FUNCTION can be used to specify an alternate function with custom key making behavior. """ return '%s:%s:%s' % (k...
[ "def", "default_key_func", "(", "key", ",", "key_prefix", ",", "version", ")", ":", "return", "'%s:%s:%s'", "%", "(", "key_prefix", ",", "version", ",", "key", ")" ]
[ 26, 0 ]
[ 34, 50 ]
python
en
['en', 'error', 'th']
False
get_key_func
(key_func)
Function to decide which key function to use. Defaults to ``default_key_func``.
Function to decide which key function to use.
def get_key_func(key_func): """ Function to decide which key function to use. Defaults to ``default_key_func``. """ if key_func is not None: if callable(key_func): return key_func else: return import_string(key_func) return default_key_func
[ "def", "get_key_func", "(", "key_func", ")", ":", "if", "key_func", "is", "not", "None", ":", "if", "callable", "(", "key_func", ")", ":", "return", "key_func", "else", ":", "return", "import_string", "(", "key_func", ")", "return", "default_key_func" ]
[ 37, 0 ]
[ 48, 27 ]
python
en
['en', 'error', 'th']
False
BaseCache.get_backend_timeout
(self, timeout=DEFAULT_TIMEOUT)
Returns the timeout value usable by this backend based upon the provided timeout.
Returns the timeout value usable by this backend based upon the provided timeout.
def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT): """ Returns the timeout value usable by this backend based upon the provided timeout. """ if timeout == DEFAULT_TIMEOUT: timeout = self.default_timeout elif timeout == 0: # ticket 21147 - avoi...
[ "def", "get_backend_timeout", "(", "self", ",", "timeout", "=", "DEFAULT_TIMEOUT", ")", ":", "if", "timeout", "==", "DEFAULT_TIMEOUT", ":", "timeout", "=", "self", ".", "default_timeout", "elif", "timeout", "==", "0", ":", "# ticket 21147 - avoid time.time() related...
[ 78, 4 ]
[ 88, 65 ]
python
en
['en', 'error', 'th']
False
BaseCache.make_key
(self, key, version=None)
Constructs the key used by all other methods. By default it uses the key_func to generate a key (which, by default, prepends the `key_prefix' and 'version'). A different key function can be provided at the time of cache construction; alternatively, you can subclass the cache backend to p...
Constructs the key used by all other methods. By default it uses the key_func to generate a key (which, by default, prepends the `key_prefix' and 'version'). A different key function can be provided at the time of cache construction; alternatively, you can subclass the cache backend to p...
def make_key(self, key, version=None): """Constructs the key used by all other methods. By default it uses the key_func to generate a key (which, by default, prepends the `key_prefix' and 'version'). A different key function can be provided at the time of cache construction; alte...
[ "def", "make_key", "(", "self", ",", "key", ",", "version", "=", "None", ")", ":", "if", "version", "is", "None", ":", "version", "=", "self", ".", "version", "new_key", "=", "self", ".", "key_func", "(", "key", ",", "self", ".", "key_prefix", ",", ...
[ 90, 4 ]
[ 102, 22 ]
python
en
['en', 'en', 'en']
True
BaseCache.add
(self, key, value, timeout=DEFAULT_TIMEOUT, version=None)
Set a value in the cache if the key does not already exist. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. Returns True if the value was stored, False otherwise.
Set a value in the cache if the key does not already exist. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used.
def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): """ Set a value in the cache if the key does not already exist. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. Returns True if the value was stored, F...
[ "def", "add", "(", "self", ",", "key", ",", "value", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "version", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseCache must provide an add() method'", ")" ]
[ 104, 4 ]
[ 112, 89 ]
python
en
['en', 'error', 'th']
False
BaseCache.get
(self, key, default=None, version=None)
Fetch a given key from the cache. If the key does not exist, return default, which itself defaults to None.
Fetch a given key from the cache. If the key does not exist, return default, which itself defaults to None.
def get(self, key, default=None, version=None): """ Fetch a given key from the cache. If the key does not exist, return default, which itself defaults to None. """ raise NotImplementedError('subclasses of BaseCache must provide a get() method')
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ",", "version", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseCache must provide a get() method'", ")" ]
[ 114, 4 ]
[ 119, 88 ]
python
en
['en', 'error', 'th']
False
BaseCache.set
(self, key, value, timeout=DEFAULT_TIMEOUT, version=None)
Set a value in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used.
Set a value in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used.
def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): """ Set a value in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. """ raise NotImplementedError('subclasses of BaseCache must provide a set(...
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "version", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseCache must provide a set() method'", ")" ]
[ 121, 4 ]
[ 126, 88 ]
python
en
['en', 'error', 'th']
False
BaseCache.delete
(self, key, version=None)
Delete a key from the cache, failing silently.
Delete a key from the cache, failing silently.
def delete(self, key, version=None): """ Delete a key from the cache, failing silently. """ raise NotImplementedError('subclasses of BaseCache must provide a delete() method')
[ "def", "delete", "(", "self", ",", "key", ",", "version", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseCache must provide a delete() method'", ")" ]
[ 128, 4 ]
[ 132, 91 ]
python
en
['en', 'error', 'th']
False
BaseCache.get_many
(self, keys, version=None)
Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values. Returns a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the response dict.
Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values.
def get_many(self, keys, version=None): """ Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values. Returns a dict mapping each key in keys to its value. If the given key is missing, it will be missin...
[ "def", "get_many", "(", "self", ",", "keys", ",", "version", "=", "None", ")", ":", "d", "=", "{", "}", "for", "k", "in", "keys", ":", "val", "=", "self", ".", "get", "(", "k", ",", "version", "=", "version", ")", "if", "val", "is", "not", "N...
[ 134, 4 ]
[ 147, 16 ]
python
en
['en', 'error', 'th']
False
BaseCache.get_or_set
(self, key, default, timeout=DEFAULT_TIMEOUT, version=None)
Fetch a given key from the cache. If the key does not exist, the key is added and set to the default value. The default value can also be any callable. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. Return the value...
Fetch a given key from the cache. If the key does not exist, the key is added and set to the default value. The default value can also be any callable. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used.
def get_or_set(self, key, default, timeout=DEFAULT_TIMEOUT, version=None): """ Fetch a given key from the cache. If the key does not exist, the key is added and set to the default value. The default value can also be any callable. If timeout is given, that timeout will be used fo...
[ "def", "get_or_set", "(", "self", ",", "key", ",", "default", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "version", "=", "None", ")", ":", "val", "=", "self", ".", "get", "(", "key", ",", "version", "=", "version", ")", "if", "val", "is", "None", ...
[ 149, 4 ]
[ 166, 18 ]
python
en
['en', 'error', 'th']
False
BaseCache.has_key
(self, key, version=None)
Returns True if the key is in the cache and has not expired.
Returns True if the key is in the cache and has not expired.
def has_key(self, key, version=None): """ Returns True if the key is in the cache and has not expired. """ return self.get(key, version=version) is not None
[ "def", "has_key", "(", "self", ",", "key", ",", "version", "=", "None", ")", ":", "return", "self", ".", "get", "(", "key", ",", "version", "=", "version", ")", "is", "not", "None" ]
[ 168, 4 ]
[ 172, 57 ]
python
en
['en', 'error', 'th']
False
BaseCache.incr
(self, key, delta=1, version=None)
Add delta to value in the cache. If the key does not exist, raise a ValueError exception.
Add delta to value in the cache. If the key does not exist, raise a ValueError exception.
def incr(self, key, delta=1, version=None): """ Add delta to value in the cache. If the key does not exist, raise a ValueError exception. """ value = self.get(key, version=version) if value is None: raise ValueError("Key '%s' not found" % key) new_valu...
[ "def", "incr", "(", "self", ",", "key", ",", "delta", "=", "1", ",", "version", "=", "None", ")", ":", "value", "=", "self", ".", "get", "(", "key", ",", "version", "=", "version", ")", "if", "value", "is", "None", ":", "raise", "ValueError", "("...
[ 174, 4 ]
[ 184, 24 ]
python
en
['en', 'error', 'th']
False
BaseCache.decr
(self, key, delta=1, version=None)
Subtract delta from value in the cache. If the key does not exist, raise a ValueError exception.
Subtract delta from value in the cache. If the key does not exist, raise a ValueError exception.
def decr(self, key, delta=1, version=None): """ Subtract delta from value in the cache. If the key does not exist, raise a ValueError exception. """ return self.incr(key, -delta, version=version)
[ "def", "decr", "(", "self", ",", "key", ",", "delta", "=", "1", ",", "version", "=", "None", ")", ":", "return", "self", ".", "incr", "(", "key", ",", "-", "delta", ",", "version", "=", "version", ")" ]
[ 186, 4 ]
[ 191, 54 ]
python
en
['en', 'error', 'th']
False
BaseCache.__contains__
(self, key)
Returns True if the key is in the cache and has not expired.
Returns True if the key is in the cache and has not expired.
def __contains__(self, key): """ Returns True if the key is in the cache and has not expired. """ # This is a separate method, rather than just a copy of has_key(), # so that it always has the same functionality as has_key(), even # if a subclass overrides it. ret...
[ "def", "__contains__", "(", "self", ",", "key", ")", ":", "# This is a separate method, rather than just a copy of has_key(),", "# so that it always has the same functionality as has_key(), even", "# if a subclass overrides it.", "return", "self", ".", "has_key", "(", "key", ")" ]
[ 193, 4 ]
[ 200, 32 ]
python
en
['en', 'error', 'th']
False
BaseCache.set_many
(self, data, timeout=DEFAULT_TIMEOUT, version=None)
Set a bunch of values in the cache at once from a dict of key/value pairs. For certain backends (memcached), this is much more efficient than calling set() multiple times. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be u...
Set a bunch of values in the cache at once from a dict of key/value pairs. For certain backends (memcached), this is much more efficient than calling set() multiple times.
def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None): """ Set a bunch of values in the cache at once from a dict of key/value pairs. For certain backends (memcached), this is much more efficient than calling set() multiple times. If timeout is given, that timeout wil...
[ "def", "set_many", "(", "self", ",", "data", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "version", "=", "None", ")", ":", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", "self", ".", "set", "(", "key", ",", "value", ",", ...
[ 202, 4 ]
[ 212, 66 ]
python
en
['en', 'error', 'th']
False
BaseCache.delete_many
(self, keys, version=None)
Delete a bunch of values in the cache at once. For certain backends (memcached), this is much more efficient than calling delete() multiple times.
Delete a bunch of values in the cache at once. For certain backends (memcached), this is much more efficient than calling delete() multiple times.
def delete_many(self, keys, version=None): """ Delete a bunch of values in the cache at once. For certain backends (memcached), this is much more efficient than calling delete() multiple times. """ for key in keys: self.delete(key, version=version)
[ "def", "delete_many", "(", "self", ",", "keys", ",", "version", "=", "None", ")", ":", "for", "key", "in", "keys", ":", "self", ".", "delete", "(", "key", ",", "version", "=", "version", ")" ]
[ 214, 4 ]
[ 221, 45 ]
python
en
['en', 'error', 'th']
False
BaseCache.clear
(self)
Remove *all* values from the cache at once.
Remove *all* values from the cache at once.
def clear(self): """Remove *all* values from the cache at once.""" raise NotImplementedError('subclasses of BaseCache must provide a clear() method')
[ "def", "clear", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseCache must provide a clear() method'", ")" ]
[ 223, 4 ]
[ 225, 90 ]
python
en
['en', 'en', 'en']
True
BaseCache.validate_key
(self, key)
Warn about keys that would not be portable to the memcached backend. This encourages (but does not force) writing backend-portable cache code.
Warn about keys that would not be portable to the memcached backend. This encourages (but does not force) writing backend-portable cache code.
def validate_key(self, key): """ Warn about keys that would not be portable to the memcached backend. This encourages (but does not force) writing backend-portable cache code. """ if len(key) > MEMCACHE_MAX_KEY_LENGTH: warnings.warn( 'Cache key...
[ "def", "validate_key", "(", "self", ",", "key", ")", ":", "if", "len", "(", "key", ")", ">", "MEMCACHE_MAX_KEY_LENGTH", ":", "warnings", ".", "warn", "(", "'Cache key will cause errors if used with memcached: %r '", "'(longer than %s)'", "%", "(", "key", ",", "MEM...
[ 227, 4 ]
[ 244, 21 ]
python
en
['en', 'error', 'th']
False
BaseCache.incr_version
(self, key, delta=1, version=None)
Adds delta to the cache version for the supplied key. Returns the new version.
Adds delta to the cache version for the supplied key. Returns the new version.
def incr_version(self, key, delta=1, version=None): """Adds delta to the cache version for the supplied key. Returns the new version. """ if version is None: version = self.version value = self.get(key, version=version) if value is None: raise Val...
[ "def", "incr_version", "(", "self", ",", "key", ",", "delta", "=", "1", ",", "version", "=", "None", ")", ":", "if", "version", "is", "None", ":", "version", "=", "self", ".", "version", "value", "=", "self", ".", "get", "(", "key", ",", "version",...
[ 246, 4 ]
[ 259, 30 ]
python
en
['en', 'en', 'en']
True
BaseCache.decr_version
(self, key, delta=1, version=None)
Subtracts delta from the cache version for the supplied key. Returns the new version.
Subtracts delta from the cache version for the supplied key. Returns the new version.
def decr_version(self, key, delta=1, version=None): """Subtracts delta from the cache version for the supplied key. Returns the new version. """ return self.incr_version(key, -delta, version)
[ "def", "decr_version", "(", "self", ",", "key", ",", "delta", "=", "1", ",", "version", "=", "None", ")", ":", "return", "self", ".", "incr_version", "(", "key", ",", "-", "delta", ",", "version", ")" ]
[ 261, 4 ]
[ 265, 54 ]
python
en
['en', 'en', 'en']
True
BaseCache.close
(self, **kwargs)
Close the cache connection
Close the cache connection
def close(self, **kwargs): """Close the cache connection""" pass
[ "def", "close", "(", "self", ",", "*", "*", "kwargs", ")", ":", "pass" ]
[ 267, 4 ]
[ 269, 12 ]
python
en
['en', 'en', 'en']
True
pkg_resources_distribution_for_wheel
(wheel_zip, name, location)
Get a pkg_resources distribution given a wheel. :raises UnsupportedWheel: on any errors
Get a pkg_resources distribution given a wheel.
def pkg_resources_distribution_for_wheel(wheel_zip, name, location): # type: (ZipFile, str, str) -> Distribution """Get a pkg_resources distribution given a wheel. :raises UnsupportedWheel: on any errors """ info_dir, _ = parse_wheel(wheel_zip, name) metadata_files = [ p for p in wheel...
[ "def", "pkg_resources_distribution_for_wheel", "(", "wheel_zip", ",", "name", ",", "location", ")", ":", "# type: (ZipFile, str, str) -> Distribution", "info_dir", ",", "_", "=", "parse_wheel", "(", "wheel_zip", ",", "name", ")", "metadata_files", "=", "[", "p", "fo...
[ 57, 0 ]
[ 91, 5 ]
python
en
['en', 'en', 'en']
True
parse_wheel
(wheel_zip, name)
Extract information from the provided wheel, ensuring it meets basic standards. Returns the name of the .dist-info directory and the parsed WHEEL metadata.
Extract information from the provided wheel, ensuring it meets basic standards.
def parse_wheel(wheel_zip, name): # type: (ZipFile, str) -> Tuple[str, Message] """Extract information from the provided wheel, ensuring it meets basic standards. Returns the name of the .dist-info directory and the parsed WHEEL metadata. """ try: info_dir = wheel_dist_info_dir(wheel_zi...
[ "def", "parse_wheel", "(", "wheel_zip", ",", "name", ")", ":", "# type: (ZipFile, str) -> Tuple[str, Message]", "try", ":", "info_dir", "=", "wheel_dist_info_dir", "(", "wheel_zip", ",", "name", ")", "metadata", "=", "wheel_metadata", "(", "wheel_zip", ",", "info_di...
[ 94, 0 ]
[ 112, 29 ]
python
en
['en', 'en', 'en']
True
wheel_dist_info_dir
(source, name)
Returns the name of the contained .dist-info directory. Raises AssertionError or UnsupportedWheel if not found, >1 found, or it doesn't match the provided name.
Returns the name of the contained .dist-info directory.
def wheel_dist_info_dir(source, name): # type: (ZipFile, str) -> str """Returns the name of the contained .dist-info directory. Raises AssertionError or UnsupportedWheel if not found, >1 found, or it doesn't match the provided name. """ # Zip file path separators must be / subdirs = set(p.s...
[ "def", "wheel_dist_info_dir", "(", "source", ",", "name", ")", ":", "# type: (ZipFile, str) -> str", "# Zip file path separators must be /", "subdirs", "=", "set", "(", "p", ".", "split", "(", "\"/\"", ",", "1", ")", "[", "0", "]", "for", "p", "in", "source", ...
[ 115, 0 ]
[ 150, 31 ]
python
en
['en', 'en', 'en']
True
wheel_metadata
(source, dist_info_dir)
Return the WHEEL metadata of an extracted wheel, if possible. Otherwise, raise UnsupportedWheel.
Return the WHEEL metadata of an extracted wheel, if possible. Otherwise, raise UnsupportedWheel.
def wheel_metadata(source, dist_info_dir): # type: (ZipFile, str) -> Message """Return the WHEEL metadata of an extracted wheel, if possible. Otherwise, raise UnsupportedWheel. """ path = "{}/WHEEL".format(dist_info_dir) # Zip file path separators must be / wheel_contents = read_wheel_metada...
[ "def", "wheel_metadata", "(", "source", ",", "dist_info_dir", ")", ":", "# type: (ZipFile, str) -> Message", "path", "=", "\"{}/WHEEL\"", ".", "format", "(", "dist_info_dir", ")", "# Zip file path separators must be /", "wheel_contents", "=", "read_wheel_metadata_file", "("...
[ 165, 0 ]
[ 182, 40 ]
python
en
['en', 'en', 'en']
True
wheel_version
(wheel_data)
Given WHEEL metadata, return the parsed Wheel-Version. Otherwise, raise UnsupportedWheel.
Given WHEEL metadata, return the parsed Wheel-Version. Otherwise, raise UnsupportedWheel.
def wheel_version(wheel_data): # type: (Message) -> Tuple[int, ...] """Given WHEEL metadata, return the parsed Wheel-Version. Otherwise, raise UnsupportedWheel. """ version_text = wheel_data["Wheel-Version"] if version_text is None: raise UnsupportedWheel("WHEEL is missing Wheel-Version"...
[ "def", "wheel_version", "(", "wheel_data", ")", ":", "# type: (Message) -> Tuple[int, ...]", "version_text", "=", "wheel_data", "[", "\"Wheel-Version\"", "]", "if", "version_text", "is", "None", ":", "raise", "UnsupportedWheel", "(", "\"WHEEL is missing Wheel-Version\"", ...
[ 185, 0 ]
[ 199, 77 ]
python
en
['en', 'de', 'en']
True
check_compatibility
(version, name)
Raises errors or warns if called with an incompatible Wheel-Version. pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Whe...
Raises errors or warns if called with an incompatible Wheel-Version.
def check_compatibility(version, name): # type: (Tuple[int, ...], str) -> None """Raises errors or warns if called with an incompatible Wheel-Version. pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a ve...
[ "def", "check_compatibility", "(", "version", ",", "name", ")", ":", "# type: (Tuple[int, ...], str) -> None", "if", "version", "[", "0", "]", ">", "VERSION_COMPATIBLE", "[", "0", "]", ":", "raise", "UnsupportedWheel", "(", "\"{}'s Wheel-Version ({}) is not compatible w...
[ 202, 0 ]
[ 224, 9 ]
python
en
['en', 'en', 'en']
True
GraphNode._encode_uri
(self, text)
Performance assured: http://stackoverflow.com/a/27086669
Performance assured: http://stackoverflow.com/a/27086669
def _encode_uri(self, text): """ Performance assured: http://stackoverflow.com/a/27086669 """ for c in URL_PATH_RESERVED_CHARSET: if not isinstance(text, str): text = str(text) # needed for WFJT node creation, identifier temporarily UUID4 type if ...
[ "def", "_encode_uri", "(", "self", ",", "text", ")", ":", "for", "c", "in", "URL_PATH_RESERVED_CHARSET", ":", "if", "not", "isinstance", "(", "text", ",", "str", ")", ":", "text", "=", "str", "(", "text", ")", "# needed for WFJT node creation, identifier tempo...
[ 69, 4 ]
[ 79, 19 ]
python
en
['en', 'error', 'th']
False
instrumented_test_render
(self, context)
An instrumented Template render method, providing a signal that can be intercepted by the test system Client
An instrumented Template render method, providing a signal that can be intercepted by the test system Client
def instrumented_test_render(self, context): """ An instrumented Template render method, providing a signal that can be intercepted by the test system Client """ template_rendered.send(sender=self, template=self, context=context) return self.nodelist.render(context)
[ "def", "instrumented_test_render", "(", "self", ",", "context", ")", ":", "template_rendered", ".", "send", "(", "sender", "=", "self", ",", "template", "=", "self", ",", "context", "=", "context", ")", "return", "self", ".", "nodelist", ".", "render", "("...
[ 100, 0 ]
[ 106, 40 ]
python
en
['en', 'error', 'th']
False
setup_test_environment
(debug=None)
Perform global pre-test setup, such as installing the instrumented template renderer and setting the email backend to the locmem email backend.
Perform global pre-test setup, such as installing the instrumented template renderer and setting the email backend to the locmem email backend.
def setup_test_environment(debug=None): """ Perform global pre-test setup, such as installing the instrumented template renderer and setting the email backend to the locmem email backend. """ if hasattr(_TestState, 'saved_data'): # Executing this function twice would overwrite the saved valu...
[ "def", "setup_test_environment", "(", "debug", "=", "None", ")", ":", "if", "hasattr", "(", "_TestState", ",", "'saved_data'", ")", ":", "# Executing this function twice would overwrite the saved values.", "raise", "RuntimeError", "(", "\"setup_test_environment() was already ...
[ 113, 0 ]
[ 146, 16 ]
python
en
['en', 'error', 'th']
False
teardown_test_environment
()
Perform any global post-test teardown, such as restoring the original template renderer and restoring the email sending functions.
Perform any global post-test teardown, such as restoring the original template renderer and restoring the email sending functions.
def teardown_test_environment(): """ Perform any global post-test teardown, such as restoring the original template renderer and restoring the email sending functions. """ saved_data = _TestState.saved_data settings.ALLOWED_HOSTS = saved_data.allowed_hosts settings.DEBUG = saved_data.debug ...
[ "def", "teardown_test_environment", "(", ")", ":", "saved_data", "=", "_TestState", ".", "saved_data", "settings", ".", "ALLOWED_HOSTS", "=", "saved_data", ".", "allowed_hosts", "settings", ".", "DEBUG", "=", "saved_data", ".", "debug", "settings", ".", "EMAIL_BAC...
[ 149, 0 ]
[ 162, 19 ]
python
en
['en', 'error', 'th']
False
setup_databases
(verbosity, interactive, keepdb=False, debug_sql=False, parallel=0, **kwargs)
Create the test databases.
Create the test databases.
def setup_databases(verbosity, interactive, keepdb=False, debug_sql=False, parallel=0, **kwargs): """ Create the test databases. """ test_databases, mirrored_aliases = get_unique_databases_and_mirrors() old_names = [] for signature, (db_name, aliases) in test_databases.items(): first_a...
[ "def", "setup_databases", "(", "verbosity", ",", "interactive", ",", "keepdb", "=", "False", ",", "debug_sql", "=", "False", ",", "parallel", "=", "0", ",", "*", "*", "kwargs", ")", ":", "test_databases", ",", "mirrored_aliases", "=", "get_unique_databases_and...
[ 165, 0 ]
[ 208, 20 ]
python
en
['en', 'error', 'th']
False
dependency_ordered
(test_databases, dependencies)
Reorder test_databases into an order that honors the dependencies described in TEST[DEPENDENCIES].
Reorder test_databases into an order that honors the dependencies described in TEST[DEPENDENCIES].
def dependency_ordered(test_databases, dependencies): """ Reorder test_databases into an order that honors the dependencies described in TEST[DEPENDENCIES]. """ ordered_test_databases = [] resolved_databases = set() # Maps db signature to dependencies of all its aliases dependencies_map...
[ "def", "dependency_ordered", "(", "test_databases", ",", "dependencies", ")", ":", "ordered_test_databases", "=", "[", "]", "resolved_databases", "=", "set", "(", ")", "# Maps db signature to dependencies of all its aliases", "dependencies_map", "=", "{", "}", "# Check th...
[ 211, 0 ]
[ 250, 33 ]
python
en
['en', 'error', 'th']
False
get_unique_databases_and_mirrors
()
Figure out which databases actually need to be created. Deduplicate entries in DATABASES that correspond the same database or are configured as test mirrors. Return two values: - test_databases: ordered mapping of signatures to (name, list of aliases) where all aliases share...
Figure out which databases actually need to be created.
def get_unique_databases_and_mirrors(): """ Figure out which databases actually need to be created. Deduplicate entries in DATABASES that correspond the same database or are configured as test mirrors. Return two values: - test_databases: ordered mapping of signatures to (name, list of aliases...
[ "def", "get_unique_databases_and_mirrors", "(", ")", ":", "mirrored_aliases", "=", "{", "}", "test_databases", "=", "{", "}", "dependencies", "=", "{", "}", "default_sig", "=", "connections", "[", "DEFAULT_DB_ALIAS", "]", ".", "creation", ".", "test_db_signature",...
[ 253, 0 ]
[ 295, 43 ]
python
en
['en', 'error', 'th']
False
teardown_databases
(old_config, verbosity, parallel=0, keepdb=False)
Destroy all the non-mirror databases.
Destroy all the non-mirror databases.
def teardown_databases(old_config, verbosity, parallel=0, keepdb=False): """ Destroy all the non-mirror databases. """ for connection, old_name, destroy in old_config: if destroy: if parallel > 1: for index in range(parallel): connection.creation.d...
[ "def", "teardown_databases", "(", "old_config", ",", "verbosity", ",", "parallel", "=", "0", ",", "keepdb", "=", "False", ")", ":", "for", "connection", ",", "old_name", ",", "destroy", "in", "old_config", ":", "if", "destroy", ":", "if", "parallel", ">", ...
[ 298, 0 ]
[ 311, 76 ]
python
en
['en', 'error', 'th']
False
compare_xml
(want, got)
Tries to do a 'xml-comparison' of want and got. Plain string comparison doesn't always work because, for example, attribute ordering should not be important. Comment nodes are not considered in the comparison. Leading and trailing whitespace is ignored on both chunks. Based on https://github.com/lxml/...
Tries to do a 'xml-comparison' of want and got. Plain string comparison doesn't always work because, for example, attribute ordering should not be important. Comment nodes are not considered in the comparison. Leading and trailing whitespace is ignored on both chunks.
def compare_xml(want, got): """Tries to do a 'xml-comparison' of want and got. Plain string comparison doesn't always work because, for example, attribute ordering should not be important. Comment nodes are not considered in the comparison. Leading and trailing whitespace is ignored on both chunks. ...
[ "def", "compare_xml", "(", "want", ",", "got", ")", ":", "_norm_whitespace_re", "=", "re", ".", "compile", "(", "r'[ \\t\\n][ \\t\\n]+'", ")", "def", "norm_whitespace", "(", "v", ")", ":", "return", "_norm_whitespace_re", ".", "sub", "(", "' '", ",", "v", ...
[ 524, 0 ]
[ 587, 45 ]
python
en
['en', 'en', 'en']
True
strip_quotes
(want, got)
Strip quotes of doctests output values: >>> strip_quotes("'foo'") "foo" >>> strip_quotes('"foo"') "foo"
Strip quotes of doctests output values:
def strip_quotes(want, got): """ Strip quotes of doctests output values: >>> strip_quotes("'foo'") "foo" >>> strip_quotes('"foo"') "foo" """ def is_quoted_string(s): s = s.strip() return len(s) >= 2 and s[0] == s[-1] and s[0] in ('"', "'") def is_quoted_unicode(s): ...
[ "def", "strip_quotes", "(", "want", ",", "got", ")", ":", "def", "is_quoted_string", "(", "s", ")", ":", "s", "=", "s", ".", "strip", "(", ")", "return", "len", "(", "s", ")", ">=", "2", "and", "s", "[", "0", "]", "==", "s", "[", "-", "1", ...
[ 590, 0 ]
[ 613, 20 ]
python
en
['en', 'error', 'th']
False
patch_logger
(logger_name, log_level, log_kwargs=False)
Context manager that takes a named logger and the logging level and provides a simple mock-like list of messages received
Context manager that takes a named logger and the logging level and provides a simple mock-like list of messages received
def patch_logger(logger_name, log_level, log_kwargs=False): """ Context manager that takes a named logger and the logging level and provides a simple mock-like list of messages received """ calls = [] def replacement(msg, *args, **kwargs): call = msg % args calls.append((call, k...
[ "def", "patch_logger", "(", "logger_name", ",", "log_level", ",", "log_kwargs", "=", "False", ")", ":", "calls", "=", "[", "]", "def", "replacement", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "call", "=", "msg", "%", "args", ...
[ 675, 0 ]
[ 691, 40 ]
python
en
['en', 'error', 'th']
False
extend_sys_path
(*paths)
Context manager to temporarily add paths to sys.path.
Context manager to temporarily add paths to sys.path.
def extend_sys_path(*paths): """Context manager to temporarily add paths to sys.path.""" _orig_sys_path = sys.path[:] sys.path.extend(paths) try: yield finally: sys.path = _orig_sys_path
[ "def", "extend_sys_path", "(", "*", "paths", ")", ":", "_orig_sys_path", "=", "sys", ".", "path", "[", ":", "]", "sys", ".", "path", ".", "extend", "(", "paths", ")", "try", ":", "yield", "finally", ":", "sys", ".", "path", "=", "_orig_sys_path" ]
[ 707, 0 ]
[ 714, 33 ]
python
en
['en', 'en', 'en']
True
isolate_lru_cache
(lru_cache_object)
Clear the cache of an LRU cache object on entering and exiting.
Clear the cache of an LRU cache object on entering and exiting.
def isolate_lru_cache(lru_cache_object): """Clear the cache of an LRU cache object on entering and exiting.""" lru_cache_object.cache_clear() try: yield finally: lru_cache_object.cache_clear()
[ "def", "isolate_lru_cache", "(", "lru_cache_object", ")", ":", "lru_cache_object", ".", "cache_clear", "(", ")", "try", ":", "yield", "finally", ":", "lru_cache_object", ".", "cache_clear", "(", ")" ]
[ 718, 0 ]
[ 724, 38 ]
python
en
['en', 'en', 'en']
True
captured_output
(stream_name)
Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Note: This function and the following ``captured_std*`` are copied from CPython's ``test.support`` module.
Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO.
def captured_output(stream_name): """Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Note: This function and the following ``captured_std*`` are copied from CPython's ``test.support`` module.""" orig_stdout ...
[ "def", "captured_output", "(", "stream_name", ")", ":", "orig_stdout", "=", "getattr", "(", "sys", ",", "stream_name", ")", "setattr", "(", "sys", ",", "stream_name", ",", "six", ".", "StringIO", "(", ")", ")", "try", ":", "yield", "getattr", "(", "sys",...
[ 728, 0 ]
[ 739, 46 ]
python
en
['en', 'en', 'en']
True
captured_stdout
()
Capture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n")
Capture the output of sys.stdout:
def captured_stdout(): """Capture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n") """ return captured_output("stdout")
[ "def", "captured_stdout", "(", ")", ":", "return", "captured_output", "(", "\"stdout\"", ")" ]
[ 742, 0 ]
[ 749, 36 ]
python
en
['en', 'en', 'en']
True
captured_stderr
()
Capture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n")
Capture the output of sys.stderr:
def captured_stderr(): """Capture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n") """ return captured_output("stderr")
[ "def", "captured_stderr", "(", ")", ":", "return", "captured_output", "(", "\"stderr\"", ")" ]
[ 752, 0 ]
[ 759, 36 ]
python
en
['en', 'en', 'en']
True
captured_stdin
()
Capture the input to sys.stdin: with captured_stdin() as stdin: stdin.write('hello\n') stdin.seek(0) # call test code that consumes from sys.stdin captured = input() self.assertEqual(captured, "hello")
Capture the input to sys.stdin:
def captured_stdin(): """Capture the input to sys.stdin: with captured_stdin() as stdin: stdin.write('hello\n') stdin.seek(0) # call test code that consumes from sys.stdin captured = input() self.assertEqual(captured, "hello") """ return captured_ou...
[ "def", "captured_stdin", "(", ")", ":", "return", "captured_output", "(", "\"stdin\"", ")" ]
[ 762, 0 ]
[ 772, 35 ]
python
en
['en', 'en', 'en']
True
reset_warning_registry
()
Clear warning registry for all modules. This is required in some tests because of a bug in Python that prevents warnings.simplefilter("always") from always making warnings appear: http://bugs.python.org/issue4180 The bug was fixed in Python 3.4.2.
Clear warning registry for all modules. This is required in some tests because of a bug in Python that prevents warnings.simplefilter("always") from always making warnings appear: http://bugs.python.org/issue4180
def reset_warning_registry(): """ Clear warning registry for all modules. This is required in some tests because of a bug in Python that prevents warnings.simplefilter("always") from always making warnings appear: http://bugs.python.org/issue4180 The bug was fixed in Python 3.4.2. """ key =...
[ "def", "reset_warning_registry", "(", ")", ":", "key", "=", "\"__warningregistry__\"", "for", "mod", "in", "sys", ".", "modules", ".", "values", "(", ")", ":", "if", "hasattr", "(", "mod", ",", "key", ")", ":", "getattr", "(", "mod", ",", "key", ")", ...
[ 775, 0 ]
[ 786, 37 ]
python
en
['en', 'error', 'th']
False
freeze_time
(t)
Context manager to temporarily freeze time.time(). This temporarily modifies the time function of the time module. Modules which import the time function directly (e.g. `from time import time`) won't be affected This isn't meant as a public API, but helps reduce some repetitive code in Django's tes...
Context manager to temporarily freeze time.time(). This temporarily modifies the time function of the time module. Modules which import the time function directly (e.g. `from time import time`) won't be affected This isn't meant as a public API, but helps reduce some repetitive code in Django's tes...
def freeze_time(t): """ Context manager to temporarily freeze time.time(). This temporarily modifies the time function of the time module. Modules which import the time function directly (e.g. `from time import time`) won't be affected This isn't meant as a public API, but helps reduce some repetiti...
[ "def", "freeze_time", "(", "t", ")", ":", "_real_time", "=", "time", ".", "time", "time", ".", "time", "=", "lambda", ":", "t", "try", ":", "yield", "finally", ":", "time", ".", "time", "=", "_real_time" ]
[ 790, 0 ]
[ 803, 30 ]
python
en
['en', 'error', 'th']
False