id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
26,600
huge-success/sanic
sanic/blueprints.py
Blueprint.group
def group(*blueprints, url_prefix=""): """ Create a list of blueprints, optionally grouping them under a general URL prefix. :param blueprints: blueprints to be registered as a group :param url_prefix: URL route to be prepended to all sub-prefixes """ def chain(nested): """itertools.chain() but leaves strings untouched""" for i in nested: if isinstance(i, (list, tuple)): yield from chain(i) elif isinstance(i, BlueprintGroup): yield from i.blueprints else: yield i bps = BlueprintGroup(url_prefix=url_prefix) for bp in chain(blueprints): if bp.url_prefix is None: bp.url_prefix = "" bp.url_prefix = url_prefix + bp.url_prefix bps.append(bp) return bps
python
def group(*blueprints, url_prefix=""): """ Create a list of blueprints, optionally grouping them under a general URL prefix. :param blueprints: blueprints to be registered as a group :param url_prefix: URL route to be prepended to all sub-prefixes """ def chain(nested): """itertools.chain() but leaves strings untouched""" for i in nested: if isinstance(i, (list, tuple)): yield from chain(i) elif isinstance(i, BlueprintGroup): yield from i.blueprints else: yield i bps = BlueprintGroup(url_prefix=url_prefix) for bp in chain(blueprints): if bp.url_prefix is None: bp.url_prefix = "" bp.url_prefix = url_prefix + bp.url_prefix bps.append(bp) return bps
[ "def", "group", "(", "*", "blueprints", ",", "url_prefix", "=", "\"\"", ")", ":", "def", "chain", "(", "nested", ")", ":", "\"\"\"itertools.chain() but leaves strings untouched\"\"\"", "for", "i", "in", "nested", ":", "if", "isinstance", "(", "i", ",", "(", "list", ",", "tuple", ")", ")", ":", "yield", "from", "chain", "(", "i", ")", "elif", "isinstance", "(", "i", ",", "BlueprintGroup", ")", ":", "yield", "from", "i", ".", "blueprints", "else", ":", "yield", "i", "bps", "=", "BlueprintGroup", "(", "url_prefix", "=", "url_prefix", ")", "for", "bp", "in", "chain", "(", "blueprints", ")", ":", "if", "bp", ".", "url_prefix", "is", "None", ":", "bp", ".", "url_prefix", "=", "\"\"", "bp", ".", "url_prefix", "=", "url_prefix", "+", "bp", ".", "url_prefix", "bps", ".", "append", "(", "bp", ")", "return", "bps" ]
Create a list of blueprints, optionally grouping them under a general URL prefix. :param blueprints: blueprints to be registered as a group :param url_prefix: URL route to be prepended to all sub-prefixes
[ "Create", "a", "list", "of", "blueprints", "optionally", "grouping", "them", "under", "a", "general", "URL", "prefix", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L68-L93
26,601
huge-success/sanic
sanic/blueprints.py
Blueprint.register
def register(self, app, options): """ Register the blueprint to the sanic app. :param app: Instance of :class:`sanic.app.Sanic` class :param options: Options to be used while registering the blueprint into the app. *url_prefix* - URL Prefix to override the blueprint prefix """ url_prefix = options.get("url_prefix", self.url_prefix) # Routes for future in self.routes: # attach the blueprint name to the handler so that it can be # prefixed properly in the router future.handler.__blueprintname__ = self.name # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri version = future.version or self.version app.route( uri=uri[1:] if uri.startswith("//") else uri, methods=future.methods, host=future.host or self.host, strict_slashes=future.strict_slashes, stream=future.stream, version=version, name=future.name, )(future.handler) for future in self.websocket_routes: # attach the blueprint name to the handler so that it can be # prefixed properly in the router future.handler.__blueprintname__ = self.name # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri app.websocket( uri=uri, host=future.host or self.host, strict_slashes=future.strict_slashes, name=future.name, )(future.handler) # Middleware for future in self.middlewares: if future.args or future.kwargs: app.register_middleware( future.middleware, *future.args, **future.kwargs ) else: app.register_middleware(future.middleware) # Exceptions for future in self.exceptions: app.exception(*future.args, **future.kwargs)(future.handler) # Static Files for future in self.statics: # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri app.static( uri, future.file_or_directory, *future.args, **future.kwargs ) # Event listeners for event, listeners in self.listeners.items(): for listener in listeners: app.listener(event)(listener)
python
def register(self, app, options): """ Register the blueprint to the sanic app. :param app: Instance of :class:`sanic.app.Sanic` class :param options: Options to be used while registering the blueprint into the app. *url_prefix* - URL Prefix to override the blueprint prefix """ url_prefix = options.get("url_prefix", self.url_prefix) # Routes for future in self.routes: # attach the blueprint name to the handler so that it can be # prefixed properly in the router future.handler.__blueprintname__ = self.name # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri version = future.version or self.version app.route( uri=uri[1:] if uri.startswith("//") else uri, methods=future.methods, host=future.host or self.host, strict_slashes=future.strict_slashes, stream=future.stream, version=version, name=future.name, )(future.handler) for future in self.websocket_routes: # attach the blueprint name to the handler so that it can be # prefixed properly in the router future.handler.__blueprintname__ = self.name # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri app.websocket( uri=uri, host=future.host or self.host, strict_slashes=future.strict_slashes, name=future.name, )(future.handler) # Middleware for future in self.middlewares: if future.args or future.kwargs: app.register_middleware( future.middleware, *future.args, **future.kwargs ) else: app.register_middleware(future.middleware) # Exceptions for future in self.exceptions: app.exception(*future.args, **future.kwargs)(future.handler) # Static Files for future in self.statics: # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri app.static( uri, future.file_or_directory, *future.args, **future.kwargs ) # Event listeners for event, listeners in self.listeners.items(): for listener in listeners: app.listener(event)(listener)
[ "def", "register", "(", "self", ",", "app", ",", "options", ")", ":", "url_prefix", "=", "options", ".", "get", "(", "\"url_prefix\"", ",", "self", ".", "url_prefix", ")", "# Routes", "for", "future", "in", "self", ".", "routes", ":", "# attach the blueprint name to the handler so that it can be", "# prefixed properly in the router", "future", ".", "handler", ".", "__blueprintname__", "=", "self", ".", "name", "# Prepend the blueprint URI prefix if available", "uri", "=", "url_prefix", "+", "future", ".", "uri", "if", "url_prefix", "else", "future", ".", "uri", "version", "=", "future", ".", "version", "or", "self", ".", "version", "app", ".", "route", "(", "uri", "=", "uri", "[", "1", ":", "]", "if", "uri", ".", "startswith", "(", "\"//\"", ")", "else", "uri", ",", "methods", "=", "future", ".", "methods", ",", "host", "=", "future", ".", "host", "or", "self", ".", "host", ",", "strict_slashes", "=", "future", ".", "strict_slashes", ",", "stream", "=", "future", ".", "stream", ",", "version", "=", "version", ",", "name", "=", "future", ".", "name", ",", ")", "(", "future", ".", "handler", ")", "for", "future", "in", "self", ".", "websocket_routes", ":", "# attach the blueprint name to the handler so that it can be", "# prefixed properly in the router", "future", ".", "handler", ".", "__blueprintname__", "=", "self", ".", "name", "# Prepend the blueprint URI prefix if available", "uri", "=", "url_prefix", "+", "future", ".", "uri", "if", "url_prefix", "else", "future", ".", "uri", "app", ".", "websocket", "(", "uri", "=", "uri", ",", "host", "=", "future", ".", "host", "or", "self", ".", "host", ",", "strict_slashes", "=", "future", ".", "strict_slashes", ",", "name", "=", "future", ".", "name", ",", ")", "(", "future", ".", "handler", ")", "# Middleware", "for", "future", "in", "self", ".", "middlewares", ":", "if", "future", ".", "args", "or", "future", ".", "kwargs", ":", "app", ".", "register_middleware", "(", "future", ".", "middleware", ",", "*", "future", ".", "args", ",", "*", "*", "future", ".", "kwargs", ")", "else", ":", "app", ".", "register_middleware", "(", "future", ".", "middleware", ")", "# Exceptions", "for", "future", "in", "self", ".", "exceptions", ":", "app", ".", "exception", "(", "*", "future", ".", "args", ",", "*", "*", "future", ".", "kwargs", ")", "(", "future", ".", "handler", ")", "# Static Files", "for", "future", "in", "self", ".", "statics", ":", "# Prepend the blueprint URI prefix if available", "uri", "=", "url_prefix", "+", "future", ".", "uri", "if", "url_prefix", "else", "future", ".", "uri", "app", ".", "static", "(", "uri", ",", "future", ".", "file_or_directory", ",", "*", "future", ".", "args", ",", "*", "*", "future", ".", "kwargs", ")", "# Event listeners", "for", "event", ",", "listeners", "in", "self", ".", "listeners", ".", "items", "(", ")", ":", "for", "listener", "in", "listeners", ":", "app", ".", "listener", "(", "event", ")", "(", "listener", ")" ]
Register the blueprint to the sanic app. :param app: Instance of :class:`sanic.app.Sanic` class :param options: Options to be used while registering the blueprint into the app. *url_prefix* - URL Prefix to override the blueprint prefix
[ "Register", "the", "blueprint", "to", "the", "sanic", "app", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L95-L164
26,602
huge-success/sanic
sanic/blueprints.py
Blueprint.route
def route( self, uri, methods=frozenset({"GET"}), host=None, strict_slashes=None, stream=False, version=None, name=None, ): """Create a blueprint route from a decorated function. :param uri: endpoint at which the route will be accessible. :param methods: list of acceptable HTTP methods. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a training */* :param stream: If the route should provide a streaming support :param version: Blueprint Version :param name: Unique name to identify the Route :return a decorated method that when invoked will return an object of type :class:`FutureRoute` """ if strict_slashes is None: strict_slashes = self.strict_slashes def decorator(handler): route = FutureRoute( handler, uri, methods, host, strict_slashes, stream, version, name, ) self.routes.append(route) return handler return decorator
python
def route( self, uri, methods=frozenset({"GET"}), host=None, strict_slashes=None, stream=False, version=None, name=None, ): """Create a blueprint route from a decorated function. :param uri: endpoint at which the route will be accessible. :param methods: list of acceptable HTTP methods. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a training */* :param stream: If the route should provide a streaming support :param version: Blueprint Version :param name: Unique name to identify the Route :return a decorated method that when invoked will return an object of type :class:`FutureRoute` """ if strict_slashes is None: strict_slashes = self.strict_slashes def decorator(handler): route = FutureRoute( handler, uri, methods, host, strict_slashes, stream, version, name, ) self.routes.append(route) return handler return decorator
[ "def", "route", "(", "self", ",", "uri", ",", "methods", "=", "frozenset", "(", "{", "\"GET\"", "}", ")", ",", "host", "=", "None", ",", "strict_slashes", "=", "None", ",", "stream", "=", "False", ",", "version", "=", "None", ",", "name", "=", "None", ",", ")", ":", "if", "strict_slashes", "is", "None", ":", "strict_slashes", "=", "self", ".", "strict_slashes", "def", "decorator", "(", "handler", ")", ":", "route", "=", "FutureRoute", "(", "handler", ",", "uri", ",", "methods", ",", "host", ",", "strict_slashes", ",", "stream", ",", "version", ",", "name", ",", ")", "self", ".", "routes", ".", "append", "(", "route", ")", "return", "handler", "return", "decorator" ]
Create a blueprint route from a decorated function. :param uri: endpoint at which the route will be accessible. :param methods: list of acceptable HTTP methods. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a training */* :param stream: If the route should provide a streaming support :param version: Blueprint Version :param name: Unique name to identify the Route :return a decorated method that when invoked will return an object of type :class:`FutureRoute`
[ "Create", "a", "blueprint", "route", "from", "a", "decorated", "function", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L166-L207
26,603
huge-success/sanic
sanic/blueprints.py
Blueprint.websocket
def websocket( self, uri, host=None, strict_slashes=None, version=None, name=None ): """Create a blueprint websocket route from a decorated function. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a training */* :param version: Blueprint Version :param name: Unique name to identify the Websocket Route """ if strict_slashes is None: strict_slashes = self.strict_slashes def decorator(handler): route = FutureRoute( handler, uri, [], host, strict_slashes, False, version, name ) self.websocket_routes.append(route) return handler return decorator
python
def websocket( self, uri, host=None, strict_slashes=None, version=None, name=None ): """Create a blueprint websocket route from a decorated function. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a training */* :param version: Blueprint Version :param name: Unique name to identify the Websocket Route """ if strict_slashes is None: strict_slashes = self.strict_slashes def decorator(handler): route = FutureRoute( handler, uri, [], host, strict_slashes, False, version, name ) self.websocket_routes.append(route) return handler return decorator
[ "def", "websocket", "(", "self", ",", "uri", ",", "host", "=", "None", ",", "strict_slashes", "=", "None", ",", "version", "=", "None", ",", "name", "=", "None", ")", ":", "if", "strict_slashes", "is", "None", ":", "strict_slashes", "=", "self", ".", "strict_slashes", "def", "decorator", "(", "handler", ")", ":", "route", "=", "FutureRoute", "(", "handler", ",", "uri", ",", "[", "]", ",", "host", ",", "strict_slashes", ",", "False", ",", "version", ",", "name", ")", "self", ".", "websocket_routes", ".", "append", "(", "route", ")", "return", "handler", "return", "decorator" ]
Create a blueprint websocket route from a decorated function. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a training */* :param version: Blueprint Version :param name: Unique name to identify the Websocket Route
[ "Create", "a", "blueprint", "websocket", "route", "from", "a", "decorated", "function", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L260-L282
26,604
huge-success/sanic
sanic/blueprints.py
Blueprint.add_websocket_route
def add_websocket_route( self, handler, uri, host=None, version=None, name=None ): """Create a blueprint websocket route from a function. :param handler: function for handling uri requests. Accepts function, or class instance with a view_class method. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic server to use. :param version: Blueprint Version :param name: Unique name to identify the Websocket Route :return: function or class instance """ self.websocket(uri=uri, host=host, version=version, name=name)(handler) return handler
python
def add_websocket_route( self, handler, uri, host=None, version=None, name=None ): """Create a blueprint websocket route from a function. :param handler: function for handling uri requests. Accepts function, or class instance with a view_class method. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic server to use. :param version: Blueprint Version :param name: Unique name to identify the Websocket Route :return: function or class instance """ self.websocket(uri=uri, host=host, version=version, name=name)(handler) return handler
[ "def", "add_websocket_route", "(", "self", ",", "handler", ",", "uri", ",", "host", "=", "None", ",", "version", "=", "None", ",", "name", "=", "None", ")", ":", "self", ".", "websocket", "(", "uri", "=", "uri", ",", "host", "=", "host", ",", "version", "=", "version", ",", "name", "=", "name", ")", "(", "handler", ")", "return", "handler" ]
Create a blueprint websocket route from a function. :param handler: function for handling uri requests. Accepts function, or class instance with a view_class method. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic server to use. :param version: Blueprint Version :param name: Unique name to identify the Websocket Route :return: function or class instance
[ "Create", "a", "blueprint", "websocket", "route", "from", "a", "function", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L284-L298
26,605
huge-success/sanic
sanic/blueprints.py
Blueprint.listener
def listener(self, event): """Create a listener from a decorated function. :param event: Event to listen to. """ def decorator(listener): self.listeners[event].append(listener) return listener return decorator
python
def listener(self, event): """Create a listener from a decorated function. :param event: Event to listen to. """ def decorator(listener): self.listeners[event].append(listener) return listener return decorator
[ "def", "listener", "(", "self", ",", "event", ")", ":", "def", "decorator", "(", "listener", ")", ":", "self", ".", "listeners", "[", "event", "]", ".", "append", "(", "listener", ")", "return", "listener", "return", "decorator" ]
Create a listener from a decorated function. :param event: Event to listen to.
[ "Create", "a", "listener", "from", "a", "decorated", "function", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L300-L310
26,606
huge-success/sanic
sanic/blueprints.py
Blueprint.middleware
def middleware(self, *args, **kwargs): """ Create a blueprint middleware from a decorated function. :param args: Positional arguments to be used while invoking the middleware :param kwargs: optional keyword args that can be used with the middleware. """ def register_middleware(_middleware): future_middleware = FutureMiddleware(_middleware, args, kwargs) self.middlewares.append(future_middleware) return _middleware # Detect which way this was called, @middleware or @middleware('AT') if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): middleware = args[0] args = [] return register_middleware(middleware) else: if kwargs.get("bp_group") and callable(args[0]): middleware = args[0] args = args[1:] kwargs.pop("bp_group") return register_middleware(middleware) else: return register_middleware
python
def middleware(self, *args, **kwargs): """ Create a blueprint middleware from a decorated function. :param args: Positional arguments to be used while invoking the middleware :param kwargs: optional keyword args that can be used with the middleware. """ def register_middleware(_middleware): future_middleware = FutureMiddleware(_middleware, args, kwargs) self.middlewares.append(future_middleware) return _middleware # Detect which way this was called, @middleware or @middleware('AT') if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): middleware = args[0] args = [] return register_middleware(middleware) else: if kwargs.get("bp_group") and callable(args[0]): middleware = args[0] args = args[1:] kwargs.pop("bp_group") return register_middleware(middleware) else: return register_middleware
[ "def", "middleware", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "register_middleware", "(", "_middleware", ")", ":", "future_middleware", "=", "FutureMiddleware", "(", "_middleware", ",", "args", ",", "kwargs", ")", "self", ".", "middlewares", ".", "append", "(", "future_middleware", ")", "return", "_middleware", "# Detect which way this was called, @middleware or @middleware('AT')", "if", "len", "(", "args", ")", "==", "1", "and", "len", "(", "kwargs", ")", "==", "0", "and", "callable", "(", "args", "[", "0", "]", ")", ":", "middleware", "=", "args", "[", "0", "]", "args", "=", "[", "]", "return", "register_middleware", "(", "middleware", ")", "else", ":", "if", "kwargs", ".", "get", "(", "\"bp_group\"", ")", "and", "callable", "(", "args", "[", "0", "]", ")", ":", "middleware", "=", "args", "[", "0", "]", "args", "=", "args", "[", "1", ":", "]", "kwargs", ".", "pop", "(", "\"bp_group\"", ")", "return", "register_middleware", "(", "middleware", ")", "else", ":", "return", "register_middleware" ]
Create a blueprint middleware from a decorated function. :param args: Positional arguments to be used while invoking the middleware :param kwargs: optional keyword args that can be used with the middleware.
[ "Create", "a", "blueprint", "middleware", "from", "a", "decorated", "function", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L312-L339
26,607
huge-success/sanic
sanic/blueprints.py
Blueprint.exception
def exception(self, *args, **kwargs): """ This method enables the process of creating a global exception handler for the current blueprint under question. :param args: List of Python exceptions to be caught by the handler :param kwargs: Additional optional arguments to be passed to the exception handler :return a decorated method to handle global exceptions for any route registered under this blueprint. """ def decorator(handler): exception = FutureException(handler, args, kwargs) self.exceptions.append(exception) return handler return decorator
python
def exception(self, *args, **kwargs): """ This method enables the process of creating a global exception handler for the current blueprint under question. :param args: List of Python exceptions to be caught by the handler :param kwargs: Additional optional arguments to be passed to the exception handler :return a decorated method to handle global exceptions for any route registered under this blueprint. """ def decorator(handler): exception = FutureException(handler, args, kwargs) self.exceptions.append(exception) return handler return decorator
[ "def", "exception", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "handler", ")", ":", "exception", "=", "FutureException", "(", "handler", ",", "args", ",", "kwargs", ")", "self", ".", "exceptions", ".", "append", "(", "exception", ")", "return", "handler", "return", "decorator" ]
This method enables the process of creating a global exception handler for the current blueprint under question. :param args: List of Python exceptions to be caught by the handler :param kwargs: Additional optional arguments to be passed to the exception handler :return a decorated method to handle global exceptions for any route registered under this blueprint.
[ "This", "method", "enables", "the", "process", "of", "creating", "a", "global", "exception", "handler", "for", "the", "current", "blueprint", "under", "question", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L341-L359
26,608
huge-success/sanic
sanic/exceptions.py
abort
def abort(status_code, message=None): """ Raise an exception based on SanicException. Returns the HTTP response message appropriate for the given status code, unless provided. :param status_code: The HTTP status code to return. :param message: The HTTP response body. Defaults to the messages in response.py for the given status code. """ if message is None: message = STATUS_CODES.get(status_code) # These are stored as bytes in the STATUS_CODES dict message = message.decode("utf8") sanic_exception = _sanic_exceptions.get(status_code, SanicException) raise sanic_exception(message=message, status_code=status_code)
python
def abort(status_code, message=None): """ Raise an exception based on SanicException. Returns the HTTP response message appropriate for the given status code, unless provided. :param status_code: The HTTP status code to return. :param message: The HTTP response body. Defaults to the messages in response.py for the given status code. """ if message is None: message = STATUS_CODES.get(status_code) # These are stored as bytes in the STATUS_CODES dict message = message.decode("utf8") sanic_exception = _sanic_exceptions.get(status_code, SanicException) raise sanic_exception(message=message, status_code=status_code)
[ "def", "abort", "(", "status_code", ",", "message", "=", "None", ")", ":", "if", "message", "is", "None", ":", "message", "=", "STATUS_CODES", ".", "get", "(", "status_code", ")", "# These are stored as bytes in the STATUS_CODES dict", "message", "=", "message", ".", "decode", "(", "\"utf8\"", ")", "sanic_exception", "=", "_sanic_exceptions", ".", "get", "(", "status_code", ",", "SanicException", ")", "raise", "sanic_exception", "(", "message", "=", "message", ",", "status_code", "=", "status_code", ")" ]
Raise an exception based on SanicException. Returns the HTTP response message appropriate for the given status code, unless provided. :param status_code: The HTTP status code to return. :param message: The HTTP response body. Defaults to the messages in response.py for the given status code.
[ "Raise", "an", "exception", "based", "on", "SanicException", ".", "Returns", "the", "HTTP", "response", "message", "appropriate", "for", "the", "given", "status", "code", "unless", "provided", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/exceptions.py#L284-L298
26,609
huge-success/sanic
sanic/app.py
Sanic.add_task
def add_task(self, task): """Schedule a task to run later, after the loop has started. Different from asyncio.ensure_future in that it does not also return a future, and the actual ensure_future call is delayed until before server start. :param task: future, couroutine or awaitable """ try: if callable(task): try: self.loop.create_task(task(self)) except TypeError: self.loop.create_task(task()) else: self.loop.create_task(task) except SanicException: @self.listener("before_server_start") def run(app, loop): if callable(task): try: loop.create_task(task(self)) except TypeError: loop.create_task(task()) else: loop.create_task(task)
python
def add_task(self, task): """Schedule a task to run later, after the loop has started. Different from asyncio.ensure_future in that it does not also return a future, and the actual ensure_future call is delayed until before server start. :param task: future, couroutine or awaitable """ try: if callable(task): try: self.loop.create_task(task(self)) except TypeError: self.loop.create_task(task()) else: self.loop.create_task(task) except SanicException: @self.listener("before_server_start") def run(app, loop): if callable(task): try: loop.create_task(task(self)) except TypeError: loop.create_task(task()) else: loop.create_task(task)
[ "def", "add_task", "(", "self", ",", "task", ")", ":", "try", ":", "if", "callable", "(", "task", ")", ":", "try", ":", "self", ".", "loop", ".", "create_task", "(", "task", "(", "self", ")", ")", "except", "TypeError", ":", "self", ".", "loop", ".", "create_task", "(", "task", "(", ")", ")", "else", ":", "self", ".", "loop", ".", "create_task", "(", "task", ")", "except", "SanicException", ":", "@", "self", ".", "listener", "(", "\"before_server_start\"", ")", "def", "run", "(", "app", ",", "loop", ")", ":", "if", "callable", "(", "task", ")", ":", "try", ":", "loop", ".", "create_task", "(", "task", "(", "self", ")", ")", "except", "TypeError", ":", "loop", ".", "create_task", "(", "task", "(", ")", ")", "else", ":", "loop", ".", "create_task", "(", "task", ")" ]
Schedule a task to run later, after the loop has started. Different from asyncio.ensure_future in that it does not also return a future, and the actual ensure_future call is delayed until before server start. :param task: future, couroutine or awaitable
[ "Schedule", "a", "task", "to", "run", "later", "after", "the", "loop", "has", "started", ".", "Different", "from", "asyncio", ".", "ensure_future", "in", "that", "it", "does", "not", "also", "return", "a", "future", "and", "the", "actual", "ensure_future", "call", "is", "delayed", "until", "before", "server", "start", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L94-L120
26,610
huge-success/sanic
sanic/app.py
Sanic.add_websocket_route
def add_websocket_route( self, handler, uri, host=None, strict_slashes=None, subprotocols=None, name=None, ): """ A helper method to register a function as a websocket route. :param handler: a callable function or instance of a class that can handle the websocket request :param host: Host IP or FQDN details :param uri: URL path that will be mapped to the websocket handler :param strict_slashes: If the API endpoint needs to terminate with a "/" or not :param subprotocols: Subprotocols to be used with websocket handshake :param name: A unique name assigned to the URL so that it can be used with :func:`url_for` :return: Objected decorated by :func:`websocket` """ if strict_slashes is None: strict_slashes = self.strict_slashes return self.websocket( uri, host=host, strict_slashes=strict_slashes, subprotocols=subprotocols, name=name, )(handler)
python
def add_websocket_route( self, handler, uri, host=None, strict_slashes=None, subprotocols=None, name=None, ): """ A helper method to register a function as a websocket route. :param handler: a callable function or instance of a class that can handle the websocket request :param host: Host IP or FQDN details :param uri: URL path that will be mapped to the websocket handler :param strict_slashes: If the API endpoint needs to terminate with a "/" or not :param subprotocols: Subprotocols to be used with websocket handshake :param name: A unique name assigned to the URL so that it can be used with :func:`url_for` :return: Objected decorated by :func:`websocket` """ if strict_slashes is None: strict_slashes = self.strict_slashes return self.websocket( uri, host=host, strict_slashes=strict_slashes, subprotocols=subprotocols, name=name, )(handler)
[ "def", "add_websocket_route", "(", "self", ",", "handler", ",", "uri", ",", "host", "=", "None", ",", "strict_slashes", "=", "None", ",", "subprotocols", "=", "None", ",", "name", "=", "None", ",", ")", ":", "if", "strict_slashes", "is", "None", ":", "strict_slashes", "=", "self", ".", "strict_slashes", "return", "self", ".", "websocket", "(", "uri", ",", "host", "=", "host", ",", "strict_slashes", "=", "strict_slashes", ",", "subprotocols", "=", "subprotocols", ",", "name", "=", "name", ",", ")", "(", "handler", ")" ]
A helper method to register a function as a websocket route. :param handler: a callable function or instance of a class that can handle the websocket request :param host: Host IP or FQDN details :param uri: URL path that will be mapped to the websocket handler :param strict_slashes: If the API endpoint needs to terminate with a "/" or not :param subprotocols: Subprotocols to be used with websocket handshake :param name: A unique name assigned to the URL so that it can be used with :func:`url_for` :return: Objected decorated by :func:`websocket`
[ "A", "helper", "method", "to", "register", "a", "function", "as", "a", "websocket", "route", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L501-L535
26,611
huge-success/sanic
sanic/app.py
Sanic.enable_websocket
def enable_websocket(self, enable=True): """Enable or disable the support for websocket. Websocket is enabled automatically if websocket routes are added to the application. """ if not self.websocket_enabled: # if the server is stopped, we want to cancel any ongoing # websocket tasks, to allow the server to exit promptly @self.listener("before_server_stop") def cancel_websocket_tasks(app, loop): for task in self.websocket_tasks: task.cancel() self.websocket_enabled = enable
python
def enable_websocket(self, enable=True): """Enable or disable the support for websocket. Websocket is enabled automatically if websocket routes are added to the application. """ if not self.websocket_enabled: # if the server is stopped, we want to cancel any ongoing # websocket tasks, to allow the server to exit promptly @self.listener("before_server_stop") def cancel_websocket_tasks(app, loop): for task in self.websocket_tasks: task.cancel() self.websocket_enabled = enable
[ "def", "enable_websocket", "(", "self", ",", "enable", "=", "True", ")", ":", "if", "not", "self", ".", "websocket_enabled", ":", "# if the server is stopped, we want to cancel any ongoing", "# websocket tasks, to allow the server to exit promptly", "@", "self", ".", "listener", "(", "\"before_server_stop\"", ")", "def", "cancel_websocket_tasks", "(", "app", ",", "loop", ")", ":", "for", "task", "in", "self", ".", "websocket_tasks", ":", "task", ".", "cancel", "(", ")", "self", ".", "websocket_enabled", "=", "enable" ]
Enable or disable the support for websocket. Websocket is enabled automatically if websocket routes are added to the application.
[ "Enable", "or", "disable", "the", "support", "for", "websocket", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L537-L551
26,612
huge-success/sanic
sanic/app.py
Sanic.exception
def exception(self, *exceptions): """Decorate a function to be registered as a handler for exceptions :param exceptions: exceptions :return: decorated function """ def response(handler): for exception in exceptions: if isinstance(exception, (tuple, list)): for e in exception: self.error_handler.add(e, handler) else: self.error_handler.add(exception, handler) return handler return response
python
def exception(self, *exceptions): """Decorate a function to be registered as a handler for exceptions :param exceptions: exceptions :return: decorated function """ def response(handler): for exception in exceptions: if isinstance(exception, (tuple, list)): for e in exception: self.error_handler.add(e, handler) else: self.error_handler.add(exception, handler) return handler return response
[ "def", "exception", "(", "self", ",", "*", "exceptions", ")", ":", "def", "response", "(", "handler", ")", ":", "for", "exception", "in", "exceptions", ":", "if", "isinstance", "(", "exception", ",", "(", "tuple", ",", "list", ")", ")", ":", "for", "e", "in", "exception", ":", "self", ".", "error_handler", ".", "add", "(", "e", ",", "handler", ")", "else", ":", "self", ".", "error_handler", ".", "add", "(", "exception", ",", "handler", ")", "return", "handler", "return", "response" ]
Decorate a function to be registered as a handler for exceptions :param exceptions: exceptions :return: decorated function
[ "Decorate", "a", "function", "to", "be", "registered", "as", "a", "handler", "for", "exceptions" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L567-L583
26,613
huge-success/sanic
sanic/app.py
Sanic.register_middleware
def register_middleware(self, middleware, attach_to="request"): """ Register an application level middleware that will be attached to all the API URLs registered under this application. This method is internally invoked by the :func:`middleware` decorator provided at the app level. :param middleware: Callback method to be attached to the middleware :param attach_to: The state at which the middleware needs to be invoked in the lifecycle of an *HTTP Request*. **request** - Invoke before the request is processed **response** - Invoke before the response is returned back :return: decorated method """ if attach_to == "request": if middleware not in self.request_middleware: self.request_middleware.append(middleware) if attach_to == "response": if middleware not in self.response_middleware: self.response_middleware.appendleft(middleware) return middleware
python
def register_middleware(self, middleware, attach_to="request"): """ Register an application level middleware that will be attached to all the API URLs registered under this application. This method is internally invoked by the :func:`middleware` decorator provided at the app level. :param middleware: Callback method to be attached to the middleware :param attach_to: The state at which the middleware needs to be invoked in the lifecycle of an *HTTP Request*. **request** - Invoke before the request is processed **response** - Invoke before the response is returned back :return: decorated method """ if attach_to == "request": if middleware not in self.request_middleware: self.request_middleware.append(middleware) if attach_to == "response": if middleware not in self.response_middleware: self.response_middleware.appendleft(middleware) return middleware
[ "def", "register_middleware", "(", "self", ",", "middleware", ",", "attach_to", "=", "\"request\"", ")", ":", "if", "attach_to", "==", "\"request\"", ":", "if", "middleware", "not", "in", "self", ".", "request_middleware", ":", "self", ".", "request_middleware", ".", "append", "(", "middleware", ")", "if", "attach_to", "==", "\"response\"", ":", "if", "middleware", "not", "in", "self", ".", "response_middleware", ":", "self", ".", "response_middleware", ".", "appendleft", "(", "middleware", ")", "return", "middleware" ]
Register an application level middleware that will be attached to all the API URLs registered under this application. This method is internally invoked by the :func:`middleware` decorator provided at the app level. :param middleware: Callback method to be attached to the middleware :param attach_to: The state at which the middleware needs to be invoked in the lifecycle of an *HTTP Request*. **request** - Invoke before the request is processed **response** - Invoke before the response is returned back :return: decorated method
[ "Register", "an", "application", "level", "middleware", "that", "will", "be", "attached", "to", "all", "the", "API", "URLs", "registered", "under", "this", "application", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L585-L607
26,614
huge-success/sanic
sanic/app.py
Sanic.handle_request
async def handle_request(self, request, write_callback, stream_callback): """Take a request from the HTTP Server and return a response object to be sent back The HTTP Server only expects a response object, so exception handling must be done here :param request: HTTP Request object :param write_callback: Synchronous response function to be called with the response as the only argument :param stream_callback: Coroutine that handles streaming a StreamingHTTPResponse if produced by the handler. :return: Nothing """ # Define `response` var here to remove warnings about # allocation before assignment below. response = None cancelled = False try: # -------------------------------------------- # # Request Middleware # -------------------------------------------- # response = await self._run_request_middleware(request) # No middleware results if not response: # -------------------------------------------- # # Execute Handler # -------------------------------------------- # # Fetch handler from router handler, args, kwargs, uri = self.router.get(request) request.uri_template = uri if handler is None: raise ServerError( ( "'None' was returned while requesting a " "handler from the router" ) ) else: if not getattr(handler, "__blueprintname__", False): request.endpoint = self._build_endpoint_name( handler.__name__ ) else: request.endpoint = self._build_endpoint_name( getattr(handler, "__blueprintname__", ""), handler.__name__, ) # Run response handler response = handler(request, *args, **kwargs) if isawaitable(response): response = await response except CancelledError: # If response handler times out, the server handles the error # and cancels the handle_request job. # In this case, the transport is already closed and we cannot # issue a response. response = None cancelled = True except Exception as e: # -------------------------------------------- # # Response Generation Failed # -------------------------------------------- # try: response = self.error_handler.response(request, e) if isawaitable(response): response = await response except Exception as e: if isinstance(e, SanicException): response = self.error_handler.default( request=request, exception=e ) elif self.debug: response = HTTPResponse( "Error while handling error: {}\nStack: {}".format( e, format_exc() ), status=500, ) else: response = HTTPResponse( "An error occurred while handling an error", status=500 ) finally: # -------------------------------------------- # # Response Middleware # -------------------------------------------- # # Don't run response middleware if response is None if response is not None: try: response = await self._run_response_middleware( request, response ) except CancelledError: # Response middleware can timeout too, as above. response = None cancelled = True except BaseException: error_logger.exception( "Exception occurred in one of response " "middleware handlers" ) if cancelled: raise CancelledError() # pass the response to the correct callback if isinstance(response, StreamingHTTPResponse): await stream_callback(response) else: write_callback(response)
python
async def handle_request(self, request, write_callback, stream_callback): """Take a request from the HTTP Server and return a response object to be sent back The HTTP Server only expects a response object, so exception handling must be done here :param request: HTTP Request object :param write_callback: Synchronous response function to be called with the response as the only argument :param stream_callback: Coroutine that handles streaming a StreamingHTTPResponse if produced by the handler. :return: Nothing """ # Define `response` var here to remove warnings about # allocation before assignment below. response = None cancelled = False try: # -------------------------------------------- # # Request Middleware # -------------------------------------------- # response = await self._run_request_middleware(request) # No middleware results if not response: # -------------------------------------------- # # Execute Handler # -------------------------------------------- # # Fetch handler from router handler, args, kwargs, uri = self.router.get(request) request.uri_template = uri if handler is None: raise ServerError( ( "'None' was returned while requesting a " "handler from the router" ) ) else: if not getattr(handler, "__blueprintname__", False): request.endpoint = self._build_endpoint_name( handler.__name__ ) else: request.endpoint = self._build_endpoint_name( getattr(handler, "__blueprintname__", ""), handler.__name__, ) # Run response handler response = handler(request, *args, **kwargs) if isawaitable(response): response = await response except CancelledError: # If response handler times out, the server handles the error # and cancels the handle_request job. # In this case, the transport is already closed and we cannot # issue a response. response = None cancelled = True except Exception as e: # -------------------------------------------- # # Response Generation Failed # -------------------------------------------- # try: response = self.error_handler.response(request, e) if isawaitable(response): response = await response except Exception as e: if isinstance(e, SanicException): response = self.error_handler.default( request=request, exception=e ) elif self.debug: response = HTTPResponse( "Error while handling error: {}\nStack: {}".format( e, format_exc() ), status=500, ) else: response = HTTPResponse( "An error occurred while handling an error", status=500 ) finally: # -------------------------------------------- # # Response Middleware # -------------------------------------------- # # Don't run response middleware if response is None if response is not None: try: response = await self._run_response_middleware( request, response ) except CancelledError: # Response middleware can timeout too, as above. response = None cancelled = True except BaseException: error_logger.exception( "Exception occurred in one of response " "middleware handlers" ) if cancelled: raise CancelledError() # pass the response to the correct callback if isinstance(response, StreamingHTTPResponse): await stream_callback(response) else: write_callback(response)
[ "async", "def", "handle_request", "(", "self", ",", "request", ",", "write_callback", ",", "stream_callback", ")", ":", "# Define `response` var here to remove warnings about", "# allocation before assignment below.", "response", "=", "None", "cancelled", "=", "False", "try", ":", "# -------------------------------------------- #", "# Request Middleware", "# -------------------------------------------- #", "response", "=", "await", "self", ".", "_run_request_middleware", "(", "request", ")", "# No middleware results", "if", "not", "response", ":", "# -------------------------------------------- #", "# Execute Handler", "# -------------------------------------------- #", "# Fetch handler from router", "handler", ",", "args", ",", "kwargs", ",", "uri", "=", "self", ".", "router", ".", "get", "(", "request", ")", "request", ".", "uri_template", "=", "uri", "if", "handler", "is", "None", ":", "raise", "ServerError", "(", "(", "\"'None' was returned while requesting a \"", "\"handler from the router\"", ")", ")", "else", ":", "if", "not", "getattr", "(", "handler", ",", "\"__blueprintname__\"", ",", "False", ")", ":", "request", ".", "endpoint", "=", "self", ".", "_build_endpoint_name", "(", "handler", ".", "__name__", ")", "else", ":", "request", ".", "endpoint", "=", "self", ".", "_build_endpoint_name", "(", "getattr", "(", "handler", ",", "\"__blueprintname__\"", ",", "\"\"", ")", ",", "handler", ".", "__name__", ",", ")", "# Run response handler", "response", "=", "handler", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "isawaitable", "(", "response", ")", ":", "response", "=", "await", "response", "except", "CancelledError", ":", "# If response handler times out, the server handles the error", "# and cancels the handle_request job.", "# In this case, the transport is already closed and we cannot", "# issue a response.", "response", "=", "None", "cancelled", "=", "True", "except", "Exception", "as", "e", ":", "# -------------------------------------------- #", "# Response Generation Failed", "# -------------------------------------------- #", "try", ":", "response", "=", "self", ".", "error_handler", ".", "response", "(", "request", ",", "e", ")", "if", "isawaitable", "(", "response", ")", ":", "response", "=", "await", "response", "except", "Exception", "as", "e", ":", "if", "isinstance", "(", "e", ",", "SanicException", ")", ":", "response", "=", "self", ".", "error_handler", ".", "default", "(", "request", "=", "request", ",", "exception", "=", "e", ")", "elif", "self", ".", "debug", ":", "response", "=", "HTTPResponse", "(", "\"Error while handling error: {}\\nStack: {}\"", ".", "format", "(", "e", ",", "format_exc", "(", ")", ")", ",", "status", "=", "500", ",", ")", "else", ":", "response", "=", "HTTPResponse", "(", "\"An error occurred while handling an error\"", ",", "status", "=", "500", ")", "finally", ":", "# -------------------------------------------- #", "# Response Middleware", "# -------------------------------------------- #", "# Don't run response middleware if response is None", "if", "response", "is", "not", "None", ":", "try", ":", "response", "=", "await", "self", ".", "_run_response_middleware", "(", "request", ",", "response", ")", "except", "CancelledError", ":", "# Response middleware can timeout too, as above.", "response", "=", "None", "cancelled", "=", "True", "except", "BaseException", ":", "error_logger", ".", "exception", "(", "\"Exception occurred in one of response \"", "\"middleware handlers\"", ")", "if", "cancelled", ":", "raise", "CancelledError", "(", ")", "# pass the response to the correct callback", "if", "isinstance", "(", "response", ",", "StreamingHTTPResponse", ")", ":", "await", "stream_callback", "(", "response", ")", "else", ":", "write_callback", "(", "response", ")" ]
Take a request from the HTTP Server and return a response object to be sent back The HTTP Server only expects a response object, so exception handling must be done here :param request: HTTP Request object :param write_callback: Synchronous response function to be called with the response as the only argument :param stream_callback: Coroutine that handles streaming a StreamingHTTPResponse if produced by the handler. :return: Nothing
[ "Take", "a", "request", "from", "the", "HTTP", "Server", "and", "return", "a", "response", "object", "to", "be", "sent", "back", "The", "HTTP", "Server", "only", "expects", "a", "response", "object", "so", "exception", "handling", "must", "be", "done", "here" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L863-L975
26,615
huge-success/sanic
sanic/app.py
Sanic.run
def run( self, host: Optional[str] = None, port: Optional[int] = None, debug: bool = False, ssl: Union[dict, SSLContext, None] = None, sock: Optional[socket] = None, workers: int = 1, protocol: Type[Protocol] = None, backlog: int = 100, stop_event: Any = None, register_sys_signals: bool = True, access_log: Optional[bool] = None, **kwargs: Any ) -> None: """Run the HTTP Server and listen until keyboard interrupt or term signal. On termination, drain connections before closing. :param host: Address to host on :type host: str :param port: Port to host on :type port: int :param debug: Enables debug output (slows server) :type debug: bool :param ssl: SSLContext, or location of certificate and key for SSL encryption of worker(s) :type ssl:SSLContext or dict :param sock: Socket for the server to accept connections from :type sock: socket :param workers: Number of processes received before it is respected :type workers: int :param protocol: Subclass of asyncio Protocol class :type protocol: type[Protocol] :param backlog: a number of unaccepted connections that the system will allow before refusing new connections :type backlog: int :param stop_event: event to be triggered before stopping the app - deprecated :type stop_event: None :param register_sys_signals: Register SIG* events :type register_sys_signals: bool :param access_log: Enables writing access logs (slows server) :type access_log: bool :return: Nothing """ if "loop" in kwargs: raise TypeError( "loop is not a valid argument. To use an existing loop, " "change to create_server().\nSee more: " "https://sanic.readthedocs.io/en/latest/sanic/deploying.html" "#asynchronous-support" ) # Default auto_reload to false auto_reload = False # If debug is set, default it to true (unless on windows) if debug and os.name == "posix": auto_reload = True # Allow for overriding either of the defaults auto_reload = kwargs.get("auto_reload", auto_reload) if sock is None: host, port = host or "127.0.0.1", port or 8000 if protocol is None: protocol = ( WebSocketProtocol if self.websocket_enabled else HttpProtocol ) if stop_event is not None: if debug: warnings.simplefilter("default") warnings.warn( "stop_event will be removed from future versions.", DeprecationWarning, ) # if access_log is passed explicitly change config.ACCESS_LOG if access_log is not None: self.config.ACCESS_LOG = access_log server_settings = self._helper( host=host, port=port, debug=debug, ssl=ssl, sock=sock, workers=workers, protocol=protocol, backlog=backlog, register_sys_signals=register_sys_signals, auto_reload=auto_reload, ) try: self.is_running = True if workers == 1: if auto_reload and os.name != "posix": # This condition must be removed after implementing # auto reloader for other operating systems. raise NotImplementedError if ( auto_reload and os.environ.get("SANIC_SERVER_RUNNING") != "true" ): reloader_helpers.watchdog(2) else: serve(**server_settings) else: serve_multiple(server_settings, workers) except BaseException: error_logger.exception( "Experienced exception while trying to serve" ) raise finally: self.is_running = False logger.info("Server Stopped")
python
def run( self, host: Optional[str] = None, port: Optional[int] = None, debug: bool = False, ssl: Union[dict, SSLContext, None] = None, sock: Optional[socket] = None, workers: int = 1, protocol: Type[Protocol] = None, backlog: int = 100, stop_event: Any = None, register_sys_signals: bool = True, access_log: Optional[bool] = None, **kwargs: Any ) -> None: """Run the HTTP Server and listen until keyboard interrupt or term signal. On termination, drain connections before closing. :param host: Address to host on :type host: str :param port: Port to host on :type port: int :param debug: Enables debug output (slows server) :type debug: bool :param ssl: SSLContext, or location of certificate and key for SSL encryption of worker(s) :type ssl:SSLContext or dict :param sock: Socket for the server to accept connections from :type sock: socket :param workers: Number of processes received before it is respected :type workers: int :param protocol: Subclass of asyncio Protocol class :type protocol: type[Protocol] :param backlog: a number of unaccepted connections that the system will allow before refusing new connections :type backlog: int :param stop_event: event to be triggered before stopping the app - deprecated :type stop_event: None :param register_sys_signals: Register SIG* events :type register_sys_signals: bool :param access_log: Enables writing access logs (slows server) :type access_log: bool :return: Nothing """ if "loop" in kwargs: raise TypeError( "loop is not a valid argument. To use an existing loop, " "change to create_server().\nSee more: " "https://sanic.readthedocs.io/en/latest/sanic/deploying.html" "#asynchronous-support" ) # Default auto_reload to false auto_reload = False # If debug is set, default it to true (unless on windows) if debug and os.name == "posix": auto_reload = True # Allow for overriding either of the defaults auto_reload = kwargs.get("auto_reload", auto_reload) if sock is None: host, port = host or "127.0.0.1", port or 8000 if protocol is None: protocol = ( WebSocketProtocol if self.websocket_enabled else HttpProtocol ) if stop_event is not None: if debug: warnings.simplefilter("default") warnings.warn( "stop_event will be removed from future versions.", DeprecationWarning, ) # if access_log is passed explicitly change config.ACCESS_LOG if access_log is not None: self.config.ACCESS_LOG = access_log server_settings = self._helper( host=host, port=port, debug=debug, ssl=ssl, sock=sock, workers=workers, protocol=protocol, backlog=backlog, register_sys_signals=register_sys_signals, auto_reload=auto_reload, ) try: self.is_running = True if workers == 1: if auto_reload and os.name != "posix": # This condition must be removed after implementing # auto reloader for other operating systems. raise NotImplementedError if ( auto_reload and os.environ.get("SANIC_SERVER_RUNNING") != "true" ): reloader_helpers.watchdog(2) else: serve(**server_settings) else: serve_multiple(server_settings, workers) except BaseException: error_logger.exception( "Experienced exception while trying to serve" ) raise finally: self.is_running = False logger.info("Server Stopped")
[ "def", "run", "(", "self", ",", "host", ":", "Optional", "[", "str", "]", "=", "None", ",", "port", ":", "Optional", "[", "int", "]", "=", "None", ",", "debug", ":", "bool", "=", "False", ",", "ssl", ":", "Union", "[", "dict", ",", "SSLContext", ",", "None", "]", "=", "None", ",", "sock", ":", "Optional", "[", "socket", "]", "=", "None", ",", "workers", ":", "int", "=", "1", ",", "protocol", ":", "Type", "[", "Protocol", "]", "=", "None", ",", "backlog", ":", "int", "=", "100", ",", "stop_event", ":", "Any", "=", "None", ",", "register_sys_signals", ":", "bool", "=", "True", ",", "access_log", ":", "Optional", "[", "bool", "]", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "\"loop\"", "in", "kwargs", ":", "raise", "TypeError", "(", "\"loop is not a valid argument. To use an existing loop, \"", "\"change to create_server().\\nSee more: \"", "\"https://sanic.readthedocs.io/en/latest/sanic/deploying.html\"", "\"#asynchronous-support\"", ")", "# Default auto_reload to false", "auto_reload", "=", "False", "# If debug is set, default it to true (unless on windows)", "if", "debug", "and", "os", ".", "name", "==", "\"posix\"", ":", "auto_reload", "=", "True", "# Allow for overriding either of the defaults", "auto_reload", "=", "kwargs", ".", "get", "(", "\"auto_reload\"", ",", "auto_reload", ")", "if", "sock", "is", "None", ":", "host", ",", "port", "=", "host", "or", "\"127.0.0.1\"", ",", "port", "or", "8000", "if", "protocol", "is", "None", ":", "protocol", "=", "(", "WebSocketProtocol", "if", "self", ".", "websocket_enabled", "else", "HttpProtocol", ")", "if", "stop_event", "is", "not", "None", ":", "if", "debug", ":", "warnings", ".", "simplefilter", "(", "\"default\"", ")", "warnings", ".", "warn", "(", "\"stop_event will be removed from future versions.\"", ",", "DeprecationWarning", ",", ")", "# if access_log is passed explicitly change config.ACCESS_LOG", "if", "access_log", "is", "not", "None", ":", "self", ".", "config", ".", "ACCESS_LOG", "=", "access_log", "server_settings", "=", "self", ".", "_helper", "(", "host", "=", "host", ",", "port", "=", "port", ",", "debug", "=", "debug", ",", "ssl", "=", "ssl", ",", "sock", "=", "sock", ",", "workers", "=", "workers", ",", "protocol", "=", "protocol", ",", "backlog", "=", "backlog", ",", "register_sys_signals", "=", "register_sys_signals", ",", "auto_reload", "=", "auto_reload", ",", ")", "try", ":", "self", ".", "is_running", "=", "True", "if", "workers", "==", "1", ":", "if", "auto_reload", "and", "os", ".", "name", "!=", "\"posix\"", ":", "# This condition must be removed after implementing", "# auto reloader for other operating systems.", "raise", "NotImplementedError", "if", "(", "auto_reload", "and", "os", ".", "environ", ".", "get", "(", "\"SANIC_SERVER_RUNNING\"", ")", "!=", "\"true\"", ")", ":", "reloader_helpers", ".", "watchdog", "(", "2", ")", "else", ":", "serve", "(", "*", "*", "server_settings", ")", "else", ":", "serve_multiple", "(", "server_settings", ",", "workers", ")", "except", "BaseException", ":", "error_logger", ".", "exception", "(", "\"Experienced exception while trying to serve\"", ")", "raise", "finally", ":", "self", ".", "is_running", "=", "False", "logger", ".", "info", "(", "\"Server Stopped\"", ")" ]
Run the HTTP Server and listen until keyboard interrupt or term signal. On termination, drain connections before closing. :param host: Address to host on :type host: str :param port: Port to host on :type port: int :param debug: Enables debug output (slows server) :type debug: bool :param ssl: SSLContext, or location of certificate and key for SSL encryption of worker(s) :type ssl:SSLContext or dict :param sock: Socket for the server to accept connections from :type sock: socket :param workers: Number of processes received before it is respected :type workers: int :param protocol: Subclass of asyncio Protocol class :type protocol: type[Protocol] :param backlog: a number of unaccepted connections that the system will allow before refusing new connections :type backlog: int :param stop_event: event to be triggered before stopping the app - deprecated :type stop_event: None :param register_sys_signals: Register SIG* events :type register_sys_signals: bool :param access_log: Enables writing access logs (slows server) :type access_log: bool :return: Nothing
[ "Run", "the", "HTTP", "Server", "and", "listen", "until", "keyboard", "interrupt", "or", "term", "signal", ".", "On", "termination", "drain", "connections", "before", "closing", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L989-L1105
26,616
huge-success/sanic
sanic/response.py
json
def json( body, status=200, headers=None, content_type="application/json", dumps=json_dumps, **kwargs ): """ Returns response object with body in json format. :param body: Response data to be serialized. :param status: Response code. :param headers: Custom Headers. :param kwargs: Remaining arguments that are passed to the json encoder. """ return HTTPResponse( dumps(body, **kwargs), headers=headers, status=status, content_type=content_type, )
python
def json( body, status=200, headers=None, content_type="application/json", dumps=json_dumps, **kwargs ): """ Returns response object with body in json format. :param body: Response data to be serialized. :param status: Response code. :param headers: Custom Headers. :param kwargs: Remaining arguments that are passed to the json encoder. """ return HTTPResponse( dumps(body, **kwargs), headers=headers, status=status, content_type=content_type, )
[ "def", "json", "(", "body", ",", "status", "=", "200", ",", "headers", "=", "None", ",", "content_type", "=", "\"application/json\"", ",", "dumps", "=", "json_dumps", ",", "*", "*", "kwargs", ")", ":", "return", "HTTPResponse", "(", "dumps", "(", "body", ",", "*", "*", "kwargs", ")", ",", "headers", "=", "headers", ",", "status", "=", "status", ",", "content_type", "=", "content_type", ",", ")" ]
Returns response object with body in json format. :param body: Response data to be serialized. :param status: Response code. :param headers: Custom Headers. :param kwargs: Remaining arguments that are passed to the json encoder.
[ "Returns", "response", "object", "with", "body", "in", "json", "format", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L203-L224
26,617
huge-success/sanic
sanic/response.py
text
def text( body, status=200, headers=None, content_type="text/plain; charset=utf-8" ): """ Returns response object with body in text format. :param body: Response data to be encoded. :param status: Response code. :param headers: Custom Headers. :param content_type: the content type (string) of the response """ return HTTPResponse( body, status=status, headers=headers, content_type=content_type )
python
def text( body, status=200, headers=None, content_type="text/plain; charset=utf-8" ): """ Returns response object with body in text format. :param body: Response data to be encoded. :param status: Response code. :param headers: Custom Headers. :param content_type: the content type (string) of the response """ return HTTPResponse( body, status=status, headers=headers, content_type=content_type )
[ "def", "text", "(", "body", ",", "status", "=", "200", ",", "headers", "=", "None", ",", "content_type", "=", "\"text/plain; charset=utf-8\"", ")", ":", "return", "HTTPResponse", "(", "body", ",", "status", "=", "status", ",", "headers", "=", "headers", ",", "content_type", "=", "content_type", ")" ]
Returns response object with body in text format. :param body: Response data to be encoded. :param status: Response code. :param headers: Custom Headers. :param content_type: the content type (string) of the response
[ "Returns", "response", "object", "with", "body", "in", "text", "format", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L227-L240
26,618
huge-success/sanic
sanic/response.py
file_stream
async def file_stream( location, status=200, chunk_size=4096, mime_type=None, headers=None, filename=None, _range=None, ): """Return a streaming response object with file data. :param location: Location of file on system. :param chunk_size: The size of each chunk in the stream (in bytes) :param mime_type: Specific mime_type. :param headers: Custom Headers. :param filename: Override filename. :param _range: """ headers = headers or {} if filename: headers.setdefault( "Content-Disposition", 'attachment; filename="{}"'.format(filename) ) filename = filename or path.split(location)[-1] _file = await open_async(location, mode="rb") async def _streaming_fn(response): nonlocal _file, chunk_size try: if _range: chunk_size = min((_range.size, chunk_size)) await _file.seek(_range.start) to_send = _range.size while to_send > 0: content = await _file.read(chunk_size) if len(content) < 1: break to_send -= len(content) await response.write(content) else: while True: content = await _file.read(chunk_size) if len(content) < 1: break await response.write(content) finally: await _file.close() return # Returning from this fn closes the stream mime_type = mime_type or guess_type(filename)[0] or "text/plain" if _range: headers["Content-Range"] = "bytes %s-%s/%s" % ( _range.start, _range.end, _range.total, ) status = 206 return StreamingHTTPResponse( streaming_fn=_streaming_fn, status=status, headers=headers, content_type=mime_type, )
python
async def file_stream( location, status=200, chunk_size=4096, mime_type=None, headers=None, filename=None, _range=None, ): """Return a streaming response object with file data. :param location: Location of file on system. :param chunk_size: The size of each chunk in the stream (in bytes) :param mime_type: Specific mime_type. :param headers: Custom Headers. :param filename: Override filename. :param _range: """ headers = headers or {} if filename: headers.setdefault( "Content-Disposition", 'attachment; filename="{}"'.format(filename) ) filename = filename or path.split(location)[-1] _file = await open_async(location, mode="rb") async def _streaming_fn(response): nonlocal _file, chunk_size try: if _range: chunk_size = min((_range.size, chunk_size)) await _file.seek(_range.start) to_send = _range.size while to_send > 0: content = await _file.read(chunk_size) if len(content) < 1: break to_send -= len(content) await response.write(content) else: while True: content = await _file.read(chunk_size) if len(content) < 1: break await response.write(content) finally: await _file.close() return # Returning from this fn closes the stream mime_type = mime_type or guess_type(filename)[0] or "text/plain" if _range: headers["Content-Range"] = "bytes %s-%s/%s" % ( _range.start, _range.end, _range.total, ) status = 206 return StreamingHTTPResponse( streaming_fn=_streaming_fn, status=status, headers=headers, content_type=mime_type, )
[ "async", "def", "file_stream", "(", "location", ",", "status", "=", "200", ",", "chunk_size", "=", "4096", ",", "mime_type", "=", "None", ",", "headers", "=", "None", ",", "filename", "=", "None", ",", "_range", "=", "None", ",", ")", ":", "headers", "=", "headers", "or", "{", "}", "if", "filename", ":", "headers", ".", "setdefault", "(", "\"Content-Disposition\"", ",", "'attachment; filename=\"{}\"'", ".", "format", "(", "filename", ")", ")", "filename", "=", "filename", "or", "path", ".", "split", "(", "location", ")", "[", "-", "1", "]", "_file", "=", "await", "open_async", "(", "location", ",", "mode", "=", "\"rb\"", ")", "async", "def", "_streaming_fn", "(", "response", ")", ":", "nonlocal", "_file", ",", "chunk_size", "try", ":", "if", "_range", ":", "chunk_size", "=", "min", "(", "(", "_range", ".", "size", ",", "chunk_size", ")", ")", "await", "_file", ".", "seek", "(", "_range", ".", "start", ")", "to_send", "=", "_range", ".", "size", "while", "to_send", ">", "0", ":", "content", "=", "await", "_file", ".", "read", "(", "chunk_size", ")", "if", "len", "(", "content", ")", "<", "1", ":", "break", "to_send", "-=", "len", "(", "content", ")", "await", "response", ".", "write", "(", "content", ")", "else", ":", "while", "True", ":", "content", "=", "await", "_file", ".", "read", "(", "chunk_size", ")", "if", "len", "(", "content", ")", "<", "1", ":", "break", "await", "response", ".", "write", "(", "content", ")", "finally", ":", "await", "_file", ".", "close", "(", ")", "return", "# Returning from this fn closes the stream", "mime_type", "=", "mime_type", "or", "guess_type", "(", "filename", ")", "[", "0", "]", "or", "\"text/plain\"", "if", "_range", ":", "headers", "[", "\"Content-Range\"", "]", "=", "\"bytes %s-%s/%s\"", "%", "(", "_range", ".", "start", ",", "_range", ".", "end", ",", "_range", ".", "total", ",", ")", "status", "=", "206", "return", "StreamingHTTPResponse", "(", "streaming_fn", "=", "_streaming_fn", ",", "status", "=", "status", ",", "headers", "=", "headers", ",", "content_type", "=", "mime_type", ",", ")" ]
Return a streaming response object with file data. :param location: Location of file on system. :param chunk_size: The size of each chunk in the stream (in bytes) :param mime_type: Specific mime_type. :param headers: Custom Headers. :param filename: Override filename. :param _range:
[ "Return", "a", "streaming", "response", "object", "with", "file", "data", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L323-L386
26,619
huge-success/sanic
sanic/response.py
stream
def stream( streaming_fn, status=200, headers=None, content_type="text/plain; charset=utf-8", ): """Accepts an coroutine `streaming_fn` which can be used to write chunks to a streaming response. Returns a `StreamingHTTPResponse`. Example usage:: @app.route("/") async def index(request): async def streaming_fn(response): await response.write('foo') await response.write('bar') return stream(streaming_fn, content_type='text/plain') :param streaming_fn: A coroutine accepts a response and writes content to that response. :param mime_type: Specific mime_type. :param headers: Custom Headers. """ return StreamingHTTPResponse( streaming_fn, headers=headers, content_type=content_type, status=status )
python
def stream( streaming_fn, status=200, headers=None, content_type="text/plain; charset=utf-8", ): """Accepts an coroutine `streaming_fn` which can be used to write chunks to a streaming response. Returns a `StreamingHTTPResponse`. Example usage:: @app.route("/") async def index(request): async def streaming_fn(response): await response.write('foo') await response.write('bar') return stream(streaming_fn, content_type='text/plain') :param streaming_fn: A coroutine accepts a response and writes content to that response. :param mime_type: Specific mime_type. :param headers: Custom Headers. """ return StreamingHTTPResponse( streaming_fn, headers=headers, content_type=content_type, status=status )
[ "def", "stream", "(", "streaming_fn", ",", "status", "=", "200", ",", "headers", "=", "None", ",", "content_type", "=", "\"text/plain; charset=utf-8\"", ",", ")", ":", "return", "StreamingHTTPResponse", "(", "streaming_fn", ",", "headers", "=", "headers", ",", "content_type", "=", "content_type", ",", "status", "=", "status", ")" ]
Accepts an coroutine `streaming_fn` which can be used to write chunks to a streaming response. Returns a `StreamingHTTPResponse`. Example usage:: @app.route("/") async def index(request): async def streaming_fn(response): await response.write('foo') await response.write('bar') return stream(streaming_fn, content_type='text/plain') :param streaming_fn: A coroutine accepts a response and writes content to that response. :param mime_type: Specific mime_type. :param headers: Custom Headers.
[ "Accepts", "an", "coroutine", "streaming_fn", "which", "can", "be", "used", "to", "write", "chunks", "to", "a", "streaming", "response", ".", "Returns", "a", "StreamingHTTPResponse", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L389-L415
26,620
huge-success/sanic
sanic/response.py
StreamingHTTPResponse.write
async def write(self, data): """Writes a chunk of data to the streaming response. :param data: bytes-ish data to be written. """ if type(data) != bytes: data = self._encode_body(data) self.protocol.push_data(b"%x\r\n%b\r\n" % (len(data), data)) await self.protocol.drain()
python
async def write(self, data): """Writes a chunk of data to the streaming response. :param data: bytes-ish data to be written. """ if type(data) != bytes: data = self._encode_body(data) self.protocol.push_data(b"%x\r\n%b\r\n" % (len(data), data)) await self.protocol.drain()
[ "async", "def", "write", "(", "self", ",", "data", ")", ":", "if", "type", "(", "data", ")", "!=", "bytes", ":", "data", "=", "self", ".", "_encode_body", "(", "data", ")", "self", ".", "protocol", ".", "push_data", "(", "b\"%x\\r\\n%b\\r\\n\"", "%", "(", "len", "(", "data", ")", ",", "data", ")", ")", "await", "self", ".", "protocol", ".", "drain", "(", ")" ]
Writes a chunk of data to the streaming response. :param data: bytes-ish data to be written.
[ "Writes", "a", "chunk", "of", "data", "to", "the", "streaming", "response", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L74-L83
26,621
huge-success/sanic
sanic/response.py
StreamingHTTPResponse.stream
async def stream( self, version="1.1", keep_alive=False, keep_alive_timeout=None ): """Streams headers, runs the `streaming_fn` callback that writes content to the response body, then finalizes the response body. """ headers = self.get_headers( version, keep_alive=keep_alive, keep_alive_timeout=keep_alive_timeout, ) self.protocol.push_data(headers) await self.protocol.drain() await self.streaming_fn(self) self.protocol.push_data(b"0\r\n\r\n")
python
async def stream( self, version="1.1", keep_alive=False, keep_alive_timeout=None ): """Streams headers, runs the `streaming_fn` callback that writes content to the response body, then finalizes the response body. """ headers = self.get_headers( version, keep_alive=keep_alive, keep_alive_timeout=keep_alive_timeout, ) self.protocol.push_data(headers) await self.protocol.drain() await self.streaming_fn(self) self.protocol.push_data(b"0\r\n\r\n")
[ "async", "def", "stream", "(", "self", ",", "version", "=", "\"1.1\"", ",", "keep_alive", "=", "False", ",", "keep_alive_timeout", "=", "None", ")", ":", "headers", "=", "self", ".", "get_headers", "(", "version", ",", "keep_alive", "=", "keep_alive", ",", "keep_alive_timeout", "=", "keep_alive_timeout", ",", ")", "self", ".", "protocol", ".", "push_data", "(", "headers", ")", "await", "self", ".", "protocol", ".", "drain", "(", ")", "await", "self", ".", "streaming_fn", "(", "self", ")", "self", ".", "protocol", ".", "push_data", "(", "b\"0\\r\\n\\r\\n\"", ")" ]
Streams headers, runs the `streaming_fn` callback that writes content to the response body, then finalizes the response body.
[ "Streams", "headers", "runs", "the", "streaming_fn", "callback", "that", "writes", "content", "to", "the", "response", "body", "then", "finalizes", "the", "response", "body", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L85-L99
26,622
huge-success/sanic
sanic/blueprint_group.py
BlueprintGroup.insert
def insert(self, index: int, item: object) -> None: """ The Abstract class `MutableSequence` leverages this insert method to perform the `BlueprintGroup.append` operation. :param index: Index to use for removing a new Blueprint item :param item: New `Blueprint` object. :return: None """ self._blueprints.insert(index, item)
python
def insert(self, index: int, item: object) -> None: """ The Abstract class `MutableSequence` leverages this insert method to perform the `BlueprintGroup.append` operation. :param index: Index to use for removing a new Blueprint item :param item: New `Blueprint` object. :return: None """ self._blueprints.insert(index, item)
[ "def", "insert", "(", "self", ",", "index", ":", "int", ",", "item", ":", "object", ")", "->", "None", ":", "self", ".", "_blueprints", ".", "insert", "(", "index", ",", "item", ")" ]
The Abstract class `MutableSequence` leverages this insert method to perform the `BlueprintGroup.append` operation. :param index: Index to use for removing a new Blueprint item :param item: New `Blueprint` object. :return: None
[ "The", "Abstract", "class", "MutableSequence", "leverages", "this", "insert", "method", "to", "perform", "the", "BlueprintGroup", ".", "append", "operation", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprint_group.py#L91-L100
26,623
huge-success/sanic
sanic/blueprint_group.py
BlueprintGroup.middleware
def middleware(self, *args, **kwargs): """ A decorator that can be used to implement a Middleware plugin to all of the Blueprints that belongs to this specific Blueprint Group. In case of nested Blueprint Groups, the same middleware is applied across each of the Blueprints recursively. :param args: Optional positional Parameters to be use middleware :param kwargs: Optional Keyword arg to use with Middleware :return: Partial function to apply the middleware """ kwargs["bp_group"] = True def register_middleware_for_blueprints(fn): for blueprint in self.blueprints: blueprint.middleware(fn, *args, **kwargs) return register_middleware_for_blueprints
python
def middleware(self, *args, **kwargs): """ A decorator that can be used to implement a Middleware plugin to all of the Blueprints that belongs to this specific Blueprint Group. In case of nested Blueprint Groups, the same middleware is applied across each of the Blueprints recursively. :param args: Optional positional Parameters to be use middleware :param kwargs: Optional Keyword arg to use with Middleware :return: Partial function to apply the middleware """ kwargs["bp_group"] = True def register_middleware_for_blueprints(fn): for blueprint in self.blueprints: blueprint.middleware(fn, *args, **kwargs) return register_middleware_for_blueprints
[ "def", "middleware", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"bp_group\"", "]", "=", "True", "def", "register_middleware_for_blueprints", "(", "fn", ")", ":", "for", "blueprint", "in", "self", ".", "blueprints", ":", "blueprint", ".", "middleware", "(", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "register_middleware_for_blueprints" ]
A decorator that can be used to implement a Middleware plugin to all of the Blueprints that belongs to this specific Blueprint Group. In case of nested Blueprint Groups, the same middleware is applied across each of the Blueprints recursively. :param args: Optional positional Parameters to be use middleware :param kwargs: Optional Keyword arg to use with Middleware :return: Partial function to apply the middleware
[ "A", "decorator", "that", "can", "be", "used", "to", "implement", "a", "Middleware", "plugin", "to", "all", "of", "the", "Blueprints", "that", "belongs", "to", "this", "specific", "Blueprint", "Group", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprint_group.py#L102-L120
26,624
huge-success/sanic
sanic/server.py
HttpProtocol.keep_alive_timeout_callback
def keep_alive_timeout_callback(self): """ Check if elapsed time since last response exceeds our configured maximum keep alive timeout value and if so, close the transport pipe and let the response writer handle the error. :return: None """ time_elapsed = time() - self._last_response_time if time_elapsed < self.keep_alive_timeout: time_left = self.keep_alive_timeout - time_elapsed self._keep_alive_timeout_handler = self.loop.call_later( time_left, self.keep_alive_timeout_callback ) else: logger.debug("KeepAlive Timeout. Closing connection.") self.transport.close() self.transport = None
python
def keep_alive_timeout_callback(self): """ Check if elapsed time since last response exceeds our configured maximum keep alive timeout value and if so, close the transport pipe and let the response writer handle the error. :return: None """ time_elapsed = time() - self._last_response_time if time_elapsed < self.keep_alive_timeout: time_left = self.keep_alive_timeout - time_elapsed self._keep_alive_timeout_handler = self.loop.call_later( time_left, self.keep_alive_timeout_callback ) else: logger.debug("KeepAlive Timeout. Closing connection.") self.transport.close() self.transport = None
[ "def", "keep_alive_timeout_callback", "(", "self", ")", ":", "time_elapsed", "=", "time", "(", ")", "-", "self", ".", "_last_response_time", "if", "time_elapsed", "<", "self", ".", "keep_alive_timeout", ":", "time_left", "=", "self", ".", "keep_alive_timeout", "-", "time_elapsed", "self", ".", "_keep_alive_timeout_handler", "=", "self", ".", "loop", ".", "call_later", "(", "time_left", ",", "self", ".", "keep_alive_timeout_callback", ")", "else", ":", "logger", ".", "debug", "(", "\"KeepAlive Timeout. Closing connection.\"", ")", "self", ".", "transport", ".", "close", "(", ")", "self", ".", "transport", "=", "None" ]
Check if elapsed time since last response exceeds our configured maximum keep alive timeout value and if so, close the transport pipe and let the response writer handle the error. :return: None
[ "Check", "if", "elapsed", "time", "since", "last", "response", "exceeds", "our", "configured", "maximum", "keep", "alive", "timeout", "value", "and", "if", "so", "close", "the", "transport", "pipe", "and", "let", "the", "response", "writer", "handle", "the", "error", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L230-L247
26,625
huge-success/sanic
sanic/server.py
HttpProtocol.write_response
def write_response(self, response): """ Writes response content synchronously to the transport. """ if self._response_timeout_handler: self._response_timeout_handler.cancel() self._response_timeout_handler = None try: keep_alive = self.keep_alive self.transport.write( response.output( self.request.version, keep_alive, self.keep_alive_timeout ) ) self.log_response(response) except AttributeError: logger.error( "Invalid response object for url %s, " "Expected Type: HTTPResponse, Actual Type: %s", self.url, type(response), ) self.write_error(ServerError("Invalid response type")) except RuntimeError: if self._debug: logger.error( "Connection lost before response written @ %s", self.request.ip, ) keep_alive = False except Exception as e: self.bail_out( "Writing response failed, connection closed {}".format(repr(e)) ) finally: if not keep_alive: self.transport.close() self.transport = None else: self._keep_alive_timeout_handler = self.loop.call_later( self.keep_alive_timeout, self.keep_alive_timeout_callback ) self._last_response_time = time() self.cleanup()
python
def write_response(self, response): """ Writes response content synchronously to the transport. """ if self._response_timeout_handler: self._response_timeout_handler.cancel() self._response_timeout_handler = None try: keep_alive = self.keep_alive self.transport.write( response.output( self.request.version, keep_alive, self.keep_alive_timeout ) ) self.log_response(response) except AttributeError: logger.error( "Invalid response object for url %s, " "Expected Type: HTTPResponse, Actual Type: %s", self.url, type(response), ) self.write_error(ServerError("Invalid response type")) except RuntimeError: if self._debug: logger.error( "Connection lost before response written @ %s", self.request.ip, ) keep_alive = False except Exception as e: self.bail_out( "Writing response failed, connection closed {}".format(repr(e)) ) finally: if not keep_alive: self.transport.close() self.transport = None else: self._keep_alive_timeout_handler = self.loop.call_later( self.keep_alive_timeout, self.keep_alive_timeout_callback ) self._last_response_time = time() self.cleanup()
[ "def", "write_response", "(", "self", ",", "response", ")", ":", "if", "self", ".", "_response_timeout_handler", ":", "self", ".", "_response_timeout_handler", ".", "cancel", "(", ")", "self", ".", "_response_timeout_handler", "=", "None", "try", ":", "keep_alive", "=", "self", ".", "keep_alive", "self", ".", "transport", ".", "write", "(", "response", ".", "output", "(", "self", ".", "request", ".", "version", ",", "keep_alive", ",", "self", ".", "keep_alive_timeout", ")", ")", "self", ".", "log_response", "(", "response", ")", "except", "AttributeError", ":", "logger", ".", "error", "(", "\"Invalid response object for url %s, \"", "\"Expected Type: HTTPResponse, Actual Type: %s\"", ",", "self", ".", "url", ",", "type", "(", "response", ")", ",", ")", "self", ".", "write_error", "(", "ServerError", "(", "\"Invalid response type\"", ")", ")", "except", "RuntimeError", ":", "if", "self", ".", "_debug", ":", "logger", ".", "error", "(", "\"Connection lost before response written @ %s\"", ",", "self", ".", "request", ".", "ip", ",", ")", "keep_alive", "=", "False", "except", "Exception", "as", "e", ":", "self", ".", "bail_out", "(", "\"Writing response failed, connection closed {}\"", ".", "format", "(", "repr", "(", "e", ")", ")", ")", "finally", ":", "if", "not", "keep_alive", ":", "self", ".", "transport", ".", "close", "(", ")", "self", ".", "transport", "=", "None", "else", ":", "self", ".", "_keep_alive_timeout_handler", "=", "self", ".", "loop", ".", "call_later", "(", "self", ".", "keep_alive_timeout", ",", "self", ".", "keep_alive_timeout_callback", ")", "self", ".", "_last_response_time", "=", "time", "(", ")", "self", ".", "cleanup", "(", ")" ]
Writes response content synchronously to the transport.
[ "Writes", "response", "content", "synchronously", "to", "the", "transport", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L412-L455
26,626
huge-success/sanic
sanic/server.py
HttpProtocol.bail_out
def bail_out(self, message, from_error=False): """ In case if the transport pipes are closed and the sanic app encounters an error while writing data to the transport pipe, we log the error with proper details. :param message: Error message to display :param from_error: If the bail out was invoked while handling an exception scenario. :type message: str :type from_error: bool :return: None """ if from_error or self.transport is None or self.transport.is_closing(): logger.error( "Transport closed @ %s and exception " "experienced during error handling", ( self.transport.get_extra_info("peername") if self.transport is not None else "N/A" ), ) logger.debug("Exception:", exc_info=True) else: self.write_error(ServerError(message)) logger.error(message)
python
def bail_out(self, message, from_error=False): """ In case if the transport pipes are closed and the sanic app encounters an error while writing data to the transport pipe, we log the error with proper details. :param message: Error message to display :param from_error: If the bail out was invoked while handling an exception scenario. :type message: str :type from_error: bool :return: None """ if from_error or self.transport is None or self.transport.is_closing(): logger.error( "Transport closed @ %s and exception " "experienced during error handling", ( self.transport.get_extra_info("peername") if self.transport is not None else "N/A" ), ) logger.debug("Exception:", exc_info=True) else: self.write_error(ServerError(message)) logger.error(message)
[ "def", "bail_out", "(", "self", ",", "message", ",", "from_error", "=", "False", ")", ":", "if", "from_error", "or", "self", ".", "transport", "is", "None", "or", "self", ".", "transport", ".", "is_closing", "(", ")", ":", "logger", ".", "error", "(", "\"Transport closed @ %s and exception \"", "\"experienced during error handling\"", ",", "(", "self", ".", "transport", ".", "get_extra_info", "(", "\"peername\"", ")", "if", "self", ".", "transport", "is", "not", "None", "else", "\"N/A\"", ")", ",", ")", "logger", ".", "debug", "(", "\"Exception:\"", ",", "exc_info", "=", "True", ")", "else", ":", "self", ".", "write_error", "(", "ServerError", "(", "message", ")", ")", "logger", ".", "error", "(", "message", ")" ]
In case if the transport pipes are closed and the sanic app encounters an error while writing data to the transport pipe, we log the error with proper details. :param message: Error message to display :param from_error: If the bail out was invoked while handling an exception scenario. :type message: str :type from_error: bool :return: None
[ "In", "case", "if", "the", "transport", "pipes", "are", "closed", "and", "the", "sanic", "app", "encounters", "an", "error", "while", "writing", "data", "to", "the", "transport", "pipe", "we", "log", "the", "error", "with", "proper", "details", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L542-L570
26,627
huge-success/sanic
sanic/server.py
HttpProtocol.cleanup
def cleanup(self): """This is called when KeepAlive feature is used, it resets the connection in order for it to be able to handle receiving another request on the same connection.""" self.parser = None self.request = None self.url = None self.headers = None self._request_handler_task = None self._request_stream_task = None self._total_request_size = 0 self._is_stream_handler = False
python
def cleanup(self): """This is called when KeepAlive feature is used, it resets the connection in order for it to be able to handle receiving another request on the same connection.""" self.parser = None self.request = None self.url = None self.headers = None self._request_handler_task = None self._request_stream_task = None self._total_request_size = 0 self._is_stream_handler = False
[ "def", "cleanup", "(", "self", ")", ":", "self", ".", "parser", "=", "None", "self", ".", "request", "=", "None", "self", ".", "url", "=", "None", "self", ".", "headers", "=", "None", "self", ".", "_request_handler_task", "=", "None", "self", ".", "_request_stream_task", "=", "None", "self", ".", "_total_request_size", "=", "0", "self", ".", "_is_stream_handler", "=", "False" ]
This is called when KeepAlive feature is used, it resets the connection in order for it to be able to handle receiving another request on the same connection.
[ "This", "is", "called", "when", "KeepAlive", "feature", "is", "used", "it", "resets", "the", "connection", "in", "order", "for", "it", "to", "be", "able", "to", "handle", "receiving", "another", "request", "on", "the", "same", "connection", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L572-L583
26,628
huge-success/sanic
sanic/request.py
StreamBuffer.read
async def read(self): """ Stop reading when gets None """ payload = await self._queue.get() self._queue.task_done() return payload
python
async def read(self): """ Stop reading when gets None """ payload = await self._queue.get() self._queue.task_done() return payload
[ "async", "def", "read", "(", "self", ")", ":", "payload", "=", "await", "self", ".", "_queue", ".", "get", "(", ")", "self", ".", "_queue", ".", "task_done", "(", ")", "return", "payload" ]
Stop reading when gets None
[ "Stop", "reading", "when", "gets", "None" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L57-L61
26,629
huge-success/sanic
sanic/request.py
Request.remote_addr
def remote_addr(self): """Attempt to return the original client ip based on X-Forwarded-For or X-Real-IP. If HTTP headers are unavailable or untrusted, returns an empty string. :return: original client ip. """ if not hasattr(self, "_remote_addr"): if self.app.config.PROXIES_COUNT == 0: self._remote_addr = "" elif self.app.config.REAL_IP_HEADER and self.headers.get( self.app.config.REAL_IP_HEADER ): self._remote_addr = self.headers[ self.app.config.REAL_IP_HEADER ] elif self.app.config.FORWARDED_FOR_HEADER: forwarded_for = self.headers.get( self.app.config.FORWARDED_FOR_HEADER, "" ).split(",") remote_addrs = [ addr for addr in [addr.strip() for addr in forwarded_for] if addr ] if self.app.config.PROXIES_COUNT == -1: self._remote_addr = remote_addrs[0] elif len(remote_addrs) >= self.app.config.PROXIES_COUNT: self._remote_addr = remote_addrs[ -self.app.config.PROXIES_COUNT ] else: self._remote_addr = "" else: self._remote_addr = "" return self._remote_addr
python
def remote_addr(self): """Attempt to return the original client ip based on X-Forwarded-For or X-Real-IP. If HTTP headers are unavailable or untrusted, returns an empty string. :return: original client ip. """ if not hasattr(self, "_remote_addr"): if self.app.config.PROXIES_COUNT == 0: self._remote_addr = "" elif self.app.config.REAL_IP_HEADER and self.headers.get( self.app.config.REAL_IP_HEADER ): self._remote_addr = self.headers[ self.app.config.REAL_IP_HEADER ] elif self.app.config.FORWARDED_FOR_HEADER: forwarded_for = self.headers.get( self.app.config.FORWARDED_FOR_HEADER, "" ).split(",") remote_addrs = [ addr for addr in [addr.strip() for addr in forwarded_for] if addr ] if self.app.config.PROXIES_COUNT == -1: self._remote_addr = remote_addrs[0] elif len(remote_addrs) >= self.app.config.PROXIES_COUNT: self._remote_addr = remote_addrs[ -self.app.config.PROXIES_COUNT ] else: self._remote_addr = "" else: self._remote_addr = "" return self._remote_addr
[ "def", "remote_addr", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_remote_addr\"", ")", ":", "if", "self", ".", "app", ".", "config", ".", "PROXIES_COUNT", "==", "0", ":", "self", ".", "_remote_addr", "=", "\"\"", "elif", "self", ".", "app", ".", "config", ".", "REAL_IP_HEADER", "and", "self", ".", "headers", ".", "get", "(", "self", ".", "app", ".", "config", ".", "REAL_IP_HEADER", ")", ":", "self", ".", "_remote_addr", "=", "self", ".", "headers", "[", "self", ".", "app", ".", "config", ".", "REAL_IP_HEADER", "]", "elif", "self", ".", "app", ".", "config", ".", "FORWARDED_FOR_HEADER", ":", "forwarded_for", "=", "self", ".", "headers", ".", "get", "(", "self", ".", "app", ".", "config", ".", "FORWARDED_FOR_HEADER", ",", "\"\"", ")", ".", "split", "(", "\",\"", ")", "remote_addrs", "=", "[", "addr", "for", "addr", "in", "[", "addr", ".", "strip", "(", ")", "for", "addr", "in", "forwarded_for", "]", "if", "addr", "]", "if", "self", ".", "app", ".", "config", ".", "PROXIES_COUNT", "==", "-", "1", ":", "self", ".", "_remote_addr", "=", "remote_addrs", "[", "0", "]", "elif", "len", "(", "remote_addrs", ")", ">=", "self", ".", "app", ".", "config", ".", "PROXIES_COUNT", ":", "self", ".", "_remote_addr", "=", "remote_addrs", "[", "-", "self", ".", "app", ".", "config", ".", "PROXIES_COUNT", "]", "else", ":", "self", ".", "_remote_addr", "=", "\"\"", "else", ":", "self", ".", "_remote_addr", "=", "\"\"", "return", "self", ".", "_remote_addr" ]
Attempt to return the original client ip based on X-Forwarded-For or X-Real-IP. If HTTP headers are unavailable or untrusted, returns an empty string. :return: original client ip.
[ "Attempt", "to", "return", "the", "original", "client", "ip", "based", "on", "X", "-", "Forwarded", "-", "For", "or", "X", "-", "Real", "-", "IP", ".", "If", "HTTP", "headers", "are", "unavailable", "or", "untrusted", "returns", "an", "empty", "string", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L357-L392
26,630
huge-success/sanic
sanic/config.py
strtobool
def strtobool(val): """ This function was borrowed from distutils.utils. While distutils is part of stdlib, it feels odd to use distutils in main application code. The function was modified to walk its talk and actually return bool and not int. """ val = val.lower() if val in ("y", "yes", "t", "true", "on", "1"): return True elif val in ("n", "no", "f", "false", "off", "0"): return False else: raise ValueError("invalid truth value %r" % (val,))
python
def strtobool(val): """ This function was borrowed from distutils.utils. While distutils is part of stdlib, it feels odd to use distutils in main application code. The function was modified to walk its talk and actually return bool and not int. """ val = val.lower() if val in ("y", "yes", "t", "true", "on", "1"): return True elif val in ("n", "no", "f", "false", "off", "0"): return False else: raise ValueError("invalid truth value %r" % (val,))
[ "def", "strtobool", "(", "val", ")", ":", "val", "=", "val", ".", "lower", "(", ")", "if", "val", "in", "(", "\"y\"", ",", "\"yes\"", ",", "\"t\"", ",", "\"true\"", ",", "\"on\"", ",", "\"1\"", ")", ":", "return", "True", "elif", "val", "in", "(", "\"n\"", ",", "\"no\"", ",", "\"f\"", ",", "\"false\"", ",", "\"off\"", ",", "\"0\"", ")", ":", "return", "False", "else", ":", "raise", "ValueError", "(", "\"invalid truth value %r\"", "%", "(", "val", ",", ")", ")" ]
This function was borrowed from distutils.utils. While distutils is part of stdlib, it feels odd to use distutils in main application code. The function was modified to walk its talk and actually return bool and not int.
[ "This", "function", "was", "borrowed", "from", "distutils", ".", "utils", ".", "While", "distutils", "is", "part", "of", "stdlib", "it", "feels", "odd", "to", "use", "distutils", "in", "main", "application", "code", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L136-L150
26,631
huge-success/sanic
sanic/config.py
Config.from_envvar
def from_envvar(self, variable_name): """Load a configuration from an environment variable pointing to a configuration file. :param variable_name: name of the environment variable :return: bool. ``True`` if able to load config, ``False`` otherwise. """ config_file = os.environ.get(variable_name) if not config_file: raise RuntimeError( "The environment variable %r is not set and " "thus configuration could not be loaded." % variable_name ) return self.from_pyfile(config_file)
python
def from_envvar(self, variable_name): """Load a configuration from an environment variable pointing to a configuration file. :param variable_name: name of the environment variable :return: bool. ``True`` if able to load config, ``False`` otherwise. """ config_file = os.environ.get(variable_name) if not config_file: raise RuntimeError( "The environment variable %r is not set and " "thus configuration could not be loaded." % variable_name ) return self.from_pyfile(config_file)
[ "def", "from_envvar", "(", "self", ",", "variable_name", ")", ":", "config_file", "=", "os", ".", "environ", ".", "get", "(", "variable_name", ")", "if", "not", "config_file", ":", "raise", "RuntimeError", "(", "\"The environment variable %r is not set and \"", "\"thus configuration could not be loaded.\"", "%", "variable_name", ")", "return", "self", ".", "from_pyfile", "(", "config_file", ")" ]
Load a configuration from an environment variable pointing to a configuration file. :param variable_name: name of the environment variable :return: bool. ``True`` if able to load config, ``False`` otherwise.
[ "Load", "a", "configuration", "from", "an", "environment", "variable", "pointing", "to", "a", "configuration", "file", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L57-L70
26,632
huge-success/sanic
sanic/config.py
Config.from_object
def from_object(self, obj): """Update the values from the given object. Objects are usually either modules or classes. Just the uppercase variables in that object are stored in the config. Example usage:: from yourapplication import default_config app.config.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. :param obj: an object holding the configuration """ for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key)
python
def from_object(self, obj): """Update the values from the given object. Objects are usually either modules or classes. Just the uppercase variables in that object are stored in the config. Example usage:: from yourapplication import default_config app.config.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. :param obj: an object holding the configuration """ for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key)
[ "def", "from_object", "(", "self", ",", "obj", ")", ":", "for", "key", "in", "dir", "(", "obj", ")", ":", "if", "key", ".", "isupper", "(", ")", ":", "self", "[", "key", "]", "=", "getattr", "(", "obj", ",", "key", ")" ]
Update the values from the given object. Objects are usually either modules or classes. Just the uppercase variables in that object are stored in the config. Example usage:: from yourapplication import default_config app.config.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. :param obj: an object holding the configuration
[ "Update", "the", "values", "from", "the", "given", "object", ".", "Objects", "are", "usually", "either", "modules", "or", "classes", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L95-L114
26,633
huge-success/sanic
sanic/config.py
Config.load_environment_vars
def load_environment_vars(self, prefix=SANIC_PREFIX): """ Looks for prefixed environment variables and applies them to the configuration if present. """ for k, v in os.environ.items(): if k.startswith(prefix): _, config_key = k.split(prefix, 1) try: self[config_key] = int(v) except ValueError: try: self[config_key] = float(v) except ValueError: try: self[config_key] = strtobool(v) except ValueError: self[config_key] = v
python
def load_environment_vars(self, prefix=SANIC_PREFIX): """ Looks for prefixed environment variables and applies them to the configuration if present. """ for k, v in os.environ.items(): if k.startswith(prefix): _, config_key = k.split(prefix, 1) try: self[config_key] = int(v) except ValueError: try: self[config_key] = float(v) except ValueError: try: self[config_key] = strtobool(v) except ValueError: self[config_key] = v
[ "def", "load_environment_vars", "(", "self", ",", "prefix", "=", "SANIC_PREFIX", ")", ":", "for", "k", ",", "v", "in", "os", ".", "environ", ".", "items", "(", ")", ":", "if", "k", ".", "startswith", "(", "prefix", ")", ":", "_", ",", "config_key", "=", "k", ".", "split", "(", "prefix", ",", "1", ")", "try", ":", "self", "[", "config_key", "]", "=", "int", "(", "v", ")", "except", "ValueError", ":", "try", ":", "self", "[", "config_key", "]", "=", "float", "(", "v", ")", "except", "ValueError", ":", "try", ":", "self", "[", "config_key", "]", "=", "strtobool", "(", "v", ")", "except", "ValueError", ":", "self", "[", "config_key", "]", "=", "v" ]
Looks for prefixed environment variables and applies them to the configuration if present.
[ "Looks", "for", "prefixed", "environment", "variables", "and", "applies", "them", "to", "the", "configuration", "if", "present", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L116-L133
26,634
huge-success/sanic
sanic/router.py
Router.parse_parameter_string
def parse_parameter_string(cls, parameter_string): """Parse a parameter string into its constituent name, type, and pattern For example:: parse_parameter_string('<param_one:[A-z]>')` -> ('param_one', str, '[A-z]') :param parameter_string: String to parse :return: tuple containing (parameter_name, parameter_type, parameter_pattern) """ # We could receive NAME or NAME:PATTERN name = parameter_string pattern = "string" if ":" in parameter_string: name, pattern = parameter_string.split(":", 1) if not name: raise ValueError( "Invalid parameter syntax: {}".format(parameter_string) ) default = (str, pattern) # Pull from pre-configured types _type, pattern = REGEX_TYPES.get(pattern, default) return name, _type, pattern
python
def parse_parameter_string(cls, parameter_string): """Parse a parameter string into its constituent name, type, and pattern For example:: parse_parameter_string('<param_one:[A-z]>')` -> ('param_one', str, '[A-z]') :param parameter_string: String to parse :return: tuple containing (parameter_name, parameter_type, parameter_pattern) """ # We could receive NAME or NAME:PATTERN name = parameter_string pattern = "string" if ":" in parameter_string: name, pattern = parameter_string.split(":", 1) if not name: raise ValueError( "Invalid parameter syntax: {}".format(parameter_string) ) default = (str, pattern) # Pull from pre-configured types _type, pattern = REGEX_TYPES.get(pattern, default) return name, _type, pattern
[ "def", "parse_parameter_string", "(", "cls", ",", "parameter_string", ")", ":", "# We could receive NAME or NAME:PATTERN", "name", "=", "parameter_string", "pattern", "=", "\"string\"", "if", "\":\"", "in", "parameter_string", ":", "name", ",", "pattern", "=", "parameter_string", ".", "split", "(", "\":\"", ",", "1", ")", "if", "not", "name", ":", "raise", "ValueError", "(", "\"Invalid parameter syntax: {}\"", ".", "format", "(", "parameter_string", ")", ")", "default", "=", "(", "str", ",", "pattern", ")", "# Pull from pre-configured types", "_type", ",", "pattern", "=", "REGEX_TYPES", ".", "get", "(", "pattern", ",", "default", ")", "return", "name", ",", "_type", ",", "pattern" ]
Parse a parameter string into its constituent name, type, and pattern For example:: parse_parameter_string('<param_one:[A-z]>')` -> ('param_one', str, '[A-z]') :param parameter_string: String to parse :return: tuple containing (parameter_name, parameter_type, parameter_pattern)
[ "Parse", "a", "parameter", "string", "into", "its", "constituent", "name", "type", "and", "pattern" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L92-L119
26,635
huge-success/sanic
sanic/router.py
Router.check_dynamic_route_exists
def check_dynamic_route_exists(pattern, routes_to_check, parameters): """ Check if a URL pattern exists in a list of routes provided based on the comparison of URL pattern and the parameters. :param pattern: URL parameter pattern :param routes_to_check: list of dynamic routes either hashable or unhashable routes. :param parameters: List of :class:`Parameter` items :return: Tuple of index and route if matching route exists else -1 for index and None for route """ for ndx, route in enumerate(routes_to_check): if route.pattern == pattern and route.parameters == parameters: return ndx, route else: return -1, None
python
def check_dynamic_route_exists(pattern, routes_to_check, parameters): """ Check if a URL pattern exists in a list of routes provided based on the comparison of URL pattern and the parameters. :param pattern: URL parameter pattern :param routes_to_check: list of dynamic routes either hashable or unhashable routes. :param parameters: List of :class:`Parameter` items :return: Tuple of index and route if matching route exists else -1 for index and None for route """ for ndx, route in enumerate(routes_to_check): if route.pattern == pattern and route.parameters == parameters: return ndx, route else: return -1, None
[ "def", "check_dynamic_route_exists", "(", "pattern", ",", "routes_to_check", ",", "parameters", ")", ":", "for", "ndx", ",", "route", "in", "enumerate", "(", "routes_to_check", ")", ":", "if", "route", ".", "pattern", "==", "pattern", "and", "route", ".", "parameters", "==", "parameters", ":", "return", "ndx", ",", "route", "else", ":", "return", "-", "1", ",", "None" ]
Check if a URL pattern exists in a list of routes provided based on the comparison of URL pattern and the parameters. :param pattern: URL parameter pattern :param routes_to_check: list of dynamic routes either hashable or unhashable routes. :param parameters: List of :class:`Parameter` items :return: Tuple of index and route if matching route exists else -1 for index and None for route
[ "Check", "if", "a", "URL", "pattern", "exists", "in", "a", "list", "of", "routes", "provided", "based", "on", "the", "comparison", "of", "URL", "pattern", "and", "the", "parameters", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L333-L349
26,636
huge-success/sanic
sanic/router.py
Router.get
def get(self, request): """Get a request handler based on the URL of the request, or raises an error :param request: Request object :return: handler, arguments, keyword arguments """ # No virtual hosts specified; default behavior if not self.hosts: return self._get(request.path, request.method, "") # virtual hosts specified; try to match route to the host header try: return self._get( request.path, request.method, request.headers.get("Host", "") ) # try default hosts except NotFound: return self._get(request.path, request.method, "")
python
def get(self, request): """Get a request handler based on the URL of the request, or raises an error :param request: Request object :return: handler, arguments, keyword arguments """ # No virtual hosts specified; default behavior if not self.hosts: return self._get(request.path, request.method, "") # virtual hosts specified; try to match route to the host header try: return self._get( request.path, request.method, request.headers.get("Host", "") ) # try default hosts except NotFound: return self._get(request.path, request.method, "")
[ "def", "get", "(", "self", ",", "request", ")", ":", "# No virtual hosts specified; default behavior", "if", "not", "self", ".", "hosts", ":", "return", "self", ".", "_get", "(", "request", ".", "path", ",", "request", ".", "method", ",", "\"\"", ")", "# virtual hosts specified; try to match route to the host header", "try", ":", "return", "self", ".", "_get", "(", "request", ".", "path", ",", "request", ".", "method", ",", "request", ".", "headers", ".", "get", "(", "\"Host\"", ",", "\"\"", ")", ")", "# try default hosts", "except", "NotFound", ":", "return", "self", ".", "_get", "(", "request", ".", "path", ",", "request", ".", "method", ",", "\"\"", ")" ]
Get a request handler based on the URL of the request, or raises an error :param request: Request object :return: handler, arguments, keyword arguments
[ "Get", "a", "request", "handler", "based", "on", "the", "URL", "of", "the", "request", "or", "raises", "an", "error" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L398-L415
26,637
huge-success/sanic
sanic/router.py
Router.get_supported_methods
def get_supported_methods(self, url): """Get a list of supported methods for a url and optional host. :param url: URL string (including host) :return: frozenset of supported methods """ route = self.routes_all.get(url) # if methods are None then this logic will prevent an error return getattr(route, "methods", None) or frozenset()
python
def get_supported_methods(self, url): """Get a list of supported methods for a url and optional host. :param url: URL string (including host) :return: frozenset of supported methods """ route = self.routes_all.get(url) # if methods are None then this logic will prevent an error return getattr(route, "methods", None) or frozenset()
[ "def", "get_supported_methods", "(", "self", ",", "url", ")", ":", "route", "=", "self", ".", "routes_all", ".", "get", "(", "url", ")", "# if methods are None then this logic will prevent an error", "return", "getattr", "(", "route", ",", "\"methods\"", ",", "None", ")", "or", "frozenset", "(", ")" ]
Get a list of supported methods for a url and optional host. :param url: URL string (including host) :return: frozenset of supported methods
[ "Get", "a", "list", "of", "supported", "methods", "for", "a", "url", "and", "optional", "host", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L417-L425
26,638
huge-success/sanic
sanic/reloader_helpers.py
_get_args_for_reloading
def _get_args_for_reloading(): """Returns the executable.""" rv = [sys.executable] main_module = sys.modules["__main__"] mod_spec = getattr(main_module, "__spec__", None) if mod_spec: # Parent exe was launched as a module rather than a script rv.extend(["-m", mod_spec.name]) if len(sys.argv) > 1: rv.extend(sys.argv[1:]) else: rv.extend(sys.argv) return rv
python
def _get_args_for_reloading(): """Returns the executable.""" rv = [sys.executable] main_module = sys.modules["__main__"] mod_spec = getattr(main_module, "__spec__", None) if mod_spec: # Parent exe was launched as a module rather than a script rv.extend(["-m", mod_spec.name]) if len(sys.argv) > 1: rv.extend(sys.argv[1:]) else: rv.extend(sys.argv) return rv
[ "def", "_get_args_for_reloading", "(", ")", ":", "rv", "=", "[", "sys", ".", "executable", "]", "main_module", "=", "sys", ".", "modules", "[", "\"__main__\"", "]", "mod_spec", "=", "getattr", "(", "main_module", ",", "\"__spec__\"", ",", "None", ")", "if", "mod_spec", ":", "# Parent exe was launched as a module rather than a script", "rv", ".", "extend", "(", "[", "\"-m\"", ",", "mod_spec", ".", "name", "]", ")", "if", "len", "(", "sys", ".", "argv", ")", ">", "1", ":", "rv", ".", "extend", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "else", ":", "rv", ".", "extend", "(", "sys", ".", "argv", ")", "return", "rv" ]
Returns the executable.
[ "Returns", "the", "executable", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L36-L48
26,639
huge-success/sanic
sanic/reloader_helpers.py
restart_with_reloader
def restart_with_reloader(): """Create a new process and a subprocess in it with the same arguments as this one. """ cwd = os.getcwd() args = _get_args_for_reloading() new_environ = os.environ.copy() new_environ["SANIC_SERVER_RUNNING"] = "true" cmd = " ".join(args) worker_process = Process( target=subprocess.call, args=(cmd,), kwargs={"cwd": cwd, "shell": True, "env": new_environ}, ) worker_process.start() return worker_process
python
def restart_with_reloader(): """Create a new process and a subprocess in it with the same arguments as this one. """ cwd = os.getcwd() args = _get_args_for_reloading() new_environ = os.environ.copy() new_environ["SANIC_SERVER_RUNNING"] = "true" cmd = " ".join(args) worker_process = Process( target=subprocess.call, args=(cmd,), kwargs={"cwd": cwd, "shell": True, "env": new_environ}, ) worker_process.start() return worker_process
[ "def", "restart_with_reloader", "(", ")", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "args", "=", "_get_args_for_reloading", "(", ")", "new_environ", "=", "os", ".", "environ", ".", "copy", "(", ")", "new_environ", "[", "\"SANIC_SERVER_RUNNING\"", "]", "=", "\"true\"", "cmd", "=", "\" \"", ".", "join", "(", "args", ")", "worker_process", "=", "Process", "(", "target", "=", "subprocess", ".", "call", ",", "args", "=", "(", "cmd", ",", ")", ",", "kwargs", "=", "{", "\"cwd\"", ":", "cwd", ",", "\"shell\"", ":", "True", ",", "\"env\"", ":", "new_environ", "}", ",", ")", "worker_process", ".", "start", "(", ")", "return", "worker_process" ]
Create a new process and a subprocess in it with the same arguments as this one.
[ "Create", "a", "new", "process", "and", "a", "subprocess", "in", "it", "with", "the", "same", "arguments", "as", "this", "one", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L51-L66
26,640
huge-success/sanic
sanic/reloader_helpers.py
kill_process_children
def kill_process_children(pid): """Find and kill child processes of a process. :param pid: PID of parent process (process ID) :return: Nothing """ if sys.platform == "darwin": kill_process_children_osx(pid) elif sys.platform == "linux": kill_process_children_unix(pid) else: pass
python
def kill_process_children(pid): """Find and kill child processes of a process. :param pid: PID of parent process (process ID) :return: Nothing """ if sys.platform == "darwin": kill_process_children_osx(pid) elif sys.platform == "linux": kill_process_children_unix(pid) else: pass
[ "def", "kill_process_children", "(", "pid", ")", ":", "if", "sys", ".", "platform", "==", "\"darwin\"", ":", "kill_process_children_osx", "(", "pid", ")", "elif", "sys", ".", "platform", "==", "\"linux\"", ":", "kill_process_children_unix", "(", "pid", ")", "else", ":", "pass" ]
Find and kill child processes of a process. :param pid: PID of parent process (process ID) :return: Nothing
[ "Find", "and", "kill", "child", "processes", "of", "a", "process", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L110-L121
26,641
huge-success/sanic
sanic/reloader_helpers.py
watchdog
def watchdog(sleep_interval): """Watch project files, restart worker process if a change happened. :param sleep_interval: interval in second. :return: Nothing """ mtimes = {} worker_process = restart_with_reloader() signal.signal( signal.SIGTERM, lambda *args: kill_program_completly(worker_process) ) signal.signal( signal.SIGINT, lambda *args: kill_program_completly(worker_process) ) while True: for filename in _iter_module_files(): try: mtime = os.stat(filename).st_mtime except OSError: continue old_time = mtimes.get(filename) if old_time is None: mtimes[filename] = mtime continue elif mtime > old_time: kill_process_children(worker_process.pid) worker_process.terminate() worker_process = restart_with_reloader() mtimes[filename] = mtime break sleep(sleep_interval)
python
def watchdog(sleep_interval): """Watch project files, restart worker process if a change happened. :param sleep_interval: interval in second. :return: Nothing """ mtimes = {} worker_process = restart_with_reloader() signal.signal( signal.SIGTERM, lambda *args: kill_program_completly(worker_process) ) signal.signal( signal.SIGINT, lambda *args: kill_program_completly(worker_process) ) while True: for filename in _iter_module_files(): try: mtime = os.stat(filename).st_mtime except OSError: continue old_time = mtimes.get(filename) if old_time is None: mtimes[filename] = mtime continue elif mtime > old_time: kill_process_children(worker_process.pid) worker_process.terminate() worker_process = restart_with_reloader() mtimes[filename] = mtime break sleep(sleep_interval)
[ "def", "watchdog", "(", "sleep_interval", ")", ":", "mtimes", "=", "{", "}", "worker_process", "=", "restart_with_reloader", "(", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "lambda", "*", "args", ":", "kill_program_completly", "(", "worker_process", ")", ")", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "lambda", "*", "args", ":", "kill_program_completly", "(", "worker_process", ")", ")", "while", "True", ":", "for", "filename", "in", "_iter_module_files", "(", ")", ":", "try", ":", "mtime", "=", "os", ".", "stat", "(", "filename", ")", ".", "st_mtime", "except", "OSError", ":", "continue", "old_time", "=", "mtimes", ".", "get", "(", "filename", ")", "if", "old_time", "is", "None", ":", "mtimes", "[", "filename", "]", "=", "mtime", "continue", "elif", "mtime", ">", "old_time", ":", "kill_process_children", "(", "worker_process", ".", "pid", ")", "worker_process", ".", "terminate", "(", ")", "worker_process", "=", "restart_with_reloader", "(", ")", "mtimes", "[", "filename", "]", "=", "mtime", "break", "sleep", "(", "sleep_interval", ")" ]
Watch project files, restart worker process if a change happened. :param sleep_interval: interval in second. :return: Nothing
[ "Watch", "project", "files", "restart", "worker", "process", "if", "a", "change", "happened", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L135-L167
26,642
huge-success/sanic
sanic/views.py
HTTPMethodView.as_view
def as_view(cls, *class_args, **class_kwargs): """Return view function for use with the routing system, that dispatches request to appropriate handler method. """ def view(*args, **kwargs): self = view.view_class(*class_args, **class_kwargs) return self.dispatch_request(*args, **kwargs) if cls.decorators: view.__module__ = cls.__module__ for decorator in cls.decorators: view = decorator(view) view.view_class = cls view.__doc__ = cls.__doc__ view.__module__ = cls.__module__ view.__name__ = cls.__name__ return view
python
def as_view(cls, *class_args, **class_kwargs): """Return view function for use with the routing system, that dispatches request to appropriate handler method. """ def view(*args, **kwargs): self = view.view_class(*class_args, **class_kwargs) return self.dispatch_request(*args, **kwargs) if cls.decorators: view.__module__ = cls.__module__ for decorator in cls.decorators: view = decorator(view) view.view_class = cls view.__doc__ = cls.__doc__ view.__module__ = cls.__module__ view.__name__ = cls.__name__ return view
[ "def", "as_view", "(", "cls", ",", "*", "class_args", ",", "*", "*", "class_kwargs", ")", ":", "def", "view", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "view", ".", "view_class", "(", "*", "class_args", ",", "*", "*", "class_kwargs", ")", "return", "self", ".", "dispatch_request", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "cls", ".", "decorators", ":", "view", ".", "__module__", "=", "cls", ".", "__module__", "for", "decorator", "in", "cls", ".", "decorators", ":", "view", "=", "decorator", "(", "view", ")", "view", ".", "view_class", "=", "cls", "view", ".", "__doc__", "=", "cls", ".", "__doc__", "view", ".", "__module__", "=", "cls", ".", "__module__", "view", ".", "__name__", "=", "cls", ".", "__name__", "return", "view" ]
Return view function for use with the routing system, that dispatches request to appropriate handler method.
[ "Return", "view", "function", "for", "use", "with", "the", "routing", "system", "that", "dispatches", "request", "to", "appropriate", "handler", "method", "." ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/views.py#L47-L65
26,643
huge-success/sanic
examples/limit_concurrency.py
bounded_fetch
async def bounded_fetch(session, url): """ Use session object to perform 'get' request on url """ async with sem, session.get(url) as response: return await response.json()
python
async def bounded_fetch(session, url): """ Use session object to perform 'get' request on url """ async with sem, session.get(url) as response: return await response.json()
[ "async", "def", "bounded_fetch", "(", "session", ",", "url", ")", ":", "async", "with", "sem", ",", "session", ".", "get", "(", "url", ")", "as", "response", ":", "return", "await", "response", ".", "json", "(", ")" ]
Use session object to perform 'get' request on url
[ "Use", "session", "object", "to", "perform", "get", "request", "on", "url" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/examples/limit_concurrency.py#L18-L23
26,644
albu/albumentations
albumentations/augmentations/functional.py
preserve_shape
def preserve_shape(func): """Preserve shape of the image.""" @wraps(func) def wrapped_function(img, *args, **kwargs): shape = img.shape result = func(img, *args, **kwargs) result = result.reshape(shape) return result return wrapped_function
python
def preserve_shape(func): """Preserve shape of the image.""" @wraps(func) def wrapped_function(img, *args, **kwargs): shape = img.shape result = func(img, *args, **kwargs) result = result.reshape(shape) return result return wrapped_function
[ "def", "preserve_shape", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped_function", "(", "img", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "shape", "=", "img", ".", "shape", "result", "=", "func", "(", "img", ",", "*", "args", ",", "*", "*", "kwargs", ")", "result", "=", "result", ".", "reshape", "(", "shape", ")", "return", "result", "return", "wrapped_function" ]
Preserve shape of the image.
[ "Preserve", "shape", "of", "the", "image", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L35-L44
26,645
albu/albumentations
albumentations/augmentations/functional.py
preserve_channel_dim
def preserve_channel_dim(func): """Preserve dummy channel dim.""" @wraps(func) def wrapped_function(img, *args, **kwargs): shape = img.shape result = func(img, *args, **kwargs) if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2: result = np.expand_dims(result, axis=-1) return result return wrapped_function
python
def preserve_channel_dim(func): """Preserve dummy channel dim.""" @wraps(func) def wrapped_function(img, *args, **kwargs): shape = img.shape result = func(img, *args, **kwargs) if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2: result = np.expand_dims(result, axis=-1) return result return wrapped_function
[ "def", "preserve_channel_dim", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped_function", "(", "img", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "shape", "=", "img", ".", "shape", "result", "=", "func", "(", "img", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "len", "(", "shape", ")", "==", "3", "and", "shape", "[", "-", "1", "]", "==", "1", "and", "len", "(", "result", ".", "shape", ")", "==", "2", ":", "result", "=", "np", ".", "expand_dims", "(", "result", ",", "axis", "=", "-", "1", ")", "return", "result", "return", "wrapped_function" ]
Preserve dummy channel dim.
[ "Preserve", "dummy", "channel", "dim", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L47-L57
26,646
albu/albumentations
albumentations/augmentations/functional.py
add_snow
def add_snow(img, snow_point, brightness_coeff): """Bleaches out pixels, mitation snow. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img: snow_point: brightness_coeff: Returns: """ non_rgb_warning(img) input_dtype = img.dtype needs_float = False snow_point *= 127.5 # = 255 / 2 snow_point += 85 # = 255 / 3 if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSnow augmentation'.format(input_dtype)) image_HLS = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) image_HLS = np.array(image_HLS, dtype=np.float32) image_HLS[:, :, 1][image_HLS[:, :, 1] < snow_point] *= brightness_coeff image_HLS[:, :, 1] = clip(image_HLS[:, :, 1], np.uint8, 255) image_HLS = np.array(image_HLS, dtype=np.uint8) image_RGB = cv2.cvtColor(image_HLS, cv2.COLOR_HLS2RGB) if needs_float: image_RGB = to_float(image_RGB, max_value=255) return image_RGB
python
def add_snow(img, snow_point, brightness_coeff): """Bleaches out pixels, mitation snow. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img: snow_point: brightness_coeff: Returns: """ non_rgb_warning(img) input_dtype = img.dtype needs_float = False snow_point *= 127.5 # = 255 / 2 snow_point += 85 # = 255 / 3 if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSnow augmentation'.format(input_dtype)) image_HLS = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) image_HLS = np.array(image_HLS, dtype=np.float32) image_HLS[:, :, 1][image_HLS[:, :, 1] < snow_point] *= brightness_coeff image_HLS[:, :, 1] = clip(image_HLS[:, :, 1], np.uint8, 255) image_HLS = np.array(image_HLS, dtype=np.uint8) image_RGB = cv2.cvtColor(image_HLS, cv2.COLOR_HLS2RGB) if needs_float: image_RGB = to_float(image_RGB, max_value=255) return image_RGB
[ "def", "add_snow", "(", "img", ",", "snow_point", ",", "brightness_coeff", ")", ":", "non_rgb_warning", "(", "img", ")", "input_dtype", "=", "img", ".", "dtype", "needs_float", "=", "False", "snow_point", "*=", "127.5", "# = 255 / 2", "snow_point", "+=", "85", "# = 255 / 3", "if", "input_dtype", "==", "np", ".", "float32", ":", "img", "=", "from_float", "(", "img", ",", "dtype", "=", "np", ".", "dtype", "(", "'uint8'", ")", ")", "needs_float", "=", "True", "elif", "input_dtype", "not", "in", "(", "np", ".", "uint8", ",", "np", ".", "float32", ")", ":", "raise", "ValueError", "(", "'Unexpected dtype {} for RandomSnow augmentation'", ".", "format", "(", "input_dtype", ")", ")", "image_HLS", "=", "cv2", ".", "cvtColor", "(", "img", ",", "cv2", ".", "COLOR_RGB2HLS", ")", "image_HLS", "=", "np", ".", "array", "(", "image_HLS", ",", "dtype", "=", "np", ".", "float32", ")", "image_HLS", "[", ":", ",", ":", ",", "1", "]", "[", "image_HLS", "[", ":", ",", ":", ",", "1", "]", "<", "snow_point", "]", "*=", "brightness_coeff", "image_HLS", "[", ":", ",", ":", ",", "1", "]", "=", "clip", "(", "image_HLS", "[", ":", ",", ":", ",", "1", "]", ",", "np", ".", "uint8", ",", "255", ")", "image_HLS", "=", "np", ".", "array", "(", "image_HLS", ",", "dtype", "=", "np", ".", "uint8", ")", "image_RGB", "=", "cv2", ".", "cvtColor", "(", "image_HLS", ",", "cv2", ".", "COLOR_HLS2RGB", ")", "if", "needs_float", ":", "image_RGB", "=", "to_float", "(", "image_RGB", ",", "max_value", "=", "255", ")", "return", "image_RGB" ]
Bleaches out pixels, mitation snow. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img: snow_point: brightness_coeff: Returns:
[ "Bleaches", "out", "pixels", "mitation", "snow", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L438-L479
26,647
albu/albumentations
albumentations/augmentations/functional.py
add_fog
def add_fog(img, fog_coef, alpha_coef, haze_list): """Add fog to the image. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): fog_coef (float): alpha_coef (float): haze_list (list): Returns: """ non_rgb_warning(img) input_dtype = img.dtype needs_float = False if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomFog augmentation'.format(input_dtype)) height, width = img.shape[:2] hw = max(int(width // 3 * fog_coef), 10) for haze_points in haze_list: x, y = haze_points overlay = img.copy() output = img.copy() alpha = alpha_coef * fog_coef rad = hw // 2 point = (x + hw // 2, y + hw // 2) cv2.circle(overlay, point, int(rad), (255, 255, 255), -1) cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output) img = output.copy() image_rgb = cv2.blur(img, (hw // 10, hw // 10)) if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
python
def add_fog(img, fog_coef, alpha_coef, haze_list): """Add fog to the image. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): fog_coef (float): alpha_coef (float): haze_list (list): Returns: """ non_rgb_warning(img) input_dtype = img.dtype needs_float = False if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomFog augmentation'.format(input_dtype)) height, width = img.shape[:2] hw = max(int(width // 3 * fog_coef), 10) for haze_points in haze_list: x, y = haze_points overlay = img.copy() output = img.copy() alpha = alpha_coef * fog_coef rad = hw // 2 point = (x + hw // 2, y + hw // 2) cv2.circle(overlay, point, int(rad), (255, 255, 255), -1) cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output) img = output.copy() image_rgb = cv2.blur(img, (hw // 10, hw // 10)) if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
[ "def", "add_fog", "(", "img", ",", "fog_coef", ",", "alpha_coef", ",", "haze_list", ")", ":", "non_rgb_warning", "(", "img", ")", "input_dtype", "=", "img", ".", "dtype", "needs_float", "=", "False", "if", "input_dtype", "==", "np", ".", "float32", ":", "img", "=", "from_float", "(", "img", ",", "dtype", "=", "np", ".", "dtype", "(", "'uint8'", ")", ")", "needs_float", "=", "True", "elif", "input_dtype", "not", "in", "(", "np", ".", "uint8", ",", "np", ".", "float32", ")", ":", "raise", "ValueError", "(", "'Unexpected dtype {} for RandomFog augmentation'", ".", "format", "(", "input_dtype", ")", ")", "height", ",", "width", "=", "img", ".", "shape", "[", ":", "2", "]", "hw", "=", "max", "(", "int", "(", "width", "//", "3", "*", "fog_coef", ")", ",", "10", ")", "for", "haze_points", "in", "haze_list", ":", "x", ",", "y", "=", "haze_points", "overlay", "=", "img", ".", "copy", "(", ")", "output", "=", "img", ".", "copy", "(", ")", "alpha", "=", "alpha_coef", "*", "fog_coef", "rad", "=", "hw", "//", "2", "point", "=", "(", "x", "+", "hw", "//", "2", ",", "y", "+", "hw", "//", "2", ")", "cv2", ".", "circle", "(", "overlay", ",", "point", ",", "int", "(", "rad", ")", ",", "(", "255", ",", "255", ",", "255", ")", ",", "-", "1", ")", "cv2", ".", "addWeighted", "(", "overlay", ",", "alpha", ",", "output", ",", "1", "-", "alpha", ",", "0", ",", "output", ")", "img", "=", "output", ".", "copy", "(", ")", "image_rgb", "=", "cv2", ".", "blur", "(", "img", ",", "(", "hw", "//", "10", ",", "hw", "//", "10", ")", ")", "if", "needs_float", ":", "image_rgb", "=", "to_float", "(", "image_rgb", ",", "max_value", "=", "255", ")", "return", "image_rgb" ]
Add fog to the image. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): fog_coef (float): alpha_coef (float): haze_list (list): Returns:
[ "Add", "fog", "to", "the", "image", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L533-L578
26,648
albu/albumentations
albumentations/augmentations/functional.py
add_sun_flare
def add_sun_flare(img, flare_center_x, flare_center_y, src_radius, src_color, circles): """Add sun flare. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): flare_center_x (float): flare_center_y (float): src_radius: src_color (int, int, int): circles (list): Returns: """ non_rgb_warning(img) input_dtype = img.dtype needs_float = False if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSunFlareaugmentation'.format(input_dtype)) overlay = img.copy() output = img.copy() for (alpha, (x, y), rad3, (r_color, g_color, b_color)) in circles: cv2.circle(overlay, (x, y), rad3, (r_color, g_color, b_color), -1) cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output) point = (int(flare_center_x), int(flare_center_y)) overlay = output.copy() num_times = src_radius // 10 alpha = np.linspace(0.0, 1, num=num_times) rad = np.linspace(1, src_radius, num=num_times) for i in range(num_times): cv2.circle(overlay, point, int(rad[i]), src_color, -1) alp = alpha[num_times - i - 1] * alpha[num_times - i - 1] * alpha[num_times - i - 1] cv2.addWeighted(overlay, alp, output, 1 - alp, 0, output) image_rgb = output if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
python
def add_sun_flare(img, flare_center_x, flare_center_y, src_radius, src_color, circles): """Add sun flare. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): flare_center_x (float): flare_center_y (float): src_radius: src_color (int, int, int): circles (list): Returns: """ non_rgb_warning(img) input_dtype = img.dtype needs_float = False if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSunFlareaugmentation'.format(input_dtype)) overlay = img.copy() output = img.copy() for (alpha, (x, y), rad3, (r_color, g_color, b_color)) in circles: cv2.circle(overlay, (x, y), rad3, (r_color, g_color, b_color), -1) cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output) point = (int(flare_center_x), int(flare_center_y)) overlay = output.copy() num_times = src_radius // 10 alpha = np.linspace(0.0, 1, num=num_times) rad = np.linspace(1, src_radius, num=num_times) for i in range(num_times): cv2.circle(overlay, point, int(rad[i]), src_color, -1) alp = alpha[num_times - i - 1] * alpha[num_times - i - 1] * alpha[num_times - i - 1] cv2.addWeighted(overlay, alp, output, 1 - alp, 0, output) image_rgb = output if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
[ "def", "add_sun_flare", "(", "img", ",", "flare_center_x", ",", "flare_center_y", ",", "src_radius", ",", "src_color", ",", "circles", ")", ":", "non_rgb_warning", "(", "img", ")", "input_dtype", "=", "img", ".", "dtype", "needs_float", "=", "False", "if", "input_dtype", "==", "np", ".", "float32", ":", "img", "=", "from_float", "(", "img", ",", "dtype", "=", "np", ".", "dtype", "(", "'uint8'", ")", ")", "needs_float", "=", "True", "elif", "input_dtype", "not", "in", "(", "np", ".", "uint8", ",", "np", ".", "float32", ")", ":", "raise", "ValueError", "(", "'Unexpected dtype {} for RandomSunFlareaugmentation'", ".", "format", "(", "input_dtype", ")", ")", "overlay", "=", "img", ".", "copy", "(", ")", "output", "=", "img", ".", "copy", "(", ")", "for", "(", "alpha", ",", "(", "x", ",", "y", ")", ",", "rad3", ",", "(", "r_color", ",", "g_color", ",", "b_color", ")", ")", "in", "circles", ":", "cv2", ".", "circle", "(", "overlay", ",", "(", "x", ",", "y", ")", ",", "rad3", ",", "(", "r_color", ",", "g_color", ",", "b_color", ")", ",", "-", "1", ")", "cv2", ".", "addWeighted", "(", "overlay", ",", "alpha", ",", "output", ",", "1", "-", "alpha", ",", "0", ",", "output", ")", "point", "=", "(", "int", "(", "flare_center_x", ")", ",", "int", "(", "flare_center_y", ")", ")", "overlay", "=", "output", ".", "copy", "(", ")", "num_times", "=", "src_radius", "//", "10", "alpha", "=", "np", ".", "linspace", "(", "0.0", ",", "1", ",", "num", "=", "num_times", ")", "rad", "=", "np", ".", "linspace", "(", "1", ",", "src_radius", ",", "num", "=", "num_times", ")", "for", "i", "in", "range", "(", "num_times", ")", ":", "cv2", ".", "circle", "(", "overlay", ",", "point", ",", "int", "(", "rad", "[", "i", "]", ")", ",", "src_color", ",", "-", "1", ")", "alp", "=", "alpha", "[", "num_times", "-", "i", "-", "1", "]", "*", "alpha", "[", "num_times", "-", "i", "-", "1", "]", "*", "alpha", "[", "num_times", "-", "i", "-", "1", "]", "cv2", ".", "addWeighted", "(", "overlay", ",", "alp", ",", "output", ",", "1", "-", "alp", ",", "0", ",", "output", ")", "image_rgb", "=", "output", "if", "needs_float", ":", "image_rgb", "=", "to_float", "(", "image_rgb", ",", "max_value", "=", "255", ")", "return", "image_rgb" ]
Add sun flare. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): flare_center_x (float): flare_center_y (float): src_radius: src_color (int, int, int): circles (list): Returns:
[ "Add", "sun", "flare", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L582-L633
26,649
albu/albumentations
albumentations/augmentations/functional.py
add_shadow
def add_shadow(img, vertices_list): """Add shadows to the image. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): vertices_list (list): Returns: """ non_rgb_warning(img) input_dtype = img.dtype needs_float = False if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSnow augmentation'.format(input_dtype)) image_hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) mask = np.zeros_like(img) # adding all shadow polygons on empty mask, single 255 denotes only red channel for vertices in vertices_list: cv2.fillPoly(mask, vertices, 255) # if red channel is hot, image's "Lightness" channel's brightness is lowered red_max_value_ind = mask[:, :, 0] == 255 image_hls[:, :, 1][red_max_value_ind] = image_hls[:, :, 1][red_max_value_ind] * 0.5 image_rgb = cv2.cvtColor(image_hls, cv2.COLOR_HLS2RGB) if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
python
def add_shadow(img, vertices_list): """Add shadows to the image. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): vertices_list (list): Returns: """ non_rgb_warning(img) input_dtype = img.dtype needs_float = False if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSnow augmentation'.format(input_dtype)) image_hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) mask = np.zeros_like(img) # adding all shadow polygons on empty mask, single 255 denotes only red channel for vertices in vertices_list: cv2.fillPoly(mask, vertices, 255) # if red channel is hot, image's "Lightness" channel's brightness is lowered red_max_value_ind = mask[:, :, 0] == 255 image_hls[:, :, 1][red_max_value_ind] = image_hls[:, :, 1][red_max_value_ind] * 0.5 image_rgb = cv2.cvtColor(image_hls, cv2.COLOR_HLS2RGB) if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
[ "def", "add_shadow", "(", "img", ",", "vertices_list", ")", ":", "non_rgb_warning", "(", "img", ")", "input_dtype", "=", "img", ".", "dtype", "needs_float", "=", "False", "if", "input_dtype", "==", "np", ".", "float32", ":", "img", "=", "from_float", "(", "img", ",", "dtype", "=", "np", ".", "dtype", "(", "'uint8'", ")", ")", "needs_float", "=", "True", "elif", "input_dtype", "not", "in", "(", "np", ".", "uint8", ",", "np", ".", "float32", ")", ":", "raise", "ValueError", "(", "'Unexpected dtype {} for RandomSnow augmentation'", ".", "format", "(", "input_dtype", ")", ")", "image_hls", "=", "cv2", ".", "cvtColor", "(", "img", ",", "cv2", ".", "COLOR_RGB2HLS", ")", "mask", "=", "np", ".", "zeros_like", "(", "img", ")", "# adding all shadow polygons on empty mask, single 255 denotes only red channel", "for", "vertices", "in", "vertices_list", ":", "cv2", ".", "fillPoly", "(", "mask", ",", "vertices", ",", "255", ")", "# if red channel is hot, image's \"Lightness\" channel's brightness is lowered", "red_max_value_ind", "=", "mask", "[", ":", ",", ":", ",", "0", "]", "==", "255", "image_hls", "[", ":", ",", ":", ",", "1", "]", "[", "red_max_value_ind", "]", "=", "image_hls", "[", ":", ",", ":", ",", "1", "]", "[", "red_max_value_ind", "]", "*", "0.5", "image_rgb", "=", "cv2", ".", "cvtColor", "(", "image_hls", ",", "cv2", ".", "COLOR_HLS2RGB", ")", "if", "needs_float", ":", "image_rgb", "=", "to_float", "(", "image_rgb", ",", "max_value", "=", "255", ")", "return", "image_rgb" ]
Add shadows to the image. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): vertices_list (list): Returns:
[ "Add", "shadows", "to", "the", "image", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L637-L675
26,650
albu/albumentations
albumentations/augmentations/functional.py
bbox_vflip
def bbox_vflip(bbox, rows, cols): """Flip a bounding box vertically around the x-axis.""" x_min, y_min, x_max, y_max = bbox return [x_min, 1 - y_max, x_max, 1 - y_min]
python
def bbox_vflip(bbox, rows, cols): """Flip a bounding box vertically around the x-axis.""" x_min, y_min, x_max, y_max = bbox return [x_min, 1 - y_max, x_max, 1 - y_min]
[ "def", "bbox_vflip", "(", "bbox", ",", "rows", ",", "cols", ")", ":", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "bbox", "return", "[", "x_min", ",", "1", "-", "y_max", ",", "x_max", ",", "1", "-", "y_min", "]" ]
Flip a bounding box vertically around the x-axis.
[ "Flip", "a", "bounding", "box", "vertically", "around", "the", "x", "-", "axis", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L918-L921
26,651
albu/albumentations
albumentations/augmentations/functional.py
bbox_hflip
def bbox_hflip(bbox, rows, cols): """Flip a bounding box horizontally around the y-axis.""" x_min, y_min, x_max, y_max = bbox return [1 - x_max, y_min, 1 - x_min, y_max]
python
def bbox_hflip(bbox, rows, cols): """Flip a bounding box horizontally around the y-axis.""" x_min, y_min, x_max, y_max = bbox return [1 - x_max, y_min, 1 - x_min, y_max]
[ "def", "bbox_hflip", "(", "bbox", ",", "rows", ",", "cols", ")", ":", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "bbox", "return", "[", "1", "-", "x_max", ",", "y_min", ",", "1", "-", "x_min", ",", "y_max", "]" ]
Flip a bounding box horizontally around the y-axis.
[ "Flip", "a", "bounding", "box", "horizontally", "around", "the", "y", "-", "axis", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L924-L927
26,652
albu/albumentations
albumentations/augmentations/functional.py
bbox_flip
def bbox_flip(bbox, d, rows, cols): """Flip a bounding box either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1. """ if d == 0: bbox = bbox_vflip(bbox, rows, cols) elif d == 1: bbox = bbox_hflip(bbox, rows, cols) elif d == -1: bbox = bbox_hflip(bbox, rows, cols) bbox = bbox_vflip(bbox, rows, cols) else: raise ValueError('Invalid d value {}. Valid values are -1, 0 and 1'.format(d)) return bbox
python
def bbox_flip(bbox, d, rows, cols): """Flip a bounding box either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1. """ if d == 0: bbox = bbox_vflip(bbox, rows, cols) elif d == 1: bbox = bbox_hflip(bbox, rows, cols) elif d == -1: bbox = bbox_hflip(bbox, rows, cols) bbox = bbox_vflip(bbox, rows, cols) else: raise ValueError('Invalid d value {}. Valid values are -1, 0 and 1'.format(d)) return bbox
[ "def", "bbox_flip", "(", "bbox", ",", "d", ",", "rows", ",", "cols", ")", ":", "if", "d", "==", "0", ":", "bbox", "=", "bbox_vflip", "(", "bbox", ",", "rows", ",", "cols", ")", "elif", "d", "==", "1", ":", "bbox", "=", "bbox_hflip", "(", "bbox", ",", "rows", ",", "cols", ")", "elif", "d", "==", "-", "1", ":", "bbox", "=", "bbox_hflip", "(", "bbox", ",", "rows", ",", "cols", ")", "bbox", "=", "bbox_vflip", "(", "bbox", ",", "rows", ",", "cols", ")", "else", ":", "raise", "ValueError", "(", "'Invalid d value {}. Valid values are -1, 0 and 1'", ".", "format", "(", "d", ")", ")", "return", "bbox" ]
Flip a bounding box either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1.
[ "Flip", "a", "bounding", "box", "either", "vertically", "horizontally", "or", "both", "depending", "on", "the", "value", "of", "d", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L930-L946
26,653
albu/albumentations
albumentations/augmentations/functional.py
crop_bbox_by_coords
def crop_bbox_by_coords(bbox, crop_coords, crop_height, crop_width, rows, cols): """Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop. """ bbox = denormalize_bbox(bbox, rows, cols) x_min, y_min, x_max, y_max = bbox x1, y1, x2, y2 = crop_coords cropped_bbox = [x_min - x1, y_min - y1, x_max - x1, y_max - y1] return normalize_bbox(cropped_bbox, crop_height, crop_width)
python
def crop_bbox_by_coords(bbox, crop_coords, crop_height, crop_width, rows, cols): """Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop. """ bbox = denormalize_bbox(bbox, rows, cols) x_min, y_min, x_max, y_max = bbox x1, y1, x2, y2 = crop_coords cropped_bbox = [x_min - x1, y_min - y1, x_max - x1, y_max - y1] return normalize_bbox(cropped_bbox, crop_height, crop_width)
[ "def", "crop_bbox_by_coords", "(", "bbox", ",", "crop_coords", ",", "crop_height", ",", "crop_width", ",", "rows", ",", "cols", ")", ":", "bbox", "=", "denormalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "bbox", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "crop_coords", "cropped_bbox", "=", "[", "x_min", "-", "x1", ",", "y_min", "-", "y1", ",", "x_max", "-", "x1", ",", "y_max", "-", "y1", "]", "return", "normalize_bbox", "(", "cropped_bbox", ",", "crop_height", ",", "crop_width", ")" ]
Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop.
[ "Crop", "a", "bounding", "box", "using", "the", "provided", "coordinates", "of", "bottom", "-", "left", "and", "top", "-", "right", "corners", "in", "pixels", "and", "the", "required", "height", "and", "width", "of", "the", "crop", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L949-L957
26,654
albu/albumentations
albumentations/augmentations/functional.py
bbox_rotate
def bbox_rotate(bbox, angle, rows, cols, interpolation): """Rotates a bounding box by angle degrees Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). angle (int): Angle of rotation in degrees rows (int): Image rows. cols (int): Image cols. interpolation (int): interpolation method. return a tuple (x_min, y_min, x_max, y_max) """ scale = cols / float(rows) x = np.array([bbox[0], bbox[2], bbox[2], bbox[0]]) y = np.array([bbox[1], bbox[1], bbox[3], bbox[3]]) x = x - 0.5 y = y - 0.5 angle = np.deg2rad(angle) x_t = (np.cos(angle) * x * scale + np.sin(angle) * y) / scale y_t = (-np.sin(angle) * x * scale + np.cos(angle) * y) x_t = x_t + 0.5 y_t = y_t + 0.5 return [min(x_t), min(y_t), max(x_t), max(y_t)]
python
def bbox_rotate(bbox, angle, rows, cols, interpolation): """Rotates a bounding box by angle degrees Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). angle (int): Angle of rotation in degrees rows (int): Image rows. cols (int): Image cols. interpolation (int): interpolation method. return a tuple (x_min, y_min, x_max, y_max) """ scale = cols / float(rows) x = np.array([bbox[0], bbox[2], bbox[2], bbox[0]]) y = np.array([bbox[1], bbox[1], bbox[3], bbox[3]]) x = x - 0.5 y = y - 0.5 angle = np.deg2rad(angle) x_t = (np.cos(angle) * x * scale + np.sin(angle) * y) / scale y_t = (-np.sin(angle) * x * scale + np.cos(angle) * y) x_t = x_t + 0.5 y_t = y_t + 0.5 return [min(x_t), min(y_t), max(x_t), max(y_t)]
[ "def", "bbox_rotate", "(", "bbox", ",", "angle", ",", "rows", ",", "cols", ",", "interpolation", ")", ":", "scale", "=", "cols", "/", "float", "(", "rows", ")", "x", "=", "np", ".", "array", "(", "[", "bbox", "[", "0", "]", ",", "bbox", "[", "2", "]", ",", "bbox", "[", "2", "]", ",", "bbox", "[", "0", "]", "]", ")", "y", "=", "np", ".", "array", "(", "[", "bbox", "[", "1", "]", ",", "bbox", "[", "1", "]", ",", "bbox", "[", "3", "]", ",", "bbox", "[", "3", "]", "]", ")", "x", "=", "x", "-", "0.5", "y", "=", "y", "-", "0.5", "angle", "=", "np", ".", "deg2rad", "(", "angle", ")", "x_t", "=", "(", "np", ".", "cos", "(", "angle", ")", "*", "x", "*", "scale", "+", "np", ".", "sin", "(", "angle", ")", "*", "y", ")", "/", "scale", "y_t", "=", "(", "-", "np", ".", "sin", "(", "angle", ")", "*", "x", "*", "scale", "+", "np", ".", "cos", "(", "angle", ")", "*", "y", ")", "x_t", "=", "x_t", "+", "0.5", "y_t", "=", "y_t", "+", "0.5", "return", "[", "min", "(", "x_t", ")", ",", "min", "(", "y_t", ")", ",", "max", "(", "x_t", ")", ",", "max", "(", "y_t", ")", "]" ]
Rotates a bounding box by angle degrees Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). angle (int): Angle of rotation in degrees rows (int): Image rows. cols (int): Image cols. interpolation (int): interpolation method. return a tuple (x_min, y_min, x_max, y_max)
[ "Rotates", "a", "bounding", "box", "by", "angle", "degrees" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L998-L1020
26,655
albu/albumentations
albumentations/augmentations/functional.py
bbox_transpose
def bbox_transpose(bbox, axis, rows, cols): """Transposes a bounding box along given axis. Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). axis (int): 0 - main axis, 1 - secondary axis. rows (int): Image rows. cols (int): Image cols. """ x_min, y_min, x_max, y_max = bbox if axis != 0 and axis != 1: raise ValueError('Axis must be either 0 or 1.') if axis == 0: bbox = [y_min, x_min, y_max, x_max] if axis == 1: bbox = [1 - y_max, 1 - x_max, 1 - y_min, 1 - x_min] return bbox
python
def bbox_transpose(bbox, axis, rows, cols): """Transposes a bounding box along given axis. Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). axis (int): 0 - main axis, 1 - secondary axis. rows (int): Image rows. cols (int): Image cols. """ x_min, y_min, x_max, y_max = bbox if axis != 0 and axis != 1: raise ValueError('Axis must be either 0 or 1.') if axis == 0: bbox = [y_min, x_min, y_max, x_max] if axis == 1: bbox = [1 - y_max, 1 - x_max, 1 - y_min, 1 - x_min] return bbox
[ "def", "bbox_transpose", "(", "bbox", ",", "axis", ",", "rows", ",", "cols", ")", ":", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "bbox", "if", "axis", "!=", "0", "and", "axis", "!=", "1", ":", "raise", "ValueError", "(", "'Axis must be either 0 or 1.'", ")", "if", "axis", "==", "0", ":", "bbox", "=", "[", "y_min", ",", "x_min", ",", "y_max", ",", "x_max", "]", "if", "axis", "==", "1", ":", "bbox", "=", "[", "1", "-", "y_max", ",", "1", "-", "x_max", ",", "1", "-", "y_min", ",", "1", "-", "x_min", "]", "return", "bbox" ]
Transposes a bounding box along given axis. Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). axis (int): 0 - main axis, 1 - secondary axis. rows (int): Image rows. cols (int): Image cols.
[ "Transposes", "a", "bounding", "box", "along", "given", "axis", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1023-L1039
26,656
albu/albumentations
albumentations/augmentations/functional.py
keypoint_vflip
def keypoint_vflip(kp, rows, cols): """Flip a keypoint vertically around the x-axis.""" x, y, angle, scale = kp c = math.cos(angle) s = math.sin(angle) angle = math.atan2(-s, c) return [x, (rows - 1) - y, angle, scale]
python
def keypoint_vflip(kp, rows, cols): """Flip a keypoint vertically around the x-axis.""" x, y, angle, scale = kp c = math.cos(angle) s = math.sin(angle) angle = math.atan2(-s, c) return [x, (rows - 1) - y, angle, scale]
[ "def", "keypoint_vflip", "(", "kp", ",", "rows", ",", "cols", ")", ":", "x", ",", "y", ",", "angle", ",", "scale", "=", "kp", "c", "=", "math", ".", "cos", "(", "angle", ")", "s", "=", "math", ".", "sin", "(", "angle", ")", "angle", "=", "math", ".", "atan2", "(", "-", "s", ",", "c", ")", "return", "[", "x", ",", "(", "rows", "-", "1", ")", "-", "y", ",", "angle", ",", "scale", "]" ]
Flip a keypoint vertically around the x-axis.
[ "Flip", "a", "keypoint", "vertically", "around", "the", "x", "-", "axis", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1042-L1048
26,657
albu/albumentations
albumentations/augmentations/functional.py
keypoint_flip
def keypoint_flip(bbox, d, rows, cols): """Flip a keypoint either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1. """ if d == 0: bbox = keypoint_vflip(bbox, rows, cols) elif d == 1: bbox = keypoint_hflip(bbox, rows, cols) elif d == -1: bbox = keypoint_hflip(bbox, rows, cols) bbox = keypoint_vflip(bbox, rows, cols) else: raise ValueError('Invalid d value {}. Valid values are -1, 0 and 1'.format(d)) return bbox
python
def keypoint_flip(bbox, d, rows, cols): """Flip a keypoint either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1. """ if d == 0: bbox = keypoint_vflip(bbox, rows, cols) elif d == 1: bbox = keypoint_hflip(bbox, rows, cols) elif d == -1: bbox = keypoint_hflip(bbox, rows, cols) bbox = keypoint_vflip(bbox, rows, cols) else: raise ValueError('Invalid d value {}. Valid values are -1, 0 and 1'.format(d)) return bbox
[ "def", "keypoint_flip", "(", "bbox", ",", "d", ",", "rows", ",", "cols", ")", ":", "if", "d", "==", "0", ":", "bbox", "=", "keypoint_vflip", "(", "bbox", ",", "rows", ",", "cols", ")", "elif", "d", "==", "1", ":", "bbox", "=", "keypoint_hflip", "(", "bbox", ",", "rows", ",", "cols", ")", "elif", "d", "==", "-", "1", ":", "bbox", "=", "keypoint_hflip", "(", "bbox", ",", "rows", ",", "cols", ")", "bbox", "=", "keypoint_vflip", "(", "bbox", ",", "rows", ",", "cols", ")", "else", ":", "raise", "ValueError", "(", "'Invalid d value {}. Valid values are -1, 0 and 1'", ".", "format", "(", "d", ")", ")", "return", "bbox" ]
Flip a keypoint either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1.
[ "Flip", "a", "keypoint", "either", "vertically", "horizontally", "or", "both", "depending", "on", "the", "value", "of", "d", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1060-L1076
26,658
albu/albumentations
albumentations/augmentations/functional.py
keypoint_scale
def keypoint_scale(keypoint, scale_x, scale_y, **params): """Scales a keypoint by scale_x and scale_y.""" x, y, a, s = keypoint return [x * scale_x, y * scale_y, a, s * max(scale_x, scale_y)]
python
def keypoint_scale(keypoint, scale_x, scale_y, **params): """Scales a keypoint by scale_x and scale_y.""" x, y, a, s = keypoint return [x * scale_x, y * scale_y, a, s * max(scale_x, scale_y)]
[ "def", "keypoint_scale", "(", "keypoint", ",", "scale_x", ",", "scale_y", ",", "*", "*", "params", ")", ":", "x", ",", "y", ",", "a", ",", "s", "=", "keypoint", "return", "[", "x", "*", "scale_x", ",", "y", "*", "scale_y", ",", "a", ",", "s", "*", "max", "(", "scale_x", ",", "scale_y", ")", "]" ]
Scales a keypoint by scale_x and scale_y.
[ "Scales", "a", "keypoint", "by", "scale_x", "and", "scale_y", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1107-L1110
26,659
albu/albumentations
albumentations/augmentations/functional.py
crop_keypoint_by_coords
def crop_keypoint_by_coords(keypoint, crop_coords, crop_height, crop_width, rows, cols): """Crop a keypoint using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop. """ x, y, a, s = keypoint x1, y1, x2, y2 = crop_coords cropped_keypoint = [x - x1, y - y1, a, s] return cropped_keypoint
python
def crop_keypoint_by_coords(keypoint, crop_coords, crop_height, crop_width, rows, cols): """Crop a keypoint using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop. """ x, y, a, s = keypoint x1, y1, x2, y2 = crop_coords cropped_keypoint = [x - x1, y - y1, a, s] return cropped_keypoint
[ "def", "crop_keypoint_by_coords", "(", "keypoint", ",", "crop_coords", ",", "crop_height", ",", "crop_width", ",", "rows", ",", "cols", ")", ":", "x", ",", "y", ",", "a", ",", "s", "=", "keypoint", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "crop_coords", "cropped_keypoint", "=", "[", "x", "-", "x1", ",", "y", "-", "y1", ",", "a", ",", "s", "]", "return", "cropped_keypoint" ]
Crop a keypoint using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop.
[ "Crop", "a", "keypoint", "using", "the", "provided", "coordinates", "of", "bottom", "-", "left", "and", "top", "-", "right", "corners", "in", "pixels", "and", "the", "required", "height", "and", "width", "of", "the", "crop", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1113-L1120
26,660
albu/albumentations
albumentations/augmentations/functional.py
py3round
def py3round(number): """Unified rounding in all python versions.""" if abs(round(number) - number) == 0.5: return int(2.0 * round(number / 2.0)) return int(round(number))
python
def py3round(number): """Unified rounding in all python versions.""" if abs(round(number) - number) == 0.5: return int(2.0 * round(number / 2.0)) return int(round(number))
[ "def", "py3round", "(", "number", ")", ":", "if", "abs", "(", "round", "(", "number", ")", "-", "number", ")", "==", "0.5", ":", "return", "int", "(", "2.0", "*", "round", "(", "number", "/", "2.0", ")", ")", "return", "int", "(", "round", "(", "number", ")", ")" ]
Unified rounding in all python versions.
[ "Unified", "rounding", "in", "all", "python", "versions", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1133-L1138
26,661
albu/albumentations
albumentations/augmentations/bbox_utils.py
normalize_bbox
def normalize_bbox(bbox, rows, cols): """Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates by image height. """ if rows == 0: raise ValueError('Argument rows cannot be zero') if cols == 0: raise ValueError('Argument cols cannot be zero') x_min, y_min, x_max, y_max = bbox[:4] normalized_bbox = [x_min / cols, y_min / rows, x_max / cols, y_max / rows] return normalized_bbox + list(bbox[4:])
python
def normalize_bbox(bbox, rows, cols): """Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates by image height. """ if rows == 0: raise ValueError('Argument rows cannot be zero') if cols == 0: raise ValueError('Argument cols cannot be zero') x_min, y_min, x_max, y_max = bbox[:4] normalized_bbox = [x_min / cols, y_min / rows, x_max / cols, y_max / rows] return normalized_bbox + list(bbox[4:])
[ "def", "normalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", ":", "if", "rows", "==", "0", ":", "raise", "ValueError", "(", "'Argument rows cannot be zero'", ")", "if", "cols", "==", "0", ":", "raise", "ValueError", "(", "'Argument cols cannot be zero'", ")", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "bbox", "[", ":", "4", "]", "normalized_bbox", "=", "[", "x_min", "/", "cols", ",", "y_min", "/", "rows", ",", "x_max", "/", "cols", ",", "y_max", "/", "rows", "]", "return", "normalized_bbox", "+", "list", "(", "bbox", "[", "4", ":", "]", ")" ]
Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates by image height.
[ "Normalize", "coordinates", "of", "a", "bounding", "box", ".", "Divide", "x", "-", "coordinates", "by", "image", "width", "and", "y", "-", "coordinates", "by", "image", "height", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L10-L20
26,662
albu/albumentations
albumentations/augmentations/bbox_utils.py
normalize_bboxes
def normalize_bboxes(bboxes, rows, cols): """Normalize a list of bounding boxes.""" return [normalize_bbox(bbox, rows, cols) for bbox in bboxes]
python
def normalize_bboxes(bboxes, rows, cols): """Normalize a list of bounding boxes.""" return [normalize_bbox(bbox, rows, cols) for bbox in bboxes]
[ "def", "normalize_bboxes", "(", "bboxes", ",", "rows", ",", "cols", ")", ":", "return", "[", "normalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", "for", "bbox", "in", "bboxes", "]" ]
Normalize a list of bounding boxes.
[ "Normalize", "a", "list", "of", "bounding", "boxes", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L37-L39
26,663
albu/albumentations
albumentations/augmentations/bbox_utils.py
denormalize_bboxes
def denormalize_bboxes(bboxes, rows, cols): """Denormalize a list of bounding boxes.""" return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes]
python
def denormalize_bboxes(bboxes, rows, cols): """Denormalize a list of bounding boxes.""" return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes]
[ "def", "denormalize_bboxes", "(", "bboxes", ",", "rows", ",", "cols", ")", ":", "return", "[", "denormalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", "for", "bbox", "in", "bboxes", "]" ]
Denormalize a list of bounding boxes.
[ "Denormalize", "a", "list", "of", "bounding", "boxes", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L42-L44
26,664
albu/albumentations
albumentations/augmentations/bbox_utils.py
calculate_bbox_area
def calculate_bbox_area(bbox, rows, cols): """Calculate the area of a bounding box in pixels.""" bbox = denormalize_bbox(bbox, rows, cols) x_min, y_min, x_max, y_max = bbox[:4] area = (x_max - x_min) * (y_max - y_min) return area
python
def calculate_bbox_area(bbox, rows, cols): """Calculate the area of a bounding box in pixels.""" bbox = denormalize_bbox(bbox, rows, cols) x_min, y_min, x_max, y_max = bbox[:4] area = (x_max - x_min) * (y_max - y_min) return area
[ "def", "calculate_bbox_area", "(", "bbox", ",", "rows", ",", "cols", ")", ":", "bbox", "=", "denormalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "bbox", "[", ":", "4", "]", "area", "=", "(", "x_max", "-", "x_min", ")", "*", "(", "y_max", "-", "y_min", ")", "return", "area" ]
Calculate the area of a bounding box in pixels.
[ "Calculate", "the", "area", "of", "a", "bounding", "box", "in", "pixels", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L47-L52
26,665
albu/albumentations
albumentations/augmentations/bbox_utils.py
filter_bboxes_by_visibility
def filter_bboxes_by_visibility(original_shape, bboxes, transformed_shape, transformed_bboxes, threshold=0., min_area=0.): """Filter bounding boxes and return only those boxes whose visibility after transformation is above the threshold and minimal area of bounding box in pixels is more then min_area. Args: original_shape (tuple): original image shape bboxes (list): original bounding boxes transformed_shape(tuple): transformed image transformed_bboxes (list): transformed bounding boxes threshold (float): visibility threshold. Should be a value in the range [0.0, 1.0]. min_area (float): Minimal area threshold. """ img_height, img_width = original_shape[:2] transformed_img_height, transformed_img_width = transformed_shape[:2] visible_bboxes = [] for bbox, transformed_bbox in zip(bboxes, transformed_bboxes): if not all(0.0 <= value <= 1.0 for value in transformed_bbox[:4]): continue bbox_area = calculate_bbox_area(bbox, img_height, img_width) transformed_bbox_area = calculate_bbox_area(transformed_bbox, transformed_img_height, transformed_img_width) if transformed_bbox_area < min_area: continue visibility = transformed_bbox_area / bbox_area if visibility >= threshold: visible_bboxes.append(transformed_bbox) return visible_bboxes
python
def filter_bboxes_by_visibility(original_shape, bboxes, transformed_shape, transformed_bboxes, threshold=0., min_area=0.): """Filter bounding boxes and return only those boxes whose visibility after transformation is above the threshold and minimal area of bounding box in pixels is more then min_area. Args: original_shape (tuple): original image shape bboxes (list): original bounding boxes transformed_shape(tuple): transformed image transformed_bboxes (list): transformed bounding boxes threshold (float): visibility threshold. Should be a value in the range [0.0, 1.0]. min_area (float): Minimal area threshold. """ img_height, img_width = original_shape[:2] transformed_img_height, transformed_img_width = transformed_shape[:2] visible_bboxes = [] for bbox, transformed_bbox in zip(bboxes, transformed_bboxes): if not all(0.0 <= value <= 1.0 for value in transformed_bbox[:4]): continue bbox_area = calculate_bbox_area(bbox, img_height, img_width) transformed_bbox_area = calculate_bbox_area(transformed_bbox, transformed_img_height, transformed_img_width) if transformed_bbox_area < min_area: continue visibility = transformed_bbox_area / bbox_area if visibility >= threshold: visible_bboxes.append(transformed_bbox) return visible_bboxes
[ "def", "filter_bboxes_by_visibility", "(", "original_shape", ",", "bboxes", ",", "transformed_shape", ",", "transformed_bboxes", ",", "threshold", "=", "0.", ",", "min_area", "=", "0.", ")", ":", "img_height", ",", "img_width", "=", "original_shape", "[", ":", "2", "]", "transformed_img_height", ",", "transformed_img_width", "=", "transformed_shape", "[", ":", "2", "]", "visible_bboxes", "=", "[", "]", "for", "bbox", ",", "transformed_bbox", "in", "zip", "(", "bboxes", ",", "transformed_bboxes", ")", ":", "if", "not", "all", "(", "0.0", "<=", "value", "<=", "1.0", "for", "value", "in", "transformed_bbox", "[", ":", "4", "]", ")", ":", "continue", "bbox_area", "=", "calculate_bbox_area", "(", "bbox", ",", "img_height", ",", "img_width", ")", "transformed_bbox_area", "=", "calculate_bbox_area", "(", "transformed_bbox", ",", "transformed_img_height", ",", "transformed_img_width", ")", "if", "transformed_bbox_area", "<", "min_area", ":", "continue", "visibility", "=", "transformed_bbox_area", "/", "bbox_area", "if", "visibility", ">=", "threshold", ":", "visible_bboxes", ".", "append", "(", "transformed_bbox", ")", "return", "visible_bboxes" ]
Filter bounding boxes and return only those boxes whose visibility after transformation is above the threshold and minimal area of bounding box in pixels is more then min_area. Args: original_shape (tuple): original image shape bboxes (list): original bounding boxes transformed_shape(tuple): transformed image transformed_bboxes (list): transformed bounding boxes threshold (float): visibility threshold. Should be a value in the range [0.0, 1.0]. min_area (float): Minimal area threshold.
[ "Filter", "bounding", "boxes", "and", "return", "only", "those", "boxes", "whose", "visibility", "after", "transformation", "is", "above", "the", "threshold", "and", "minimal", "area", "of", "bounding", "box", "in", "pixels", "is", "more", "then", "min_area", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L55-L82
26,666
albu/albumentations
albumentations/augmentations/bbox_utils.py
convert_bbox_from_albumentations
def convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity=False): """Convert a bounding box from the format used by albumentations to a format, specified in `target_format`. Args: bbox (list): bounding box with coordinates in the format used by albumentations target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. rows (int): image height cols (int): image width check_validity (bool): check if all boxes are valid boxes Note: The `coco` format of a bounding box looks like `[x_min, y_min, width, height]`, e.g. [97, 12, 150, 200]. The `pascal_voc` format of a bounding box looks like `[x_min, y_min, x_max, y_max]`, e.g. [97, 12, 247, 212]. Raises: ValueError: if `target_format` is not equal to `coco` or `pascal_voc`. """ if target_format not in {'coco', 'pascal_voc'}: raise ValueError( "Unknown target_format {}. Supported formats are: 'coco' and 'pascal_voc'".format(target_format) ) if check_validity: check_bbox(bbox) bbox = denormalize_bbox(bbox, rows, cols) if target_format == 'coco': x_min, y_min, x_max, y_max = bbox[:4] width = x_max - x_min height = y_max - y_min bbox = [x_min, y_min, width, height] + list(bbox[4:]) return bbox
python
def convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity=False): """Convert a bounding box from the format used by albumentations to a format, specified in `target_format`. Args: bbox (list): bounding box with coordinates in the format used by albumentations target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. rows (int): image height cols (int): image width check_validity (bool): check if all boxes are valid boxes Note: The `coco` format of a bounding box looks like `[x_min, y_min, width, height]`, e.g. [97, 12, 150, 200]. The `pascal_voc` format of a bounding box looks like `[x_min, y_min, x_max, y_max]`, e.g. [97, 12, 247, 212]. Raises: ValueError: if `target_format` is not equal to `coco` or `pascal_voc`. """ if target_format not in {'coco', 'pascal_voc'}: raise ValueError( "Unknown target_format {}. Supported formats are: 'coco' and 'pascal_voc'".format(target_format) ) if check_validity: check_bbox(bbox) bbox = denormalize_bbox(bbox, rows, cols) if target_format == 'coco': x_min, y_min, x_max, y_max = bbox[:4] width = x_max - x_min height = y_max - y_min bbox = [x_min, y_min, width, height] + list(bbox[4:]) return bbox
[ "def", "convert_bbox_from_albumentations", "(", "bbox", ",", "target_format", ",", "rows", ",", "cols", ",", "check_validity", "=", "False", ")", ":", "if", "target_format", "not", "in", "{", "'coco'", ",", "'pascal_voc'", "}", ":", "raise", "ValueError", "(", "\"Unknown target_format {}. Supported formats are: 'coco' and 'pascal_voc'\"", ".", "format", "(", "target_format", ")", ")", "if", "check_validity", ":", "check_bbox", "(", "bbox", ")", "bbox", "=", "denormalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", "if", "target_format", "==", "'coco'", ":", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "bbox", "[", ":", "4", "]", "width", "=", "x_max", "-", "x_min", "height", "=", "y_max", "-", "y_min", "bbox", "=", "[", "x_min", ",", "y_min", ",", "width", ",", "height", "]", "+", "list", "(", "bbox", "[", "4", ":", "]", ")", "return", "bbox" ]
Convert a bounding box from the format used by albumentations to a format, specified in `target_format`. Args: bbox (list): bounding box with coordinates in the format used by albumentations target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. rows (int): image height cols (int): image width check_validity (bool): check if all boxes are valid boxes Note: The `coco` format of a bounding box looks like `[x_min, y_min, width, height]`, e.g. [97, 12, 150, 200]. The `pascal_voc` format of a bounding box looks like `[x_min, y_min, x_max, y_max]`, e.g. [97, 12, 247, 212]. Raises: ValueError: if `target_format` is not equal to `coco` or `pascal_voc`.
[ "Convert", "a", "bounding", "box", "from", "the", "format", "used", "by", "albumentations", "to", "a", "format", "specified", "in", "target_format", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L122-L152
26,667
albu/albumentations
albumentations/augmentations/bbox_utils.py
convert_bboxes_to_albumentations
def convert_bboxes_to_albumentations(bboxes, source_format, rows, cols, check_validity=False): """Convert a list bounding boxes from a format specified in `source_format` to the format used by albumentations """ return [convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity) for bbox in bboxes]
python
def convert_bboxes_to_albumentations(bboxes, source_format, rows, cols, check_validity=False): """Convert a list bounding boxes from a format specified in `source_format` to the format used by albumentations """ return [convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity) for bbox in bboxes]
[ "def", "convert_bboxes_to_albumentations", "(", "bboxes", ",", "source_format", ",", "rows", ",", "cols", ",", "check_validity", "=", "False", ")", ":", "return", "[", "convert_bbox_to_albumentations", "(", "bbox", ",", "source_format", ",", "rows", ",", "cols", ",", "check_validity", ")", "for", "bbox", "in", "bboxes", "]" ]
Convert a list bounding boxes from a format specified in `source_format` to the format used by albumentations
[ "Convert", "a", "list", "bounding", "boxes", "from", "a", "format", "specified", "in", "source_format", "to", "the", "format", "used", "by", "albumentations" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L155-L158
26,668
albu/albumentations
albumentations/augmentations/bbox_utils.py
convert_bboxes_from_albumentations
def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False): """Convert a list of bounding boxes from the format used by albumentations to a format, specified in `target_format`. Args: bboxes (list): List of bounding box with coordinates in the format used by albumentations target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. rows (int): image height cols (int): image width check_validity (bool): check if all boxes are valid boxes """ return [convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity) for bbox in bboxes]
python
def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False): """Convert a list of bounding boxes from the format used by albumentations to a format, specified in `target_format`. Args: bboxes (list): List of bounding box with coordinates in the format used by albumentations target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. rows (int): image height cols (int): image width check_validity (bool): check if all boxes are valid boxes """ return [convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity) for bbox in bboxes]
[ "def", "convert_bboxes_from_albumentations", "(", "bboxes", ",", "target_format", ",", "rows", ",", "cols", ",", "check_validity", "=", "False", ")", ":", "return", "[", "convert_bbox_from_albumentations", "(", "bbox", ",", "target_format", ",", "rows", ",", "cols", ",", "check_validity", ")", "for", "bbox", "in", "bboxes", "]" ]
Convert a list of bounding boxes from the format used by albumentations to a format, specified in `target_format`. Args: bboxes (list): List of bounding box with coordinates in the format used by albumentations target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. rows (int): image height cols (int): image width check_validity (bool): check if all boxes are valid boxes
[ "Convert", "a", "list", "of", "bounding", "boxes", "from", "the", "format", "used", "by", "albumentations", "to", "a", "format", "specified", "in", "target_format", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L161-L172
26,669
albu/albumentations
albumentations/augmentations/bbox_utils.py
check_bbox
def check_bbox(bbox): """Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums""" for name, value in zip(['x_min', 'y_min', 'x_max', 'y_max'], bbox[:4]): if not 0 <= value <= 1: raise ValueError( 'Expected {name} for bbox {bbox} ' 'to be in the range [0.0, 1.0], got {value}.'.format( bbox=bbox, name=name, value=value, ) ) x_min, y_min, x_max, y_max = bbox[:4] if x_max <= x_min: raise ValueError('x_max is less than or equal to x_min for bbox {bbox}.'.format( bbox=bbox, )) if y_max <= y_min: raise ValueError('y_max is less than or equal to y_min for bbox {bbox}.'.format( bbox=bbox, ))
python
def check_bbox(bbox): """Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums""" for name, value in zip(['x_min', 'y_min', 'x_max', 'y_max'], bbox[:4]): if not 0 <= value <= 1: raise ValueError( 'Expected {name} for bbox {bbox} ' 'to be in the range [0.0, 1.0], got {value}.'.format( bbox=bbox, name=name, value=value, ) ) x_min, y_min, x_max, y_max = bbox[:4] if x_max <= x_min: raise ValueError('x_max is less than or equal to x_min for bbox {bbox}.'.format( bbox=bbox, )) if y_max <= y_min: raise ValueError('y_max is less than or equal to y_min for bbox {bbox}.'.format( bbox=bbox, ))
[ "def", "check_bbox", "(", "bbox", ")", ":", "for", "name", ",", "value", "in", "zip", "(", "[", "'x_min'", ",", "'y_min'", ",", "'x_max'", ",", "'y_max'", "]", ",", "bbox", "[", ":", "4", "]", ")", ":", "if", "not", "0", "<=", "value", "<=", "1", ":", "raise", "ValueError", "(", "'Expected {name} for bbox {bbox} '", "'to be in the range [0.0, 1.0], got {value}.'", ".", "format", "(", "bbox", "=", "bbox", ",", "name", "=", "name", ",", "value", "=", "value", ",", ")", ")", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "bbox", "[", ":", "4", "]", "if", "x_max", "<=", "x_min", ":", "raise", "ValueError", "(", "'x_max is less than or equal to x_min for bbox {bbox}.'", ".", "format", "(", "bbox", "=", "bbox", ",", ")", ")", "if", "y_max", "<=", "y_min", ":", "raise", "ValueError", "(", "'y_max is less than or equal to y_min for bbox {bbox}.'", ".", "format", "(", "bbox", "=", "bbox", ",", ")", ")" ]
Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums
[ "Check", "if", "bbox", "boundaries", "are", "in", "range", "0", "1", "and", "minimums", "are", "lesser", "then", "maximums" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L175-L195
26,670
albu/albumentations
albumentations/augmentations/bbox_utils.py
filter_bboxes
def filter_bboxes(bboxes, rows, cols, min_area=0., min_visibility=0.): """Remove bounding boxes that either lie outside of the visible area by more then min_visibility or whose area in pixels is under the threshold set by `min_area`. Also it crops boxes to final image size. Args: bboxes (list): List of bounding box with coordinates in the format used by albumentations rows (int): Image rows. cols (int): Image cols. min_area (float): minimum area of a bounding box. All bounding boxes whose visible area in pixels is less than this value will be removed. Default: 0.0. min_visibility (float): minimum fraction of area for a bounding box to remain this box in list. Default: 0.0. """ resulting_boxes = [] for bbox in bboxes: transformed_box_area = calculate_bbox_area(bbox, rows, cols) bbox[:4] = np.clip(bbox[:4], 0, 1.) clipped_box_area = calculate_bbox_area(bbox, rows, cols) if not transformed_box_area or clipped_box_area / transformed_box_area <= min_visibility: continue else: bbox[:4] = np.clip(bbox[:4], 0, 1.) if calculate_bbox_area(bbox, rows, cols) <= min_area: continue resulting_boxes.append(bbox) return resulting_boxes
python
def filter_bboxes(bboxes, rows, cols, min_area=0., min_visibility=0.): """Remove bounding boxes that either lie outside of the visible area by more then min_visibility or whose area in pixels is under the threshold set by `min_area`. Also it crops boxes to final image size. Args: bboxes (list): List of bounding box with coordinates in the format used by albumentations rows (int): Image rows. cols (int): Image cols. min_area (float): minimum area of a bounding box. All bounding boxes whose visible area in pixels is less than this value will be removed. Default: 0.0. min_visibility (float): minimum fraction of area for a bounding box to remain this box in list. Default: 0.0. """ resulting_boxes = [] for bbox in bboxes: transformed_box_area = calculate_bbox_area(bbox, rows, cols) bbox[:4] = np.clip(bbox[:4], 0, 1.) clipped_box_area = calculate_bbox_area(bbox, rows, cols) if not transformed_box_area or clipped_box_area / transformed_box_area <= min_visibility: continue else: bbox[:4] = np.clip(bbox[:4], 0, 1.) if calculate_bbox_area(bbox, rows, cols) <= min_area: continue resulting_boxes.append(bbox) return resulting_boxes
[ "def", "filter_bboxes", "(", "bboxes", ",", "rows", ",", "cols", ",", "min_area", "=", "0.", ",", "min_visibility", "=", "0.", ")", ":", "resulting_boxes", "=", "[", "]", "for", "bbox", "in", "bboxes", ":", "transformed_box_area", "=", "calculate_bbox_area", "(", "bbox", ",", "rows", ",", "cols", ")", "bbox", "[", ":", "4", "]", "=", "np", ".", "clip", "(", "bbox", "[", ":", "4", "]", ",", "0", ",", "1.", ")", "clipped_box_area", "=", "calculate_bbox_area", "(", "bbox", ",", "rows", ",", "cols", ")", "if", "not", "transformed_box_area", "or", "clipped_box_area", "/", "transformed_box_area", "<=", "min_visibility", ":", "continue", "else", ":", "bbox", "[", ":", "4", "]", "=", "np", ".", "clip", "(", "bbox", "[", ":", "4", "]", ",", "0", ",", "1.", ")", "if", "calculate_bbox_area", "(", "bbox", ",", "rows", ",", "cols", ")", "<=", "min_area", ":", "continue", "resulting_boxes", ".", "append", "(", "bbox", ")", "return", "resulting_boxes" ]
Remove bounding boxes that either lie outside of the visible area by more then min_visibility or whose area in pixels is under the threshold set by `min_area`. Also it crops boxes to final image size. Args: bboxes (list): List of bounding box with coordinates in the format used by albumentations rows (int): Image rows. cols (int): Image cols. min_area (float): minimum area of a bounding box. All bounding boxes whose visible area in pixels is less than this value will be removed. Default: 0.0. min_visibility (float): minimum fraction of area for a bounding box to remain this box in list. Default: 0.0.
[ "Remove", "bounding", "boxes", "that", "either", "lie", "outside", "of", "the", "visible", "area", "by", "more", "then", "min_visibility", "or", "whose", "area", "in", "pixels", "is", "under", "the", "threshold", "set", "by", "min_area", ".", "Also", "it", "crops", "boxes", "to", "final", "image", "size", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L204-L228
26,671
albu/albumentations
albumentations/augmentations/bbox_utils.py
union_of_bboxes
def union_of_bboxes(height, width, bboxes, erosion_rate=0.0, to_int=False): """Calculate union of bounding boxes. Args: height (float): Height of image or space. width (float): Width of image or space. bboxes (list): List like bounding boxes. Format is `[x_min, y_min, x_max, y_max]`. erosion_rate (float): How much each bounding box can be shrinked, useful for erosive cropping. Set this in range [0, 1]. 0 will not be erosive at all, 1.0 can make any bbox to lose its volume. """ x1, y1 = width, height x2, y2 = 0, 0 for b in bboxes: w, h = b[2] - b[0], b[3] - b[1] lim_x1, lim_y1 = b[0] + erosion_rate * w, b[1] + erosion_rate * h lim_x2, lim_y2 = b[2] - erosion_rate * w, b[3] - erosion_rate * h x1, y1 = np.min([x1, lim_x1]), np.min([y1, lim_y1]) x2, y2 = np.max([x2, lim_x2]), np.max([y2, lim_y2]) return x1, y1, x2, y2
python
def union_of_bboxes(height, width, bboxes, erosion_rate=0.0, to_int=False): """Calculate union of bounding boxes. Args: height (float): Height of image or space. width (float): Width of image or space. bboxes (list): List like bounding boxes. Format is `[x_min, y_min, x_max, y_max]`. erosion_rate (float): How much each bounding box can be shrinked, useful for erosive cropping. Set this in range [0, 1]. 0 will not be erosive at all, 1.0 can make any bbox to lose its volume. """ x1, y1 = width, height x2, y2 = 0, 0 for b in bboxes: w, h = b[2] - b[0], b[3] - b[1] lim_x1, lim_y1 = b[0] + erosion_rate * w, b[1] + erosion_rate * h lim_x2, lim_y2 = b[2] - erosion_rate * w, b[3] - erosion_rate * h x1, y1 = np.min([x1, lim_x1]), np.min([y1, lim_y1]) x2, y2 = np.max([x2, lim_x2]), np.max([y2, lim_y2]) return x1, y1, x2, y2
[ "def", "union_of_bboxes", "(", "height", ",", "width", ",", "bboxes", ",", "erosion_rate", "=", "0.0", ",", "to_int", "=", "False", ")", ":", "x1", ",", "y1", "=", "width", ",", "height", "x2", ",", "y2", "=", "0", ",", "0", "for", "b", "in", "bboxes", ":", "w", ",", "h", "=", "b", "[", "2", "]", "-", "b", "[", "0", "]", ",", "b", "[", "3", "]", "-", "b", "[", "1", "]", "lim_x1", ",", "lim_y1", "=", "b", "[", "0", "]", "+", "erosion_rate", "*", "w", ",", "b", "[", "1", "]", "+", "erosion_rate", "*", "h", "lim_x2", ",", "lim_y2", "=", "b", "[", "2", "]", "-", "erosion_rate", "*", "w", ",", "b", "[", "3", "]", "-", "erosion_rate", "*", "h", "x1", ",", "y1", "=", "np", ".", "min", "(", "[", "x1", ",", "lim_x1", "]", ")", ",", "np", ".", "min", "(", "[", "y1", ",", "lim_y1", "]", ")", "x2", ",", "y2", "=", "np", ".", "max", "(", "[", "x2", ",", "lim_x2", "]", ")", ",", "np", ".", "max", "(", "[", "y2", ",", "lim_y2", "]", ")", "return", "x1", ",", "y1", ",", "x2", ",", "y2" ]
Calculate union of bounding boxes. Args: height (float): Height of image or space. width (float): Width of image or space. bboxes (list): List like bounding boxes. Format is `[x_min, y_min, x_max, y_max]`. erosion_rate (float): How much each bounding box can be shrinked, useful for erosive cropping. Set this in range [0, 1]. 0 will not be erosive at all, 1.0 can make any bbox to lose its volume.
[ "Calculate", "union", "of", "bounding", "boxes", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L231-L249
26,672
albu/albumentations
albumentations/augmentations/keypoints_utils.py
check_keypoint
def check_keypoint(kp, rows, cols): """Check if keypoint coordinates are in range [0, 1)""" for name, value, size in zip(['x', 'y'], kp[:2], [cols, rows]): if not 0 <= value < size: raise ValueError( 'Expected {name} for keypoint {kp} ' 'to be in the range [0.0, {size}], got {value}.'.format( kp=kp, name=name, value=value, size=size ) )
python
def check_keypoint(kp, rows, cols): """Check if keypoint coordinates are in range [0, 1)""" for name, value, size in zip(['x', 'y'], kp[:2], [cols, rows]): if not 0 <= value < size: raise ValueError( 'Expected {name} for keypoint {kp} ' 'to be in the range [0.0, {size}], got {value}.'.format( kp=kp, name=name, value=value, size=size ) )
[ "def", "check_keypoint", "(", "kp", ",", "rows", ",", "cols", ")", ":", "for", "name", ",", "value", ",", "size", "in", "zip", "(", "[", "'x'", ",", "'y'", "]", ",", "kp", "[", ":", "2", "]", ",", "[", "cols", ",", "rows", "]", ")", ":", "if", "not", "0", "<=", "value", "<", "size", ":", "raise", "ValueError", "(", "'Expected {name} for keypoint {kp} '", "'to be in the range [0.0, {size}], got {value}.'", ".", "format", "(", "kp", "=", "kp", ",", "name", "=", "name", ",", "value", "=", "value", ",", "size", "=", "size", ")", ")" ]
Check if keypoint coordinates are in range [0, 1)
[ "Check", "if", "keypoint", "coordinates", "are", "in", "range", "[", "0", "1", ")" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/keypoints_utils.py#L5-L17
26,673
albu/albumentations
albumentations/augmentations/keypoints_utils.py
check_keypoints
def check_keypoints(keypoints, rows, cols): """Check if keypoints boundaries are in range [0, 1)""" for kp in keypoints: check_keypoint(kp, rows, cols)
python
def check_keypoints(keypoints, rows, cols): """Check if keypoints boundaries are in range [0, 1)""" for kp in keypoints: check_keypoint(kp, rows, cols)
[ "def", "check_keypoints", "(", "keypoints", ",", "rows", ",", "cols", ")", ":", "for", "kp", "in", "keypoints", ":", "check_keypoint", "(", "kp", ",", "rows", ",", "cols", ")" ]
Check if keypoints boundaries are in range [0, 1)
[ "Check", "if", "keypoints", "boundaries", "are", "in", "range", "[", "0", "1", ")" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/keypoints_utils.py#L20-L23
26,674
tornadoweb/tornado
tornado/autoreload.py
main
def main() -> None: """Command-line wrapper to re-run a script whenever its source changes. Scripts may be specified by filename or module name:: python -m tornado.autoreload -m tornado.test.runtests python -m tornado.autoreload tornado/test/runtests.py Running a script with this wrapper is similar to calling `tornado.autoreload.wait` at the end of the script, but this wrapper can catch import-time problems like syntax errors that would otherwise prevent the script from reaching its call to `wait`. """ # Remember that we were launched with autoreload as main. # The main module can be tricky; set the variables both in our globals # (which may be __main__) and the real importable version. import tornado.autoreload global _autoreload_is_main global _original_argv, _original_spec tornado.autoreload._autoreload_is_main = _autoreload_is_main = True original_argv = sys.argv tornado.autoreload._original_argv = _original_argv = original_argv original_spec = getattr(sys.modules["__main__"], "__spec__", None) tornado.autoreload._original_spec = _original_spec = original_spec sys.argv = sys.argv[:] if len(sys.argv) >= 3 and sys.argv[1] == "-m": mode = "module" module = sys.argv[2] del sys.argv[1:3] elif len(sys.argv) >= 2: mode = "script" script = sys.argv[1] sys.argv = sys.argv[1:] else: print(_USAGE, file=sys.stderr) sys.exit(1) try: if mode == "module": import runpy runpy.run_module(module, run_name="__main__", alter_sys=True) elif mode == "script": with open(script) as f: # Execute the script in our namespace instead of creating # a new one so that something that tries to import __main__ # (e.g. the unittest module) will see names defined in the # script instead of just those defined in this module. global __file__ __file__ = script # If __package__ is defined, imports may be incorrectly # interpreted as relative to this module. global __package__ del __package__ exec_in(f.read(), globals(), globals()) except SystemExit as e: logging.basicConfig() gen_log.info("Script exited with status %s", e.code) except Exception as e: logging.basicConfig() gen_log.warning("Script exited with uncaught exception", exc_info=True) # If an exception occurred at import time, the file with the error # never made it into sys.modules and so we won't know to watch it. # Just to make sure we've covered everything, walk the stack trace # from the exception and watch every file. for (filename, lineno, name, line) in traceback.extract_tb(sys.exc_info()[2]): watch(filename) if isinstance(e, SyntaxError): # SyntaxErrors are special: their innermost stack frame is fake # so extract_tb won't see it and we have to get the filename # from the exception object. watch(e.filename) else: logging.basicConfig() gen_log.info("Script exited normally") # restore sys.argv so subsequent executions will include autoreload sys.argv = original_argv if mode == "module": # runpy did a fake import of the module as __main__, but now it's # no longer in sys.modules. Figure out where it is and watch it. loader = pkgutil.get_loader(module) if loader is not None: watch(loader.get_filename()) # type: ignore wait()
python
def main() -> None: """Command-line wrapper to re-run a script whenever its source changes. Scripts may be specified by filename or module name:: python -m tornado.autoreload -m tornado.test.runtests python -m tornado.autoreload tornado/test/runtests.py Running a script with this wrapper is similar to calling `tornado.autoreload.wait` at the end of the script, but this wrapper can catch import-time problems like syntax errors that would otherwise prevent the script from reaching its call to `wait`. """ # Remember that we were launched with autoreload as main. # The main module can be tricky; set the variables both in our globals # (which may be __main__) and the real importable version. import tornado.autoreload global _autoreload_is_main global _original_argv, _original_spec tornado.autoreload._autoreload_is_main = _autoreload_is_main = True original_argv = sys.argv tornado.autoreload._original_argv = _original_argv = original_argv original_spec = getattr(sys.modules["__main__"], "__spec__", None) tornado.autoreload._original_spec = _original_spec = original_spec sys.argv = sys.argv[:] if len(sys.argv) >= 3 and sys.argv[1] == "-m": mode = "module" module = sys.argv[2] del sys.argv[1:3] elif len(sys.argv) >= 2: mode = "script" script = sys.argv[1] sys.argv = sys.argv[1:] else: print(_USAGE, file=sys.stderr) sys.exit(1) try: if mode == "module": import runpy runpy.run_module(module, run_name="__main__", alter_sys=True) elif mode == "script": with open(script) as f: # Execute the script in our namespace instead of creating # a new one so that something that tries to import __main__ # (e.g. the unittest module) will see names defined in the # script instead of just those defined in this module. global __file__ __file__ = script # If __package__ is defined, imports may be incorrectly # interpreted as relative to this module. global __package__ del __package__ exec_in(f.read(), globals(), globals()) except SystemExit as e: logging.basicConfig() gen_log.info("Script exited with status %s", e.code) except Exception as e: logging.basicConfig() gen_log.warning("Script exited with uncaught exception", exc_info=True) # If an exception occurred at import time, the file with the error # never made it into sys.modules and so we won't know to watch it. # Just to make sure we've covered everything, walk the stack trace # from the exception and watch every file. for (filename, lineno, name, line) in traceback.extract_tb(sys.exc_info()[2]): watch(filename) if isinstance(e, SyntaxError): # SyntaxErrors are special: their innermost stack frame is fake # so extract_tb won't see it and we have to get the filename # from the exception object. watch(e.filename) else: logging.basicConfig() gen_log.info("Script exited normally") # restore sys.argv so subsequent executions will include autoreload sys.argv = original_argv if mode == "module": # runpy did a fake import of the module as __main__, but now it's # no longer in sys.modules. Figure out where it is and watch it. loader = pkgutil.get_loader(module) if loader is not None: watch(loader.get_filename()) # type: ignore wait()
[ "def", "main", "(", ")", "->", "None", ":", "# Remember that we were launched with autoreload as main.", "# The main module can be tricky; set the variables both in our globals", "# (which may be __main__) and the real importable version.", "import", "tornado", ".", "autoreload", "global", "_autoreload_is_main", "global", "_original_argv", ",", "_original_spec", "tornado", ".", "autoreload", ".", "_autoreload_is_main", "=", "_autoreload_is_main", "=", "True", "original_argv", "=", "sys", ".", "argv", "tornado", ".", "autoreload", ".", "_original_argv", "=", "_original_argv", "=", "original_argv", "original_spec", "=", "getattr", "(", "sys", ".", "modules", "[", "\"__main__\"", "]", ",", "\"__spec__\"", ",", "None", ")", "tornado", ".", "autoreload", ".", "_original_spec", "=", "_original_spec", "=", "original_spec", "sys", ".", "argv", "=", "sys", ".", "argv", "[", ":", "]", "if", "len", "(", "sys", ".", "argv", ")", ">=", "3", "and", "sys", ".", "argv", "[", "1", "]", "==", "\"-m\"", ":", "mode", "=", "\"module\"", "module", "=", "sys", ".", "argv", "[", "2", "]", "del", "sys", ".", "argv", "[", "1", ":", "3", "]", "elif", "len", "(", "sys", ".", "argv", ")", ">=", "2", ":", "mode", "=", "\"script\"", "script", "=", "sys", ".", "argv", "[", "1", "]", "sys", ".", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", "else", ":", "print", "(", "_USAGE", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "if", "mode", "==", "\"module\"", ":", "import", "runpy", "runpy", ".", "run_module", "(", "module", ",", "run_name", "=", "\"__main__\"", ",", "alter_sys", "=", "True", ")", "elif", "mode", "==", "\"script\"", ":", "with", "open", "(", "script", ")", "as", "f", ":", "# Execute the script in our namespace instead of creating", "# a new one so that something that tries to import __main__", "# (e.g. the unittest module) will see names defined in the", "# script instead of just those defined in this module.", "global", "__file__", "__file__", "=", "script", "# If __package__ is defined, imports may be incorrectly", "# interpreted as relative to this module.", "global", "__package__", "del", "__package__", "exec_in", "(", "f", ".", "read", "(", ")", ",", "globals", "(", ")", ",", "globals", "(", ")", ")", "except", "SystemExit", "as", "e", ":", "logging", ".", "basicConfig", "(", ")", "gen_log", ".", "info", "(", "\"Script exited with status %s\"", ",", "e", ".", "code", ")", "except", "Exception", "as", "e", ":", "logging", ".", "basicConfig", "(", ")", "gen_log", ".", "warning", "(", "\"Script exited with uncaught exception\"", ",", "exc_info", "=", "True", ")", "# If an exception occurred at import time, the file with the error", "# never made it into sys.modules and so we won't know to watch it.", "# Just to make sure we've covered everything, walk the stack trace", "# from the exception and watch every file.", "for", "(", "filename", ",", "lineno", ",", "name", ",", "line", ")", "in", "traceback", ".", "extract_tb", "(", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", ":", "watch", "(", "filename", ")", "if", "isinstance", "(", "e", ",", "SyntaxError", ")", ":", "# SyntaxErrors are special: their innermost stack frame is fake", "# so extract_tb won't see it and we have to get the filename", "# from the exception object.", "watch", "(", "e", ".", "filename", ")", "else", ":", "logging", ".", "basicConfig", "(", ")", "gen_log", ".", "info", "(", "\"Script exited normally\"", ")", "# restore sys.argv so subsequent executions will include autoreload", "sys", ".", "argv", "=", "original_argv", "if", "mode", "==", "\"module\"", ":", "# runpy did a fake import of the module as __main__, but now it's", "# no longer in sys.modules. Figure out where it is and watch it.", "loader", "=", "pkgutil", ".", "get_loader", "(", "module", ")", "if", "loader", "is", "not", "None", ":", "watch", "(", "loader", ".", "get_filename", "(", ")", ")", "# type: ignore", "wait", "(", ")" ]
Command-line wrapper to re-run a script whenever its source changes. Scripts may be specified by filename or module name:: python -m tornado.autoreload -m tornado.test.runtests python -m tornado.autoreload tornado/test/runtests.py Running a script with this wrapper is similar to calling `tornado.autoreload.wait` at the end of the script, but this wrapper can catch import-time problems like syntax errors that would otherwise prevent the script from reaching its call to `wait`.
[ "Command", "-", "line", "wrapper", "to", "re", "-", "run", "a", "script", "whenever", "its", "source", "changes", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/autoreload.py#L272-L358
26,675
tornadoweb/tornado
tornado/tcpclient.py
_Connector.split
def split( addrinfo: List[Tuple] ) -> Tuple[ List[Tuple[socket.AddressFamily, Tuple]], List[Tuple[socket.AddressFamily, Tuple]], ]: """Partition the ``addrinfo`` list by address family. Returns two lists. The first list contains the first entry from ``addrinfo`` and all others with the same family, and the second list contains all other addresses (normally one list will be AF_INET and the other AF_INET6, although non-standard resolvers may return additional families). """ primary = [] secondary = [] primary_af = addrinfo[0][0] for af, addr in addrinfo: if af == primary_af: primary.append((af, addr)) else: secondary.append((af, addr)) return primary, secondary
python
def split( addrinfo: List[Tuple] ) -> Tuple[ List[Tuple[socket.AddressFamily, Tuple]], List[Tuple[socket.AddressFamily, Tuple]], ]: """Partition the ``addrinfo`` list by address family. Returns two lists. The first list contains the first entry from ``addrinfo`` and all others with the same family, and the second list contains all other addresses (normally one list will be AF_INET and the other AF_INET6, although non-standard resolvers may return additional families). """ primary = [] secondary = [] primary_af = addrinfo[0][0] for af, addr in addrinfo: if af == primary_af: primary.append((af, addr)) else: secondary.append((af, addr)) return primary, secondary
[ "def", "split", "(", "addrinfo", ":", "List", "[", "Tuple", "]", ")", "->", "Tuple", "[", "List", "[", "Tuple", "[", "socket", ".", "AddressFamily", ",", "Tuple", "]", "]", ",", "List", "[", "Tuple", "[", "socket", ".", "AddressFamily", ",", "Tuple", "]", "]", ",", "]", ":", "primary", "=", "[", "]", "secondary", "=", "[", "]", "primary_af", "=", "addrinfo", "[", "0", "]", "[", "0", "]", "for", "af", ",", "addr", "in", "addrinfo", ":", "if", "af", "==", "primary_af", ":", "primary", ".", "append", "(", "(", "af", ",", "addr", ")", ")", "else", ":", "secondary", ".", "append", "(", "(", "af", ",", "addr", ")", ")", "return", "primary", ",", "secondary" ]
Partition the ``addrinfo`` list by address family. Returns two lists. The first list contains the first entry from ``addrinfo`` and all others with the same family, and the second list contains all other addresses (normally one list will be AF_INET and the other AF_INET6, although non-standard resolvers may return additional families).
[ "Partition", "the", "addrinfo", "list", "by", "address", "family", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/tcpclient.py#L81-L103
26,676
tornadoweb/tornado
tornado/tcpclient.py
TCPClient.connect
async def connect( self, host: str, port: int, af: socket.AddressFamily = socket.AF_UNSPEC, ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None, max_buffer_size: int = None, source_ip: str = None, source_port: int = None, timeout: Union[float, datetime.timedelta] = None, ) -> IOStream: """Connect to the given host and port. Asynchronously returns an `.IOStream` (or `.SSLIOStream` if ``ssl_options`` is not None). Using the ``source_ip`` kwarg, one can specify the source IP address to use when establishing the connection. In case the user needs to resolve and use a specific interface, it has to be handled outside of Tornado as this depends very much on the platform. Raises `TimeoutError` if the input future does not complete before ``timeout``, which may be specified in any form allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time relative to `.IOLoop.time`) Similarly, when the user requires a certain source port, it can be specified using the ``source_port`` arg. .. versionchanged:: 4.5 Added the ``source_ip`` and ``source_port`` arguments. .. versionchanged:: 5.0 Added the ``timeout`` argument. """ if timeout is not None: if isinstance(timeout, numbers.Real): timeout = IOLoop.current().time() + timeout elif isinstance(timeout, datetime.timedelta): timeout = IOLoop.current().time() + timeout.total_seconds() else: raise TypeError("Unsupported timeout %r" % timeout) if timeout is not None: addrinfo = await gen.with_timeout( timeout, self.resolver.resolve(host, port, af) ) else: addrinfo = await self.resolver.resolve(host, port, af) connector = _Connector( addrinfo, functools.partial( self._create_stream, max_buffer_size, source_ip=source_ip, source_port=source_port, ), ) af, addr, stream = await connector.start(connect_timeout=timeout) # TODO: For better performance we could cache the (af, addr) # information here and re-use it on subsequent connections to # the same host. (http://tools.ietf.org/html/rfc6555#section-4.2) if ssl_options is not None: if timeout is not None: stream = await gen.with_timeout( timeout, stream.start_tls( False, ssl_options=ssl_options, server_hostname=host ), ) else: stream = await stream.start_tls( False, ssl_options=ssl_options, server_hostname=host ) return stream
python
async def connect( self, host: str, port: int, af: socket.AddressFamily = socket.AF_UNSPEC, ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None, max_buffer_size: int = None, source_ip: str = None, source_port: int = None, timeout: Union[float, datetime.timedelta] = None, ) -> IOStream: """Connect to the given host and port. Asynchronously returns an `.IOStream` (or `.SSLIOStream` if ``ssl_options`` is not None). Using the ``source_ip`` kwarg, one can specify the source IP address to use when establishing the connection. In case the user needs to resolve and use a specific interface, it has to be handled outside of Tornado as this depends very much on the platform. Raises `TimeoutError` if the input future does not complete before ``timeout``, which may be specified in any form allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time relative to `.IOLoop.time`) Similarly, when the user requires a certain source port, it can be specified using the ``source_port`` arg. .. versionchanged:: 4.5 Added the ``source_ip`` and ``source_port`` arguments. .. versionchanged:: 5.0 Added the ``timeout`` argument. """ if timeout is not None: if isinstance(timeout, numbers.Real): timeout = IOLoop.current().time() + timeout elif isinstance(timeout, datetime.timedelta): timeout = IOLoop.current().time() + timeout.total_seconds() else: raise TypeError("Unsupported timeout %r" % timeout) if timeout is not None: addrinfo = await gen.with_timeout( timeout, self.resolver.resolve(host, port, af) ) else: addrinfo = await self.resolver.resolve(host, port, af) connector = _Connector( addrinfo, functools.partial( self._create_stream, max_buffer_size, source_ip=source_ip, source_port=source_port, ), ) af, addr, stream = await connector.start(connect_timeout=timeout) # TODO: For better performance we could cache the (af, addr) # information here and re-use it on subsequent connections to # the same host. (http://tools.ietf.org/html/rfc6555#section-4.2) if ssl_options is not None: if timeout is not None: stream = await gen.with_timeout( timeout, stream.start_tls( False, ssl_options=ssl_options, server_hostname=host ), ) else: stream = await stream.start_tls( False, ssl_options=ssl_options, server_hostname=host ) return stream
[ "async", "def", "connect", "(", "self", ",", "host", ":", "str", ",", "port", ":", "int", ",", "af", ":", "socket", ".", "AddressFamily", "=", "socket", ".", "AF_UNSPEC", ",", "ssl_options", ":", "Union", "[", "Dict", "[", "str", ",", "Any", "]", ",", "ssl", ".", "SSLContext", "]", "=", "None", ",", "max_buffer_size", ":", "int", "=", "None", ",", "source_ip", ":", "str", "=", "None", ",", "source_port", ":", "int", "=", "None", ",", "timeout", ":", "Union", "[", "float", ",", "datetime", ".", "timedelta", "]", "=", "None", ",", ")", "->", "IOStream", ":", "if", "timeout", "is", "not", "None", ":", "if", "isinstance", "(", "timeout", ",", "numbers", ".", "Real", ")", ":", "timeout", "=", "IOLoop", ".", "current", "(", ")", ".", "time", "(", ")", "+", "timeout", "elif", "isinstance", "(", "timeout", ",", "datetime", ".", "timedelta", ")", ":", "timeout", "=", "IOLoop", ".", "current", "(", ")", ".", "time", "(", ")", "+", "timeout", ".", "total_seconds", "(", ")", "else", ":", "raise", "TypeError", "(", "\"Unsupported timeout %r\"", "%", "timeout", ")", "if", "timeout", "is", "not", "None", ":", "addrinfo", "=", "await", "gen", ".", "with_timeout", "(", "timeout", ",", "self", ".", "resolver", ".", "resolve", "(", "host", ",", "port", ",", "af", ")", ")", "else", ":", "addrinfo", "=", "await", "self", ".", "resolver", ".", "resolve", "(", "host", ",", "port", ",", "af", ")", "connector", "=", "_Connector", "(", "addrinfo", ",", "functools", ".", "partial", "(", "self", ".", "_create_stream", ",", "max_buffer_size", ",", "source_ip", "=", "source_ip", ",", "source_port", "=", "source_port", ",", ")", ",", ")", "af", ",", "addr", ",", "stream", "=", "await", "connector", ".", "start", "(", "connect_timeout", "=", "timeout", ")", "# TODO: For better performance we could cache the (af, addr)", "# information here and re-use it on subsequent connections to", "# the same host. (http://tools.ietf.org/html/rfc6555#section-4.2)", "if", "ssl_options", "is", "not", "None", ":", "if", "timeout", "is", "not", "None", ":", "stream", "=", "await", "gen", ".", "with_timeout", "(", "timeout", ",", "stream", ".", "start_tls", "(", "False", ",", "ssl_options", "=", "ssl_options", ",", "server_hostname", "=", "host", ")", ",", ")", "else", ":", "stream", "=", "await", "stream", ".", "start_tls", "(", "False", ",", "ssl_options", "=", "ssl_options", ",", "server_hostname", "=", "host", ")", "return", "stream" ]
Connect to the given host and port. Asynchronously returns an `.IOStream` (or `.SSLIOStream` if ``ssl_options`` is not None). Using the ``source_ip`` kwarg, one can specify the source IP address to use when establishing the connection. In case the user needs to resolve and use a specific interface, it has to be handled outside of Tornado as this depends very much on the platform. Raises `TimeoutError` if the input future does not complete before ``timeout``, which may be specified in any form allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time relative to `.IOLoop.time`) Similarly, when the user requires a certain source port, it can be specified using the ``source_port`` arg. .. versionchanged:: 4.5 Added the ``source_ip`` and ``source_port`` arguments. .. versionchanged:: 5.0 Added the ``timeout`` argument.
[ "Connect", "to", "the", "given", "host", "and", "port", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/tcpclient.py#L222-L296
26,677
tornadoweb/tornado
tornado/httpserver.py
HTTPServer.close_all_connections
async def close_all_connections(self) -> None: """Close all open connections and asynchronously wait for them to finish. This method is used in combination with `~.TCPServer.stop` to support clean shutdowns (especially for unittests). Typical usage would call ``stop()`` first to stop accepting new connections, then ``await close_all_connections()`` to wait for existing connections to finish. This method does not currently close open websocket connections. Note that this method is a coroutine and must be caled with ``await``. """ while self._connections: # Peek at an arbitrary element of the set conn = next(iter(self._connections)) await conn.close()
python
async def close_all_connections(self) -> None: """Close all open connections and asynchronously wait for them to finish. This method is used in combination with `~.TCPServer.stop` to support clean shutdowns (especially for unittests). Typical usage would call ``stop()`` first to stop accepting new connections, then ``await close_all_connections()`` to wait for existing connections to finish. This method does not currently close open websocket connections. Note that this method is a coroutine and must be caled with ``await``. """ while self._connections: # Peek at an arbitrary element of the set conn = next(iter(self._connections)) await conn.close()
[ "async", "def", "close_all_connections", "(", "self", ")", "->", "None", ":", "while", "self", ".", "_connections", ":", "# Peek at an arbitrary element of the set", "conn", "=", "next", "(", "iter", "(", "self", ".", "_connections", ")", ")", "await", "conn", ".", "close", "(", ")" ]
Close all open connections and asynchronously wait for them to finish. This method is used in combination with `~.TCPServer.stop` to support clean shutdowns (especially for unittests). Typical usage would call ``stop()`` first to stop accepting new connections, then ``await close_all_connections()`` to wait for existing connections to finish. This method does not currently close open websocket connections. Note that this method is a coroutine and must be caled with ``await``.
[ "Close", "all", "open", "connections", "and", "asynchronously", "wait", "for", "them", "to", "finish", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httpserver.py#L204-L221
26,678
tornadoweb/tornado
tornado/httpserver.py
_HTTPRequestContext._apply_xheaders
def _apply_xheaders(self, headers: httputil.HTTPHeaders) -> None: """Rewrite the ``remote_ip`` and ``protocol`` fields.""" # Squid uses X-Forwarded-For, others use X-Real-Ip ip = headers.get("X-Forwarded-For", self.remote_ip) # Skip trusted downstream hosts in X-Forwarded-For list for ip in (cand.strip() for cand in reversed(ip.split(","))): if ip not in self.trusted_downstream: break ip = headers.get("X-Real-Ip", ip) if netutil.is_valid_ip(ip): self.remote_ip = ip # AWS uses X-Forwarded-Proto proto_header = headers.get( "X-Scheme", headers.get("X-Forwarded-Proto", self.protocol) ) if proto_header: # use only the last proto entry if there is more than one # TODO: support trusting mutiple layers of proxied protocol proto_header = proto_header.split(",")[-1].strip() if proto_header in ("http", "https"): self.protocol = proto_header
python
def _apply_xheaders(self, headers: httputil.HTTPHeaders) -> None: """Rewrite the ``remote_ip`` and ``protocol`` fields.""" # Squid uses X-Forwarded-For, others use X-Real-Ip ip = headers.get("X-Forwarded-For", self.remote_ip) # Skip trusted downstream hosts in X-Forwarded-For list for ip in (cand.strip() for cand in reversed(ip.split(","))): if ip not in self.trusted_downstream: break ip = headers.get("X-Real-Ip", ip) if netutil.is_valid_ip(ip): self.remote_ip = ip # AWS uses X-Forwarded-Proto proto_header = headers.get( "X-Scheme", headers.get("X-Forwarded-Proto", self.protocol) ) if proto_header: # use only the last proto entry if there is more than one # TODO: support trusting mutiple layers of proxied protocol proto_header = proto_header.split(",")[-1].strip() if proto_header in ("http", "https"): self.protocol = proto_header
[ "def", "_apply_xheaders", "(", "self", ",", "headers", ":", "httputil", ".", "HTTPHeaders", ")", "->", "None", ":", "# Squid uses X-Forwarded-For, others use X-Real-Ip", "ip", "=", "headers", ".", "get", "(", "\"X-Forwarded-For\"", ",", "self", ".", "remote_ip", ")", "# Skip trusted downstream hosts in X-Forwarded-For list", "for", "ip", "in", "(", "cand", ".", "strip", "(", ")", "for", "cand", "in", "reversed", "(", "ip", ".", "split", "(", "\",\"", ")", ")", ")", ":", "if", "ip", "not", "in", "self", ".", "trusted_downstream", ":", "break", "ip", "=", "headers", ".", "get", "(", "\"X-Real-Ip\"", ",", "ip", ")", "if", "netutil", ".", "is_valid_ip", "(", "ip", ")", ":", "self", ".", "remote_ip", "=", "ip", "# AWS uses X-Forwarded-Proto", "proto_header", "=", "headers", ".", "get", "(", "\"X-Scheme\"", ",", "headers", ".", "get", "(", "\"X-Forwarded-Proto\"", ",", "self", ".", "protocol", ")", ")", "if", "proto_header", ":", "# use only the last proto entry if there is more than one", "# TODO: support trusting mutiple layers of proxied protocol", "proto_header", "=", "proto_header", ".", "split", "(", "\",\"", ")", "[", "-", "1", "]", ".", "strip", "(", ")", "if", "proto_header", "in", "(", "\"http\"", ",", "\"https\"", ")", ":", "self", ".", "protocol", "=", "proto_header" ]
Rewrite the ``remote_ip`` and ``protocol`` fields.
[ "Rewrite", "the", "remote_ip", "and", "protocol", "fields", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httpserver.py#L332-L352
26,679
tornadoweb/tornado
tornado/httpserver.py
_HTTPRequestContext._unapply_xheaders
def _unapply_xheaders(self) -> None: """Undo changes from `_apply_xheaders`. Xheaders are per-request so they should not leak to the next request on the same connection. """ self.remote_ip = self._orig_remote_ip self.protocol = self._orig_protocol
python
def _unapply_xheaders(self) -> None: """Undo changes from `_apply_xheaders`. Xheaders are per-request so they should not leak to the next request on the same connection. """ self.remote_ip = self._orig_remote_ip self.protocol = self._orig_protocol
[ "def", "_unapply_xheaders", "(", "self", ")", "->", "None", ":", "self", ".", "remote_ip", "=", "self", ".", "_orig_remote_ip", "self", ".", "protocol", "=", "self", ".", "_orig_protocol" ]
Undo changes from `_apply_xheaders`. Xheaders are per-request so they should not leak to the next request on the same connection.
[ "Undo", "changes", "from", "_apply_xheaders", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httpserver.py#L354-L361
26,680
tornadoweb/tornado
tornado/locale.py
set_default_locale
def set_default_locale(code: str) -> None: """Sets the default locale. The default locale is assumed to be the language used for all strings in the system. The translations loaded from disk are mappings from the default locale to the destination locale. Consequently, you don't need to create a translation file for the default locale. """ global _default_locale global _supported_locales _default_locale = code _supported_locales = frozenset(list(_translations.keys()) + [_default_locale])
python
def set_default_locale(code: str) -> None: """Sets the default locale. The default locale is assumed to be the language used for all strings in the system. The translations loaded from disk are mappings from the default locale to the destination locale. Consequently, you don't need to create a translation file for the default locale. """ global _default_locale global _supported_locales _default_locale = code _supported_locales = frozenset(list(_translations.keys()) + [_default_locale])
[ "def", "set_default_locale", "(", "code", ":", "str", ")", "->", "None", ":", "global", "_default_locale", "global", "_supported_locales", "_default_locale", "=", "code", "_supported_locales", "=", "frozenset", "(", "list", "(", "_translations", ".", "keys", "(", ")", ")", "+", "[", "_default_locale", "]", ")" ]
Sets the default locale. The default locale is assumed to be the language used for all strings in the system. The translations loaded from disk are mappings from the default locale to the destination locale. Consequently, you don't need to create a translation file for the default locale.
[ "Sets", "the", "default", "locale", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L77-L88
26,681
tornadoweb/tornado
tornado/locale.py
load_translations
def load_translations(directory: str, encoding: str = None) -> None: """Loads translations from CSV files in a directory. Translations are strings with optional Python-style named placeholders (e.g., ``My name is %(name)s``) and their associated translations. The directory should have translation files of the form ``LOCALE.csv``, e.g. ``es_GT.csv``. The CSV files should have two or three columns: string, translation, and an optional plural indicator. Plural indicators should be one of "plural" or "singular". A given string can have both singular and plural forms. For example ``%(name)s liked this`` may have a different verb conjugation depending on whether %(name)s is one name or a list of names. There should be two rows in the CSV file for that string, one with plural indicator "singular", and one "plural". For strings with no verbs that would change on translation, simply use "unknown" or the empty string (or don't include the column at all). The file is read using the `csv` module in the default "excel" dialect. In this format there should not be spaces after the commas. If no ``encoding`` parameter is given, the encoding will be detected automatically (among UTF-8 and UTF-16) if the file contains a byte-order marker (BOM), defaulting to UTF-8 if no BOM is present. Example translation ``es_LA.csv``:: "I love you","Te amo" "%(name)s liked this","A %(name)s les gustó esto","plural" "%(name)s liked this","A %(name)s le gustó esto","singular" .. versionchanged:: 4.3 Added ``encoding`` parameter. Added support for BOM-based encoding detection, UTF-16, and UTF-8-with-BOM. """ global _translations global _supported_locales _translations = {} for path in os.listdir(directory): if not path.endswith(".csv"): continue locale, extension = path.split(".") if not re.match("[a-z]+(_[A-Z]+)?$", locale): gen_log.error( "Unrecognized locale %r (path: %s)", locale, os.path.join(directory, path), ) continue full_path = os.path.join(directory, path) if encoding is None: # Try to autodetect encoding based on the BOM. with open(full_path, "rb") as bf: data = bf.read(len(codecs.BOM_UTF16_LE)) if data in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): encoding = "utf-16" else: # utf-8-sig is "utf-8 with optional BOM". It's discouraged # in most cases but is common with CSV files because Excel # cannot read utf-8 files without a BOM. encoding = "utf-8-sig" # python 3: csv.reader requires a file open in text mode. # Specify an encoding to avoid dependence on $LANG environment variable. with open(full_path, encoding=encoding) as f: _translations[locale] = {} for i, row in enumerate(csv.reader(f)): if not row or len(row) < 2: continue row = [escape.to_unicode(c).strip() for c in row] english, translation = row[:2] if len(row) > 2: plural = row[2] or "unknown" else: plural = "unknown" if plural not in ("plural", "singular", "unknown"): gen_log.error( "Unrecognized plural indicator %r in %s line %d", plural, path, i + 1, ) continue _translations[locale].setdefault(plural, {})[english] = translation _supported_locales = frozenset(list(_translations.keys()) + [_default_locale]) gen_log.debug("Supported locales: %s", sorted(_supported_locales))
python
def load_translations(directory: str, encoding: str = None) -> None: """Loads translations from CSV files in a directory. Translations are strings with optional Python-style named placeholders (e.g., ``My name is %(name)s``) and their associated translations. The directory should have translation files of the form ``LOCALE.csv``, e.g. ``es_GT.csv``. The CSV files should have two or three columns: string, translation, and an optional plural indicator. Plural indicators should be one of "plural" or "singular". A given string can have both singular and plural forms. For example ``%(name)s liked this`` may have a different verb conjugation depending on whether %(name)s is one name or a list of names. There should be two rows in the CSV file for that string, one with plural indicator "singular", and one "plural". For strings with no verbs that would change on translation, simply use "unknown" or the empty string (or don't include the column at all). The file is read using the `csv` module in the default "excel" dialect. In this format there should not be spaces after the commas. If no ``encoding`` parameter is given, the encoding will be detected automatically (among UTF-8 and UTF-16) if the file contains a byte-order marker (BOM), defaulting to UTF-8 if no BOM is present. Example translation ``es_LA.csv``:: "I love you","Te amo" "%(name)s liked this","A %(name)s les gustó esto","plural" "%(name)s liked this","A %(name)s le gustó esto","singular" .. versionchanged:: 4.3 Added ``encoding`` parameter. Added support for BOM-based encoding detection, UTF-16, and UTF-8-with-BOM. """ global _translations global _supported_locales _translations = {} for path in os.listdir(directory): if not path.endswith(".csv"): continue locale, extension = path.split(".") if not re.match("[a-z]+(_[A-Z]+)?$", locale): gen_log.error( "Unrecognized locale %r (path: %s)", locale, os.path.join(directory, path), ) continue full_path = os.path.join(directory, path) if encoding is None: # Try to autodetect encoding based on the BOM. with open(full_path, "rb") as bf: data = bf.read(len(codecs.BOM_UTF16_LE)) if data in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): encoding = "utf-16" else: # utf-8-sig is "utf-8 with optional BOM". It's discouraged # in most cases but is common with CSV files because Excel # cannot read utf-8 files without a BOM. encoding = "utf-8-sig" # python 3: csv.reader requires a file open in text mode. # Specify an encoding to avoid dependence on $LANG environment variable. with open(full_path, encoding=encoding) as f: _translations[locale] = {} for i, row in enumerate(csv.reader(f)): if not row or len(row) < 2: continue row = [escape.to_unicode(c).strip() for c in row] english, translation = row[:2] if len(row) > 2: plural = row[2] or "unknown" else: plural = "unknown" if plural not in ("plural", "singular", "unknown"): gen_log.error( "Unrecognized plural indicator %r in %s line %d", plural, path, i + 1, ) continue _translations[locale].setdefault(plural, {})[english] = translation _supported_locales = frozenset(list(_translations.keys()) + [_default_locale]) gen_log.debug("Supported locales: %s", sorted(_supported_locales))
[ "def", "load_translations", "(", "directory", ":", "str", ",", "encoding", ":", "str", "=", "None", ")", "->", "None", ":", "global", "_translations", "global", "_supported_locales", "_translations", "=", "{", "}", "for", "path", "in", "os", ".", "listdir", "(", "directory", ")", ":", "if", "not", "path", ".", "endswith", "(", "\".csv\"", ")", ":", "continue", "locale", ",", "extension", "=", "path", ".", "split", "(", "\".\"", ")", "if", "not", "re", ".", "match", "(", "\"[a-z]+(_[A-Z]+)?$\"", ",", "locale", ")", ":", "gen_log", ".", "error", "(", "\"Unrecognized locale %r (path: %s)\"", ",", "locale", ",", "os", ".", "path", ".", "join", "(", "directory", ",", "path", ")", ",", ")", "continue", "full_path", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "path", ")", "if", "encoding", "is", "None", ":", "# Try to autodetect encoding based on the BOM.", "with", "open", "(", "full_path", ",", "\"rb\"", ")", "as", "bf", ":", "data", "=", "bf", ".", "read", "(", "len", "(", "codecs", ".", "BOM_UTF16_LE", ")", ")", "if", "data", "in", "(", "codecs", ".", "BOM_UTF16_LE", ",", "codecs", ".", "BOM_UTF16_BE", ")", ":", "encoding", "=", "\"utf-16\"", "else", ":", "# utf-8-sig is \"utf-8 with optional BOM\". It's discouraged", "# in most cases but is common with CSV files because Excel", "# cannot read utf-8 files without a BOM.", "encoding", "=", "\"utf-8-sig\"", "# python 3: csv.reader requires a file open in text mode.", "# Specify an encoding to avoid dependence on $LANG environment variable.", "with", "open", "(", "full_path", ",", "encoding", "=", "encoding", ")", "as", "f", ":", "_translations", "[", "locale", "]", "=", "{", "}", "for", "i", ",", "row", "in", "enumerate", "(", "csv", ".", "reader", "(", "f", ")", ")", ":", "if", "not", "row", "or", "len", "(", "row", ")", "<", "2", ":", "continue", "row", "=", "[", "escape", ".", "to_unicode", "(", "c", ")", ".", "strip", "(", ")", "for", "c", "in", "row", "]", "english", ",", "translation", "=", "row", "[", ":", "2", "]", "if", "len", "(", "row", ")", ">", "2", ":", "plural", "=", "row", "[", "2", "]", "or", "\"unknown\"", "else", ":", "plural", "=", "\"unknown\"", "if", "plural", "not", "in", "(", "\"plural\"", ",", "\"singular\"", ",", "\"unknown\"", ")", ":", "gen_log", ".", "error", "(", "\"Unrecognized plural indicator %r in %s line %d\"", ",", "plural", ",", "path", ",", "i", "+", "1", ",", ")", "continue", "_translations", "[", "locale", "]", ".", "setdefault", "(", "plural", ",", "{", "}", ")", "[", "english", "]", "=", "translation", "_supported_locales", "=", "frozenset", "(", "list", "(", "_translations", ".", "keys", "(", ")", ")", "+", "[", "_default_locale", "]", ")", "gen_log", ".", "debug", "(", "\"Supported locales: %s\"", ",", "sorted", "(", "_supported_locales", ")", ")" ]
Loads translations from CSV files in a directory. Translations are strings with optional Python-style named placeholders (e.g., ``My name is %(name)s``) and their associated translations. The directory should have translation files of the form ``LOCALE.csv``, e.g. ``es_GT.csv``. The CSV files should have two or three columns: string, translation, and an optional plural indicator. Plural indicators should be one of "plural" or "singular". A given string can have both singular and plural forms. For example ``%(name)s liked this`` may have a different verb conjugation depending on whether %(name)s is one name or a list of names. There should be two rows in the CSV file for that string, one with plural indicator "singular", and one "plural". For strings with no verbs that would change on translation, simply use "unknown" or the empty string (or don't include the column at all). The file is read using the `csv` module in the default "excel" dialect. In this format there should not be spaces after the commas. If no ``encoding`` parameter is given, the encoding will be detected automatically (among UTF-8 and UTF-16) if the file contains a byte-order marker (BOM), defaulting to UTF-8 if no BOM is present. Example translation ``es_LA.csv``:: "I love you","Te amo" "%(name)s liked this","A %(name)s les gustó esto","plural" "%(name)s liked this","A %(name)s le gustó esto","singular" .. versionchanged:: 4.3 Added ``encoding`` parameter. Added support for BOM-based encoding detection, UTF-16, and UTF-8-with-BOM.
[ "Loads", "translations", "from", "CSV", "files", "in", "a", "directory", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L91-L175
26,682
tornadoweb/tornado
tornado/locale.py
load_gettext_translations
def load_gettext_translations(directory: str, domain: str) -> None: """Loads translations from `gettext`'s locale tree Locale tree is similar to system's ``/usr/share/locale``, like:: {directory}/{lang}/LC_MESSAGES/{domain}.mo Three steps are required to have your app translated: 1. Generate POT translation file:: xgettext --language=Python --keyword=_:1,2 -d mydomain file1.py file2.html etc 2. Merge against existing POT file:: msgmerge old.po mydomain.po > new.po 3. Compile:: msgfmt mydomain.po -o {directory}/pt_BR/LC_MESSAGES/mydomain.mo """ global _translations global _supported_locales global _use_gettext _translations = {} for lang in os.listdir(directory): if lang.startswith("."): continue # skip .svn, etc if os.path.isfile(os.path.join(directory, lang)): continue try: os.stat(os.path.join(directory, lang, "LC_MESSAGES", domain + ".mo")) _translations[lang] = gettext.translation( domain, directory, languages=[lang] ) except Exception as e: gen_log.error("Cannot load translation for '%s': %s", lang, str(e)) continue _supported_locales = frozenset(list(_translations.keys()) + [_default_locale]) _use_gettext = True gen_log.debug("Supported locales: %s", sorted(_supported_locales))
python
def load_gettext_translations(directory: str, domain: str) -> None: """Loads translations from `gettext`'s locale tree Locale tree is similar to system's ``/usr/share/locale``, like:: {directory}/{lang}/LC_MESSAGES/{domain}.mo Three steps are required to have your app translated: 1. Generate POT translation file:: xgettext --language=Python --keyword=_:1,2 -d mydomain file1.py file2.html etc 2. Merge against existing POT file:: msgmerge old.po mydomain.po > new.po 3. Compile:: msgfmt mydomain.po -o {directory}/pt_BR/LC_MESSAGES/mydomain.mo """ global _translations global _supported_locales global _use_gettext _translations = {} for lang in os.listdir(directory): if lang.startswith("."): continue # skip .svn, etc if os.path.isfile(os.path.join(directory, lang)): continue try: os.stat(os.path.join(directory, lang, "LC_MESSAGES", domain + ".mo")) _translations[lang] = gettext.translation( domain, directory, languages=[lang] ) except Exception as e: gen_log.error("Cannot load translation for '%s': %s", lang, str(e)) continue _supported_locales = frozenset(list(_translations.keys()) + [_default_locale]) _use_gettext = True gen_log.debug("Supported locales: %s", sorted(_supported_locales))
[ "def", "load_gettext_translations", "(", "directory", ":", "str", ",", "domain", ":", "str", ")", "->", "None", ":", "global", "_translations", "global", "_supported_locales", "global", "_use_gettext", "_translations", "=", "{", "}", "for", "lang", "in", "os", ".", "listdir", "(", "directory", ")", ":", "if", "lang", ".", "startswith", "(", "\".\"", ")", ":", "continue", "# skip .svn, etc", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "lang", ")", ")", ":", "continue", "try", ":", "os", ".", "stat", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "lang", ",", "\"LC_MESSAGES\"", ",", "domain", "+", "\".mo\"", ")", ")", "_translations", "[", "lang", "]", "=", "gettext", ".", "translation", "(", "domain", ",", "directory", ",", "languages", "=", "[", "lang", "]", ")", "except", "Exception", "as", "e", ":", "gen_log", ".", "error", "(", "\"Cannot load translation for '%s': %s\"", ",", "lang", ",", "str", "(", "e", ")", ")", "continue", "_supported_locales", "=", "frozenset", "(", "list", "(", "_translations", ".", "keys", "(", ")", ")", "+", "[", "_default_locale", "]", ")", "_use_gettext", "=", "True", "gen_log", ".", "debug", "(", "\"Supported locales: %s\"", ",", "sorted", "(", "_supported_locales", ")", ")" ]
Loads translations from `gettext`'s locale tree Locale tree is similar to system's ``/usr/share/locale``, like:: {directory}/{lang}/LC_MESSAGES/{domain}.mo Three steps are required to have your app translated: 1. Generate POT translation file:: xgettext --language=Python --keyword=_:1,2 -d mydomain file1.py file2.html etc 2. Merge against existing POT file:: msgmerge old.po mydomain.po > new.po 3. Compile:: msgfmt mydomain.po -o {directory}/pt_BR/LC_MESSAGES/mydomain.mo
[ "Loads", "translations", "from", "gettext", "s", "locale", "tree" ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L178-L218
26,683
tornadoweb/tornado
tornado/locale.py
Locale.get_closest
def get_closest(cls, *locale_codes: str) -> "Locale": """Returns the closest match for the given locale code.""" for code in locale_codes: if not code: continue code = code.replace("-", "_") parts = code.split("_") if len(parts) > 2: continue elif len(parts) == 2: code = parts[0].lower() + "_" + parts[1].upper() if code in _supported_locales: return cls.get(code) if parts[0].lower() in _supported_locales: return cls.get(parts[0].lower()) return cls.get(_default_locale)
python
def get_closest(cls, *locale_codes: str) -> "Locale": """Returns the closest match for the given locale code.""" for code in locale_codes: if not code: continue code = code.replace("-", "_") parts = code.split("_") if len(parts) > 2: continue elif len(parts) == 2: code = parts[0].lower() + "_" + parts[1].upper() if code in _supported_locales: return cls.get(code) if parts[0].lower() in _supported_locales: return cls.get(parts[0].lower()) return cls.get(_default_locale)
[ "def", "get_closest", "(", "cls", ",", "*", "locale_codes", ":", "str", ")", "->", "\"Locale\"", ":", "for", "code", "in", "locale_codes", ":", "if", "not", "code", ":", "continue", "code", "=", "code", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", "parts", "=", "code", ".", "split", "(", "\"_\"", ")", "if", "len", "(", "parts", ")", ">", "2", ":", "continue", "elif", "len", "(", "parts", ")", "==", "2", ":", "code", "=", "parts", "[", "0", "]", ".", "lower", "(", ")", "+", "\"_\"", "+", "parts", "[", "1", "]", ".", "upper", "(", ")", "if", "code", "in", "_supported_locales", ":", "return", "cls", ".", "get", "(", "code", ")", "if", "parts", "[", "0", "]", ".", "lower", "(", ")", "in", "_supported_locales", ":", "return", "cls", ".", "get", "(", "parts", "[", "0", "]", ".", "lower", "(", ")", ")", "return", "cls", ".", "get", "(", "_default_locale", ")" ]
Returns the closest match for the given locale code.
[ "Returns", "the", "closest", "match", "for", "the", "given", "locale", "code", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L236-L251
26,684
tornadoweb/tornado
tornado/locale.py
Locale.get
def get(cls, code: str) -> "Locale": """Returns the Locale for the given locale code. If it is not supported, we raise an exception. """ if code not in cls._cache: assert code in _supported_locales translations = _translations.get(code, None) if translations is None: locale = CSVLocale(code, {}) # type: Locale elif _use_gettext: locale = GettextLocale(code, translations) else: locale = CSVLocale(code, translations) cls._cache[code] = locale return cls._cache[code]
python
def get(cls, code: str) -> "Locale": """Returns the Locale for the given locale code. If it is not supported, we raise an exception. """ if code not in cls._cache: assert code in _supported_locales translations = _translations.get(code, None) if translations is None: locale = CSVLocale(code, {}) # type: Locale elif _use_gettext: locale = GettextLocale(code, translations) else: locale = CSVLocale(code, translations) cls._cache[code] = locale return cls._cache[code]
[ "def", "get", "(", "cls", ",", "code", ":", "str", ")", "->", "\"Locale\"", ":", "if", "code", "not", "in", "cls", ".", "_cache", ":", "assert", "code", "in", "_supported_locales", "translations", "=", "_translations", ".", "get", "(", "code", ",", "None", ")", "if", "translations", "is", "None", ":", "locale", "=", "CSVLocale", "(", "code", ",", "{", "}", ")", "# type: Locale", "elif", "_use_gettext", ":", "locale", "=", "GettextLocale", "(", "code", ",", "translations", ")", "else", ":", "locale", "=", "CSVLocale", "(", "code", ",", "translations", ")", "cls", ".", "_cache", "[", "code", "]", "=", "locale", "return", "cls", ".", "_cache", "[", "code", "]" ]
Returns the Locale for the given locale code. If it is not supported, we raise an exception.
[ "Returns", "the", "Locale", "for", "the", "given", "locale", "code", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L254-L269
26,685
tornadoweb/tornado
tornado/locale.py
Locale.translate
def translate( self, message: str, plural_message: str = None, count: int = None ) -> str: """Returns the translation for the given message for this locale. If ``plural_message`` is given, you must also provide ``count``. We return ``plural_message`` when ``count != 1``, and we return the singular form for the given message when ``count == 1``. """ raise NotImplementedError()
python
def translate( self, message: str, plural_message: str = None, count: int = None ) -> str: """Returns the translation for the given message for this locale. If ``plural_message`` is given, you must also provide ``count``. We return ``plural_message`` when ``count != 1``, and we return the singular form for the given message when ``count == 1``. """ raise NotImplementedError()
[ "def", "translate", "(", "self", ",", "message", ":", "str", ",", "plural_message", ":", "str", "=", "None", ",", "count", ":", "int", "=", "None", ")", "->", "str", ":", "raise", "NotImplementedError", "(", ")" ]
Returns the translation for the given message for this locale. If ``plural_message`` is given, you must also provide ``count``. We return ``plural_message`` when ``count != 1``, and we return the singular form for the given message when ``count == 1``.
[ "Returns", "the", "translation", "for", "the", "given", "message", "for", "this", "locale", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L306-L316
26,686
tornadoweb/tornado
tornado/locale.py
Locale.format_day
def format_day( self, date: datetime.datetime, gmt_offset: int = 0, dow: bool = True ) -> bool: """Formats the given date as a day of week. Example: "Monday, January 22". You can remove the day of week with ``dow=False``. """ local_date = date - datetime.timedelta(minutes=gmt_offset) _ = self.translate if dow: return _("%(weekday)s, %(month_name)s %(day)s") % { "month_name": self._months[local_date.month - 1], "weekday": self._weekdays[local_date.weekday()], "day": str(local_date.day), } else: return _("%(month_name)s %(day)s") % { "month_name": self._months[local_date.month - 1], "day": str(local_date.day), }
python
def format_day( self, date: datetime.datetime, gmt_offset: int = 0, dow: bool = True ) -> bool: """Formats the given date as a day of week. Example: "Monday, January 22". You can remove the day of week with ``dow=False``. """ local_date = date - datetime.timedelta(minutes=gmt_offset) _ = self.translate if dow: return _("%(weekday)s, %(month_name)s %(day)s") % { "month_name": self._months[local_date.month - 1], "weekday": self._weekdays[local_date.weekday()], "day": str(local_date.day), } else: return _("%(month_name)s %(day)s") % { "month_name": self._months[local_date.month - 1], "day": str(local_date.day), }
[ "def", "format_day", "(", "self", ",", "date", ":", "datetime", ".", "datetime", ",", "gmt_offset", ":", "int", "=", "0", ",", "dow", ":", "bool", "=", "True", ")", "->", "bool", ":", "local_date", "=", "date", "-", "datetime", ".", "timedelta", "(", "minutes", "=", "gmt_offset", ")", "_", "=", "self", ".", "translate", "if", "dow", ":", "return", "_", "(", "\"%(weekday)s, %(month_name)s %(day)s\"", ")", "%", "{", "\"month_name\"", ":", "self", ".", "_months", "[", "local_date", ".", "month", "-", "1", "]", ",", "\"weekday\"", ":", "self", ".", "_weekdays", "[", "local_date", ".", "weekday", "(", ")", "]", ",", "\"day\"", ":", "str", "(", "local_date", ".", "day", ")", ",", "}", "else", ":", "return", "_", "(", "\"%(month_name)s %(day)s\"", ")", "%", "{", "\"month_name\"", ":", "self", ".", "_months", "[", "local_date", ".", "month", "-", "1", "]", ",", "\"day\"", ":", "str", "(", "local_date", ".", "day", ")", ",", "}" ]
Formats the given date as a day of week. Example: "Monday, January 22". You can remove the day of week with ``dow=False``.
[ "Formats", "the", "given", "date", "as", "a", "day", "of", "week", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L423-L443
26,687
tornadoweb/tornado
tornado/locale.py
Locale.list
def list(self, parts: Any) -> str: """Returns a comma-separated list for the given list of parts. The format is, e.g., "A, B and C", "A and B" or just "A" for lists of size 1. """ _ = self.translate if len(parts) == 0: return "" if len(parts) == 1: return parts[0] comma = u" \u0648 " if self.code.startswith("fa") else u", " return _("%(commas)s and %(last)s") % { "commas": comma.join(parts[:-1]), "last": parts[len(parts) - 1], }
python
def list(self, parts: Any) -> str: """Returns a comma-separated list for the given list of parts. The format is, e.g., "A, B and C", "A and B" or just "A" for lists of size 1. """ _ = self.translate if len(parts) == 0: return "" if len(parts) == 1: return parts[0] comma = u" \u0648 " if self.code.startswith("fa") else u", " return _("%(commas)s and %(last)s") % { "commas": comma.join(parts[:-1]), "last": parts[len(parts) - 1], }
[ "def", "list", "(", "self", ",", "parts", ":", "Any", ")", "->", "str", ":", "_", "=", "self", ".", "translate", "if", "len", "(", "parts", ")", "==", "0", ":", "return", "\"\"", "if", "len", "(", "parts", ")", "==", "1", ":", "return", "parts", "[", "0", "]", "comma", "=", "u\" \\u0648 \"", "if", "self", ".", "code", ".", "startswith", "(", "\"fa\"", ")", "else", "u\", \"", "return", "_", "(", "\"%(commas)s and %(last)s\"", ")", "%", "{", "\"commas\"", ":", "comma", ".", "join", "(", "parts", "[", ":", "-", "1", "]", ")", ",", "\"last\"", ":", "parts", "[", "len", "(", "parts", ")", "-", "1", "]", ",", "}" ]
Returns a comma-separated list for the given list of parts. The format is, e.g., "A, B and C", "A and B" or just "A" for lists of size 1.
[ "Returns", "a", "comma", "-", "separated", "list", "for", "the", "given", "list", "of", "parts", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L445-L460
26,688
tornadoweb/tornado
tornado/locale.py
Locale.friendly_number
def friendly_number(self, value: int) -> str: """Returns a comma-separated number for the given integer.""" if self.code not in ("en", "en_US"): return str(value) s = str(value) parts = [] while s: parts.append(s[-3:]) s = s[:-3] return ",".join(reversed(parts))
python
def friendly_number(self, value: int) -> str: """Returns a comma-separated number for the given integer.""" if self.code not in ("en", "en_US"): return str(value) s = str(value) parts = [] while s: parts.append(s[-3:]) s = s[:-3] return ",".join(reversed(parts))
[ "def", "friendly_number", "(", "self", ",", "value", ":", "int", ")", "->", "str", ":", "if", "self", ".", "code", "not", "in", "(", "\"en\"", ",", "\"en_US\"", ")", ":", "return", "str", "(", "value", ")", "s", "=", "str", "(", "value", ")", "parts", "=", "[", "]", "while", "s", ":", "parts", ".", "append", "(", "s", "[", "-", "3", ":", "]", ")", "s", "=", "s", "[", ":", "-", "3", "]", "return", "\",\"", ".", "join", "(", "reversed", "(", "parts", ")", ")" ]
Returns a comma-separated number for the given integer.
[ "Returns", "a", "comma", "-", "separated", "number", "for", "the", "given", "integer", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L462-L471
26,689
tornadoweb/tornado
tornado/locale.py
GettextLocale.pgettext
def pgettext( self, context: str, message: str, plural_message: str = None, count: int = None ) -> str: """Allows to set context for translation, accepts plural forms. Usage example:: pgettext("law", "right") pgettext("good", "right") Plural message example:: pgettext("organization", "club", "clubs", len(clubs)) pgettext("stick", "club", "clubs", len(clubs)) To generate POT file with context, add following options to step 1 of `load_gettext_translations` sequence:: xgettext [basic options] --keyword=pgettext:1c,2 --keyword=pgettext:1c,2,3 .. versionadded:: 4.2 """ if plural_message is not None: assert count is not None msgs_with_ctxt = ( "%s%s%s" % (context, CONTEXT_SEPARATOR, message), "%s%s%s" % (context, CONTEXT_SEPARATOR, plural_message), count, ) result = self.ngettext(*msgs_with_ctxt) if CONTEXT_SEPARATOR in result: # Translation not found result = self.ngettext(message, plural_message, count) return result else: msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message) result = self.gettext(msg_with_ctxt) if CONTEXT_SEPARATOR in result: # Translation not found result = message return result
python
def pgettext( self, context: str, message: str, plural_message: str = None, count: int = None ) -> str: """Allows to set context for translation, accepts plural forms. Usage example:: pgettext("law", "right") pgettext("good", "right") Plural message example:: pgettext("organization", "club", "clubs", len(clubs)) pgettext("stick", "club", "clubs", len(clubs)) To generate POT file with context, add following options to step 1 of `load_gettext_translations` sequence:: xgettext [basic options] --keyword=pgettext:1c,2 --keyword=pgettext:1c,2,3 .. versionadded:: 4.2 """ if plural_message is not None: assert count is not None msgs_with_ctxt = ( "%s%s%s" % (context, CONTEXT_SEPARATOR, message), "%s%s%s" % (context, CONTEXT_SEPARATOR, plural_message), count, ) result = self.ngettext(*msgs_with_ctxt) if CONTEXT_SEPARATOR in result: # Translation not found result = self.ngettext(message, plural_message, count) return result else: msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message) result = self.gettext(msg_with_ctxt) if CONTEXT_SEPARATOR in result: # Translation not found result = message return result
[ "def", "pgettext", "(", "self", ",", "context", ":", "str", ",", "message", ":", "str", ",", "plural_message", ":", "str", "=", "None", ",", "count", ":", "int", "=", "None", ")", "->", "str", ":", "if", "plural_message", "is", "not", "None", ":", "assert", "count", "is", "not", "None", "msgs_with_ctxt", "=", "(", "\"%s%s%s\"", "%", "(", "context", ",", "CONTEXT_SEPARATOR", ",", "message", ")", ",", "\"%s%s%s\"", "%", "(", "context", ",", "CONTEXT_SEPARATOR", ",", "plural_message", ")", ",", "count", ",", ")", "result", "=", "self", ".", "ngettext", "(", "*", "msgs_with_ctxt", ")", "if", "CONTEXT_SEPARATOR", "in", "result", ":", "# Translation not found", "result", "=", "self", ".", "ngettext", "(", "message", ",", "plural_message", ",", "count", ")", "return", "result", "else", ":", "msg_with_ctxt", "=", "\"%s%s%s\"", "%", "(", "context", ",", "CONTEXT_SEPARATOR", ",", "message", ")", "result", "=", "self", ".", "gettext", "(", "msg_with_ctxt", ")", "if", "CONTEXT_SEPARATOR", "in", "result", ":", "# Translation not found", "result", "=", "message", "return", "result" ]
Allows to set context for translation, accepts plural forms. Usage example:: pgettext("law", "right") pgettext("good", "right") Plural message example:: pgettext("organization", "club", "clubs", len(clubs)) pgettext("stick", "club", "clubs", len(clubs)) To generate POT file with context, add following options to step 1 of `load_gettext_translations` sequence:: xgettext [basic options] --keyword=pgettext:1c,2 --keyword=pgettext:1c,2,3 .. versionadded:: 4.2
[ "Allows", "to", "set", "context", "for", "translation", "accepts", "plural", "forms", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L522-L562
26,690
tornadoweb/tornado
tornado/routing.py
_unquote_or_none
def _unquote_or_none(s: Optional[str]) -> Optional[bytes]: # noqa: F811 """None-safe wrapper around url_unescape to handle unmatched optional groups correctly. Note that args are passed as bytes so the handler can decide what encoding to use. """ if s is None: return s return url_unescape(s, encoding=None, plus=False)
python
def _unquote_or_none(s: Optional[str]) -> Optional[bytes]: # noqa: F811 """None-safe wrapper around url_unescape to handle unmatched optional groups correctly. Note that args are passed as bytes so the handler can decide what encoding to use. """ if s is None: return s return url_unescape(s, encoding=None, plus=False)
[ "def", "_unquote_or_none", "(", "s", ":", "Optional", "[", "str", "]", ")", "->", "Optional", "[", "bytes", "]", ":", "# noqa: F811", "if", "s", "is", "None", ":", "return", "s", "return", "url_unescape", "(", "s", ",", "encoding", "=", "None", ",", "plus", "=", "False", ")" ]
None-safe wrapper around url_unescape to handle unmatched optional groups correctly. Note that args are passed as bytes so the handler can decide what encoding to use.
[ "None", "-", "safe", "wrapper", "around", "url_unescape", "to", "handle", "unmatched", "optional", "groups", "correctly", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L702-L711
26,691
tornadoweb/tornado
tornado/routing.py
Router.find_handler
def find_handler( self, request: httputil.HTTPServerRequest, **kwargs: Any ) -> Optional[httputil.HTTPMessageDelegate]: """Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate` that can serve the request. Routing implementations may pass additional kwargs to extend the routing logic. :arg httputil.HTTPServerRequest request: current HTTP request. :arg kwargs: additional keyword arguments passed by routing implementation. :returns: an instance of `~.httputil.HTTPMessageDelegate` that will be used to process the request. """ raise NotImplementedError()
python
def find_handler( self, request: httputil.HTTPServerRequest, **kwargs: Any ) -> Optional[httputil.HTTPMessageDelegate]: """Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate` that can serve the request. Routing implementations may pass additional kwargs to extend the routing logic. :arg httputil.HTTPServerRequest request: current HTTP request. :arg kwargs: additional keyword arguments passed by routing implementation. :returns: an instance of `~.httputil.HTTPMessageDelegate` that will be used to process the request. """ raise NotImplementedError()
[ "def", "find_handler", "(", "self", ",", "request", ":", "httputil", ".", "HTTPServerRequest", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Optional", "[", "httputil", ".", "HTTPMessageDelegate", "]", ":", "raise", "NotImplementedError", "(", ")" ]
Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate` that can serve the request. Routing implementations may pass additional kwargs to extend the routing logic. :arg httputil.HTTPServerRequest request: current HTTP request. :arg kwargs: additional keyword arguments passed by routing implementation. :returns: an instance of `~.httputil.HTTPMessageDelegate` that will be used to process the request.
[ "Must", "be", "implemented", "to", "return", "an", "appropriate", "instance", "of", "~", ".", "httputil", ".", "HTTPMessageDelegate", "that", "can", "serve", "the", "request", ".", "Routing", "implementations", "may", "pass", "additional", "kwargs", "to", "extend", "the", "routing", "logic", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L193-L205
26,692
tornadoweb/tornado
tornado/routing.py
RuleRouter.add_rules
def add_rules(self, rules: _RuleList) -> None: """Appends new rules to the router. :arg rules: a list of Rule instances (or tuples of arguments, which are passed to Rule constructor). """ for rule in rules: if isinstance(rule, (tuple, list)): assert len(rule) in (2, 3, 4) if isinstance(rule[0], basestring_type): rule = Rule(PathMatches(rule[0]), *rule[1:]) else: rule = Rule(*rule) self.rules.append(self.process_rule(rule))
python
def add_rules(self, rules: _RuleList) -> None: """Appends new rules to the router. :arg rules: a list of Rule instances (or tuples of arguments, which are passed to Rule constructor). """ for rule in rules: if isinstance(rule, (tuple, list)): assert len(rule) in (2, 3, 4) if isinstance(rule[0], basestring_type): rule = Rule(PathMatches(rule[0]), *rule[1:]) else: rule = Rule(*rule) self.rules.append(self.process_rule(rule))
[ "def", "add_rules", "(", "self", ",", "rules", ":", "_RuleList", ")", "->", "None", ":", "for", "rule", "in", "rules", ":", "if", "isinstance", "(", "rule", ",", "(", "tuple", ",", "list", ")", ")", ":", "assert", "len", "(", "rule", ")", "in", "(", "2", ",", "3", ",", "4", ")", "if", "isinstance", "(", "rule", "[", "0", "]", ",", "basestring_type", ")", ":", "rule", "=", "Rule", "(", "PathMatches", "(", "rule", "[", "0", "]", ")", ",", "*", "rule", "[", "1", ":", "]", ")", "else", ":", "rule", "=", "Rule", "(", "*", "rule", ")", "self", ".", "rules", ".", "append", "(", "self", ".", "process_rule", "(", "rule", ")", ")" ]
Appends new rules to the router. :arg rules: a list of Rule instances (or tuples of arguments, which are passed to Rule constructor).
[ "Appends", "new", "rules", "to", "the", "router", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L334-L348
26,693
tornadoweb/tornado
tornado/routing.py
RuleRouter.get_target_delegate
def get_target_delegate( self, target: Any, request: httputil.HTTPServerRequest, **target_params: Any ) -> Optional[httputil.HTTPMessageDelegate]: """Returns an instance of `~.httputil.HTTPMessageDelegate` for a Rule's target. This method is called by `~.find_handler` and can be extended to provide additional target types. :arg target: a Rule's target. :arg httputil.HTTPServerRequest request: current request. :arg target_params: additional parameters that can be useful for `~.httputil.HTTPMessageDelegate` creation. """ if isinstance(target, Router): return target.find_handler(request, **target_params) elif isinstance(target, httputil.HTTPServerConnectionDelegate): assert request.connection is not None return target.start_request(request.server_connection, request.connection) elif callable(target): assert request.connection is not None return _CallableAdapter( partial(target, **target_params), request.connection ) return None
python
def get_target_delegate( self, target: Any, request: httputil.HTTPServerRequest, **target_params: Any ) -> Optional[httputil.HTTPMessageDelegate]: """Returns an instance of `~.httputil.HTTPMessageDelegate` for a Rule's target. This method is called by `~.find_handler` and can be extended to provide additional target types. :arg target: a Rule's target. :arg httputil.HTTPServerRequest request: current request. :arg target_params: additional parameters that can be useful for `~.httputil.HTTPMessageDelegate` creation. """ if isinstance(target, Router): return target.find_handler(request, **target_params) elif isinstance(target, httputil.HTTPServerConnectionDelegate): assert request.connection is not None return target.start_request(request.server_connection, request.connection) elif callable(target): assert request.connection is not None return _CallableAdapter( partial(target, **target_params), request.connection ) return None
[ "def", "get_target_delegate", "(", "self", ",", "target", ":", "Any", ",", "request", ":", "httputil", ".", "HTTPServerRequest", ",", "*", "*", "target_params", ":", "Any", ")", "->", "Optional", "[", "httputil", ".", "HTTPMessageDelegate", "]", ":", "if", "isinstance", "(", "target", ",", "Router", ")", ":", "return", "target", ".", "find_handler", "(", "request", ",", "*", "*", "target_params", ")", "elif", "isinstance", "(", "target", ",", "httputil", ".", "HTTPServerConnectionDelegate", ")", ":", "assert", "request", ".", "connection", "is", "not", "None", "return", "target", ".", "start_request", "(", "request", ".", "server_connection", ",", "request", ".", "connection", ")", "elif", "callable", "(", "target", ")", ":", "assert", "request", ".", "connection", "is", "not", "None", "return", "_CallableAdapter", "(", "partial", "(", "target", ",", "*", "*", "target_params", ")", ",", "request", ".", "connection", ")", "return", "None" ]
Returns an instance of `~.httputil.HTTPMessageDelegate` for a Rule's target. This method is called by `~.find_handler` and can be extended to provide additional target types. :arg target: a Rule's target. :arg httputil.HTTPServerRequest request: current request. :arg target_params: additional parameters that can be useful for `~.httputil.HTTPMessageDelegate` creation.
[ "Returns", "an", "instance", "of", "~", ".", "httputil", ".", "HTTPMessageDelegate", "for", "a", "Rule", "s", "target", ".", "This", "method", "is", "called", "by", "~", ".", "find_handler", "and", "can", "be", "extended", "to", "provide", "additional", "target", "types", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L376-L401
26,694
tornadoweb/tornado
tornado/routing.py
Matcher.match
def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]: """Matches current instance against the request. :arg httputil.HTTPServerRequest request: current HTTP request :returns: a dict of parameters to be passed to the target handler (for example, ``handler_kwargs``, ``path_args``, ``path_kwargs`` can be passed for proper `~.web.RequestHandler` instantiation). An empty dict is a valid (and common) return value to indicate a match when the argument-passing features are not used. ``None`` must be returned to indicate that there is no match.""" raise NotImplementedError()
python
def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]: """Matches current instance against the request. :arg httputil.HTTPServerRequest request: current HTTP request :returns: a dict of parameters to be passed to the target handler (for example, ``handler_kwargs``, ``path_args``, ``path_kwargs`` can be passed for proper `~.web.RequestHandler` instantiation). An empty dict is a valid (and common) return value to indicate a match when the argument-passing features are not used. ``None`` must be returned to indicate that there is no match.""" raise NotImplementedError()
[ "def", "match", "(", "self", ",", "request", ":", "httputil", ".", "HTTPServerRequest", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "raise", "NotImplementedError", "(", ")" ]
Matches current instance against the request. :arg httputil.HTTPServerRequest request: current HTTP request :returns: a dict of parameters to be passed to the target handler (for example, ``handler_kwargs``, ``path_args``, ``path_kwargs`` can be passed for proper `~.web.RequestHandler` instantiation). An empty dict is a valid (and common) return value to indicate a match when the argument-passing features are not used. ``None`` must be returned to indicate that there is no match.
[ "Matches", "current", "instance", "against", "the", "request", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L493-L503
26,695
tornadoweb/tornado
demos/webspider/webspider.py
get_links_from_url
async def get_links_from_url(url): """Download the page at `url` and parse it for links. Returned links have had the fragment after `#` removed, and have been made absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes 'http://www.tornadoweb.org/en/stable/gen.html'. """ response = await httpclient.AsyncHTTPClient().fetch(url) print("fetched %s" % url) html = response.body.decode(errors="ignore") return [urljoin(url, remove_fragment(new_url)) for new_url in get_links(html)]
python
async def get_links_from_url(url): """Download the page at `url` and parse it for links. Returned links have had the fragment after `#` removed, and have been made absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes 'http://www.tornadoweb.org/en/stable/gen.html'. """ response = await httpclient.AsyncHTTPClient().fetch(url) print("fetched %s" % url) html = response.body.decode(errors="ignore") return [urljoin(url, remove_fragment(new_url)) for new_url in get_links(html)]
[ "async", "def", "get_links_from_url", "(", "url", ")", ":", "response", "=", "await", "httpclient", ".", "AsyncHTTPClient", "(", ")", ".", "fetch", "(", "url", ")", "print", "(", "\"fetched %s\"", "%", "url", ")", "html", "=", "response", ".", "body", ".", "decode", "(", "errors", "=", "\"ignore\"", ")", "return", "[", "urljoin", "(", "url", ",", "remove_fragment", "(", "new_url", ")", ")", "for", "new_url", "in", "get_links", "(", "html", ")", "]" ]
Download the page at `url` and parse it for links. Returned links have had the fragment after `#` removed, and have been made absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes 'http://www.tornadoweb.org/en/stable/gen.html'.
[ "Download", "the", "page", "at", "url", "and", "parse", "it", "for", "links", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/demos/webspider/webspider.py#L15-L26
26,696
tornadoweb/tornado
demos/chat/chatdemo.py
MessageBuffer.get_messages_since
def get_messages_since(self, cursor): """Returns a list of messages newer than the given cursor. ``cursor`` should be the ``id`` of the last message received. """ results = [] for msg in reversed(self.cache): if msg["id"] == cursor: break results.append(msg) results.reverse() return results
python
def get_messages_since(self, cursor): """Returns a list of messages newer than the given cursor. ``cursor`` should be the ``id`` of the last message received. """ results = [] for msg in reversed(self.cache): if msg["id"] == cursor: break results.append(msg) results.reverse() return results
[ "def", "get_messages_since", "(", "self", ",", "cursor", ")", ":", "results", "=", "[", "]", "for", "msg", "in", "reversed", "(", "self", ".", "cache", ")", ":", "if", "msg", "[", "\"id\"", "]", "==", "cursor", ":", "break", "results", ".", "append", "(", "msg", ")", "results", ".", "reverse", "(", ")", "return", "results" ]
Returns a list of messages newer than the given cursor. ``cursor`` should be the ``id`` of the last message received.
[ "Returns", "a", "list", "of", "messages", "newer", "than", "the", "given", "cursor", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/demos/chat/chatdemo.py#L38-L49
26,697
tornadoweb/tornado
tornado/util.py
import_object
def import_object(name: str) -> Any: """Imports an object by name. ``import_object('x')`` is equivalent to ``import x``. ``import_object('x.y.z')`` is equivalent to ``from x.y import z``. >>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> import_object('tornado.escape.utf8') is tornado.escape.utf8 True >>> import_object('tornado') is tornado True >>> import_object('tornado.missing_module') Traceback (most recent call last): ... ImportError: No module named missing_module """ if name.count(".") == 0: return __import__(name) parts = name.split(".") obj = __import__(".".join(parts[:-1]), fromlist=[parts[-1]]) try: return getattr(obj, parts[-1]) except AttributeError: raise ImportError("No module named %s" % parts[-1])
python
def import_object(name: str) -> Any: """Imports an object by name. ``import_object('x')`` is equivalent to ``import x``. ``import_object('x.y.z')`` is equivalent to ``from x.y import z``. >>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> import_object('tornado.escape.utf8') is tornado.escape.utf8 True >>> import_object('tornado') is tornado True >>> import_object('tornado.missing_module') Traceback (most recent call last): ... ImportError: No module named missing_module """ if name.count(".") == 0: return __import__(name) parts = name.split(".") obj = __import__(".".join(parts[:-1]), fromlist=[parts[-1]]) try: return getattr(obj, parts[-1]) except AttributeError: raise ImportError("No module named %s" % parts[-1])
[ "def", "import_object", "(", "name", ":", "str", ")", "->", "Any", ":", "if", "name", ".", "count", "(", "\".\"", ")", "==", "0", ":", "return", "__import__", "(", "name", ")", "parts", "=", "name", ".", "split", "(", "\".\"", ")", "obj", "=", "__import__", "(", "\".\"", ".", "join", "(", "parts", "[", ":", "-", "1", "]", ")", ",", "fromlist", "=", "[", "parts", "[", "-", "1", "]", "]", ")", "try", ":", "return", "getattr", "(", "obj", ",", "parts", "[", "-", "1", "]", ")", "except", "AttributeError", ":", "raise", "ImportError", "(", "\"No module named %s\"", "%", "parts", "[", "-", "1", "]", ")" ]
Imports an object by name. ``import_object('x')`` is equivalent to ``import x``. ``import_object('x.y.z')`` is equivalent to ``from x.y import z``. >>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> import_object('tornado.escape.utf8') is tornado.escape.utf8 True >>> import_object('tornado') is tornado True >>> import_object('tornado.missing_module') Traceback (most recent call last): ... ImportError: No module named missing_module
[ "Imports", "an", "object", "by", "name", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L131-L157
26,698
tornadoweb/tornado
tornado/util.py
GzipDecompressor.decompress
def decompress(self, value: bytes, max_length: int = 0) -> bytes: """Decompress a chunk, returning newly-available data. Some data may be buffered for later processing; `flush` must be called when there is no more input data to ensure that all data was processed. If ``max_length`` is given, some input data may be left over in ``unconsumed_tail``; you must retrieve this value and pass it back to a future call to `decompress` if it is not empty. """ return self.decompressobj.decompress(value, max_length)
python
def decompress(self, value: bytes, max_length: int = 0) -> bytes: """Decompress a chunk, returning newly-available data. Some data may be buffered for later processing; `flush` must be called when there is no more input data to ensure that all data was processed. If ``max_length`` is given, some input data may be left over in ``unconsumed_tail``; you must retrieve this value and pass it back to a future call to `decompress` if it is not empty. """ return self.decompressobj.decompress(value, max_length)
[ "def", "decompress", "(", "self", ",", "value", ":", "bytes", ",", "max_length", ":", "int", "=", "0", ")", "->", "bytes", ":", "return", "self", ".", "decompressobj", ".", "decompress", "(", "value", ",", "max_length", ")" ]
Decompress a chunk, returning newly-available data. Some data may be buffered for later processing; `flush` must be called when there is no more input data to ensure that all data was processed. If ``max_length`` is given, some input data may be left over in ``unconsumed_tail``; you must retrieve this value and pass it back to a future call to `decompress` if it is not empty.
[ "Decompress", "a", "chunk", "returning", "newly", "-", "available", "data", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L103-L114
26,699
tornadoweb/tornado
tornado/wsgi.py
WSGIContainer.environ
def environ(request: httputil.HTTPServerRequest) -> Dict[Text, Any]: """Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment. """ hostport = request.host.split(":") if len(hostport) == 2: host = hostport[0] port = int(hostport[1]) else: host = request.host port = 443 if request.protocol == "https" else 80 environ = { "REQUEST_METHOD": request.method, "SCRIPT_NAME": "", "PATH_INFO": to_wsgi_str( escape.url_unescape(request.path, encoding=None, plus=False) ), "QUERY_STRING": request.query, "REMOTE_ADDR": request.remote_ip, "SERVER_NAME": host, "SERVER_PORT": str(port), "SERVER_PROTOCOL": request.version, "wsgi.version": (1, 0), "wsgi.url_scheme": request.protocol, "wsgi.input": BytesIO(escape.utf8(request.body)), "wsgi.errors": sys.stderr, "wsgi.multithread": False, "wsgi.multiprocess": True, "wsgi.run_once": False, } if "Content-Type" in request.headers: environ["CONTENT_TYPE"] = request.headers.pop("Content-Type") if "Content-Length" in request.headers: environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length") for key, value in request.headers.items(): environ["HTTP_" + key.replace("-", "_").upper()] = value return environ
python
def environ(request: httputil.HTTPServerRequest) -> Dict[Text, Any]: """Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment. """ hostport = request.host.split(":") if len(hostport) == 2: host = hostport[0] port = int(hostport[1]) else: host = request.host port = 443 if request.protocol == "https" else 80 environ = { "REQUEST_METHOD": request.method, "SCRIPT_NAME": "", "PATH_INFO": to_wsgi_str( escape.url_unescape(request.path, encoding=None, plus=False) ), "QUERY_STRING": request.query, "REMOTE_ADDR": request.remote_ip, "SERVER_NAME": host, "SERVER_PORT": str(port), "SERVER_PROTOCOL": request.version, "wsgi.version": (1, 0), "wsgi.url_scheme": request.protocol, "wsgi.input": BytesIO(escape.utf8(request.body)), "wsgi.errors": sys.stderr, "wsgi.multithread": False, "wsgi.multiprocess": True, "wsgi.run_once": False, } if "Content-Type" in request.headers: environ["CONTENT_TYPE"] = request.headers.pop("Content-Type") if "Content-Length" in request.headers: environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length") for key, value in request.headers.items(): environ["HTTP_" + key.replace("-", "_").upper()] = value return environ
[ "def", "environ", "(", "request", ":", "httputil", ".", "HTTPServerRequest", ")", "->", "Dict", "[", "Text", ",", "Any", "]", ":", "hostport", "=", "request", ".", "host", ".", "split", "(", "\":\"", ")", "if", "len", "(", "hostport", ")", "==", "2", ":", "host", "=", "hostport", "[", "0", "]", "port", "=", "int", "(", "hostport", "[", "1", "]", ")", "else", ":", "host", "=", "request", ".", "host", "port", "=", "443", "if", "request", ".", "protocol", "==", "\"https\"", "else", "80", "environ", "=", "{", "\"REQUEST_METHOD\"", ":", "request", ".", "method", ",", "\"SCRIPT_NAME\"", ":", "\"\"", ",", "\"PATH_INFO\"", ":", "to_wsgi_str", "(", "escape", ".", "url_unescape", "(", "request", ".", "path", ",", "encoding", "=", "None", ",", "plus", "=", "False", ")", ")", ",", "\"QUERY_STRING\"", ":", "request", ".", "query", ",", "\"REMOTE_ADDR\"", ":", "request", ".", "remote_ip", ",", "\"SERVER_NAME\"", ":", "host", ",", "\"SERVER_PORT\"", ":", "str", "(", "port", ")", ",", "\"SERVER_PROTOCOL\"", ":", "request", ".", "version", ",", "\"wsgi.version\"", ":", "(", "1", ",", "0", ")", ",", "\"wsgi.url_scheme\"", ":", "request", ".", "protocol", ",", "\"wsgi.input\"", ":", "BytesIO", "(", "escape", ".", "utf8", "(", "request", ".", "body", ")", ")", ",", "\"wsgi.errors\"", ":", "sys", ".", "stderr", ",", "\"wsgi.multithread\"", ":", "False", ",", "\"wsgi.multiprocess\"", ":", "True", ",", "\"wsgi.run_once\"", ":", "False", ",", "}", "if", "\"Content-Type\"", "in", "request", ".", "headers", ":", "environ", "[", "\"CONTENT_TYPE\"", "]", "=", "request", ".", "headers", ".", "pop", "(", "\"Content-Type\"", ")", "if", "\"Content-Length\"", "in", "request", ".", "headers", ":", "environ", "[", "\"CONTENT_LENGTH\"", "]", "=", "request", ".", "headers", ".", "pop", "(", "\"Content-Length\"", ")", "for", "key", ",", "value", "in", "request", ".", "headers", ".", "items", "(", ")", ":", "environ", "[", "\"HTTP_\"", "+", "key", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", ".", "upper", "(", ")", "]", "=", "value", "return", "environ" ]
Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.
[ "Converts", "a", "tornado", ".", "httputil", ".", "HTTPServerRequest", "to", "a", "WSGI", "environment", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/wsgi.py#L148-L183