Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function: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_plus(to, safe=":/%#?&=@[]!$&'()*+,;")
# According to RFC 7231, a relative URI is n... | [
"Abort execution and cause a 302 redirect (by default).\n\n :param to: path or fully qualified URL to redirect to\n :param headers: optional dict of headers to include in the new request\n :param status: status code (int) of the new request, defaults to 302\n :param content_type: the content type (strin... |
Please provide a description of the function:async def write(self, data):
if type(data) != bytes:
data = self._encode_body(data)
self.protocol.push_data(b"%x\r\n%b\r\n" % (len(data), data))
await self.protocol.drain() | [
"Writes a chunk of data to the streaming response.\n\n :param data: bytes-ish data to be written.\n "
] |
Please provide a description of the function:async def stream(
self, version="1.1", keep_alive=False, keep_alive_timeout=None
):
headers = self.get_headers(
version,
keep_alive=keep_alive,
keep_alive_timeout=keep_alive_timeout,
)
self.prot... | [
"Streams headers, runs the `streaming_fn` callback that writes\n content to the response body, then finalizes the response body.\n "
] |
Please provide a description of the function:def insert(self, index: int, item: object) -> None:
self._blueprints.insert(index, item) | [
"\n The Abstract class `MutableSequence` leverages this insert method to\n perform the `BlueprintGroup.append` operation.\n\n :param index: Index to use for removing a new Blueprint item\n :param item: New `Blueprint` object.\n :return: None\n "
] |
Please provide a description of the function:def middleware(self, *args, **kwargs):
kwargs["bp_group"] = True
def register_middleware_for_blueprints(fn):
for blueprint in self.blueprints:
blueprint.middleware(fn, *args, **kwargs)
return register_middleware_... | [
"\n A decorator that can be used to implement a Middleware plugin to\n all of the Blueprints that belongs to this specific Blueprint Group.\n\n In case of nested Blueprint Groups, the same middleware is applied\n across each of the Blueprints recursively.\n\n :param args: Optional... |
Please provide a description of the function:def response(self, request, exception):
handler = self.lookup(exception)
response = None
try:
if handler:
response = handler(request, exception)
if response is None:
response = self.defa... | [
"Fetches and executes an exception handler and returns a response\n object\n\n :param request: Instance of :class:`sanic.request.Request`\n :param exception: Exception to handle\n\n :type request: :class:`sanic.request.Request`\n :type exception: :class:`sanic.exceptions.SanicExce... |
Please provide a description of the function:def default(self, request, exception):
self.log(format_exc())
try:
url = repr(request.url)
except AttributeError:
url = "unknown"
response_message = "Exception occurred while handling uri: %s"
logger.e... | [
"\n Provide a default behavior for the objects of :class:`ErrorHandler`.\n If a developer chooses to extent the :class:`ErrorHandler` they can\n provide a custom implementation for this method to behave in a way\n they see fit.\n\n :param request: Incoming request\n :param ... |
Please provide a description of the function:def _create_ssl_context(cfg):
ctx = ssl.SSLContext(cfg.ssl_version)
ctx.load_cert_chain(cfg.certfile, cfg.keyfile)
ctx.verify_mode = cfg.cert_reqs
if cfg.ca_certs:
ctx.load_verify_locations(cfg.ca_certs)
if cfg.cip... | [
" Creates SSLContext instance for usage in asyncio.create_server.\n See ssl.SSLSocket.__init__ for more details.\n "
] |
Please provide a description of the function:def trigger_events(events, loop):
for event in events:
result = event(loop)
if isawaitable(result):
loop.run_until_complete(result) | [
"Trigger event callbacks (functions or async)\n\n :param events: one or more sync or async functions to execute\n :param loop: event loop\n "
] |
Please provide a description of the function: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,
... | [
"Start asynchronous HTTP Server on an individual process.\n\n :param host: Address to host on\n :param port: Port to host on\n :param request_handler: Sanic request handler with middleware\n :param error_handler: Sanic error handler with middleware\n :param before_start: function to be executed befor... |
Please provide a description of the function:def keep_alive(self):
return (
self._keep_alive
and not self.signal.stopped
and self.parser.should_keep_alive()
) | [
"\n Check if the connection needs to be kept alive based on the params\n attached to the `_keep_alive` attribute, :attr:`Signal.stopped`\n and :func:`HttpProtocol.parser.should_keep_alive`\n\n :return: ``True`` if connection is to be kept alive ``False`` else\n "
] |
Please provide a description of the function:def keep_alive_timeout_callback(self):
time_elapsed = time() - self._last_response_time
if time_elapsed < self.keep_alive_timeout:
time_left = self.keep_alive_timeout - time_elapsed
self._keep_alive_timeout_handler = self.loop... | [
"\n Check if elapsed time since last response exceeds our configured\n maximum keep alive timeout value and if so, close the transport\n pipe and let the response writer handle the error.\n\n :return: None\n "
] |
Please provide a description of the function:def execute_request_handler(self):
self._response_timeout_handler = self.loop.call_later(
self.response_timeout, self.response_timeout_callback
)
self._last_request_time = time()
self._request_handler_task = self.loop.crea... | [
"\n Invoke the request handler defined by the\n :func:`sanic.app.Sanic.handle_request` method\n\n :return: None\n "
] |
Please provide a description of the function:def log_response(self, response):
if self.access_log:
extra = {"status": getattr(response, "status", 0)}
if isinstance(response, HTTPResponse):
extra["byte"] = len(response.body)
else:
extr... | [
"\n Helper method provided to enable the logging of responses in case if\n the :attr:`HttpProtocol.access_log` is enabled.\n\n :param response: Response generated for the current request\n\n :type response: :class:`sanic.response.HTTPResponse` or\n :class:`sanic.response.Strea... |
Please provide a description of the function:def write_response(self, response):
if self._response_timeout_handler:
self._response_timeout_handler.cancel()
self._response_timeout_handler = None
try:
keep_alive = self.keep_alive
self.transport.writ... | [
"\n Writes response content synchronously to the transport.\n "
] |
Please provide a description of the function:def bail_out(self, message, from_error=False):
if from_error or self.transport is None or self.transport.is_closing():
logger.error(
"Transport closed @ %s and exception "
"experienced during error handling",
... | [
"\n In case if the transport pipes are closed and the sanic app encounters\n an error while writing data to the transport pipe, we log the error\n with proper details.\n\n :param message: Error message to display\n :param from_error: If the bail out was invoked while handling an\n... |
Please provide a description of the function:def cleanup(self):
self.parser = None
self.request = None
self.url = None
self.headers = None
self._request_handler_task = None
self._request_stream_task = None
self._total_request_size = 0
self._is_str... | [
"This is called when KeepAlive feature is used,\n it resets the connection in order for it to be able\n to handle receiving another request on the same connection."
] |
Please provide a description of the function:def parse_multipart_form(body, boundary):
files = RequestParameters()
fields = RequestParameters()
form_parts = body.split(boundary)
for form_part in form_parts[1:-1]:
file_name = None
content_type = "text/plain"
content_charset ... | [
"Parse a request body and returns fields and files\n\n :param body: bytes request body\n :param boundary: bytes multipart boundary\n :return: fields (RequestParameters), files (RequestParameters)\n "
] |
Please provide a description of the function:async def read(self):
payload = await self._queue.get()
self._queue.task_done()
return payload | [
" Stop reading when gets None "
] |
Please provide a description of the function:def token(self):
prefixes = ("Bearer", "Token")
auth_header = self.headers.get("Authorization")
if auth_header is not None:
for prefix in prefixes:
if prefix in auth_header:
return auth_header.... | [
"Attempt to return the auth header token.\n\n :return: token related to request\n "
] |
Please provide a description of the function:def get_args(
self,
keep_blank_values: bool = False,
strict_parsing: bool = False,
encoding: str = "utf-8",
errors: str = "replace",
) -> RequestParameters:
if not self.parsed_args[
(keep_blank_values, ... | [
"\n Method to parse `query_string` using `urllib.parse.parse_qs`.\n This methods is used by `args` property.\n Can be used directly if you need to change default parameters.\n :param keep_blank_values: flag indicating whether blank values in\n percent-encoded queries should be... |
Please provide a description of the function:def get_query_args(
self,
keep_blank_values: bool = False,
strict_parsing: bool = False,
encoding: str = "utf-8",
errors: str = "replace",
) -> list:
if not self.parsed_not_grouped_args[
(keep_blank_val... | [
"\n Method to parse `query_string` using `urllib.parse.parse_qsl`.\n This methods is used by `query_args` property.\n Can be used directly if you need to change default parameters.\n :param keep_blank_values: flag indicating whether blank values in\n percent-encoded queries sh... |
Please provide a description of the function:def remote_addr(self):
if not hasattr(self, "_remote_addr"):
if self.app.config.PROXIES_COUNT == 0:
self._remote_addr = ""
elif self.app.config.REAL_IP_HEADER and self.headers.get(
self.app.config.REAL_... | [
"Attempt to return the original client ip based on X-Forwarded-For\n or X-Real-IP. If HTTP headers are unavailable or untrusted, returns\n an empty string.\n\n :return: original client ip.\n "
] |
Please provide a description of the function:def strtobool(val):
val = val.lower()
if val in ("y", "yes", "t", "true", "on", "1"):
return True
elif val in ("n", "no", "f", "false", "off", "0"):
return False
else:
raise ValueError("invalid truth value %r" % (val,)) | [
"\n This function was borrowed from distutils.utils. While distutils\n is part of stdlib, it feels odd to use distutils in main application code.\n\n The function was modified to walk its talk and actually return bool\n and not int.\n "
] |
Please provide a description of the function:def from_envvar(self, variable_name):
config_file = os.environ.get(variable_name)
if not config_file:
raise RuntimeError(
"The environment variable %r is not set and "
"thus configuration could not be loade... | [
"Load a configuration from an environment variable pointing to\n a configuration file.\n\n :param variable_name: name of the environment variable\n :return: bool. ``True`` if able to load config, ``False`` otherwise.\n "
] |
Please provide a description of the function:def from_object(self, obj):
for key in dir(obj):
if key.isupper():
self[key] = getattr(obj, key) | [
"Update the values from the given object.\n Objects are usually either modules or classes.\n\n Just the uppercase variables in that object are stored in the config.\n Example usage::\n\n from yourapplication import default_config\n app.config.from_object(default_config)\n\... |
Please provide a description of the function:def load_environment_vars(self, prefix=SANIC_PREFIX):
for k, v in os.environ.items():
if k.startswith(prefix):
_, config_key = k.split(prefix, 1)
try:
self[config_key] = int(v)
e... | [
"\n Looks for prefixed environment variables and applies\n them to the configuration if present.\n "
] |
Please provide a description of the function:def parse_parameter_string(cls, parameter_string):
# We could receive NAME or NAME:PATTERN
name = parameter_string
pattern = "string"
if ":" in parameter_string:
name, pattern = parameter_string.split(":", 1)
i... | [
"Parse a parameter string into its constituent name, type, and\n pattern\n\n For example::\n\n parse_parameter_string('<param_one:[A-z]>')` ->\n ('param_one', str, '[A-z]')\n\n :param parameter_string: String to parse\n :return: tuple containing\n (pa... |
Please provide a description of the function:def add(
self,
uri,
methods,
handler,
host=None,
strict_slashes=False,
version=None,
name=None,
):
if version is not None:
version = re.escape(str(version).strip("/").lstrip("v")... | [
"Add a handler to the route list\n\n :param uri: path to match\n :param methods: sequence of accepted method names. If none are\n provided, any method is allowed\n :param handler: request handler function.\n When executed, it should provide a response object.\n :par... |
Please provide a description of the function:def _add(self, uri, methods, handler, host=None, name=None):
if host is not None:
if isinstance(host, str):
uri = host + uri
self.hosts.add(host)
else:
if not isinstance(host, Iterable)... | [
"Add a handler to the route list\n\n :param uri: path to match\n :param methods: sequence of accepted method names. If none are\n provided, any method is allowed\n :param handler: request handler function.\n When executed, it should provide a response object.\n :par... |
Please provide a description of the function:def check_dynamic_route_exists(pattern, routes_to_check, parameters):
for ndx, route in enumerate(routes_to_check):
if route.pattern == pattern and route.parameters == parameters:
return ndx, route
else:
return... | [
"\n Check if a URL pattern exists in a list of routes provided based on\n the comparison of URL pattern and the parameters.\n\n :param pattern: URL parameter pattern\n :param routes_to_check: list of dynamic routes either hashable or\n unhashable routes.\n :param parame... |
Please provide a description of the function: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(".static"):
return self.routes_static_files.get(name, (None, None))
return... | [
"Find a route in the router based on the specified view name.\n\n :param view_name: string of view name to search by\n :param kwargs: additional params, usually for static files\n :return: tuple containing (uri, Route)\n "
] |
Please provide a description of the function:def get(self, request):
# No virtual hosts specified; default behavior
if not self.hosts:
return self._get(request.path, request.method, "")
# virtual hosts specified; try to match route to the host header
try:
... | [
"Get a request handler based on the URL of the request, or raises an\n error\n\n :param request: Request object\n :return: handler, arguments, keyword arguments\n "
] |
Please provide a description of the function:def get_supported_methods(self, url):
route = self.routes_all.get(url)
# if methods are None then this logic will prevent an error
return getattr(route, "methods", None) or frozenset() | [
"Get a list of supported methods for a url and optional host.\n\n :param url: URL string (including host)\n :return: frozenset of supported methods\n "
] |
Please provide a description of the function:def _get(self, url, method, host):
url = unquote(host + url)
# Check against known static routes
route = self.routes_static.get(url)
method_not_supported = MethodNotSupported(
"Method {} not allowed for URL {}".format(meth... | [
"Get a request handler based on the URL of the request, or raises an\n error. Internal method for caching.\n\n :param url: request URL\n :param method: request method\n :return: handler, arguments, keyword arguments\n "
] |
Please provide a description of the function:def is_stream_handler(self, request):
try:
handler = self.get(request)[0]
except (NotFound, MethodNotSupported):
return False
if hasattr(handler, "view_class") and hasattr(
handler.view_class, request.metho... | [
" Handler for request is stream or not.\n :param request: Request object\n :return: bool\n "
] |
Please provide a description of the function:def _get_args_for_reloading():
rv = [sys.executable]
main_module = sys.modules["__main__"]
mod_spec = getattr(main_module, "__spec__", None)
if mod_spec:
# Parent exe was launched as a module rather than a script
rv.extend(["-m", mod_spec... | [
"Returns the executable."
] |
Please provide a description of the function:def restart_with_reloader():
cwd = os.getcwd()
args = _get_args_for_reloading()
new_environ = os.environ.copy()
new_environ["SANIC_SERVER_RUNNING"] = "true"
cmd = " ".join(args)
worker_process = Process(
target=subprocess.call,
ar... | [
"Create a new process and a subprocess in it with the same arguments as\n this one.\n "
] |
Please provide a description of the function: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
with open(root_process_path) as children_list_file:
children_list_pid = children_list_... | [
"Find and kill child processes of a process (maximum two level).\n\n :param pid: PID of parent process (process ID)\n :return: Nothing\n "
] |
Please provide a description of the function:def kill_process_children(pid):
if sys.platform == "darwin":
kill_process_children_osx(pid)
elif sys.platform == "linux":
kill_process_children_unix(pid)
else:
pass | [
"Find and kill child processes of a process.\n\n :param pid: PID of parent process (process ID)\n :return: Nothing\n "
] |
Please provide a description of the function:def watchdog(sleep_interval):
mtimes = {}
worker_process = restart_with_reloader()
signal.signal(
signal.SIGTERM, lambda *args: kill_program_completly(worker_process)
)
signal.signal(
signal.SIGINT, lambda *args: kill_program_completl... | [
"Watch project files, restart worker process if a change happened.\n\n :param sleep_interval: interval in second.\n :return: Nothing\n "
] |
Please provide a description of the function:def as_view(cls, *class_args, **class_kwargs):
def view(*args, **kwargs):
self = view.view_class(*class_args, **class_kwargs)
return self.dispatch_request(*args, **kwargs)
if cls.decorators:
view.__module__ = cls... | [
"Return view function for use with the routing system, that\n dispatches request to appropriate handler method.\n "
] |
Please provide a description of the function:async def bounded_fetch(session, url):
async with sem, session.get(url) as response:
return await response.json() | [
"\n Use session object to perform 'get' request on url\n "
] |
Please provide a description of the function:def remove_entity_headers(headers, allowed=("content-location", "expires")):
allowed = set([h.lower() for h in allowed])
headers = {
header: value
for header, value in headers.items()
if not is_entity_header(header) or header.lower() in a... | [
"\n Removes all the entity headers present in the headers given.\n According to RFC 2616 Section 10.3.5,\n Content-Location and Expires are allowed as for the\n \"strong cache validator\".\n https://tools.ietf.org/html/rfc2616#section-10.3.5\n\n returns the headers without the entity headers\n ... |
Please provide a description of the function:def preserve_shape(func):
@wraps(func)
def wrapped_function(img, *args, **kwargs):
shape = img.shape
result = func(img, *args, **kwargs)
result = result.reshape(shape)
return result
return wrapped_function | [
"Preserve shape of the image."
] |
Please provide a description of the function:def preserve_channel_dim(func):
@wraps(func)
def wrapped_function(img, *args, **kwargs):
shape = img.shape
result = func(img, *args, **kwargs)
if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2:
result = np.expan... | [
"Preserve dummy channel dim."
] |
Please provide a description of the function:def add_snow(img, snow_point, brightness_coeff):
non_rgb_warning(img)
input_dtype = img.dtype
needs_float = False
snow_point *= 127.5 # = 255 / 2
snow_point += 85 # = 255 / 3
if input_dtype == np.float32:
img = from_float(img, dtype=... | [
"Bleaches out pixels, mitation snow.\n\n From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library\n\n Args:\n img:\n snow_point:\n brightness_coeff:\n\n Returns:\n\n "
] |
Please provide a description of the function:def add_fog(img, fog_coef, alpha_coef, haze_list):
non_rgb_warning(img)
input_dtype = img.dtype
needs_float = False
if input_dtype == np.float32:
img = from_float(img, dtype=np.dtype('uint8'))
needs_float = True
elif input_dtype not... | [
"Add fog to the image.\n\n From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library\n\n Args:\n img (np.array):\n fog_coef (float):\n alpha_coef (float):\n haze_list (list):\n Returns:\n\n "
] |
Please provide a description of the function:def add_sun_flare(img, flare_center_x, flare_center_y, src_radius, src_color, circles):
non_rgb_warning(img)
input_dtype = img.dtype
needs_float = False
if input_dtype == np.float32:
img = from_float(img, dtype=np.dtype('uint8'))
needs_... | [
"Add sun flare.\n\n From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library\n\n Args:\n img (np.array):\n flare_center_x (float):\n flare_center_y (float):\n src_radius:\n src_color (int, int, int):\n circles (list):\n\n Returns:\n\n "
] |
Please provide a description of the function:def add_shadow(img, vertices_list):
non_rgb_warning(img)
input_dtype = img.dtype
needs_float = False
if input_dtype == np.float32:
img = from_float(img, dtype=np.dtype('uint8'))
needs_float = True
elif input_dtype not in (np.uint8, n... | [
"Add shadows to the image.\n\n From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library\n\n Args:\n img (np.array):\n vertices_list (list):\n\n Returns:\n\n "
] |
Please provide a description of the function:def optical_distortion(img, k=0, dx=0, dy=0, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101,
value=None):
height, width = img.shape[:2]
fx = width
fy = width
cx = width * 0.5 + dx
cy = height * 0.5 + dy
... | [
"Barrel / pincushion distortion. Unconventional augment.\n\n Reference:\n | https://stackoverflow.com/questions/6199636/formulas-for-barrel-pincushion-distortion\n | https://stackoverflow.com/questions/10364201/image-transformation-in-opencv\n | https://stackoverflow.com/questions/2477774... |
Please provide a description of the function:def grid_distortion(img, num_steps=10, xsteps=[], ysteps=[], interpolation=cv2.INTER_LINEAR,
border_mode=cv2.BORDER_REFLECT_101, value=None):
height, width = img.shape[:2]
x_step = width // num_steps
xx = np.zeros(width, np.float32)
... | [
"\n Reference:\n http://pythology.blogspot.sg/2014/03/interpolation-on-regular-distorted-grid.html\n "
] |
Please provide a description of the function: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):
if random_state is None:
random_state = np.random.RandomStat... | [
"Elastic deformation of images as described in [Simard2003]_ (with modifications).\n Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5\n\n .. [Simard2003] Simard, Steinkraus and Platt, \"Best Practices for\n Convolutional Neural Networks applied to Visual Document Analysis\", in\n ... |
Please provide a description of the function:def bbox_vflip(bbox, rows, cols):
x_min, y_min, x_max, y_max = bbox
return [x_min, 1 - y_max, x_max, 1 - y_min] | [
"Flip a bounding box vertically around the x-axis."
] |
Please provide a description of the function:def bbox_hflip(bbox, rows, cols):
x_min, y_min, x_max, y_max = bbox
return [1 - x_max, y_min, 1 - x_min, y_max] | [
"Flip a bounding box horizontally around the y-axis."
] |
Please provide a description of the function:def bbox_flip(bbox, d, rows, cols):
if d == 0:
bbox = bbox_vflip(bbox, rows, cols)
elif d == 1:
bbox = bbox_hflip(bbox, rows, cols)
elif d == -1:
bbox = bbox_hflip(bbox, rows, cols)
bbox = bbox_vflip(bbox, rows, cols)
else... | [
"Flip a bounding box either vertically, horizontally or both depending on the value of `d`.\n\n Raises:\n ValueError: if value of `d` is not -1, 0 or 1.\n\n "
] |
Please provide a description of the function:def crop_bbox_by_coords(bbox, crop_coords, crop_height, crop_width, rows, cols):
bbox = denormalize_bbox(bbox, rows, cols)
x_min, y_min, x_max, y_max = bbox
x1, y1, x2, y2 = crop_coords
cropped_bbox = [x_min - x1, y_min - y1, x_max - x1, y_max - y1]
... | [
"Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the\n required height and width of the crop.\n "
] |
Please provide a description of the function: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, y_max = bbox
if factor == 1:
bbox = [y_min, 1 - x_max, y_max, 1 - x_min]
if factor == 2:
... | [
"Rotates a bounding box by 90 degrees CCW (see np.rot90)\n\n Args:\n bbox (tuple): A tuple (x_min, y_min, x_max, y_max).\n factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.\n rows (int): Image rows.\n cols (int): Image cols.\n "
] |
Please provide a description of the function:def bbox_rotate(bbox, angle, rows, cols, interpolation):
scale = cols / float(rows)
x = np.array([bbox[0], bbox[2], bbox[2], bbox[0]])
y = np.array([bbox[1], bbox[1], bbox[3], bbox[3]])
x = x - 0.5
y = y - 0.5
angle = np.deg2rad(angle)
x_t = ... | [
"Rotates a bounding box by angle degrees\n\n Args:\n bbox (tuple): A tuple (x_min, y_min, x_max, y_max).\n angle (int): Angle of rotation in degrees\n rows (int): Image rows.\n cols (int): Image cols.\n interpolation (int): interpolation method.\n\n return a tuple (x_min... |
Please provide a description of the function:def bbox_transpose(bbox, axis, rows, cols):
x_min, y_min, x_max, y_max = bbox
if axis != 0 and axis != 1:
raise ValueError('Axis must be either 0 or 1.')
if axis == 0:
bbox = [y_min, x_min, y_max, x_max]
if axis == 1:
bbox = [1 - ... | [
"Transposes a bounding box along given axis.\n\n Args:\n bbox (tuple): A tuple (x_min, y_min, x_max, y_max).\n axis (int): 0 - main axis, 1 - secondary axis.\n rows (int): Image rows.\n cols (int): Image cols.\n "
] |
Please provide a description of the function:def keypoint_vflip(kp, rows, cols):
x, y, angle, scale = kp
c = math.cos(angle)
s = math.sin(angle)
angle = math.atan2(-s, c)
return [x, (rows - 1) - y, angle, scale] | [
"Flip a keypoint vertically around the x-axis."
] |
Please provide a description of the function:def keypoint_flip(bbox, d, rows, cols):
if d == 0:
bbox = keypoint_vflip(bbox, rows, cols)
elif d == 1:
bbox = keypoint_hflip(bbox, rows, cols)
elif d == -1:
bbox = keypoint_hflip(bbox, rows, cols)
bbox = keypoint_vflip(bbox, ... | [
"Flip a keypoint either vertically, horizontally or both depending on the value of `d`.\n\n Raises:\n ValueError: if value of `d` is not -1, 0 or 1.\n\n "
] |
Please provide a description of the function: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, y, angle, scale = keypoint
if factor == 1:
keypoint = [y, (cols - 1) - x, angle - math.pi / 2, ... | [
"Rotates a keypoint by 90 degrees CCW (see np.rot90)\n\n Args:\n keypoint (tuple): A tuple (x, y, angle, scale).\n factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.\n rows (int): Image rows.\n cols (int): Image cols.\n "
] |
Please provide a description of the function:def keypoint_scale(keypoint, scale_x, scale_y, **params):
x, y, a, s = keypoint
return [x * scale_x, y * scale_y, a, s * max(scale_x, scale_y)] | [
"Scales a keypoint by scale_x and scale_y."
] |
Please provide a description of the function:def crop_keypoint_by_coords(keypoint, crop_coords, crop_height, crop_width, rows, cols):
x, y, a, s = keypoint
x1, y1, x2, y2 = crop_coords
cropped_keypoint = [x - x1, y - y1, a, s]
return cropped_keypoint | [
"Crop a keypoint using the provided coordinates of bottom-left and top-right corners in pixels and the\n required height and width of the crop.\n "
] |
Please provide a description of the function:def py3round(number):
if abs(round(number) - number) == 0.5:
return int(2.0 * round(number / 2.0))
return int(round(number)) | [
"Unified rounding in all python versions."
] |
Please provide a description of the function:def apply(self, img, factor=0, **params):
return np.ascontiguousarray(np.rot90(img, factor)) | [
"\n Args:\n factor (int): number of times the input will be rotated by 90 degrees.\n "
] |
Please provide a description of the function:def normalize_bbox(bbox, rows, cols):
if rows == 0:
raise ValueError('Argument rows cannot be zero')
if cols == 0:
raise ValueError('Argument cols cannot be zero')
x_min, y_min, x_max, y_max = bbox[:4]
normalized_bbox = [x_min / cols, y_m... | [
"Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates\n by image height.\n "
] |
Please provide a description of the function: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 zero')
x_min, y_min, x_max, y_max = bbox[:4]
denormalized_bbox = [x_min * cols... | [
"Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates\n by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`.\n "
] |
Please provide a description of the function:def normalize_bboxes(bboxes, rows, cols):
return [normalize_bbox(bbox, rows, cols) for bbox in bboxes] | [
"Normalize a list of bounding boxes."
] |
Please provide a description of the function:def denormalize_bboxes(bboxes, rows, cols):
return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes] | [
"Denormalize a list of bounding boxes."
] |
Please provide a description of the function:def calculate_bbox_area(bbox, rows, cols):
bbox = denormalize_bbox(bbox, rows, cols)
x_min, y_min, x_max, y_max = bbox[:4]
area = (x_max - x_min) * (y_max - y_min)
return area | [
"Calculate the area of a bounding box in pixels."
] |
Please provide a description of the function:def filter_bboxes_by_visibility(original_shape, bboxes, transformed_shape, transformed_bboxes,
threshold=0., min_area=0.):
img_height, img_width = original_shape[:2]
transformed_img_height, transformed_img_width = transformed_shap... | [
"Filter bounding boxes and return only those boxes whose visibility after transformation is above\n the threshold and minimal area of bounding box in pixels is more then min_area.\n\n Args:\n original_shape (tuple): original image shape\n bboxes (list): original bounding boxes\n transform... |
Please provide a description of the function:def convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity=False):
if source_format not in {'coco', 'pascal_voc'}:
raise ValueError(
"Unknown source_format {}. Supported formats are: 'coco' and 'pascal_voc'".format(source_... | [
"Convert a bounding box from a format specified in `source_format` to the format used by albumentations:\n normalized coordinates of bottom-left and top-right corners of the bounding box in a form of\n `[x_min, y_min, x_max, y_max]` e.g. `[0.15, 0.27, 0.67, 0.5]`.\n\n Args:\n bbox (list): bounding b... |
Please provide a description of the function:def convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity=False):
if target_format not in {'coco', 'pascal_voc'}:
raise ValueError(
"Unknown target_format {}. Supported formats are: 'coco' and 'pascal_voc'".format(targe... | [
"Convert a bounding box from the format used by albumentations to a format, specified in `target_format`.\n\n Args:\n bbox (list): bounding box with coordinates in the format used by albumentations\n target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'.\... |
Please provide a description of the function:def convert_bboxes_to_albumentations(bboxes, source_format, rows, cols, check_validity=False):
return [convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity) for bbox in bboxes] | [
"Convert a list bounding boxes from a format specified in `source_format` to the format used by albumentations\n "
] |
Please provide a description of the function:def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False):
return [convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity) for bbox in bboxes] | [
"Convert a list of bounding boxes from the format used by albumentations to a format, specified\n in `target_format`.\n\n Args:\n bboxes (list): List of bounding box with coordinates in the format used by albumentations\n target_format (str): required format of the output bounding box. Should be... |
Please provide a description of the function:def check_bbox(bbox):
for name, value in zip(['x_min', 'y_min', 'x_max', 'y_max'], bbox[:4]):
if not 0 <= value <= 1:
raise ValueError(
'Expected {name} for bbox {bbox} '
'to be in the range [0.0, 1.0], got {value}... | [
"Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums"
] |
Please provide a description of the function:def filter_bboxes(bboxes, rows, cols, min_area=0., min_visibility=0.):
resulting_boxes = []
for bbox in bboxes:
transformed_box_area = calculate_bbox_area(bbox, rows, cols)
bbox[:4] = np.clip(bbox[:4], 0, 1.)
clipped_box_area = calculate_... | [
"Remove bounding boxes that either lie outside of the visible area by more then min_visibility\n or whose area in pixels is under the threshold set by `min_area`. Also it crops boxes to final image size.\n\n Args:\n bboxes (list): List of bounding box with coordinates in the format used by albumentatio... |
Please provide a description of the function:def union_of_bboxes(height, width, bboxes, erosion_rate=0.0, to_int=False):
x1, y1 = width, height
x2, y2 = 0, 0
for b in bboxes:
w, h = b[2] - b[0], b[3] - b[1]
lim_x1, lim_y1 = b[0] + erosion_rate * w, b[1] + erosion_rate * h
lim_x2... | [
"Calculate union of bounding boxes.\n\n Args:\n height (float): Height of image or space.\n width (float): Width of image or space.\n bboxes (list): List like bounding boxes. Format is `[x_min, y_min, x_max, y_max]`.\n erosion_rate (float): How much each bounding box can be shrinked, ... |
Please provide a description of the function: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 param is None:
return param
if isinstance(param, (int, float)):
if low is None:
... | [
"Convert input argument to min-max tuple\n Args:\n param (scalar, tuple or list of 2+ elements): Input value.\n If value is scalar, return value would be (offset - value, offset + value).\n If value is tuple, return value would be value + offset (broadcasted).\n low: Second e... |
Please provide a description of the function:def check_keypoint(kp, rows, cols):
for name, value, size in zip(['x', 'y'], kp[:2], [cols, rows]):
if not 0 <= value < size:
raise ValueError(
'Expected {name} for keypoint {kp} '
'to be in the range [0.0, {size}]... | [
"Check if keypoint coordinates are in range [0, 1)"
] |
Please provide a description of the function:def check_keypoints(keypoints, rows, cols):
for kp in keypoints:
check_keypoint(kp, rows, cols) | [
"Check if keypoints boundaries are in range [0, 1)"
] |
Please provide a description of the function:def start(check_time: int = 500) -> None:
io_loop = ioloop.IOLoop.current()
if io_loop in _io_loops:
return
_io_loops[io_loop] = True
if len(_io_loops) > 1:
gen_log.warning("tornado.autoreload started more than once in the same process")
... | [
"Begins watching source files for changes.\n\n .. versionchanged:: 5.0\n The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n "
] |
Please provide a description of the function:def main() -> None:
# Remember that we were launched with autoreload as main.
# The main module can be tricky; set the variables both in our globals
# (which may be __main__) and the real importable version.
import tornado.autoreload
global _autorel... | [
"Command-line wrapper to re-run a script whenever its source changes.\n\n Scripts may be specified by filename or module name::\n\n python -m tornado.autoreload -m tornado.test.runtests\n python -m tornado.autoreload tornado/test/runtests.py\n\n Running a script with this wrapper is similar to c... |
Please provide a description of the function:def split(
addrinfo: List[Tuple]
) -> Tuple[
List[Tuple[socket.AddressFamily, Tuple]],
List[Tuple[socket.AddressFamily, Tuple]],
]:
primary = []
secondary = []
primary_af = addrinfo[0][0]
for af, addr i... | [
"Partition the ``addrinfo`` list by address family.\n\n Returns two lists. The first list contains the first entry from\n ``addrinfo`` and all others with the same family, and the\n second list contains all other addresses (normally one list will\n be AF_INET and the other AF_INET6, alt... |
Please provide a description of the function:async def connect(
self,
host: str,
port: int,
af: socket.AddressFamily = socket.AF_UNSPEC,
ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None,
max_buffer_size: int = None,
source_ip: str = None,
source_p... | [
"Connect to the given host and port.\n\n Asynchronously returns an `.IOStream` (or `.SSLIOStream` if\n ``ssl_options`` is not None).\n\n Using the ``source_ip`` kwarg, one can specify the source\n IP address to use when establishing the connection.\n In case the user needs to reso... |
Please provide a description of the function:async def close_all_connections(self) -> None:
while self._connections:
# Peek at an arbitrary element of the set
conn = next(iter(self._connections))
await conn.close() | [
"Close all open connections and asynchronously wait for them to finish.\n\n This method is used in combination with `~.TCPServer.stop` to\n support clean shutdowns (especially for unittests). Typical\n usage would call ``stop()`` first to stop accepting new\n connections, then ``await cl... |
Please provide a description of the function:def _apply_xheaders(self, headers: httputil.HTTPHeaders) -> None:
# Squid uses X-Forwarded-For, others use X-Real-Ip
ip = headers.get("X-Forwarded-For", self.remote_ip)
# Skip trusted downstream hosts in X-Forwarded-For list
for ip in... | [
"Rewrite the ``remote_ip`` and ``protocol`` fields."
] |
Please provide a description of the function:def _unapply_xheaders(self) -> None:
self.remote_ip = self._orig_remote_ip
self.protocol = self._orig_protocol | [
"Undo changes from `_apply_xheaders`.\n\n Xheaders are per-request so they should not leak to the next\n request on the same connection.\n "
] |
Please provide a description of the function:def set_default_locale(code: str) -> None:
global _default_locale
global _supported_locales
_default_locale = code
_supported_locales = frozenset(list(_translations.keys()) + [_default_locale]) | [
"Sets the default locale.\n\n The default locale is assumed to be the language used for all strings\n in the system. The translations loaded from disk are mappings from\n the default locale to the destination locale. Consequently, you don't\n need to create a translation file for the default locale.\n ... |
Please provide a description of the function:def load_translations(directory: str, encoding: str = None) -> None:
global _translations
global _supported_locales
_translations = {}
for path in os.listdir(directory):
if not path.endswith(".csv"):
continue
locale, extension... | [
"Loads translations from CSV files in a directory.\n\n Translations are strings with optional Python-style named placeholders\n (e.g., ``My name is %(name)s``) and their associated translations.\n\n The directory should have translation files of the form ``LOCALE.csv``,\n e.g. ``es_GT.csv``. The CSV fil... |
Please provide a description of the function:def load_gettext_translations(directory: str, domain: str) -> None:
global _translations
global _supported_locales
global _use_gettext
_translations = {}
for lang in os.listdir(directory):
if lang.startswith("."):
continue # skip... | [
"Loads translations from `gettext`'s locale tree\n\n Locale tree is similar to system's ``/usr/share/locale``, like::\n\n {directory}/{lang}/LC_MESSAGES/{domain}.mo\n\n Three steps are required to have your app translated:\n\n 1. Generate POT translation file::\n\n xgettext --language=Python ... |
Please provide a description of the function:def get_closest(cls, *locale_codes: str) -> "Locale":
for code in locale_codes:
if not code:
continue
code = code.replace("-", "_")
parts = code.split("_")
if len(parts) > 2:
con... | [
"Returns the closest match for the given locale code."
] |
Please provide a description of the function:def get(cls, code: str) -> "Locale":
if code not in cls._cache:
assert code in _supported_locales
translations = _translations.get(code, None)
if translations is None:
locale = CSVLocale(code, {}) # type: ... | [
"Returns the Locale for the given locale code.\n\n If it is not supported, we raise an exception.\n "
] |
Please provide a description of the function:def translate(
self, message: str, plural_message: str = None, count: int = None
) -> str:
raise NotImplementedError() | [
"Returns the translation for the given message for this locale.\n\n If ``plural_message`` is given, you must also provide\n ``count``. We return ``plural_message`` when ``count != 1``,\n and we return the singular form for the given message when\n ``count == 1``.\n "
] |
Please provide a description of the function:def format_date(
self,
date: Union[int, float, datetime.datetime],
gmt_offset: int = 0,
relative: bool = True,
shorter: bool = False,
full_format: bool = False,
) -> str:
if isinstance(date, (int, float)):
... | [
"Formats the given date (which should be GMT).\n\n By default, we return a relative time (e.g., \"2 minutes ago\"). You\n can return an absolute date string with ``relative=False``.\n\n You can force a full format date (\"July 10, 1980\") with\n ``full_format=True``.\n\n This meth... |
Please provide a description of the function:def format_day(
self, date: datetime.datetime, gmt_offset: int = 0, dow: bool = True
) -> bool:
local_date = date - datetime.timedelta(minutes=gmt_offset)
_ = self.translate
if dow:
return _("%(weekday)s, %(month_name)... | [
"Formats the given date as a day of week.\n\n Example: \"Monday, January 22\". You can remove the day of week with\n ``dow=False``.\n "
] |
Please provide a description of the function:def list(self, parts: Any) -> str:
_ = self.translate
if len(parts) == 0:
return ""
if len(parts) == 1:
return parts[0]
comma = u" \u0648 " if self.code.startswith("fa") else u", "
return _("%(commas)s ... | [
"Returns a comma-separated list for the given list of parts.\n\n The format is, e.g., \"A, B and C\", \"A and B\" or just \"A\" for lists\n of size 1.\n "
] |
Please provide a description of the function:def friendly_number(self, value: int) -> str:
if self.code not in ("en", "en_US"):
return str(value)
s = str(value)
parts = []
while s:
parts.append(s[-3:])
s = s[:-3]
return ",".join(revers... | [
"Returns a comma-separated number for the given integer."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.