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
Optimization.get_min_eig_vec_proxy
(self, use_tf_eig=False)
Computes the min eigen value and corresponding vector of matrix M. Args: use_tf_eig: Whether to use tf's default full eigen decomposition Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector
Computes the min eigen value and corresponding vector of matrix M.
def get_min_eig_vec_proxy(self, use_tf_eig=False): """Computes the min eigen value and corresponding vector of matrix M. Args: use_tf_eig: Whether to use tf's default full eigen decomposition Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eig...
[ "def", "get_min_eig_vec_proxy", "(", "self", ",", "use_tf_eig", "=", "False", ")", ":", "if", "use_tf_eig", ":", "# If smoothness parameter is too small, essentially no smoothing", "# Just output the eigen vector corresponding to min", "return", "tf", ".", "cond", "(", "self"...
[ 83, 4 ]
[ 114, 37 ]
python
en
['en', 'ca', 'en']
True
Optimization.get_scipy_eig_vec
(self)
Computes scipy estimate of min eigenvalue for matrix M. Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector
Computes scipy estimate of min eigenvalue for matrix M.
def get_scipy_eig_vec(self): """Computes scipy estimate of min eigenvalue for matrix M. Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector """ if not self.params["has_conv"]: matrix_m = self.sess.run(self.dual_object.matrix...
[ "def", "get_scipy_eig_vec", "(", "self", ")", ":", "if", "not", "self", ".", "params", "[", "\"has_conv\"", "]", ":", "matrix_m", "=", "self", ".", "sess", ".", "run", "(", "self", ".", "dual_object", ".", "matrix_m", ")", "min_eig_vec_val", ",", "estima...
[ 116, 4 ]
[ 148, 79 ]
python
en
['en', 'it', 'nl']
False
Optimization.prepare_for_optimization
(self)
Create tensorflow op for running one step of descent.
Create tensorflow op for running one step of descent.
def prepare_for_optimization(self): """Create tensorflow op for running one step of descent.""" if self.params["eig_type"] == "TF": self.eig_vec_estimate = self.get_min_eig_vec_proxy() elif self.params["eig_type"] == "LZS": self.eig_vec_estimate = self.dual_object.m_min_v...
[ "def", "prepare_for_optimization", "(", "self", ")", ":", "if", "self", ".", "params", "[", "\"eig_type\"", "]", "==", "\"TF\"", ":", "self", ".", "eig_vec_estimate", "=", "self", ".", "get_min_eig_vec_proxy", "(", ")", "elif", "self", ".", "params", "[", ...
[ 150, 4 ]
[ 254, 55 ]
python
en
['en', 'en', 'nl']
True
Optimization.run_one_step
( self, eig_init_vec_val, eig_num_iter_val, smooth_val, penalty_val, learning_rate_val, )
Run one step of gradient descent for optimization. Args: eig_init_vec_val: Start value for eigen value computations eig_num_iter_val: Number of iterations to run for eigen computations smooth_val: Value of smoothness parameter penalty_val: Value of penalty for the curren...
Run one step of gradient descent for optimization.
def run_one_step( self, eig_init_vec_val, eig_num_iter_val, smooth_val, penalty_val, learning_rate_val, ): """Run one step of gradient descent for optimization. Args: eig_init_vec_val: Start value for eigen value computations eig_n...
[ "def", "run_one_step", "(", "self", ",", "eig_init_vec_val", ",", "eig_num_iter_val", ",", "smooth_val", ",", "penalty_val", ",", "learning_rate_val", ",", ")", ":", "# Running step", "step_feed_dict", "=", "{", "self", ".", "eig_init_vec_placeholder", ":", "eig_ini...
[ 256, 4 ]
[ 360, 20 ]
python
en
['en', 'en', 'en']
True
Optimization.run_optimization
(self)
Run the optimization, call run_one_step with suitable placeholders. Returns: True if certificate is found False otherwise
Run the optimization, call run_one_step with suitable placeholders.
def run_optimization(self): """Run the optimization, call run_one_step with suitable placeholders. Returns: True if certificate is found False otherwise """ penalty_val = self.params["init_penalty"] # Don't use smoothing initially - very inaccurate for large ...
[ "def", "run_optimization", "(", "self", ")", ":", "penalty_val", "=", "self", ".", "params", "[", "\"init_penalty\"", "]", "# Don't use smoothing initially - very inaccurate for large dimension", "self", ".", "smooth_on", "=", "False", "smooth_val", "=", "0", "learning_...
[ 362, 4 ]
[ 423, 20 ]
python
en
['en', 'en', 'en']
True
TestChoosePubDate.test_choose_date_sent_large_tot_messages
(self)
Test for a bug that was present, where specifying a large amount of messages to generate would cause each message to have date_sent set to timezone_now(), instead of the date_sents being distributed across the span of several days.
Test for a bug that was present, where specifying a large amount of messages to generate would cause each message to have date_sent set to timezone_now(), instead of the date_sents being distributed across the span of several days.
def test_choose_date_sent_large_tot_messages(self) -> None: """ Test for a bug that was present, where specifying a large amount of messages to generate would cause each message to have date_sent set to timezone_now(), instead of the date_sents being distributed across the span of severa...
[ "def", "test_choose_date_sent_large_tot_messages", "(", "self", ")", "->", "None", ":", "tot_messages", "=", "1000000", "datetimes_list", "=", "[", "choose_date_sent", "(", "i", ",", "tot_messages", ",", "1", ")", "for", "i", "in", "range", "(", "1", ",", "t...
[ 7, 4 ]
[ 23, 13 ]
python
en
['en', 'error', 'th']
False
interpret
(marker, execution_context=None)
Interpret a marker and return a result depending on environment. :param marker: The marker to interpret. :type marker: str :param execution_context: The context used for name lookup. :type execution_context: mapping
Interpret a marker and return a result depending on environment.
def interpret(marker, execution_context=None): """ Interpret a marker and return a result depending on environment. :param marker: The marker to interpret. :type marker: str :param execution_context: The context used for name lookup. :type execution_context: mapping """ try: exp...
[ "def", "interpret", "(", "marker", ",", "execution_context", "=", "None", ")", ":", "try", ":", "expr", ",", "rest", "=", "parse_marker", "(", "marker", ")", "except", "Exception", "as", "e", ":", "raise", "SyntaxError", "(", "'Unable to interpret marker synta...
[ 112, 0 ]
[ 130, 44 ]
python
en
['en', 'error', 'th']
False
Evaluator.evaluate
(self, expr, context)
Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context.
Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context.
def evaluate(self, expr, context): """ Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context. """ if isinstance(expr, string_types): if expr[0] in '\'"': result = expr[1:-1] else: ...
[ "def", "evaluate", "(", "self", ",", "expr", ",", "context", ")", ":", "if", "isinstance", "(", "expr", ",", "string_types", ")", ":", "if", "expr", "[", "0", "]", "in", "'\\'\"'", ":", "result", "=", "expr", "[", "1", ":", "-", "1", "]", "else",...
[ 49, 4 ]
[ 74, 21 ]
python
en
['en', 'error', 'th']
False
Retry.from_int
(cls, retries, redirect=True, default=None)
Backwards-compatibility for the old retries format.
Backwards-compatibility for the old retries format.
def from_int(cls, retries, redirect=True, default=None): """ Backwards-compatibility for the old retries format.""" if retries is None: retries = default if default is not None else cls.DEFAULT if isinstance(retries, Retry): return retries redirect = bool(redire...
[ "def", "from_int", "(", "cls", ",", "retries", ",", "redirect", "=", "True", ",", "default", "=", "None", ")", ":", "if", "retries", "is", "None", ":", "retries", "=", "default", "if", "default", "is", "not", "None", "else", "cls", ".", "DEFAULT", "i...
[ 219, 4 ]
[ 230, 26 ]
python
en
['en', 'en', 'en']
True
Retry.get_backoff_time
(self)
Formula for computing the current backoff :rtype: float
Formula for computing the current backoff
def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ # We want to consider only the last consecutive errors sequence (Ignore redirects). consecutive_errors_len = len( list( takewhile(lambda x: x.redirect_location...
[ "def", "get_backoff_time", "(", "self", ")", ":", "# We want to consider only the last consecutive errors sequence (Ignore redirects).", "consecutive_errors_len", "=", "len", "(", "list", "(", "takewhile", "(", "lambda", "x", ":", "x", ".", "redirect_location", "is", "Non...
[ 232, 4 ]
[ 247, 51 ]
python
en
['en', 'en', 'en']
True
Retry.get_retry_after
(self, response)
Get the value of Retry-After in seconds.
Get the value of Retry-After in seconds.
def get_retry_after(self, response): """ Get the value of Retry-After in seconds. """ retry_after = response.getheader("Retry-After") if retry_after is None: return None return self.parse_retry_after(retry_after)
[ "def", "get_retry_after", "(", "self", ",", "response", ")", ":", "retry_after", "=", "response", ".", "getheader", "(", "\"Retry-After\"", ")", "if", "retry_after", "is", "None", ":", "return", "None", "return", "self", ".", "parse_retry_after", "(", "retry_a...
[ 265, 4 ]
[ 273, 50 ]
python
en
['en', 'en', 'en']
True
Retry.sleep
(self, response=None)
Sleep between retry attempts. This method will respect a server's ``Retry-After`` response header and sleep the duration of the time requested. If that is not present, it will use an exponential backoff. By default, the backoff factor is 0 and this method will return immediately. ...
Sleep between retry attempts.
def sleep(self, response=None): """ Sleep between retry attempts. This method will respect a server's ``Retry-After`` response header and sleep the duration of the time requested. If that is not present, it will use an exponential backoff. By default, the backoff factor is 0 and ...
[ "def", "sleep", "(", "self", ",", "response", "=", "None", ")", ":", "if", "self", ".", "respect_retry_after_header", "and", "response", ":", "slept", "=", "self", ".", "sleep_for_retry", "(", "response", ")", "if", "slept", ":", "return", "self", ".", "...
[ 289, 4 ]
[ 303, 29 ]
python
en
['en', 'nl', 'en']
True
Retry._is_connection_error
(self, err)
Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry.
Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry.
def _is_connection_error(self, err): """ Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry. """ if isinstance(err, ProxyError): err = err.original_error return isinstance(err, ConnectTimeoutError)
[ "def", "_is_connection_error", "(", "self", ",", "err", ")", ":", "if", "isinstance", "(", "err", ",", "ProxyError", ")", ":", "err", "=", "err", ".", "original_error", "return", "isinstance", "(", "err", ",", "ConnectTimeoutError", ")" ]
[ 305, 4 ]
[ 311, 51 ]
python
en
['en', 'en', 'en']
True
Retry._is_read_error
(self, err)
Errors that occur after the request has been started, so we should assume that the server began processing it.
Errors that occur after the request has been started, so we should assume that the server began processing it.
def _is_read_error(self, err): """ Errors that occur after the request has been started, so we should assume that the server began processing it. """ return isinstance(err, (ReadTimeoutError, ProtocolError))
[ "def", "_is_read_error", "(", "self", ",", "err", ")", ":", "return", "isinstance", "(", "err", ",", "(", "ReadTimeoutError", ",", "ProtocolError", ")", ")" ]
[ 313, 4 ]
[ 317, 65 ]
python
en
['en', 'en', 'en']
True
Retry._is_method_retryable
(self, method)
Checks if a given HTTP method should be retried upon, depending if it is included on the method whitelist.
Checks if a given HTTP method should be retried upon, depending if it is included on the method whitelist.
def _is_method_retryable(self, method): """ Checks if a given HTTP method should be retried upon, depending if it is included on the method whitelist. """ if self.method_whitelist and method.upper() not in self.method_whitelist: return False return True
[ "def", "_is_method_retryable", "(", "self", ",", "method", ")", ":", "if", "self", ".", "method_whitelist", "and", "method", ".", "upper", "(", ")", "not", "in", "self", ".", "method_whitelist", ":", "return", "False", "return", "True" ]
[ 319, 4 ]
[ 326, 19 ]
python
en
['en', 'en', 'en']
True
Retry.is_retry
(self, method, status_code, has_retry_after=False)
Is this method/status code retryable? (Based on whitelists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the returned status code is on the list of status codes to be retried upo...
Is this method/status code retryable? (Based on whitelists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the returned status code is on the list of status codes to be retried upo...
def is_retry(self, method, status_code, has_retry_after=False): """ Is this method/status code retryable? (Based on whitelists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the re...
[ "def", "is_retry", "(", "self", ",", "method", ",", "status_code", ",", "has_retry_after", "=", "False", ")", ":", "if", "not", "self", ".", "_is_method_retryable", "(", "method", ")", ":", "return", "False", "if", "self", ".", "status_forcelist", "and", "...
[ 328, 4 ]
[ 346, 9 ]
python
en
['en', 'en', 'en']
True
Retry.is_exhausted
(self)
Are we out of retries?
Are we out of retries?
def is_exhausted(self): """ Are we out of retries? """ retry_counts = (self.total, self.connect, self.read, self.redirect, self.status) retry_counts = list(filter(None, retry_counts)) if not retry_counts: return False return min(retry_counts) < 0
[ "def", "is_exhausted", "(", "self", ")", ":", "retry_counts", "=", "(", "self", ".", "total", ",", "self", ".", "connect", ",", "self", ".", "read", ",", "self", ".", "redirect", ",", "self", ".", "status", ")", "retry_counts", "=", "list", "(", "fil...
[ 348, 4 ]
[ 355, 36 ]
python
en
['en', 'en', 'en']
True
Retry.increment
( self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None, )
Return a new Retry object with incremented retry counters. :param response: A response object, or None, if the server did not return a response. :type response: :class:`~urllib3.response.HTTPResponse` :param Exception error: An error encountered during the request, or N...
Return a new Retry object with incremented retry counters.
def increment( self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None, ): """ Return a new Retry object with incremented retry counters. :param response: A response object, or None, if the server did not ...
[ "def", "increment", "(", "self", ",", "method", "=", "None", ",", "url", "=", "None", ",", "response", "=", "None", ",", "error", "=", "None", ",", "_pool", "=", "None", ",", "_stacktrace", "=", "None", ",", ")", ":", "if", "self", ".", "total", ...
[ 357, 4 ]
[ 442, 24 ]
python
en
['en', 'en', 'en']
True
compile_string
(template_string, origin)
Compiles template_string into NodeList ready for rendering
Compiles template_string into NodeList ready for rendering
def compile_string(template_string, origin): "Compiles template_string into NodeList ready for rendering" if settings.TEMPLATE_DEBUG: from django.template.debug import DebugLexer, DebugParser lexer_class, parser_class = DebugLexer, DebugParser else: lexer_class, parser_class = Lexer,...
[ "def", "compile_string", "(", "template_string", ",", "origin", ")", ":", "if", "settings", ".", "TEMPLATE_DEBUG", ":", "from", "django", ".", "template", ".", "debug", "import", "DebugLexer", ",", "DebugParser", "lexer_class", ",", "parser_class", "=", "DebugLe...
[ 154, 0 ]
[ 163, 25 ]
python
en
['en', 'en', 'en']
True
resolve_variable
(path, context)
Returns the resolved variable, which may contain attribute syntax, within the given context. Deprecated; use the Variable class instead.
Returns the resolved variable, which may contain attribute syntax, within the given context.
def resolve_variable(path, context): """ Returns the resolved variable, which may contain attribute syntax, within the given context. Deprecated; use the Variable class instead. """ warnings.warn("resolve_variable() is deprecated. Use django.template." "Variable(path).resolve(...
[ "def", "resolve_variable", "(", "path", ",", "context", ")", ":", "warnings", ".", "warn", "(", "\"resolve_variable() is deprecated. Use django.template.\"", "\"Variable(path).resolve(context) instead\"", ",", "RemovedInDjango20Warning", ",", "stacklevel", "=", "2", ")", "r...
[ 655, 0 ]
[ 665, 42 ]
python
en
['en', 'error', 'th']
False
render_value_in_context
(value, context)
Converts any value to a string to become part of a rendered template. This means escaping, if required, and conversion to a unicode object. If value is a string, it is expected to have already been translated.
Converts any value to a string to become part of a rendered template. This means escaping, if required, and conversion to a unicode object. If value is a string, it is expected to have already been translated.
def render_value_in_context(value, context): """ Converts any value to a string to become part of a rendered template. This means escaping, if required, and conversion to a unicode object. If value is a string, it is expected to have already been translated. """ value = template_localtime(value,...
[ "def", "render_value_in_context", "(", "value", ",", "context", ")", ":", "value", "=", "template_localtime", "(", "value", ",", "use_tz", "=", "context", ".", "use_tz", ")", "value", "=", "localize", "(", "value", ",", "use_l10n", "=", "context", ".", "us...
[ 883, 0 ]
[ 896, 20 ]
python
en
['en', 'error', 'th']
False
token_kwargs
(bits, parser, support_legacy=False)
A utility method for parsing token keyword arguments. :param bits: A list containing remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments will be removed from this list. :param support_legacy: If set to true ``True``, the legacy format ``1 ...
A utility method for parsing token keyword arguments.
def token_kwargs(bits, parser, support_legacy=False): """ A utility method for parsing token keyword arguments. :param bits: A list containing remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments will be removed from this list. :param support_le...
[ "def", "token_kwargs", "(", "bits", ",", "parser", ",", "support_legacy", "=", "False", ")", ":", "if", "not", "bits", ":", "return", "{", "}", "match", "=", "kwarg_re", ".", "match", "(", "bits", "[", "0", "]", ")", "kwarg_format", "=", "match", "an...
[ 920, 0 ]
[ 967, 17 ]
python
en
['en', 'error', 'th']
False
parse_bits
(parser, bits, params, varargs, varkw, defaults, takes_context, name)
Parses bits for template tag helpers (simple_tag, include_tag and assignment_tag), in particular by detecting syntax errors and by extracting positional and keyword arguments.
Parses bits for template tag helpers (simple_tag, include_tag and assignment_tag), in particular by detecting syntax errors and by extracting positional and keyword arguments.
def parse_bits(parser, bits, params, varargs, varkw, defaults, takes_context, name): """ Parses bits for template tag helpers (simple_tag, include_tag and assignment_tag), in particular by detecting syntax errors and by extracting positional and keyword arguments. """ if takes_con...
[ "def", "parse_bits", "(", "parser", ",", "bits", ",", "params", ",", "varargs", ",", "varkw", ",", "defaults", ",", "takes_context", ",", "name", ")", ":", "if", "takes_context", ":", "if", "params", "[", "0", "]", "==", "'context'", ":", "params", "="...
[ 970, 0 ]
[ 1035, 23 ]
python
en
['en', 'error', 'th']
False
generic_tag_compiler
(parser, token, params, varargs, varkw, defaults, name, takes_context, node_class)
Returns a template.Node subclass.
Returns a template.Node subclass.
def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, name, takes_context, node_class): """ Returns a template.Node subclass. """ bits = token.split_contents()[1:] args, kwargs = parse_bits(parser, bits, params, varargs, varkw, ...
[ "def", "generic_tag_compiler", "(", "parser", ",", "token", ",", "params", ",", "varargs", ",", "varkw", ",", "defaults", ",", "name", ",", "takes_context", ",", "node_class", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "[", "1", ":"...
[ 1038, 0 ]
[ 1046, 50 ]
python
en
['en', 'error', 'th']
False
is_library_missing
(name)
Check if library that failed to load cannot be found under any templatetags directory or does exist but fails to import. Non-existing condition is checked recursively for each subpackage in cases like <appdir>/templatetags/subpackage/package/module.py.
Check if library that failed to load cannot be found under any templatetags directory or does exist but fails to import.
def is_library_missing(name): """Check if library that failed to load cannot be found under any templatetags directory or does exist but fails to import. Non-existing condition is checked recursively for each subpackage in cases like <appdir>/templatetags/subpackage/package/module.py. """ # Don...
[ "def", "is_library_missing", "(", "name", ")", ":", "# Don't bother to check if '.' is in name since any name will be prefixed", "# with some template root.", "path", ",", "module", "=", "name", ".", "rsplit", "(", "'.'", ",", "1", ")", "try", ":", "package", "=", "im...
[ 1255, 0 ]
[ 1269, 39 ]
python
en
['en', 'en', 'en']
True
import_library
(taglib_module)
Load a template tag library module. Verifies that the library contains a 'register' attribute, and returns that attribute as the representation of the library
Load a template tag library module.
def import_library(taglib_module): """ Load a template tag library module. Verifies that the library contains a 'register' attribute, and returns that attribute as the representation of the library """ try: mod = import_module(taglib_module) except ImportError as e: # If the...
[ "def", "import_library", "(", "taglib_module", ")", ":", "try", ":", "mod", "=", "import_module", "(", "taglib_module", ")", "except", "ImportError", "as", "e", ":", "# If the ImportError is because the taglib submodule does not exist,", "# that's not an error that should be ...
[ 1272, 0 ]
[ 1296, 51 ]
python
en
['en', 'error', 'th']
False
get_templatetags_modules
()
Return the list of all available template tag modules. Caches the result for faster access.
Return the list of all available template tag modules.
def get_templatetags_modules(): """ Return the list of all available template tag modules. Caches the result for faster access. """ global templatetags_modules if not templatetags_modules: _templatetags_modules = [] # Populate list once per process. Mutate the local list first, ...
[ "def", "get_templatetags_modules", "(", ")", ":", "global", "templatetags_modules", "if", "not", "templatetags_modules", ":", "_templatetags_modules", "=", "[", "]", "# Populate list once per process. Mutate the local list first, and", "# then assign it to the global name to ensure t...
[ 1301, 0 ]
[ 1324, 31 ]
python
en
['en', 'error', 'th']
False
get_library
(library_name)
Load the template library module with the given name. If library is not already loaded loop over all templatetags modules to locate it. {% load somelib %} and {% load someotherlib %} loops twice. Subsequent loads eg. {% load somelib %} in the same process will grab the cached module from lib...
Load the template library module with the given name.
def get_library(library_name): """ Load the template library module with the given name. If library is not already loaded loop over all templatetags modules to locate it. {% load somelib %} and {% load someotherlib %} loops twice. Subsequent loads eg. {% load somelib %} in the same process wi...
[ "def", "get_library", "(", "library_name", ")", ":", "lib", "=", "libraries", ".", "get", "(", "library_name", ",", "None", ")", "if", "not", "lib", ":", "templatetags_modules", "=", "get_templatetags_modules", "(", ")", "tried_modules", "=", "[", "]", "for"...
[ 1327, 0 ]
[ 1355, 14 ]
python
en
['en', 'error', 'th']
False
Template.render
(self, context)
Display stage -- can be called many times
Display stage -- can be called many times
def render(self, context): "Display stage -- can be called many times" context.render_context.push() try: return self._render(context) finally: context.render_context.pop()
[ "def", "render", "(", "self", ",", "context", ")", ":", "context", ".", "render_context", ".", "push", "(", ")", "try", ":", "return", "self", ".", "_render", "(", "context", ")", "finally", ":", "context", ".", "render_context", ".", "pop", "(", ")" ]
[ 145, 4 ]
[ 151, 40 ]
python
en
['en', 'en', 'en']
True
Lexer.tokenize
(self)
Return a list of tokens from a given template_string.
Return a list of tokens from a given template_string.
def tokenize(self): """ Return a list of tokens from a given template_string. """ in_tag = False result = [] for bit in tag_re.split(self.template_string): if bit: result.append(self.create_token(bit, in_tag)) in_tag = not in_tag ...
[ "def", "tokenize", "(", "self", ")", ":", "in_tag", "=", "False", "result", "=", "[", "]", "for", "bit", "in", "tag_re", ".", "split", "(", "self", ".", "template_string", ")", ":", "if", "bit", ":", "result", ".", "append", "(", "self", ".", "crea...
[ 201, 4 ]
[ 211, 21 ]
python
en
['en', 'error', 'th']
False
Lexer.create_token
(self, token_string, in_tag)
Convert the given token string into a new Token object and return it. If in_tag is True, we are processing something that matched a tag, otherwise it should be treated as a literal string.
Convert the given token string into a new Token object and return it. If in_tag is True, we are processing something that matched a tag, otherwise it should be treated as a literal string.
def create_token(self, token_string, in_tag): """ Convert the given token string into a new Token object and return it. If in_tag is True, we are processing something that matched a tag, otherwise it should be treated as a literal string. """ if in_tag and token_string.st...
[ "def", "create_token", "(", "self", ",", "token_string", ",", "in_tag", ")", ":", "if", "in_tag", "and", "token_string", ".", "startswith", "(", "BLOCK_TAG_START", ")", ":", "# The [2:-2] ranges below strip off *_TAG_START and *_TAG_END.", "# We could do len(BLOCK_TAG_START...
[ 213, 4 ]
[ 243, 20 ]
python
en
['en', 'error', 'th']
False
Parser.compile_filter
(self, token)
Convenient wrapper for FilterExpression
Convenient wrapper for FilterExpression
def compile_filter(self, token): """ Convenient wrapper for FilterExpression """ return FilterExpression(token, self)
[ "def", "compile_filter", "(", "self", ",", "token", ")", ":", "return", "FilterExpression", "(", "token", ",", "self", ")" ]
[ 369, 4 ]
[ 373, 44 ]
python
en
['en', 'error', 'th']
False
TokenParser.top
(self)
Overload this method to do the actual parsing and return the result.
Overload this method to do the actual parsing and return the result.
def top(self): """ Overload this method to do the actual parsing and return the result. """ raise NotImplementedError('subclasses of Tokenparser must provide a top() method')
[ "def", "top", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of Tokenparser must provide a top() method'", ")" ]
[ 397, 4 ]
[ 401, 90 ]
python
en
['en', 'error', 'th']
False
TokenParser.more
(self)
Returns True if there is more stuff in the tag.
Returns True if there is more stuff in the tag.
def more(self): """ Returns True if there is more stuff in the tag. """ return self.pointer < len(self.subject)
[ "def", "more", "(", "self", ")", ":", "return", "self", ".", "pointer", "<", "len", "(", "self", ".", "subject", ")" ]
[ 403, 4 ]
[ 407, 47 ]
python
en
['en', 'error', 'th']
False
TokenParser.back
(self)
Undoes the last microparser. Use this for lookahead and backtracking.
Undoes the last microparser. Use this for lookahead and backtracking.
def back(self): """ Undoes the last microparser. Use this for lookahead and backtracking. """ if not len(self.backout): raise TemplateSyntaxError("back called without some previous " "parsing") self.pointer = self.backout.pop()
[ "def", "back", "(", "self", ")", ":", "if", "not", "len", "(", "self", ".", "backout", ")", ":", "raise", "TemplateSyntaxError", "(", "\"back called without some previous \"", "\"parsing\"", ")", "self", ".", "pointer", "=", "self", ".", "backout", ".", "pop...
[ 409, 4 ]
[ 416, 41 ]
python
en
['en', 'error', 'th']
False
TokenParser.tag
(self)
A microparser that just returns the next tag from the line.
A microparser that just returns the next tag from the line.
def tag(self): """ A microparser that just returns the next tag from the line. """ subject = self.subject i = self.pointer if i >= len(subject): raise TemplateSyntaxError("expected another tag, found " "end of string: %s" ...
[ "def", "tag", "(", "self", ")", ":", "subject", "=", "self", ".", "subject", "i", "=", "self", ".", "pointer", "if", "i", ">=", "len", "(", "subject", ")", ":", "raise", "TemplateSyntaxError", "(", "\"expected another tag, found \"", "\"end of string: %s\"", ...
[ 418, 4 ]
[ 435, 16 ]
python
en
['en', 'error', 'th']
False
TokenParser.value
(self)
A microparser that parses for a value: some string constant or variable name.
A microparser that parses for a value: some string constant or variable name.
def value(self): """ A microparser that parses for a value: some string constant or variable name. """ subject = self.subject i = self.pointer def next_space_index(subject, i): """ Increment pointer until a real space (i.e. a space not wit...
[ "def", "value", "(", "self", ")", ":", "subject", "=", "self", ".", "subject", "i", "=", "self", ".", "pointer", "def", "next_space_index", "(", "subject", ",", "i", ")", ":", "\"\"\"\n Increment pointer until a real space (i.e. a space not within\n ...
[ 437, 4 ]
[ 496, 20 ]
python
en
['en', 'error', 'th']
False
Variable.resolve
(self, context)
Resolve this variable against a given context.
Resolve this variable against a given context.
def resolve(self, context): """Resolve this variable against a given context.""" if self.lookups is not None: # We're dealing with a variable that needs to be resolved value = self._resolve_lookup(context) else: # We're dealing with a literal, so it's already ...
[ "def", "resolve", "(", "self", ",", "context", ")", ":", "if", "self", ".", "lookups", "is", "not", "None", ":", "# We're dealing with a variable that needs to be resolved", "value", "=", "self", ".", "_resolve_lookup", "(", "context", ")", "else", ":", "# We're...
[ 734, 4 ]
[ 747, 20 ]
python
en
['en', 'en', 'en']
True
Variable._resolve_lookup
(self, context)
Performs resolution of a real variable (i.e. not a literal) against the given context. As indicated by the method's name, this method is an implementation detail and shouldn't be called by external code. Use Variable.resolve() instead.
Performs resolution of a real variable (i.e. not a literal) against the given context.
def _resolve_lookup(self, context): """ Performs resolution of a real variable (i.e. not a literal) against the given context. As indicated by the method's name, this method is an implementation detail and shouldn't be called by external code. Use Variable.resolve() inst...
[ "def", "_resolve_lookup", "(", "self", ",", "context", ")", ":", "current", "=", "context", "try", ":", "# catch-all for silent variable failures", "for", "bit", "in", "self", ".", "lookups", ":", "try", ":", "# dictionary lookup", "current", "=", "current", "["...
[ 755, 4 ]
[ 812, 22 ]
python
en
['en', 'error', 'th']
False
Node.render
(self, context)
Return the node rendered as a string.
Return the node rendered as a string.
def render(self, context): """ Return the node rendered as a string. """ pass
[ "def", "render", "(", "self", ",", "context", ")", ":", "pass" ]
[ 821, 4 ]
[ 825, 12 ]
python
en
['en', 'error', 'th']
False
Node.get_nodes_by_type
(self, nodetype)
Return a list of all nodes (within this node and its nodelist) of the given type
Return a list of all nodes (within this node and its nodelist) of the given type
def get_nodes_by_type(self, nodetype): """ Return a list of all nodes (within this node and its nodelist) of the given type """ nodes = [] if isinstance(self, nodetype): nodes.append(self) for attr in self.child_nodelists: nodelist = getatt...
[ "def", "get_nodes_by_type", "(", "self", ",", "nodetype", ")", ":", "nodes", "=", "[", "]", "if", "isinstance", "(", "self", ",", "nodetype", ")", ":", "nodes", ".", "append", "(", "self", ")", "for", "attr", "in", "self", ".", "child_nodelists", ":", ...
[ 830, 4 ]
[ 842, 20 ]
python
en
['en', 'error', 'th']
False
NodeList.get_nodes_by_type
(self, nodetype)
Return a list of all nodes of the given type
Return a list of all nodes of the given type
def get_nodes_by_type(self, nodetype): "Return a list of all nodes of the given type" nodes = [] for node in self: nodes.extend(node.get_nodes_by_type(nodetype)) return nodes
[ "def", "get_nodes_by_type", "(", "self", ",", "nodetype", ")", ":", "nodes", "=", "[", "]", "for", "node", "in", "self", ":", "nodes", ".", "extend", "(", "node", ".", "get_nodes_by_type", "(", "nodetype", ")", ")", "return", "nodes" ]
[ 860, 4 ]
[ 865, 20 ]
python
en
['en', 'en', 'en']
True
convert_strings_to_cmake_list
(*args)
Converts a sequence of whitespace-separated strings of tokens into a semicolon-separated string of tokens for CMake.
Converts a sequence of whitespace-separated strings of tokens into a semicolon-separated string of tokens for CMake.
def convert_strings_to_cmake_list(*args): """Converts a sequence of whitespace-separated strings of tokens into a semicolon-separated string of tokens for CMake. """ return ';'.join(' '.join(args).split())
[ "def", "convert_strings_to_cmake_list", "(", "*", "args", ")", ":", "return", "';'", ".", "join", "(", "' '", ".", "join", "(", "args", ")", ".", "split", "(", ")", ")" ]
[ 30, 0 ]
[ 35, 43 ]
python
en
['en', 'en', 'en']
True
translate_arg
(arg, new_name, value_when_none='no')
Translate a value populated from the command-line into a name to pass to the invocation of CMake.
Translate a value populated from the command-line into a name to pass to the invocation of CMake.
def translate_arg(arg, new_name, value_when_none='no'): """ Translate a value populated from the command-line into a name to pass to the invocation of CMake. """ if arg is None: value = value_when_none elif type(arg) is bool: value = 'yes' if arg else 'no' else: value = a...
[ "def", "translate_arg", "(", "arg", ",", "new_name", ",", "value_when_none", "=", "'no'", ")", ":", "if", "arg", "is", "None", ":", "value", "=", "value_when_none", "elif", "type", "(", "arg", ")", "is", "bool", ":", "value", "=", "'yes'", "if", "arg",...
[ 37, 0 ]
[ 48, 52 ]
python
en
['en', 'error', 'th']
False
getimage
(photo)
Copies the contents of a PhotoImage to a PIL image memory.
Copies the contents of a PhotoImage to a PIL image memory.
def getimage(photo): """Copies the contents of a PhotoImage to a PIL image memory.""" im = Image.new("RGBA", (photo.width(), photo.height())) block = im.im photo.tk.call("PyImagingPhotoGet", photo, block.id) return im
[ "def", "getimage", "(", "photo", ")", ":", "im", "=", "Image", ".", "new", "(", "\"RGBA\"", ",", "(", "photo", ".", "width", "(", ")", ",", "photo", ".", "height", "(", ")", ")", ")", "block", "=", "im", ".", "im", "photo", ".", "tk", ".", "c...
[ 273, 0 ]
[ 280, 13 ]
python
en
['en', 'en', 'en']
True
_show
(image, title)
Helper for the Image.show method.
Helper for the Image.show method.
def _show(image, title): """Helper for the Image.show method.""" class UI(tkinter.Label): def __init__(self, master, im): if im.mode == "1": self.image = BitmapImage(im, foreground="white", master=master) else: self.image = PhotoImage(im, master=m...
[ "def", "_show", "(", "image", ",", "title", ")", ":", "class", "UI", "(", "tkinter", ".", "Label", ")", ":", "def", "__init__", "(", "self", ",", "master", ",", "im", ")", ":", "if", "im", ".", "mode", "==", "\"1\"", ":", "self", ".", "image", ...
[ 283, 0 ]
[ 299, 25 ]
python
en
['en', 'en', 'en']
True
PhotoImage.__str__
(self)
Get the Tkinter photo image identifier. This method is automatically called by Tkinter whenever a PhotoImage object is passed to a Tkinter method. :return: A Tkinter photo image identifier (a string).
Get the Tkinter photo image identifier. This method is automatically called by Tkinter whenever a PhotoImage object is passed to a Tkinter method.
def __str__(self): """ Get the Tkinter photo image identifier. This method is automatically called by Tkinter whenever a PhotoImage object is passed to a Tkinter method. :return: A Tkinter photo image identifier (a string). """ return str(self.__photo)
[ "def", "__str__", "(", "self", ")", ":", "return", "str", "(", "self", ".", "__photo", ")" ]
[ 124, 4 ]
[ 132, 32 ]
python
en
['en', 'error', 'th']
False
PhotoImage.width
(self)
Get the width of the image. :return: The width, in pixels.
Get the width of the image.
def width(self): """ Get the width of the image. :return: The width, in pixels. """ return self.__size[0]
[ "def", "width", "(", "self", ")", ":", "return", "self", ".", "__size", "[", "0", "]" ]
[ 134, 4 ]
[ 140, 29 ]
python
en
['en', 'error', 'th']
False
PhotoImage.height
(self)
Get the height of the image. :return: The height, in pixels.
Get the height of the image.
def height(self): """ Get the height of the image. :return: The height, in pixels. """ return self.__size[1]
[ "def", "height", "(", "self", ")", ":", "return", "self", ".", "__size", "[", "1", "]" ]
[ 142, 4 ]
[ 148, 29 ]
python
en
['en', 'error', 'th']
False
PhotoImage.paste
(self, im, box=None)
Paste a PIL image into the photo image. Note that this can be very slow if the photo image is displayed. :param im: A PIL image. The size must match the target region. If the mode does not match, the image is converted to the mode of the bitmap image. ...
Paste a PIL image into the photo image. Note that this can be very slow if the photo image is displayed.
def paste(self, im, box=None): """ Paste a PIL image into the photo image. Note that this can be very slow if the photo image is displayed. :param im: A PIL image. The size must match the target region. If the mode does not match, the image is converted to the mode ...
[ "def", "paste", "(", "self", ",", "im", ",", "box", "=", "None", ")", ":", "# convert to blittable", "im", ".", "load", "(", ")", "image", "=", "im", ".", "im", "if", "image", ".", "isblock", "(", ")", "and", "im", ".", "mode", "==", "self", ".",...
[ 150, 4 ]
[ 198, 21 ]
python
en
['en', 'error', 'th']
False
BitmapImage.width
(self)
Get the width of the image. :return: The width, in pixels.
Get the width of the image.
def width(self): """ Get the width of the image. :return: The width, in pixels. """ return self.__size[0]
[ "def", "width", "(", "self", ")", ":", "return", "self", ".", "__size", "[", "0", "]" ]
[ 246, 4 ]
[ 252, 29 ]
python
en
['en', 'error', 'th']
False
BitmapImage.height
(self)
Get the height of the image. :return: The height, in pixels.
Get the height of the image.
def height(self): """ Get the height of the image. :return: The height, in pixels. """ return self.__size[1]
[ "def", "height", "(", "self", ")", ":", "return", "self", ".", "__size", "[", "1", "]" ]
[ 254, 4 ]
[ 260, 29 ]
python
en
['en', 'error', 'th']
False
BitmapImage.__str__
(self)
Get the Tkinter bitmap image identifier. This method is automatically called by Tkinter whenever a BitmapImage object is passed to a Tkinter method. :return: A Tkinter bitmap image identifier (a string).
Get the Tkinter bitmap image identifier. This method is automatically called by Tkinter whenever a BitmapImage object is passed to a Tkinter method.
def __str__(self): """ Get the Tkinter bitmap image identifier. This method is automatically called by Tkinter whenever a BitmapImage object is passed to a Tkinter method. :return: A Tkinter bitmap image identifier (a string). """ return str(self.__photo)
[ "def", "__str__", "(", "self", ")", ":", "return", "str", "(", "self", ".", "__photo", ")" ]
[ 262, 4 ]
[ 270, 32 ]
python
en
['en', 'error', 'th']
False
HandlerTests.test_lock_safety
(self)
Tests for bug #11193 (errors inside middleware shouldn't leave the initLock locked).
Tests for bug #11193 (errors inside middleware shouldn't leave the initLock locked).
def test_lock_safety(self): """ Tests for bug #11193 (errors inside middleware shouldn't leave the initLock locked). """ # Try running the handler, it will fail in load_middleware handler = WSGIHandler() self.assertEqual(handler.initLock.locked(), False) w...
[ "def", "test_lock_safety", "(", "self", ")", ":", "# Try running the handler, it will fail in load_middleware", "handler", "=", "WSGIHandler", "(", ")", "self", ".", "assertEqual", "(", "handler", ".", "initLock", ".", "locked", "(", ")", ",", "False", ")", "with"...
[ 23, 4 ]
[ 33, 58 ]
python
en
['en', 'error', 'th']
False
HandlerTests.test_bad_path_info
(self)
Tests for bug #15672 ('request' referenced before assignment)
Tests for bug #15672 ('request' referenced before assignment)
def test_bad_path_info(self): """Tests for bug #15672 ('request' referenced before assignment)""" environ = RequestFactory().get('/').environ environ['PATH_INFO'] = b'\xed' if six.PY2 else '\xed' handler = WSGIHandler() response = handler(environ, lambda *a, **k: None) se...
[ "def", "test_bad_path_info", "(", "self", ")", ":", "environ", "=", "RequestFactory", "(", ")", ".", "get", "(", "'/'", ")", ".", "environ", "environ", "[", "'PATH_INFO'", "]", "=", "b'\\xed'", "if", "six", ".", "PY2", "else", "'\\xed'", "handler", "=", ...
[ 35, 4 ]
[ 41, 51 ]
python
en
['en', 'en', 'en']
True
HandlerTests.test_non_ascii_query_string
(self)
Test that non-ASCII query strings are properly decoded (#20530, #22996).
Test that non-ASCII query strings are properly decoded (#20530, #22996).
def test_non_ascii_query_string(self): """ Test that non-ASCII query strings are properly decoded (#20530, #22996). """ environ = RequestFactory().get('/').environ raw_query_strings = [ b'want=caf%C3%A9', # This is the proper way to encode 'café' b'want=c...
[ "def", "test_non_ascii_query_string", "(", "self", ")", ":", "environ", "=", "RequestFactory", "(", ")", ".", "get", "(", "'/'", ")", ".", "environ", "raw_query_strings", "=", "[", "b'want=caf%C3%A9'", ",", "# This is the proper way to encode 'café'", "b'want=caf\\xc3...
[ 43, 4 ]
[ 67, 79 ]
python
en
['en', 'error', 'th']
False
HandlerTests.test_non_ascii_cookie
(self)
Test that non-ASCII cookies set in JavaScript are properly decoded (#20557).
Test that non-ASCII cookies set in JavaScript are properly decoded (#20557).
def test_non_ascii_cookie(self): """Test that non-ASCII cookies set in JavaScript are properly decoded (#20557).""" environ = RequestFactory().get('/').environ raw_cookie = 'want="café"' if six.PY3: raw_cookie = raw_cookie.encode('utf-8').decode('iso-8859-1') environ[...
[ "def", "test_non_ascii_cookie", "(", "self", ")", ":", "environ", "=", "RequestFactory", "(", ")", ".", "get", "(", "'/'", ")", ".", "environ", "raw_cookie", "=", "'want=\"café\"'", "if", "six", ".", "PY3", ":", "raw_cookie", "=", "raw_cookie", ".", "encod...
[ 69, 4 ]
[ 80, 69 ]
python
en
['en', 'en', 'en']
True
ImageBatchesBase.__init__
(self, datastore_client, entity_kind_batches, entity_kind_images)
Initialize ImageBatchesBase. Args: datastore_client: instance of the CompetitionDatastoreClient entity_kind_batches: Cloud Datastore entity kind which is used to store batches of images. entity_kind_images: Cloud Datastore entity kind which is used to store ...
Initialize ImageBatchesBase.
def __init__(self, datastore_client, entity_kind_batches, entity_kind_images): """Initialize ImageBatchesBase. Args: datastore_client: instance of the CompetitionDatastoreClient entity_kind_batches: Cloud Datastore entity kind which is used to store batches of images. ...
[ "def", "__init__", "(", "self", ",", "datastore_client", ",", "entity_kind_batches", ",", "entity_kind_images", ")", ":", "self", ".", "_datastore_client", "=", "datastore_client", "self", ".", "_entity_kind_batches", "=", "entity_kind_batches", "self", ".", "_entity_...
[ 47, 4 ]
[ 69, 23 ]
python
en
['en', 'zu', 'it']
False
ImageBatchesBase._write_single_batch_images_internal
(self, batch_id, client_batch)
Helper method to write images from single batch into datastore.
Helper method to write images from single batch into datastore.
def _write_single_batch_images_internal(self, batch_id, client_batch): """Helper method to write images from single batch into datastore.""" client = self._datastore_client batch_key = client.key(self._entity_kind_batches, batch_id) for img_id, img in iteritems(self._data[batch_id]["imag...
[ "def", "_write_single_batch_images_internal", "(", "self", ",", "batch_id", ",", "client_batch", ")", ":", "client", "=", "self", ".", "_datastore_client", "batch_key", "=", "client", ".", "key", "(", "self", ".", "_entity_kind_batches", ",", "batch_id", ")", "f...
[ 71, 4 ]
[ 81, 40 ]
python
en
['en', 'en', 'en']
True
ImageBatchesBase.write_to_datastore
(self)
Writes all image batches to the datastore.
Writes all image batches to the datastore.
def write_to_datastore(self): """Writes all image batches to the datastore.""" client = self._datastore_client with client.no_transact_batch() as client_batch: for batch_id, batch_data in iteritems(self._data): batch_key = client.key(self._entity_kind_batches, batch_i...
[ "def", "write_to_datastore", "(", "self", ")", ":", "client", "=", "self", ".", "_datastore_client", "with", "client", ".", "no_transact_batch", "(", ")", "as", "client_batch", ":", "for", "batch_id", ",", "batch_data", "in", "iteritems", "(", "self", ".", "...
[ 83, 4 ]
[ 94, 80 ]
python
en
['en', 'en', 'en']
True
ImageBatchesBase.write_single_batch_images_to_datastore
(self, batch_id)
Writes only images from one batch to the datastore.
Writes only images from one batch to the datastore.
def write_single_batch_images_to_datastore(self, batch_id): """Writes only images from one batch to the datastore.""" client = self._datastore_client with client.no_transact_batch() as client_batch: self._write_single_batch_images_internal(batch_id, client_batch)
[ "def", "write_single_batch_images_to_datastore", "(", "self", ",", "batch_id", ")", ":", "client", "=", "self", ".", "_datastore_client", "with", "client", ".", "no_transact_batch", "(", ")", "as", "client_batch", ":", "self", ".", "_write_single_batch_images_internal...
[ 96, 4 ]
[ 100, 76 ]
python
en
['en', 'en', 'en']
True
ImageBatchesBase.init_from_datastore
(self)
Initializes batches by reading from the datastore.
Initializes batches by reading from the datastore.
def init_from_datastore(self): """Initializes batches by reading from the datastore.""" self._data = {} for entity in self._datastore_client.query_fetch( kind=self._entity_kind_batches ): batch_id = entity.key.flat_path[-1] self._data[batch_id] = dict(...
[ "def", "init_from_datastore", "(", "self", ")", ":", "self", ".", "_data", "=", "{", "}", "for", "entity", "in", "self", ".", "_datastore_client", ".", "query_fetch", "(", "kind", "=", "self", ".", "_entity_kind_batches", ")", ":", "batch_id", "=", "entity...
[ 102, 4 ]
[ 114, 67 ]
python
en
['en', 'en', 'en']
True
ImageBatchesBase.data
(self)
Dictionary with data.
Dictionary with data.
def data(self): """Dictionary with data.""" return self._data
[ "def", "data", "(", "self", ")", ":", "return", "self", ".", "_data" ]
[ 117, 4 ]
[ 119, 25 ]
python
en
['en', 'en', 'en']
True
ImageBatchesBase.__getitem__
(self, key)
Returns specific batch by its key.
Returns specific batch by its key.
def __getitem__(self, key): """Returns specific batch by its key.""" return self._data[key]
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "return", "self", ".", "_data", "[", "key", "]" ]
[ 121, 4 ]
[ 123, 30 ]
python
en
['en', 'en', 'en']
True
ImageBatchesBase.add_batch
(self, batch_id, batch_properties=None)
Adds batch with give ID and list of properties.
Adds batch with give ID and list of properties.
def add_batch(self, batch_id, batch_properties=None): """Adds batch with give ID and list of properties.""" if batch_properties is None: batch_properties = {} if not isinstance(batch_properties, dict): raise ValueError( "batch_properties has to be dict, ho...
[ "def", "add_batch", "(", "self", ",", "batch_id", ",", "batch_properties", "=", "None", ")", ":", "if", "batch_properties", "is", "None", ":", "batch_properties", "=", "{", "}", "if", "not", "isinstance", "(", "batch_properties", ",", "dict", ")", ":", "ra...
[ 125, 4 ]
[ 135, 43 ]
python
en
['en', 'en', 'en']
True
ImageBatchesBase.add_image
(self, batch_id, image_id, image_properties=None)
Adds image to given batch.
Adds image to given batch.
def add_image(self, batch_id, image_id, image_properties=None): """Adds image to given batch.""" if batch_id not in self._data: raise KeyError('Batch with ID "{0}" does not exist'.format(batch_id)) if image_properties is None: image_properties = {} if not isinstan...
[ "def", "add_image", "(", "self", ",", "batch_id", ",", "image_id", ",", "image_properties", "=", "None", ")", ":", "if", "batch_id", "not", "in", "self", ".", "_data", ":", "raise", "KeyError", "(", "'Batch with ID \"{0}\" does not exist'", ".", "format", "(",...
[ 137, 4 ]
[ 148, 74 ]
python
en
['en', 'en', 'en']
True
ImageBatchesBase.count_num_images
(self)
Counts total number of images in all batches.
Counts total number of images in all batches.
def count_num_images(self): """Counts total number of images in all batches.""" return sum([len(v["images"]) for v in itervalues(self.data)])
[ "def", "count_num_images", "(", "self", ")", ":", "return", "sum", "(", "[", "len", "(", "v", "[", "\"images\"", "]", ")", "for", "v", "in", "itervalues", "(", "self", ".", "data", ")", "]", ")" ]
[ 150, 4 ]
[ 152, 69 ]
python
en
['en', 'en', 'en']
True
ImageBatchesBase.__str__
(self)
Returns human readable representation, which is useful for debugging.
Returns human readable representation, which is useful for debugging.
def __str__(self): """Returns human readable representation, which is useful for debugging.""" buf = StringIO() for batch_idx, (batch_id, batch_val) in enumerate(iteritems(self.data)): if batch_idx >= TO_STR_MAX_BATCHES: buf.write(u"...\n") break ...
[ "def", "__str__", "(", "self", ")", ":", "buf", "=", "StringIO", "(", ")", "for", "batch_idx", ",", "(", "batch_id", ",", "batch_val", ")", "in", "enumerate", "(", "iteritems", "(", "self", ".", "data", ")", ")", ":", "if", "batch_idx", ">=", "TO_STR...
[ 154, 4 ]
[ 175, 29 ]
python
en
['en', 'en', 'en']
True
DatasetBatches.__init__
(self, datastore_client, storage_client, dataset_name)
Initializes DatasetBatches. Args: datastore_client: instance of CompetitionDatastoreClient storage_client: instance of CompetitionStorageClient dataset_name: name of the dataset ('dev' or 'final')
Initializes DatasetBatches.
def __init__(self, datastore_client, storage_client, dataset_name): """Initializes DatasetBatches. Args: datastore_client: instance of CompetitionDatastoreClient storage_client: instance of CompetitionStorageClient dataset_name: name of the dataset ('dev' or 'final') ...
[ "def", "__init__", "(", "self", ",", "datastore_client", ",", "storage_client", ",", "dataset_name", ")", ":", "super", "(", "DatasetBatches", ",", "self", ")", ".", "__init__", "(", "datastore_client", "=", "datastore_client", ",", "entity_kind_batches", "=", "...
[ 181, 4 ]
[ 195, 41 ]
python
it
['pl', 'zu', 'it']
False
DatasetBatches._read_image_list
(self, skip_image_ids=None)
Reads list of dataset images from the datastore.
Reads list of dataset images from the datastore.
def _read_image_list(self, skip_image_ids=None): """Reads list of dataset images from the datastore.""" if skip_image_ids is None: skip_image_ids = [] images = self._storage_client.list_blobs( prefix=os.path.join("dataset", self._dataset_name) + "/" ) zip_...
[ "def", "_read_image_list", "(", "self", ",", "skip_image_ids", "=", "None", ")", ":", "if", "skip_image_ids", "is", "None", ":", "skip_image_ids", "=", "[", "]", "images", "=", "self", ".", "_storage_client", ".", "list_blobs", "(", "prefix", "=", "os", "....
[ 197, 4 ]
[ 235, 21 ]
python
en
['en', 'en', 'en']
True
DatasetBatches.init_from_storage_write_to_datastore
( self, batch_size=100, allowed_epsilon=None, skip_image_ids=None, max_num_images=None, )
Initializes dataset batches from the list of images in the datastore. Args: batch_size: batch size allowed_epsilon: list of allowed epsilon or None to use default skip_image_ids: list of image ids to skip max_num_images: maximum number of images to read
Initializes dataset batches from the list of images in the datastore.
def init_from_storage_write_to_datastore( self, batch_size=100, allowed_epsilon=None, skip_image_ids=None, max_num_images=None, ): """Initializes dataset batches from the list of images in the datastore. Args: batch_size: batch size allowe...
[ "def", "init_from_storage_write_to_datastore", "(", "self", ",", "batch_size", "=", "100", ",", "allowed_epsilon", "=", "None", ",", "skip_image_ids", "=", "None", ",", "max_num_images", "=", "None", ",", ")", ":", "if", "allowed_epsilon", "is", "None", ":", "...
[ 237, 4 ]
[ 275, 33 ]
python
en
['en', 'en', 'en']
True
AversarialBatches.__init__
(self, datastore_client)
Initializes AversarialBatches. Args: datastore_client: instance of CompetitionDatastoreClient
Initializes AversarialBatches.
def __init__(self, datastore_client): """Initializes AversarialBatches. Args: datastore_client: instance of CompetitionDatastoreClient """ super(AversarialBatches, self).__init__( datastore_client=datastore_client, entity_kind_batches=KIND_ADVERSARIAL_B...
[ "def", "__init__", "(", "self", ",", "datastore_client", ")", ":", "super", "(", "AversarialBatches", ",", "self", ")", ".", "__init__", "(", "datastore_client", "=", "datastore_client", ",", "entity_kind_batches", "=", "KIND_ADVERSARIAL_BATCH", ",", "entity_kind_im...
[ 281, 4 ]
[ 291, 9 ]
python
it
['pl', 'sn', 'it']
False
AversarialBatches.init_from_dataset_and_submissions_write_to_datastore
( self, dataset_batches, attack_submission_ids )
Init list of adversarial batches from dataset batches and submissions. Args: dataset_batches: instances of DatasetBatches attack_submission_ids: iterable with IDs of all (targeted and nontargeted) attack submissions, could be obtains as CompetitionSubmissions.get_all...
Init list of adversarial batches from dataset batches and submissions.
def init_from_dataset_and_submissions_write_to_datastore( self, dataset_batches, attack_submission_ids ): """Init list of adversarial batches from dataset batches and submissions. Args: dataset_batches: instances of DatasetBatches attack_submission_ids: iterable with IDs...
[ "def", "init_from_dataset_and_submissions_write_to_datastore", "(", "self", ",", "dataset_batches", ",", "attack_submission_ids", ")", ":", "batches_x_attacks", "=", "itertools", ".", "product", "(", "dataset_batches", ".", "data", ".", "keys", "(", ")", ",", "attack_...
[ 293, 4 ]
[ 313, 33 ]
python
en
['en', 'en', 'en']
True
AversarialBatches.count_generated_adv_examples
(self)
Returns total number of all generated adversarial examples.
Returns total number of all generated adversarial examples.
def count_generated_adv_examples(self): """Returns total number of all generated adversarial examples.""" result = {} for v in itervalues(self.data): s_id = v["submission_id"] result[s_id] = result.get(s_id, 0) + len(v["images"]) return result
[ "def", "count_generated_adv_examples", "(", "self", ")", ":", "result", "=", "{", "}", "for", "v", "in", "itervalues", "(", "self", ".", "data", ")", ":", "s_id", "=", "v", "[", "\"submission_id\"", "]", "result", "[", "s_id", "]", "=", "result", ".", ...
[ 315, 4 ]
[ 321, 21 ]
python
en
['en', 'en', 'en']
True
salted_hmac
(key_salt, value, secret=None)
Return the HMAC-SHA1 of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY). A different key_salt should be passed in for every application of HMAC.
Return the HMAC-SHA1 of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY).
def salted_hmac(key_salt, value, secret=None): """ Return the HMAC-SHA1 of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY). A different key_salt should be passed in for every application of HMAC. """ if secret is None: secret = settings....
[ "def", "salted_hmac", "(", "key_salt", ",", "value", ",", "secret", "=", "None", ")", ":", "if", "secret", "is", "None", ":", "secret", "=", "settings", ".", "SECRET_KEY", "key_salt", "=", "force_bytes", "(", "key_salt", ")", "secret", "=", "force_bytes", ...
[ 11, 0 ]
[ 33, 72 ]
python
en
['en', 'error', 'th']
False
get_random_string
(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
Return a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
Return a securely generated random string.
def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Return a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit va...
[ "def", "get_random_string", "(", "length", "=", "12", ",", "allowed_chars", "=", "'abcdefghijklmnopqrstuvwxyz'", "'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'", ")", ":", "return", "''", ".", "join", "(", "secrets", ".", "choice", "(", "allowed_chars", ")", "for", "i", ...
[ 36, 0 ]
[ 45, 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", ")", ")" ]
[ 48, 0 ]
[ 50, 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...
[ 53, 0 ]
[ 60, 80 ]
python
en
['en', 'la', 'en']
True
get_source
(location, **kwargs)
Factory for StubSource Instance. Args: location (str): PathLike object or valid URL Returns: obj: Either Local or Remote StubSource Instance
Factory for StubSource Instance.
def get_source(location, **kwargs): """Factory for StubSource Instance. Args: location (str): PathLike object or valid URL Returns: obj: Either Local or Remote StubSource Instance """ try: utils.ensure_existing_dir(location) except NotADirectoryError: return Re...
[ "def", "get_source", "(", "location", ",", "*", "*", "kwargs", ")", ":", "try", ":", "utils", ".", "ensure_existing_dir", "(", "location", ")", "except", "NotADirectoryError", ":", "return", "RemoteStubSource", "(", "location", ",", "*", "*", "kwargs", ")", ...
[ 249, 0 ]
[ 264, 50 ]
python
en
['en', 'en', 'en']
True
StubRepo.has_package
(self, name)
Checks if package is available in repo. Args: name (str): name of package Returns: bool: True if package is available
Checks if package is available in repo.
def has_package(self, name): """Checks if package is available in repo. Args: name (str): name of package Returns: bool: True if package is available """ url = self.get_url(name) return utils.is_downloadable(url)
[ "def", "has_package", "(", "self", ",", "name", ")", ":", "url", "=", "self", ".", "get_url", "(", "name", ")", "return", "utils", ".", "is_downloadable", "(", "url", ")" ]
[ 47, 4 ]
[ 58, 41 ]
python
en
['en', 'en', 'en']
True
StubRepo.get_url
(self, path)
Returns formatted url to provided path. Args: path (str): path to format Returns: str: formatted url
Returns formatted url to provided path.
def get_url(self, path): """Returns formatted url to provided path. Args: path (str): path to format Returns: str: formatted url """ base_path = PurePosixPath(parse.urlparse(self.location).path) pkg_path = base_path / PurePosixPath(self.path) / ...
[ "def", "get_url", "(", "self", ",", "path", ")", ":", "base_path", "=", "PurePosixPath", "(", "parse", ".", "urlparse", "(", "self", ".", "location", ")", ".", "path", ")", "pkg_path", "=", "base_path", "/", "PurePosixPath", "(", "self", ".", "path", "...
[ 60, 4 ]
[ 74, 18 ]
python
en
['en', 'en', 'en']
True
StubRepo.search
(self, query)
Searches repository packages. Args: query (str): query to search by Returns: [str]: List of matching results
Searches repository packages.
def search(self, query): """Searches repository packages. Args: query (str): query to search by Returns: [str]: List of matching results """ query = query.strip().lower() pkg_names = [p["name"] for p in self.packages] results = set([p fo...
[ "def", "search", "(", "self", ",", "query", ")", ":", "query", "=", "query", ".", "strip", "(", ")", ".", "lower", "(", ")", "pkg_names", "=", "[", "p", "[", "\"name\"", "]", "for", "p", "in", "self", ".", "packages", "]", "results", "=", "set", ...
[ 76, 4 ]
[ 89, 22 ]
python
en
['en', 'en', 'en']
True
StubRepo.resolve_package
(cls, name)
Attempts to resolve package from all repos. Args: name (str): package to resolve Raises: StubNotFound: Package could not be resolved Returns: str: url to package
Attempts to resolve package from all repos.
def resolve_package(cls, name): """Attempts to resolve package from all repos. Args: name (str): package to resolve Raises: StubNotFound: Package could not be resolved Returns: str: url to package """ results = (r for r in cls.repos...
[ "def", "resolve_package", "(", "cls", ",", "name", ")", ":", "results", "=", "(", "r", "for", "r", "in", "cls", ".", "repos", "if", "r", ".", "has_package", "(", "name", ")", ")", "try", ":", "repo", "=", "next", "(", "results", ")", "except", "S...
[ 92, 4 ]
[ 112, 26 ]
python
en
['en', 'en', 'en']
True
StubRepo.from_json
(cls, content)
Create StubRepo Instances from JSON file. Args: file_obj (str or bytes): json content Returns: iterable of created repos
Create StubRepo Instances from JSON file.
def from_json(cls, content): """Create StubRepo Instances from JSON file. Args: file_obj (str or bytes): json content Returns: iterable of created repos """ data = json.loads(content) for source in data: source_url = source["source"]...
[ "def", "from_json", "(", "cls", ",", "content", ")", ":", "data", "=", "json", ".", "loads", "(", "content", ")", "for", "source", "in", "data", ":", "source_url", "=", "source", "[", "\"source\"", "]", "source_data", "=", "requests", ".", "get", "(", ...
[ 115, 4 ]
[ 130, 24 ]
python
en
['en', 'en', 'en']
True
StubSource.ready
(self, path=None, teardown=None)
Yields prepared Stub Source. Allows StubSource subclasses to have a preperation method before providing a local path to itself. Args: path (str, optional): path to stub source. Defaults to location. teardown (func, optional): callback to execute on exit....
Yields prepared Stub Source.
def ready(self, path=None, teardown=None): """Yields prepared Stub Source. Allows StubSource subclasses to have a preperation method before providing a local path to itself. Args: path (str, optional): path to stub source. Defaults to location. t...
[ "def", "ready", "(", "self", ",", "path", "=", "None", ",", "teardown", "=", "None", ")", ":", "_path", "=", "path", "or", "self", ".", "location", "info_path", "=", "next", "(", "_path", ".", "rglob", "(", "\"info.json\"", ")", ",", "None", ")", "...
[ 148, 4 ]
[ 169, 22 ]
python
en
['en', 'pl', 'en']
True
RemoteStubSource._unpack_archive
(self, file_bytes, path)
Unpack archive from bytes buffer. Args: file_bytes (bytes): Byte array to extract from Must be from tarfile with gzip compression path (str): path to extract file to Returns: path: path extracted to
Unpack archive from bytes buffer.
def _unpack_archive(self, file_bytes, path): """Unpack archive from bytes buffer. Args: file_bytes (bytes): Byte array to extract from Must be from tarfile with gzip compression path (str): path to extract file to Returns: path: path extracte...
[ "def", "_unpack_archive", "(", "self", ",", "file_bytes", ",", "path", ")", ":", "tar_bytes_obj", "=", "io", ".", "BytesIO", "(", "file_bytes", ")", "with", "tarfile", ".", "open", "(", "fileobj", "=", "tar_bytes_obj", ",", "mode", "=", "\"r:gz\"", ")", ...
[ 207, 4 ]
[ 223, 21 ]
python
en
['en', 'en', 'en']
True
RemoteStubSource.ready
(self)
Retrieves and unpacks source. Prepares remote stub resource by downloading and unpacking it into a temporary directory. This directory is removed on exit of the superclass context manager Returns: callable: StubSource.ready parent method
Retrieves and unpacks source.
def ready(self): """Retrieves and unpacks source. Prepares remote stub resource by downloading and unpacking it into a temporary directory. This directory is removed on exit of the superclass context manager Returns: callable: StubSource.ready parent method ...
[ "def", "ready", "(", "self", ")", ":", "tmp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "tmp_path", "=", "Path", "(", "tmp_dir", ")", "filename", "=", "utils", ".", "get_url_filename", "(", "self", ".", "location", ")", ".", "split", "(", "\".tar....
[ 225, 4 ]
[ 246, 65 ]
python
en
['en', 'af', 'en']
True
main
(argv=None)
Make a confidence report and save it to disk.
Make a confidence report and save it to disk.
def main(argv=None): """ Make a confidence report and save it to disk. """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) make_confidence_report( filepath=filepath, test_start=FLAGS.test_start, test_end=FLAGS.test_end, ...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "try", ":", "_name_of_script", ",", "filepath", "=", "argv", "except", "ValueError", ":", "raise", "ValueError", "(", "argv", ")", "make_confidence_report", "(", "filepath", "=", "filepath", ",", "test_start...
[ 56, 0 ]
[ 75, 5 ]
python
en
['en', 'error', 'th']
False
_basic_auth_str
(username, password)
Returns a Basic Auth string.
Returns a Basic Auth string.
def _basic_auth_str(username, password): """Returns a Basic Auth string.""" # "I want us to put a big-ol' comment on top of it that # says that this behaviour is dumb but we need to preserve # it because people are relying on it." # - Lukasa # # These are here solely to maintain backward...
[ "def", "_basic_auth_str", "(", "username", ",", "password", ")", ":", "# \"I want us to put a big-ol' comment on top of it that", "# says that this behaviour is dumb but we need to preserve", "# it because people are relying on it.\"", "# - Lukasa", "#", "# These are here solely to main...
[ 27, 0 ]
[ 68, 18 ]
python
en
['en', 'en', 'en']
True
HTTPDigestAuth.build_digest_header
(self, method, url)
:rtype: str
:rtype: str
def build_digest_header(self, method, url): """ :rtype: str """ realm = self._thread_local.chal['realm'] nonce = self._thread_local.chal['nonce'] qop = self._thread_local.chal.get('qop') algorithm = self._thread_local.chal.get('algorithm') opaque = self._...
[ "def", "build_digest_header", "(", "self", ",", "method", ",", "url", ")", ":", "realm", "=", "self", ".", "_thread_local", ".", "chal", "[", "'realm'", "]", "nonce", "=", "self", ".", "_thread_local", ".", "chal", "[", "'nonce'", "]", "qop", "=", "sel...
[ 126, 4 ]
[ 226, 35 ]
python
en
['en', 'error', 'th']
False
HTTPDigestAuth.handle_redirect
(self, r, **kwargs)
Reset num_401_calls counter on redirects.
Reset num_401_calls counter on redirects.
def handle_redirect(self, r, **kwargs): """Reset num_401_calls counter on redirects.""" if r.is_redirect: self._thread_local.num_401_calls = 1
[ "def", "handle_redirect", "(", "self", ",", "r", ",", "*", "*", "kwargs", ")", ":", "if", "r", ".", "is_redirect", ":", "self", ".", "_thread_local", ".", "num_401_calls", "=", "1" ]
[ 228, 4 ]
[ 231, 48 ]
python
en
['en', 'en', 'en']
True
HTTPDigestAuth.handle_401
(self, r, **kwargs)
Takes the given response and tries digest-auth, if needed. :rtype: requests.Response
Takes the given response and tries digest-auth, if needed.
def handle_401(self, r, **kwargs): """ Takes the given response and tries digest-auth, if needed. :rtype: requests.Response """ # If response is not 4xx, do not auth # See https://github.com/psf/requests/issues/3772 if not 400 <= r.status_code < 500: ...
[ "def", "handle_401", "(", "self", ",", "r", ",", "*", "*", "kwargs", ")", ":", "# If response is not 4xx, do not auth", "# See https://github.com/psf/requests/issues/3772", "if", "not", "400", "<=", "r", ".", "status_code", "<", "500", ":", "self", ".", "_thread_l...
[ 233, 4 ]
[ 275, 16 ]
python
en
['en', 'error', 'th']
False
StubManager.iter_by_firmware
(self, stubs=None)
Iterate stubs sorted by firmware. Args: stubs ([Stub], optional): Sublist of Stubs to iterate over. Defaults to None. If none, uses all installed stubs.
Iterate stubs sorted by firmware.
def iter_by_firmware(self, stubs=None): """Iterate stubs sorted by firmware. Args: stubs ([Stub], optional): Sublist of Stubs to iterate over. Defaults to None. If none, uses all installed stubs. """ loaded = stubs or self._loaded for firm in self._f...
[ "def", "iter_by_firmware", "(", "self", ",", "stubs", "=", "None", ")", ":", "loaded", "=", "stubs", "or", "self", ".", "_loaded", "for", "firm", "in", "self", ".", "_firmware", ":", "stubs", "=", "[", "s", "for", "s", "in", "loaded", "if", "s", "....
[ 46, 4 ]
[ 59, 32 ]
python
en
['en', 'en', 'en']
True
StubManager.verbose_log
(self, state)
Enable Stub logging to stdout. Args: state (bool): State to set Returns: bool: state
Enable Stub logging to stdout.
def verbose_log(self, state): """Enable Stub logging to stdout. Args: state (bool): State to set Returns: bool: state """ self.log.stdout = state return state
[ "def", "verbose_log", "(", "self", ",", "state", ")", ":", "self", ".", "log", ".", "stdout", "=", "state", "return", "state" ]
[ 61, 4 ]
[ 72, 20 ]
python
en
['en', 'en', 'en']
True
StubManager._load
(self, stub_source, strict=True, **kwargs)
Loads a stub into StubManager. Args: stub_source (StubSource): Stub Source Instance strict (bool, optional): Raise Exception if stub fails to resolve. Defaults to True. Raises: e: Exception raised by resolving failure Returns: St...
Loads a stub into StubManager.
def _load(self, stub_source, strict=True, **kwargs): """Loads a stub into StubManager. Args: stub_source (StubSource): Stub Source Instance strict (bool, optional): Raise Exception if stub fails to resolve. Defaults to True. Raises: e: Except...
[ "def", "_load", "(", "self", ",", "stub_source", ",", "strict", "=", "True", ",", "*", "*", "kwargs", ")", ":", "with", "stub_source", ".", "ready", "(", ")", "as", "src_path", ":", "try", ":", "stub_type", "=", "self", ".", "_get_stubtype", "(", "sr...
[ 74, 4 ]
[ 108, 27 ]
python
en
['en', 'en', 'en']
True
StubManager.resolve_firmware
(self, stub)
Resolves FirmwareStub for DeviceStub instance. Args: stub (DeviceStub): Stub to resolve Returns: FirmwareStub: Instance of FirmwareStub NoneType: None if an appropriate FirmwareStub cannot be found
Resolves FirmwareStub for DeviceStub instance.
def resolve_firmware(self, stub): """Resolves FirmwareStub for DeviceStub instance. Args: stub (DeviceStub): Stub to resolve Returns: FirmwareStub: Instance of FirmwareStub NoneType: None if an appropriate FirmwareStub cannot be found ...
[ "def", "resolve_firmware", "(", "self", ",", "stub", ")", ":", "fware_name", "=", "stub", ".", "firmware_name", "self", ".", "log", ".", "info", "(", "f\"Detected Firmware: $[{fware_name}]\"", ")", "results", "=", "(", "f", "for", "f", "in", "self", ".", "...
[ 110, 4 ]
[ 136, 20 ]
python
en
['en', 'da', 'en']
True
StubManager.validate
(self, path, schema=None)
Validates given stub path against its schema. Args: path (str): path to validate schema (str, optional): Path to schema. Defaults to None. If None, the DeviceStub schema is used. Raises: StubError: Raised if no info file can be found Stub...
Validates given stub path against its schema.
def validate(self, path, schema=None): """Validates given stub path against its schema. Args: path (str): path to validate schema (str, optional): Path to schema. Defaults to None. If None, the DeviceStub schema is used. Raises: StubError: Ra...
[ "def", "validate", "(", "self", ",", "path", ",", "schema", "=", "None", ")", ":", "self", ".", "log", ".", "debug", "(", "f\"Validating: {path}\"", ")", "schema", "=", "schema", "or", "self", ".", "_schema", "path", "=", "Path", "(", "path", ")", "....
[ 138, 4 ]
[ 161, 51 ]
python
en
['en', 'en', 'en']
True
StubManager._get_stubtype
(self, path)
Resolves appropriate stub type. Args: path (str): path to stub Returns: cls: Appropriate class for stub
Resolves appropriate stub type.
def _get_stubtype(self, path): """Resolves appropriate stub type. Args: path (str): path to stub Returns: cls: Appropriate class for stub """ try: self.validate(path) except StubValidationError: try: self....
[ "def", "_get_stubtype", "(", "self", ",", "path", ")", ":", "try", ":", "self", ".", "validate", "(", "path", ")", "except", "StubValidationError", ":", "try", ":", "self", ".", "validate", "(", "path", ",", "schema", "=", "self", ".", "_firm_schema", ...
[ 163, 4 ]
[ 185, 29 ]
python
en
['et', 'en', 'en']
True
StubManager.is_valid
(self, path)
Check if stub is valid without raising an exception. Args: path (str): path to stub Returns: bool: True if stub is valid
Check if stub is valid without raising an exception.
def is_valid(self, path): """Check if stub is valid without raising an exception. Args: path (str): path to stub Returns: bool: True if stub is valid """ try: self._get_stubtype(path) except Exception: return False ...
[ "def", "is_valid", "(", "self", ",", "path", ")", ":", "try", ":", "self", ".", "_get_stubtype", "(", "path", ")", "except", "Exception", ":", "return", "False", "else", ":", "return", "True" ]
[ 187, 4 ]
[ 202, 23 ]
python
en
['en', 'en', 'en']
True
StubManager._check_existing
(self, location)
check if location is or contains an existing stub. Args: location (str): name or path of Stub Returns: generator of existing stubs
check if location is or contains an existing stub.
def _check_existing(self, location): """check if location is or contains an existing stub. Args: location (str): name or path of Stub Returns: generator of existing stubs """ try: do_recurse = self._should_recurse(location) except St...
[ "def", "_check_existing", "(", "self", ",", "location", ")", ":", "try", ":", "do_recurse", "=", "self", ".", "_should_recurse", "(", "location", ")", "except", "StubError", ":", "yield", "else", ":", "if", "do_recurse", ":", "for", "s", "in", "(", "self...
[ 204, 4 ]
[ 232, 26 ]
python
en
['en', 'en', 'en']
True