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
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
SimpleListFilter.value
(self)
Return the value (in string format) provided in the request's query string for this filter, if any, or None if the value wasn't provided.
Return the value (in string format) provided in the request's query string for this filter, if any, or None if the value wasn't provided.
def value(self): """ Return the value (in string format) provided in the request's query string for this filter, if any, or None if the value wasn't provided. """ return self.used_parameters.get(self.parameter_name)
[ "def", "value", "(", "self", ")", ":", "return", "self", ".", "used_parameters", ".", "get", "(", "self", ".", "parameter_name", ")" ]
[ 83, 4 ]
[ 89, 60 ]
python
en
['en', 'error', 'th']
False
SimpleListFilter.lookups
(self, request, model_admin)
Must be overridden to return a list of tuples (value, verbose value)
Must be overridden to return a list of tuples (value, verbose value)
def lookups(self, request, model_admin): """ Must be overridden to return a list of tuples (value, verbose value) """ raise NotImplementedError( 'The SimpleListFilter.lookups() method must be overridden to ' 'return a list of tuples (value, verbose value).' )
[ "def", "lookups", "(", "self", ",", "request", ",", "model_admin", ")", ":", "raise", "NotImplementedError", "(", "'The SimpleListFilter.lookups() method must be overridden to '", "'return a list of tuples (value, verbose value).'", ")" ]
[ 91, 4 ]
[ 98, 9 ]
python
en
['en', 'error', 'th']
False
RelatedFieldListFilter.include_empty_choice
(self)
Return True if a "(None)" choice should be included, which filters out everything except empty relationships.
Return True if a "(None)" choice should be included, which filters out everything except empty relationships.
def include_empty_choice(self): """ Return True if a "(None)" choice should be included, which filters out everything except empty relationships. """ return self.field.null or (self.field.is_relation and self.field.many_to_many)
[ "def", "include_empty_choice", "(", "self", ")", ":", "return", "self", ".", "field", ".", "null", "or", "(", "self", ".", "field", ".", "is_relation", "and", "self", ".", "field", ".", "many_to_many", ")" ]
[ 178, 4 ]
[ 183, 86 ]
python
en
['en', 'error', 'th']
False
RelatedFieldListFilter.field_admin_ordering
(self, field, request, model_admin)
Return the model admin's ordering for related field, if provided.
Return the model admin's ordering for related field, if provided.
def field_admin_ordering(self, field, request, model_admin): """ Return the model admin's ordering for related field, if provided. """ related_admin = model_admin.admin_site._registry.get(field.remote_field.model) if related_admin is not None: return related_admin.get_ordering(request) return ()
[ "def", "field_admin_ordering", "(", "self", ",", "field", ",", "request", ",", "model_admin", ")", ":", "related_admin", "=", "model_admin", ".", "admin_site", ".", "_registry", ".", "get", "(", "field", ".", "remote_field", ".", "model", ")", "if", "related_admin", "is", "not", "None", ":", "return", "related_admin", ".", "get_ordering", "(", "request", ")", "return", "(", ")" ]
[ 195, 4 ]
[ 202, 17 ]
python
en
['en', 'error', 'th']
False
BaseSpecifier.__str__
(self)
Returns the str representation of this Specifier like object. This should be representative of the Specifier itself.
Returns the str representation of this Specifier like object. This should be representative of the Specifier itself.
def __str__(self): """ Returns the str representation of this Specifier like object. This should be representative of the Specifier itself. """
[ "def", "__str__", "(", "self", ")", ":" ]
[ 23, 4 ]
[ 27, 11 ]
python
en
['en', 'error', 'th']
False
BaseSpecifier.__hash__
(self)
Returns a hash value for this Specifier like object.
Returns a hash value for this Specifier like object.
def __hash__(self): """ Returns a hash value for this Specifier like object. """
[ "def", "__hash__", "(", "self", ")", ":" ]
[ 30, 4 ]
[ 33, 11 ]
python
en
['en', 'error', 'th']
False
BaseSpecifier.__eq__
(self, other)
Returns a boolean representing whether or not the two Specifier like objects are equal.
Returns a boolean representing whether or not the two Specifier like objects are equal.
def __eq__(self, other): """ Returns a boolean representing whether or not the two Specifier like objects are equal. """
[ "def", "__eq__", "(", "self", ",", "other", ")", ":" ]
[ 36, 4 ]
[ 40, 11 ]
python
en
['en', 'error', 'th']
False
BaseSpecifier.__ne__
(self, other)
Returns a boolean representing whether or not the two Specifier like objects are not equal.
Returns a boolean representing whether or not the two Specifier like objects are not equal.
def __ne__(self, other): """ Returns a boolean representing whether or not the two Specifier like objects are not equal. """
[ "def", "__ne__", "(", "self", ",", "other", ")", ":" ]
[ 43, 4 ]
[ 47, 11 ]
python
en
['en', 'error', 'th']
False
BaseSpecifier.prereleases
(self)
Returns whether or not pre-releases as a whole are allowed by this specifier.
Returns whether or not pre-releases as a whole are allowed by this specifier.
def prereleases(self): """ Returns whether or not pre-releases as a whole are allowed by this specifier. """
[ "def", "prereleases", "(", "self", ")", ":" ]
[ 50, 4 ]
[ 54, 11 ]
python
en
['en', 'error', 'th']
False
BaseSpecifier.prereleases
(self, value)
Sets whether or not pre-releases as a whole are allowed by this specifier.
Sets whether or not pre-releases as a whole are allowed by this specifier.
def prereleases(self, value): """ Sets whether or not pre-releases as a whole are allowed by this specifier. """
[ "def", "prereleases", "(", "self", ",", "value", ")", ":" ]
[ 57, 4 ]
[ 61, 11 ]
python
en
['en', 'error', 'th']
False
BaseSpecifier.contains
(self, item, prereleases=None)
Determines if the given item is contained within this specifier.
Determines if the given item is contained within this specifier.
def contains(self, item, prereleases=None): """ Determines if the given item is contained within this specifier. """
[ "def", "contains", "(", "self", ",", "item", ",", "prereleases", "=", "None", ")", ":" ]
[ 64, 4 ]
[ 67, 11 ]
python
en
['en', 'error', 'th']
False
BaseSpecifier.filter
(self, iterable, prereleases=None)
Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it.
Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it.
def filter(self, iterable, prereleases=None): """ Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it. """
[ "def", "filter", "(", "self", ",", "iterable", ",", "prereleases", "=", "None", ")", ":" ]
[ 70, 4 ]
[ 74, 11 ]
python
en
['en', 'error', 'th']
False
find
(path, all=False)
Find a static file with the given path using all enabled finders. If ``all`` is ``False`` (default), return the first matching absolute path (or ``None`` if no match). Otherwise return a list.
Find a static file with the given path using all enabled finders.
def find(path, all=False): """ Find a static file with the given path using all enabled finders. If ``all`` is ``False`` (default), return the first matching absolute path (or ``None`` if no match). Otherwise return a list. """ searched_locations[:] = [] matches = [] for finder in get_finders(): result = finder.find(path, all=all) if not all and result: return result if not isinstance(result, (list, tuple)): result = [result] matches.extend(result) if matches: return matches # No match. return [] if all else None
[ "def", "find", "(", "path", ",", "all", "=", "False", ")", ":", "searched_locations", "[", ":", "]", "=", "[", "]", "matches", "=", "[", "]", "for", "finder", "in", "get_finders", "(", ")", ":", "result", "=", "finder", ".", "find", "(", "path", ",", "all", "=", "all", ")", "if", "not", "all", "and", "result", ":", "return", "result", "if", "not", "isinstance", "(", "result", ",", "(", "list", ",", "tuple", ")", ")", ":", "result", "=", "[", "result", "]", "matches", ".", "extend", "(", "result", ")", "if", "matches", ":", "return", "matches", "# No match.", "return", "[", "]", "if", "all", "else", "None" ]
[ 256, 0 ]
[ 275, 30 ]
python
en
['en', 'error', 'th']
False
get_finder
(import_path)
Import the staticfiles finder class described by import_path, where import_path is the full Python path to the class.
Import the staticfiles finder class described by import_path, where import_path is the full Python path to the class.
def get_finder(import_path): """ Import the staticfiles finder class described by import_path, where import_path is the full Python path to the class. """ Finder = import_string(import_path) if not issubclass(Finder, BaseFinder): raise ImproperlyConfigured('Finder "%s" is not a subclass of "%s"' % (Finder, BaseFinder)) return Finder()
[ "def", "get_finder", "(", "import_path", ")", ":", "Finder", "=", "import_string", "(", "import_path", ")", "if", "not", "issubclass", "(", "Finder", ",", "BaseFinder", ")", ":", "raise", "ImproperlyConfigured", "(", "'Finder \"%s\" is not a subclass of \"%s\"'", "%", "(", "Finder", ",", "BaseFinder", ")", ")", "return", "Finder", "(", ")" ]
[ 284, 0 ]
[ 293, 19 ]
python
en
['en', 'error', 'th']
False
BaseFinder.find
(self, path, all=False)
Given a relative file path, find an absolute file path. If the ``all`` parameter is False (default) return only the first found file path; if True, return a list of all found files paths.
Given a relative file path, find an absolute file path.
def find(self, path, all=False): """ Given a relative file path, find an absolute file path. If the ``all`` parameter is False (default) return only the first found file path; if True, return a list of all found files paths. """ raise NotImplementedError('subclasses of BaseFinder must provide a find() method')
[ "def", "find", "(", "self", ",", "path", ",", "all", "=", "False", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseFinder must provide a find() method'", ")" ]
[ 29, 4 ]
[ 36, 90 ]
python
en
['en', 'error', 'th']
False
BaseFinder.list
(self, ignore_patterns)
Given an optional list of paths to ignore, return a two item iterable consisting of the relative path and storage instance.
Given an optional list of paths to ignore, return a two item iterable consisting of the relative path and storage instance.
def list(self, ignore_patterns): """ Given an optional list of paths to ignore, return a two item iterable consisting of the relative path and storage instance. """ raise NotImplementedError('subclasses of BaseFinder must provide a list() method')
[ "def", "list", "(", "self", ",", "ignore_patterns", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseFinder must provide a list() method'", ")" ]
[ 38, 4 ]
[ 43, 90 ]
python
en
['en', 'error', 'th']
False
FileSystemFinder.find
(self, path, all=False)
Look for files in the extra locations as defined in STATICFILES_DIRS.
Look for files in the extra locations as defined in STATICFILES_DIRS.
def find(self, path, all=False): """ Look for files in the extra locations as defined in STATICFILES_DIRS. """ matches = [] for prefix, root in self.locations: if root not in searched_locations: searched_locations.append(root) matched_path = self.find_location(root, path, prefix) if matched_path: if not all: return matched_path matches.append(matched_path) return matches
[ "def", "find", "(", "self", ",", "path", ",", "all", "=", "False", ")", ":", "matches", "=", "[", "]", "for", "prefix", ",", "root", "in", "self", ".", "locations", ":", "if", "root", "not", "in", "searched_locations", ":", "searched_locations", ".", "append", "(", "root", ")", "matched_path", "=", "self", ".", "find_location", "(", "root", ",", "path", ",", "prefix", ")", "if", "matched_path", ":", "if", "not", "all", ":", "return", "matched_path", "matches", ".", "append", "(", "matched_path", ")", "return", "matches" ]
[ 94, 4 ]
[ 107, 22 ]
python
en
['en', 'error', 'th']
False
FileSystemFinder.find_location
(self, root, path, prefix=None)
Find a requested static file in a location and return the found absolute path (or ``None`` if no match).
Find a requested static file in a location and return the found absolute path (or ``None`` if no match).
def find_location(self, root, path, prefix=None): """ Find a requested static file in a location and return the found absolute path (or ``None`` if no match). """ if prefix: prefix = '%s%s' % (prefix, os.sep) if not path.startswith(prefix): return None path = path[len(prefix):] path = safe_join(root, path) if os.path.exists(path): return path
[ "def", "find_location", "(", "self", ",", "root", ",", "path", ",", "prefix", "=", "None", ")", ":", "if", "prefix", ":", "prefix", "=", "'%s%s'", "%", "(", "prefix", ",", "os", ".", "sep", ")", "if", "not", "path", ".", "startswith", "(", "prefix", ")", ":", "return", "None", "path", "=", "path", "[", "len", "(", "prefix", ")", ":", "]", "path", "=", "safe_join", "(", "root", ",", "path", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "path" ]
[ 109, 4 ]
[ 121, 23 ]
python
en
['en', 'error', 'th']
False
FileSystemFinder.list
(self, ignore_patterns)
List all files in all locations.
List all files in all locations.
def list(self, ignore_patterns): """ List all files in all locations. """ for prefix, root in self.locations: storage = self.storages[root] for path in utils.get_files(storage, ignore_patterns): yield path, storage
[ "def", "list", "(", "self", ",", "ignore_patterns", ")", ":", "for", "prefix", ",", "root", "in", "self", ".", "locations", ":", "storage", "=", "self", ".", "storages", "[", "root", "]", "for", "path", "in", "utils", ".", "get_files", "(", "storage", ",", "ignore_patterns", ")", ":", "yield", "path", ",", "storage" ]
[ 123, 4 ]
[ 130, 35 ]
python
en
['en', 'error', 'th']
False
AppDirectoriesFinder.list
(self, ignore_patterns)
List all files in all app storages.
List all files in all app storages.
def list(self, ignore_patterns): """ List all files in all app storages. """ for storage in self.storages.values(): if storage.exists(''): # check if storage location exists for path in utils.get_files(storage, ignore_patterns): yield path, storage
[ "def", "list", "(", "self", ",", "ignore_patterns", ")", ":", "for", "storage", "in", "self", ".", "storages", ".", "values", "(", ")", ":", "if", "storage", ".", "exists", "(", "''", ")", ":", "# check if storage location exists", "for", "path", "in", "utils", ".", "get_files", "(", "storage", ",", "ignore_patterns", ")", ":", "yield", "path", ",", "storage" ]
[ 159, 4 ]
[ 166, 39 ]
python
en
['en', 'error', 'th']
False
AppDirectoriesFinder.find
(self, path, all=False)
Look for files in the app directories.
Look for files in the app directories.
def find(self, path, all=False): """ Look for files in the app directories. """ matches = [] for app in self.apps: app_location = self.storages[app].location if app_location not in searched_locations: searched_locations.append(app_location) match = self.find_in_app(app, path) if match: if not all: return match matches.append(match) return matches
[ "def", "find", "(", "self", ",", "path", ",", "all", "=", "False", ")", ":", "matches", "=", "[", "]", "for", "app", "in", "self", ".", "apps", ":", "app_location", "=", "self", ".", "storages", "[", "app", "]", ".", "location", "if", "app_location", "not", "in", "searched_locations", ":", "searched_locations", ".", "append", "(", "app_location", ")", "match", "=", "self", ".", "find_in_app", "(", "app", ",", "path", ")", "if", "match", ":", "if", "not", "all", ":", "return", "match", "matches", ".", "append", "(", "match", ")", "return", "matches" ]
[ 168, 4 ]
[ 182, 22 ]
python
en
['en', 'error', 'th']
False
AppDirectoriesFinder.find_in_app
(self, app, path)
Find a requested static file in an app's static locations.
Find a requested static file in an app's static locations.
def find_in_app(self, app, path): """ Find a requested static file in an app's static locations. """ storage = self.storages.get(app) # Only try to find a file if the source dir actually exists. if storage and storage.exists(path): matched_path = storage.path(path) if matched_path: return matched_path
[ "def", "find_in_app", "(", "self", ",", "app", ",", "path", ")", ":", "storage", "=", "self", ".", "storages", ".", "get", "(", "app", ")", "# Only try to find a file if the source dir actually exists.", "if", "storage", "and", "storage", ".", "exists", "(", "path", ")", ":", "matched_path", "=", "storage", ".", "path", "(", "path", ")", "if", "matched_path", ":", "return", "matched_path" ]
[ 184, 4 ]
[ 193, 35 ]
python
en
['en', 'error', 'th']
False
BaseStorageFinder.find
(self, path, all=False)
Look for files in the default file storage, if it's local.
Look for files in the default file storage, if it's local.
def find(self, path, all=False): """ Look for files in the default file storage, if it's local. """ try: self.storage.path('') except NotImplementedError: pass else: if self.storage.location not in searched_locations: searched_locations.append(self.storage.location) if self.storage.exists(path): match = self.storage.path(path) if all: match = [match] return match return []
[ "def", "find", "(", "self", ",", "path", ",", "all", "=", "False", ")", ":", "try", ":", "self", ".", "storage", ".", "path", "(", "''", ")", "except", "NotImplementedError", ":", "pass", "else", ":", "if", "self", ".", "storage", ".", "location", "not", "in", "searched_locations", ":", "searched_locations", ".", "append", "(", "self", ".", "storage", ".", "location", ")", "if", "self", ".", "storage", ".", "exists", "(", "path", ")", ":", "match", "=", "self", ".", "storage", ".", "path", "(", "path", ")", "if", "all", ":", "match", "=", "[", "match", "]", "return", "match", "return", "[", "]" ]
[ 215, 4 ]
[ 231, 17 ]
python
en
['en', 'error', 'th']
False
BaseStorageFinder.list
(self, ignore_patterns)
List all files of the storage.
List all files of the storage.
def list(self, ignore_patterns): """ List all files of the storage. """ for path in utils.get_files(self.storage, ignore_patterns): yield path, self.storage
[ "def", "list", "(", "self", ",", "ignore_patterns", ")", ":", "for", "path", "in", "utils", ".", "get_files", "(", "self", ".", "storage", ",", "ignore_patterns", ")", ":", "yield", "path", ",", "self", ".", "storage" ]
[ 233, 4 ]
[ 238, 36 ]
python
en
['en', 'error', 'th']
False
eval
(expression, _dict={}, **kw)
Evaluates an image expression. :param expression: A string containing a Python-style expression. :param options: Values to add to the evaluation context. You can either use a dictionary, or one or more keyword arguments. :return: The evaluated expression. This is usually an image object, but can also be an integer, a floating point value, or a pixel tuple, depending on the expression.
Evaluates an image expression.
def eval(expression, _dict={}, **kw): """ Evaluates an image expression. :param expression: A string containing a Python-style expression. :param options: Values to add to the evaluation context. You can either use a dictionary, or one or more keyword arguments. :return: The evaluated expression. This is usually an image object, but can also be an integer, a floating point value, or a pixel tuple, depending on the expression. """ # build execution namespace args = ops.copy() args.update(_dict) args.update(kw) for k, v in list(args.items()): if hasattr(v, "im"): args[k] = _Operand(v) out = builtins.eval(expression, args) try: return out.im except AttributeError: return out
[ "def", "eval", "(", "expression", ",", "_dict", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "# build execution namespace", "args", "=", "ops", ".", "copy", "(", ")", "args", ".", "update", "(", "_dict", ")", "args", ".", "update", "(", "kw", ")", "for", "k", ",", "v", "in", "list", "(", "args", ".", "items", "(", ")", ")", ":", "if", "hasattr", "(", "v", ",", "\"im\"", ")", ":", "args", "[", "k", "]", "=", "_Operand", "(", "v", ")", "out", "=", "builtins", ".", "eval", "(", "expression", ",", "args", ")", "try", ":", "return", "out", ".", "im", "except", "AttributeError", ":", "return", "out" ]
[ 227, 0 ]
[ 252, 18 ]
python
en
['en', 'error', 'th']
False
ASGIHandler.__call__
(self, scope, receive, send)
Async entrypoint - parses the request and hands off to get_response.
Async entrypoint - parses the request and hands off to get_response.
async def __call__(self, scope, receive, send): """ Async entrypoint - parses the request and hands off to get_response. """ # Serve only HTTP connections. # FIXME: Allow to override this. if scope['type'] != 'http': raise ValueError( 'Django can only handle ASGI/HTTP connections, not %s.' % scope['type'] ) # Receive the HTTP request body as a stream object. try: body_file = await self.read_body(receive) except RequestAborted: return # Request is complete and can be served. set_script_prefix(self.get_script_prefix(scope)) await sync_to_async(signals.request_started.send, thread_sensitive=True)(sender=self.__class__, scope=scope) # Get the request and check for basic issues. request, error_response = self.create_request(scope, body_file) if request is None: await self.send_response(error_response, send) return # Get the response, using the async mode of BaseHandler. response = await self.get_response_async(request) response._handler_class = self.__class__ # Increase chunk size on file responses (ASGI servers handles low-level # chunking). if isinstance(response, FileResponse): response.block_size = self.chunk_size # Send the response. await self.send_response(response, send)
[ "async", "def", "__call__", "(", "self", ",", "scope", ",", "receive", ",", "send", ")", ":", "# Serve only HTTP connections.", "# FIXME: Allow to override this.", "if", "scope", "[", "'type'", "]", "!=", "'http'", ":", "raise", "ValueError", "(", "'Django can only handle ASGI/HTTP connections, not %s.'", "%", "scope", "[", "'type'", "]", ")", "# Receive the HTTP request body as a stream object.", "try", ":", "body_file", "=", "await", "self", ".", "read_body", "(", "receive", ")", "except", "RequestAborted", ":", "return", "# Request is complete and can be served.", "set_script_prefix", "(", "self", ".", "get_script_prefix", "(", "scope", ")", ")", "await", "sync_to_async", "(", "signals", ".", "request_started", ".", "send", ",", "thread_sensitive", "=", "True", ")", "(", "sender", "=", "self", ".", "__class__", ",", "scope", "=", "scope", ")", "# Get the request and check for basic issues.", "request", ",", "error_response", "=", "self", ".", "create_request", "(", "scope", ",", "body_file", ")", "if", "request", "is", "None", ":", "await", "self", ".", "send_response", "(", "error_response", ",", "send", ")", "return", "# Get the response, using the async mode of BaseHandler.", "response", "=", "await", "self", ".", "get_response_async", "(", "request", ")", "response", ".", "_handler_class", "=", "self", ".", "__class__", "# Increase chunk size on file responses (ASGI servers handles low-level", "# chunking).", "if", "isinstance", "(", "response", ",", "FileResponse", ")", ":", "response", ".", "block_size", "=", "self", ".", "chunk_size", "# Send the response.", "await", "self", ".", "send_response", "(", "response", ",", "send", ")" ]
[ 135, 4 ]
[ 167, 48 ]
python
en
['en', 'error', 'th']
False
ASGIHandler.read_body
(self, receive)
Reads a HTTP body from an ASGI connection.
Reads a HTTP body from an ASGI connection.
async def read_body(self, receive): """Reads a HTTP body from an ASGI connection.""" # Use the tempfile that auto rolls-over to a disk file as it fills up. body_file = tempfile.SpooledTemporaryFile(max_size=settings.FILE_UPLOAD_MAX_MEMORY_SIZE, mode='w+b') while True: message = await receive() if message['type'] == 'http.disconnect': # Early client disconnect. raise RequestAborted() # Add a body chunk from the message, if provided. if 'body' in message: body_file.write(message['body']) # Quit out if that's the end. if not message.get('more_body', False): break body_file.seek(0) return body_file
[ "async", "def", "read_body", "(", "self", ",", "receive", ")", ":", "# Use the tempfile that auto rolls-over to a disk file as it fills up.", "body_file", "=", "tempfile", ".", "SpooledTemporaryFile", "(", "max_size", "=", "settings", ".", "FILE_UPLOAD_MAX_MEMORY_SIZE", ",", "mode", "=", "'w+b'", ")", "while", "True", ":", "message", "=", "await", "receive", "(", ")", "if", "message", "[", "'type'", "]", "==", "'http.disconnect'", ":", "# Early client disconnect.", "raise", "RequestAborted", "(", ")", "# Add a body chunk from the message, if provided.", "if", "'body'", "in", "message", ":", "body_file", ".", "write", "(", "message", "[", "'body'", "]", ")", "# Quit out if that's the end.", "if", "not", "message", ".", "get", "(", "'more_body'", ",", "False", ")", ":", "break", "body_file", ".", "seek", "(", "0", ")", "return", "body_file" ]
[ 169, 4 ]
[ 185, 24 ]
python
en
['en', 'en', 'en']
True
ASGIHandler.create_request
(self, scope, body_file)
Create the Request object and returns either (request, None) or (None, response) if there is an error response.
Create the Request object and returns either (request, None) or (None, response) if there is an error response.
def create_request(self, scope, body_file): """ Create the Request object and returns either (request, None) or (None, response) if there is an error response. """ try: return self.request_class(scope, body_file), None except UnicodeDecodeError: logger.warning( 'Bad Request (UnicodeDecodeError)', exc_info=sys.exc_info(), extra={'status_code': 400}, ) return None, HttpResponseBadRequest() except RequestDataTooBig: return None, HttpResponse('413 Payload too large', status=413)
[ "def", "create_request", "(", "self", ",", "scope", ",", "body_file", ")", ":", "try", ":", "return", "self", ".", "request_class", "(", "scope", ",", "body_file", ")", ",", "None", "except", "UnicodeDecodeError", ":", "logger", ".", "warning", "(", "'Bad Request (UnicodeDecodeError)'", ",", "exc_info", "=", "sys", ".", "exc_info", "(", ")", ",", "extra", "=", "{", "'status_code'", ":", "400", "}", ",", ")", "return", "None", ",", "HttpResponseBadRequest", "(", ")", "except", "RequestDataTooBig", ":", "return", "None", ",", "HttpResponse", "(", "'413 Payload too large'", ",", "status", "=", "413", ")" ]
[ 187, 4 ]
[ 202, 74 ]
python
en
['en', 'error', 'th']
False
ASGIHandler.handle_uncaught_exception
(self, request, resolver, exc_info)
Last-chance handler for exceptions.
Last-chance handler for exceptions.
def handle_uncaught_exception(self, request, resolver, exc_info): """Last-chance handler for exceptions.""" # There's no WSGI server to catch the exception further up # if this fails, so translate it into a plain text response. try: return super().handle_uncaught_exception(request, resolver, exc_info) except Exception: return HttpResponseServerError( traceback.format_exc() if settings.DEBUG else 'Internal Server Error', content_type='text/plain', )
[ "def", "handle_uncaught_exception", "(", "self", ",", "request", ",", "resolver", ",", "exc_info", ")", ":", "# There's no WSGI server to catch the exception further up", "# if this fails, so translate it into a plain text response.", "try", ":", "return", "super", "(", ")", ".", "handle_uncaught_exception", "(", "request", ",", "resolver", ",", "exc_info", ")", "except", "Exception", ":", "return", "HttpResponseServerError", "(", "traceback", ".", "format_exc", "(", ")", "if", "settings", ".", "DEBUG", "else", "'Internal Server Error'", ",", "content_type", "=", "'text/plain'", ",", ")" ]
[ 204, 4 ]
[ 214, 13 ]
python
en
['da', 'en', 'en']
True
ASGIHandler.send_response
(self, response, send)
Encode and send a response out over ASGI.
Encode and send a response out over ASGI.
async def send_response(self, response, send): """Encode and send a response out over ASGI.""" # Collect cookies into headers. Have to preserve header case as there # are some non-RFC compliant clients that require e.g. Content-Type. response_headers = [] for header, value in response.items(): if isinstance(header, str): header = header.encode('ascii') if isinstance(value, str): value = value.encode('latin1') response_headers.append((bytes(header), bytes(value))) for c in response.cookies.values(): response_headers.append( (b'Set-Cookie', c.output(header='').encode('ascii').strip()) ) # Initial response message. await send({ 'type': 'http.response.start', 'status': response.status_code, 'headers': response_headers, }) # Streaming responses need to be pinned to their iterator. if response.streaming: # Access `__iter__` and not `streaming_content` directly in case # it has been overridden in a subclass. for part in response: for chunk, _ in self.chunk_bytes(part): await send({ 'type': 'http.response.body', 'body': chunk, # Ignore "more" as there may be more parts; instead, # use an empty final closing message with False. 'more_body': True, }) # Final closing message. await send({'type': 'http.response.body'}) # Other responses just need chunking. else: # Yield chunks of response. for chunk, last in self.chunk_bytes(response.content): await send({ 'type': 'http.response.body', 'body': chunk, 'more_body': not last, }) await sync_to_async(response.close, thread_sensitive=True)()
[ "async", "def", "send_response", "(", "self", ",", "response", ",", "send", ")", ":", "# Collect cookies into headers. Have to preserve header case as there", "# are some non-RFC compliant clients that require e.g. Content-Type.", "response_headers", "=", "[", "]", "for", "header", ",", "value", "in", "response", ".", "items", "(", ")", ":", "if", "isinstance", "(", "header", ",", "str", ")", ":", "header", "=", "header", ".", "encode", "(", "'ascii'", ")", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "value", ".", "encode", "(", "'latin1'", ")", "response_headers", ".", "append", "(", "(", "bytes", "(", "header", ")", ",", "bytes", "(", "value", ")", ")", ")", "for", "c", "in", "response", ".", "cookies", ".", "values", "(", ")", ":", "response_headers", ".", "append", "(", "(", "b'Set-Cookie'", ",", "c", ".", "output", "(", "header", "=", "''", ")", ".", "encode", "(", "'ascii'", ")", ".", "strip", "(", ")", ")", ")", "# Initial response message.", "await", "send", "(", "{", "'type'", ":", "'http.response.start'", ",", "'status'", ":", "response", ".", "status_code", ",", "'headers'", ":", "response_headers", ",", "}", ")", "# Streaming responses need to be pinned to their iterator.", "if", "response", ".", "streaming", ":", "# Access `__iter__` and not `streaming_content` directly in case", "# it has been overridden in a subclass.", "for", "part", "in", "response", ":", "for", "chunk", ",", "_", "in", "self", ".", "chunk_bytes", "(", "part", ")", ":", "await", "send", "(", "{", "'type'", ":", "'http.response.body'", ",", "'body'", ":", "chunk", ",", "# Ignore \"more\" as there may be more parts; instead,", "# use an empty final closing message with False.", "'more_body'", ":", "True", ",", "}", ")", "# Final closing message.", "await", "send", "(", "{", "'type'", ":", "'http.response.body'", "}", ")", "# Other responses just need chunking.", "else", ":", "# Yield chunks of response.", "for", "chunk", ",", "last", "in", "self", ".", "chunk_bytes", "(", "response", ".", "content", ")", ":", "await", "send", "(", "{", "'type'", ":", "'http.response.body'", ",", "'body'", ":", "chunk", ",", "'more_body'", ":", "not", "last", ",", "}", ")", "await", "sync_to_async", "(", "response", ".", "close", ",", "thread_sensitive", "=", "True", ")", "(", ")" ]
[ 216, 4 ]
[ 261, 68 ]
python
en
['en', 'en', 'en']
True
ASGIHandler.chunk_bytes
(cls, data)
Chunks some data up so it can be sent in reasonable size messages. Yields (chunk, last_chunk) tuples.
Chunks some data up so it can be sent in reasonable size messages. Yields (chunk, last_chunk) tuples.
def chunk_bytes(cls, data): """ Chunks some data up so it can be sent in reasonable size messages. Yields (chunk, last_chunk) tuples. """ position = 0 if not data: yield data, True return while position < len(data): yield ( data[position:position + cls.chunk_size], (position + cls.chunk_size) >= len(data), ) position += cls.chunk_size
[ "def", "chunk_bytes", "(", "cls", ",", "data", ")", ":", "position", "=", "0", "if", "not", "data", ":", "yield", "data", ",", "True", "return", "while", "position", "<", "len", "(", "data", ")", ":", "yield", "(", "data", "[", "position", ":", "position", "+", "cls", ".", "chunk_size", "]", ",", "(", "position", "+", "cls", ".", "chunk_size", ")", ">=", "len", "(", "data", ")", ",", ")", "position", "+=", "cls", ".", "chunk_size" ]
[ 264, 4 ]
[ 278, 38 ]
python
en
['en', 'error', 'th']
False
ASGIHandler.get_script_prefix
(self, scope)
Return the script prefix to use from either the scope or a setting.
Return the script prefix to use from either the scope or a setting.
def get_script_prefix(self, scope): """ Return the script prefix to use from either the scope or a setting. """ if settings.FORCE_SCRIPT_NAME: return settings.FORCE_SCRIPT_NAME return scope.get('root_path', '') or ''
[ "def", "get_script_prefix", "(", "self", ",", "scope", ")", ":", "if", "settings", ".", "FORCE_SCRIPT_NAME", ":", "return", "settings", ".", "FORCE_SCRIPT_NAME", "return", "scope", ".", "get", "(", "'root_path'", ",", "''", ")", "or", "''" ]
[ 280, 4 ]
[ 286, 47 ]
python
en
['en', 'error', 'th']
False
get_rmse
(output_row, output_col, actual)
Compute rmse between predicted and actual ratings. Args: output_row: evaluated numpy array of row_factor output_col: evaluated numpy array of col_factor actual: coo_matrix of actual (test) values Returns: rmse
Compute rmse between predicted and actual ratings.
def get_rmse(output_row, output_col, actual): """Compute rmse between predicted and actual ratings. Args: output_row: evaluated numpy array of row_factor output_col: evaluated numpy array of col_factor actual: coo_matrix of actual (test) values Returns: rmse """ mse = 0 for i in xrange(actual.data.shape[0]): row_pred = output_row[actual.row[i]] col_pred = output_col[actual.col[i]] err = actual.data[i] - np.dot(row_pred, col_pred) mse += err * err mse /= actual.data.shape[0] rmse = math.sqrt(mse) return rmse
[ "def", "get_rmse", "(", "output_row", ",", "output_col", ",", "actual", ")", ":", "mse", "=", "0", "for", "i", "in", "xrange", "(", "actual", ".", "data", ".", "shape", "[", "0", "]", ")", ":", "row_pred", "=", "output_row", "[", "actual", ".", "row", "[", "i", "]", "]", "col_pred", "=", "output_col", "[", "actual", ".", "col", "[", "i", "]", "]", "err", "=", "actual", ".", "data", "[", "i", "]", "-", "np", ".", "dot", "(", "row_pred", ",", "col_pred", ")", "mse", "+=", "err", "*", "err", "mse", "/=", "actual", ".", "data", ".", "shape", "[", "0", "]", "rmse", "=", "math", ".", "sqrt", "(", "mse", ")", "return", "rmse" ]
[ 23, 0 ]
[ 42, 13 ]
python
en
['en', 'en', 'en']
True
simple_train
(model, input_tensor, num_iterations)
Helper function to train model on input for num_iterations. Args: model: WALSModel instance input_tensor: SparseTensor for input ratings matrix num_iterations: number of row/column updates to run Returns: tensorflow session, for evaluating results
Helper function to train model on input for num_iterations.
def simple_train(model, input_tensor, num_iterations): """Helper function to train model on input for num_iterations. Args: model: WALSModel instance input_tensor: SparseTensor for input ratings matrix num_iterations: number of row/column updates to run Returns: tensorflow session, for evaluating results """ sess = tf.Session(graph=input_tensor.graph) with input_tensor.graph.as_default(): row_update_op = model.update_row_factors(sp_input=input_tensor)[1] col_update_op = model.update_col_factors(sp_input=input_tensor)[1] sess.run(model.initialize_op) sess.run(model.worker_init) for _ in xrange(num_iterations): sess.run(model.row_update_prep_gramian_op) sess.run(model.initialize_row_update_op) sess.run(row_update_op) sess.run(model.col_update_prep_gramian_op) sess.run(model.initialize_col_update_op) sess.run(col_update_op) return sess
[ "def", "simple_train", "(", "model", ",", "input_tensor", ",", "num_iterations", ")", ":", "sess", "=", "tf", ".", "Session", "(", "graph", "=", "input_tensor", ".", "graph", ")", "with", "input_tensor", ".", "graph", ".", "as_default", "(", ")", ":", "row_update_op", "=", "model", ".", "update_row_factors", "(", "sp_input", "=", "input_tensor", ")", "[", "1", "]", "col_update_op", "=", "model", ".", "update_col_factors", "(", "sp_input", "=", "input_tensor", ")", "[", "1", "]", "sess", ".", "run", "(", "model", ".", "initialize_op", ")", "sess", ".", "run", "(", "model", ".", "worker_init", ")", "for", "_", "in", "xrange", "(", "num_iterations", ")", ":", "sess", ".", "run", "(", "model", ".", "row_update_prep_gramian_op", ")", "sess", ".", "run", "(", "model", ".", "initialize_row_update_op", ")", "sess", ".", "run", "(", "row_update_op", ")", "sess", ".", "run", "(", "model", ".", "col_update_prep_gramian_op", ")", "sess", ".", "run", "(", "model", ".", "initialize_col_update_op", ")", "sess", ".", "run", "(", "col_update_op", ")", "return", "sess" ]
[ 45, 0 ]
[ 72, 13 ]
python
en
['en', 'en', 'en']
True
make_wts
(data, wt_type, obs_wt, feature_wt_exp, axis)
Generate observed item weights. Args: data: coo_matrix of ratings data wt_type: weight type, LOG_RATINGS or LINEAR_RATINGS obs_wt: linear weight factor feature_wt_exp: logarithmic weight factor axis: axis to make weights for, 1=rows/users, 0=cols/items Returns: vector of weights for cols (items) or rows (users)
Generate observed item weights.
def make_wts(data, wt_type, obs_wt, feature_wt_exp, axis): """Generate observed item weights. Args: data: coo_matrix of ratings data wt_type: weight type, LOG_RATINGS or LINEAR_RATINGS obs_wt: linear weight factor feature_wt_exp: logarithmic weight factor axis: axis to make weights for, 1=rows/users, 0=cols/items Returns: vector of weights for cols (items) or rows (users) """ # recipricol of sum of number of items across rows (if axis is 0) frac = np.array(1.0/(data > 0.0).sum(axis)) # filter any invalid entries frac[np.ma.masked_invalid(frac).mask] = 0.0 # normalize weights according to assumed distribution of ratings if wt_type == LOG_RATINGS: wts = np.array(np.power(frac, feature_wt_exp)).flatten() else: wts = np.array(obs_wt * frac).flatten() # check again for any numerically unstable entries assert np.isfinite(wts).sum() == wts.shape[0] return wts
[ "def", "make_wts", "(", "data", ",", "wt_type", ",", "obs_wt", ",", "feature_wt_exp", ",", "axis", ")", ":", "# recipricol of sum of number of items across rows (if axis is 0)", "frac", "=", "np", ".", "array", "(", "1.0", "/", "(", "data", ">", "0.0", ")", ".", "sum", "(", "axis", ")", ")", "# filter any invalid entries", "frac", "[", "np", ".", "ma", ".", "masked_invalid", "(", "frac", ")", ".", "mask", "]", "=", "0.0", "# normalize weights according to assumed distribution of ratings", "if", "wt_type", "==", "LOG_RATINGS", ":", "wts", "=", "np", ".", "array", "(", "np", ".", "power", "(", "frac", ",", "feature_wt_exp", ")", ")", ".", "flatten", "(", ")", "else", ":", "wts", "=", "np", ".", "array", "(", "obs_wt", "*", "frac", ")", ".", "flatten", "(", ")", "# check again for any numerically unstable entries", "assert", "np", ".", "isfinite", "(", "wts", ")", ".", "sum", "(", ")", "==", "wts", ".", "shape", "[", "0", "]", "return", "wts" ]
[ 79, 0 ]
[ 106, 12 ]
python
en
['en', 'en', 'en']
True
wals_model
(data, dim, reg, unobs, weights=False, wt_type=LINEAR_RATINGS, feature_wt_exp=None, obs_wt=LINEAR_OBS_W)
Create the WALSModel and input, row and col factor tensors. Args: data: scipy coo_matrix of item ratings dim: number of latent factors reg: regularization constant unobs: unobserved item weight weights: True: set obs weights, False: obs weights = unobs weights wt_type: feature weight type: linear (0) or log (1) feature_wt_exp: feature weight exponent constant obs_wt: feature weight linear factor constant Returns: input_tensor: tensor holding the input ratings matrix row_factor: tensor for row_factor col_factor: tensor for col_factor model: WALSModel instance
Create the WALSModel and input, row and col factor tensors.
def wals_model(data, dim, reg, unobs, weights=False, wt_type=LINEAR_RATINGS, feature_wt_exp=None, obs_wt=LINEAR_OBS_W): """Create the WALSModel and input, row and col factor tensors. Args: data: scipy coo_matrix of item ratings dim: number of latent factors reg: regularization constant unobs: unobserved item weight weights: True: set obs weights, False: obs weights = unobs weights wt_type: feature weight type: linear (0) or log (1) feature_wt_exp: feature weight exponent constant obs_wt: feature weight linear factor constant Returns: input_tensor: tensor holding the input ratings matrix row_factor: tensor for row_factor col_factor: tensor for col_factor model: WALSModel instance """ row_wts = None col_wts = None num_rows = data.shape[0] num_cols = data.shape[1] if weights: assert feature_wt_exp is not None row_wts = np.ones(num_rows) col_wts = make_wts(data, wt_type, obs_wt, feature_wt_exp, 0) row_factor = None col_factor = None with tf.Graph().as_default(): input_tensor = tf.SparseTensor(indices=zip(data.row, data.col), values=(data.data).astype(np.float32), dense_shape=data.shape) model = factorization_ops.WALSModel(num_rows, num_cols, dim, unobserved_weight=unobs, regularization=reg, row_weights=row_wts, col_weights=col_wts) # retrieve the row and column factors row_factor = model.row_factors[0] col_factor = model.col_factors[0] return input_tensor, row_factor, col_factor, model
[ "def", "wals_model", "(", "data", ",", "dim", ",", "reg", ",", "unobs", ",", "weights", "=", "False", ",", "wt_type", "=", "LINEAR_RATINGS", ",", "feature_wt_exp", "=", "None", ",", "obs_wt", "=", "LINEAR_OBS_W", ")", ":", "row_wts", "=", "None", "col_wts", "=", "None", "num_rows", "=", "data", ".", "shape", "[", "0", "]", "num_cols", "=", "data", ".", "shape", "[", "1", "]", "if", "weights", ":", "assert", "feature_wt_exp", "is", "not", "None", "row_wts", "=", "np", ".", "ones", "(", "num_rows", ")", "col_wts", "=", "make_wts", "(", "data", ",", "wt_type", ",", "obs_wt", ",", "feature_wt_exp", ",", "0", ")", "row_factor", "=", "None", "col_factor", "=", "None", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "input_tensor", "=", "tf", ".", "SparseTensor", "(", "indices", "=", "zip", "(", "data", ".", "row", ",", "data", ".", "col", ")", ",", "values", "=", "(", "data", ".", "data", ")", ".", "astype", "(", "np", ".", "float32", ")", ",", "dense_shape", "=", "data", ".", "shape", ")", "model", "=", "factorization_ops", ".", "WALSModel", "(", "num_rows", ",", "num_cols", ",", "dim", ",", "unobserved_weight", "=", "unobs", ",", "regularization", "=", "reg", ",", "row_weights", "=", "row_wts", ",", "col_weights", "=", "col_wts", ")", "# retrieve the row and column factors", "row_factor", "=", "model", ".", "row_factors", "[", "0", "]", "col_factor", "=", "model", ".", "col_factors", "[", "0", "]", "return", "input_tensor", ",", "row_factor", ",", "col_factor", ",", "model" ]
[ 109, 0 ]
[ 160, 52 ]
python
en
['en', 'en', 'en']
True
reset_cache
(**kwargs)
Reset global state when LANGUAGES setting has been changed, as some languages should no longer be accepted.
Reset global state when LANGUAGES setting has been changed, as some languages should no longer be accepted.
def reset_cache(**kwargs): """ Reset global state when LANGUAGES setting has been changed, as some languages should no longer be accepted. """ if kwargs['setting'] in ('LANGUAGES', 'LANGUAGE_CODE'): check_for_language.cache_clear() get_languages.cache_clear() get_supported_language_variant.cache_clear()
[ "def", "reset_cache", "(", "*", "*", "kwargs", ")", ":", "if", "kwargs", "[", "'setting'", "]", "in", "(", "'LANGUAGES'", ",", "'LANGUAGE_CODE'", ")", ":", "check_for_language", ".", "cache_clear", "(", ")", "get_languages", ".", "cache_clear", "(", ")", "get_supported_language_variant", ".", "cache_clear", "(", ")" ]
[ 49, 0 ]
[ 57, 52 ]
python
en
['en', 'error', 'th']
False
translation
(language)
Return a translation object in the default 'django' domain.
Return a translation object in the default 'django' domain.
def translation(language): """ Return a translation object in the default 'django' domain. """ global _translations if language not in _translations: _translations[language] = DjangoTranslation(language) return _translations[language]
[ "def", "translation", "(", "language", ")", ":", "global", "_translations", "if", "language", "not", "in", "_translations", ":", "_translations", "[", "language", "]", "=", "DjangoTranslation", "(", "language", ")", "return", "_translations", "[", "language", "]" ]
[ 261, 0 ]
[ 268, 34 ]
python
en
['en', 'error', 'th']
False
activate
(language)
Fetch the translation object for a given language and install it as the current translation object for the current thread.
Fetch the translation object for a given language and install it as the current translation object for the current thread.
def activate(language): """ Fetch the translation object for a given language and install it as the current translation object for the current thread. """ if not language: return _active.value = translation(language)
[ "def", "activate", "(", "language", ")", ":", "if", "not", "language", ":", "return", "_active", ".", "value", "=", "translation", "(", "language", ")" ]
[ 271, 0 ]
[ 278, 41 ]
python
en
['en', 'error', 'th']
False
deactivate
()
Uninstall the active translation object so that further _() calls resolve to the default translation object.
Uninstall the active translation object so that further _() calls resolve to the default translation object.
def deactivate(): """ Uninstall the active translation object so that further _() calls resolve to the default translation object. """ if hasattr(_active, "value"): del _active.value
[ "def", "deactivate", "(", ")", ":", "if", "hasattr", "(", "_active", ",", "\"value\"", ")", ":", "del", "_active", ".", "value" ]
[ 281, 0 ]
[ 287, 25 ]
python
en
['en', 'error', 'th']
False
deactivate_all
()
Make the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason.
Make the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason.
def deactivate_all(): """ Make the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason. """ _active.value = gettext_module.NullTranslations() _active.value.to_language = lambda *args: None
[ "def", "deactivate_all", "(", ")", ":", "_active", ".", "value", "=", "gettext_module", ".", "NullTranslations", "(", ")", "_active", ".", "value", ".", "to_language", "=", "lambda", "*", "args", ":", "None" ]
[ 290, 0 ]
[ 297, 50 ]
python
en
['en', 'error', 'th']
False
get_language
()
Return the currently selected language.
Return the currently selected language.
def get_language(): """Return the currently selected language.""" t = getattr(_active, "value", None) if t is not None: try: return t.to_language() except AttributeError: pass # If we don't have a real translation object, assume it's the default language. return settings.LANGUAGE_CODE
[ "def", "get_language", "(", ")", ":", "t", "=", "getattr", "(", "_active", ",", "\"value\"", ",", "None", ")", "if", "t", "is", "not", "None", ":", "try", ":", "return", "t", ".", "to_language", "(", ")", "except", "AttributeError", ":", "pass", "# If we don't have a real translation object, assume it's the default language.", "return", "settings", ".", "LANGUAGE_CODE" ]
[ 300, 0 ]
[ 309, 33 ]
python
en
['en', 'en', 'en']
True
get_language_bidi
()
Return selected language's BiDi layout. * False = left-to-right layout * True = right-to-left layout
Return selected language's BiDi layout.
def get_language_bidi(): """ Return selected language's BiDi layout. * False = left-to-right layout * True = right-to-left layout """ lang = get_language() if lang is None: return False else: base_lang = get_language().split('-')[0] return base_lang in settings.LANGUAGES_BIDI
[ "def", "get_language_bidi", "(", ")", ":", "lang", "=", "get_language", "(", ")", "if", "lang", "is", "None", ":", "return", "False", "else", ":", "base_lang", "=", "get_language", "(", ")", ".", "split", "(", "'-'", ")", "[", "0", "]", "return", "base_lang", "in", "settings", ".", "LANGUAGES_BIDI" ]
[ 312, 0 ]
[ 324, 51 ]
python
en
['en', 'error', 'th']
False
catalog
()
Return the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string.
Return the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string.
def catalog(): """ Return the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string. """ global _default t = getattr(_active, "value", None) if t is not None: return t if _default is None: _default = translation(settings.LANGUAGE_CODE) return _default
[ "def", "catalog", "(", ")", ":", "global", "_default", "t", "=", "getattr", "(", "_active", ",", "\"value\"", ",", "None", ")", "if", "t", "is", "not", "None", ":", "return", "t", "if", "_default", "is", "None", ":", "_default", "=", "translation", "(", "settings", ".", "LANGUAGE_CODE", ")", "return", "_default" ]
[ 327, 0 ]
[ 340, 19 ]
python
en
['en', 'error', 'th']
False
gettext
(message)
Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object.
Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object.
def gettext(message): """ Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. """ global _default eol_message = message.replace('\r\n', '\n').replace('\r', '\n') if eol_message: _default = _default or translation(settings.LANGUAGE_CODE) translation_object = getattr(_active, "value", _default) result = translation_object.gettext(eol_message) else: # Return an empty value of the corresponding type if an empty message # is given, instead of metadata, which is the default gettext behavior. result = type(message)('') if isinstance(message, SafeData): return mark_safe(result) return result
[ "def", "gettext", "(", "message", ")", ":", "global", "_default", "eol_message", "=", "message", ".", "replace", "(", "'\\r\\n'", ",", "'\\n'", ")", ".", "replace", "(", "'\\r'", ",", "'\\n'", ")", "if", "eol_message", ":", "_default", "=", "_default", "or", "translation", "(", "settings", ".", "LANGUAGE_CODE", ")", "translation_object", "=", "getattr", "(", "_active", ",", "\"value\"", ",", "_default", ")", "result", "=", "translation_object", ".", "gettext", "(", "eol_message", ")", "else", ":", "# Return an empty value of the corresponding type if an empty message", "# is given, instead of metadata, which is the default gettext behavior.", "result", "=", "type", "(", "message", ")", "(", "''", ")", "if", "isinstance", "(", "message", ",", "SafeData", ")", ":", "return", "mark_safe", "(", "result", ")", "return", "result" ]
[ 343, 0 ]
[ 366, 17 ]
python
en
['en', 'error', 'th']
False
gettext_noop
(message)
Mark strings for translation but don't translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later.
Mark strings for translation but don't translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later.
def gettext_noop(message): """ Mark strings for translation but don't translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later. """ return message
[ "def", "gettext_noop", "(", "message", ")", ":", "return", "message" ]
[ 380, 0 ]
[ 387, 18 ]
python
en
['en', 'error', 'th']
False
ngettext
(singular, plural, number)
Return a string of the translation of either the singular or plural, based on the number.
Return a string of the translation of either the singular or plural, based on the number.
def ngettext(singular, plural, number): """ Return a string of the translation of either the singular or plural, based on the number. """ return do_ntranslate(singular, plural, number, 'ngettext')
[ "def", "ngettext", "(", "singular", ",", "plural", ",", "number", ")", ":", "return", "do_ntranslate", "(", "singular", ",", "plural", ",", "number", ",", "'ngettext'", ")" ]
[ 401, 0 ]
[ 406, 62 ]
python
en
['en', 'error', 'th']
False
all_locale_paths
()
Return a list of paths to user-provides languages files.
Return a list of paths to user-provides languages files.
def all_locale_paths(): """ Return a list of paths to user-provides languages files. """ globalpath = os.path.join( os.path.dirname(sys.modules[settings.__module__].__file__), 'locale') app_paths = [] for app_config in apps.get_app_configs(): locale_path = os.path.join(app_config.path, 'locale') if os.path.exists(locale_path): app_paths.append(locale_path) return [globalpath, *settings.LOCALE_PATHS, *app_paths]
[ "def", "all_locale_paths", "(", ")", ":", "globalpath", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "sys", ".", "modules", "[", "settings", ".", "__module__", "]", ".", "__file__", ")", ",", "'locale'", ")", "app_paths", "=", "[", "]", "for", "app_config", "in", "apps", ".", "get_app_configs", "(", ")", ":", "locale_path", "=", "os", ".", "path", ".", "join", "(", "app_config", ".", "path", ",", "'locale'", ")", "if", "os", ".", "path", ".", "exists", "(", "locale_path", ")", ":", "app_paths", ".", "append", "(", "locale_path", ")", "return", "[", "globalpath", ",", "*", "settings", ".", "LOCALE_PATHS", ",", "*", "app_paths", "]" ]
[ 420, 0 ]
[ 431, 59 ]
python
en
['en', 'error', 'th']
False
check_for_language
(lang_code)
Check whether there is a global language file for the given language code. This is used to decide whether a user-provided language is available. lru_cache should have a maxsize to prevent from memory exhaustion attacks, as the provided language codes are taken from the HTTP request. See also <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.
Check whether there is a global language file for the given language code. This is used to decide whether a user-provided language is available.
def check_for_language(lang_code): """ Check whether there is a global language file for the given language code. This is used to decide whether a user-provided language is available. lru_cache should have a maxsize to prevent from memory exhaustion attacks, as the provided language codes are taken from the HTTP request. See also <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>. """ # First, a quick check to make sure lang_code is well-formed (#21458) if lang_code is None or not language_code_re.search(lang_code): return False return any( gettext_module.find('django', path, [to_locale(lang_code)]) is not None for path in all_locale_paths() )
[ "def", "check_for_language", "(", "lang_code", ")", ":", "# First, a quick check to make sure lang_code is well-formed (#21458)", "if", "lang_code", "is", "None", "or", "not", "language_code_re", ".", "search", "(", "lang_code", ")", ":", "return", "False", "return", "any", "(", "gettext_module", ".", "find", "(", "'django'", ",", "path", ",", "[", "to_locale", "(", "lang_code", ")", "]", ")", "is", "not", "None", "for", "path", "in", "all_locale_paths", "(", ")", ")" ]
[ 435, 0 ]
[ 451, 5 ]
python
en
['en', 'error', 'th']
False
get_languages
()
Cache of settings.LANGUAGES in a dictionary for easy lookups by key.
Cache of settings.LANGUAGES in a dictionary for easy lookups by key.
def get_languages(): """ Cache of settings.LANGUAGES in a dictionary for easy lookups by key. """ return dict(settings.LANGUAGES)
[ "def", "get_languages", "(", ")", ":", "return", "dict", "(", "settings", ".", "LANGUAGES", ")" ]
[ 455, 0 ]
[ 459, 35 ]
python
en
['en', 'error', 'th']
False
get_supported_language_variant
(lang_code, strict=False)
Return the language code that's listed in supported languages, possibly selecting a more generic variant. Raise LookupError if nothing is found. If `strict` is False (the default), look for a country-specific variant when neither the language code nor its generic variant is found. lru_cache should have a maxsize to prevent from memory exhaustion attacks, as the provided language codes are taken from the HTTP request. See also <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.
Return the language code that's listed in supported languages, possibly selecting a more generic variant. Raise LookupError if nothing is found.
def get_supported_language_variant(lang_code, strict=False): """ Return the language code that's listed in supported languages, possibly selecting a more generic variant. Raise LookupError if nothing is found. If `strict` is False (the default), look for a country-specific variant when neither the language code nor its generic variant is found. lru_cache should have a maxsize to prevent from memory exhaustion attacks, as the provided language codes are taken from the HTTP request. See also <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>. """ if lang_code: # If 'fr-ca' is not supported, try special fallback or language-only 'fr'. possible_lang_codes = [lang_code] try: possible_lang_codes.extend(LANG_INFO[lang_code]['fallback']) except KeyError: pass generic_lang_code = lang_code.split('-')[0] possible_lang_codes.append(generic_lang_code) supported_lang_codes = get_languages() for code in possible_lang_codes: if code in supported_lang_codes and check_for_language(code): return code if not strict: # if fr-fr is not supported, try fr-ca. for supported_code in supported_lang_codes: if supported_code.startswith(generic_lang_code + '-'): return supported_code raise LookupError(lang_code)
[ "def", "get_supported_language_variant", "(", "lang_code", ",", "strict", "=", "False", ")", ":", "if", "lang_code", ":", "# If 'fr-ca' is not supported, try special fallback or language-only 'fr'.", "possible_lang_codes", "=", "[", "lang_code", "]", "try", ":", "possible_lang_codes", ".", "extend", "(", "LANG_INFO", "[", "lang_code", "]", "[", "'fallback'", "]", ")", "except", "KeyError", ":", "pass", "generic_lang_code", "=", "lang_code", ".", "split", "(", "'-'", ")", "[", "0", "]", "possible_lang_codes", ".", "append", "(", "generic_lang_code", ")", "supported_lang_codes", "=", "get_languages", "(", ")", "for", "code", "in", "possible_lang_codes", ":", "if", "code", "in", "supported_lang_codes", "and", "check_for_language", "(", "code", ")", ":", "return", "code", "if", "not", "strict", ":", "# if fr-fr is not supported, try fr-ca.", "for", "supported_code", "in", "supported_lang_codes", ":", "if", "supported_code", ".", "startswith", "(", "generic_lang_code", "+", "'-'", ")", ":", "return", "supported_code", "raise", "LookupError", "(", "lang_code", ")" ]
[ 463, 0 ]
[ 494, 32 ]
python
en
['en', 'error', 'th']
False
get_language_from_path
(path, strict=False)
Return the language code if there's a valid language code found in `path`. If `strict` is False (the default), look for a country-specific variant when neither the language code nor its generic variant is found.
Return the language code if there's a valid language code found in `path`.
def get_language_from_path(path, strict=False): """ Return the language code if there's a valid language code found in `path`. If `strict` is False (the default), look for a country-specific variant when neither the language code nor its generic variant is found. """ regex_match = language_code_prefix_re.match(path) if not regex_match: return None lang_code = regex_match[1] try: return get_supported_language_variant(lang_code, strict=strict) except LookupError: return None
[ "def", "get_language_from_path", "(", "path", ",", "strict", "=", "False", ")", ":", "regex_match", "=", "language_code_prefix_re", ".", "match", "(", "path", ")", "if", "not", "regex_match", ":", "return", "None", "lang_code", "=", "regex_match", "[", "1", "]", "try", ":", "return", "get_supported_language_variant", "(", "lang_code", ",", "strict", "=", "strict", ")", "except", "LookupError", ":", "return", "None" ]
[ 497, 0 ]
[ 511, 19 ]
python
en
['en', 'error', 'th']
False
get_language_from_request
(request, check_path=False)
Analyze the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. If check_path is True, the URL path prefix will be checked for a language code, otherwise this is skipped for backwards compatibility.
Analyze the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language.
def get_language_from_request(request, check_path=False): """ Analyze the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. If check_path is True, the URL path prefix will be checked for a language code, otherwise this is skipped for backwards compatibility. """ if check_path: lang_code = get_language_from_path(request.path_info) if lang_code is not None: return lang_code lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) if lang_code is not None and lang_code in get_languages() and check_for_language(lang_code): return lang_code try: return get_supported_language_variant(lang_code) except LookupError: pass accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '') for accept_lang, unused in parse_accept_lang_header(accept): if accept_lang == '*': break if not language_code_re.search(accept_lang): continue try: return get_supported_language_variant(accept_lang) except LookupError: continue try: return get_supported_language_variant(settings.LANGUAGE_CODE) except LookupError: return settings.LANGUAGE_CODE
[ "def", "get_language_from_request", "(", "request", ",", "check_path", "=", "False", ")", ":", "if", "check_path", ":", "lang_code", "=", "get_language_from_path", "(", "request", ".", "path_info", ")", "if", "lang_code", "is", "not", "None", ":", "return", "lang_code", "lang_code", "=", "request", ".", "COOKIES", ".", "get", "(", "settings", ".", "LANGUAGE_COOKIE_NAME", ")", "if", "lang_code", "is", "not", "None", "and", "lang_code", "in", "get_languages", "(", ")", "and", "check_for_language", "(", "lang_code", ")", ":", "return", "lang_code", "try", ":", "return", "get_supported_language_variant", "(", "lang_code", ")", "except", "LookupError", ":", "pass", "accept", "=", "request", ".", "META", ".", "get", "(", "'HTTP_ACCEPT_LANGUAGE'", ",", "''", ")", "for", "accept_lang", ",", "unused", "in", "parse_accept_lang_header", "(", "accept", ")", ":", "if", "accept_lang", "==", "'*'", ":", "break", "if", "not", "language_code_re", ".", "search", "(", "accept_lang", ")", ":", "continue", "try", ":", "return", "get_supported_language_variant", "(", "accept_lang", ")", "except", "LookupError", ":", "continue", "try", ":", "return", "get_supported_language_variant", "(", "settings", ".", "LANGUAGE_CODE", ")", "except", "LookupError", ":", "return", "settings", ".", "LANGUAGE_CODE" ]
[ 514, 0 ]
[ 554, 37 ]
python
en
['en', 'error', 'th']
False
parse_accept_lang_header
(lang_string)
Parse the lang_string, which is the body of an HTTP Accept-Language header, and return a tuple of (lang, q-value), ordered by 'q' values. Return an empty tuple if there are any format errors in lang_string.
Parse the lang_string, which is the body of an HTTP Accept-Language header, and return a tuple of (lang, q-value), ordered by 'q' values.
def parse_accept_lang_header(lang_string): """ Parse the lang_string, which is the body of an HTTP Accept-Language header, and return a tuple of (lang, q-value), ordered by 'q' values. Return an empty tuple if there are any format errors in lang_string. """ result = [] pieces = accept_language_re.split(lang_string.lower()) if pieces[-1]: return () for i in range(0, len(pieces) - 1, 3): first, lang, priority = pieces[i:i + 3] if first: return () if priority: priority = float(priority) else: priority = 1.0 result.append((lang, priority)) result.sort(key=lambda k: k[1], reverse=True) return tuple(result)
[ "def", "parse_accept_lang_header", "(", "lang_string", ")", ":", "result", "=", "[", "]", "pieces", "=", "accept_language_re", ".", "split", "(", "lang_string", ".", "lower", "(", ")", ")", "if", "pieces", "[", "-", "1", "]", ":", "return", "(", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "pieces", ")", "-", "1", ",", "3", ")", ":", "first", ",", "lang", ",", "priority", "=", "pieces", "[", "i", ":", "i", "+", "3", "]", "if", "first", ":", "return", "(", ")", "if", "priority", ":", "priority", "=", "float", "(", "priority", ")", "else", ":", "priority", "=", "1.0", "result", ".", "append", "(", "(", "lang", ",", "priority", ")", ")", "result", ".", "sort", "(", "key", "=", "lambda", "k", ":", "k", "[", "1", "]", ",", "reverse", "=", "True", ")", "return", "tuple", "(", "result", ")" ]
[ 558, 0 ]
[ 579, 24 ]
python
en
['en', 'error', 'th']
False
DjangoTranslation.__init__
(self, language, domain=None, localedirs=None)
Create a GNUTranslations() using many locale directories
Create a GNUTranslations() using many locale directories
def __init__(self, language, domain=None, localedirs=None): """Create a GNUTranslations() using many locale directories""" gettext_module.GNUTranslations.__init__(self) if domain is not None: self.domain = domain self.__language = language self.__to_language = to_language(language) self.__locale = to_locale(language) self._catalog = None # If a language doesn't have a catalog, use the Germanic default for # pluralization: anything except one is pluralized. self.plural = lambda n: int(n != 1) if self.domain == 'django': if localedirs is not None: # A module-level cache is used for caching 'django' translations warnings.warn("localedirs is ignored when domain is 'django'.", RuntimeWarning) localedirs = None self._init_translation_catalog() if localedirs: for localedir in localedirs: translation = self._new_gnu_trans(localedir) self.merge(translation) else: self._add_installed_apps_translations() self._add_local_translations() if self.__language == settings.LANGUAGE_CODE and self.domain == 'django' and self._catalog is None: # default lang should have at least one translation file available. raise OSError('No translation files found for default language %s.' % settings.LANGUAGE_CODE) self._add_fallback(localedirs) if self._catalog is None: # No catalogs found for this language, set an empty catalog. self._catalog = TranslationCatalog()
[ "def", "__init__", "(", "self", ",", "language", ",", "domain", "=", "None", ",", "localedirs", "=", "None", ")", ":", "gettext_module", ".", "GNUTranslations", ".", "__init__", "(", "self", ")", "if", "domain", "is", "not", "None", ":", "self", ".", "domain", "=", "domain", "self", ".", "__language", "=", "language", "self", ".", "__to_language", "=", "to_language", "(", "language", ")", "self", ".", "__locale", "=", "to_locale", "(", "language", ")", "self", ".", "_catalog", "=", "None", "# If a language doesn't have a catalog, use the Germanic default for", "# pluralization: anything except one is pluralized.", "self", ".", "plural", "=", "lambda", "n", ":", "int", "(", "n", "!=", "1", ")", "if", "self", ".", "domain", "==", "'django'", ":", "if", "localedirs", "is", "not", "None", ":", "# A module-level cache is used for caching 'django' translations", "warnings", ".", "warn", "(", "\"localedirs is ignored when domain is 'django'.\"", ",", "RuntimeWarning", ")", "localedirs", "=", "None", "self", ".", "_init_translation_catalog", "(", ")", "if", "localedirs", ":", "for", "localedir", "in", "localedirs", ":", "translation", "=", "self", ".", "_new_gnu_trans", "(", "localedir", ")", "self", ".", "merge", "(", "translation", ")", "else", ":", "self", ".", "_add_installed_apps_translations", "(", ")", "self", ".", "_add_local_translations", "(", ")", "if", "self", ".", "__language", "==", "settings", ".", "LANGUAGE_CODE", "and", "self", ".", "domain", "==", "'django'", "and", "self", ".", "_catalog", "is", "None", ":", "# default lang should have at least one translation file available.", "raise", "OSError", "(", "'No translation files found for default language %s.'", "%", "settings", ".", "LANGUAGE_CODE", ")", "self", ".", "_add_fallback", "(", "localedirs", ")", "if", "self", ".", "_catalog", "is", "None", ":", "# No catalogs found for this language, set an empty catalog.", "self", ".", "_catalog", "=", "TranslationCatalog", "(", ")" ]
[ 128, 4 ]
[ 163, 48 ]
python
en
['en', 'en', 'en']
True
DjangoTranslation._new_gnu_trans
(self, localedir, use_null_fallback=True)
Return a mergeable gettext.GNUTranslations instance. A convenience wrapper. By default gettext uses 'fallback=False'. Using param `use_null_fallback` to avoid confusion with any other references to 'fallback'.
Return a mergeable gettext.GNUTranslations instance.
def _new_gnu_trans(self, localedir, use_null_fallback=True): """ Return a mergeable gettext.GNUTranslations instance. A convenience wrapper. By default gettext uses 'fallback=False'. Using param `use_null_fallback` to avoid confusion with any other references to 'fallback'. """ return gettext_module.translation( domain=self.domain, localedir=localedir, languages=[self.__locale], fallback=use_null_fallback, )
[ "def", "_new_gnu_trans", "(", "self", ",", "localedir", ",", "use_null_fallback", "=", "True", ")", ":", "return", "gettext_module", ".", "translation", "(", "domain", "=", "self", ".", "domain", ",", "localedir", "=", "localedir", ",", "languages", "=", "[", "self", ".", "__locale", "]", ",", "fallback", "=", "use_null_fallback", ",", ")" ]
[ 168, 4 ]
[ 181, 9 ]
python
en
['en', 'error', 'th']
False
DjangoTranslation._init_translation_catalog
(self)
Create a base catalog using global django translations.
Create a base catalog using global django translations.
def _init_translation_catalog(self): """Create a base catalog using global django translations.""" settingsfile = sys.modules[settings.__module__].__file__ localedir = os.path.join(os.path.dirname(settingsfile), 'locale') translation = self._new_gnu_trans(localedir) self.merge(translation)
[ "def", "_init_translation_catalog", "(", "self", ")", ":", "settingsfile", "=", "sys", ".", "modules", "[", "settings", ".", "__module__", "]", ".", "__file__", "localedir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "settingsfile", ")", ",", "'locale'", ")", "translation", "=", "self", ".", "_new_gnu_trans", "(", "localedir", ")", "self", ".", "merge", "(", "translation", ")" ]
[ 183, 4 ]
[ 188, 31 ]
python
en
['en', 'bg', 'en']
True
DjangoTranslation._add_installed_apps_translations
(self)
Merge translations from each installed app.
Merge translations from each installed app.
def _add_installed_apps_translations(self): """Merge translations from each installed app.""" try: app_configs = reversed(list(apps.get_app_configs())) except AppRegistryNotReady: raise AppRegistryNotReady( "The translation infrastructure cannot be initialized before the " "apps registry is ready. Check that you don't make non-lazy " "gettext calls at import time.") for app_config in app_configs: localedir = os.path.join(app_config.path, 'locale') if os.path.exists(localedir): translation = self._new_gnu_trans(localedir) self.merge(translation)
[ "def", "_add_installed_apps_translations", "(", "self", ")", ":", "try", ":", "app_configs", "=", "reversed", "(", "list", "(", "apps", ".", "get_app_configs", "(", ")", ")", ")", "except", "AppRegistryNotReady", ":", "raise", "AppRegistryNotReady", "(", "\"The translation infrastructure cannot be initialized before the \"", "\"apps registry is ready. Check that you don't make non-lazy \"", "\"gettext calls at import time.\"", ")", "for", "app_config", "in", "app_configs", ":", "localedir", "=", "os", ".", "path", ".", "join", "(", "app_config", ".", "path", ",", "'locale'", ")", "if", "os", ".", "path", ".", "exists", "(", "localedir", ")", ":", "translation", "=", "self", ".", "_new_gnu_trans", "(", "localedir", ")", "self", ".", "merge", "(", "translation", ")" ]
[ 190, 4 ]
[ 203, 39 ]
python
en
['en', 'en', 'en']
True
DjangoTranslation._add_local_translations
(self)
Merge translations defined in LOCALE_PATHS.
Merge translations defined in LOCALE_PATHS.
def _add_local_translations(self): """Merge translations defined in LOCALE_PATHS.""" for localedir in reversed(settings.LOCALE_PATHS): translation = self._new_gnu_trans(localedir) self.merge(translation)
[ "def", "_add_local_translations", "(", "self", ")", ":", "for", "localedir", "in", "reversed", "(", "settings", ".", "LOCALE_PATHS", ")", ":", "translation", "=", "self", ".", "_new_gnu_trans", "(", "localedir", ")", "self", ".", "merge", "(", "translation", ")" ]
[ 205, 4 ]
[ 209, 35 ]
python
en
['en', 'en', 'en']
True
DjangoTranslation._add_fallback
(self, localedirs=None)
Set the GNUTranslations() fallback with the default language.
Set the GNUTranslations() fallback with the default language.
def _add_fallback(self, localedirs=None): """Set the GNUTranslations() fallback with the default language.""" # Don't set a fallback for the default language or any English variant # (as it's empty, so it'll ALWAYS fall back to the default language) if self.__language == settings.LANGUAGE_CODE or self.__language.startswith('en'): return if self.domain == 'django': # Get from cache default_translation = translation(settings.LANGUAGE_CODE) else: default_translation = DjangoTranslation( settings.LANGUAGE_CODE, domain=self.domain, localedirs=localedirs ) self.add_fallback(default_translation)
[ "def", "_add_fallback", "(", "self", ",", "localedirs", "=", "None", ")", ":", "# Don't set a fallback for the default language or any English variant", "# (as it's empty, so it'll ALWAYS fall back to the default language)", "if", "self", ".", "__language", "==", "settings", ".", "LANGUAGE_CODE", "or", "self", ".", "__language", ".", "startswith", "(", "'en'", ")", ":", "return", "if", "self", ".", "domain", "==", "'django'", ":", "# Get from cache", "default_translation", "=", "translation", "(", "settings", ".", "LANGUAGE_CODE", ")", "else", ":", "default_translation", "=", "DjangoTranslation", "(", "settings", ".", "LANGUAGE_CODE", ",", "domain", "=", "self", ".", "domain", ",", "localedirs", "=", "localedirs", ")", "self", ".", "add_fallback", "(", "default_translation", ")" ]
[ 211, 4 ]
[ 224, 46 ]
python
en
['en', 'en', 'en']
True
DjangoTranslation.merge
(self, other)
Merge another translation into this catalog.
Merge another translation into this catalog.
def merge(self, other): """Merge another translation into this catalog.""" if not getattr(other, '_catalog', None): return # NullTranslations() has no _catalog if self._catalog is None: # Take plural and _info from first catalog found (generally Django's). self.plural = other.plural self._info = other._info.copy() self._catalog = TranslationCatalog(other) else: self._catalog.update(other) if other._fallback: self.add_fallback(other._fallback)
[ "def", "merge", "(", "self", ",", "other", ")", ":", "if", "not", "getattr", "(", "other", ",", "'_catalog'", ",", "None", ")", ":", "return", "# NullTranslations() has no _catalog", "if", "self", ".", "_catalog", "is", "None", ":", "# Take plural and _info from first catalog found (generally Django's).", "self", ".", "plural", "=", "other", ".", "plural", "self", ".", "_info", "=", "other", ".", "_info", ".", "copy", "(", ")", "self", ".", "_catalog", "=", "TranslationCatalog", "(", "other", ")", "else", ":", "self", ".", "_catalog", ".", "update", "(", "other", ")", "if", "other", ".", "_fallback", ":", "self", ".", "add_fallback", "(", "other", ".", "_fallback", ")" ]
[ 226, 4 ]
[ 238, 46 ]
python
en
['en', 'en', 'en']
True
DjangoTranslation.language
(self)
Return the translation language.
Return the translation language.
def language(self): """Return the translation language.""" return self.__language
[ "def", "language", "(", "self", ")", ":", "return", "self", ".", "__language" ]
[ 240, 4 ]
[ 242, 30 ]
python
en
['en', 'zu', 'en']
True
DjangoTranslation.to_language
(self)
Return the translation language name.
Return the translation language name.
def to_language(self): """Return the translation language name.""" return self.__to_language
[ "def", "to_language", "(", "self", ")", ":", "return", "self", ".", "__to_language" ]
[ 244, 4 ]
[ 246, 33 ]
python
en
['en', 'zu', 'en']
True
detect
(byte_str)
Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray``
Detect the encoding of the given byte string.
def detect(byte_str): """ Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` """ if not isinstance(byte_str, bytearray): if not isinstance(byte_str, bytes): raise TypeError('Expected object of type bytes or bytearray, got: ' '{}'.format(type(byte_str))) else: byte_str = bytearray(byte_str) detector = UniversalDetector() detector.feed(byte_str) return detector.close()
[ "def", "detect", "(", "byte_str", ")", ":", "if", "not", "isinstance", "(", "byte_str", ",", "bytearray", ")", ":", "if", "not", "isinstance", "(", "byte_str", ",", "bytes", ")", ":", "raise", "TypeError", "(", "'Expected object of type bytes or bytearray, got: '", "'{}'", ".", "format", "(", "type", "(", "byte_str", ")", ")", ")", "else", ":", "byte_str", "=", "bytearray", "(", "byte_str", ")", "detector", "=", "UniversalDetector", "(", ")", "detector", ".", "feed", "(", "byte_str", ")", "return", "detector", ".", "close", "(", ")" ]
[ 26, 0 ]
[ 41, 27 ]
python
en
['en', 'error', 'th']
False
detect_all
(byte_str)
Detect all the possible encodings of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray``
Detect all the possible encodings of the given byte string.
def detect_all(byte_str): """ Detect all the possible encodings of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` """ if not isinstance(byte_str, bytearray): if not isinstance(byte_str, bytes): raise TypeError('Expected object of type bytes or bytearray, got: ' '{}'.format(type(byte_str))) else: byte_str = bytearray(byte_str) detector = UniversalDetector() detector.feed(byte_str) detector.close() if detector._input_state == InputState.HIGH_BYTE: results = [] for prober in detector._charset_probers: if prober.get_confidence() > detector.MINIMUM_THRESHOLD: charset_name = prober.charset_name lower_charset_name = prober.charset_name.lower() # Use Windows encoding name instead of ISO-8859 if we saw any # extra Windows-specific bytes if lower_charset_name.startswith('iso-8859'): if detector._has_win_bytes: charset_name = detector.ISO_WIN_MAP.get(lower_charset_name, charset_name) results.append({ 'encoding': charset_name, 'confidence': prober.get_confidence(), 'language': prober.language, }) if len(results) > 0: return sorted(results, key=lambda result: -result['confidence']) return [detector.result]
[ "def", "detect_all", "(", "byte_str", ")", ":", "if", "not", "isinstance", "(", "byte_str", ",", "bytearray", ")", ":", "if", "not", "isinstance", "(", "byte_str", ",", "bytes", ")", ":", "raise", "TypeError", "(", "'Expected object of type bytes or bytearray, got: '", "'{}'", ".", "format", "(", "type", "(", "byte_str", ")", ")", ")", "else", ":", "byte_str", "=", "bytearray", "(", "byte_str", ")", "detector", "=", "UniversalDetector", "(", ")", "detector", ".", "feed", "(", "byte_str", ")", "detector", ".", "close", "(", ")", "if", "detector", ".", "_input_state", "==", "InputState", ".", "HIGH_BYTE", ":", "results", "=", "[", "]", "for", "prober", "in", "detector", ".", "_charset_probers", ":", "if", "prober", ".", "get_confidence", "(", ")", ">", "detector", ".", "MINIMUM_THRESHOLD", ":", "charset_name", "=", "prober", ".", "charset_name", "lower_charset_name", "=", "prober", ".", "charset_name", ".", "lower", "(", ")", "# Use Windows encoding name instead of ISO-8859 if we saw any", "# extra Windows-specific bytes", "if", "lower_charset_name", ".", "startswith", "(", "'iso-8859'", ")", ":", "if", "detector", ".", "_has_win_bytes", ":", "charset_name", "=", "detector", ".", "ISO_WIN_MAP", ".", "get", "(", "lower_charset_name", ",", "charset_name", ")", "results", ".", "append", "(", "{", "'encoding'", ":", "charset_name", ",", "'confidence'", ":", "prober", ".", "get_confidence", "(", ")", ",", "'language'", ":", "prober", ".", "language", ",", "}", ")", "if", "len", "(", "results", ")", ">", "0", ":", "return", "sorted", "(", "results", ",", "key", "=", "lambda", "result", ":", "-", "result", "[", "'confidence'", "]", ")", "return", "[", "detector", ".", "result", "]" ]
[ 44, 0 ]
[ 82, 28 ]
python
en
['en', 'error', 'th']
False
TreeWalker.__init__
(self, tree)
Creates a TreeWalker :arg tree: the tree to walk
Creates a TreeWalker
def __init__(self, tree): """Creates a TreeWalker :arg tree: the tree to walk """ self.tree = tree
[ "def", "__init__", "(", "self", ",", "tree", ")", ":", "self", ".", "tree", "=", "tree" ]
[ 26, 4 ]
[ 32, 24 ]
python
en
['en', 'et', 'en']
True
TreeWalker.error
(self, msg)
Generates an error token with the given message :arg msg: the error message :returns: SerializeError token
Generates an error token with the given message
def error(self, msg): """Generates an error token with the given message :arg msg: the error message :returns: SerializeError token """ return {"type": "SerializeError", "data": msg}
[ "def", "error", "(", "self", ",", "msg", ")", ":", "return", "{", "\"type\"", ":", "\"SerializeError\"", ",", "\"data\"", ":", "msg", "}" ]
[ 37, 4 ]
[ 45, 54 ]
python
en
['en', 'en', 'en']
True
TreeWalker.emptyTag
(self, namespace, name, attrs, hasChildren=False)
Generates an EmptyTag token :arg namespace: the namespace of the token--can be ``None`` :arg name: the name of the element :arg attrs: the attributes of the element as a dict :arg hasChildren: whether or not to yield a SerializationError because this tag shouldn't have children :returns: EmptyTag token
Generates an EmptyTag token
def emptyTag(self, namespace, name, attrs, hasChildren=False): """Generates an EmptyTag token :arg namespace: the namespace of the token--can be ``None`` :arg name: the name of the element :arg attrs: the attributes of the element as a dict :arg hasChildren: whether or not to yield a SerializationError because this tag shouldn't have children :returns: EmptyTag token """ yield {"type": "EmptyTag", "name": name, "namespace": namespace, "data": attrs} if hasChildren: yield self.error("Void element has children")
[ "def", "emptyTag", "(", "self", ",", "namespace", ",", "name", ",", "attrs", ",", "hasChildren", "=", "False", ")", ":", "yield", "{", "\"type\"", ":", "\"EmptyTag\"", ",", "\"name\"", ":", "name", ",", "\"namespace\"", ":", "namespace", ",", "\"data\"", ":", "attrs", "}", "if", "hasChildren", ":", "yield", "self", ".", "error", "(", "\"Void element has children\"", ")" ]
[ 47, 4 ]
[ 66, 57 ]
python
de
['en', 'de', 'nl']
False
TreeWalker.startTag
(self, namespace, name, attrs)
Generates a StartTag token :arg namespace: the namespace of the token--can be ``None`` :arg name: the name of the element :arg attrs: the attributes of the element as a dict :returns: StartTag token
Generates a StartTag token
def startTag(self, namespace, name, attrs): """Generates a StartTag token :arg namespace: the namespace of the token--can be ``None`` :arg name: the name of the element :arg attrs: the attributes of the element as a dict :returns: StartTag token """ return {"type": "StartTag", "name": name, "namespace": namespace, "data": attrs}
[ "def", "startTag", "(", "self", ",", "namespace", ",", "name", ",", "attrs", ")", ":", "return", "{", "\"type\"", ":", "\"StartTag\"", ",", "\"name\"", ":", "name", ",", "\"namespace\"", ":", "namespace", ",", "\"data\"", ":", "attrs", "}" ]
[ 68, 4 ]
[ 83, 30 ]
python
en
['en', 'de', 'en']
True
TreeWalker.endTag
(self, namespace, name)
Generates an EndTag token :arg namespace: the namespace of the token--can be ``None`` :arg name: the name of the element :returns: EndTag token
Generates an EndTag token
def endTag(self, namespace, name): """Generates an EndTag token :arg namespace: the namespace of the token--can be ``None`` :arg name: the name of the element :returns: EndTag token """ return {"type": "EndTag", "name": name, "namespace": namespace}
[ "def", "endTag", "(", "self", ",", "namespace", ",", "name", ")", ":", "return", "{", "\"type\"", ":", "\"EndTag\"", ",", "\"name\"", ":", "name", ",", "\"namespace\"", ":", "namespace", "}" ]
[ 85, 4 ]
[ 97, 39 ]
python
en
['en', 'en', 'nl']
True
TreeWalker.text
(self, data)
Generates SpaceCharacters and Characters tokens Depending on what's in the data, this generates one or more ``SpaceCharacters`` and ``Characters`` tokens. For example: >>> from html5lib.treewalkers.base import TreeWalker >>> # Give it an empty tree just so it instantiates >>> walker = TreeWalker([]) >>> list(walker.text('')) [] >>> list(walker.text(' ')) [{u'data': ' ', u'type': u'SpaceCharacters'}] >>> list(walker.text(' abc ')) # doctest: +NORMALIZE_WHITESPACE [{u'data': ' ', u'type': u'SpaceCharacters'}, {u'data': u'abc', u'type': u'Characters'}, {u'data': u' ', u'type': u'SpaceCharacters'}] :arg data: the text data :returns: one or more ``SpaceCharacters`` and ``Characters`` tokens
Generates SpaceCharacters and Characters tokens
def text(self, data): """Generates SpaceCharacters and Characters tokens Depending on what's in the data, this generates one or more ``SpaceCharacters`` and ``Characters`` tokens. For example: >>> from html5lib.treewalkers.base import TreeWalker >>> # Give it an empty tree just so it instantiates >>> walker = TreeWalker([]) >>> list(walker.text('')) [] >>> list(walker.text(' ')) [{u'data': ' ', u'type': u'SpaceCharacters'}] >>> list(walker.text(' abc ')) # doctest: +NORMALIZE_WHITESPACE [{u'data': ' ', u'type': u'SpaceCharacters'}, {u'data': u'abc', u'type': u'Characters'}, {u'data': u' ', u'type': u'SpaceCharacters'}] :arg data: the text data :returns: one or more ``SpaceCharacters`` and ``Characters`` tokens """ data = data middle = data.lstrip(spaceCharacters) left = data[:len(data) - len(middle)] if left: yield {"type": "SpaceCharacters", "data": left} data = middle middle = data.rstrip(spaceCharacters) right = data[len(middle):] if middle: yield {"type": "Characters", "data": middle} if right: yield {"type": "SpaceCharacters", "data": right}
[ "def", "text", "(", "self", ",", "data", ")", ":", "data", "=", "data", "middle", "=", "data", ".", "lstrip", "(", "spaceCharacters", ")", "left", "=", "data", "[", ":", "len", "(", "data", ")", "-", "len", "(", "middle", ")", "]", "if", "left", ":", "yield", "{", "\"type\"", ":", "\"SpaceCharacters\"", ",", "\"data\"", ":", "left", "}", "data", "=", "middle", "middle", "=", "data", ".", "rstrip", "(", "spaceCharacters", ")", "right", "=", "data", "[", "len", "(", "middle", ")", ":", "]", "if", "middle", ":", "yield", "{", "\"type\"", ":", "\"Characters\"", ",", "\"data\"", ":", "middle", "}", "if", "right", ":", "yield", "{", "\"type\"", ":", "\"SpaceCharacters\"", ",", "\"data\"", ":", "right", "}" ]
[ 99, 4 ]
[ 135, 60 ]
python
en
['en', 'en', 'en']
True
TreeWalker.comment
(self, data)
Generates a Comment token :arg data: the comment :returns: Comment token
Generates a Comment token
def comment(self, data): """Generates a Comment token :arg data: the comment :returns: Comment token """ return {"type": "Comment", "data": data}
[ "def", "comment", "(", "self", ",", "data", ")", ":", "return", "{", "\"type\"", ":", "\"Comment\"", ",", "\"data\"", ":", "data", "}" ]
[ 137, 4 ]
[ 145, 48 ]
python
en
['en', 'en', 'en']
True
TreeWalker.doctype
(self, name, publicId=None, systemId=None)
Generates a Doctype token :arg name: :arg publicId: :arg systemId: :returns: the Doctype token
Generates a Doctype token
def doctype(self, name, publicId=None, systemId=None): """Generates a Doctype token :arg name: :arg publicId: :arg systemId: :returns: the Doctype token """ return {"type": "Doctype", "name": name, "publicId": publicId, "systemId": systemId}
[ "def", "doctype", "(", "self", ",", "name", ",", "publicId", "=", "None", ",", "systemId", "=", "None", ")", ":", "return", "{", "\"type\"", ":", "\"Doctype\"", ",", "\"name\"", ":", "name", ",", "\"publicId\"", ":", "publicId", ",", "\"systemId\"", ":", "systemId", "}" ]
[ 147, 4 ]
[ 162, 37 ]
python
en
['en', 'en', 'en']
True
TreeWalker.entity
(self, name)
Generates an Entity token :arg name: the entity name :returns: an Entity token
Generates an Entity token
def entity(self, name): """Generates an Entity token :arg name: the entity name :returns: an Entity token """ return {"type": "Entity", "name": name}
[ "def", "entity", "(", "self", ",", "name", ")", ":", "return", "{", "\"type\"", ":", "\"Entity\"", ",", "\"name\"", ":", "name", "}" ]
[ 164, 4 ]
[ 172, 47 ]
python
en
['en', 'en', 'nl']
True
TreeWalker.unknown
(self, nodeType)
Handles unknown node types
Handles unknown node types
def unknown(self, nodeType): """Handles unknown node types""" return self.error("Unknown node type: " + nodeType)
[ "def", "unknown", "(", "self", ",", "nodeType", ")", ":", "return", "self", ".", "error", "(", "\"Unknown node type: \"", "+", "nodeType", ")" ]
[ 174, 4 ]
[ 176, 59 ]
python
en
['en', 'de', 'en']
True
InvalidRod.__init__
(self, rod)
:param object rod: The :class:`Rod` which is invalid.
def __init__(self, rod): """ :param object rod: The :class:`Rod` which is invalid. """ super(InvalidRod, self).__init__( 'invalid rod: {rod}'.format(rod=rod)) self.rod = rod
[ "def", "__init__", "(", "self", ",", "rod", ")", ":", "super", "(", "InvalidRod", ",", "self", ")", ".", "__init__", "(", "'invalid rod: {rod}'", ".", "format", "(", "rod", "=", "rod", ")", ")", "self", ".", "rod", "=", "rod" ]
[ 30, 4 ]
[ 38, 22 ]
python
en
['en', 'error', 'th']
False
InvalidRods.__init__
(self, rods)
:param object rods: The :class:`Rods` which are invalid
:param object rods: The :class:`Rods` which are invalid
def __init__(self, rods): """ :param object rods: The :class:`Rods` which are invalid """ super(InvalidRods, self).__init__( 'invalid rod: {rods}'.format( rods=rods)) self.rods = rods
[ "def", "__init__", "(", "self", ",", "rods", ")", ":", "super", "(", "InvalidRods", ",", "self", ")", ".", "__init__", "(", "'invalid rod: {rods}'", ".", "format", "(", "rods", "=", "rods", ")", ")", "self", ".", "rods", "=", "rods" ]
[ 42, 4 ]
[ 50, 24 ]
python
en
['en', 'error', 'th']
False
InvalidRodHeight.__init__
(self, rod, max_height)
:param Rod rod: The :class:`Rod` which has an invalid height. :param int max_height: The max allowed height of the :class:`Rod`.
:param Rod rod: The :class:`Rod` which has an invalid height. :param int max_height: The max allowed height of the :class:`Rod`.
def __init__(self, rod, max_height): """ :param Rod rod: The :class:`Rod` which has an invalid height. :param int max_height: The max allowed height of the :class:`Rod`. """ super(InvalidRodHeight, self).__init__( 'invalid rod height: {rod} expecting: {height}.'.format( rod=rod, height=max_height)) self.rod = rod self.height = max_height
[ "def", "__init__", "(", "self", ",", "rod", ",", "max_height", ")", ":", "super", "(", "InvalidRodHeight", ",", "self", ")", ".", "__init__", "(", "'invalid rod height: {rod} expecting: {height}.'", ".", "format", "(", "rod", "=", "rod", ",", "height", "=", "max_height", ")", ")", "self", ".", "rod", "=", "rod", "self", ".", "height", "=", "max_height" ]
[ 54, 4 ]
[ 65, 32 ]
python
en
['en', 'error', 'th']
False
DuplicateDisk.__init__
(self, rod, disk_width)
:param Rod rod: The duplicate :class:`Rod`. :param int disk_width: The width of the :class:`Disk`.
:param Rod rod: The duplicate :class:`Rod`. :param int disk_width: The width of the :class:`Disk`.
def __init__(self, rod, disk_width): """ :param Rod rod: The duplicate :class:`Rod`. :param int disk_width: The width of the :class:`Disk`. """ super(DuplicateDisk, self).__init__( 'Duplicate disk width found: {disk_width} in: {rod}'.format( disk_width=disk_width, rod=rod)) self.rod = rod self.disk_width = disk_width
[ "def", "__init__", "(", "self", ",", "rod", ",", "disk_width", ")", ":", "super", "(", "DuplicateDisk", ",", "self", ")", ".", "__init__", "(", "'Duplicate disk width found: {disk_width} in: {rod}'", ".", "format", "(", "disk_width", "=", "disk_width", ",", "rod", "=", "rod", ")", ")", "self", ".", "rod", "=", "rod", "self", ".", "disk_width", "=", "disk_width" ]
[ 73, 4 ]
[ 84, 36 ]
python
en
['en', 'error', 'th']
False
CorruptRod.__init__
(self, rod, disk)
:param Rod rod: The :class:`Rod` which is corrupt. :param int disk: A :class:`Disk` which sits directly atop a smaller :class:`Disk`.
:param Rod rod: The :class:`Rod` which is corrupt. :param int disk: A :class:`Disk` which sits directly atop a smaller :class:`Disk`.
def __init__(self, rod, disk): """ :param Rod rod: The :class:`Rod` which is corrupt. :param int disk: A :class:`Disk` which sits directly atop a smaller :class:`Disk`. """ super(CorruptRod, self).__init__( 'Corrupt rod, at least one disk is larger than the one below it: {rod}'.format( rod=rod)) self.rod = rod self.disk = disk
[ "def", "__init__", "(", "self", ",", "rod", ",", "disk", ")", ":", "super", "(", "CorruptRod", ",", "self", ")", ".", "__init__", "(", "'Corrupt rod, at least one disk is larger than the one below it: {rod}'", ".", "format", "(", "rod", "=", "rod", ")", ")", "self", ".", "rod", "=", "rod", "self", ".", "disk", "=", "disk" ]
[ 92, 4 ]
[ 103, 24 ]
python
en
['en', 'error', 'th']
False
InvalidStartingConditions.__init__
(self, rods, moves)
:param Rod rods: The :class:`Rod`'s. :param int moves: Total number of moves already made (should be zero).
:param Rod rods: The :class:`Rod`'s. :param int moves: Total number of moves already made (should be zero).
def __init__(self, rods, moves): """ :param Rod rods: The :class:`Rod`'s. :param int moves: Total number of moves already made (should be zero). """ super(InvalidStartingConditions, self).__init__( 'Invalid starting condition for rods: {rods}, with existing moves: {moves}'.format( rods=rods, moves=moves)) self.rods = rods self.moves = moves
[ "def", "__init__", "(", "self", ",", "rods", ",", "moves", ")", ":", "super", "(", "InvalidStartingConditions", ",", "self", ")", ".", "__init__", "(", "'Invalid starting condition for rods: {rods}, with existing moves: {moves}'", ".", "format", "(", "rods", "=", "rods", ",", "moves", "=", "moves", ")", ")", "self", ".", "rods", "=", "rods", "self", ".", "moves", "=", "moves" ]
[ 111, 4 ]
[ 122, 26 ]
python
en
['en', 'error', 'th']
False
InvalidEndingConditions.__init__
(self, rods)
:param Rod rods: The :class:`Rod`'s.
:param Rod rods: The :class:`Rod`'s.
def __init__(self, rods): """ :param Rod rods: The :class:`Rod`'s. """ super(InvalidEndingConditions, self).__init__( 'Invalid ending condition for rods: {rods}'.format( rods=rods)) self.rods = rods
[ "def", "__init__", "(", "self", ",", "rods", ")", ":", "super", "(", "InvalidEndingConditions", ",", "self", ")", ".", "__init__", "(", "'Invalid ending condition for rods: {rods}'", ".", "format", "(", "rods", "=", "rods", ")", ")", "self", ".", "rods", "=", "rods" ]
[ 130, 4 ]
[ 138, 24 ]
python
en
['en', 'error', 'th']
False
InvalidTowerHeight.__init__
(self, height)
:param int height: The invalid height.
:param int height: The invalid height.
def __init__(self, height): """ :param int height: The invalid height. """ super(InvalidTowerHeight, self).__init__( 'Invalid tower height: {height}'.format( height=height)) self.height = height
[ "def", "__init__", "(", "self", ",", "height", ")", ":", "super", "(", "InvalidTowerHeight", ",", "self", ")", ".", "__init__", "(", "'Invalid tower height: {height}'", ".", "format", "(", "height", "=", "height", ")", ")", "self", ".", "height", "=", "height" ]
[ 146, 4 ]
[ 154, 28 ]
python
en
['en', 'error', 'th']
False
InvalidDiskPosition.__init__
(self, position, height)
:param int position: The invalid position on the :class:`Rod`. :param int height: The height.
:param int position: The invalid position on the :class:`Rod`. :param int height: The height.
def __init__(self, position, height): """ :param int position: The invalid position on the :class:`Rod`. :param int height: The height. """ super(InvalidDiskPosition, self).__init__( 'Invalid disk position: {position} on Rod of height: {height}'.format( position=position, height=height)) self.position = position self.height = height
[ "def", "__init__", "(", "self", ",", "position", ",", "height", ")", ":", "super", "(", "InvalidDiskPosition", ",", "self", ")", ".", "__init__", "(", "'Invalid disk position: {position} on Rod of height: {height}'", ".", "format", "(", "position", "=", "position", ",", "height", "=", "height", ")", ")", "self", ".", "position", "=", "position", "self", ".", "height", "=", "height" ]
[ 162, 4 ]
[ 173, 28 ]
python
en
['en', 'error', 'th']
False
InvalidMoves.__init__
(self, moves)
:param int moves: The invalid `moves`.
:param int moves: The invalid `moves`.
def __init__(self, moves): """ :param int moves: The invalid `moves`. """ super(InvalidMoves, self).__init__( 'Invalid moves: {moves}'.format( moves=moves)) self.moves = moves
[ "def", "__init__", "(", "self", ",", "moves", ")", ":", "super", "(", "InvalidMoves", ",", "self", ")", ".", "__init__", "(", "'Invalid moves: {moves}'", ".", "format", "(", "moves", "=", "moves", ")", ")", "self", ".", "moves", "=", "moves" ]
[ 181, 4 ]
[ 189, 26 ]
python
en
['en', 'error', 'th']
False
RatingPredictionEvaluation.__init__
(self, sep='\t', metrics=list(['MAE', 'RMSE']), all_but_one_eval=False, verbose=True, as_table=False, table_sep='\t', as_rank=False, n_rank=(5, 10))
Class to evaluate predictions in a rating prediction scenario :param sep: Delimiter for input files :type sep: str, default '\t' :param metrics: List of evaluation metrics :type metrics: list, default ('MAE', 'RMSE') :param all_but_one_eval: If True, considers only one pair (u, i) from the test set to evaluate the ranking :type all_but_one_eval: bool, default False :param verbose: Print the evaluation results :type verbose: bool, default True :param as_table: Print the evaluation results as table (only work with verbose=True) :type as_table: bool, default False :param table_sep: Delimiter for print results (only work with verbose=True and as_table=True) :type table_sep: str, default '\t' :param as_rank: If True, evaluate as rank. :type as_rank: bool, default False
Class to evaluate predictions in a rating prediction scenario
def __init__(self, sep='\t', metrics=list(['MAE', 'RMSE']), all_but_one_eval=False, verbose=True, as_table=False, table_sep='\t', as_rank=False, n_rank=(5, 10)): """ Class to evaluate predictions in a rating prediction scenario :param sep: Delimiter for input files :type sep: str, default '\t' :param metrics: List of evaluation metrics :type metrics: list, default ('MAE', 'RMSE') :param all_but_one_eval: If True, considers only one pair (u, i) from the test set to evaluate the ranking :type all_but_one_eval: bool, default False :param verbose: Print the evaluation results :type verbose: bool, default True :param as_table: Print the evaluation results as table (only work with verbose=True) :type as_table: bool, default False :param table_sep: Delimiter for print results (only work with verbose=True and as_table=True) :type table_sep: str, default '\t' :param as_rank: If True, evaluate as rank. :type as_rank: bool, default False """ super(RatingPredictionEvaluation, self).__init__(sep=sep, metrics=metrics, all_but_one_eval=all_but_one_eval, verbose=verbose, as_table=as_table, table_sep=table_sep) self.as_rank = as_rank self.n_rank = n_rank
[ "def", "__init__", "(", "self", ",", "sep", "=", "'\\t'", ",", "metrics", "=", "list", "(", "[", "'MAE'", ",", "'RMSE'", "]", ")", ",", "all_but_one_eval", "=", "False", ",", "verbose", "=", "True", ",", "as_table", "=", "False", ",", "table_sep", "=", "'\\t'", ",", "as_rank", "=", "False", ",", "n_rank", "=", "(", "5", ",", "10", ")", ")", ":", "super", "(", "RatingPredictionEvaluation", ",", "self", ")", ".", "__init__", "(", "sep", "=", "sep", ",", "metrics", "=", "metrics", ",", "all_but_one_eval", "=", "all_but_one_eval", ",", "verbose", "=", "verbose", ",", "as_table", "=", "as_table", ",", "table_sep", "=", "table_sep", ")", "self", ".", "as_rank", "=", "as_rank", "self", ".", "n_rank", "=", "n_rank" ]
[ 25, 4 ]
[ 56, 28 ]
python
en
['en', 'error', 'th']
False
RatingPredictionEvaluation.evaluate
(self, predictions, test_set)
Method to calculate all the metrics for item recommendation scenario using dictionaries of ranking and test set. Use read() in ReadFile to transform your prediction and test files in a dict :param predictions: Dict of predictions :type predictions: dict :param test_set: Dictionary with test set information. :type test_set: dict :return: Dictionary with all evaluation metrics and results :rtype: dict
Method to calculate all the metrics for item recommendation scenario using dictionaries of ranking and test set. Use read() in ReadFile to transform your prediction and test files in a dict
def evaluate(self, predictions, test_set): """ Method to calculate all the metrics for item recommendation scenario using dictionaries of ranking and test set. Use read() in ReadFile to transform your prediction and test files in a dict :param predictions: Dict of predictions :type predictions: dict :param test_set: Dictionary with test set information. :type test_set: dict :return: Dictionary with all evaluation metrics and results :rtype: dict """ eval_results = {} predictions_list = [] test_list = [] if not self.as_rank: # Create All but one set, selecting only one sample from the test set for each user if self.all_but_one_eval: for user in test_set['users']: # select a random item item = random.choice(test_set['feedback'][user]) test_set['feedback'][user] = {item: test_set['feedback'][user][item]} for user in predictions: for item in predictions[user]: rui_predict = predictions[user][item] rui_test = test_set["feedback"].get(user, {}).get(item, np.nan) if not np.isnan(rui_test): predictions_list.append(rui_predict) test_list.append(float(rui_test)) eval_results.update({ 'MAE': round(mean_absolute_error(test_list, predictions_list), 6), 'RMSE': round(np.sqrt(mean_squared_error(test_list, predictions_list)), 6) }) if self.verbose: self.print_results(eval_results) else: new_predict_set = [] new_test_set = {} for user in predictions: partial_predictions = [] for item in predictions[user]: if predictions[user][item] > 3: partial_predictions.append([user, item, predictions[user][item]]) if test_set["feedback"].get(user, {}).get(item, 0) > 3: new_test_set.setdefault(user, []).append(item) partial_predictions = sorted(partial_predictions, key=lambda x: -x[2]) new_predict_set += partial_predictions new_test_set['items_seen_by_user'] = new_test_set new_test_set['users'] = test_set['users'] ItemRecommendationEvaluation(n_ranks=self.n_rank, all_but_one_eval=self.all_but_one_eval).evaluate_recommender( new_predict_set, new_test_set) return eval_results
[ "def", "evaluate", "(", "self", ",", "predictions", ",", "test_set", ")", ":", "eval_results", "=", "{", "}", "predictions_list", "=", "[", "]", "test_list", "=", "[", "]", "if", "not", "self", ".", "as_rank", ":", "# Create All but one set, selecting only one sample from the test set for each user", "if", "self", ".", "all_but_one_eval", ":", "for", "user", "in", "test_set", "[", "'users'", "]", ":", "# select a random item", "item", "=", "random", ".", "choice", "(", "test_set", "[", "'feedback'", "]", "[", "user", "]", ")", "test_set", "[", "'feedback'", "]", "[", "user", "]", "=", "{", "item", ":", "test_set", "[", "'feedback'", "]", "[", "user", "]", "[", "item", "]", "}", "for", "user", "in", "predictions", ":", "for", "item", "in", "predictions", "[", "user", "]", ":", "rui_predict", "=", "predictions", "[", "user", "]", "[", "item", "]", "rui_test", "=", "test_set", "[", "\"feedback\"", "]", ".", "get", "(", "user", ",", "{", "}", ")", ".", "get", "(", "item", ",", "np", ".", "nan", ")", "if", "not", "np", ".", "isnan", "(", "rui_test", ")", ":", "predictions_list", ".", "append", "(", "rui_predict", ")", "test_list", ".", "append", "(", "float", "(", "rui_test", ")", ")", "eval_results", ".", "update", "(", "{", "'MAE'", ":", "round", "(", "mean_absolute_error", "(", "test_list", ",", "predictions_list", ")", ",", "6", ")", ",", "'RMSE'", ":", "round", "(", "np", ".", "sqrt", "(", "mean_squared_error", "(", "test_list", ",", "predictions_list", ")", ")", ",", "6", ")", "}", ")", "if", "self", ".", "verbose", ":", "self", ".", "print_results", "(", "eval_results", ")", "else", ":", "new_predict_set", "=", "[", "]", "new_test_set", "=", "{", "}", "for", "user", "in", "predictions", ":", "partial_predictions", "=", "[", "]", "for", "item", "in", "predictions", "[", "user", "]", ":", "if", "predictions", "[", "user", "]", "[", "item", "]", ">", "3", ":", "partial_predictions", ".", "append", "(", "[", "user", ",", "item", ",", "predictions", "[", "user", "]", "[", "item", "]", "]", ")", "if", "test_set", "[", "\"feedback\"", "]", ".", "get", "(", "user", ",", "{", "}", ")", ".", "get", "(", "item", ",", "0", ")", ">", "3", ":", "new_test_set", ".", "setdefault", "(", "user", ",", "[", "]", ")", ".", "append", "(", "item", ")", "partial_predictions", "=", "sorted", "(", "partial_predictions", ",", "key", "=", "lambda", "x", ":", "-", "x", "[", "2", "]", ")", "new_predict_set", "+=", "partial_predictions", "new_test_set", "[", "'items_seen_by_user'", "]", "=", "new_test_set", "new_test_set", "[", "'users'", "]", "=", "test_set", "[", "'users'", "]", "ItemRecommendationEvaluation", "(", "n_ranks", "=", "self", ".", "n_rank", ",", "all_but_one_eval", "=", "self", ".", "all_but_one_eval", ")", ".", "evaluate_recommender", "(", "new_predict_set", ",", "new_test_set", ")", "return", "eval_results" ]
[ 58, 4 ]
[ 126, 27 ]
python
en
['en', 'error', 'th']
False
default_filter
(src, dst)
The default progress/filter callback; returns True for all files
The default progress/filter callback; returns True for all files
def default_filter(src, dst): """The default progress/filter callback; returns True for all files""" return dst
[ "def", "default_filter", "(", "src", ",", "dst", ")", ":", "return", "dst" ]
[ 22, 0 ]
[ 24, 14 ]
python
en
['en', 'sv', 'en']
True
unpack_archive
(filename, extract_dir, progress_filter=default_filter, drivers=None)
Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat`` `progress_filter` is a function taking two arguments: a source path internal to the archive ('/'-separated), and a filesystem path where it will be extracted. The callback must return the desired extract path (which may be the same as the one passed in), or else ``None`` to skip that file or directory. The callback can thus be used to report on the progress of the extraction, as well as to filter the items extracted or alter their extraction paths. `drivers`, if supplied, must be a non-empty sequence of functions with the same signature as this function (minus the `drivers` argument), that raise ``UnrecognizedFormat`` if they do not support extracting the designated archive type. The `drivers` are tried in sequence until one is found that does not raise an error, or until all are exhausted (in which case ``UnrecognizedFormat`` is raised). If you do not supply a sequence of drivers, the module's ``extraction_drivers`` constant will be used, which means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that order.
Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
def unpack_archive(filename, extract_dir, progress_filter=default_filter, drivers=None): """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat`` `progress_filter` is a function taking two arguments: a source path internal to the archive ('/'-separated), and a filesystem path where it will be extracted. The callback must return the desired extract path (which may be the same as the one passed in), or else ``None`` to skip that file or directory. The callback can thus be used to report on the progress of the extraction, as well as to filter the items extracted or alter their extraction paths. `drivers`, if supplied, must be a non-empty sequence of functions with the same signature as this function (minus the `drivers` argument), that raise ``UnrecognizedFormat`` if they do not support extracting the designated archive type. The `drivers` are tried in sequence until one is found that does not raise an error, or until all are exhausted (in which case ``UnrecognizedFormat`` is raised). If you do not supply a sequence of drivers, the module's ``extraction_drivers`` constant will be used, which means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that order. """ for driver in drivers or extraction_drivers: try: driver(filename, extract_dir, progress_filter) except UnrecognizedFormat: continue else: return else: raise UnrecognizedFormat( "Not a recognized archive type: %s" % filename )
[ "def", "unpack_archive", "(", "filename", ",", "extract_dir", ",", "progress_filter", "=", "default_filter", ",", "drivers", "=", "None", ")", ":", "for", "driver", "in", "drivers", "or", "extraction_drivers", ":", "try", ":", "driver", "(", "filename", ",", "extract_dir", ",", "progress_filter", ")", "except", "UnrecognizedFormat", ":", "continue", "else", ":", "return", "else", ":", "raise", "UnrecognizedFormat", "(", "\"Not a recognized archive type: %s\"", "%", "filename", ")" ]
[ 27, 0 ]
[ 59, 9 ]
python
en
['en', 'la', 'en']
True
unpack_directory
(filename, extract_dir, progress_filter=default_filter)
Unpack" a directory, using the same interface as for archives Raises ``UnrecognizedFormat`` if `filename` is not a directory
Unpack" a directory, using the same interface as for archives
def unpack_directory(filename, extract_dir, progress_filter=default_filter): """"Unpack" a directory, using the same interface as for archives Raises ``UnrecognizedFormat`` if `filename` is not a directory """ if not os.path.isdir(filename): raise UnrecognizedFormat("%s is not a directory" % filename) paths = { filename: ('', extract_dir), } for base, dirs, files in os.walk(filename): src, dst = paths[base] for d in dirs: paths[os.path.join(base, d)] = src + d + '/', os.path.join(dst, d) for f in files: target = os.path.join(dst, f) target = progress_filter(src + f, target) if not target: # skip non-files continue ensure_directory(target) f = os.path.join(base, f) shutil.copyfile(f, target) shutil.copystat(f, target)
[ "def", "unpack_directory", "(", "filename", ",", "extract_dir", ",", "progress_filter", "=", "default_filter", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "filename", ")", ":", "raise", "UnrecognizedFormat", "(", "\"%s is not a directory\"", "%", "filename", ")", "paths", "=", "{", "filename", ":", "(", "''", ",", "extract_dir", ")", ",", "}", "for", "base", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "filename", ")", ":", "src", ",", "dst", "=", "paths", "[", "base", "]", "for", "d", "in", "dirs", ":", "paths", "[", "os", ".", "path", ".", "join", "(", "base", ",", "d", ")", "]", "=", "src", "+", "d", "+", "'/'", ",", "os", ".", "path", ".", "join", "(", "dst", ",", "d", ")", "for", "f", "in", "files", ":", "target", "=", "os", ".", "path", ".", "join", "(", "dst", ",", "f", ")", "target", "=", "progress_filter", "(", "src", "+", "f", ",", "target", ")", "if", "not", "target", ":", "# skip non-files", "continue", "ensure_directory", "(", "target", ")", "f", "=", "os", ".", "path", ".", "join", "(", "base", ",", "f", ")", "shutil", ".", "copyfile", "(", "f", ",", "target", ")", "shutil", ".", "copystat", "(", "f", ",", "target", ")" ]
[ 62, 0 ]
[ 86, 38 ]
python
en
['en', 'en', 'en']
True
unpack_zipfile
(filename, extract_dir, progress_filter=default_filter)
Unpack zip `filename` to `extract_dir` Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined by ``zipfile.is_zipfile()``). See ``unpack_archive()`` for an explanation of the `progress_filter` argument.
Unpack zip `filename` to `extract_dir`
def unpack_zipfile(filename, extract_dir, progress_filter=default_filter): """Unpack zip `filename` to `extract_dir` Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined by ``zipfile.is_zipfile()``). See ``unpack_archive()`` for an explanation of the `progress_filter` argument. """ if not zipfile.is_zipfile(filename): raise UnrecognizedFormat("%s is not a zip file" % (filename,)) with zipfile.ZipFile(filename) as z: for info in z.infolist(): name = info.filename # don't extract absolute paths or ones with .. in them if name.startswith('/') or '..' in name.split('/'): continue target = os.path.join(extract_dir, *name.split('/')) target = progress_filter(name, target) if not target: continue if name.endswith('/'): # directory ensure_directory(target) else: # file ensure_directory(target) data = z.read(info.filename) with open(target, 'wb') as f: f.write(data) unix_attributes = info.external_attr >> 16 if unix_attributes: os.chmod(target, unix_attributes)
[ "def", "unpack_zipfile", "(", "filename", ",", "extract_dir", ",", "progress_filter", "=", "default_filter", ")", ":", "if", "not", "zipfile", ".", "is_zipfile", "(", "filename", ")", ":", "raise", "UnrecognizedFormat", "(", "\"%s is not a zip file\"", "%", "(", "filename", ",", ")", ")", "with", "zipfile", ".", "ZipFile", "(", "filename", ")", "as", "z", ":", "for", "info", "in", "z", ".", "infolist", "(", ")", ":", "name", "=", "info", ".", "filename", "# don't extract absolute paths or ones with .. in them", "if", "name", ".", "startswith", "(", "'/'", ")", "or", "'..'", "in", "name", ".", "split", "(", "'/'", ")", ":", "continue", "target", "=", "os", ".", "path", ".", "join", "(", "extract_dir", ",", "*", "name", ".", "split", "(", "'/'", ")", ")", "target", "=", "progress_filter", "(", "name", ",", "target", ")", "if", "not", "target", ":", "continue", "if", "name", ".", "endswith", "(", "'/'", ")", ":", "# directory", "ensure_directory", "(", "target", ")", "else", ":", "# file", "ensure_directory", "(", "target", ")", "data", "=", "z", ".", "read", "(", "info", ".", "filename", ")", "with", "open", "(", "target", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "data", ")", "unix_attributes", "=", "info", ".", "external_attr", ">>", "16", "if", "unix_attributes", ":", "os", ".", "chmod", "(", "target", ",", "unix_attributes", ")" ]
[ 89, 0 ]
[ 123, 49 ]
python
en
['en', 'nl', 'ur']
False
unpack_tarfile
(filename, extract_dir, progress_filter=default_filter)
Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined by ``tarfile.open()``). See ``unpack_archive()`` for an explanation of the `progress_filter` argument.
Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
def unpack_tarfile(filename, extract_dir, progress_filter=default_filter): """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined by ``tarfile.open()``). See ``unpack_archive()`` for an explanation of the `progress_filter` argument. """ try: tarobj = tarfile.open(filename) except tarfile.TarError: raise UnrecognizedFormat( "%s is not a compressed or uncompressed tar file" % (filename,) ) with contextlib.closing(tarobj): # don't do any chowning! tarobj.chown = lambda *args: None for member in tarobj: name = member.name # don't extract absolute paths or ones with .. in them if not name.startswith('/') and '..' not in name.split('/'): prelim_dst = os.path.join(extract_dir, *name.split('/')) # resolve any links and to extract the link targets as normal # files while member is not None and (member.islnk() or member.issym()): linkpath = member.linkname if member.issym(): base = posixpath.dirname(member.name) linkpath = posixpath.join(base, linkpath) linkpath = posixpath.normpath(linkpath) member = tarobj._getmember(linkpath) if member is not None and (member.isfile() or member.isdir()): final_dst = progress_filter(name, prelim_dst) if final_dst: if final_dst.endswith(os.sep): final_dst = final_dst[:-1] try: # XXX Ugh tarobj._extract_member(member, final_dst) except tarfile.ExtractError: # chown/chmod/mkfifo/mknode/makedev failed pass return True
[ "def", "unpack_tarfile", "(", "filename", ",", "extract_dir", ",", "progress_filter", "=", "default_filter", ")", ":", "try", ":", "tarobj", "=", "tarfile", ".", "open", "(", "filename", ")", "except", "tarfile", ".", "TarError", ":", "raise", "UnrecognizedFormat", "(", "\"%s is not a compressed or uncompressed tar file\"", "%", "(", "filename", ",", ")", ")", "with", "contextlib", ".", "closing", "(", "tarobj", ")", ":", "# don't do any chowning!", "tarobj", ".", "chown", "=", "lambda", "*", "args", ":", "None", "for", "member", "in", "tarobj", ":", "name", "=", "member", ".", "name", "# don't extract absolute paths or ones with .. in them", "if", "not", "name", ".", "startswith", "(", "'/'", ")", "and", "'..'", "not", "in", "name", ".", "split", "(", "'/'", ")", ":", "prelim_dst", "=", "os", ".", "path", ".", "join", "(", "extract_dir", ",", "*", "name", ".", "split", "(", "'/'", ")", ")", "# resolve any links and to extract the link targets as normal", "# files", "while", "member", "is", "not", "None", "and", "(", "member", ".", "islnk", "(", ")", "or", "member", ".", "issym", "(", ")", ")", ":", "linkpath", "=", "member", ".", "linkname", "if", "member", ".", "issym", "(", ")", ":", "base", "=", "posixpath", ".", "dirname", "(", "member", ".", "name", ")", "linkpath", "=", "posixpath", ".", "join", "(", "base", ",", "linkpath", ")", "linkpath", "=", "posixpath", ".", "normpath", "(", "linkpath", ")", "member", "=", "tarobj", ".", "_getmember", "(", "linkpath", ")", "if", "member", "is", "not", "None", "and", "(", "member", ".", "isfile", "(", ")", "or", "member", ".", "isdir", "(", ")", ")", ":", "final_dst", "=", "progress_filter", "(", "name", ",", "prelim_dst", ")", "if", "final_dst", ":", "if", "final_dst", ".", "endswith", "(", "os", ".", "sep", ")", ":", "final_dst", "=", "final_dst", "[", ":", "-", "1", "]", "try", ":", "# XXX Ugh", "tarobj", ".", "_extract_member", "(", "member", ",", "final_dst", ")", "except", "tarfile", ".", "ExtractError", ":", "# chown/chmod/mkfifo/mknode/makedev failed", "pass", "return", "True" ]
[ 126, 0 ]
[ 169, 19 ]
python
en
['en', 'id', 'hi']
False
CacheControlAdapter.send
(self, request, cacheable_methods=None, **kw)
Send a request. Use the request information to see if it exists in the cache and cache the response if we need to and can.
Send a request. Use the request information to see if it exists in the cache and cache the response if we need to and can.
def send(self, request, cacheable_methods=None, **kw): """ Send a request. Use the request information to see if it exists in the cache and cache the response if we need to and can. """ cacheable = cacheable_methods or self.cacheable_methods if request.method in cacheable: try: cached_response = self.controller.cached_request(request) except zlib.error: cached_response = None if cached_response: return self.build_response(request, cached_response, from_cache=True) # check for etags and add headers if appropriate request.headers.update(self.controller.conditional_headers(request)) resp = super(CacheControlAdapter, self).send(request, **kw) return resp
[ "def", "send", "(", "self", ",", "request", ",", "cacheable_methods", "=", "None", ",", "*", "*", "kw", ")", ":", "cacheable", "=", "cacheable_methods", "or", "self", ".", "cacheable_methods", "if", "request", ".", "method", "in", "cacheable", ":", "try", ":", "cached_response", "=", "self", ".", "controller", ".", "cached_request", "(", "request", ")", "except", "zlib", ".", "error", ":", "cached_response", "=", "None", "if", "cached_response", ":", "return", "self", ".", "build_response", "(", "request", ",", "cached_response", ",", "from_cache", "=", "True", ")", "# check for etags and add headers if appropriate", "request", ".", "headers", ".", "update", "(", "self", ".", "controller", ".", "conditional_headers", "(", "request", ")", ")", "resp", "=", "super", "(", "CacheControlAdapter", ",", "self", ")", ".", "send", "(", "request", ",", "*", "*", "kw", ")", "return", "resp" ]
[ 35, 4 ]
[ 54, 19 ]
python
en
['en', 'error', 'th']
False
CacheControlAdapter.build_response
( self, request, response, from_cache=False, cacheable_methods=None )
Build a response by making a request or using the cache. This will end up calling send and returning a potentially cached response
Build a response by making a request or using the cache.
def build_response( self, request, response, from_cache=False, cacheable_methods=None ): """ Build a response by making a request or using the cache. This will end up calling send and returning a potentially cached response """ cacheable = cacheable_methods or self.cacheable_methods if not from_cache and request.method in cacheable: # Check for any heuristics that might update headers # before trying to cache. if self.heuristic: response = self.heuristic.apply(response) # apply any expiration heuristics if response.status == 304: # We must have sent an ETag request. This could mean # that we've been expired already or that we simply # have an etag. In either case, we want to try and # update the cache if that is the case. cached_response = self.controller.update_cached_response( request, response ) if cached_response is not response: from_cache = True # We are done with the server response, read a # possible response body (compliant servers will # not return one, but we cannot be 100% sure) and # release the connection back to the pool. response.read(decode_content=False) response.release_conn() response = cached_response # We always cache the 301 responses elif response.status == 301: self.controller.cache_response(request, response) else: # Wrap the response file with a wrapper that will cache the # response when the stream has been consumed. response._fp = CallbackFileWrapper( response._fp, functools.partial( self.controller.cache_response, request, response ), ) if response.chunked: super_update_chunk_length = response._update_chunk_length def _update_chunk_length(self): super_update_chunk_length() if self.chunk_left == 0: self._fp._close() response._update_chunk_length = types.MethodType( _update_chunk_length, response ) resp = super(CacheControlAdapter, self).build_response(request, response) # See if we should invalidate the cache. if request.method in self.invalidating_methods and resp.ok: cache_url = self.controller.cache_url(request.url) self.cache.delete(cache_url) # Give the request a from_cache attr to let people use it resp.from_cache = from_cache return resp
[ "def", "build_response", "(", "self", ",", "request", ",", "response", ",", "from_cache", "=", "False", ",", "cacheable_methods", "=", "None", ")", ":", "cacheable", "=", "cacheable_methods", "or", "self", ".", "cacheable_methods", "if", "not", "from_cache", "and", "request", ".", "method", "in", "cacheable", ":", "# Check for any heuristics that might update headers", "# before trying to cache.", "if", "self", ".", "heuristic", ":", "response", "=", "self", ".", "heuristic", ".", "apply", "(", "response", ")", "# apply any expiration heuristics", "if", "response", ".", "status", "==", "304", ":", "# We must have sent an ETag request. This could mean", "# that we've been expired already or that we simply", "# have an etag. In either case, we want to try and", "# update the cache if that is the case.", "cached_response", "=", "self", ".", "controller", ".", "update_cached_response", "(", "request", ",", "response", ")", "if", "cached_response", "is", "not", "response", ":", "from_cache", "=", "True", "# We are done with the server response, read a", "# possible response body (compliant servers will", "# not return one, but we cannot be 100% sure) and", "# release the connection back to the pool.", "response", ".", "read", "(", "decode_content", "=", "False", ")", "response", ".", "release_conn", "(", ")", "response", "=", "cached_response", "# We always cache the 301 responses", "elif", "response", ".", "status", "==", "301", ":", "self", ".", "controller", ".", "cache_response", "(", "request", ",", "response", ")", "else", ":", "# Wrap the response file with a wrapper that will cache the", "# response when the stream has been consumed.", "response", ".", "_fp", "=", "CallbackFileWrapper", "(", "response", ".", "_fp", ",", "functools", ".", "partial", "(", "self", ".", "controller", ".", "cache_response", ",", "request", ",", "response", ")", ",", ")", "if", "response", ".", "chunked", ":", "super_update_chunk_length", "=", "response", ".", "_update_chunk_length", "def", "_update_chunk_length", "(", "self", ")", ":", "super_update_chunk_length", "(", ")", "if", "self", ".", "chunk_left", "==", "0", ":", "self", ".", "_fp", ".", "_close", "(", ")", "response", ".", "_update_chunk_length", "=", "types", ".", "MethodType", "(", "_update_chunk_length", ",", "response", ")", "resp", "=", "super", "(", "CacheControlAdapter", ",", "self", ")", ".", "build_response", "(", "request", ",", "response", ")", "# See if we should invalidate the cache.", "if", "request", ".", "method", "in", "self", ".", "invalidating_methods", "and", "resp", ".", "ok", ":", "cache_url", "=", "self", ".", "controller", ".", "cache_url", "(", "request", ".", "url", ")", "self", ".", "cache", ".", "delete", "(", "cache_url", ")", "# Give the request a from_cache attr to let people use it", "resp", ".", "from_cache", "=", "from_cache", "return", "resp" ]
[ 56, 4 ]
[ 128, 19 ]
python
en
['en', 'error', 'th']
False
split_first
(s, delims)
.. deprecated:: 1.25 Given a string and an iterable of delimiters, split on the first found delimiter. Return two split parts and the matched delimiter. If not found, then the first part is the full input string. Example:: >>> split_first('foo/bar?baz', '?/=') ('foo', 'bar?baz', '/') >>> split_first('foo/bar?baz', '123') ('foo/bar?baz', '', None) Scales linearly with number of delims. Not ideal for large number of delims.
.. deprecated:: 1.25
def split_first(s, delims): """ .. deprecated:: 1.25 Given a string and an iterable of delimiters, split on the first found delimiter. Return two split parts and the matched delimiter. If not found, then the first part is the full input string. Example:: >>> split_first('foo/bar?baz', '?/=') ('foo', 'bar?baz', '/') >>> split_first('foo/bar?baz', '123') ('foo/bar?baz', '', None) Scales linearly with number of delims. Not ideal for large number of delims. """ min_idx = None min_delim = None for d in delims: idx = s.find(d) if idx < 0: continue if min_idx is None or idx < min_idx: min_idx = idx min_delim = d if min_idx is None or min_idx < 0: return s, "", None return s[:min_idx], s[min_idx + 1 :], min_delim
[ "def", "split_first", "(", "s", ",", "delims", ")", ":", "min_idx", "=", "None", "min_delim", "=", "None", "for", "d", "in", "delims", ":", "idx", "=", "s", ".", "find", "(", "d", ")", "if", "idx", "<", "0", ":", "continue", "if", "min_idx", "is", "None", "or", "idx", "<", "min_idx", ":", "min_idx", "=", "idx", "min_delim", "=", "d", "if", "min_idx", "is", "None", "or", "min_idx", "<", "0", ":", "return", "s", ",", "\"\"", ",", "None", "return", "s", "[", ":", "min_idx", "]", ",", "s", "[", "min_idx", "+", "1", ":", "]", ",", "min_delim" ]
[ 174, 0 ]
[ 206, 51 ]
python
en
['en', 'error', 'th']
False
_encode_invalid_chars
(component, allowed_chars, encoding="utf-8")
Percent-encodes a URI component without reapplying onto an already percent-encoded component.
Percent-encodes a URI component without reapplying onto an already percent-encoded component.
def _encode_invalid_chars(component, allowed_chars, encoding="utf-8"): """Percent-encodes a URI component without reapplying onto an already percent-encoded component. """ if component is None: return component component = six.ensure_text(component) # Normalize existing percent-encoded bytes. # Try to see if the component we're encoding is already percent-encoded # so we can skip all '%' characters but still encode all others. component, percent_encodings = PERCENT_RE.subn( lambda match: match.group(0).upper(), component ) uri_bytes = component.encode("utf-8", "surrogatepass") is_percent_encoded = percent_encodings == uri_bytes.count(b"%") encoded_component = bytearray() for i in range(0, len(uri_bytes)): # Will return a single character bytestring on both Python 2 & 3 byte = uri_bytes[i : i + 1] byte_ord = ord(byte) if (is_percent_encoded and byte == b"%") or ( byte_ord < 128 and byte.decode() in allowed_chars ): encoded_component += byte continue encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper())) return encoded_component.decode(encoding)
[ "def", "_encode_invalid_chars", "(", "component", ",", "allowed_chars", ",", "encoding", "=", "\"utf-8\"", ")", ":", "if", "component", "is", "None", ":", "return", "component", "component", "=", "six", ".", "ensure_text", "(", "component", ")", "# Normalize existing percent-encoded bytes.", "# Try to see if the component we're encoding is already percent-encoded", "# so we can skip all '%' characters but still encode all others.", "component", ",", "percent_encodings", "=", "PERCENT_RE", ".", "subn", "(", "lambda", "match", ":", "match", ".", "group", "(", "0", ")", ".", "upper", "(", ")", ",", "component", ")", "uri_bytes", "=", "component", ".", "encode", "(", "\"utf-8\"", ",", "\"surrogatepass\"", ")", "is_percent_encoded", "=", "percent_encodings", "==", "uri_bytes", ".", "count", "(", "b\"%\"", ")", "encoded_component", "=", "bytearray", "(", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "uri_bytes", ")", ")", ":", "# Will return a single character bytestring on both Python 2 & 3", "byte", "=", "uri_bytes", "[", "i", ":", "i", "+", "1", "]", "byte_ord", "=", "ord", "(", "byte", ")", "if", "(", "is_percent_encoded", "and", "byte", "==", "b\"%\"", ")", "or", "(", "byte_ord", "<", "128", "and", "byte", ".", "decode", "(", ")", "in", "allowed_chars", ")", ":", "encoded_component", "+=", "byte", "continue", "encoded_component", ".", "extend", "(", "b\"%\"", "+", "(", "hex", "(", "byte_ord", ")", "[", "2", ":", "]", ".", "encode", "(", ")", ".", "zfill", "(", "2", ")", ".", "upper", "(", ")", ")", ")", "return", "encoded_component", ".", "decode", "(", "encoding", ")" ]
[ 209, 0 ]
[ 240, 45 ]
python
en
['en', 'en', 'en']
True
_encode_target
(target)
Percent-encodes a request target so that there are no invalid characters
Percent-encodes a request target so that there are no invalid characters
def _encode_target(target): """Percent-encodes a request target so that there are no invalid characters""" path, query = TARGET_RE.match(target).groups() target = _encode_invalid_chars(path, PATH_CHARS) query = _encode_invalid_chars(query, QUERY_CHARS) if query is not None: target += "?" + query return target
[ "def", "_encode_target", "(", "target", ")", ":", "path", ",", "query", "=", "TARGET_RE", ".", "match", "(", "target", ")", ".", "groups", "(", ")", "target", "=", "_encode_invalid_chars", "(", "path", ",", "PATH_CHARS", ")", "query", "=", "_encode_invalid_chars", "(", "query", ",", "QUERY_CHARS", ")", "if", "query", "is", "not", "None", ":", "target", "+=", "\"?\"", "+", "query", "return", "target" ]
[ 319, 0 ]
[ 326, 17 ]
python
en
['en', 'en', 'en']
True
parse_url
(url)
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None. This parser is RFC 3986 compliant. The parser logic and helper functions are based heavily on work done in the ``rfc3986`` module. :param str url: URL to parse into a :class:`.Url` namedtuple. Partly backwards-compatible with :mod:`urlparse`. Example:: >>> parse_url('http://google.com/mail/') Url(scheme='http', host='google.com', port=None, path='/mail/', ...) >>> parse_url('google.com:80') Url(scheme=None, host='google.com', port=80, path=None, ...) >>> parse_url('/foo?bar') Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None. This parser is RFC 3986 compliant.
def parse_url(url): """ Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None. This parser is RFC 3986 compliant. The parser logic and helper functions are based heavily on work done in the ``rfc3986`` module. :param str url: URL to parse into a :class:`.Url` namedtuple. Partly backwards-compatible with :mod:`urlparse`. Example:: >>> parse_url('http://google.com/mail/') Url(scheme='http', host='google.com', port=None, path='/mail/', ...) >>> parse_url('google.com:80') Url(scheme=None, host='google.com', port=80, path=None, ...) >>> parse_url('/foo?bar') Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...) """ if not url: # Empty return Url() source_url = url if not SCHEME_RE.search(url): url = "//" + url try: scheme, authority, path, query, fragment = URI_RE.match(url).groups() normalize_uri = scheme is None or scheme.lower() in NORMALIZABLE_SCHEMES if scheme: scheme = scheme.lower() if authority: auth, _, host_port = authority.rpartition("@") auth = auth or None host, port = _HOST_PORT_RE.match(host_port).groups() if auth and normalize_uri: auth = _encode_invalid_chars(auth, USERINFO_CHARS) if port == "": port = None else: auth, host, port = None, None, None if port is not None: port = int(port) if not (0 <= port <= 65535): raise LocationParseError(url) host = _normalize_host(host, scheme) if normalize_uri and path: path = _remove_path_dot_segments(path) path = _encode_invalid_chars(path, PATH_CHARS) if normalize_uri and query: query = _encode_invalid_chars(query, QUERY_CHARS) if normalize_uri and fragment: fragment = _encode_invalid_chars(fragment, FRAGMENT_CHARS) except (ValueError, AttributeError): return six.raise_from(LocationParseError(source_url), None) # For the sake of backwards compatibility we put empty # string values for path if there are any defined values # beyond the path in the URL. # TODO: Remove this when we break backwards compatibility. if not path: if query is not None or fragment is not None: path = "" else: path = None # Ensure that each part of the URL is a `str` for # backwards compatibility. if isinstance(url, six.text_type): ensure_func = six.ensure_text else: ensure_func = six.ensure_str def ensure_type(x): return x if x is None else ensure_func(x) return Url( scheme=ensure_type(scheme), auth=ensure_type(auth), host=ensure_type(host), port=port, path=ensure_type(path), query=ensure_type(query), fragment=ensure_type(fragment), )
[ "def", "parse_url", "(", "url", ")", ":", "if", "not", "url", ":", "# Empty", "return", "Url", "(", ")", "source_url", "=", "url", "if", "not", "SCHEME_RE", ".", "search", "(", "url", ")", ":", "url", "=", "\"//\"", "+", "url", "try", ":", "scheme", ",", "authority", ",", "path", ",", "query", ",", "fragment", "=", "URI_RE", ".", "match", "(", "url", ")", ".", "groups", "(", ")", "normalize_uri", "=", "scheme", "is", "None", "or", "scheme", ".", "lower", "(", ")", "in", "NORMALIZABLE_SCHEMES", "if", "scheme", ":", "scheme", "=", "scheme", ".", "lower", "(", ")", "if", "authority", ":", "auth", ",", "_", ",", "host_port", "=", "authority", ".", "rpartition", "(", "\"@\"", ")", "auth", "=", "auth", "or", "None", "host", ",", "port", "=", "_HOST_PORT_RE", ".", "match", "(", "host_port", ")", ".", "groups", "(", ")", "if", "auth", "and", "normalize_uri", ":", "auth", "=", "_encode_invalid_chars", "(", "auth", ",", "USERINFO_CHARS", ")", "if", "port", "==", "\"\"", ":", "port", "=", "None", "else", ":", "auth", ",", "host", ",", "port", "=", "None", ",", "None", ",", "None", "if", "port", "is", "not", "None", ":", "port", "=", "int", "(", "port", ")", "if", "not", "(", "0", "<=", "port", "<=", "65535", ")", ":", "raise", "LocationParseError", "(", "url", ")", "host", "=", "_normalize_host", "(", "host", ",", "scheme", ")", "if", "normalize_uri", "and", "path", ":", "path", "=", "_remove_path_dot_segments", "(", "path", ")", "path", "=", "_encode_invalid_chars", "(", "path", ",", "PATH_CHARS", ")", "if", "normalize_uri", "and", "query", ":", "query", "=", "_encode_invalid_chars", "(", "query", ",", "QUERY_CHARS", ")", "if", "normalize_uri", "and", "fragment", ":", "fragment", "=", "_encode_invalid_chars", "(", "fragment", ",", "FRAGMENT_CHARS", ")", "except", "(", "ValueError", ",", "AttributeError", ")", ":", "return", "six", ".", "raise_from", "(", "LocationParseError", "(", "source_url", ")", ",", "None", ")", "# For the sake of backwards compatibility we put empty", "# string values for path if there are any defined values", "# beyond the path in the URL.", "# TODO: Remove this when we break backwards compatibility.", "if", "not", "path", ":", "if", "query", "is", "not", "None", "or", "fragment", "is", "not", "None", ":", "path", "=", "\"\"", "else", ":", "path", "=", "None", "# Ensure that each part of the URL is a `str` for", "# backwards compatibility.", "if", "isinstance", "(", "url", ",", "six", ".", "text_type", ")", ":", "ensure_func", "=", "six", ".", "ensure_text", "else", ":", "ensure_func", "=", "six", ".", "ensure_str", "def", "ensure_type", "(", "x", ")", ":", "return", "x", "if", "x", "is", "None", "else", "ensure_func", "(", "x", ")", "return", "Url", "(", "scheme", "=", "ensure_type", "(", "scheme", ")", ",", "auth", "=", "ensure_type", "(", "auth", ")", ",", "host", "=", "ensure_type", "(", "host", ")", ",", "port", "=", "port", ",", "path", "=", "ensure_type", "(", "path", ")", ",", "query", "=", "ensure_type", "(", "query", ")", ",", "fragment", "=", "ensure_type", "(", "fragment", ")", ",", ")" ]
[ 329, 0 ]
[ 423, 5 ]
python
en
['en', 'error', 'th']
False
get_host
(url)
Deprecated. Use :func:`parse_url` instead.
Deprecated. Use :func:`parse_url` instead.
def get_host(url): """ Deprecated. Use :func:`parse_url` instead. """ p = parse_url(url) return p.scheme or "http", p.hostname, p.port
[ "def", "get_host", "(", "url", ")", ":", "p", "=", "parse_url", "(", "url", ")", "return", "p", ".", "scheme", "or", "\"http\"", ",", "p", ".", "hostname", ",", "p", ".", "port" ]
[ 426, 0 ]
[ 431, 49 ]
python
en
['en', 'error', 'th']
False
Url.hostname
(self)
For backwards-compatibility with urlparse. We're nice like that.
For backwards-compatibility with urlparse. We're nice like that.
def hostname(self): """For backwards-compatibility with urlparse. We're nice like that.""" return self.host
[ "def", "hostname", "(", "self", ")", ":", "return", "self", ".", "host" ]
[ 109, 4 ]
[ 111, 24 ]
python
en
['en', 'en', 'en']
True