partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | Sanic.enable_websocket | Enable or disable the support for websocket.
Websocket is enabled automatically if websocket routes are
added to the application. | sanic/app.py | 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
... | 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
... | [
"Enable",
"or",
"disable",
"the",
"support",
"for",
"websocket",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L537-L551 | [
"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",
".",
"liste... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Sanic.remove_route | This method provides the app user a mechanism by which an already
existing route can be removed from the :class:`Sanic` object
:param uri: URL Path to be removed from the app
:param clean_cache: Instruct sanic if it needs to clean up the LRU
route cache
:param host: IP addre... | sanic/app.py | def remove_route(self, uri, clean_cache=True, host=None):
"""
This method provides the app user a mechanism by which an already
existing route can be removed from the :class:`Sanic` object
:param uri: URL Path to be removed from the app
:param clean_cache: Instruct sanic if it n... | def remove_route(self, uri, clean_cache=True, host=None):
"""
This method provides the app user a mechanism by which an already
existing route can be removed from the :class:`Sanic` object
:param uri: URL Path to be removed from the app
:param clean_cache: Instruct sanic if it n... | [
"This",
"method",
"provides",
"the",
"app",
"user",
"a",
"mechanism",
"by",
"which",
"an",
"already",
"existing",
"route",
"can",
"be",
"removed",
"from",
"the",
":",
"class",
":",
"Sanic",
"object"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L553-L564 | [
"def",
"remove_route",
"(",
"self",
",",
"uri",
",",
"clean_cache",
"=",
"True",
",",
"host",
"=",
"None",
")",
":",
"self",
".",
"router",
".",
"remove",
"(",
"uri",
",",
"clean_cache",
",",
"host",
")"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Sanic.exception | Decorate a function to be registered as a handler for exceptions
:param exceptions: exceptions
:return: decorated function | sanic/app.py | 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, l... | 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, l... | [
"Decorate",
"a",
"function",
"to",
"be",
"registered",
"as",
"a",
"handler",
"for",
"exceptions"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L567-L583 | [
"def",
"exception",
"(",
"self",
",",
"*",
"exceptions",
")",
":",
"def",
"response",
"(",
"handler",
")",
":",
"for",
"exception",
"in",
"exceptions",
":",
"if",
"isinstance",
"(",
"exception",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"for",
"... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Sanic.register_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
mi... | sanic/app.py | 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 lev... | 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 lev... | [
"Register",
"an",
"application",
"level",
"middleware",
"that",
"will",
"be",
"attached",
"to",
"all",
"the",
"API",
"URLs",
"registered",
"under",
"this",
"application",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L585-L607 | [
"def",
"register_middleware",
"(",
"self",
",",
"middleware",
",",
"attach_to",
"=",
"\"request\"",
")",
":",
"if",
"attach_to",
"==",
"\"request\"",
":",
"if",
"middleware",
"not",
"in",
"self",
".",
"request_middleware",
":",
"self",
".",
"request_middleware",... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Sanic.middleware | Decorate and register middleware to be called before a request.
Can either be called as *@app.middleware* or
*@app.middleware('request')*
:param: middleware_or_request: Optional parameter to use for
identifying which type of middleware is being registered. | sanic/app.py | def middleware(self, middleware_or_request):
"""
Decorate and register middleware to be called before a request.
Can either be called as *@app.middleware* or
*@app.middleware('request')*
:param: middleware_or_request: Optional parameter to use for
identifying which t... | def middleware(self, middleware_or_request):
"""
Decorate and register middleware to be called before a request.
Can either be called as *@app.middleware* or
*@app.middleware('request')*
:param: middleware_or_request: Optional parameter to use for
identifying which t... | [
"Decorate",
"and",
"register",
"middleware",
"to",
"be",
"called",
"before",
"a",
"request",
".",
"Can",
"either",
"be",
"called",
"as",
"*",
"@app",
".",
"middleware",
"*",
"or",
"*",
"@app",
".",
"middleware",
"(",
"request",
")",
"*"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L610-L626 | [
"def",
"middleware",
"(",
"self",
",",
"middleware_or_request",
")",
":",
"# Detect which way this was called, @middleware or @middleware('AT')",
"if",
"callable",
"(",
"middleware_or_request",
")",
":",
"return",
"self",
".",
"register_middleware",
"(",
"middleware_or_reques... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Sanic.static | Register a root to serve files from. The input can either be a
file or a directory. This method will enable an easy and simple way
to setup the :class:`Route` necessary to serve the static files.
:param uri: URL path to be used for serving static content
:param file_or_directory: Path f... | sanic/app.py | def static(
self,
uri,
file_or_directory,
pattern=r"/?.+",
use_modified_since=True,
use_content_range=False,
stream_large_files=False,
name="static",
host=None,
strict_slashes=None,
content_type=None,
):
"""
Regi... | def static(
self,
uri,
file_or_directory,
pattern=r"/?.+",
use_modified_since=True,
use_content_range=False,
stream_large_files=False,
name="static",
host=None,
strict_slashes=None,
content_type=None,
):
"""
Regi... | [
"Register",
"a",
"root",
"to",
"serve",
"files",
"from",
".",
"The",
"input",
"can",
"either",
"be",
"a",
"file",
"or",
"a",
"directory",
".",
"This",
"method",
"will",
"enable",
"an",
"easy",
"and",
"simple",
"way",
"to",
"setup",
"the",
":",
"class",... | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L629-L679 | [
"def",
"static",
"(",
"self",
",",
"uri",
",",
"file_or_directory",
",",
"pattern",
"=",
"r\"/?.+\"",
",",
"use_modified_since",
"=",
"True",
",",
"use_content_range",
"=",
"False",
",",
"stream_large_files",
"=",
"False",
",",
"name",
"=",
"\"static\"",
",",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Sanic.blueprint | Register a blueprint on the application.
:param blueprint: Blueprint object or (list, tuple) thereof
:param options: option dictionary with blueprint defaults
:return: Nothing | sanic/app.py | def blueprint(self, blueprint, **options):
"""Register a blueprint on the application.
:param blueprint: Blueprint object or (list, tuple) thereof
:param options: option dictionary with blueprint defaults
:return: Nothing
"""
if isinstance(blueprint, (list, tuple, Bluepr... | def blueprint(self, blueprint, **options):
"""Register a blueprint on the application.
:param blueprint: Blueprint object or (list, tuple) thereof
:param options: option dictionary with blueprint defaults
:return: Nothing
"""
if isinstance(blueprint, (list, tuple, Bluepr... | [
"Register",
"a",
"blueprint",
"on",
"the",
"application",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L681-L700 | [
"def",
"blueprint",
"(",
"self",
",",
"blueprint",
",",
"*",
"*",
"options",
")",
":",
"if",
"isinstance",
"(",
"blueprint",
",",
"(",
"list",
",",
"tuple",
",",
"BlueprintGroup",
")",
")",
":",
"for",
"item",
"in",
"blueprint",
":",
"self",
".",
"bl... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Sanic.register_blueprint | Proxy method provided for invoking the :func:`blueprint` method
.. note::
To be deprecated in 1.0. Use :func:`blueprint` instead.
:param args: Blueprint object or (list, tuple) thereof
:param kwargs: option dictionary with blueprint defaults
:return: None | sanic/app.py | def register_blueprint(self, *args, **kwargs):
"""
Proxy method provided for invoking the :func:`blueprint` method
.. note::
To be deprecated in 1.0. Use :func:`blueprint` instead.
:param args: Blueprint object or (list, tuple) thereof
:param kwargs: option dictiona... | def register_blueprint(self, *args, **kwargs):
"""
Proxy method provided for invoking the :func:`blueprint` method
.. note::
To be deprecated in 1.0. Use :func:`blueprint` instead.
:param args: Blueprint object or (list, tuple) thereof
:param kwargs: option dictiona... | [
"Proxy",
"method",
"provided",
"for",
"invoking",
"the",
":",
"func",
":",
"blueprint",
"method"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L702-L722 | [
"def",
"register_blueprint",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"debug",
":",
"warnings",
".",
"simplefilter",
"(",
"\"default\"",
")",
"warnings",
".",
"warn",
"(",
"\"Use of register_blueprint will be depreca... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Sanic.handle_request | 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... | sanic/app.py | 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
... | 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
... | [
"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",
"he... | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L863-L975 | [
"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... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Sanic.run | 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)
... | sanic/app.py | 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,
sto... | 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,
sto... | [
"Run",
"the",
"HTTP",
"Server",
"and",
"listen",
"until",
"keyboard",
"interrupt",
"or",
"term",
"signal",
".",
"On",
"termination",
"drain",
"connections",
"before",
"closing",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L989-L1105 | [
"def",
"run",
"(",
"self",
",",
"host",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"port",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"debug",
":",
"bool",
"=",
"False",
",",
"ssl",
":",
"Union",
"[",
"dict",
",",
"SSLContext",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Sanic.create_server | Asynchronous version of :func:`run`.
This method will take care of the operations necessary to invoke
the *before_start* events via :func:`trigger_events` method invocation
before starting the *sanic* app in Async mode.
.. note::
This does not support multiprocessing and is... | sanic/app.py | async def create_server(
self,
host: Optional[str] = None,
port: Optional[int] = None,
debug: bool = False,
ssl: Union[dict, SSLContext, None] = None,
sock: Optional[socket] = None,
protocol: Type[Protocol] = None,
backlog: int = 100,
stop_event: A... | async def create_server(
self,
host: Optional[str] = None,
port: Optional[int] = None,
debug: bool = False,
ssl: Union[dict, SSLContext, None] = None,
sock: Optional[socket] = None,
protocol: Type[Protocol] = None,
backlog: int = 100,
stop_event: A... | [
"Asynchronous",
"version",
"of",
":",
"func",
":",
"run",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L1115-L1209 | [
"async",
"def",
"create_server",
"(",
"self",
",",
"host",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"port",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"debug",
":",
"bool",
"=",
"False",
",",
"ssl",
":",
"Union",
"[",
"dict",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Sanic._helper | Helper function used by `run` and `create_server`. | sanic/app.py | def _helper(
self,
host=None,
port=None,
debug=False,
ssl=None,
sock=None,
workers=1,
loop=None,
protocol=HttpProtocol,
backlog=100,
stop_event=None,
register_sys_signals=True,
run_async=False,
auto_reload=Fa... | def _helper(
self,
host=None,
port=None,
debug=False,
ssl=None,
sock=None,
workers=1,
loop=None,
protocol=HttpProtocol,
backlog=100,
stop_event=None,
register_sys_signals=True,
run_async=False,
auto_reload=Fa... | [
"Helper",
"function",
"used",
"by",
"run",
"and",
"create_server",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L1243-L1351 | [
"def",
"_helper",
"(",
"self",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"debug",
"=",
"False",
",",
"ssl",
"=",
"None",
",",
"sock",
"=",
"None",
",",
"workers",
"=",
"1",
",",
"loop",
"=",
"None",
",",
"protocol",
"=",
"HttpProto... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | json | 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. | sanic/response.py | 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.
:para... | 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.
:para... | [
"Returns",
"response",
"object",
"with",
"body",
"in",
"json",
"format",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L203-L224 | [
"def",
"json",
"(",
"body",
",",
"status",
"=",
"200",
",",
"headers",
"=",
"None",
",",
"content_type",
"=",
"\"application/json\"",
",",
"dumps",
"=",
"json_dumps",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"HTTPResponse",
"(",
"dumps",
"(",
"body",... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | text | 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 | sanic/response.py | 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) ... | 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) ... | [
"Returns",
"response",
"object",
"with",
"body",
"in",
"text",
"format",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L227-L240 | [
"def",
"text",
"(",
"body",
",",
"status",
"=",
"200",
",",
"headers",
"=",
"None",
",",
"content_type",
"=",
"\"text/plain; charset=utf-8\"",
")",
":",
"return",
"HTTPResponse",
"(",
"body",
",",
"status",
"=",
"status",
",",
"headers",
"=",
"headers",
",... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | file_stream | 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: | sanic/response.py | 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 (... | 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 (... | [
"Return",
"a",
"streaming",
"response",
"object",
"with",
"file",
"data",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L323-L386 | [
"async",
"def",
"file_stream",
"(",
"location",
",",
"status",
"=",
"200",
",",
"chunk_size",
"=",
"4096",
",",
"mime_type",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"_range",
"=",
"None",
",",
")",
":",
"headers",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | stream | 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')
... | sanic/response.py | 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 in... | 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 in... | [
"Accepts",
"an",
"coroutine",
"streaming_fn",
"which",
"can",
"be",
"used",
"to",
"write",
"chunks",
"to",
"a",
"streaming",
"response",
".",
"Returns",
"a",
"StreamingHTTPResponse",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L389-L415 | [
"def",
"stream",
"(",
"streaming_fn",
",",
"status",
"=",
"200",
",",
"headers",
"=",
"None",
",",
"content_type",
"=",
"\"text/plain; charset=utf-8\"",
",",
")",
":",
"return",
"StreamingHTTPResponse",
"(",
"streaming_fn",
",",
"headers",
"=",
"headers",
",",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | redirect | Abort execution and cause a 302 redirect (by default).
:param to: path or fully qualified URL to redirect to
:param headers: optional dict of headers to include in the new request
:param status: status code (int) of the new request, defaults to 302
:param content_type: the content type (string) of the ... | sanic/response.py | def redirect(
to, headers=None, status=302, content_type="text/html; charset=utf-8"
):
"""Abort execution and cause a 302 redirect (by default).
:param to: path or fully qualified URL to redirect to
:param headers: optional dict of headers to include in the new request
:param status: status code (i... | def redirect(
to, headers=None, status=302, content_type="text/html; charset=utf-8"
):
"""Abort execution and cause a 302 redirect (by default).
:param to: path or fully qualified URL to redirect to
:param headers: optional dict of headers to include in the new request
:param status: status code (i... | [
"Abort",
"execution",
"and",
"cause",
"a",
"302",
"redirect",
"(",
"by",
"default",
")",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L418-L439 | [
"def",
"redirect",
"(",
"to",
",",
"headers",
"=",
"None",
",",
"status",
"=",
"302",
",",
"content_type",
"=",
"\"text/html; charset=utf-8\"",
")",
":",
"headers",
"=",
"headers",
"or",
"{",
"}",
"# URL Quote the URL before redirecting",
"safe_to",
"=",
"quote_... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | StreamingHTTPResponse.write | Writes a chunk of data to the streaming response.
:param data: bytes-ish data to be written. | sanic/response.py | 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.pr... | 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.pr... | [
"Writes",
"a",
"chunk",
"of",
"data",
"to",
"the",
"streaming",
"response",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L74-L83 | [
"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\"",
"%",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | StreamingHTTPResponse.stream | Streams headers, runs the `streaming_fn` callback that writes
content to the response body, then finalizes the response body. | sanic/response.py | 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,
... | 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,
... | [
"Streams",
"headers",
"runs",
"the",
"streaming_fn",
"callback",
"that",
"writes",
"content",
"to",
"the",
"response",
"body",
"then",
"finalizes",
"the",
"response",
"body",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L85-L99 | [
"async",
"def",
"stream",
"(",
"self",
",",
"version",
"=",
"\"1.1\"",
",",
"keep_alive",
"=",
"False",
",",
"keep_alive_timeout",
"=",
"None",
")",
":",
"headers",
"=",
"self",
".",
"get_headers",
"(",
"version",
",",
"keep_alive",
"=",
"keep_alive",
",",... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | BlueprintGroup.insert | 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 | sanic/blueprint_group.py | 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.
:... | 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.
:... | [
"The",
"Abstract",
"class",
"MutableSequence",
"leverages",
"this",
"insert",
"method",
"to",
"perform",
"the",
"BlueprintGroup",
".",
"append",
"operation",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprint_group.py#L91-L100 | [
"def",
"insert",
"(",
"self",
",",
"index",
":",
"int",
",",
"item",
":",
"object",
")",
"->",
"None",
":",
"self",
".",
"_blueprints",
".",
"insert",
"(",
"index",
",",
"item",
")"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | BlueprintGroup.middleware | 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 Parameter... | sanic/blueprint_group.py | 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 recur... | 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 recur... | [
"A",
"decorator",
"that",
"can",
"be",
"used",
"to",
"implement",
"a",
"Middleware",
"plugin",
"to",
"all",
"of",
"the",
"Blueprints",
"that",
"belongs",
"to",
"this",
"specific",
"Blueprint",
"Group",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprint_group.py#L102-L120 | [
"def",
"middleware",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"bp_group\"",
"]",
"=",
"True",
"def",
"register_middleware_for_blueprints",
"(",
"fn",
")",
":",
"for",
"blueprint",
"in",
"self",
".",
"blueprints",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | ErrorHandler.response | Fetches and executes an exception handler and returns a response
object
:param request: Instance of :class:`sanic.request.Request`
:param exception: Exception to handle
:type request: :class:`sanic.request.Request`
:type exception: :class:`sanic.exceptions.SanicException` or
... | sanic/handlers.py | def response(self, request, exception):
"""Fetches and executes an exception handler and returns a response
object
:param request: Instance of :class:`sanic.request.Request`
:param exception: Exception to handle
:type request: :class:`sanic.request.Request`
:type except... | def response(self, request, exception):
"""Fetches and executes an exception handler and returns a response
object
:param request: Instance of :class:`sanic.request.Request`
:param exception: Exception to handle
:type request: :class:`sanic.request.Request`
:type except... | [
"Fetches",
"and",
"executes",
"an",
"exception",
"handler",
"and",
"returns",
"a",
"response",
"object"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/handlers.py#L111-L147 | [
"def",
"response",
"(",
"self",
",",
"request",
",",
"exception",
")",
":",
"handler",
"=",
"self",
".",
"lookup",
"(",
"exception",
")",
"response",
"=",
"None",
"try",
":",
"if",
"handler",
":",
"response",
"=",
"handler",
"(",
"request",
",",
"excep... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | ErrorHandler.default | Provide a default behavior for the objects of :class:`ErrorHandler`.
If a developer chooses to extent the :class:`ErrorHandler` they can
provide a custom implementation for this method to behave in a way
they see fit.
:param request: Incoming request
:param exception: Exception ... | sanic/handlers.py | def default(self, request, exception):
"""
Provide a default behavior for the objects of :class:`ErrorHandler`.
If a developer chooses to extent the :class:`ErrorHandler` they can
provide a custom implementation for this method to behave in a way
they see fit.
:param req... | def default(self, request, exception):
"""
Provide a default behavior for the objects of :class:`ErrorHandler`.
If a developer chooses to extent the :class:`ErrorHandler` they can
provide a custom implementation for this method to behave in a way
they see fit.
:param req... | [
"Provide",
"a",
"default",
"behavior",
"for",
"the",
"objects",
"of",
":",
"class",
":",
"ErrorHandler",
".",
"If",
"a",
"developer",
"chooses",
"to",
"extent",
"the",
":",
"class",
":",
"ErrorHandler",
"they",
"can",
"provide",
"a",
"custom",
"implementatio... | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/handlers.py#L154-L189 | [
"def",
"default",
"(",
"self",
",",
"request",
",",
"exception",
")",
":",
"self",
".",
"log",
"(",
"format_exc",
"(",
")",
")",
"try",
":",
"url",
"=",
"repr",
"(",
"request",
".",
"url",
")",
"except",
"AttributeError",
":",
"url",
"=",
"\"unknown\... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | GunicornWorker._create_ssl_context | Creates SSLContext instance for usage in asyncio.create_server.
See ssl.SSLSocket.__init__ for more details. | sanic/worker.py | def _create_ssl_context(cfg):
""" Creates SSLContext instance for usage in asyncio.create_server.
See ssl.SSLSocket.__init__ for more details.
"""
ctx = ssl.SSLContext(cfg.ssl_version)
ctx.load_cert_chain(cfg.certfile, cfg.keyfile)
ctx.verify_mode = cfg.cert_reqs
... | def _create_ssl_context(cfg):
""" Creates SSLContext instance for usage in asyncio.create_server.
See ssl.SSLSocket.__init__ for more details.
"""
ctx = ssl.SSLContext(cfg.ssl_version)
ctx.load_cert_chain(cfg.certfile, cfg.keyfile)
ctx.verify_mode = cfg.cert_reqs
... | [
"Creates",
"SSLContext",
"instance",
"for",
"usage",
"in",
"asyncio",
".",
"create_server",
".",
"See",
"ssl",
".",
"SSLSocket",
".",
"__init__",
"for",
"more",
"details",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/worker.py#L176-L187 | [
"def",
"_create_ssl_context",
"(",
"cfg",
")",
":",
"ctx",
"=",
"ssl",
".",
"SSLContext",
"(",
"cfg",
".",
"ssl_version",
")",
"ctx",
".",
"load_cert_chain",
"(",
"cfg",
".",
"certfile",
",",
"cfg",
".",
"keyfile",
")",
"ctx",
".",
"verify_mode",
"=",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | trigger_events | Trigger event callbacks (functions or async)
:param events: one or more sync or async functions to execute
:param loop: event loop | sanic/server.py | def trigger_events(events, loop):
"""Trigger event callbacks (functions or async)
:param events: one or more sync or async functions to execute
:param loop: event loop
"""
for event in events:
result = event(loop)
if isawaitable(result):
loop.run_until_complete(result) | def trigger_events(events, loop):
"""Trigger event callbacks (functions or async)
:param events: one or more sync or async functions to execute
:param loop: event loop
"""
for event in events:
result = event(loop)
if isawaitable(result):
loop.run_until_complete(result) | [
"Trigger",
"event",
"callbacks",
"(",
"functions",
"or",
"async",
")"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L604-L613 | [
"def",
"trigger_events",
"(",
"events",
",",
"loop",
")",
":",
"for",
"event",
"in",
"events",
":",
"result",
"=",
"event",
"(",
"loop",
")",
"if",
"isawaitable",
"(",
"result",
")",
":",
"loop",
".",
"run_until_complete",
"(",
"result",
")"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | serve | Start asynchronous HTTP Server on an individual process.
:param host: Address to host on
:param port: Port to host on
:param request_handler: Sanic request handler with middleware
:param error_handler: Sanic error handler with middleware
:param before_start: function to be executed before the serve... | sanic/server.py | def serve(
host,
port,
app,
request_handler,
error_handler,
before_start=None,
after_start=None,
before_stop=None,
after_stop=None,
debug=False,
request_timeout=60,
response_timeout=60,
keep_alive_timeout=5,
ssl=None,
sock=None,
request_max_size=None,
... | def serve(
host,
port,
app,
request_handler,
error_handler,
before_start=None,
after_start=None,
before_stop=None,
after_stop=None,
debug=False,
request_timeout=60,
response_timeout=60,
keep_alive_timeout=5,
ssl=None,
sock=None,
request_max_size=None,
... | [
"Start",
"asynchronous",
"HTTP",
"Server",
"on",
"an",
"individual",
"process",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L616-L820 | [
"def",
"serve",
"(",
"host",
",",
"port",
",",
"app",
",",
"request_handler",
",",
"error_handler",
",",
"before_start",
"=",
"None",
",",
"after_start",
"=",
"None",
",",
"before_stop",
"=",
"None",
",",
"after_stop",
"=",
"None",
",",
"debug",
"=",
"Fa... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | HttpProtocol.keep_alive | Check if the connection needs to be kept alive based on the params
attached to the `_keep_alive` attribute, :attr:`Signal.stopped`
and :func:`HttpProtocol.parser.should_keep_alive`
:return: ``True`` if connection is to be kept alive ``False`` else | sanic/server.py | def keep_alive(self):
"""
Check if the connection needs to be kept alive based on the params
attached to the `_keep_alive` attribute, :attr:`Signal.stopped`
and :func:`HttpProtocol.parser.should_keep_alive`
:return: ``True`` if connection is to be kept alive ``False`` else
... | def keep_alive(self):
"""
Check if the connection needs to be kept alive based on the params
attached to the `_keep_alive` attribute, :attr:`Signal.stopped`
and :func:`HttpProtocol.parser.should_keep_alive`
:return: ``True`` if connection is to be kept alive ``False`` else
... | [
"Check",
"if",
"the",
"connection",
"needs",
"to",
"be",
"kept",
"alive",
"based",
"on",
"the",
"params",
"attached",
"to",
"the",
"_keep_alive",
"attribute",
":",
"attr",
":",
"Signal",
".",
"stopped",
"and",
":",
"func",
":",
"HttpProtocol",
".",
"parser... | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L151-L163 | [
"def",
"keep_alive",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_keep_alive",
"and",
"not",
"self",
".",
"signal",
".",
"stopped",
"and",
"self",
".",
"parser",
".",
"should_keep_alive",
"(",
")",
")"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | HttpProtocol.keep_alive_timeout_callback | 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 | sanic/server.py | 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() ... | 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() ... | [
"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",
... | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L230-L247 | [
"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",
"... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | HttpProtocol.execute_request_handler | Invoke the request handler defined by the
:func:`sanic.app.Sanic.handle_request` method
:return: None | sanic/server.py | def execute_request_handler(self):
"""
Invoke the request handler defined by the
:func:`sanic.app.Sanic.handle_request` method
:return: None
"""
self._response_timeout_handler = self.loop.call_later(
self.response_timeout, self.response_timeout_callback
... | def execute_request_handler(self):
"""
Invoke the request handler defined by the
:func:`sanic.app.Sanic.handle_request` method
:return: None
"""
self._response_timeout_handler = self.loop.call_later(
self.response_timeout, self.response_timeout_callback
... | [
"Invoke",
"the",
"request",
"handler",
"defined",
"by",
"the",
":",
"func",
":",
"sanic",
".",
"app",
".",
"Sanic",
".",
"handle_request",
"method"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L357-L372 | [
"def",
"execute_request_handler",
"(",
"self",
")",
":",
"self",
".",
"_response_timeout_handler",
"=",
"self",
".",
"loop",
".",
"call_later",
"(",
"self",
".",
"response_timeout",
",",
"self",
".",
"response_timeout_callback",
")",
"self",
".",
"_last_request_ti... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | HttpProtocol.log_response | Helper method provided to enable the logging of responses in case if
the :attr:`HttpProtocol.access_log` is enabled.
:param response: Response generated for the current request
:type response: :class:`sanic.response.HTTPResponse` or
:class:`sanic.response.StreamingHTTPResponse`
... | sanic/server.py | def log_response(self, response):
"""
Helper method provided to enable the logging of responses in case if
the :attr:`HttpProtocol.access_log` is enabled.
:param response: Response generated for the current request
:type response: :class:`sanic.response.HTTPResponse` or
... | def log_response(self, response):
"""
Helper method provided to enable the logging of responses in case if
the :attr:`HttpProtocol.access_log` is enabled.
:param response: Response generated for the current request
:type response: :class:`sanic.response.HTTPResponse` or
... | [
"Helper",
"method",
"provided",
"to",
"enable",
"the",
"logging",
"of",
"responses",
"in",
"case",
"if",
"the",
":",
"attr",
":",
"HttpProtocol",
".",
"access_log",
"is",
"enabled",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L377-L410 | [
"def",
"log_response",
"(",
"self",
",",
"response",
")",
":",
"if",
"self",
".",
"access_log",
":",
"extra",
"=",
"{",
"\"status\"",
":",
"getattr",
"(",
"response",
",",
"\"status\"",
",",
"0",
")",
"}",
"if",
"isinstance",
"(",
"response",
",",
"HTT... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | HttpProtocol.write_response | Writes response content synchronously to the transport. | sanic/server.py | 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_ali... | 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_ali... | [
"Writes",
"response",
"content",
"synchronously",
"to",
"the",
"transport",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L412-L455 | [
"def",
"write_response",
"(",
"self",
",",
"response",
")",
":",
"if",
"self",
".",
"_response_timeout_handler",
":",
"self",
".",
"_response_timeout_handler",
".",
"cancel",
"(",
")",
"self",
".",
"_response_timeout_handler",
"=",
"None",
"try",
":",
"keep_aliv... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | HttpProtocol.bail_out | 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... | sanic/server.py | 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: ... | 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: ... | [
"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",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L542-L570 | [
"def",
"bail_out",
"(",
"self",
",",
"message",
",",
"from_error",
"=",
"False",
")",
":",
"if",
"from_error",
"or",
"self",
".",
"transport",
"is",
"None",
"or",
"self",
".",
"transport",
".",
"is_closing",
"(",
")",
":",
"logger",
".",
"error",
"(",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | HttpProtocol.cleanup | 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. | sanic/server.py | 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
... | 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
... | [
"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",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L572-L583 | [
"def",
"cleanup",
"(",
"self",
")",
":",
"self",
".",
"parser",
"=",
"None",
"self",
".",
"request",
"=",
"None",
"self",
".",
"url",
"=",
"None",
"self",
".",
"headers",
"=",
"None",
"self",
".",
"_request_handler_task",
"=",
"None",
"self",
".",
"_... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | parse_multipart_form | Parse a request body and returns fields and files
:param body: bytes request body
:param boundary: bytes multipart boundary
:return: fields (RequestParameters), files (RequestParameters) | sanic/request.py | def parse_multipart_form(body, boundary):
"""Parse a request body and returns fields and files
:param body: bytes request body
:param boundary: bytes multipart boundary
:return: fields (RequestParameters), files (RequestParameters)
"""
files = RequestParameters()
fields = RequestParameters(... | def parse_multipart_form(body, boundary):
"""Parse a request body and returns fields and files
:param body: bytes request body
:param boundary: bytes multipart boundary
:return: fields (RequestParameters), files (RequestParameters)
"""
files = RequestParameters()
fields = RequestParameters(... | [
"Parse",
"a",
"request",
"body",
"and",
"returns",
"fields",
"and",
"files"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L445-L513 | [
"def",
"parse_multipart_form",
"(",
"body",
",",
"boundary",
")",
":",
"files",
"=",
"RequestParameters",
"(",
")",
"fields",
"=",
"RequestParameters",
"(",
")",
"form_parts",
"=",
"body",
".",
"split",
"(",
"boundary",
")",
"for",
"form_part",
"in",
"form_p... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | StreamBuffer.read | Stop reading when gets None | sanic/request.py | async def read(self):
""" Stop reading when gets None """
payload = await self._queue.get()
self._queue.task_done()
return payload | async def read(self):
""" Stop reading when gets None """
payload = await self._queue.get()
self._queue.task_done()
return payload | [
"Stop",
"reading",
"when",
"gets",
"None"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L57-L61 | [
"async",
"def",
"read",
"(",
"self",
")",
":",
"payload",
"=",
"await",
"self",
".",
"_queue",
".",
"get",
"(",
")",
"self",
".",
"_queue",
".",
"task_done",
"(",
")",
"return",
"payload"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Request.token | Attempt to return the auth header token.
:return: token related to request | sanic/request.py | def token(self):
"""Attempt to return the auth header token.
:return: token related to request
"""
prefixes = ("Bearer", "Token")
auth_header = self.headers.get("Authorization")
if auth_header is not None:
for prefix in prefixes:
if prefix in... | def token(self):
"""Attempt to return the auth header token.
:return: token related to request
"""
prefixes = ("Bearer", "Token")
auth_header = self.headers.get("Authorization")
if auth_header is not None:
for prefix in prefixes:
if prefix in... | [
"Attempt",
"to",
"return",
"the",
"auth",
"header",
"token",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L158-L171 | [
"def",
"token",
"(",
"self",
")",
":",
"prefixes",
"=",
"(",
"\"Bearer\"",
",",
"\"Token\"",
")",
"auth_header",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"\"Authorization\"",
")",
"if",
"auth_header",
"is",
"not",
"None",
":",
"for",
"prefix",
"in",... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Request.get_args | Method to parse `query_string` using `urllib.parse.parse_qs`.
This methods is used by `args` property.
Can be used directly if you need to change default parameters.
:param keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank s... | sanic/request.py | def get_args(
self,
keep_blank_values: bool = False,
strict_parsing: bool = False,
encoding: str = "utf-8",
errors: str = "replace",
) -> RequestParameters:
"""
Method to parse `query_string` using `urllib.parse.parse_qs`.
This methods is used by `args... | def get_args(
self,
keep_blank_values: bool = False,
strict_parsing: bool = False,
encoding: str = "utf-8",
errors: str = "replace",
) -> RequestParameters:
"""
Method to parse `query_string` using `urllib.parse.parse_qs`.
This methods is used by `args... | [
"Method",
"to",
"parse",
"query_string",
"using",
"urllib",
".",
"parse",
".",
"parse_qs",
".",
"This",
"methods",
"is",
"used",
"by",
"args",
"property",
".",
"Can",
"be",
"used",
"directly",
"if",
"you",
"need",
"to",
"change",
"default",
"parameters",
"... | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L205-L252 | [
"def",
"get_args",
"(",
"self",
",",
"keep_blank_values",
":",
"bool",
"=",
"False",
",",
"strict_parsing",
":",
"bool",
"=",
"False",
",",
"encoding",
":",
"str",
"=",
"\"utf-8\"",
",",
"errors",
":",
"str",
"=",
"\"replace\"",
",",
")",
"->",
"RequestP... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Request.get_query_args | Method to parse `query_string` using `urllib.parse.parse_qsl`.
This methods is used by `query_args` property.
Can be used directly if you need to change default parameters.
:param keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as ... | sanic/request.py | def get_query_args(
self,
keep_blank_values: bool = False,
strict_parsing: bool = False,
encoding: str = "utf-8",
errors: str = "replace",
) -> list:
"""
Method to parse `query_string` using `urllib.parse.parse_qsl`.
This methods is used by `query_args... | def get_query_args(
self,
keep_blank_values: bool = False,
strict_parsing: bool = False,
encoding: str = "utf-8",
errors: str = "replace",
) -> list:
"""
Method to parse `query_string` using `urllib.parse.parse_qsl`.
This methods is used by `query_args... | [
"Method",
"to",
"parse",
"query_string",
"using",
"urllib",
".",
"parse",
".",
"parse_qsl",
".",
"This",
"methods",
"is",
"used",
"by",
"query_args",
"property",
".",
"Can",
"be",
"used",
"directly",
"if",
"you",
"need",
"to",
"change",
"default",
"parameter... | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L268-L312 | [
"def",
"get_query_args",
"(",
"self",
",",
"keep_blank_values",
":",
"bool",
"=",
"False",
",",
"strict_parsing",
":",
"bool",
"=",
"False",
",",
"encoding",
":",
"str",
"=",
"\"utf-8\"",
",",
"errors",
":",
"str",
"=",
"\"replace\"",
",",
")",
"->",
"li... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Request.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. | sanic/request.py | 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... | 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... | [
"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",
... | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L357-L392 | [
"def",
"remote_addr",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_remote_addr\"",
")",
":",
"if",
"self",
".",
"app",
".",
"config",
".",
"PROXIES_COUNT",
"==",
"0",
":",
"self",
".",
"_remote_addr",
"=",
"\"\"",
"elif",
"self"... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | strtobool | 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. | sanic/config.py | 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... | 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... | [
"This",
"function",
"was",
"borrowed",
"from",
"distutils",
".",
"utils",
".",
"While",
"distutils",
"is",
"part",
"of",
"stdlib",
"it",
"feels",
"odd",
"to",
"use",
"distutils",
"in",
"main",
"application",
"code",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L136-L150 | [
"def",
"strtobool",
"(",
"val",
")",
":",
"val",
"=",
"val",
".",
"lower",
"(",
")",
"if",
"val",
"in",
"(",
"\"y\"",
",",
"\"yes\"",
",",
"\"t\"",
",",
"\"true\"",
",",
"\"on\"",
",",
"\"1\"",
")",
":",
"return",
"True",
"elif",
"val",
"in",
"("... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Config.from_envvar | 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. | sanic/config.py | 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.e... | 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.e... | [
"Load",
"a",
"configuration",
"from",
"an",
"environment",
"variable",
"pointing",
"to",
"a",
"configuration",
"file",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L57-L70 | [
"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 \"",
"\... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Config.from_object | 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 s... | sanic/config.py | 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.fro... | 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.fro... | [
"Update",
"the",
"values",
"from",
"the",
"given",
"object",
".",
"Objects",
"are",
"usually",
"either",
"modules",
"or",
"classes",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L95-L114 | [
"def",
"from_object",
"(",
"self",
",",
"obj",
")",
":",
"for",
"key",
"in",
"dir",
"(",
"obj",
")",
":",
"if",
"key",
".",
"isupper",
"(",
")",
":",
"self",
"[",
"key",
"]",
"=",
"getattr",
"(",
"obj",
",",
"key",
")"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Config.load_environment_vars | Looks for prefixed environment variables and applies
them to the configuration if present. | sanic/config.py | 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)
... | 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)
... | [
"Looks",
"for",
"prefixed",
"environment",
"variables",
"and",
"applies",
"them",
"to",
"the",
"configuration",
"if",
"present",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L116-L133 | [
"def",
"load_environment_vars",
"(",
"self",
",",
"prefix",
"=",
"SANIC_PREFIX",
")",
":",
"for",
"k",
",",
"v",
"in",
"os",
".",
"environ",
".",
"items",
"(",
")",
":",
"if",
"k",
".",
"startswith",
"(",
"prefix",
")",
":",
"_",
",",
"config_key",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Router.parse_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, p... | sanic/router.py | 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
... | 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
... | [
"Parse",
"a",
"parameter",
"string",
"into",
"its",
"constituent",
"name",
"type",
"and",
"pattern"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L92-L119 | [
"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",
"=",
"parame... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Router.add | Add a handler to the route list
:param uri: path to match
:param methods: sequence of accepted method names. If none are
provided, any method is allowed
:param handler: request handler function.
When executed, it should provide a response object.
:param strict_sl... | sanic/router.py | def add(
self,
uri,
methods,
handler,
host=None,
strict_slashes=False,
version=None,
name=None,
):
"""Add a handler to the route list
:param uri: path to match
:param methods: sequence of accepted method names. If none are
... | def add(
self,
uri,
methods,
handler,
host=None,
strict_slashes=False,
version=None,
name=None,
):
"""Add a handler to the route list
:param uri: path to match
:param methods: sequence of accepted method names. If none are
... | [
"Add",
"a",
"handler",
"to",
"the",
"route",
"list"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L121-L182 | [
"def",
"add",
"(",
"self",
",",
"uri",
",",
"methods",
",",
"handler",
",",
"host",
"=",
"None",
",",
"strict_slashes",
"=",
"False",
",",
"version",
"=",
"None",
",",
"name",
"=",
"None",
",",
")",
":",
"if",
"version",
"is",
"not",
"None",
":",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Router._add | Add a handler to the route list
:param uri: path to match
:param methods: sequence of accepted method names. If none are
provided, any method is allowed
:param handler: request handler function.
When executed, it should provide a response object.
:param name: use... | sanic/router.py | def _add(self, uri, methods, handler, host=None, name=None):
"""Add a handler to the route list
:param uri: path to match
:param methods: sequence of accepted method names. If none are
provided, any method is allowed
:param handler: request handler function.
When... | def _add(self, uri, methods, handler, host=None, name=None):
"""Add a handler to the route list
:param uri: path to match
:param methods: sequence of accepted method names. If none are
provided, any method is allowed
:param handler: request handler function.
When... | [
"Add",
"a",
"handler",
"to",
"the",
"route",
"list"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L184-L330 | [
"def",
"_add",
"(",
"self",
",",
"uri",
",",
"methods",
",",
"handler",
",",
"host",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"host",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"host",
",",
"str",
")",
":",
"uri",
"=",
"ho... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Router.check_dynamic_route_exists | 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:... | sanic/router.py | 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 ei... | 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 ei... | [
"Check",
"if",
"a",
"URL",
"pattern",
"exists",
"in",
"a",
"list",
"of",
"routes",
"provided",
"based",
"on",
"the",
"comparison",
"of",
"URL",
"pattern",
"and",
"the",
"parameters",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L333-L349 | [
"def",
"check_dynamic_route_exists",
"(",
"pattern",
",",
"routes_to_check",
",",
"parameters",
")",
":",
"for",
"ndx",
",",
"route",
"in",
"enumerate",
"(",
"routes_to_check",
")",
":",
"if",
"route",
".",
"pattern",
"==",
"pattern",
"and",
"route",
".",
"p... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Router.find_route_by_view_name | Find a route in the router based on the specified view name.
:param view_name: string of view name to search by
:param kwargs: additional params, usually for static files
:return: tuple containing (uri, Route) | sanic/router.py | def find_route_by_view_name(self, view_name, name=None):
"""Find a route in the router based on the specified view name.
:param view_name: string of view name to search by
:param kwargs: additional params, usually for static files
:return: tuple containing (uri, Route)
"""
... | def find_route_by_view_name(self, view_name, name=None):
"""Find a route in the router based on the specified view name.
:param view_name: string of view name to search by
:param kwargs: additional params, usually for static files
:return: tuple containing (uri, Route)
"""
... | [
"Find",
"a",
"route",
"in",
"the",
"router",
"based",
"on",
"the",
"specified",
"view",
"name",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L383-L396 | [
"def",
"find_route_by_view_name",
"(",
"self",
",",
"view_name",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"view_name",
":",
"return",
"(",
"None",
",",
"None",
")",
"if",
"view_name",
"==",
"\"static\"",
"or",
"view_name",
".",
"endswith",
"(",
"... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Router.get | Get a request handler based on the URL of the request, or raises an
error
:param request: Request object
:return: handler, arguments, keyword arguments | sanic/router.py | 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:
re... | 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:
re... | [
"Get",
"a",
"request",
"handler",
"based",
"on",
"the",
"URL",
"of",
"the",
"request",
"or",
"raises",
"an",
"error"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L398-L415 | [
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"# No virtual hosts specified; default behavior",
"if",
"not",
"self",
".",
"hosts",
":",
"return",
"self",
".",
"_get",
"(",
"request",
".",
"path",
",",
"request",
".",
"method",
",",
"\"\"",
")",
"# v... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Router.get_supported_methods | Get a list of supported methods for a url and optional host.
:param url: URL string (including host)
:return: frozenset of supported methods | sanic/router.py | 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 a... | 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 a... | [
"Get",
"a",
"list",
"of",
"supported",
"methods",
"for",
"a",
"url",
"and",
"optional",
"host",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L417-L425 | [
"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\"",
",",
"Non... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Router._get | Get a request handler based on the URL of the request, or raises an
error. Internal method for caching.
:param url: request URL
:param method: request method
:return: handler, arguments, keyword arguments | sanic/router.py | def _get(self, url, method, host):
"""Get a request handler based on the URL of the request, or raises an
error. Internal method for caching.
:param url: request URL
:param method: request method
:return: handler, arguments, keyword arguments
"""
url = unquote(h... | def _get(self, url, method, host):
"""Get a request handler based on the URL of the request, or raises an
error. Internal method for caching.
:param url: request URL
:param method: request method
:return: handler, arguments, keyword arguments
"""
url = unquote(h... | [
"Get",
"a",
"request",
"handler",
"based",
"on",
"the",
"URL",
"of",
"the",
"request",
"or",
"raises",
"an",
"error",
".",
"Internal",
"method",
"for",
"caching",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L428-L478 | [
"def",
"_get",
"(",
"self",
",",
"url",
",",
"method",
",",
"host",
")",
":",
"url",
"=",
"unquote",
"(",
"host",
"+",
"url",
")",
"# Check against known static routes",
"route",
"=",
"self",
".",
"routes_static",
".",
"get",
"(",
"url",
")",
"method_not... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | Router.is_stream_handler | Handler for request is stream or not.
:param request: Request object
:return: bool | sanic/router.py | def is_stream_handler(self, request):
""" Handler for request is stream or not.
:param request: Request object
:return: bool
"""
try:
handler = self.get(request)[0]
except (NotFound, MethodNotSupported):
return False
if hasattr(handler, "vi... | def is_stream_handler(self, request):
""" Handler for request is stream or not.
:param request: Request object
:return: bool
"""
try:
handler = self.get(request)[0]
except (NotFound, MethodNotSupported):
return False
if hasattr(handler, "vi... | [
"Handler",
"for",
"request",
"is",
"stream",
"or",
"not",
".",
":",
"param",
"request",
":",
"Request",
"object",
":",
"return",
":",
"bool"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L480-L493 | [
"def",
"is_stream_handler",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"handler",
"=",
"self",
".",
"get",
"(",
"request",
")",
"[",
"0",
"]",
"except",
"(",
"NotFound",
",",
"MethodNotSupported",
")",
":",
"return",
"False",
"if",
"hasattr",
"... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | _get_args_for_reloading | Returns the executable. | sanic/reloader_helpers.py | 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])
... | 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])
... | [
"Returns",
"the",
"executable",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L36-L48 | [
"def",
"_get_args_for_reloading",
"(",
")",
":",
"rv",
"=",
"[",
"sys",
".",
"executable",
"]",
"main_module",
"=",
"sys",
".",
"modules",
"[",
"\"__main__\"",
"]",
"mod_spec",
"=",
"getattr",
"(",
"main_module",
",",
"\"__spec__\"",
",",
"None",
")",
"if"... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | restart_with_reloader | Create a new process and a subprocess in it with the same arguments as
this one. | sanic/reloader_helpers.py | 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 = P... | 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 = P... | [
"Create",
"a",
"new",
"process",
"and",
"a",
"subprocess",
"in",
"it",
"with",
"the",
"same",
"arguments",
"as",
"this",
"one",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L51-L66 | [
"def",
"restart_with_reloader",
"(",
")",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"args",
"=",
"_get_args_for_reloading",
"(",
")",
"new_environ",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"new_environ",
"[",
"\"SANIC_SERVER_RUNNING\"",
"]",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | kill_process_children_unix | Find and kill child processes of a process (maximum two level).
:param pid: PID of parent process (process ID)
:return: Nothing | sanic/reloader_helpers.py | def kill_process_children_unix(pid):
"""Find and kill child processes of a process (maximum two level).
:param pid: PID of parent process (process ID)
:return: Nothing
"""
root_process_path = "/proc/{pid}/task/{pid}/children".format(pid=pid)
if not os.path.isfile(root_process_path):
ret... | def kill_process_children_unix(pid):
"""Find and kill child processes of a process (maximum two level).
:param pid: PID of parent process (process ID)
:return: Nothing
"""
root_process_path = "/proc/{pid}/task/{pid}/children".format(pid=pid)
if not os.path.isfile(root_process_path):
ret... | [
"Find",
"and",
"kill",
"child",
"processes",
"of",
"a",
"process",
"(",
"maximum",
"two",
"level",
")",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L69-L98 | [
"def",
"kill_process_children_unix",
"(",
"pid",
")",
":",
"root_process_path",
"=",
"\"/proc/{pid}/task/{pid}/children\"",
".",
"format",
"(",
"pid",
"=",
"pid",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"root_process_path",
")",
":",
"return",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | kill_process_children | Find and kill child processes of a process.
:param pid: PID of parent process (process ID)
:return: Nothing | sanic/reloader_helpers.py | 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:
... | 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:
... | [
"Find",
"and",
"kill",
"child",
"processes",
"of",
"a",
"process",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L110-L121 | [
"def",
"kill_process_children",
"(",
"pid",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"\"darwin\"",
":",
"kill_process_children_osx",
"(",
"pid",
")",
"elif",
"sys",
".",
"platform",
"==",
"\"linux\"",
":",
"kill_process_children_unix",
"(",
"pid",
")",
"e... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | watchdog | Watch project files, restart worker process if a change happened.
:param sleep_interval: interval in second.
:return: Nothing | sanic/reloader_helpers.py | 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... | 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... | [
"Watch",
"project",
"files",
"restart",
"worker",
"process",
"if",
"a",
"change",
"happened",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L135-L167 | [
"def",
"watchdog",
"(",
"sleep_interval",
")",
":",
"mtimes",
"=",
"{",
"}",
"worker_process",
"=",
"restart_with_reloader",
"(",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"lambda",
"*",
"args",
":",
"kill_program_completly",
"(",
"wo... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | HTTPMethodView.as_view | Return view function for use with the routing system, that
dispatches request to appropriate handler method. | sanic/views.py | 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_... | 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_... | [
"Return",
"view",
"function",
"for",
"use",
"with",
"the",
"routing",
"system",
"that",
"dispatches",
"request",
"to",
"appropriate",
"handler",
"method",
"."
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/views.py#L47-L65 | [
"def",
"as_view",
"(",
"cls",
",",
"*",
"class_args",
",",
"*",
"*",
"class_kwargs",
")",
":",
"def",
"view",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"view",
".",
"view_class",
"(",
"*",
"class_args",
",",
"*",
"*",
"cla... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | bounded_fetch | Use session object to perform 'get' request on url | examples/limit_concurrency.py | 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):
"""
Use session object to perform 'get' request on url
"""
async with sem, session.get(url) as response:
return await response.json() | [
"Use",
"session",
"object",
"to",
"perform",
"get",
"request",
"on",
"url"
] | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/examples/limit_concurrency.py#L18-L23 | [
"async",
"def",
"bounded_fetch",
"(",
"session",
",",
"url",
")",
":",
"async",
"with",
"sem",
",",
"session",
".",
"get",
"(",
"url",
")",
"as",
"response",
":",
"return",
"await",
"response",
".",
"json",
"(",
")"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | remove_entity_headers | Removes all the entity headers present in the headers given.
According to RFC 2616 Section 10.3.5,
Content-Location and Expires are allowed as for the
"strong cache validator".
https://tools.ietf.org/html/rfc2616#section-10.3.5
returns the headers without the entity headers | sanic/helpers.py | def remove_entity_headers(headers, allowed=("content-location", "expires")):
"""
Removes all the entity headers present in the headers given.
According to RFC 2616 Section 10.3.5,
Content-Location and Expires are allowed as for the
"strong cache validator".
https://tools.ietf.org/html/rfc2616#se... | def remove_entity_headers(headers, allowed=("content-location", "expires")):
"""
Removes all the entity headers present in the headers given.
According to RFC 2616 Section 10.3.5,
Content-Location and Expires are allowed as for the
"strong cache validator".
https://tools.ietf.org/html/rfc2616#se... | [
"Removes",
"all",
"the",
"entity",
"headers",
"present",
"in",
"the",
"headers",
"given",
".",
"According",
"to",
"RFC",
"2616",
"Section",
"10",
".",
"3",
".",
"5",
"Content",
"-",
"Location",
"and",
"Expires",
"are",
"allowed",
"as",
"for",
"the",
"str... | huge-success/sanic | python | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/helpers.py#L117-L133 | [
"def",
"remove_entity_headers",
"(",
"headers",
",",
"allowed",
"=",
"(",
"\"content-location\"",
",",
"\"expires\"",
")",
")",
":",
"allowed",
"=",
"set",
"(",
"[",
"h",
".",
"lower",
"(",
")",
"for",
"h",
"in",
"allowed",
"]",
")",
"headers",
"=",
"{... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd |
train | preserve_shape | Preserve shape of the image. | albumentations/augmentations/functional.py | 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):
"""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 | [
"Preserve",
"shape",
"of",
"the",
"image",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L35-L44 | [
"def",
"preserve_shape",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped_function",
"(",
"img",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"shape",
"=",
"img",
".",
"shape",
"result",
"=",
"func",
"(",
"img",
",",
... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | preserve_channel_dim | Preserve dummy channel dim. | albumentations/augmentations/functional.py | 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(resul... | 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(resul... | [
"Preserve",
"dummy",
"channel",
"dim",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L47-L57 | [
"def",
"preserve_channel_dim",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped_function",
"(",
"img",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"shape",
"=",
"img",
".",
"shape",
"result",
"=",
"func",
"(",
"img",
... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | add_snow | Bleaches out pixels, mitation snow.
From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
Args:
img:
snow_point:
brightness_coeff:
Returns: | albumentations/augmentations/functional.py | 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
... | 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
... | [
"Bleaches",
"out",
"pixels",
"mitation",
"snow",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L438-L479 | [
"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",... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | add_fog | 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: | albumentations/augmentations/functional.py | 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)
... | 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)
... | [
"Add",
"fog",
"to",
"the",
"image",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L533-L578 | [
"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",
":",
... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | add_sun_flare | 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: | albumentations/augmentations/functional.py | 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_c... | 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_c... | [
"Add",
"sun",
"flare",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L582-L633 | [
"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",
"... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | add_shadow | Add shadows to the image.
From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
Args:
img (np.array):
vertices_list (list):
Returns: | albumentations/augmentations/functional.py | 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 ... | 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 ... | [
"Add",
"shadows",
"to",
"the",
"image",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L637-L675 | [
"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",
"(",
... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | optical_distortion | Barrel / pincushion distortion. Unconventional augment.
Reference:
| https://stackoverflow.com/questions/6199636/formulas-for-barrel-pincushion-distortion
| https://stackoverflow.com/questions/10364201/image-transformation-in-opencv
| https://stackoverflow.com/questions/2477774/correctin... | albumentations/augmentations/functional.py | def optical_distortion(img, k=0, dx=0, dy=0, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101,
value=None):
"""Barrel / pincushion distortion. Unconventional augment.
Reference:
| https://stackoverflow.com/questions/6199636/formulas-for-barrel-pincushion-distor... | def optical_distortion(img, k=0, dx=0, dy=0, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101,
value=None):
"""Barrel / pincushion distortion. Unconventional augment.
Reference:
| https://stackoverflow.com/questions/6199636/formulas-for-barrel-pincushion-distor... | [
"Barrel",
"/",
"pincushion",
"distortion",
".",
"Unconventional",
"augment",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L679-L704 | [
"def",
"optical_distortion",
"(",
"img",
",",
"k",
"=",
"0",
",",
"dx",
"=",
"0",
",",
"dy",
"=",
"0",
",",
"interpolation",
"=",
"cv2",
".",
"INTER_LINEAR",
",",
"border_mode",
"=",
"cv2",
".",
"BORDER_REFLECT_101",
",",
"value",
"=",
"None",
")",
"... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | grid_distortion | Reference:
http://pythology.blogspot.sg/2014/03/interpolation-on-regular-distorted-grid.html | albumentations/augmentations/functional.py | def grid_distortion(img, num_steps=10, xsteps=[], ysteps=[], interpolation=cv2.INTER_LINEAR,
border_mode=cv2.BORDER_REFLECT_101, value=None):
"""
Reference:
http://pythology.blogspot.sg/2014/03/interpolation-on-regular-distorted-grid.html
"""
height, width = img.shape[:2]
... | def grid_distortion(img, num_steps=10, xsteps=[], ysteps=[], interpolation=cv2.INTER_LINEAR,
border_mode=cv2.BORDER_REFLECT_101, value=None):
"""
Reference:
http://pythology.blogspot.sg/2014/03/interpolation-on-regular-distorted-grid.html
"""
height, width = img.shape[:2]
... | [
"Reference",
":",
"http",
":",
"//",
"pythology",
".",
"blogspot",
".",
"sg",
"/",
"2014",
"/",
"03",
"/",
"interpolation",
"-",
"on",
"-",
"regular",
"-",
"distorted",
"-",
"grid",
".",
"html"
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L708-L750 | [
"def",
"grid_distortion",
"(",
"img",
",",
"num_steps",
"=",
"10",
",",
"xsteps",
"=",
"[",
"]",
",",
"ysteps",
"=",
"[",
"]",
",",
"interpolation",
"=",
"cv2",
".",
"INTER_LINEAR",
",",
"border_mode",
"=",
"cv2",
".",
"BORDER_REFLECT_101",
",",
"value",... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | elastic_transform | Elastic deformation of images as described in [Simard2003]_ (with modifications).
Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5
.. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for
Convolutional Neural Networks applied to Visual Document Analysis", in
Proc. of... | albumentations/augmentations/functional.py | def elastic_transform(image, alpha, sigma, alpha_affine, interpolation=cv2.INTER_LINEAR,
border_mode=cv2.BORDER_REFLECT_101, value=None, random_state=None, approximate=False):
"""Elastic deformation of images as described in [Simard2003]_ (with modifications).
Based on https://gist.github.... | def elastic_transform(image, alpha, sigma, alpha_affine, interpolation=cv2.INTER_LINEAR,
border_mode=cv2.BORDER_REFLECT_101, value=None, random_state=None, approximate=False):
"""Elastic deformation of images as described in [Simard2003]_ (with modifications).
Based on https://gist.github.... | [
"Elastic",
"deformation",
"of",
"images",
"as",
"described",
"in",
"[",
"Simard2003",
"]",
"_",
"(",
"with",
"modifications",
")",
".",
"Based",
"on",
"https",
":",
"//",
"gist",
".",
"github",
".",
"com",
"/",
"erniejunior",
"/",
"601cdf56d2b424757de5"
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L754-L803 | [
"def",
"elastic_transform",
"(",
"image",
",",
"alpha",
",",
"sigma",
",",
"alpha_affine",
",",
"interpolation",
"=",
"cv2",
".",
"INTER_LINEAR",
",",
"border_mode",
"=",
"cv2",
".",
"BORDER_REFLECT_101",
",",
"value",
"=",
"None",
",",
"random_state",
"=",
... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | bbox_vflip | Flip a bounding box vertically around the x-axis. | albumentations/augmentations/functional.py | 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):
"""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] | [
"Flip",
"a",
"bounding",
"box",
"vertically",
"around",
"the",
"x",
"-",
"axis",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L918-L921 | [
"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",
"]"
] | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | bbox_hflip | Flip a bounding box horizontally around the y-axis. | albumentations/augmentations/functional.py | 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):
"""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] | [
"Flip",
"a",
"bounding",
"box",
"horizontally",
"around",
"the",
"y",
"-",
"axis",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L924-L927 | [
"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",
"]"
] | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | bbox_flip | 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. | albumentations/augmentations/functional.py | 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, r... | 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, r... | [
"Flip",
"a",
"bounding",
"box",
"either",
"vertically",
"horizontally",
"or",
"both",
"depending",
"on",
"the",
"value",
"of",
"d",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L930-L946 | [
"def",
"bbox_flip",
"(",
"bbox",
",",
"d",
",",
"rows",
",",
"cols",
")",
":",
"if",
"d",
"==",
"0",
":",
"bbox",
"=",
"bbox_vflip",
"(",
"bbox",
",",
"rows",
",",
"cols",
")",
"elif",
"d",
"==",
"1",
":",
"bbox",
"=",
"bbox_hflip",
"(",
"bbox"... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | crop_bbox_by_coords | 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. | albumentations/augmentations/functional.py | 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_ma... | 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_ma... | [
"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",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L949-L957 | [
"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",
",... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | bbox_rot90 | Rotates a bounding box by 90 degrees CCW (see np.rot90)
Args:
bbox (tuple): A tuple (x_min, y_min, x_max, y_max).
factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.
rows (int): Image rows.
cols (int): Image cols. | albumentations/augmentations/functional.py | def bbox_rot90(bbox, factor, rows, cols):
"""Rotates a bounding box by 90 degrees CCW (see np.rot90)
Args:
bbox (tuple): A tuple (x_min, y_min, x_max, y_max).
factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.
rows (int): Image rows.
cols (int): Image co... | def bbox_rot90(bbox, factor, rows, cols):
"""Rotates a bounding box by 90 degrees CCW (see np.rot90)
Args:
bbox (tuple): A tuple (x_min, y_min, x_max, y_max).
factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.
rows (int): Image rows.
cols (int): Image co... | [
"Rotates",
"a",
"bounding",
"box",
"by",
"90",
"degrees",
"CCW",
"(",
"see",
"np",
".",
"rot90",
")"
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L977-L995 | [
"def",
"bbox_rot90",
"(",
"bbox",
",",
"factor",
",",
"rows",
",",
"cols",
")",
":",
"if",
"factor",
"<",
"0",
"or",
"factor",
">",
"3",
":",
"raise",
"ValueError",
"(",
"'Parameter n must be in range [0;3]'",
")",
"x_min",
",",
"y_min",
",",
"x_max",
",... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | bbox_rotate | 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... | albumentations/augmentations/functional.py | 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): in... | 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): in... | [
"Rotates",
"a",
"bounding",
"box",
"by",
"angle",
"degrees"
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L998-L1020 | [
"def",
"bbox_rotate",
"(",
"bbox",
",",
"angle",
",",
"rows",
",",
"cols",
",",
"interpolation",
")",
":",
"scale",
"=",
"cols",
"/",
"float",
"(",
"rows",
")",
"x",
"=",
"np",
".",
"array",
"(",
"[",
"bbox",
"[",
"0",
"]",
",",
"bbox",
"[",
"2... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | bbox_transpose | 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. | albumentations/augmentations/functional.py | 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_... | 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_... | [
"Transposes",
"a",
"bounding",
"box",
"along",
"given",
"axis",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1023-L1039 | [
"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 ... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | keypoint_vflip | Flip a keypoint vertically around the x-axis. | albumentations/augmentations/functional.py | 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):
"""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] | [
"Flip",
"a",
"keypoint",
"vertically",
"around",
"the",
"x",
"-",
"axis",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1042-L1048 | [
"def",
"keypoint_vflip",
"(",
"kp",
",",
"rows",
",",
"cols",
")",
":",
"x",
",",
"y",
",",
"angle",
",",
"scale",
"=",
"kp",
"c",
"=",
"math",
".",
"cos",
"(",
"angle",
")",
"s",
"=",
"math",
".",
"sin",
"(",
"angle",
")",
"angle",
"=",
"mat... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | keypoint_flip | 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. | albumentations/augmentations/functional.py | 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... | 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... | [
"Flip",
"a",
"keypoint",
"either",
"vertically",
"horizontally",
"or",
"both",
"depending",
"on",
"the",
"value",
"of",
"d",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1060-L1076 | [
"def",
"keypoint_flip",
"(",
"bbox",
",",
"d",
",",
"rows",
",",
"cols",
")",
":",
"if",
"d",
"==",
"0",
":",
"bbox",
"=",
"keypoint_vflip",
"(",
"bbox",
",",
"rows",
",",
"cols",
")",
"elif",
"d",
"==",
"1",
":",
"bbox",
"=",
"keypoint_hflip",
"... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | keypoint_rot90 | Rotates a keypoint by 90 degrees CCW (see np.rot90)
Args:
keypoint (tuple): A tuple (x, y, angle, scale).
factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.
rows (int): Image rows.
cols (int): Image cols. | albumentations/augmentations/functional.py | def keypoint_rot90(keypoint, factor, rows, cols, **params):
"""Rotates a keypoint by 90 degrees CCW (see np.rot90)
Args:
keypoint (tuple): A tuple (x, y, angle, scale).
factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.
rows (int): Image rows.
cols (int)... | def keypoint_rot90(keypoint, factor, rows, cols, **params):
"""Rotates a keypoint by 90 degrees CCW (see np.rot90)
Args:
keypoint (tuple): A tuple (x, y, angle, scale).
factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.
rows (int): Image rows.
cols (int)... | [
"Rotates",
"a",
"keypoint",
"by",
"90",
"degrees",
"CCW",
"(",
"see",
"np",
".",
"rot90",
")"
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1079-L1097 | [
"def",
"keypoint_rot90",
"(",
"keypoint",
",",
"factor",
",",
"rows",
",",
"cols",
",",
"*",
"*",
"params",
")",
":",
"if",
"factor",
"<",
"0",
"or",
"factor",
">",
"3",
":",
"raise",
"ValueError",
"(",
"'Parameter n must be in range [0;3]'",
")",
"x",
"... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | keypoint_scale | Scales a keypoint by scale_x and scale_y. | albumentations/augmentations/functional.py | 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):
"""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)] | [
"Scales",
"a",
"keypoint",
"by",
"scale_x",
"and",
"scale_y",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1107-L1110 | [
"def",
"keypoint_scale",
"(",
"keypoint",
",",
"scale_x",
",",
"scale_y",
",",
"*",
"*",
"params",
")",
":",
"x",
",",
"y",
",",
"a",
",",
"s",
"=",
"keypoint",
"return",
"[",
"x",
"*",
"scale_x",
",",
"y",
"*",
"scale_y",
",",
"a",
",",
"s",
"... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | crop_keypoint_by_coords | 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. | albumentations/augmentations/functional.py | 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_... | 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_... | [
"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",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1113-L1120 | [
"def",
"crop_keypoint_by_coords",
"(",
"keypoint",
",",
"crop_coords",
",",
"crop_height",
",",
"crop_width",
",",
"rows",
",",
"cols",
")",
":",
"x",
",",
"y",
",",
"a",
",",
"s",
"=",
"keypoint",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"=",
"crop_co... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | py3round | Unified rounding in all python versions. | albumentations/augmentations/functional.py | 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):
"""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)) | [
"Unified",
"rounding",
"in",
"all",
"python",
"versions",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1133-L1138 | [
"def",
"py3round",
"(",
"number",
")",
":",
"if",
"abs",
"(",
"round",
"(",
"number",
")",
"-",
"number",
")",
"==",
"0.5",
":",
"return",
"int",
"(",
"2.0",
"*",
"round",
"(",
"number",
"/",
"2.0",
")",
")",
"return",
"int",
"(",
"round",
"(",
... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | RandomRotate90.apply | Args:
factor (int): number of times the input will be rotated by 90 degrees. | albumentations/augmentations/transforms.py | def apply(self, img, factor=0, **params):
"""
Args:
factor (int): number of times the input will be rotated by 90 degrees.
"""
return np.ascontiguousarray(np.rot90(img, factor)) | def apply(self, img, factor=0, **params):
"""
Args:
factor (int): number of times the input will be rotated by 90 degrees.
"""
return np.ascontiguousarray(np.rot90(img, factor)) | [
"Args",
":",
"factor",
"(",
"int",
")",
":",
"number",
"of",
"times",
"the",
"input",
"will",
"be",
"rotated",
"by",
"90",
"degrees",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/transforms.py#L319-L324 | [
"def",
"apply",
"(",
"self",
",",
"img",
",",
"factor",
"=",
"0",
",",
"*",
"*",
"params",
")",
":",
"return",
"np",
".",
"ascontiguousarray",
"(",
"np",
".",
"rot90",
"(",
"img",
",",
"factor",
")",
")"
] | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | normalize_bbox | Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates
by image height. | albumentations/augmentations/bbox_utils.py | 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')
... | 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')
... | [
"Normalize",
"coordinates",
"of",
"a",
"bounding",
"box",
".",
"Divide",
"x",
"-",
"coordinates",
"by",
"image",
"width",
"and",
"y",
"-",
"coordinates",
"by",
"image",
"height",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L10-L20 | [
"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'... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | denormalize_bbox | Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates
by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`. | albumentations/augmentations/bbox_utils.py | def denormalize_bbox(bbox, rows, cols):
"""Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates
by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`.
"""
if rows == 0:
raise ValueError('Argument ... | def denormalize_bbox(bbox, rows, cols):
"""Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates
by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`.
"""
if rows == 0:
raise ValueError('Argument ... | [
"Denormalize",
"coordinates",
"of",
"a",
"bounding",
"box",
".",
"Multiply",
"x",
"-",
"coordinates",
"by",
"image",
"width",
"and",
"y",
"-",
"coordinates",
"by",
"image",
"height",
".",
"This",
"is",
"an",
"inverse",
"operation",
"for",
":",
"func",
":",... | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L23-L34 | [
"def",
"denormalize_bbox",
"(",
"bbox",
",",
"rows",
",",
"cols",
")",
":",
"if",
"rows",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'Argument rows cannot be zero'",
")",
"if",
"cols",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'Argument cols cannot be zer... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | normalize_bboxes | Normalize a list of bounding boxes. | albumentations/augmentations/bbox_utils.py | 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):
"""Normalize a list of bounding boxes."""
return [normalize_bbox(bbox, rows, cols) for bbox in bboxes] | [
"Normalize",
"a",
"list",
"of",
"bounding",
"boxes",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L37-L39 | [
"def",
"normalize_bboxes",
"(",
"bboxes",
",",
"rows",
",",
"cols",
")",
":",
"return",
"[",
"normalize_bbox",
"(",
"bbox",
",",
"rows",
",",
"cols",
")",
"for",
"bbox",
"in",
"bboxes",
"]"
] | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | denormalize_bboxes | Denormalize a list of bounding boxes. | albumentations/augmentations/bbox_utils.py | 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):
"""Denormalize a list of bounding boxes."""
return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes] | [
"Denormalize",
"a",
"list",
"of",
"bounding",
"boxes",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L42-L44 | [
"def",
"denormalize_bboxes",
"(",
"bboxes",
",",
"rows",
",",
"cols",
")",
":",
"return",
"[",
"denormalize_bbox",
"(",
"bbox",
",",
"rows",
",",
"cols",
")",
"for",
"bbox",
"in",
"bboxes",
"]"
] | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | calculate_bbox_area | Calculate the area of a bounding box in pixels. | albumentations/augmentations/bbox_utils.py | 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):
"""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 | [
"Calculate",
"the",
"area",
"of",
"a",
"bounding",
"box",
"in",
"pixels",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L47-L52 | [
"def",
"calculate_bbox_area",
"(",
"bbox",
",",
"rows",
",",
"cols",
")",
":",
"bbox",
"=",
"denormalize_bbox",
"(",
"bbox",
",",
"rows",
",",
"cols",
")",
"x_min",
",",
"y_min",
",",
"x_max",
",",
"y_max",
"=",
"bbox",
"[",
":",
"4",
"]",
"area",
... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | filter_bboxes_by_visibility | 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(tu... | albumentations/augmentations/bbox_utils.py | 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 ... | 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 ... | [
"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",
... | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L55-L82 | [
"def",
"filter_bboxes_by_visibility",
"(",
"original_shape",
",",
"bboxes",
",",
"transformed_shape",
",",
"transformed_bboxes",
",",
"threshold",
"=",
"0.",
",",
"min_area",
"=",
"0.",
")",
":",
"img_height",
",",
"img_width",
"=",
"original_shape",
"[",
":",
"... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | convert_bbox_to_albumentations | Convert a bounding box from a format specified in `source_format` to the format used by albumentations:
normalized coordinates of bottom-left and top-right corners of the bounding box in a form of
`[x_min, y_min, x_max, y_max]` e.g. `[0.15, 0.27, 0.67, 0.5]`.
Args:
bbox (list): bounding box
... | albumentations/augmentations/bbox_utils.py | def convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity=False):
"""Convert a bounding box from a format specified in `source_format` to the format used by albumentations:
normalized coordinates of bottom-left and top-right corners of the bounding box in a form of
`[x_min, y_min, x... | def convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity=False):
"""Convert a bounding box from a format specified in `source_format` to the format used by albumentations:
normalized coordinates of bottom-left and top-right corners of the bounding box in a form of
`[x_min, y_min, x... | [
"Convert",
"a",
"bounding",
"box",
"from",
"a",
"format",
"specified",
"in",
"source_format",
"to",
"the",
"format",
"used",
"by",
"albumentations",
":",
"normalized",
"coordinates",
"of",
"bottom",
"-",
"left",
"and",
"top",
"-",
"right",
"corners",
"of",
"... | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L85-L119 | [
"def",
"convert_bbox_to_albumentations",
"(",
"bbox",
",",
"source_format",
",",
"rows",
",",
"cols",
",",
"check_validity",
"=",
"False",
")",
":",
"if",
"source_format",
"not",
"in",
"{",
"'coco'",
",",
"'pascal_voc'",
"}",
":",
"raise",
"ValueError",
"(",
... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | convert_bbox_from_albumentations | 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'.
r... | albumentations/augmentations/bbox_utils.py | 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_f... | 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_f... | [
"Convert",
"a",
"bounding",
"box",
"from",
"the",
"format",
"used",
"by",
"albumentations",
"to",
"a",
"format",
"specified",
"in",
"target_format",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L122-L152 | [
"def",
"convert_bbox_from_albumentations",
"(",
"bbox",
",",
"target_format",
",",
"rows",
",",
"cols",
",",
"check_validity",
"=",
"False",
")",
":",
"if",
"target_format",
"not",
"in",
"{",
"'coco'",
",",
"'pascal_voc'",
"}",
":",
"raise",
"ValueError",
"(",... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | convert_bboxes_to_albumentations | Convert a list bounding boxes from a format specified in `source_format` to the format used by albumentations | albumentations/augmentations/bbox_utils.py | 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... | 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... | [
"Convert",
"a",
"list",
"bounding",
"boxes",
"from",
"a",
"format",
"specified",
"in",
"source_format",
"to",
"the",
"format",
"used",
"by",
"albumentations"
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L155-L158 | [
"def",
"convert_bboxes_to_albumentations",
"(",
"bboxes",
",",
"source_format",
",",
"rows",
",",
"cols",
",",
"check_validity",
"=",
"False",
")",
":",
"return",
"[",
"convert_bbox_to_albumentations",
"(",
"bbox",
",",
"source_format",
",",
"rows",
",",
"cols",
... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | convert_bboxes_from_albumentations | 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... | albumentations/augmentations/bbox_utils.py | 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 alb... | 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 alb... | [
"Convert",
"a",
"list",
"of",
"bounding",
"boxes",
"from",
"the",
"format",
"used",
"by",
"albumentations",
"to",
"a",
"format",
"specified",
"in",
"target_format",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L161-L172 | [
"def",
"convert_bboxes_from_albumentations",
"(",
"bboxes",
",",
"target_format",
",",
"rows",
",",
"cols",
",",
"check_validity",
"=",
"False",
")",
":",
"return",
"[",
"convert_bbox_from_albumentations",
"(",
"bbox",
",",
"target_format",
",",
"rows",
",",
"cols... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | check_bbox | Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums | albumentations/augmentations/bbox_utils.py | 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} '
't... | 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} '
't... | [
"Check",
"if",
"bbox",
"boundaries",
"are",
"in",
"range",
"0",
"1",
"and",
"minimums",
"are",
"lesser",
"then",
"maximums"
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L175-L195 | [
"def",
"check_bbox",
"(",
"bbox",
")",
":",
"for",
"name",
",",
"value",
"in",
"zip",
"(",
"[",
"'x_min'",
",",
"'y_min'",
",",
"'x_max'",
",",
"'y_max'",
"]",
",",
"bbox",
"[",
":",
"4",
"]",
")",
":",
"if",
"not",
"0",
"<=",
"value",
"<=",
"1... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | filter_bboxes | 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
... | albumentations/augmentations/bbox_utils.py | 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): Lis... | 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): Lis... | [
"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",
... | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L204-L228 | [
"def",
"filter_bboxes",
"(",
"bboxes",
",",
"rows",
",",
"cols",
",",
"min_area",
"=",
"0.",
",",
"min_visibility",
"=",
"0.",
")",
":",
"resulting_boxes",
"=",
"[",
"]",
"for",
"bbox",
"in",
"bboxes",
":",
"transformed_box_area",
"=",
"calculate_bbox_area",... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | union_of_bboxes | 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 ... | albumentations/augmentations/bbox_utils.py | 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]`.
... | 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]`.
... | [
"Calculate",
"union",
"of",
"bounding",
"boxes",
"."
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L231-L249 | [
"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",
"bb... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | to_tuple | Convert input argument to min-max tuple
Args:
param (scalar, tuple or list of 2+ elements): Input value.
If value is scalar, return value would be (offset - value, offset + value).
If value is tuple, return value would be value + offset (broadcasted).
low: Second element of ... | albumentations/core/transforms_interface.py | def to_tuple(param, low=None, bias=None):
"""Convert input argument to min-max tuple
Args:
param (scalar, tuple or list of 2+ elements): Input value.
If value is scalar, return value would be (offset - value, offset + value).
If value is tuple, return value would be value + offse... | def to_tuple(param, low=None, bias=None):
"""Convert input argument to min-max tuple
Args:
param (scalar, tuple or list of 2+ elements): Input value.
If value is scalar, return value would be (offset - value, offset + value).
If value is tuple, return value would be value + offse... | [
"Convert",
"input",
"argument",
"to",
"min",
"-",
"max",
"tuple",
"Args",
":",
"param",
"(",
"scalar",
"tuple",
"or",
"list",
"of",
"2",
"+",
"elements",
")",
":",
"Input",
"value",
".",
"If",
"value",
"is",
"scalar",
"return",
"value",
"would",
"be",
... | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/core/transforms_interface.py#L8-L36 | [
"def",
"to_tuple",
"(",
"param",
",",
"low",
"=",
"None",
",",
"bias",
"=",
"None",
")",
":",
"if",
"low",
"is",
"not",
"None",
"and",
"bias",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'Arguments low and bias are mutually exclusive'",
")",
"if... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | check_keypoint | Check if keypoint coordinates are in range [0, 1) | albumentations/augmentations/keypoints_utils.py | 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.... | 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.... | [
"Check",
"if",
"keypoint",
"coordinates",
"are",
"in",
"range",
"[",
"0",
"1",
")"
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/keypoints_utils.py#L5-L17 | [
"def",
"check_keypoint",
"(",
"kp",
",",
"rows",
",",
"cols",
")",
":",
"for",
"name",
",",
"value",
",",
"size",
"in",
"zip",
"(",
"[",
"'x'",
",",
"'y'",
"]",
",",
"kp",
"[",
":",
"2",
"]",
",",
"[",
"cols",
",",
"rows",
"]",
")",
":",
"i... | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | check_keypoints | Check if keypoints boundaries are in range [0, 1) | albumentations/augmentations/keypoints_utils.py | 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):
"""Check if keypoints boundaries are in range [0, 1)"""
for kp in keypoints:
check_keypoint(kp, rows, cols) | [
"Check",
"if",
"keypoints",
"boundaries",
"are",
"in",
"range",
"[",
"0",
"1",
")"
] | albu/albumentations | python | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/keypoints_utils.py#L20-L23 | [
"def",
"check_keypoints",
"(",
"keypoints",
",",
"rows",
",",
"cols",
")",
":",
"for",
"kp",
"in",
"keypoints",
":",
"check_keypoint",
"(",
"kp",
",",
"rows",
",",
"cols",
")"
] | b31393cd6126516d37a84e44c879bd92c68ffc93 |
train | start | Begins watching source files for changes.
.. versionchanged:: 5.0
The ``io_loop`` argument (deprecated since version 4.1) has been removed. | tornado/autoreload.py | def start(check_time: int = 500) -> None:
"""Begins watching source files for changes.
.. versionchanged:: 5.0
The ``io_loop`` argument (deprecated since version 4.1) has been removed.
"""
io_loop = ioloop.IOLoop.current()
if io_loop in _io_loops:
return
_io_loops[io_loop] = True... | def start(check_time: int = 500) -> None:
"""Begins watching source files for changes.
.. versionchanged:: 5.0
The ``io_loop`` argument (deprecated since version 4.1) has been removed.
"""
io_loop = ioloop.IOLoop.current()
if io_loop in _io_loops:
return
_io_loops[io_loop] = True... | [
"Begins",
"watching",
"source",
"files",
"for",
"changes",
"."
] | tornadoweb/tornado | python | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/autoreload.py#L118-L133 | [
"def",
"start",
"(",
"check_time",
":",
"int",
"=",
"500",
")",
"->",
"None",
":",
"io_loop",
"=",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
"if",
"io_loop",
"in",
"_io_loops",
":",
"return",
"_io_loops",
"[",
"io_loop",
"]",
"=",
"True",
"i... | b8b481770bcdb333a69afde5cce7eaa449128326 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.