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 | _DefinitionBase.setup | Setup this resource so that is ready to be used in a test. If the
resource has already been created, this call does nothing.
For most resources, this just involves creating the resource in Docker.
:param helper:
The resource helper to use, if one was not provided when this
... | seaworthy/definitions.py | def setup(self, helper=None, **create_kwargs):
"""
Setup this resource so that is ready to be used in a test. If the
resource has already been created, this call does nothing.
For most resources, this just involves creating the resource in Docker.
:param helper:
The... | def setup(self, helper=None, **create_kwargs):
"""
Setup this resource so that is ready to be used in a test. If the
resource has already been created, this call does nothing.
For most resources, this just involves creating the resource in Docker.
:param helper:
The... | [
"Setup",
"this",
"resource",
"so",
"that",
"is",
"ready",
"to",
"be",
"used",
"in",
"a",
"test",
".",
"If",
"the",
"resource",
"has",
"already",
"been",
"created",
"this",
"call",
"does",
"nothing",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L76-L99 | [
"def",
"setup",
"(",
"self",
",",
"helper",
"=",
"None",
",",
"*",
"*",
"create_kwargs",
")",
":",
"if",
"self",
".",
"created",
":",
"return",
"self",
".",
"set_helper",
"(",
"helper",
")",
"self",
".",
"create",
"(",
"*",
"*",
"create_kwargs",
")",... | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | _DefinitionBase.set_helper | .. todo::
Document this. | seaworthy/definitions.py | def set_helper(self, helper):
"""
.. todo::
Document this.
"""
# We don't want to "unset" in this method.
if helper is None:
return
# Get the right kind of helper if given a DockerHelper
if isinstance(helper, DockerHelper):
he... | def set_helper(self, helper):
"""
.. todo::
Document this.
"""
# We don't want to "unset" in this method.
if helper is None:
return
# Get the right kind of helper if given a DockerHelper
if isinstance(helper, DockerHelper):
he... | [
"..",
"todo",
"::"
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L125-L145 | [
"def",
"set_helper",
"(",
"self",
",",
"helper",
")",
":",
"# We don't want to \"unset\" in this method.",
"if",
"helper",
"is",
"None",
":",
"return",
"# Get the right kind of helper if given a DockerHelper",
"if",
"isinstance",
"(",
"helper",
",",
"DockerHelper",
")",
... | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | _DefinitionBase.as_fixture | A decorator to inject this container into a function as a test fixture. | seaworthy/definitions.py | def as_fixture(self, name=None):
"""
A decorator to inject this container into a function as a test fixture.
"""
if name is None:
name = self.name
def deco(f):
@functools.wraps(f)
def wrapper(*args, **kw):
with self:
... | def as_fixture(self, name=None):
"""
A decorator to inject this container into a function as a test fixture.
"""
if name is None:
name = self.name
def deco(f):
@functools.wraps(f)
def wrapper(*args, **kw):
with self:
... | [
"A",
"decorator",
"to",
"inject",
"this",
"container",
"into",
"a",
"function",
"as",
"a",
"test",
"fixture",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L147-L161 | [
"def",
"as_fixture",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"name",
"def",
"deco",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*... | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | _DefinitionBase.inner | :returns: the underlying Docker model object | seaworthy/definitions.py | def inner(self):
"""
:returns: the underlying Docker model object
"""
if not self.created:
raise RuntimeError(
'{} not created yet.'.format(self.__model_type__.__name__))
return self._inner | def inner(self):
"""
:returns: the underlying Docker model object
"""
if not self.created:
raise RuntimeError(
'{} not created yet.'.format(self.__model_type__.__name__))
return self._inner | [
":",
"returns",
":",
"the",
"underlying",
"Docker",
"model",
"object"
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L163-L170 | [
"def",
"inner",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"created",
":",
"raise",
"RuntimeError",
"(",
"'{} not created yet.'",
".",
"format",
"(",
"self",
".",
"__model_type__",
".",
"__name__",
")",
")",
"return",
"self",
".",
"_inner"
] | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | ContainerDefinition.setup | Creates the container, starts it, and waits for it to completely start.
:param helper:
The resource helper to use, if one was not provided when this
container definition was created.
:param **run_kwargs: Keyword arguments passed to :meth:`.run`.
:returns:
Th... | seaworthy/definitions.py | def setup(self, helper=None, **run_kwargs):
"""
Creates the container, starts it, and waits for it to completely start.
:param helper:
The resource helper to use, if one was not provided when this
container definition was created.
:param **run_kwargs: Keyword arg... | def setup(self, helper=None, **run_kwargs):
"""
Creates the container, starts it, and waits for it to completely start.
:param helper:
The resource helper to use, if one was not provided when this
container definition was created.
:param **run_kwargs: Keyword arg... | [
"Creates",
"the",
"container",
"starts",
"it",
"and",
"waits",
"for",
"it",
"to",
"completely",
"start",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L246-L267 | [
"def",
"setup",
"(",
"self",
",",
"helper",
"=",
"None",
",",
"*",
"*",
"run_kwargs",
")",
":",
"if",
"self",
".",
"created",
":",
"return",
"self",
".",
"set_helper",
"(",
"helper",
")",
"self",
".",
"run",
"(",
"*",
"*",
"run_kwargs",
")",
"self"... | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | ContainerDefinition.teardown | Stop and remove the container if it exists. | seaworthy/definitions.py | def teardown(self):
"""
Stop and remove the container if it exists.
"""
while self._http_clients:
self._http_clients.pop().close()
if self.created:
self.halt() | def teardown(self):
"""
Stop and remove the container if it exists.
"""
while self._http_clients:
self._http_clients.pop().close()
if self.created:
self.halt() | [
"Stop",
"and",
"remove",
"the",
"container",
"if",
"it",
"exists",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L269-L276 | [
"def",
"teardown",
"(",
"self",
")",
":",
"while",
"self",
".",
"_http_clients",
":",
"self",
".",
"_http_clients",
".",
"pop",
"(",
")",
".",
"close",
"(",
")",
"if",
"self",
".",
"created",
":",
"self",
".",
"halt",
"(",
")"
] | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | ContainerDefinition.status | Get the container's current status from Docker.
If the container does not exist (before creation and after removal),
the status is ``None``. | seaworthy/definitions.py | def status(self):
"""
Get the container's current status from Docker.
If the container does not exist (before creation and after removal),
the status is ``None``.
"""
if not self.created:
return None
self.inner().reload()
return self.inner().s... | def status(self):
"""
Get the container's current status from Docker.
If the container does not exist (before creation and after removal),
the status is ``None``.
"""
if not self.created:
return None
self.inner().reload()
return self.inner().s... | [
"Get",
"the",
"container",
"s",
"current",
"status",
"from",
"Docker",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L278-L288 | [
"def",
"status",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"created",
":",
"return",
"None",
"self",
".",
"inner",
"(",
")",
".",
"reload",
"(",
")",
"return",
"self",
".",
"inner",
"(",
")",
".",
"status"
] | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | ContainerDefinition.stop | Stop the container. The container must have been created.
:param timeout:
Timeout in seconds to wait for the container to stop before sending
a ``SIGKILL``. Default: 5 (half the Docker default) | seaworthy/definitions.py | def stop(self, timeout=5):
"""
Stop the container. The container must have been created.
:param timeout:
Timeout in seconds to wait for the container to stop before sending
a ``SIGKILL``. Default: 5 (half the Docker default)
"""
self.inner().stop(timeout=... | def stop(self, timeout=5):
"""
Stop the container. The container must have been created.
:param timeout:
Timeout in seconds to wait for the container to stop before sending
a ``SIGKILL``. Default: 5 (half the Docker default)
"""
self.inner().stop(timeout=... | [
"Stop",
"the",
"container",
".",
"The",
"container",
"must",
"have",
"been",
"created",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L297-L306 | [
"def",
"stop",
"(",
"self",
",",
"timeout",
"=",
"5",
")",
":",
"self",
".",
"inner",
"(",
")",
".",
"stop",
"(",
"timeout",
"=",
"timeout",
")",
"self",
".",
"inner",
"(",
")",
".",
"reload",
"(",
")"
] | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | ContainerDefinition.run | Create the container and start it. Similar to ``docker run``.
:param fetch_image:
Whether to try pull the image if it's not found. The behaviour here
is similar to ``docker run`` and this parameter defaults to
``True``.
:param **kwargs: Keyword arguments passed to :m... | seaworthy/definitions.py | def run(self, fetch_image=True, **kwargs):
"""
Create the container and start it. Similar to ``docker run``.
:param fetch_image:
Whether to try pull the image if it's not found. The behaviour here
is similar to ``docker run`` and this parameter defaults to
``... | def run(self, fetch_image=True, **kwargs):
"""
Create the container and start it. Similar to ``docker run``.
:param fetch_image:
Whether to try pull the image if it's not found. The behaviour here
is similar to ``docker run`` and this parameter defaults to
``... | [
"Create",
"the",
"container",
"and",
"start",
"it",
".",
"Similar",
"to",
"docker",
"run",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L308-L319 | [
"def",
"run",
"(",
"self",
",",
"fetch_image",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"create",
"(",
"fetch_image",
"=",
"fetch_image",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"start",
"(",
")"
] | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | ContainerDefinition.wait_for_start | Wait for the container to start.
By default this will wait for the log lines matching the patterns
passed in the ``wait_patterns`` parameter of the constructor using an
UnorderedMatcher. For more advanced checks for container startup, this
method should be overridden. | seaworthy/definitions.py | def wait_for_start(self):
"""
Wait for the container to start.
By default this will wait for the log lines matching the patterns
passed in the ``wait_patterns`` parameter of the constructor using an
UnorderedMatcher. For more advanced checks for container startup, this
m... | def wait_for_start(self):
"""
Wait for the container to start.
By default this will wait for the log lines matching the patterns
passed in the ``wait_patterns`` parameter of the constructor using an
UnorderedMatcher. For more advanced checks for container startup, this
m... | [
"Wait",
"for",
"the",
"container",
"to",
"start",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L321-L332 | [
"def",
"wait_for_start",
"(",
"self",
")",
":",
"if",
"self",
".",
"wait_matchers",
":",
"matcher",
"=",
"UnorderedMatcher",
"(",
"*",
"self",
".",
"wait_matchers",
")",
"self",
".",
"wait_for_logs_matching",
"(",
"matcher",
",",
"timeout",
"=",
"self",
".",... | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | ContainerDefinition.get_host_port | :param container_port: The container port.
:param proto: The protocol ('tcp' or 'udp').
:param index: The index of the mapping entry to return.
:returns: A tuple of the interface IP and port on the host. | seaworthy/definitions.py | def get_host_port(self, container_port, proto='tcp', index=0):
"""
:param container_port: The container port.
:param proto: The protocol ('tcp' or 'udp').
:param index: The index of the mapping entry to return.
:returns: A tuple of the interface IP and port on the host.
"... | def get_host_port(self, container_port, proto='tcp', index=0):
"""
:param container_port: The container port.
:param proto: The protocol ('tcp' or 'udp').
:param index: The index of the mapping entry to return.
:returns: A tuple of the interface IP and port on the host.
"... | [
":",
"param",
"container_port",
":",
"The",
"container",
"port",
".",
":",
"param",
"proto",
":",
"The",
"protocol",
"(",
"tcp",
"or",
"udp",
")",
".",
":",
"param",
"index",
":",
"The",
"index",
"of",
"the",
"mapping",
"entry",
"to",
"return",
".",
... | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L370-L378 | [
"def",
"get_host_port",
"(",
"self",
",",
"container_port",
",",
"proto",
"=",
"'tcp'",
",",
"index",
"=",
"0",
")",
":",
"port_spec",
"=",
"'{}/{}'",
".",
"format",
"(",
"container_port",
",",
"proto",
")",
"return",
"self",
".",
"_host_port",
"(",
"por... | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | ContainerDefinition.get_first_host_port | Get the first mapping of the first (lowest) container port that has a
mapping. Useful when a container publishes only one port.
Note that unlike the Docker API, which sorts ports lexicographically
(e.g. ``90/tcp`` > ``8000/tcp``), we sort ports numerically so that the
lowest port is alw... | seaworthy/definitions.py | def get_first_host_port(self):
"""
Get the first mapping of the first (lowest) container port that has a
mapping. Useful when a container publishes only one port.
Note that unlike the Docker API, which sorts ports lexicographically
(e.g. ``90/tcp`` > ``8000/tcp``), we sort ports... | def get_first_host_port(self):
"""
Get the first mapping of the first (lowest) container port that has a
mapping. Useful when a container publishes only one port.
Note that unlike the Docker API, which sorts ports lexicographically
(e.g. ``90/tcp`` > ``8000/tcp``), we sort ports... | [
"Get",
"the",
"first",
"mapping",
"of",
"the",
"first",
"(",
"lowest",
")",
"container",
"port",
"that",
"has",
"a",
"mapping",
".",
"Useful",
"when",
"a",
"container",
"publishes",
"only",
"one",
"port",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L380-L398 | [
"def",
"get_first_host_port",
"(",
"self",
")",
":",
"mapped_ports",
"=",
"{",
"p",
":",
"m",
"for",
"p",
",",
"m",
"in",
"self",
".",
"ports",
".",
"items",
"(",
")",
"if",
"m",
"is",
"not",
"None",
"}",
"if",
"not",
"mapped_ports",
":",
"raise",
... | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | ContainerDefinition.get_logs | Get container logs.
This method does not support streaming, use :meth:`stream_logs` for
that. | seaworthy/definitions.py | def get_logs(self, stdout=True, stderr=True, timestamps=False, tail='all',
since=None):
"""
Get container logs.
This method does not support streaming, use :meth:`stream_logs` for
that.
"""
return self.inner().logs(
stdout=stdout, stderr=stde... | def get_logs(self, stdout=True, stderr=True, timestamps=False, tail='all',
since=None):
"""
Get container logs.
This method does not support streaming, use :meth:`stream_logs` for
that.
"""
return self.inner().logs(
stdout=stdout, stderr=stde... | [
"Get",
"container",
"logs",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L400-L410 | [
"def",
"get_logs",
"(",
"self",
",",
"stdout",
"=",
"True",
",",
"stderr",
"=",
"True",
",",
"timestamps",
"=",
"False",
",",
"tail",
"=",
"'all'",
",",
"since",
"=",
"None",
")",
":",
"return",
"self",
".",
"inner",
"(",
")",
".",
"logs",
"(",
"... | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | ContainerDefinition.stream_logs | Stream container output. | seaworthy/definitions.py | def stream_logs(self, stdout=True, stderr=True, tail='all', timeout=10.0):
"""
Stream container output.
"""
return stream_logs(
self.inner(), stdout=stdout, stderr=stderr, tail=tail,
timeout=timeout) | def stream_logs(self, stdout=True, stderr=True, tail='all', timeout=10.0):
"""
Stream container output.
"""
return stream_logs(
self.inner(), stdout=stdout, stderr=stderr, tail=tail,
timeout=timeout) | [
"Stream",
"container",
"output",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L412-L418 | [
"def",
"stream_logs",
"(",
"self",
",",
"stdout",
"=",
"True",
",",
"stderr",
"=",
"True",
",",
"tail",
"=",
"'all'",
",",
"timeout",
"=",
"10.0",
")",
":",
"return",
"stream_logs",
"(",
"self",
".",
"inner",
"(",
")",
",",
"stdout",
"=",
"stdout",
... | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | ContainerDefinition.wait_for_logs_matching | Wait for logs matching the given matcher. | seaworthy/definitions.py | def wait_for_logs_matching(self, matcher, timeout=10, encoding='utf-8',
**logs_kwargs):
"""
Wait for logs matching the given matcher.
"""
wait_for_logs_matching(
self.inner(), matcher, timeout=timeout, encoding=encoding,
**logs_kwarg... | def wait_for_logs_matching(self, matcher, timeout=10, encoding='utf-8',
**logs_kwargs):
"""
Wait for logs matching the given matcher.
"""
wait_for_logs_matching(
self.inner(), matcher, timeout=timeout, encoding=encoding,
**logs_kwarg... | [
"Wait",
"for",
"logs",
"matching",
"the",
"given",
"matcher",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L420-L427 | [
"def",
"wait_for_logs_matching",
"(",
"self",
",",
"matcher",
",",
"timeout",
"=",
"10",
",",
"encoding",
"=",
"'utf-8'",
",",
"*",
"*",
"logs_kwargs",
")",
":",
"wait_for_logs_matching",
"(",
"self",
".",
"inner",
"(",
")",
",",
"matcher",
",",
"timeout",... | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | ContainerDefinition.http_client | Construct an HTTP client for this container. | seaworthy/definitions.py | def http_client(self, port=None):
"""
Construct an HTTP client for this container.
"""
# Local import to avoid potential circularity.
from seaworthy.client import ContainerHttpClient
client = ContainerHttpClient.for_container(self, container_port=port)
self._http_... | def http_client(self, port=None):
"""
Construct an HTTP client for this container.
"""
# Local import to avoid potential circularity.
from seaworthy.client import ContainerHttpClient
client = ContainerHttpClient.for_container(self, container_port=port)
self._http_... | [
"Construct",
"an",
"HTTP",
"client",
"for",
"this",
"container",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L429-L437 | [
"def",
"http_client",
"(",
"self",
",",
"port",
"=",
"None",
")",
":",
"# Local import to avoid potential circularity.",
"from",
"seaworthy",
".",
"client",
"import",
"ContainerHttpClient",
"client",
"=",
"ContainerHttpClient",
".",
"for_container",
"(",
"self",
",",
... | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | cmd_register | Войти в приложение с помощью SMS. | rock_cli/cli/register.py | def cmd_register(phone):
"""
Войти в приложение с помощью SMS.
"""
if phone is None:
phone = click.prompt("Номер телефона")
r = rocket.devices.register.post(data={"phone": phone})
r = handle_error(r)
id = r.json()["sms_verification"]["id"]
code = click.prompt("Введите код из SM... | def cmd_register(phone):
"""
Войти в приложение с помощью SMS.
"""
if phone is None:
phone = click.prompt("Номер телефона")
r = rocket.devices.register.post(data={"phone": phone})
r = handle_error(r)
id = r.json()["sms_verification"]["id"]
code = click.prompt("Введите код из SM... | [
"Войти",
"в",
"приложение",
"с",
"помощью",
"SMS",
"."
] | notpushkin/rock | python | https://github.com/notpushkin/rock/blob/c1451a7604b462c19e4929f0eb171cbcf23e50ab/rock_cli/cli/register.py#L7-L27 | [
"def",
"cmd_register",
"(",
"phone",
")",
":",
"if",
"phone",
"is",
"None",
":",
"phone",
"=",
"click",
".",
"prompt",
"(",
"\"Номер телефона\")",
"",
"r",
"=",
"rocket",
".",
"devices",
".",
"register",
".",
"post",
"(",
"data",
"=",
"{",
"\"phone\"",... | c1451a7604b462c19e4929f0eb171cbcf23e50ab |
train | create_autosummary_file | Create the module's index. | docs/apigen.py | def create_autosummary_file(modules, opts):
# type: (List[unicode], Any, unicode) -> None
"""Create the module's index."""
lines = [
'API Reference',
'=============',
'',
'.. autosummary::',
' :template: api_module.rst',
' :toctree: {}'.format(opts.destdir... | def create_autosummary_file(modules, opts):
# type: (List[unicode], Any, unicode) -> None
"""Create the module's index."""
lines = [
'API Reference',
'=============',
'',
'.. autosummary::',
' :template: api_module.rst',
' :toctree: {}'.format(opts.destdir... | [
"Create",
"the",
"module",
"s",
"index",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/docs/apigen.py#L62-L83 | [
"def",
"create_autosummary_file",
"(",
"modules",
",",
"opts",
")",
":",
"# type: (List[unicode], Any, unicode) -> None",
"lines",
"=",
"[",
"'API Reference'",
",",
"'============='",
",",
"''",
",",
"'.. autosummary::'",
",",
"' :template: api_module.rst'",
",",
"' :... | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | recurse_tree | Look for every file in the directory tree and create the corresponding
ReST files. | docs/apigen.py | def recurse_tree(rootpath, excludes, opts):
# type: (unicode, List[unicode], Any) -> List[unicode]
"""
Look for every file in the directory tree and create the corresponding
ReST files.
"""
if INITPY in os.listdir(rootpath):
path_prefix = path.sep.join(rootpath.split(path.sep)[:-1])
... | def recurse_tree(rootpath, excludes, opts):
# type: (unicode, List[unicode], Any) -> List[unicode]
"""
Look for every file in the directory tree and create the corresponding
ReST files.
"""
if INITPY in os.listdir(rootpath):
path_prefix = path.sep.join(rootpath.split(path.sep)[:-1])
... | [
"Look",
"for",
"every",
"file",
"in",
"the",
"directory",
"tree",
"and",
"create",
"the",
"corresponding",
"ReST",
"files",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/docs/apigen.py#L105-L154 | [
"def",
"recurse_tree",
"(",
"rootpath",
",",
"excludes",
",",
"opts",
")",
":",
"# type: (unicode, List[unicode], Any) -> List[unicode]",
"if",
"INITPY",
"in",
"os",
".",
"listdir",
"(",
"rootpath",
")",
":",
"path_prefix",
"=",
"path",
".",
"sep",
".",
"join",
... | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | main | Parse and check the command line arguments. | docs/apigen.py | def main(argv=sys.argv):
# type: (List[str]) -> int
"""Parse and check the command line arguments."""
parser = optparse.OptionParser(
usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_pattern, ...]
Look recursively in <module_path> for Python modules and packages and create
... | def main(argv=sys.argv):
# type: (List[str]) -> int
"""Parse and check the command line arguments."""
parser = optparse.OptionParser(
usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_pattern, ...]
Look recursively in <module_path> for Python modules and packages and create
... | [
"Parse",
"and",
"check",
"the",
"command",
"line",
"arguments",
"."
] | praekeltfoundation/seaworthy | python | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/docs/apigen.py#L176-L236 | [
"def",
"main",
"(",
"argv",
"=",
"sys",
".",
"argv",
")",
":",
"# type: (List[str]) -> int",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"usage",
"=",
"\"\"\"\\\nusage: %prog [options] -o <output_path> <module_path> [exclude_pattern, ...]\n\nLook recursively in <module... | 6f10a19b45d4ea1dc3bd0553cc4d0438696c079c |
train | cmd_repl | Запускает интерпретатор Python с подключенной обёрткой API Рокетбанка. | rock_cli/cli/repl.py | def cmd_repl():
"""
Запускает интерпретатор Python с подключенной обёрткой API Рокетбанка.
"""
import code
import rlcompleter # noqa
import readline
import sys
readline.parse_and_bind("tab: complete")
shell = code.InteractiveConsole({
"rocket": rocket,
})
shell.inte... | def cmd_repl():
"""
Запускает интерпретатор Python с подключенной обёрткой API Рокетбанка.
"""
import code
import rlcompleter # noqa
import readline
import sys
readline.parse_and_bind("tab: complete")
shell = code.InteractiveConsole({
"rocket": rocket,
})
shell.inte... | [
"Запускает",
"интерпретатор",
"Python",
"с",
"подключенной",
"обёрткой",
"API",
"Рокетбанка",
"."
] | notpushkin/rock | python | https://github.com/notpushkin/rock/blob/c1451a7604b462c19e4929f0eb171cbcf23e50ab/rock_cli/cli/repl.py#L7-L21 | [
"def",
"cmd_repl",
"(",
")",
":",
"import",
"code",
"import",
"rlcompleter",
"# noqa",
"import",
"readline",
"import",
"sys",
"readline",
".",
"parse_and_bind",
"(",
"\"tab: complete\"",
")",
"shell",
"=",
"code",
".",
"InteractiveConsole",
"(",
"{",
"\"rocket\"... | c1451a7604b462c19e4929f0eb171cbcf23e50ab |
train | OAuthHandler.get_authorization_url | Get the authorization URL to redirect the user | pyfoursquare/foursquare.py | def get_authorization_url(self):
"""Get the authorization URL to redirect the user"""
url = self._get_oauth_url('authenticate')
query = {
'client_id': self._client_id,
'response_type': 'code',
'redirect_uri': self.callback
}
query_str = self.ur... | def get_authorization_url(self):
"""Get the authorization URL to redirect the user"""
url = self._get_oauth_url('authenticate')
query = {
'client_id': self._client_id,
'response_type': 'code',
'redirect_uri': self.callback
}
query_str = self.ur... | [
"Get",
"the",
"authorization",
"URL",
"to",
"redirect",
"the",
"user"
] | marcelcaraciolo/foursquare | python | https://github.com/marcelcaraciolo/foursquare/blob/a8bda33cc2d61e25aa8df72011246269fd98aa13/pyfoursquare/foursquare.py#L208-L218 | [
"def",
"get_authorization_url",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_get_oauth_url",
"(",
"'authenticate'",
")",
"query",
"=",
"{",
"'client_id'",
":",
"self",
".",
"_client_id",
",",
"'response_type'",
":",
"'code'",
",",
"'redirect_uri'",
":",
... | a8bda33cc2d61e25aa8df72011246269fd98aa13 |
train | OAuthHandler.get_access_token | After user has authorized the request token, get access token
with user supplied verifier. | pyfoursquare/foursquare.py | def get_access_token(self, verifier=None):
"""
After user has authorized the request token, get access token
with user supplied verifier.
"""
try:
url = self._get_oauth_url('access_token')
#build request
query = {
'client_id': ... | def get_access_token(self, verifier=None):
"""
After user has authorized the request token, get access token
with user supplied verifier.
"""
try:
url = self._get_oauth_url('access_token')
#build request
query = {
'client_id': ... | [
"After",
"user",
"has",
"authorized",
"the",
"request",
"token",
"get",
"access",
"token",
"with",
"user",
"supplied",
"verifier",
"."
] | marcelcaraciolo/foursquare | python | https://github.com/marcelcaraciolo/foursquare/blob/a8bda33cc2d61e25aa8df72011246269fd98aa13/pyfoursquare/foursquare.py#L227-L256 | [
"def",
"get_access_token",
"(",
"self",
",",
"verifier",
"=",
"None",
")",
":",
"try",
":",
"url",
"=",
"self",
".",
"_get_oauth_url",
"(",
"'access_token'",
")",
"#build request",
"query",
"=",
"{",
"'client_id'",
":",
"self",
".",
"_client_id",
",",
"'cl... | a8bda33cc2d61e25aa8df72011246269fd98aa13 |
train | _dispatch_change_event | Prepare and dispatch a trait change event to a listener. | src/automate/traits_fixes.py | def _dispatch_change_event(self, object, trait_name, old, new, handler):
""" Prepare and dispatch a trait change event to a listener. """
# Extract the arguments needed from the handler.
args = self.argument_transform(object, trait_name, old, new)
# Send a description of the event to the change event ... | def _dispatch_change_event(self, object, trait_name, old, new, handler):
""" Prepare and dispatch a trait change event to a listener. """
# Extract the arguments needed from the handler.
args = self.argument_transform(object, trait_name, old, new)
# Send a description of the event to the change event ... | [
"Prepare",
"and",
"dispatch",
"a",
"trait",
"change",
"event",
"to",
"a",
"listener",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/traits_fixes.py#L59-L85 | [
"def",
"_dispatch_change_event",
"(",
"self",
",",
"object",
",",
"trait_name",
",",
"old",
",",
"new",
",",
"handler",
")",
":",
"# Extract the arguments needed from the handler.",
"args",
"=",
"self",
".",
"argument_transform",
"(",
"object",
",",
"trait_name",
... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | split | Split `value` into value and "exponent-of-10", where "exponent-of-10" is a
multiple of 3. This corresponds to SI prefixes.
Returns tuple, where the second value is the "exponent-of-10" and the first
value is `value` divided by the "exponent-of-10".
Args
----
value : int, float
Input v... | si_prefix/__init__.py | def split(value, precision=1):
'''
Split `value` into value and "exponent-of-10", where "exponent-of-10" is a
multiple of 3. This corresponds to SI prefixes.
Returns tuple, where the second value is the "exponent-of-10" and the first
value is `value` divided by the "exponent-of-10".
Args
... | def split(value, precision=1):
'''
Split `value` into value and "exponent-of-10", where "exponent-of-10" is a
multiple of 3. This corresponds to SI prefixes.
Returns tuple, where the second value is the "exponent-of-10" and the first
value is `value` divided by the "exponent-of-10".
Args
... | [
"Split",
"value",
"into",
"value",
"and",
"exponent",
"-",
"of",
"-",
"10",
"where",
"exponent",
"-",
"of",
"-",
"10",
"is",
"a",
"multiple",
"of",
"3",
".",
"This",
"corresponds",
"to",
"SI",
"prefixes",
"."
] | cfobel/si-prefix | python | https://github.com/cfobel/si-prefix/blob/274fdf47f65d87d0b7a2e3c80f267db63d042c59/si_prefix/__init__.py#L47-L106 | [
"def",
"split",
"(",
"value",
",",
"precision",
"=",
"1",
")",
":",
"negative",
"=",
"False",
"digits",
"=",
"precision",
"+",
"1",
"if",
"value",
"<",
"0.",
":",
"value",
"=",
"-",
"value",
"negative",
"=",
"True",
"elif",
"value",
"==",
"0.",
":"... | 274fdf47f65d87d0b7a2e3c80f267db63d042c59 |
train | prefix | Args:
expof10 : Exponent of a power of 10 associated with a SI unit
character.
Returns:
str : One of the characters in "yzafpnum kMGTPEZY". | si_prefix/__init__.py | def prefix(expof10):
'''
Args:
expof10 : Exponent of a power of 10 associated with a SI unit
character.
Returns:
str : One of the characters in "yzafpnum kMGTPEZY".
'''
prefix_levels = (len(SI_PREFIX_UNITS) - 1) // 2
si_level = expof10 // 3
if abs(si_level) > ... | def prefix(expof10):
'''
Args:
expof10 : Exponent of a power of 10 associated with a SI unit
character.
Returns:
str : One of the characters in "yzafpnum kMGTPEZY".
'''
prefix_levels = (len(SI_PREFIX_UNITS) - 1) // 2
si_level = expof10 // 3
if abs(si_level) > ... | [
"Args",
":"
] | cfobel/si-prefix | python | https://github.com/cfobel/si-prefix/blob/274fdf47f65d87d0b7a2e3c80f267db63d042c59/si_prefix/__init__.py#L109-L125 | [
"def",
"prefix",
"(",
"expof10",
")",
":",
"prefix_levels",
"=",
"(",
"len",
"(",
"SI_PREFIX_UNITS",
")",
"-",
"1",
")",
"//",
"2",
"si_level",
"=",
"expof10",
"//",
"3",
"if",
"abs",
"(",
"si_level",
")",
">",
"prefix_levels",
":",
"raise",
"ValueErro... | 274fdf47f65d87d0b7a2e3c80f267db63d042c59 |
train | si_format | Format value to string with SI prefix, using the specified precision.
Parameters
----------
value : int, float
Input value.
precision : int
Number of digits after decimal place to include.
format_str : str or unicode
Format string where ``{prefix}`` and ``{value}`` represent... | si_prefix/__init__.py | def si_format(value, precision=1, format_str=u'{value} {prefix}',
exp_format_str=u'{value}e{expof10}'):
'''
Format value to string with SI prefix, using the specified precision.
Parameters
----------
value : int, float
Input value.
precision : int
Number of digits ... | def si_format(value, precision=1, format_str=u'{value} {prefix}',
exp_format_str=u'{value}e{expof10}'):
'''
Format value to string with SI prefix, using the specified precision.
Parameters
----------
value : int, float
Input value.
precision : int
Number of digits ... | [
"Format",
"value",
"to",
"string",
"with",
"SI",
"prefix",
"using",
"the",
"specified",
"precision",
"."
] | cfobel/si-prefix | python | https://github.com/cfobel/si-prefix/blob/274fdf47f65d87d0b7a2e3c80f267db63d042c59/si_prefix/__init__.py#L128-L221 | [
"def",
"si_format",
"(",
"value",
",",
"precision",
"=",
"1",
",",
"format_str",
"=",
"u'{value} {prefix}'",
",",
"exp_format_str",
"=",
"u'{value}e{expof10}'",
")",
":",
"svalue",
",",
"expof10",
"=",
"split",
"(",
"value",
",",
"precision",
")",
"value_forma... | 274fdf47f65d87d0b7a2e3c80f267db63d042c59 |
train | si_parse | Parse a value expressed using SI prefix units to a floating point number.
Parameters
----------
value : str or unicode
Value expressed using SI prefix units (as returned by :func:`si_format`
function).
.. versionchanged:: 1.0
Use unicode string for SI unit to support micro (i.... | si_prefix/__init__.py | def si_parse(value):
'''
Parse a value expressed using SI prefix units to a floating point number.
Parameters
----------
value : str or unicode
Value expressed using SI prefix units (as returned by :func:`si_format`
function).
.. versionchanged:: 1.0
Use unicode string... | def si_parse(value):
'''
Parse a value expressed using SI prefix units to a floating point number.
Parameters
----------
value : str or unicode
Value expressed using SI prefix units (as returned by :func:`si_format`
function).
.. versionchanged:: 1.0
Use unicode string... | [
"Parse",
"a",
"value",
"expressed",
"using",
"SI",
"prefix",
"units",
"to",
"a",
"floating",
"point",
"number",
"."
] | cfobel/si-prefix | python | https://github.com/cfobel/si-prefix/blob/274fdf47f65d87d0b7a2e3c80f267db63d042c59/si_prefix/__init__.py#L224-L263 | [
"def",
"si_parse",
"(",
"value",
")",
":",
"CRE_10E_NUMBER",
"=",
"re",
".",
"compile",
"(",
"r'^\\s*(?P<integer>[\\+\\-]?\\d+)?'",
"r'(?P<fraction>.\\d+)?\\s*([eE]\\s*'",
"r'(?P<expof10>[\\+\\-]?\\d+))?$'",
")",
"CRE_SI_NUMBER",
"=",
"re",
".",
"compile",
"(",
"r'^\\s*(?... | 274fdf47f65d87d0b7a2e3c80f267db63d042c59 |
train | ExternalApi.set_status | Set sensor ``name`` status to ``status``. | src/automate/extensions/rpc/rpc.py | def set_status(self, name, status):
"""
Set sensor ``name`` status to ``status``.
"""
getattr(self.system, name).status = status
return True | def set_status(self, name, status):
"""
Set sensor ``name`` status to ``status``.
"""
getattr(self.system, name).status = status
return True | [
"Set",
"sensor",
"name",
"status",
"to",
"status",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/rpc/rpc.py#L31-L36 | [
"def",
"set_status",
"(",
"self",
",",
"name",
",",
"status",
")",
":",
"getattr",
"(",
"self",
".",
"system",
",",
"name",
")",
".",
"status",
"=",
"status",
"return",
"True"
] | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | ExternalApi.set_object_status | Set statuses from a dictionary of format ``{name: status}`` | src/automate/extensions/rpc/rpc.py | def set_object_status(self, statusdict):
"""
Set statuses from a dictionary of format ``{name: status}``
"""
for name, value in statusdict.items():
getattr(self.system, name).status = value
return True | def set_object_status(self, statusdict):
"""
Set statuses from a dictionary of format ``{name: status}``
"""
for name, value in statusdict.items():
getattr(self.system, name).status = value
return True | [
"Set",
"statuses",
"from",
"a",
"dictionary",
"of",
"format",
"{",
"name",
":",
"status",
"}"
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/rpc/rpc.py#L44-L50 | [
"def",
"set_object_status",
"(",
"self",
",",
"statusdict",
")",
":",
"for",
"name",
",",
"value",
"in",
"statusdict",
".",
"items",
"(",
")",
":",
"getattr",
"(",
"self",
".",
"system",
",",
"name",
")",
".",
"status",
"=",
"value",
"return",
"True"
] | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | ExternalApi.toggle_object_status | Toggle boolean-valued sensor status between ``True`` and ``False``. | src/automate/extensions/rpc/rpc.py | def toggle_object_status(self, objname):
"""
Toggle boolean-valued sensor status between ``True`` and ``False``.
"""
o = getattr(self.system, objname)
o.status = not o.status
self.system.flush()
return o.status | def toggle_object_status(self, objname):
"""
Toggle boolean-valued sensor status between ``True`` and ``False``.
"""
o = getattr(self.system, objname)
o.status = not o.status
self.system.flush()
return o.status | [
"Toggle",
"boolean",
"-",
"valued",
"sensor",
"status",
"between",
"True",
"and",
"False",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/rpc/rpc.py#L52-L59 | [
"def",
"toggle_object_status",
"(",
"self",
",",
"objname",
")",
":",
"o",
"=",
"getattr",
"(",
"self",
".",
"system",
",",
"objname",
")",
"o",
".",
"status",
"=",
"not",
"o",
".",
"status",
"self",
".",
"system",
".",
"flush",
"(",
")",
"return",
... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | ExternalApi.get_sensors | Get sensors as a dictionary of format ``{name: status}`` | src/automate/extensions/rpc/rpc.py | def get_sensors(self):
"""
Get sensors as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.sensors} | def get_sensors(self):
"""
Get sensors as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.sensors} | [
"Get",
"sensors",
"as",
"a",
"dictionary",
"of",
"format",
"{",
"name",
":",
"status",
"}"
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/rpc/rpc.py#L61-L65 | [
"def",
"get_sensors",
"(",
"self",
")",
":",
"return",
"{",
"i",
".",
"name",
":",
"i",
".",
"status",
"for",
"i",
"in",
"self",
".",
"system",
".",
"sensors",
"}"
] | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | ExternalApi.get_websensors | Get sensors with defined tag as a dictionary of format ``{name: status}`` | src/automate/extensions/rpc/rpc.py | def get_websensors(self):
"""
Get sensors with defined tag as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.sensors if self.tag & i.tags} | def get_websensors(self):
"""
Get sensors with defined tag as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.sensors if self.tag & i.tags} | [
"Get",
"sensors",
"with",
"defined",
"tag",
"as",
"a",
"dictionary",
"of",
"format",
"{",
"name",
":",
"status",
"}"
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/rpc/rpc.py#L67-L71 | [
"def",
"get_websensors",
"(",
"self",
")",
":",
"return",
"{",
"i",
".",
"name",
":",
"i",
".",
"status",
"for",
"i",
"in",
"self",
".",
"system",
".",
"sensors",
"if",
"self",
".",
"tag",
"&",
"i",
".",
"tags",
"}"
] | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | ExternalApi.get_actuators | Get actuators as a dictionary of format ``{name: status}`` | src/automate/extensions/rpc/rpc.py | def get_actuators(self):
"""
Get actuators as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.actuators} | def get_actuators(self):
"""
Get actuators as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.actuators} | [
"Get",
"actuators",
"as",
"a",
"dictionary",
"of",
"format",
"{",
"name",
":",
"status",
"}"
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/rpc/rpc.py#L73-L77 | [
"def",
"get_actuators",
"(",
"self",
")",
":",
"return",
"{",
"i",
".",
"name",
":",
"i",
".",
"status",
"for",
"i",
"in",
"self",
".",
"system",
".",
"actuators",
"}"
] | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | ExternalApi.log | Return recent log entries as a string. | src/automate/extensions/rpc/rpc.py | def log(self):
"""
Return recent log entries as a string.
"""
logserv = self.system.request_service('LogStoreService')
return logserv.lastlog(html=False) | def log(self):
"""
Return recent log entries as a string.
"""
logserv = self.system.request_service('LogStoreService')
return logserv.lastlog(html=False) | [
"Return",
"recent",
"log",
"entries",
"as",
"a",
"string",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/rpc/rpc.py#L93-L98 | [
"def",
"log",
"(",
"self",
")",
":",
"logserv",
"=",
"self",
".",
"system",
".",
"request_service",
"(",
"'LogStoreService'",
")",
"return",
"logserv",
".",
"lastlog",
"(",
"html",
"=",
"False",
")"
] | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | cmd_tariffs | Посмотреть список тарифов. | rock_cli/cli/tariffs.py | def cmd_tariffs():
"""
Посмотреть список тарифов.
"""
r = rocket.tariffs.get()
r = handle_error(r)
for tariff in r.json():
click.echo("- {name} <{url}>".format(
name=click.style(tariff["name"], fg="green", bold=True),
url=tariff["url"])) | def cmd_tariffs():
"""
Посмотреть список тарифов.
"""
r = rocket.tariffs.get()
r = handle_error(r)
for tariff in r.json():
click.echo("- {name} <{url}>".format(
name=click.style(tariff["name"], fg="green", bold=True),
url=tariff["url"])) | [
"Посмотреть",
"список",
"тарифов",
"."
] | notpushkin/rock | python | https://github.com/notpushkin/rock/blob/c1451a7604b462c19e4929f0eb171cbcf23e50ab/rock_cli/cli/tariffs.py#L6-L16 | [
"def",
"cmd_tariffs",
"(",
")",
":",
"r",
"=",
"rocket",
".",
"tariffs",
".",
"get",
"(",
")",
"r",
"=",
"handle_error",
"(",
"r",
")",
"for",
"tariff",
"in",
"r",
".",
"json",
"(",
")",
":",
"click",
".",
"echo",
"(",
"\"- {name} <{url}>\"",
".",
... | c1451a7604b462c19e4929f0eb171cbcf23e50ab |
train | System.load_or_create | Load system from a dump, if dump file exists, or create a new system if it does not exist. | src/automate/system.py | def load_or_create(cls, filename=None, no_input=False, create_new=False, **kwargs):
"""
Load system from a dump, if dump file exists, or create a new system if it does not exist.
"""
parser = argparse.ArgumentParser()
parser.add_argument('--no_input', action='store_true')
... | def load_or_create(cls, filename=None, no_input=False, create_new=False, **kwargs):
"""
Load system from a dump, if dump file exists, or create a new system if it does not exist.
"""
parser = argparse.ArgumentParser()
parser.add_argument('--no_input', action='store_true')
... | [
"Load",
"system",
"from",
"a",
"dump",
"if",
"dump",
"file",
"exists",
"or",
"create",
"a",
"new",
"system",
"if",
"it",
"does",
"not",
"exist",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L200-L261 | [
"def",
"load_or_create",
"(",
"cls",
",",
"filename",
"=",
"None",
",",
"no_input",
"=",
"False",
",",
"create_new",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | System.save_state | Save state of the system to a dump file :attr:`System.filename` | src/automate/system.py | def save_state(self):
"""
Save state of the system to a dump file :attr:`System.filename`
"""
if not self.filename:
self.logger.error('Filename not specified. Could not save state')
return
self.logger.debug('Saving system state to %s', self.filename)
... | def save_state(self):
"""
Save state of the system to a dump file :attr:`System.filename`
"""
if not self.filename:
self.logger.error('Filename not specified. Could not save state')
return
self.logger.debug('Saving system state to %s', self.filename)
... | [
"Save",
"state",
"of",
"the",
"system",
"to",
"a",
"dump",
"file",
":",
"attr",
":",
"System",
".",
"filename"
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L263-L284 | [
"def",
"save_state",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"filename",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'Filename not specified. Could not save state'",
")",
"return",
"self",
".",
"logger",
".",
"debug",
"(",
"'Saving system state to %... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | System.cmd_namespace | A read-only property that gives the namespace of the system for evaluating commands. | src/automate/system.py | def cmd_namespace(self):
"""
A read-only property that gives the namespace of the system for evaluating commands.
"""
import automate
ns = dict(list(automate.__dict__.items()) + list(self.namespace.items()))
return ns | def cmd_namespace(self):
"""
A read-only property that gives the namespace of the system for evaluating commands.
"""
import automate
ns = dict(list(automate.__dict__.items()) + list(self.namespace.items()))
return ns | [
"A",
"read",
"-",
"only",
"property",
"that",
"gives",
"the",
"namespace",
"of",
"the",
"system",
"for",
"evaluating",
"commands",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L287-L293 | [
"def",
"cmd_namespace",
"(",
"self",
")",
":",
"import",
"automate",
"ns",
"=",
"dict",
"(",
"list",
"(",
"automate",
".",
"__dict__",
".",
"items",
"(",
")",
")",
"+",
"list",
"(",
"self",
".",
"namespace",
".",
"items",
"(",
")",
")",
")",
"retur... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | System.get_unique_name | Give unique name for an Sensor/Program/Actuator object | src/automate/system.py | def get_unique_name(self, obj, name='', name_from_system=''):
"""
Give unique name for an Sensor/Program/Actuator object
"""
ns = self.namespace
newname = name
if not newname:
newname = name_from_system
if not newname:
newname = u"Name... | def get_unique_name(self, obj, name='', name_from_system=''):
"""
Give unique name for an Sensor/Program/Actuator object
"""
ns = self.namespace
newname = name
if not newname:
newname = name_from_system
if not newname:
newname = u"Name... | [
"Give",
"unique",
"name",
"for",
"an",
"Sensor",
"/",
"Program",
"/",
"Actuator",
"object"
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L300-L320 | [
"def",
"get_unique_name",
"(",
"self",
",",
"obj",
",",
"name",
"=",
"''",
",",
"name_from_system",
"=",
"''",
")",
":",
"ns",
"=",
"self",
".",
"namespace",
"newname",
"=",
"name",
"if",
"not",
"newname",
":",
"newname",
"=",
"name_from_system",
"if",
... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | System.services_by_name | A property that gives a dictionary that contains services as values and their names as keys. | src/automate/system.py | def services_by_name(self):
"""
A property that gives a dictionary that contains services as values and their names as keys.
"""
srvs = defaultdict(list)
for i in self.services:
srvs[i.__class__.__name__].append(i)
return srvs | def services_by_name(self):
"""
A property that gives a dictionary that contains services as values and their names as keys.
"""
srvs = defaultdict(list)
for i in self.services:
srvs[i.__class__.__name__].append(i)
return srvs | [
"A",
"property",
"that",
"gives",
"a",
"dictionary",
"that",
"contains",
"services",
"as",
"values",
"and",
"their",
"names",
"as",
"keys",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L323-L330 | [
"def",
"services_by_name",
"(",
"self",
")",
":",
"srvs",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"i",
"in",
"self",
".",
"services",
":",
"srvs",
"[",
"i",
".",
"__class__",
".",
"__name__",
"]",
".",
"append",
"(",
"i",
")",
"return",
"srvs"
] | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | System.name_to_system_object | Give SystemObject instance corresponding to the name | src/automate/system.py | def name_to_system_object(self, name):
"""
Give SystemObject instance corresponding to the name
"""
if isinstance(name, str):
if self.allow_name_referencing:
name = name
else:
raise NameError('System.allow_name_referencing is se... | def name_to_system_object(self, name):
"""
Give SystemObject instance corresponding to the name
"""
if isinstance(name, str):
if self.allow_name_referencing:
name = name
else:
raise NameError('System.allow_name_referencing is se... | [
"Give",
"SystemObject",
"instance",
"corresponding",
"to",
"the",
"name"
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L345-L356 | [
"def",
"name_to_system_object",
"(",
"self",
",",
"name",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"if",
"self",
".",
"allow_name_referencing",
":",
"name",
"=",
"name",
"else",
":",
"raise",
"NameError",
"(",
"'System.allow_name_refe... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | System.eval_in_system_namespace | Get Callable for specified string (for GUI-based editing) | src/automate/system.py | def eval_in_system_namespace(self, exec_str):
"""
Get Callable for specified string (for GUI-based editing)
"""
ns = self.cmd_namespace
try:
return eval(exec_str, ns)
except Exception as e:
self.logger.warning('Could not execute %s, gave error ... | def eval_in_system_namespace(self, exec_str):
"""
Get Callable for specified string (for GUI-based editing)
"""
ns = self.cmd_namespace
try:
return eval(exec_str, ns)
except Exception as e:
self.logger.warning('Could not execute %s, gave error ... | [
"Get",
"Callable",
"for",
"specified",
"string",
"(",
"for",
"GUI",
"-",
"based",
"editing",
")"
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L358-L367 | [
"def",
"eval_in_system_namespace",
"(",
"self",
",",
"exec_str",
")",
":",
"ns",
"=",
"self",
".",
"cmd_namespace",
"try",
":",
"return",
"eval",
"(",
"exec_str",
",",
"ns",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | System.register_service_functions | Register function in the system namespace. Called by Services. | src/automate/system.py | def register_service_functions(self, *funcs):
"""
Register function in the system namespace. Called by Services.
"""
for func in funcs:
self.namespace[func.__name__] = func | def register_service_functions(self, *funcs):
"""
Register function in the system namespace. Called by Services.
"""
for func in funcs:
self.namespace[func.__name__] = func | [
"Register",
"function",
"in",
"the",
"system",
"namespace",
".",
"Called",
"by",
"Services",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L369-L374 | [
"def",
"register_service_functions",
"(",
"self",
",",
"*",
"funcs",
")",
":",
"for",
"func",
"in",
"funcs",
":",
"self",
".",
"namespace",
"[",
"func",
".",
"__name__",
"]",
"=",
"func"
] | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | System.register_service | Register service into the system. Called by Services. | src/automate/system.py | def register_service(self, service):
"""
Register service into the system. Called by Services.
"""
if service not in self.services:
self.services.append(service) | def register_service(self, service):
"""
Register service into the system. Called by Services.
"""
if service not in self.services:
self.services.append(service) | [
"Register",
"service",
"into",
"the",
"system",
".",
"Called",
"by",
"Services",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L376-L381 | [
"def",
"register_service",
"(",
"self",
",",
"service",
")",
":",
"if",
"service",
"not",
"in",
"self",
".",
"services",
":",
"self",
".",
"services",
".",
"append",
"(",
"service",
")"
] | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | System.request_service | Used by Sensors/Actuators/other services that need to use other services for their
operations. | src/automate/system.py | def request_service(self, type, id=0):
"""
Used by Sensors/Actuators/other services that need to use other services for their
operations.
"""
srvs = self.services_by_name.get(type)
if not srvs:
return
ser = srvs[id]
if not ser.system:... | def request_service(self, type, id=0):
"""
Used by Sensors/Actuators/other services that need to use other services for their
operations.
"""
srvs = self.services_by_name.get(type)
if not srvs:
return
ser = srvs[id]
if not ser.system:... | [
"Used",
"by",
"Sensors",
"/",
"Actuators",
"/",
"other",
"services",
"that",
"need",
"to",
"use",
"other",
"services",
"for",
"their",
"operations",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L383-L396 | [
"def",
"request_service",
"(",
"self",
",",
"type",
",",
"id",
"=",
"0",
")",
":",
"srvs",
"=",
"self",
".",
"services_by_name",
".",
"get",
"(",
"type",
")",
"if",
"not",
"srvs",
":",
"return",
"ser",
"=",
"srvs",
"[",
"id",
"]",
"if",
"not",
"s... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | System.cleanup | Clean up before quitting | src/automate/system.py | def cleanup(self):
"""
Clean up before quitting
"""
self.pre_exit_trigger = True
self.logger.info("Shutting down %s, please wait a moment.", self.name)
for t in threading.enumerate():
if isinstance(t, TimerClass):
t.cancel()
self.... | def cleanup(self):
"""
Clean up before quitting
"""
self.pre_exit_trigger = True
self.logger.info("Shutting down %s, please wait a moment.", self.name)
for t in threading.enumerate():
if isinstance(t, TimerClass):
t.cancel()
self.... | [
"Clean",
"up",
"before",
"quitting"
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L398-L429 | [
"def",
"cleanup",
"(",
"self",
")",
":",
"self",
".",
"pre_exit_trigger",
"=",
"True",
"self",
".",
"logger",
".",
"info",
"(",
"\"Shutting down %s, please wait a moment.\"",
",",
"self",
".",
"name",
")",
"for",
"t",
"in",
"threading",
".",
"enumerate",
"("... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | System.cmd_exec | Execute commands in automate namespace | src/automate/system.py | def cmd_exec(self, cmd):
"""
Execute commands in automate namespace
"""
if not cmd:
return
ns = self.cmd_namespace
import copy
rval = True
nscopy = copy.copy(ns)
try:
r = eval(cmd, ns)
if isinstance(r, Syste... | def cmd_exec(self, cmd):
"""
Execute commands in automate namespace
"""
if not cmd:
return
ns = self.cmd_namespace
import copy
rval = True
nscopy = copy.copy(ns)
try:
r = eval(cmd, ns)
if isinstance(r, Syste... | [
"Execute",
"commands",
"in",
"automate",
"namespace"
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/system.py#L431-L474 | [
"def",
"cmd_exec",
"(",
"self",
",",
"cmd",
")",
":",
"if",
"not",
"cmd",
":",
"return",
"ns",
"=",
"self",
".",
"cmd_namespace",
"import",
"copy",
"rval",
"=",
"True",
"nscopy",
"=",
"copy",
".",
"copy",
"(",
"ns",
")",
"try",
":",
"r",
"=",
"ev... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | handle_parser | This function parses in values from command line, allowing for user control from the system terminal. | pymoresane/parser.py | def handle_parser():
"""
This function parses in values from command line, allowing for user control from the system terminal.
"""
parser = argparse.ArgumentParser(description="Runs the pymoresane deconvolution algorithm with the specified "
"arguments. I... | def handle_parser():
"""
This function parses in values from command line, allowing for user control from the system terminal.
"""
parser = argparse.ArgumentParser(description="Runs the pymoresane deconvolution algorithm with the specified "
"arguments. I... | [
"This",
"function",
"parses",
"in",
"values",
"from",
"command",
"line",
"allowing",
"for",
"user",
"control",
"from",
"the",
"system",
"terminal",
"."
] | ratt-ru/PyMORESANE | python | https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/parser.py#L4-L125 | [
"def",
"handle_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Runs the pymoresane deconvolution algorithm with the specified \"",
"\"arguments. In the event that non-critical parameters are missing, \"",
"\"the defaults will be use... | b024591ad0bbb69320d08841f28a2c27f62ae1af |
train | PlantUMLService.write_puml | Writes PUML from the system. If filename is given, stores result in the file.
Otherwise returns result as a string. | src/automate/services/plantumlserv.py | def write_puml(self, filename=''):
"""
Writes PUML from the system. If filename is given, stores result in the file.
Otherwise returns result as a string.
"""
def get_type(o):
type = 'program'
if isinstance(o, AbstractSensor):
type ... | def write_puml(self, filename=''):
"""
Writes PUML from the system. If filename is given, stores result in the file.
Otherwise returns result as a string.
"""
def get_type(o):
type = 'program'
if isinstance(o, AbstractSensor):
type ... | [
"Writes",
"PUML",
"from",
"the",
"system",
".",
"If",
"filename",
"is",
"given",
"stores",
"result",
"in",
"the",
"file",
".",
"Otherwise",
"returns",
"result",
"as",
"a",
"string",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/services/plantumlserv.py#L54-L112 | [
"def",
"write_puml",
"(",
"self",
",",
"filename",
"=",
"''",
")",
":",
"def",
"get_type",
"(",
"o",
")",
":",
"type",
"=",
"'program'",
"if",
"isinstance",
"(",
"o",
",",
"AbstractSensor",
")",
":",
"type",
"=",
"'sensor'",
"elif",
"isinstance",
"(",
... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | PlantUMLService.write_svg | Returns PUML from the system as a SVG image. Requires plantuml library. | src/automate/services/plantumlserv.py | def write_svg(self):
"""
Returns PUML from the system as a SVG image. Requires plantuml library.
"""
import plantuml
puml = self.write_puml()
server = plantuml.PlantUML(url=self.url)
svg = server.processes(puml)
return svg | def write_svg(self):
"""
Returns PUML from the system as a SVG image. Requires plantuml library.
"""
import plantuml
puml = self.write_puml()
server = plantuml.PlantUML(url=self.url)
svg = server.processes(puml)
return svg | [
"Returns",
"PUML",
"from",
"the",
"system",
"as",
"a",
"SVG",
"image",
".",
"Requires",
"plantuml",
"library",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/services/plantumlserv.py#L114-L122 | [
"def",
"write_svg",
"(",
"self",
")",
":",
"import",
"plantuml",
"puml",
"=",
"self",
".",
"write_puml",
"(",
")",
"server",
"=",
"plantuml",
".",
"PlantUML",
"(",
"url",
"=",
"self",
".",
"url",
")",
"svg",
"=",
"server",
".",
"processes",
"(",
"pum... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | median_kneighbour_distance | Calculate the median kneighbor distance.
Find the distance between a set of random datapoints and
their kth nearest neighbours. This is a heuristic for setting the
kernel length scale. | lsanomaly/__init__.py | def median_kneighbour_distance(X, k=5):
"""
Calculate the median kneighbor distance.
Find the distance between a set of random datapoints and
their kth nearest neighbours. This is a heuristic for setting the
kernel length scale.
"""
N_all = X.shape[0]
k = min(k, N_all)
N_subset = mi... | def median_kneighbour_distance(X, k=5):
"""
Calculate the median kneighbor distance.
Find the distance between a set of random datapoints and
their kth nearest neighbours. This is a heuristic for setting the
kernel length scale.
"""
N_all = X.shape[0]
k = min(k, N_all)
N_subset = mi... | [
"Calculate",
"the",
"median",
"kneighbor",
"distance",
"."
] | lsanomaly/lsanomaly | python | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L12-L27 | [
"def",
"median_kneighbour_distance",
"(",
"X",
",",
"k",
"=",
"5",
")",
":",
"N_all",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"k",
"=",
"min",
"(",
"k",
",",
"N_all",
")",
"N_subset",
"=",
"min",
"(",
"N_all",
",",
"2000",
")",
"sample_idx_train",
... | 7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e |
train | pair_distance_centile | Calculate centiles of distances between random pairs in a dataset.
This an alternative to the median kNN distance for setting the kernel
length scale. | lsanomaly/__init__.py | def pair_distance_centile(X, centile, max_pairs=5000):
"""
Calculate centiles of distances between random pairs in a dataset.
This an alternative to the median kNN distance for setting the kernel
length scale.
"""
N = X.shape[0]
n_pairs = min(max_pairs, N**2)
# randorder1 = np.random.pe... | def pair_distance_centile(X, centile, max_pairs=5000):
"""
Calculate centiles of distances between random pairs in a dataset.
This an alternative to the median kNN distance for setting the kernel
length scale.
"""
N = X.shape[0]
n_pairs = min(max_pairs, N**2)
# randorder1 = np.random.pe... | [
"Calculate",
"centiles",
"of",
"distances",
"between",
"random",
"pairs",
"in",
"a",
"dataset",
"."
] | lsanomaly/lsanomaly | python | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L30-L51 | [
"def",
"pair_distance_centile",
"(",
"X",
",",
"centile",
",",
"max_pairs",
"=",
"5000",
")",
":",
"N",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"n_pairs",
"=",
"min",
"(",
"max_pairs",
",",
"N",
"**",
"2",
")",
"# randorder1 = np.random.permutation(N)",
"... | 7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e |
train | LSAnomaly.fit | Fit the inlier model given training data.
This function attempts to choose reasonable defaults for parameters
sigma and rho if none are specified, which could then be adjusted
to improve performance.
Parameters
----------
X : array
Examples of inlier data, o... | lsanomaly/__init__.py | def fit(self, X, y=None):
"""
Fit the inlier model given training data.
This function attempts to choose reasonable defaults for parameters
sigma and rho if none are specified, which could then be adjusted
to improve performance.
Parameters
----------
X ... | def fit(self, X, y=None):
"""
Fit the inlier model given training data.
This function attempts to choose reasonable defaults for parameters
sigma and rho if none are specified, which could then be adjusted
to improve performance.
Parameters
----------
X ... | [
"Fit",
"the",
"inlier",
"model",
"given",
"training",
"data",
"."
] | lsanomaly/lsanomaly | python | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L108-L164 | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"N",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"if",
"y",
"is",
"None",
":",
"y",
"=",
"np",
".",
"zeros",
"(",
"N",
")",
"self",
".",
"classes",
"=",
"list",
"(",
"set",
... | 7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e |
train | LSAnomaly.predict | Assign classes to test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns
-------
y_predicted : array
A vector of length N containing assigned classes. If n... | lsanomaly/__init__.py | def predict(self, X):
"""
Assign classes to test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns
-------
y_predicted : array
A vector of ... | def predict(self, X):
"""
Assign classes to test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns
-------
y_predicted : array
A vector of ... | [
"Assign",
"classes",
"to",
"test",
"data",
"."
] | lsanomaly/lsanomaly | python | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L166-L192 | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"predictions_proba",
"=",
"self",
".",
"predict_proba",
"(",
"X",
")",
"predictions",
"=",
"[",
"]",
"allclasses",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"classes",
")",
"allclasses",
".",
"append... | 7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e |
train | LSAnomaly.predict_proba | Calculate posterior probabilities of test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns:
-------
y_prob : array
An array of dimension N times n_inlier_... | lsanomaly/__init__.py | def predict_proba(self, X):
"""
Calculate posterior probabilities of test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns:
-------
y_prob : array
... | def predict_proba(self, X):
"""
Calculate posterior probabilities of test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns:
-------
y_prob : array
... | [
"Calculate",
"posterior",
"probabilities",
"of",
"test",
"data",
"."
] | lsanomaly/lsanomaly | python | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L194-L223 | [
"def",
"predict_proba",
"(",
"self",
",",
"X",
")",
":",
"Phi",
"=",
"metrics",
".",
"pairwise",
".",
"rbf_kernel",
"(",
"X",
",",
"self",
".",
"kernel_pos",
",",
"self",
".",
"gamma",
")",
"N",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"predictions",... | 7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e |
train | LSAnomaly.decision_function | Generate an inlier score for each test data example.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns:
-------
scores : array
A vector of length N, where each e... | lsanomaly/__init__.py | def decision_function(self, X):
"""
Generate an inlier score for each test data example.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns:
-------
scores : ... | def decision_function(self, X):
"""
Generate an inlier score for each test data example.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns:
-------
scores : ... | [
"Generate",
"an",
"inlier",
"score",
"for",
"each",
"test",
"data",
"example",
"."
] | lsanomaly/lsanomaly | python | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L225-L245 | [
"def",
"decision_function",
"(",
"self",
",",
"X",
")",
":",
"predictions",
"=",
"self",
".",
"predict_proba",
"(",
"X",
")",
"out",
"=",
"np",
".",
"zeros",
"(",
"(",
"predictions",
".",
"shape",
"[",
"0",
"]",
",",
"1",
")",
")",
"out",
"[",
":... | 7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e |
train | LSAnomaly.score | Calculate accuracy score.
Needed because of bug in metrics.accuracy_score when comparing
list with numpy array. | lsanomaly/__init__.py | def score(self, X, y):
"""
Calculate accuracy score.
Needed because of bug in metrics.accuracy_score when comparing
list with numpy array.
"""
predictions = self.predict(X)
true = 0.0
total = 0.0
for i in range(len(predictions)):
total... | def score(self, X, y):
"""
Calculate accuracy score.
Needed because of bug in metrics.accuracy_score when comparing
list with numpy array.
"""
predictions = self.predict(X)
true = 0.0
total = 0.0
for i in range(len(predictions)):
total... | [
"Calculate",
"accuracy",
"score",
"."
] | lsanomaly/lsanomaly | python | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L247-L261 | [
"def",
"score",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"predictions",
"=",
"self",
".",
"predict",
"(",
"X",
")",
"true",
"=",
"0.0",
"total",
"=",
"0.0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"predictions",
")",
")",
":",
"total",
"+... | 7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e |
train | LSAnomaly.predict_sequence | Calculate class probabilities for a sequence of data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are time frames, columns
are data dimensions)
A : class transition matrix, where A[i,j] contains p(y_t=j|y_{t-1}=i)
pi : vector o... | lsanomaly/__init__.py | def predict_sequence(self, X, A, pi, inference='smoothing'):
"""
Calculate class probabilities for a sequence of data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are time frames, columns
are data dimensions)
A : class ... | def predict_sequence(self, X, A, pi, inference='smoothing'):
"""
Calculate class probabilities for a sequence of data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are time frames, columns
are data dimensions)
A : class ... | [
"Calculate",
"class",
"probabilities",
"for",
"a",
"sequence",
"of",
"data",
"."
] | lsanomaly/lsanomaly | python | https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L263-L310 | [
"def",
"predict_sequence",
"(",
"self",
",",
"X",
",",
"A",
",",
"pi",
",",
"inference",
"=",
"'smoothing'",
")",
":",
"obsll",
"=",
"self",
".",
"predict_proba",
"(",
"X",
")",
"T",
",",
"S",
"=",
"obsll",
".",
"shape",
"alpha",
"=",
"np",
".",
... | 7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e |
train | toggle_sensor | This is used only if websocket fails | src/automate/extensions/webui/djangoapp/views.py | def toggle_sensor(request, sensorname):
"""
This is used only if websocket fails
"""
if service.read_only:
service.logger.warning("Could not perform operation: read only mode enabled")
raise Http404
source = request.GET.get('source', 'main')
sensor = service.system.namespace[sens... | def toggle_sensor(request, sensorname):
"""
This is used only if websocket fails
"""
if service.read_only:
service.logger.warning("Could not perform operation: read only mode enabled")
raise Http404
source = request.GET.get('source', 'main')
sensor = service.system.namespace[sens... | [
"This",
"is",
"used",
"only",
"if",
"websocket",
"fails"
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/webui/djangoapp/views.py#L279-L290 | [
"def",
"toggle_sensor",
"(",
"request",
",",
"sensorname",
")",
":",
"if",
"service",
".",
"read_only",
":",
"service",
".",
"logger",
".",
"warning",
"(",
"\"Could not perform operation: read only mode enabled\"",
")",
"raise",
"Http404",
"source",
"=",
"request",
... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | toggle_value | For manual shortcut links to perform toggle actions | src/automate/extensions/webui/djangoapp/views.py | def toggle_value(request, name):
"""
For manual shortcut links to perform toggle actions
"""
obj = service.system.namespace.get(name, None)
if not obj or service.read_only:
raise Http404
new_status = obj.status = not obj.status
if service.redirect_from_setters:
return HttpRes... | def toggle_value(request, name):
"""
For manual shortcut links to perform toggle actions
"""
obj = service.system.namespace.get(name, None)
if not obj or service.read_only:
raise Http404
new_status = obj.status = not obj.status
if service.redirect_from_setters:
return HttpRes... | [
"For",
"manual",
"shortcut",
"links",
"to",
"perform",
"toggle",
"actions"
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/webui/djangoapp/views.py#L294-L305 | [
"def",
"toggle_value",
"(",
"request",
",",
"name",
")",
":",
"obj",
"=",
"service",
".",
"system",
".",
"namespace",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"not",
"obj",
"or",
"service",
".",
"read_only",
":",
"raise",
"Http404",
"new_status... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | set_value | For manual shortcut links to perform set value actions | src/automate/extensions/webui/djangoapp/views.py | def set_value(request, name, value):
"""
For manual shortcut links to perform set value actions
"""
obj = service.system.namespace.get(name, None)
if not obj or service.read_only:
raise Http404
obj.status = value
if service.redirect_from_setters:
return HttpResponseRedirect(r... | def set_value(request, name, value):
"""
For manual shortcut links to perform set value actions
"""
obj = service.system.namespace.get(name, None)
if not obj or service.read_only:
raise Http404
obj.status = value
if service.redirect_from_setters:
return HttpResponseRedirect(r... | [
"For",
"manual",
"shortcut",
"links",
"to",
"perform",
"set",
"value",
"actions"
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/webui/djangoapp/views.py#L309-L320 | [
"def",
"set_value",
"(",
"request",
",",
"name",
",",
"value",
")",
":",
"obj",
"=",
"service",
".",
"system",
".",
"namespace",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"not",
"obj",
"or",
"service",
".",
"read_only",
":",
"raise",
"Http404"... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | SystemObject.object_type | A read-only property that gives the object type as string; sensor, actuator, program, other.
Used by WEB interface templates. | src/automate/systemobject.py | def object_type(self):
"""
A read-only property that gives the object type as string; sensor, actuator, program, other.
Used by WEB interface templates.
"""
from .statusobject import AbstractSensor, AbstractActuator
from .program import Program
if isinsta... | def object_type(self):
"""
A read-only property that gives the object type as string; sensor, actuator, program, other.
Used by WEB interface templates.
"""
from .statusobject import AbstractSensor, AbstractActuator
from .program import Program
if isinsta... | [
"A",
"read",
"-",
"only",
"property",
"that",
"gives",
"the",
"object",
"type",
"as",
"string",
";",
"sensor",
"actuator",
"program",
"other",
".",
"Used",
"by",
"WEB",
"interface",
"templates",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/systemobject.py#L115-L130 | [
"def",
"object_type",
"(",
"self",
")",
":",
"from",
".",
"statusobject",
"import",
"AbstractSensor",
",",
"AbstractActuator",
"from",
".",
"program",
"import",
"Program",
"if",
"isinstance",
"(",
"self",
",",
"AbstractSensor",
")",
":",
"return",
"'sensor'",
... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | SystemObject.get_as_datadict | Get information about this object as a dictionary. Used by WebSocket interface to pass some
relevant information to client applications. | src/automate/systemobject.py | def get_as_datadict(self):
"""
Get information about this object as a dictionary. Used by WebSocket interface to pass some
relevant information to client applications.
"""
return dict(type=self.__class__.__name__, tags=list(self.tags)) | def get_as_datadict(self):
"""
Get information about this object as a dictionary. Used by WebSocket interface to pass some
relevant information to client applications.
"""
return dict(type=self.__class__.__name__, tags=list(self.tags)) | [
"Get",
"information",
"about",
"this",
"object",
"as",
"a",
"dictionary",
".",
"Used",
"by",
"WebSocket",
"interface",
"to",
"pass",
"some",
"relevant",
"information",
"to",
"client",
"applications",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/systemobject.py#L156-L161 | [
"def",
"get_as_datadict",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"type",
"=",
"self",
".",
"__class__",
".",
"__name__",
",",
"tags",
"=",
"list",
"(",
"self",
".",
"tags",
")",
")"
] | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | SystemObject.setup_system | Set system attribute and do some initialization. Used by System. | src/automate/systemobject.py | def setup_system(self, system, name_from_system='', **kwargs):
"""
Set system attribute and do some initialization. Used by System.
"""
if not self.system:
self.system = system
name, traits = self._passed_arguments
new_name = self.system.get_unique_name(s... | def setup_system(self, system, name_from_system='', **kwargs):
"""
Set system attribute and do some initialization. Used by System.
"""
if not self.system:
self.system = system
name, traits = self._passed_arguments
new_name = self.system.get_unique_name(s... | [
"Set",
"system",
"attribute",
"and",
"do",
"some",
"initialization",
".",
"Used",
"by",
"System",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/systemobject.py#L169-L194 | [
"def",
"setup_system",
"(",
"self",
",",
"system",
",",
"name_from_system",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"system",
":",
"self",
".",
"system",
"=",
"system",
"name",
",",
"traits",
"=",
"self",
".",
"_passed... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | SystemObject.setup_callables | Setup Callable attributes that belong to this object. | src/automate/systemobject.py | def setup_callables(self):
"""
Setup Callable attributes that belong to this object.
"""
defaults = self.get_default_callables()
for key, value in list(defaults.items()):
self._postponed_callables.setdefault(key, value)
for key in self.callables:
... | def setup_callables(self):
"""
Setup Callable attributes that belong to this object.
"""
defaults = self.get_default_callables()
for key, value in list(defaults.items()):
self._postponed_callables.setdefault(key, value)
for key in self.callables:
... | [
"Setup",
"Callable",
"attributes",
"that",
"belong",
"to",
"this",
"object",
"."
] | tuomas2/automate | python | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/systemobject.py#L196-L206 | [
"def",
"setup_callables",
"(",
"self",
")",
":",
"defaults",
"=",
"self",
".",
"get_default_callables",
"(",
")",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"defaults",
".",
"items",
"(",
")",
")",
":",
"self",
".",
"_postponed_callables",
".",
"setd... | d8a8cd03cd0da047e033a2d305f3f260f8c4e017 |
train | grab_keyfile | Function to acqure the keyfile
SNS keys expire and Amazon does not promise they will use the same key
for all SNS requests. So we need to keep a copy of the cert in our
cache | django_bouncy/utils.py | def grab_keyfile(cert_url):
"""
Function to acqure the keyfile
SNS keys expire and Amazon does not promise they will use the same key
for all SNS requests. So we need to keep a copy of the cert in our
cache
"""
key_cache = caches[getattr(settings, 'BOUNCY_KEY_CACHE', 'default')]
pemfil... | def grab_keyfile(cert_url):
"""
Function to acqure the keyfile
SNS keys expire and Amazon does not promise they will use the same key
for all SNS requests. So we need to keep a copy of the cert in our
cache
"""
key_cache = caches[getattr(settings, 'BOUNCY_KEY_CACHE', 'default')]
pemfil... | [
"Function",
"to",
"acqure",
"the",
"keyfile"
] | ofa/django-bouncy | python | https://github.com/ofa/django-bouncy/blob/a386dfa8c4ce59bd18978a3537c03cd6ad07bf06/django_bouncy/utils.py#L67-L91 | [
"def",
"grab_keyfile",
"(",
"cert_url",
")",
":",
"key_cache",
"=",
"caches",
"[",
"getattr",
"(",
"settings",
",",
"'BOUNCY_KEY_CACHE'",
",",
"'default'",
")",
"]",
"pemfile",
"=",
"key_cache",
".",
"get",
"(",
"cert_url",
")",
"if",
"not",
"pemfile",
":"... | a386dfa8c4ce59bd18978a3537c03cd6ad07bf06 |
train | verify_notification | Function to verify notification came from a trusted source
Returns True if verfied, False if not verified | django_bouncy/utils.py | def verify_notification(data):
"""
Function to verify notification came from a trusted source
Returns True if verfied, False if not verified
"""
pemfile = grab_keyfile(data['SigningCertURL'])
cert = crypto.load_certificate(crypto.FILETYPE_PEM, pemfile)
signature = base64.decodestring(six.b(... | def verify_notification(data):
"""
Function to verify notification came from a trusted source
Returns True if verfied, False if not verified
"""
pemfile = grab_keyfile(data['SigningCertURL'])
cert = crypto.load_certificate(crypto.FILETYPE_PEM, pemfile)
signature = base64.decodestring(six.b(... | [
"Function",
"to",
"verify",
"notification",
"came",
"from",
"a",
"trusted",
"source"
] | ofa/django-bouncy | python | https://github.com/ofa/django-bouncy/blob/a386dfa8c4ce59bd18978a3537c03cd6ad07bf06/django_bouncy/utils.py#L94-L114 | [
"def",
"verify_notification",
"(",
"data",
")",
":",
"pemfile",
"=",
"grab_keyfile",
"(",
"data",
"[",
"'SigningCertURL'",
"]",
")",
"cert",
"=",
"crypto",
".",
"load_certificate",
"(",
"crypto",
".",
"FILETYPE_PEM",
",",
"pemfile",
")",
"signature",
"=",
"b... | a386dfa8c4ce59bd18978a3537c03cd6ad07bf06 |
train | approve_subscription | Function to approve a SNS subscription with Amazon
We don't do a ton of verification here, past making sure that the endpoint
we're told to go to to verify the subscription is on the correct host | django_bouncy/utils.py | def approve_subscription(data):
"""
Function to approve a SNS subscription with Amazon
We don't do a ton of verification here, past making sure that the endpoint
we're told to go to to verify the subscription is on the correct host
"""
url = data['SubscribeURL']
domain = urlparse(url).netl... | def approve_subscription(data):
"""
Function to approve a SNS subscription with Amazon
We don't do a ton of verification here, past making sure that the endpoint
we're told to go to to verify the subscription is on the correct host
"""
url = data['SubscribeURL']
domain = urlparse(url).netl... | [
"Function",
"to",
"approve",
"a",
"SNS",
"subscription",
"with",
"Amazon"
] | ofa/django-bouncy | python | https://github.com/ofa/django-bouncy/blob/a386dfa8c4ce59bd18978a3537c03cd6ad07bf06/django_bouncy/utils.py#L117-L150 | [
"def",
"approve_subscription",
"(",
"data",
")",
":",
"url",
"=",
"data",
"[",
"'SubscribeURL'",
"]",
"domain",
"=",
"urlparse",
"(",
"url",
")",
".",
"netloc",
"pattern",
"=",
"getattr",
"(",
"settings",
",",
"'BOUNCY_SUBSCRIBE_DOMAIN_REGEX'",
",",
"r\"sns.[a... | a386dfa8c4ce59bd18978a3537c03cd6ad07bf06 |
train | clean_time | Return a datetime from the Amazon-provided datetime string | django_bouncy/utils.py | def clean_time(time_string):
"""Return a datetime from the Amazon-provided datetime string"""
# Get a timezone-aware datetime object from the string
time = dateutil.parser.parse(time_string)
if not settings.USE_TZ:
# If timezone support is not active, convert the time to UTC and
# remove... | def clean_time(time_string):
"""Return a datetime from the Amazon-provided datetime string"""
# Get a timezone-aware datetime object from the string
time = dateutil.parser.parse(time_string)
if not settings.USE_TZ:
# If timezone support is not active, convert the time to UTC and
# remove... | [
"Return",
"a",
"datetime",
"from",
"the",
"Amazon",
"-",
"provided",
"datetime",
"string"
] | ofa/django-bouncy | python | https://github.com/ofa/django-bouncy/blob/a386dfa8c4ce59bd18978a3537c03cd6ad07bf06/django_bouncy/utils.py#L153-L161 | [
"def",
"clean_time",
"(",
"time_string",
")",
":",
"# Get a timezone-aware datetime object from the string",
"time",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"time_string",
")",
"if",
"not",
"settings",
".",
"USE_TZ",
":",
"# If timezone support is not active,... | a386dfa8c4ce59bd18978a3537c03cd6ad07bf06 |
train | parse_selectors | Validates fields are valid and maps pseudo-fields to actual fields
for a given model class. | preserialize/utils.py | def parse_selectors(model, fields=None, exclude=None, key_map=None, **options):
"""Validates fields are valid and maps pseudo-fields to actual fields
for a given model class.
"""
fields = fields or DEFAULT_SELECTORS
exclude = exclude or ()
key_map = key_map or {}
validated = []
for alia... | def parse_selectors(model, fields=None, exclude=None, key_map=None, **options):
"""Validates fields are valid and maps pseudo-fields to actual fields
for a given model class.
"""
fields = fields or DEFAULT_SELECTORS
exclude = exclude or ()
key_map = key_map or {}
validated = []
for alia... | [
"Validates",
"fields",
"are",
"valid",
"and",
"maps",
"pseudo",
"-",
"fields",
"to",
"actual",
"fields",
"for",
"a",
"given",
"model",
"class",
"."
] | bruth/django-preserialize | python | https://github.com/bruth/django-preserialize/blob/d772c224bd8c2c9e9ff997d82c54fe6ebb9444b6/preserialize/utils.py#L96-L125 | [
"def",
"parse_selectors",
"(",
"model",
",",
"fields",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"key_map",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"fields",
"=",
"fields",
"or",
"DEFAULT_SELECTORS",
"exclude",
"=",
"exclude",
"or",
"(",
... | d772c224bd8c2c9e9ff997d82c54fe6ebb9444b6 |
train | ModelFieldResolver._get_local_fields | Return the names of all locally defined fields on the model class. | preserialize/utils.py | def _get_local_fields(self, model):
"Return the names of all locally defined fields on the model class."
local = [f for f in model._meta.fields]
m2m = [f for f in model._meta.many_to_many]
fields = local + m2m
names = tuple([x.name for x in fields])
return {
... | def _get_local_fields(self, model):
"Return the names of all locally defined fields on the model class."
local = [f for f in model._meta.fields]
m2m = [f for f in model._meta.many_to_many]
fields = local + m2m
names = tuple([x.name for x in fields])
return {
... | [
"Return",
"the",
"names",
"of",
"all",
"locally",
"defined",
"fields",
"on",
"the",
"model",
"class",
"."
] | bruth/django-preserialize | python | https://github.com/bruth/django-preserialize/blob/d772c224bd8c2c9e9ff997d82c54fe6ebb9444b6/preserialize/utils.py#L42-L51 | [
"def",
"_get_local_fields",
"(",
"self",
",",
"model",
")",
":",
"local",
"=",
"[",
"f",
"for",
"f",
"in",
"model",
".",
"_meta",
".",
"fields",
"]",
"m2m",
"=",
"[",
"f",
"for",
"f",
"in",
"model",
".",
"_meta",
".",
"many_to_many",
"]",
"fields",... | d772c224bd8c2c9e9ff997d82c54fe6ebb9444b6 |
train | ModelFieldResolver._get_related_fields | Returns the names of all related fields for model class. | preserialize/utils.py | def _get_related_fields(self, model):
"Returns the names of all related fields for model class."
reverse_fk = self._get_all_related_objects(model)
reverse_m2m = self._get_all_related_many_to_many_objects(model)
fields = tuple(reverse_fk + reverse_m2m)
names = tuple([x.get_access... | def _get_related_fields(self, model):
"Returns the names of all related fields for model class."
reverse_fk = self._get_all_related_objects(model)
reverse_m2m = self._get_all_related_many_to_many_objects(model)
fields = tuple(reverse_fk + reverse_m2m)
names = tuple([x.get_access... | [
"Returns",
"the",
"names",
"of",
"all",
"related",
"fields",
"for",
"model",
"class",
"."
] | bruth/django-preserialize | python | https://github.com/bruth/django-preserialize/blob/d772c224bd8c2c9e9ff997d82c54fe6ebb9444b6/preserialize/utils.py#L53-L63 | [
"def",
"_get_related_fields",
"(",
"self",
",",
"model",
")",
":",
"reverse_fk",
"=",
"self",
".",
"_get_all_related_objects",
"(",
"model",
")",
"reverse_m2m",
"=",
"self",
".",
"_get_all_related_many_to_many_objects",
"(",
"model",
")",
"fields",
"=",
"tuple",
... | d772c224bd8c2c9e9ff997d82c54fe6ebb9444b6 |
train | HTMLTable.to_html | Return HTML version of the table
This is a wrapper of the to_html method of the pandas dataframe.
:param bool index: do not include the index
:param bool escape: do not escape special characters
:param bool header: include header
:param bool collapse_table: long tables are shor... | reports/htmltable.py | def to_html(self, index=False, escape=False, header=True,
collapse_table=True, class_outer="table_outer", **kargs):
"""Return HTML version of the table
This is a wrapper of the to_html method of the pandas dataframe.
:param bool index: do not include the index
:param bool e... | def to_html(self, index=False, escape=False, header=True,
collapse_table=True, class_outer="table_outer", **kargs):
"""Return HTML version of the table
This is a wrapper of the to_html method of the pandas dataframe.
:param bool index: do not include the index
:param bool e... | [
"Return",
"HTML",
"version",
"of",
"the",
"table"
] | cokelaer/reports | python | https://github.com/cokelaer/reports/blob/7703b1e27d440c3193ee6cc90bfecd78cc98b737/reports/htmltable.py#L75-L108 | [
"def",
"to_html",
"(",
"self",
",",
"index",
"=",
"False",
",",
"escape",
"=",
"False",
",",
"header",
"=",
"True",
",",
"collapse_table",
"=",
"True",
",",
"class_outer",
"=",
"\"table_outer\"",
",",
"*",
"*",
"kargs",
")",
":",
"_buffer",
"=",
"{",
... | 7703b1e27d440c3193ee6cc90bfecd78cc98b737 |
train | HTMLTable.add_bgcolor | Change column content into HTML paragraph with background color
:param colname:
:param cmap: a colormap (matplotlib) or created using
colormap package (from pypi).
:param mode: type of normalisation in 'absmax', 'max', 'clip'
(see details below)
:param threshold:... | reports/htmltable.py | def add_bgcolor(self, colname, cmap='copper', mode='absmax',
threshold=2):
"""Change column content into HTML paragraph with background color
:param colname:
:param cmap: a colormap (matplotlib) or created using
colormap package (from pypi).
:param mode: type of ... | def add_bgcolor(self, colname, cmap='copper', mode='absmax',
threshold=2):
"""Change column content into HTML paragraph with background color
:param colname:
:param cmap: a colormap (matplotlib) or created using
colormap package (from pypi).
:param mode: type of ... | [
"Change",
"column",
"content",
"into",
"HTML",
"paragraph",
"with",
"background",
"color"
] | cokelaer/reports | python | https://github.com/cokelaer/reports/blob/7703b1e27d440c3193ee6cc90bfecd78cc98b737/reports/htmltable.py#L110-L180 | [
"def",
"add_bgcolor",
"(",
"self",
",",
"colname",
",",
"cmap",
"=",
"'copper'",
",",
"mode",
"=",
"'absmax'",
",",
"threshold",
"=",
"2",
")",
":",
"try",
":",
"# if a cmap is provided, it may be just a known cmap name",
"cmap",
"=",
"cmap_builder",
"(",
"cmap"... | 7703b1e27d440c3193ee6cc90bfecd78cc98b737 |
train | TrackingEventAdmin.changelist_view | Get object currently tracked and add a button to get back to it | tracking_fields/admin.py | def changelist_view(self, request, extra_context=None):
""" Get object currently tracked and add a button to get back to it """
extra_context = extra_context or {}
if 'object' in request.GET.keys():
value = request.GET['object'].split(':')
content_type = get_object_or_404... | def changelist_view(self, request, extra_context=None):
""" Get object currently tracked and add a button to get back to it """
extra_context = extra_context or {}
if 'object' in request.GET.keys():
value = request.GET['object'].split(':')
content_type = get_object_or_404... | [
"Get",
"object",
"currently",
"tracked",
"and",
"add",
"a",
"button",
"to",
"get",
"back",
"to",
"it"
] | makinacorpus/django-tracking-fields | python | https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/admin.py#L118-L134 | [
"def",
"changelist_view",
"(",
"self",
",",
"request",
",",
"extra_context",
"=",
"None",
")",
":",
"extra_context",
"=",
"extra_context",
"or",
"{",
"}",
"if",
"'object'",
"in",
"request",
".",
"GET",
".",
"keys",
"(",
")",
":",
"value",
"=",
"request",... | 463313d0f9c0f8107a0413f4d418d1a8c2311981 |
train | ConfigsService.list | Get a list of configs.
:param filter: (optional) Filters to apply as a string list.
:param type: (optional) `union` or `inter` as string.
:param sort: (optional) Sort fields to apply as string list.
:param limit: (optional) Limit returned list length.
:param page: (optional) Pag... | cdrouter/configs.py | def list(self, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=redefined-builtin
"""Get a list of configs.
:param filter: (optional) Filters to apply as a string list.
:param type: (optional) `union` or `inter` as string.
:param sort: (optional) Sort fields ... | def list(self, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=redefined-builtin
"""Get a list of configs.
:param filter: (optional) Filters to apply as a string list.
:param type: (optional) `union` or `inter` as string.
:param sort: (optional) Sort fields ... | [
"Get",
"a",
"list",
"of",
"configs",
"."
] | qacafe/cdrouter.py | python | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L187-L200 | [
"def",
"list",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"type",
"=",
"None",
",",
"sort",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"page",
"=",
"None",
")",
":",
"# pylint: disable=redefined-builtin",
"schema",
"=",
"self",
".",
"LIST_SCHEMA",
... | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 |
train | ConfigsService.iter_list | Get a list of configs. Whereas ``list`` fetches a single page of
configs according to its ``limit`` and ``page`` arguments,
``iter_list`` returns all configs by internally making
successive calls to ``list``.
:param args: Arguments that ``list`` takes.
:param kwargs: Optional a... | cdrouter/configs.py | def iter_list(self, *args, **kwargs):
"""Get a list of configs. Whereas ``list`` fetches a single page of
configs according to its ``limit`` and ``page`` arguments,
``iter_list`` returns all configs by internally making
successive calls to ``list``.
:param args: Arguments that ... | def iter_list(self, *args, **kwargs):
"""Get a list of configs. Whereas ``list`` fetches a single page of
configs according to its ``limit`` and ``page`` arguments,
``iter_list`` returns all configs by internally making
successive calls to ``list``.
:param args: Arguments that ... | [
"Get",
"a",
"list",
"of",
"configs",
".",
"Whereas",
"list",
"fetches",
"a",
"single",
"page",
"of",
"configs",
"according",
"to",
"its",
"limit",
"and",
"page",
"arguments",
"iter_list",
"returns",
"all",
"configs",
"by",
"internally",
"making",
"successive",... | qacafe/cdrouter.py | python | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L202-L213 | [
"def",
"iter_list",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"service",
".",
"iter_list",
"(",
"self",
".",
"list",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 |
train | ConfigsService.get_plaintext | Get a config as plaintext.
:param id: Config ID as an int.
:rtype: string | cdrouter/configs.py | def get_plaintext(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Get a config as plaintext.
:param id: Config ID as an int.
:rtype: string
"""
return self.service.get_id(self.base, id, params={'format': 'text'}).text | def get_plaintext(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Get a config as plaintext.
:param id: Config ID as an int.
:rtype: string
"""
return self.service.get_id(self.base, id, params={'format': 'text'}).text | [
"Get",
"a",
"config",
"as",
"plaintext",
"."
] | qacafe/cdrouter.py | python | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L233-L239 | [
"def",
"get_plaintext",
"(",
"self",
",",
"id",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"return",
"self",
".",
"service",
".",
"get_id",
"(",
"self",
".",
"base",
",",
"id",
",",
"params",
"=",
"{",
"'format'",
":",
"'text'",
"}",
")",
... | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 |
train | ConfigsService.create | Create a new config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config | cdrouter/configs.py | def create(self, resource):
"""Create a new config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config
"""
schema = self.CREATE_SCHEMA
json = self.service.encode(schema,... | def create(self, resource):
"""Create a new config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config
"""
schema = self.CREATE_SCHEMA
json = self.service.encode(schema,... | [
"Create",
"a",
"new",
"config",
"."
] | qacafe/cdrouter.py | python | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L253-L265 | [
"def",
"create",
"(",
"self",
",",
"resource",
")",
":",
"schema",
"=",
"self",
".",
"CREATE_SCHEMA",
"json",
"=",
"self",
".",
"service",
".",
"encode",
"(",
"schema",
",",
"resource",
")",
"schema",
"=",
"self",
".",
"GET_SCHEMA",
"resp",
"=",
"self"... | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 |
train | ConfigsService.edit | Edit a config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config | cdrouter/configs.py | def edit(self, resource):
"""Edit a config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config
"""
schema = self.EDIT_SCHEMA
json = self.service.encode(schema, resource)... | def edit(self, resource):
"""Edit a config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config
"""
schema = self.EDIT_SCHEMA
json = self.service.encode(schema, resource)... | [
"Edit",
"a",
"config",
"."
] | qacafe/cdrouter.py | python | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L267-L279 | [
"def",
"edit",
"(",
"self",
",",
"resource",
")",
":",
"schema",
"=",
"self",
".",
"EDIT_SCHEMA",
"json",
"=",
"self",
".",
"service",
".",
"encode",
"(",
"schema",
",",
"resource",
")",
"schema",
"=",
"self",
".",
"GET_SCHEMA",
"resp",
"=",
"self",
... | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 |
train | ConfigsService.edit_shares | Edit shares for a config.
:param id: Config ID as an int.
:param user_ids: User IDs as int list.
:return: :class:`cdrouter.Share <cdrouter.Share>` list | cdrouter/configs.py | def edit_shares(self, id, user_ids): # pylint: disable=invalid-name,redefined-builtin
"""Edit shares for a config.
:param id: Config ID as an int.
:param user_ids: User IDs as int list.
:return: :class:`cdrouter.Share <cdrouter.Share>` list
"""
return self.service.edit_s... | def edit_shares(self, id, user_ids): # pylint: disable=invalid-name,redefined-builtin
"""Edit shares for a config.
:param id: Config ID as an int.
:param user_ids: User IDs as int list.
:return: :class:`cdrouter.Share <cdrouter.Share>` list
"""
return self.service.edit_s... | [
"Edit",
"shares",
"for",
"a",
"config",
"."
] | qacafe/cdrouter.py | python | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L296-L303 | [
"def",
"edit_shares",
"(",
"self",
",",
"id",
",",
"user_ids",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"return",
"self",
".",
"service",
".",
"edit_shares",
"(",
"self",
".",
"base",
",",
"id",
",",
"user_ids",
")"
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 |
train | ConfigsService.check_config | Process config contents with cdrouter-cli -check-config.
:param contents: Config contents as string.
:return: :class:`configs.CheckConfig <configs.CheckConfig>` object
:rtype: configs.CheckConfig | cdrouter/configs.py | def check_config(self, contents):
"""Process config contents with cdrouter-cli -check-config.
:param contents: Config contents as string.
:return: :class:`configs.CheckConfig <configs.CheckConfig>` object
:rtype: configs.CheckConfig
"""
schema = CheckConfigSchema()
... | def check_config(self, contents):
"""Process config contents with cdrouter-cli -check-config.
:param contents: Config contents as string.
:return: :class:`configs.CheckConfig <configs.CheckConfig>` object
:rtype: configs.CheckConfig
"""
schema = CheckConfigSchema()
... | [
"Process",
"config",
"contents",
"with",
"cdrouter",
"-",
"cli",
"-",
"check",
"-",
"config",
"."
] | qacafe/cdrouter.py | python | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L313-L323 | [
"def",
"check_config",
"(",
"self",
",",
"contents",
")",
":",
"schema",
"=",
"CheckConfigSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"post",
"(",
"self",
".",
"base",
",",
"params",
"=",
"{",
"'process'",
":",
"'check'",
"}",
",",
"... | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 |
train | ConfigsService.upgrade_config | Process config contents with cdrouter-cli -upgrade-config.
:param contents: Config contents as string.
:return: :class:`configs.UpgradeConfig <configs.UpgradeConfig>` object
:rtype: configs.UpgradeConfig | cdrouter/configs.py | def upgrade_config(self, contents):
"""Process config contents with cdrouter-cli -upgrade-config.
:param contents: Config contents as string.
:return: :class:`configs.UpgradeConfig <configs.UpgradeConfig>` object
:rtype: configs.UpgradeConfig
"""
schema = UpgradeConfigSc... | def upgrade_config(self, contents):
"""Process config contents with cdrouter-cli -upgrade-config.
:param contents: Config contents as string.
:return: :class:`configs.UpgradeConfig <configs.UpgradeConfig>` object
:rtype: configs.UpgradeConfig
"""
schema = UpgradeConfigSc... | [
"Process",
"config",
"contents",
"with",
"cdrouter",
"-",
"cli",
"-",
"upgrade",
"-",
"config",
"."
] | qacafe/cdrouter.py | python | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L325-L335 | [
"def",
"upgrade_config",
"(",
"self",
",",
"contents",
")",
":",
"schema",
"=",
"UpgradeConfigSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"post",
"(",
"self",
".",
"base",
",",
"params",
"=",
"{",
"'process'",
":",
"'upgrade'",
"}",
",... | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 |
train | ConfigsService.get_networks | Process config contents with cdrouter-cli -print-networks-json.
:param contents: Config contents as string.
:return: :class:`configs.Networks <configs.Networks>` object
:rtype: configs.Networks | cdrouter/configs.py | def get_networks(self, contents):
"""Process config contents with cdrouter-cli -print-networks-json.
:param contents: Config contents as string.
:return: :class:`configs.Networks <configs.Networks>` object
:rtype: configs.Networks
"""
schema = NetworksSchema()
re... | def get_networks(self, contents):
"""Process config contents with cdrouter-cli -print-networks-json.
:param contents: Config contents as string.
:return: :class:`configs.Networks <configs.Networks>` object
:rtype: configs.Networks
"""
schema = NetworksSchema()
re... | [
"Process",
"config",
"contents",
"with",
"cdrouter",
"-",
"cli",
"-",
"print",
"-",
"networks",
"-",
"json",
"."
] | qacafe/cdrouter.py | python | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L337-L347 | [
"def",
"get_networks",
"(",
"self",
",",
"contents",
")",
":",
"schema",
"=",
"NetworksSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"post",
"(",
"self",
".",
"base",
",",
"params",
"=",
"{",
"'process'",
":",
"'networks'",
"}",
",",
"... | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 |
train | ConfigsService.bulk_copy | Bulk copy a set of configs.
:param ids: Int list of config IDs.
:return: :class:`configs.Config <configs.Config>` list | cdrouter/configs.py | def bulk_copy(self, ids):
"""Bulk copy a set of configs.
:param ids: Int list of config IDs.
:return: :class:`configs.Config <configs.Config>` list
"""
schema = self.GET_SCHEMA
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) | def bulk_copy(self, ids):
"""Bulk copy a set of configs.
:param ids: Int list of config IDs.
:return: :class:`configs.Config <configs.Config>` list
"""
schema = self.GET_SCHEMA
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) | [
"Bulk",
"copy",
"a",
"set",
"of",
"configs",
"."
] | qacafe/cdrouter.py | python | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L357-L364 | [
"def",
"bulk_copy",
"(",
"self",
",",
"ids",
")",
":",
"schema",
"=",
"self",
".",
"GET_SCHEMA",
"return",
"self",
".",
"service",
".",
"bulk_copy",
"(",
"self",
".",
"base",
",",
"self",
".",
"RESOURCE",
",",
"ids",
",",
"schema",
")"
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 |
train | ConfigsService.bulk_edit | Bulk edit a set of configs.
:param _fields: :class:`configs.Config <configs.Config>` object
:param ids: (optional) Int list of config IDs.
:param filter: (optional) String list of filters.
:param type: (optional) `union` or `inter` as string.
:param all: (optional) Apply to all ... | cdrouter/configs.py | def bulk_edit(self, _fields, ids=None, filter=None, type=None, all=False, testvars=None): # pylint: disable=redefined-builtin
"""Bulk edit a set of configs.
:param _fields: :class:`configs.Config <configs.Config>` object
:param ids: (optional) Int list of config IDs.
:param filter: (opt... | def bulk_edit(self, _fields, ids=None, filter=None, type=None, all=False, testvars=None): # pylint: disable=redefined-builtin
"""Bulk edit a set of configs.
:param _fields: :class:`configs.Config <configs.Config>` object
:param ids: (optional) Int list of config IDs.
:param filter: (opt... | [
"Bulk",
"edit",
"a",
"set",
"of",
"configs",
"."
] | qacafe/cdrouter.py | python | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L366-L379 | [
"def",
"bulk_edit",
"(",
"self",
",",
"_fields",
",",
"ids",
"=",
"None",
",",
"filter",
"=",
"None",
",",
"type",
"=",
"None",
",",
"all",
"=",
"False",
",",
"testvars",
"=",
"None",
")",
":",
"# pylint: disable=redefined-builtin",
"schema",
"=",
"self"... | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 |
train | ConfigsService.bulk_delete | Bulk delete a set of configs.
:param ids: (optional) Int list of config IDs.
:param filter: (optional) String list of filters.
:param type: (optional) `union` or `inter` as string.
:param all: (optional) Apply to all if bool `True`. | cdrouter/configs.py | def bulk_delete(self, ids=None, filter=None, type=None, all=False): # pylint: disable=redefined-builtin
"""Bulk delete a set of configs.
:param ids: (optional) Int list of config IDs.
:param filter: (optional) String list of filters.
:param type: (optional) `union` or `inter` as string.... | def bulk_delete(self, ids=None, filter=None, type=None, all=False): # pylint: disable=redefined-builtin
"""Bulk delete a set of configs.
:param ids: (optional) Int list of config IDs.
:param filter: (optional) String list of filters.
:param type: (optional) `union` or `inter` as string.... | [
"Bulk",
"delete",
"a",
"set",
"of",
"configs",
"."
] | qacafe/cdrouter.py | python | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L381-L390 | [
"def",
"bulk_delete",
"(",
"self",
",",
"ids",
"=",
"None",
",",
"filter",
"=",
"None",
",",
"type",
"=",
"None",
",",
"all",
"=",
"False",
")",
":",
"# pylint: disable=redefined-builtin",
"return",
"self",
".",
"service",
".",
"bulk_delete",
"(",
"self",
... | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 |
train | response_token_setter | Extract token from response and set it for the user.
:param remote: The remote application.
:param resp: The response.
:raises invenio_oauthclient.errors.OAuthClientError: If authorization with
remote service failed.
:raises invenio_oauthclient.errors.OAuthResponseError: In case of bad
... | invenio_oauthclient/handlers.py | def response_token_setter(remote, resp):
"""Extract token from response and set it for the user.
:param remote: The remote application.
:param resp: The response.
:raises invenio_oauthclient.errors.OAuthClientError: If authorization with
remote service failed.
:raises invenio_oauthclient.er... | def response_token_setter(remote, resp):
"""Extract token from response and set it for the user.
:param remote: The remote application.
:param resp: The response.
:raises invenio_oauthclient.errors.OAuthClientError: If authorization with
remote service failed.
:raises invenio_oauthclient.er... | [
"Extract",
"token",
"from",
"response",
"and",
"set",
"it",
"for",
"the",
"user",
"."
] | inveniosoftware/invenio-oauthclient | python | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L69-L92 | [
"def",
"response_token_setter",
"(",
"remote",
",",
"resp",
")",
":",
"if",
"resp",
"is",
"None",
":",
"raise",
"OAuthRejectedRequestError",
"(",
"'User rejected request.'",
",",
"remote",
",",
"resp",
")",
"else",
":",
"if",
"'access_token'",
"in",
"resp",
":... | 2500dc6935738107617aeade79e050d7608004bb |
train | oauth1_token_setter | Set an OAuth1 token.
:param remote: The remote application.
:param resp: The response.
:param token_type: The token type. (Default: ``''``)
:param extra_data: Extra information. (Default: ``None``)
:returns: A :class:`invenio_oauthclient.models.RemoteToken` instance. | invenio_oauthclient/handlers.py | def oauth1_token_setter(remote, resp, token_type='', extra_data=None):
"""Set an OAuth1 token.
:param remote: The remote application.
:param resp: The response.
:param token_type: The token type. (Default: ``''``)
:param extra_data: Extra information. (Default: ``None``)
:returns: A :class:`inv... | def oauth1_token_setter(remote, resp, token_type='', extra_data=None):
"""Set an OAuth1 token.
:param remote: The remote application.
:param resp: The response.
:param token_type: The token type. (Default: ``''``)
:param extra_data: Extra information. (Default: ``None``)
:returns: A :class:`inv... | [
"Set",
"an",
"OAuth1",
"token",
"."
] | inveniosoftware/invenio-oauthclient | python | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L95-L110 | [
"def",
"oauth1_token_setter",
"(",
"remote",
",",
"resp",
",",
"token_type",
"=",
"''",
",",
"extra_data",
"=",
"None",
")",
":",
"return",
"token_setter",
"(",
"remote",
",",
"resp",
"[",
"'oauth_token'",
"]",
",",
"secret",
"=",
"resp",
"[",
"'oauth_toke... | 2500dc6935738107617aeade79e050d7608004bb |
train | oauth2_token_setter | Set an OAuth2 token.
The refresh_token can be used to obtain a new access_token after
the old one is expired. It is saved in the database for long term use.
A refresh_token will be present only if `access_type=offline` is included
in the authorization code request.
:param remote: The remote applic... | invenio_oauthclient/handlers.py | def oauth2_token_setter(remote, resp, token_type='', extra_data=None):
"""Set an OAuth2 token.
The refresh_token can be used to obtain a new access_token after
the old one is expired. It is saved in the database for long term use.
A refresh_token will be present only if `access_type=offline` is include... | def oauth2_token_setter(remote, resp, token_type='', extra_data=None):
"""Set an OAuth2 token.
The refresh_token can be used to obtain a new access_token after
the old one is expired. It is saved in the database for long term use.
A refresh_token will be present only if `access_type=offline` is include... | [
"Set",
"an",
"OAuth2",
"token",
"."
] | inveniosoftware/invenio-oauthclient | python | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L113-L133 | [
"def",
"oauth2_token_setter",
"(",
"remote",
",",
"resp",
",",
"token_type",
"=",
"''",
",",
"extra_data",
"=",
"None",
")",
":",
"return",
"token_setter",
"(",
"remote",
",",
"resp",
"[",
"'access_token'",
"]",
",",
"secret",
"=",
"''",
",",
"token_type",... | 2500dc6935738107617aeade79e050d7608004bb |
train | token_setter | Set token for user.
:param remote: The remote application.
:param token: The token to set.
:param token_type: The token type. (Default: ``''``)
:param extra_data: Extra information. (Default: ``None``)
:param user: The user owner of the remote token. If it's not defined,
the current user is... | invenio_oauthclient/handlers.py | def token_setter(remote, token, secret='', token_type='', extra_data=None,
user=None):
"""Set token for user.
:param remote: The remote application.
:param token: The token to set.
:param token_type: The token type. (Default: ``''``)
:param extra_data: Extra information. (Default: ... | def token_setter(remote, token, secret='', token_type='', extra_data=None,
user=None):
"""Set token for user.
:param remote: The remote application.
:param token: The token to set.
:param token_type: The token type. (Default: ``''``)
:param extra_data: Extra information. (Default: ... | [
"Set",
"token",
"for",
"user",
"."
] | inveniosoftware/invenio-oauthclient | python | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L136-L169 | [
"def",
"token_setter",
"(",
"remote",
",",
"token",
",",
"secret",
"=",
"''",
",",
"token_type",
"=",
"''",
",",
"extra_data",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"session",
"[",
"token_session_key",
"(",
"remote",
".",
"name",
")",
"]",
... | 2500dc6935738107617aeade79e050d7608004bb |
train | token_getter | Retrieve OAuth access token.
Used by flask-oauthlib to get the access token when making requests.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default: ``''``)
:returns: The token. | invenio_oauthclient/handlers.py | def token_getter(remote, token=''):
"""Retrieve OAuth access token.
Used by flask-oauthlib to get the access token when making requests.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default... | def token_getter(remote, token=''):
"""Retrieve OAuth access token.
Used by flask-oauthlib to get the access token when making requests.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default... | [
"Retrieve",
"OAuth",
"access",
"token",
"."
] | inveniosoftware/invenio-oauthclient | python | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L172-L199 | [
"def",
"token_getter",
"(",
"remote",
",",
"token",
"=",
"''",
")",
":",
"session_key",
"=",
"token_session_key",
"(",
"remote",
".",
"name",
")",
"if",
"session_key",
"not",
"in",
"session",
"and",
"current_user",
".",
"is_authenticated",
":",
"# Fetch key fr... | 2500dc6935738107617aeade79e050d7608004bb |
train | token_delete | Remove OAuth access tokens from session.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default: ``''``)
:returns: The token. | invenio_oauthclient/handlers.py | def token_delete(remote, token=''):
"""Remove OAuth access tokens from session.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default: ``''``)
:returns: The token.
"""
session_key = t... | def token_delete(remote, token=''):
"""Remove OAuth access tokens from session.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default: ``''``)
:returns: The token.
"""
session_key = t... | [
"Remove",
"OAuth",
"access",
"tokens",
"from",
"session",
"."
] | inveniosoftware/invenio-oauthclient | python | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L202-L211 | [
"def",
"token_delete",
"(",
"remote",
",",
"token",
"=",
"''",
")",
":",
"session_key",
"=",
"token_session_key",
"(",
"remote",
".",
"name",
")",
"return",
"session",
".",
"pop",
"(",
"session_key",
",",
"None",
")"
] | 2500dc6935738107617aeade79e050d7608004bb |
train | oauth_error_handler | Decorator to handle exceptions. | invenio_oauthclient/handlers.py | def oauth_error_handler(f):
"""Decorator to handle exceptions."""
@wraps(f)
def inner(*args, **kwargs):
# OAuthErrors should not happen, so they are not caught here. Hence
# they will result in a 500 Internal Server Error which is what we
# are interested in.
try:
... | def oauth_error_handler(f):
"""Decorator to handle exceptions."""
@wraps(f)
def inner(*args, **kwargs):
# OAuthErrors should not happen, so they are not caught here. Hence
# they will result in a 500 Internal Server Error which is what we
# are interested in.
try:
... | [
"Decorator",
"to",
"handle",
"exceptions",
"."
] | inveniosoftware/invenio-oauthclient | python | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L217-L244 | [
"def",
"oauth_error_handler",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# OAuthErrors should not happen, so they are not caught here. Hence",
"# they will result in a 500 Internal Server Error ... | 2500dc6935738107617aeade79e050d7608004bb |
train | authorized_default_handler | Store access token in session.
Default authorized handler.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response. | invenio_oauthclient/handlers.py | def authorized_default_handler(resp, remote, *args, **kwargs):
"""Store access token in session.
Default authorized handler.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response.
"""
response_token_setter(remote, resp)
db.session.commit()
re... | def authorized_default_handler(resp, remote, *args, **kwargs):
"""Store access token in session.
Default authorized handler.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response.
"""
response_token_setter(remote, resp)
db.session.commit()
re... | [
"Store",
"access",
"token",
"in",
"session",
"."
] | inveniosoftware/invenio-oauthclient | python | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L251-L262 | [
"def",
"authorized_default_handler",
"(",
"resp",
",",
"remote",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response_token_setter",
"(",
"remote",
",",
"resp",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"return",
"redirect",
"(",
"url... | 2500dc6935738107617aeade79e050d7608004bb |
train | authorized_signup_handler | Handle sign-in/up functionality.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response. | invenio_oauthclient/handlers.py | def authorized_signup_handler(resp, remote, *args, **kwargs):
"""Handle sign-in/up functionality.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response.
"""
# Remove any previously stored auto register session key
session.pop(token_session_key(remote.... | def authorized_signup_handler(resp, remote, *args, **kwargs):
"""Handle sign-in/up functionality.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response.
"""
# Remove any previously stored auto register session key
session.pop(token_session_key(remote.... | [
"Handle",
"sign",
"-",
"in",
"/",
"up",
"functionality",
"."
] | inveniosoftware/invenio-oauthclient | python | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L266-L348 | [
"def",
"authorized_signup_handler",
"(",
"resp",
",",
"remote",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Remove any previously stored auto register session key",
"session",
".",
"pop",
"(",
"token_session_key",
"(",
"remote",
".",
"name",
")",
"+",
... | 2500dc6935738107617aeade79e050d7608004bb |
train | disconnect_handler | Handle unlinking of remote account.
This default handler will just delete the remote account link. You may
wish to extend this module to perform clean-up in the remote service
before removing the link (e.g. removing install webhooks).
:param remote: The remote application.
:returns: Redirect respo... | invenio_oauthclient/handlers.py | def disconnect_handler(remote, *args, **kwargs):
"""Handle unlinking of remote account.
This default handler will just delete the remote account link. You may
wish to extend this module to perform clean-up in the remote service
before removing the link (e.g. removing install webhooks).
:param remo... | def disconnect_handler(remote, *args, **kwargs):
"""Handle unlinking of remote account.
This default handler will just delete the remote account link. You may
wish to extend this module to perform clean-up in the remote service
before removing the link (e.g. removing install webhooks).
:param remo... | [
"Handle",
"unlinking",
"of",
"remote",
"account",
"."
] | inveniosoftware/invenio-oauthclient | python | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L351-L373 | [
"def",
"disconnect_handler",
"(",
"remote",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"current_user",
".",
"is_authenticated",
":",
"return",
"current_app",
".",
"login_manager",
".",
"unauthorized",
"(",
")",
"with",
"db",
".",
"se... | 2500dc6935738107617aeade79e050d7608004bb |
train | signup_handler | Handle extra signup information.
:param remote: The remote application.
:returns: Redirect response or the template rendered. | invenio_oauthclient/handlers.py | def signup_handler(remote, *args, **kwargs):
"""Handle extra signup information.
:param remote: The remote application.
:returns: Redirect response or the template rendered.
"""
# User already authenticated so move on
if current_user.is_authenticated:
return redirect('/')
# Retriev... | def signup_handler(remote, *args, **kwargs):
"""Handle extra signup information.
:param remote: The remote application.
:returns: Redirect response or the template rendered.
"""
# User already authenticated so move on
if current_user.is_authenticated:
return redirect('/')
# Retriev... | [
"Handle",
"extra",
"signup",
"information",
"."
] | inveniosoftware/invenio-oauthclient | python | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L376-L466 | [
"def",
"signup_handler",
"(",
"remote",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# User already authenticated so move on",
"if",
"current_user",
".",
"is_authenticated",
":",
"return",
"redirect",
"(",
"'/'",
")",
"# Retrieve token from session",
"oauth... | 2500dc6935738107617aeade79e050d7608004bb |
train | oauth_logout_handler | Remove all access tokens from session on logout. | invenio_oauthclient/handlers.py | def oauth_logout_handler(sender_app, user=None):
"""Remove all access tokens from session on logout."""
oauth = current_app.extensions['oauthlib.client']
for remote in oauth.remote_apps.values():
token_delete(remote)
db.session.commit() | def oauth_logout_handler(sender_app, user=None):
"""Remove all access tokens from session on logout."""
oauth = current_app.extensions['oauthlib.client']
for remote in oauth.remote_apps.values():
token_delete(remote)
db.session.commit() | [
"Remove",
"all",
"access",
"tokens",
"from",
"session",
"on",
"logout",
"."
] | inveniosoftware/invenio-oauthclient | python | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L469-L474 | [
"def",
"oauth_logout_handler",
"(",
"sender_app",
",",
"user",
"=",
"None",
")",
":",
"oauth",
"=",
"current_app",
".",
"extensions",
"[",
"'oauthlib.client'",
"]",
"for",
"remote",
"in",
"oauth",
".",
"remote_apps",
".",
"values",
"(",
")",
":",
"token_dele... | 2500dc6935738107617aeade79e050d7608004bb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.