repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
jcrist/skein | skein/ui.py | ProxiedPage.address | def address(self):
"""The full proxied address to this page"""
path = urlsplit(self.target).path
suffix = '/' if not path or path.endswith('/') else ''
return '%s%s/%s%s' % (self._ui_address[:-1], self._proxy_prefix,
self.route, suffix) | python | def address(self):
"""The full proxied address to this page"""
path = urlsplit(self.target).path
suffix = '/' if not path or path.endswith('/') else ''
return '%s%s/%s%s' % (self._ui_address[:-1], self._proxy_prefix,
self.route, suffix) | [
"def",
"address",
"(",
"self",
")",
":",
"path",
"=",
"urlsplit",
"(",
"self",
".",
"target",
")",
".",
"path",
"suffix",
"=",
"'/'",
"if",
"not",
"path",
"or",
"path",
".",
"endswith",
"(",
"'/'",
")",
"else",
"''",
"return",
"'%s%s/%s%s'",
"%",
"... | The full proxied address to this page | [
"The",
"full",
"proxied",
"address",
"to",
"this",
"page"
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/ui.py#L43-L48 | train | 210,000 |
jcrist/skein | skein/ui.py | WebUI.add_page | def add_page(self, route, target, link_name=None):
"""Add a new proxied page to the Web UI.
Parameters
----------
route : str
The route for the proxied page. Must be a valid path *segment* in a
url (e.g. ``foo`` in ``/foo/bar/baz``). Routes must be unique
across the application.
target : str
The target address to be proxied to this page. Must be a valid url.
link_name : str, optional
If provided, will be the link text used in the Web UI. If not
provided, the page will still be proxied, but no link will be added
to the Web UI. Link names must be unique across the application.
Returns
-------
ProxiedPage
"""
req = proto.Proxy(route=route, target=target, link_name=link_name)
self._client._call('AddProxy', req)
return ProxiedPage(route, target, link_name, self.address,
self.proxy_prefix) | python | def add_page(self, route, target, link_name=None):
"""Add a new proxied page to the Web UI.
Parameters
----------
route : str
The route for the proxied page. Must be a valid path *segment* in a
url (e.g. ``foo`` in ``/foo/bar/baz``). Routes must be unique
across the application.
target : str
The target address to be proxied to this page. Must be a valid url.
link_name : str, optional
If provided, will be the link text used in the Web UI. If not
provided, the page will still be proxied, but no link will be added
to the Web UI. Link names must be unique across the application.
Returns
-------
ProxiedPage
"""
req = proto.Proxy(route=route, target=target, link_name=link_name)
self._client._call('AddProxy', req)
return ProxiedPage(route, target, link_name, self.address,
self.proxy_prefix) | [
"def",
"add_page",
"(",
"self",
",",
"route",
",",
"target",
",",
"link_name",
"=",
"None",
")",
":",
"req",
"=",
"proto",
".",
"Proxy",
"(",
"route",
"=",
"route",
",",
"target",
"=",
"target",
",",
"link_name",
"=",
"link_name",
")",
"self",
".",
... | Add a new proxied page to the Web UI.
Parameters
----------
route : str
The route for the proxied page. Must be a valid path *segment* in a
url (e.g. ``foo`` in ``/foo/bar/baz``). Routes must be unique
across the application.
target : str
The target address to be proxied to this page. Must be a valid url.
link_name : str, optional
If provided, will be the link text used in the Web UI. If not
provided, the page will still be proxied, but no link will be added
to the Web UI. Link names must be unique across the application.
Returns
-------
ProxiedPage | [
"Add",
"a",
"new",
"proxied",
"page",
"to",
"the",
"Web",
"UI",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/ui.py#L90-L113 | train | 210,001 |
jcrist/skein | skein/ui.py | WebUI.remove_page | def remove_page(self, route):
"""Remove a proxied page from the Web UI.
Parameters
----------
route : str
The route for the proxied page. Must be a valid path *segment* in a
url (e.g. ``foo`` in ``/foo/bar/baz``). Routes must be unique
across the application.
"""
req = proto.RemoveProxyRequest(route=route)
self._client._call('RemoveProxy', req) | python | def remove_page(self, route):
"""Remove a proxied page from the Web UI.
Parameters
----------
route : str
The route for the proxied page. Must be a valid path *segment* in a
url (e.g. ``foo`` in ``/foo/bar/baz``). Routes must be unique
across the application.
"""
req = proto.RemoveProxyRequest(route=route)
self._client._call('RemoveProxy', req) | [
"def",
"remove_page",
"(",
"self",
",",
"route",
")",
":",
"req",
"=",
"proto",
".",
"RemoveProxyRequest",
"(",
"route",
"=",
"route",
")",
"self",
".",
"_client",
".",
"_call",
"(",
"'RemoveProxy'",
",",
"req",
")"
] | Remove a proxied page from the Web UI.
Parameters
----------
route : str
The route for the proxied page. Must be a valid path *segment* in a
url (e.g. ``foo`` in ``/foo/bar/baz``). Routes must be unique
across the application. | [
"Remove",
"a",
"proxied",
"page",
"from",
"the",
"Web",
"UI",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/ui.py#L115-L126 | train | 210,002 |
jcrist/skein | skein/ui.py | WebUI.get_pages | def get_pages(self):
"""Get all registered pages.
Returns
-------
pages : dict
A ``dict`` of ``route`` to ``ProxiedPage`` for all pages.
"""
resp = self._client._call('GetProxies', proto.GetProxiesRequest())
return {i.route: ProxiedPage(i.route, i.target,
i.link_name if i.link_name else None,
self.address, self.proxy_prefix)
for i in resp.proxy} | python | def get_pages(self):
"""Get all registered pages.
Returns
-------
pages : dict
A ``dict`` of ``route`` to ``ProxiedPage`` for all pages.
"""
resp = self._client._call('GetProxies', proto.GetProxiesRequest())
return {i.route: ProxiedPage(i.route, i.target,
i.link_name if i.link_name else None,
self.address, self.proxy_prefix)
for i in resp.proxy} | [
"def",
"get_pages",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_client",
".",
"_call",
"(",
"'GetProxies'",
",",
"proto",
".",
"GetProxiesRequest",
"(",
")",
")",
"return",
"{",
"i",
".",
"route",
":",
"ProxiedPage",
"(",
"i",
".",
"route",
",... | Get all registered pages.
Returns
-------
pages : dict
A ``dict`` of ``route`` to ``ProxiedPage`` for all pages. | [
"Get",
"all",
"registered",
"pages",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/ui.py#L128-L140 | train | 210,003 |
jcrist/skein | examples/echo_server/client.py | tcp_echo_client | async def tcp_echo_client(message, loop, host, port):
"""Generic python tcp echo client"""
print("Connecting to server at %s:%d" % (host, port))
reader, writer = await asyncio.open_connection(host, port, loop=loop)
writer.write(message.encode())
print('Sent: %r' % message)
data = await reader.read(100)
print('Received: %r' % data.decode())
writer.close() | python | async def tcp_echo_client(message, loop, host, port):
"""Generic python tcp echo client"""
print("Connecting to server at %s:%d" % (host, port))
reader, writer = await asyncio.open_connection(host, port, loop=loop)
writer.write(message.encode())
print('Sent: %r' % message)
data = await reader.read(100)
print('Received: %r' % data.decode())
writer.close() | [
"async",
"def",
"tcp_echo_client",
"(",
"message",
",",
"loop",
",",
"host",
",",
"port",
")",
":",
"print",
"(",
"\"Connecting to server at %s:%d\"",
"%",
"(",
"host",
",",
"port",
")",
")",
"reader",
",",
"writer",
"=",
"await",
"asyncio",
".",
"open_con... | Generic python tcp echo client | [
"Generic",
"python",
"tcp",
"echo",
"client"
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/examples/echo_server/client.py#L6-L17 | train | 210,004 |
jcrist/skein | examples/echo_server/client.py | echo_all | async def echo_all(app, message):
"""Send and recieve a message from all running echo servers"""
# Loop through all registered server addresses
for address in app.kv.get_prefix('address.').values():
# Parse the host and port from the stored address
host, port = address.decode().split(':')
port = int(port)
# Send the message to the echo server
await tcp_echo_client(message, loop, host, port) | python | async def echo_all(app, message):
"""Send and recieve a message from all running echo servers"""
# Loop through all registered server addresses
for address in app.kv.get_prefix('address.').values():
# Parse the host and port from the stored address
host, port = address.decode().split(':')
port = int(port)
# Send the message to the echo server
await tcp_echo_client(message, loop, host, port) | [
"async",
"def",
"echo_all",
"(",
"app",
",",
"message",
")",
":",
"# Loop through all registered server addresses",
"for",
"address",
"in",
"app",
".",
"kv",
".",
"get_prefix",
"(",
"'address.'",
")",
".",
"values",
"(",
")",
":",
"# Parse the host and port from t... | Send and recieve a message from all running echo servers | [
"Send",
"and",
"recieve",
"a",
"message",
"from",
"all",
"running",
"echo",
"servers"
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/examples/echo_server/client.py#L20-L29 | train | 210,005 |
jcrist/skein | skein/core.py | Client.from_global_driver | def from_global_driver(self):
"""Connect to the global driver."""
address, _ = _read_driver()
if address is None:
raise DriverNotRunningError("No driver currently running")
security = Security.from_default()
return Client(address=address, security=security) | python | def from_global_driver(self):
"""Connect to the global driver."""
address, _ = _read_driver()
if address is None:
raise DriverNotRunningError("No driver currently running")
security = Security.from_default()
return Client(address=address, security=security) | [
"def",
"from_global_driver",
"(",
"self",
")",
":",
"address",
",",
"_",
"=",
"_read_driver",
"(",
")",
"if",
"address",
"is",
"None",
":",
"raise",
"DriverNotRunningError",
"(",
"\"No driver currently running\"",
")",
"security",
"=",
"Security",
".",
"from_def... | Connect to the global driver. | [
"Connect",
"to",
"the",
"global",
"driver",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L376-L384 | train | 210,006 |
jcrist/skein | skein/core.py | Client.start_global_driver | def start_global_driver(keytab=None, principal=None, log=None,
log_level=None, java_options=None):
"""Start the global driver.
No-op if the global driver is already running.
Parameters
----------
keytab : str, optional
Path to a keytab file to use when starting the driver. If not
provided, the driver will login using the ticket cache instead.
principal : str, optional
The principal to use when starting the driver with a keytab.
log : str, bool, or None, optional
Sets the logging behavior for the driver. Values may be a path for
logs to be written to, ``None`` to log to stdout/stderr, or
``False`` to turn off logging completely. Default is ``None``.
log_level : str or skein.model.LogLevel, optional
The driver log level. Sets the ``skein.log.level`` system property.
One of {'ALL', 'TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL',
'OFF'} (from most to least verbose). Default is 'INFO'.
java_options : str or list of str, optional
Additional Java options to forward to the driver. Can also be
configured by setting the environment variable
``SKEIN_DRIVER_JAVA_OPTIONS``.
Returns
-------
address : str
The address of the driver
"""
address, pid = _read_driver()
if address is not None:
try:
Client(address=address)
return address
except ConnectionError:
if pid_exists(pid):
# PID exists, but we can't connect, reraise
raise
# PID doesn't exist, warn and continue as normal
context.warn("Previous driver at %s, PID %d has died. Restarting."
% (address, pid))
address, _ = _start_driver(set_global=True,
keytab=keytab,
principal=principal,
log=log,
log_level=log_level,
java_options=java_options)
return address | python | def start_global_driver(keytab=None, principal=None, log=None,
log_level=None, java_options=None):
"""Start the global driver.
No-op if the global driver is already running.
Parameters
----------
keytab : str, optional
Path to a keytab file to use when starting the driver. If not
provided, the driver will login using the ticket cache instead.
principal : str, optional
The principal to use when starting the driver with a keytab.
log : str, bool, or None, optional
Sets the logging behavior for the driver. Values may be a path for
logs to be written to, ``None`` to log to stdout/stderr, or
``False`` to turn off logging completely. Default is ``None``.
log_level : str or skein.model.LogLevel, optional
The driver log level. Sets the ``skein.log.level`` system property.
One of {'ALL', 'TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL',
'OFF'} (from most to least verbose). Default is 'INFO'.
java_options : str or list of str, optional
Additional Java options to forward to the driver. Can also be
configured by setting the environment variable
``SKEIN_DRIVER_JAVA_OPTIONS``.
Returns
-------
address : str
The address of the driver
"""
address, pid = _read_driver()
if address is not None:
try:
Client(address=address)
return address
except ConnectionError:
if pid_exists(pid):
# PID exists, but we can't connect, reraise
raise
# PID doesn't exist, warn and continue as normal
context.warn("Previous driver at %s, PID %d has died. Restarting."
% (address, pid))
address, _ = _start_driver(set_global=True,
keytab=keytab,
principal=principal,
log=log,
log_level=log_level,
java_options=java_options)
return address | [
"def",
"start_global_driver",
"(",
"keytab",
"=",
"None",
",",
"principal",
"=",
"None",
",",
"log",
"=",
"None",
",",
"log_level",
"=",
"None",
",",
"java_options",
"=",
"None",
")",
":",
"address",
",",
"pid",
"=",
"_read_driver",
"(",
")",
"if",
"ad... | Start the global driver.
No-op if the global driver is already running.
Parameters
----------
keytab : str, optional
Path to a keytab file to use when starting the driver. If not
provided, the driver will login using the ticket cache instead.
principal : str, optional
The principal to use when starting the driver with a keytab.
log : str, bool, or None, optional
Sets the logging behavior for the driver. Values may be a path for
logs to be written to, ``None`` to log to stdout/stderr, or
``False`` to turn off logging completely. Default is ``None``.
log_level : str or skein.model.LogLevel, optional
The driver log level. Sets the ``skein.log.level`` system property.
One of {'ALL', 'TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL',
'OFF'} (from most to least verbose). Default is 'INFO'.
java_options : str or list of str, optional
Additional Java options to forward to the driver. Can also be
configured by setting the environment variable
``SKEIN_DRIVER_JAVA_OPTIONS``.
Returns
-------
address : str
The address of the driver | [
"Start",
"the",
"global",
"driver",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L387-L437 | train | 210,007 |
jcrist/skein | skein/core.py | Client.stop_global_driver | def stop_global_driver(force=False):
"""Stops the global driver if running.
No-op if no global driver is running.
Parameters
----------
force : bool, optional
By default skein will check that the process associated with the
driver PID is actually a skein driver. Setting ``force`` to
``True`` will kill the process in all cases.
"""
address, pid = _read_driver()
if address is None:
return
if not force:
# Attempt to connect first, errors on failure
try:
Client(address=address)
except ConnectionError:
if pid_exists(pid):
# PID exists, but we can't connect, reraise
raise
# PID doesn't exist, continue cleanup as normal
try:
os.kill(pid, signal.SIGTERM)
except OSError as exc:
# If we're forcing a kill, ignore EPERM as well, as we're not sure
# if the process is a driver.
ignore = (errno.ESRCH, errno.EPERM) if force else (errno.ESRCH,)
if exc.errno not in ignore: # pragma: no cover
raise
try:
os.remove(os.path.join(properties.config_dir, 'driver'))
except OSError: # pragma: no cover
pass | python | def stop_global_driver(force=False):
"""Stops the global driver if running.
No-op if no global driver is running.
Parameters
----------
force : bool, optional
By default skein will check that the process associated with the
driver PID is actually a skein driver. Setting ``force`` to
``True`` will kill the process in all cases.
"""
address, pid = _read_driver()
if address is None:
return
if not force:
# Attempt to connect first, errors on failure
try:
Client(address=address)
except ConnectionError:
if pid_exists(pid):
# PID exists, but we can't connect, reraise
raise
# PID doesn't exist, continue cleanup as normal
try:
os.kill(pid, signal.SIGTERM)
except OSError as exc:
# If we're forcing a kill, ignore EPERM as well, as we're not sure
# if the process is a driver.
ignore = (errno.ESRCH, errno.EPERM) if force else (errno.ESRCH,)
if exc.errno not in ignore: # pragma: no cover
raise
try:
os.remove(os.path.join(properties.config_dir, 'driver'))
except OSError: # pragma: no cover
pass | [
"def",
"stop_global_driver",
"(",
"force",
"=",
"False",
")",
":",
"address",
",",
"pid",
"=",
"_read_driver",
"(",
")",
"if",
"address",
"is",
"None",
":",
"return",
"if",
"not",
"force",
":",
"# Attempt to connect first, errors on failure",
"try",
":",
"Clie... | Stops the global driver if running.
No-op if no global driver is running.
Parameters
----------
force : bool, optional
By default skein will check that the process associated with the
driver PID is actually a skein driver. Setting ``force`` to
``True`` will kill the process in all cases. | [
"Stops",
"the",
"global",
"driver",
"if",
"running",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L440-L477 | train | 210,008 |
jcrist/skein | skein/core.py | Client.close | def close(self):
"""Closes the java driver if started by this client. No-op otherwise."""
if self._proc is not None:
self._proc.stdin.close()
self._proc.wait() | python | def close(self):
"""Closes the java driver if started by this client. No-op otherwise."""
if self._proc is not None:
self._proc.stdin.close()
self._proc.wait() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_proc",
"is",
"not",
"None",
":",
"self",
".",
"_proc",
".",
"stdin",
".",
"close",
"(",
")",
"self",
".",
"_proc",
".",
"wait",
"(",
")"
] | Closes the java driver if started by this client. No-op otherwise. | [
"Closes",
"the",
"java",
"driver",
"if",
"started",
"by",
"this",
"client",
".",
"No",
"-",
"op",
"otherwise",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L482-L486 | train | 210,009 |
jcrist/skein | skein/core.py | Client.submit | def submit(self, spec):
"""Submit a new skein application.
Parameters
----------
spec : ApplicationSpec, str, or dict
A description of the application to run. Can be an
``ApplicationSpec`` object, a path to a yaml/json file, or a
dictionary description of an application specification.
Returns
-------
app_id : str
The id of the submitted application.
"""
spec = ApplicationSpec._from_any(spec)
resp = self._call('submit', spec.to_protobuf())
return resp.id | python | def submit(self, spec):
"""Submit a new skein application.
Parameters
----------
spec : ApplicationSpec, str, or dict
A description of the application to run. Can be an
``ApplicationSpec`` object, a path to a yaml/json file, or a
dictionary description of an application specification.
Returns
-------
app_id : str
The id of the submitted application.
"""
spec = ApplicationSpec._from_any(spec)
resp = self._call('submit', spec.to_protobuf())
return resp.id | [
"def",
"submit",
"(",
"self",
",",
"spec",
")",
":",
"spec",
"=",
"ApplicationSpec",
".",
"_from_any",
"(",
"spec",
")",
"resp",
"=",
"self",
".",
"_call",
"(",
"'submit'",
",",
"spec",
".",
"to_protobuf",
"(",
")",
")",
"return",
"resp",
".",
"id"
] | Submit a new skein application.
Parameters
----------
spec : ApplicationSpec, str, or dict
A description of the application to run. Can be an
``ApplicationSpec`` object, a path to a yaml/json file, or a
dictionary description of an application specification.
Returns
-------
app_id : str
The id of the submitted application. | [
"Submit",
"a",
"new",
"skein",
"application",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L497-L514 | train | 210,010 |
jcrist/skein | skein/core.py | Client.submit_and_connect | def submit_and_connect(self, spec):
"""Submit a new skein application, and wait to connect to it.
If an error occurs before the application connects, the application is
killed.
Parameters
----------
spec : ApplicationSpec, str, or dict
A description of the application to run. Can be an
``ApplicationSpec`` object, a path to a yaml/json file, or a
dictionary description of an application specification.
Returns
-------
app_client : ApplicationClient
"""
spec = ApplicationSpec._from_any(spec)
app_id = self.submit(spec)
try:
return self.connect(app_id, security=spec.master.security)
except BaseException:
self.kill_application(app_id)
raise | python | def submit_and_connect(self, spec):
"""Submit a new skein application, and wait to connect to it.
If an error occurs before the application connects, the application is
killed.
Parameters
----------
spec : ApplicationSpec, str, or dict
A description of the application to run. Can be an
``ApplicationSpec`` object, a path to a yaml/json file, or a
dictionary description of an application specification.
Returns
-------
app_client : ApplicationClient
"""
spec = ApplicationSpec._from_any(spec)
app_id = self.submit(spec)
try:
return self.connect(app_id, security=spec.master.security)
except BaseException:
self.kill_application(app_id)
raise | [
"def",
"submit_and_connect",
"(",
"self",
",",
"spec",
")",
":",
"spec",
"=",
"ApplicationSpec",
".",
"_from_any",
"(",
"spec",
")",
"app_id",
"=",
"self",
".",
"submit",
"(",
"spec",
")",
"try",
":",
"return",
"self",
".",
"connect",
"(",
"app_id",
",... | Submit a new skein application, and wait to connect to it.
If an error occurs before the application connects, the application is
killed.
Parameters
----------
spec : ApplicationSpec, str, or dict
A description of the application to run. Can be an
``ApplicationSpec`` object, a path to a yaml/json file, or a
dictionary description of an application specification.
Returns
-------
app_client : ApplicationClient | [
"Submit",
"a",
"new",
"skein",
"application",
"and",
"wait",
"to",
"connect",
"to",
"it",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L516-L539 | train | 210,011 |
jcrist/skein | skein/core.py | Client.connect | def connect(self, app_id, wait=True, security=None):
"""Connect to a running application.
Parameters
----------
app_id : str
The id of the application.
wait : bool, optional
If true [default], blocks until the application starts. If False,
will raise a ``ApplicationNotRunningError`` immediately if the
application isn't running.
security : Security, optional
The security configuration to use to communicate with the
application master. Defaults to the global configuration.
Returns
-------
app_client : ApplicationClient
Raises
------
ApplicationNotRunningError
If the application isn't running.
"""
if wait:
resp = self._call('waitForStart', proto.Application(id=app_id))
else:
resp = self._call('getStatus', proto.Application(id=app_id))
report = ApplicationReport.from_protobuf(resp)
if report.state is not ApplicationState.RUNNING:
raise ApplicationNotRunningError(
"%s is not running. Application state: "
"%s" % (app_id, report.state))
if security is None:
security = self.security
return ApplicationClient('%s:%d' % (report.host, report.port),
app_id,
security=security) | python | def connect(self, app_id, wait=True, security=None):
"""Connect to a running application.
Parameters
----------
app_id : str
The id of the application.
wait : bool, optional
If true [default], blocks until the application starts. If False,
will raise a ``ApplicationNotRunningError`` immediately if the
application isn't running.
security : Security, optional
The security configuration to use to communicate with the
application master. Defaults to the global configuration.
Returns
-------
app_client : ApplicationClient
Raises
------
ApplicationNotRunningError
If the application isn't running.
"""
if wait:
resp = self._call('waitForStart', proto.Application(id=app_id))
else:
resp = self._call('getStatus', proto.Application(id=app_id))
report = ApplicationReport.from_protobuf(resp)
if report.state is not ApplicationState.RUNNING:
raise ApplicationNotRunningError(
"%s is not running. Application state: "
"%s" % (app_id, report.state))
if security is None:
security = self.security
return ApplicationClient('%s:%d' % (report.host, report.port),
app_id,
security=security) | [
"def",
"connect",
"(",
"self",
",",
"app_id",
",",
"wait",
"=",
"True",
",",
"security",
"=",
"None",
")",
":",
"if",
"wait",
":",
"resp",
"=",
"self",
".",
"_call",
"(",
"'waitForStart'",
",",
"proto",
".",
"Application",
"(",
"id",
"=",
"app_id",
... | Connect to a running application.
Parameters
----------
app_id : str
The id of the application.
wait : bool, optional
If true [default], blocks until the application starts. If False,
will raise a ``ApplicationNotRunningError`` immediately if the
application isn't running.
security : Security, optional
The security configuration to use to communicate with the
application master. Defaults to the global configuration.
Returns
-------
app_client : ApplicationClient
Raises
------
ApplicationNotRunningError
If the application isn't running. | [
"Connect",
"to",
"a",
"running",
"application",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L541-L580 | train | 210,012 |
jcrist/skein | skein/core.py | Client.get_applications | def get_applications(self, states=None, name=None, user=None, queue=None,
started_begin=None, started_end=None,
finished_begin=None, finished_end=None):
"""Get the status of current skein applications.
Parameters
----------
states : sequence of ApplicationState, optional
If provided, applications will be filtered to these application
states. Default is ``['SUBMITTED', 'ACCEPTED', 'RUNNING']``.
name : str, optional
Only select applications with this name.
user : str, optional
Only select applications with this user.
queue : str, optional
Only select applications in this queue.
started_begin : datetime or str, optional
Only select applications that started after this time (inclusive).
Can be either a datetime or a string representation of one. String
representations can use any of the following formats:
- ``YYYY-M-D H:M:S`` (e.g. 2019-4-10 14:50:20)
- ``YYYY-M-D H:M`` (e.g. 2019-4-10 14:50)
- ``YYYY-M-D`` (e.g. 2019-4-10)
- ``H:M:S`` (e.g. 14:50:20, today is used for date)
- ``H:M`` (e.g. 14:50, today is used for date)
started_end : datetime or str, optional
Only select applications that started before this time (inclusive).
Can be either a datetime or a string representation of one.
finished_begin : datetime or str, optional
Only select applications that finished after this time (inclusive).
Can be either a datetime or a string representation of one.
finished_end : datetime or str, optional
Only select applications that finished before this time (inclusive).
Can be either a datetime or a string representation of one.
Returns
-------
reports : list of ApplicationReport
Examples
--------
Get all the finished and failed applications
>>> client.get_applications(states=['FINISHED', 'FAILED'])
[ApplicationReport<name='demo'>,
ApplicationReport<name='dask'>,
ApplicationReport<name='demo'>]
Get all applications named 'demo' started after 2019-4-10:
>>> client.get_applications(name='demo', started_begin='2019-4-10')
[ApplicationReport<name='demo'>,
ApplicationReport<name='demo'>]
"""
if states is not None:
states = tuple(ApplicationState(s) for s in states)
else:
states = (ApplicationState.SUBMITTED,
ApplicationState.ACCEPTED,
ApplicationState.RUNNING)
started_begin = self._parse_datetime(started_begin, 'started_begin')
started_end = self._parse_datetime(started_end, 'started_end')
finished_begin = self._parse_datetime(finished_begin, 'finished_begin')
finished_end = self._parse_datetime(finished_end, 'finished_end')
req = proto.ApplicationsRequest(
states=[str(s) for s in states],
name=name,
user=user,
queue=queue,
started_begin=datetime_to_millis(started_begin),
started_end=datetime_to_millis(started_end),
finished_begin=datetime_to_millis(finished_begin),
finished_end=datetime_to_millis(finished_end)
)
resp = self._call('getApplications', req)
return sorted((ApplicationReport.from_protobuf(r) for r in resp.reports),
key=lambda x: x.id) | python | def get_applications(self, states=None, name=None, user=None, queue=None,
started_begin=None, started_end=None,
finished_begin=None, finished_end=None):
"""Get the status of current skein applications.
Parameters
----------
states : sequence of ApplicationState, optional
If provided, applications will be filtered to these application
states. Default is ``['SUBMITTED', 'ACCEPTED', 'RUNNING']``.
name : str, optional
Only select applications with this name.
user : str, optional
Only select applications with this user.
queue : str, optional
Only select applications in this queue.
started_begin : datetime or str, optional
Only select applications that started after this time (inclusive).
Can be either a datetime or a string representation of one. String
representations can use any of the following formats:
- ``YYYY-M-D H:M:S`` (e.g. 2019-4-10 14:50:20)
- ``YYYY-M-D H:M`` (e.g. 2019-4-10 14:50)
- ``YYYY-M-D`` (e.g. 2019-4-10)
- ``H:M:S`` (e.g. 14:50:20, today is used for date)
- ``H:M`` (e.g. 14:50, today is used for date)
started_end : datetime or str, optional
Only select applications that started before this time (inclusive).
Can be either a datetime or a string representation of one.
finished_begin : datetime or str, optional
Only select applications that finished after this time (inclusive).
Can be either a datetime or a string representation of one.
finished_end : datetime or str, optional
Only select applications that finished before this time (inclusive).
Can be either a datetime or a string representation of one.
Returns
-------
reports : list of ApplicationReport
Examples
--------
Get all the finished and failed applications
>>> client.get_applications(states=['FINISHED', 'FAILED'])
[ApplicationReport<name='demo'>,
ApplicationReport<name='dask'>,
ApplicationReport<name='demo'>]
Get all applications named 'demo' started after 2019-4-10:
>>> client.get_applications(name='demo', started_begin='2019-4-10')
[ApplicationReport<name='demo'>,
ApplicationReport<name='demo'>]
"""
if states is not None:
states = tuple(ApplicationState(s) for s in states)
else:
states = (ApplicationState.SUBMITTED,
ApplicationState.ACCEPTED,
ApplicationState.RUNNING)
started_begin = self._parse_datetime(started_begin, 'started_begin')
started_end = self._parse_datetime(started_end, 'started_end')
finished_begin = self._parse_datetime(finished_begin, 'finished_begin')
finished_end = self._parse_datetime(finished_end, 'finished_end')
req = proto.ApplicationsRequest(
states=[str(s) for s in states],
name=name,
user=user,
queue=queue,
started_begin=datetime_to_millis(started_begin),
started_end=datetime_to_millis(started_end),
finished_begin=datetime_to_millis(finished_begin),
finished_end=datetime_to_millis(finished_end)
)
resp = self._call('getApplications', req)
return sorted((ApplicationReport.from_protobuf(r) for r in resp.reports),
key=lambda x: x.id) | [
"def",
"get_applications",
"(",
"self",
",",
"states",
"=",
"None",
",",
"name",
"=",
"None",
",",
"user",
"=",
"None",
",",
"queue",
"=",
"None",
",",
"started_begin",
"=",
"None",
",",
"started_end",
"=",
"None",
",",
"finished_begin",
"=",
"None",
"... | Get the status of current skein applications.
Parameters
----------
states : sequence of ApplicationState, optional
If provided, applications will be filtered to these application
states. Default is ``['SUBMITTED', 'ACCEPTED', 'RUNNING']``.
name : str, optional
Only select applications with this name.
user : str, optional
Only select applications with this user.
queue : str, optional
Only select applications in this queue.
started_begin : datetime or str, optional
Only select applications that started after this time (inclusive).
Can be either a datetime or a string representation of one. String
representations can use any of the following formats:
- ``YYYY-M-D H:M:S`` (e.g. 2019-4-10 14:50:20)
- ``YYYY-M-D H:M`` (e.g. 2019-4-10 14:50)
- ``YYYY-M-D`` (e.g. 2019-4-10)
- ``H:M:S`` (e.g. 14:50:20, today is used for date)
- ``H:M`` (e.g. 14:50, today is used for date)
started_end : datetime or str, optional
Only select applications that started before this time (inclusive).
Can be either a datetime or a string representation of one.
finished_begin : datetime or str, optional
Only select applications that finished after this time (inclusive).
Can be either a datetime or a string representation of one.
finished_end : datetime or str, optional
Only select applications that finished before this time (inclusive).
Can be either a datetime or a string representation of one.
Returns
-------
reports : list of ApplicationReport
Examples
--------
Get all the finished and failed applications
>>> client.get_applications(states=['FINISHED', 'FAILED'])
[ApplicationReport<name='demo'>,
ApplicationReport<name='dask'>,
ApplicationReport<name='demo'>]
Get all applications named 'demo' started after 2019-4-10:
>>> client.get_applications(name='demo', started_begin='2019-4-10')
[ApplicationReport<name='demo'>,
ApplicationReport<name='demo'>] | [
"Get",
"the",
"status",
"of",
"current",
"skein",
"applications",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L607-L687 | train | 210,013 |
jcrist/skein | skein/core.py | Client.get_nodes | def get_nodes(self, states=None):
"""Get the status of nodes in the cluster.
Parameters
----------
states : sequence of NodeState, optional
If provided, nodes will be filtered to these node states. Default
is all states.
Returns
-------
reports : list of NodeReport
Examples
--------
Get all the running nodes
>>> client.get_nodes(states=['RUNNING'])
[NodeReport<id='worker1.example.com:34721'>,
NodeReport<id='worker2.example.com:34721'>]
"""
if states is not None:
states = tuple(NodeState(s) for s in states)
else:
states = ()
req = proto.NodesRequest(states=[str(s) for s in states])
resp = self._call('getNodes', req)
return sorted((NodeReport.from_protobuf(r) for r in resp.reports),
key=lambda x: x.id) | python | def get_nodes(self, states=None):
"""Get the status of nodes in the cluster.
Parameters
----------
states : sequence of NodeState, optional
If provided, nodes will be filtered to these node states. Default
is all states.
Returns
-------
reports : list of NodeReport
Examples
--------
Get all the running nodes
>>> client.get_nodes(states=['RUNNING'])
[NodeReport<id='worker1.example.com:34721'>,
NodeReport<id='worker2.example.com:34721'>]
"""
if states is not None:
states = tuple(NodeState(s) for s in states)
else:
states = ()
req = proto.NodesRequest(states=[str(s) for s in states])
resp = self._call('getNodes', req)
return sorted((NodeReport.from_protobuf(r) for r in resp.reports),
key=lambda x: x.id) | [
"def",
"get_nodes",
"(",
"self",
",",
"states",
"=",
"None",
")",
":",
"if",
"states",
"is",
"not",
"None",
":",
"states",
"=",
"tuple",
"(",
"NodeState",
"(",
"s",
")",
"for",
"s",
"in",
"states",
")",
"else",
":",
"states",
"=",
"(",
")",
"req"... | Get the status of nodes in the cluster.
Parameters
----------
states : sequence of NodeState, optional
If provided, nodes will be filtered to these node states. Default
is all states.
Returns
-------
reports : list of NodeReport
Examples
--------
Get all the running nodes
>>> client.get_nodes(states=['RUNNING'])
[NodeReport<id='worker1.example.com:34721'>,
NodeReport<id='worker2.example.com:34721'>] | [
"Get",
"the",
"status",
"of",
"nodes",
"in",
"the",
"cluster",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L689-L718 | train | 210,014 |
jcrist/skein | skein/core.py | Client.get_queue | def get_queue(self, name):
"""Get information about a queue.
Parameters
----------
name : str
The queue name.
Returns
-------
queue : Queue
Examples
--------
>>> client.get_queue('myqueue')
Queue<name='myqueue', percent_used=5.00>
"""
req = proto.QueueRequest(name=name)
resp = self._call('getQueue', req)
return Queue.from_protobuf(resp) | python | def get_queue(self, name):
"""Get information about a queue.
Parameters
----------
name : str
The queue name.
Returns
-------
queue : Queue
Examples
--------
>>> client.get_queue('myqueue')
Queue<name='myqueue', percent_used=5.00>
"""
req = proto.QueueRequest(name=name)
resp = self._call('getQueue', req)
return Queue.from_protobuf(resp) | [
"def",
"get_queue",
"(",
"self",
",",
"name",
")",
":",
"req",
"=",
"proto",
".",
"QueueRequest",
"(",
"name",
"=",
"name",
")",
"resp",
"=",
"self",
".",
"_call",
"(",
"'getQueue'",
",",
"req",
")",
"return",
"Queue",
".",
"from_protobuf",
"(",
"res... | Get information about a queue.
Parameters
----------
name : str
The queue name.
Returns
-------
queue : Queue
Examples
--------
>>> client.get_queue('myqueue')
Queue<name='myqueue', percent_used=5.00> | [
"Get",
"information",
"about",
"a",
"queue",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L720-L739 | train | 210,015 |
jcrist/skein | skein/core.py | Client.get_child_queues | def get_child_queues(self, name):
"""Get information about all children of a parent queue.
Parameters
----------
name : str
The parent queue name.
Returns
-------
queues : list of Queue
Examples
--------
>>> client.get_child_queues('myqueue')
[Queue<name='child1', percent_used=10.00>,
Queue<name='child2', percent_used=0.00>]
"""
req = proto.QueueRequest(name=name)
resp = self._call('getChildQueues', req)
return [Queue.from_protobuf(q) for q in resp.queues] | python | def get_child_queues(self, name):
"""Get information about all children of a parent queue.
Parameters
----------
name : str
The parent queue name.
Returns
-------
queues : list of Queue
Examples
--------
>>> client.get_child_queues('myqueue')
[Queue<name='child1', percent_used=10.00>,
Queue<name='child2', percent_used=0.00>]
"""
req = proto.QueueRequest(name=name)
resp = self._call('getChildQueues', req)
return [Queue.from_protobuf(q) for q in resp.queues] | [
"def",
"get_child_queues",
"(",
"self",
",",
"name",
")",
":",
"req",
"=",
"proto",
".",
"QueueRequest",
"(",
"name",
"=",
"name",
")",
"resp",
"=",
"self",
".",
"_call",
"(",
"'getChildQueues'",
",",
"req",
")",
"return",
"[",
"Queue",
".",
"from_prot... | Get information about all children of a parent queue.
Parameters
----------
name : str
The parent queue name.
Returns
-------
queues : list of Queue
Examples
--------
>>> client.get_child_queues('myqueue')
[Queue<name='child1', percent_used=10.00>,
Queue<name='child2', percent_used=0.00>] | [
"Get",
"information",
"about",
"all",
"children",
"of",
"a",
"parent",
"queue",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L741-L761 | train | 210,016 |
jcrist/skein | skein/core.py | Client.get_all_queues | def get_all_queues(self):
"""Get information about all queues in the cluster.
Returns
-------
queues : list of Queue
Examples
--------
>>> client.get_all_queues()
[Queue<name='default', percent_used=0.00>,
Queue<name='myqueue', percent_used=5.00>,
Queue<name='child1', percent_used=10.00>,
Queue<name='child2', percent_used=0.00>]
"""
resp = self._call('getAllQueues', proto.Empty())
return [Queue.from_protobuf(q) for q in resp.queues] | python | def get_all_queues(self):
"""Get information about all queues in the cluster.
Returns
-------
queues : list of Queue
Examples
--------
>>> client.get_all_queues()
[Queue<name='default', percent_used=0.00>,
Queue<name='myqueue', percent_used=5.00>,
Queue<name='child1', percent_used=10.00>,
Queue<name='child2', percent_used=0.00>]
"""
resp = self._call('getAllQueues', proto.Empty())
return [Queue.from_protobuf(q) for q in resp.queues] | [
"def",
"get_all_queues",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_call",
"(",
"'getAllQueues'",
",",
"proto",
".",
"Empty",
"(",
")",
")",
"return",
"[",
"Queue",
".",
"from_protobuf",
"(",
"q",
")",
"for",
"q",
"in",
"resp",
".",
"queues",... | Get information about all queues in the cluster.
Returns
-------
queues : list of Queue
Examples
--------
>>> client.get_all_queues()
[Queue<name='default', percent_used=0.00>,
Queue<name='myqueue', percent_used=5.00>,
Queue<name='child1', percent_used=10.00>,
Queue<name='child2', percent_used=0.00>] | [
"Get",
"information",
"about",
"all",
"queues",
"in",
"the",
"cluster",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L763-L779 | train | 210,017 |
jcrist/skein | skein/core.py | Client.application_report | def application_report(self, app_id):
"""Get a report on the status of a skein application.
Parameters
----------
app_id : str
The id of the application.
Returns
-------
report : ApplicationReport
Examples
--------
>>> client.application_report('application_1526134340424_0012')
ApplicationReport<name='demo'>
"""
resp = self._call('getStatus', proto.Application(id=app_id))
return ApplicationReport.from_protobuf(resp) | python | def application_report(self, app_id):
"""Get a report on the status of a skein application.
Parameters
----------
app_id : str
The id of the application.
Returns
-------
report : ApplicationReport
Examples
--------
>>> client.application_report('application_1526134340424_0012')
ApplicationReport<name='demo'>
"""
resp = self._call('getStatus', proto.Application(id=app_id))
return ApplicationReport.from_protobuf(resp) | [
"def",
"application_report",
"(",
"self",
",",
"app_id",
")",
":",
"resp",
"=",
"self",
".",
"_call",
"(",
"'getStatus'",
",",
"proto",
".",
"Application",
"(",
"id",
"=",
"app_id",
")",
")",
"return",
"ApplicationReport",
".",
"from_protobuf",
"(",
"resp"... | Get a report on the status of a skein application.
Parameters
----------
app_id : str
The id of the application.
Returns
-------
report : ApplicationReport
Examples
--------
>>> client.application_report('application_1526134340424_0012')
ApplicationReport<name='demo'> | [
"Get",
"a",
"report",
"on",
"the",
"status",
"of",
"a",
"skein",
"application",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L781-L799 | train | 210,018 |
jcrist/skein | skein/core.py | Client.move_application | def move_application(self, app_id, queue):
"""Move an application to a different queue.
Parameters
----------
app_id : str
The id of the application to move.
queue : str
The queue to move the application to.
"""
self._call('moveApplication', proto.MoveRequest(id=app_id, queue=queue)) | python | def move_application(self, app_id, queue):
"""Move an application to a different queue.
Parameters
----------
app_id : str
The id of the application to move.
queue : str
The queue to move the application to.
"""
self._call('moveApplication', proto.MoveRequest(id=app_id, queue=queue)) | [
"def",
"move_application",
"(",
"self",
",",
"app_id",
",",
"queue",
")",
":",
"self",
".",
"_call",
"(",
"'moveApplication'",
",",
"proto",
".",
"MoveRequest",
"(",
"id",
"=",
"app_id",
",",
"queue",
"=",
"queue",
")",
")"
] | Move an application to a different queue.
Parameters
----------
app_id : str
The id of the application to move.
queue : str
The queue to move the application to. | [
"Move",
"an",
"application",
"to",
"a",
"different",
"queue",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L801-L811 | train | 210,019 |
jcrist/skein | skein/core.py | Client.kill_application | def kill_application(self, app_id, user=""):
"""Kill an application.
Parameters
----------
app_id : str
The id of the application to kill.
user : str, optional
The user to kill the application as. Requires the current user to
have permissions to proxy as ``user``. Default is the current user.
"""
self._call('kill', proto.KillRequest(id=app_id, user=user)) | python | def kill_application(self, app_id, user=""):
"""Kill an application.
Parameters
----------
app_id : str
The id of the application to kill.
user : str, optional
The user to kill the application as. Requires the current user to
have permissions to proxy as ``user``. Default is the current user.
"""
self._call('kill', proto.KillRequest(id=app_id, user=user)) | [
"def",
"kill_application",
"(",
"self",
",",
"app_id",
",",
"user",
"=",
"\"\"",
")",
":",
"self",
".",
"_call",
"(",
"'kill'",
",",
"proto",
".",
"KillRequest",
"(",
"id",
"=",
"app_id",
",",
"user",
"=",
"user",
")",
")"
] | Kill an application.
Parameters
----------
app_id : str
The id of the application to kill.
user : str, optional
The user to kill the application as. Requires the current user to
have permissions to proxy as ``user``. Default is the current user. | [
"Kill",
"an",
"application",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L813-L824 | train | 210,020 |
jcrist/skein | skein/core.py | ApplicationClient.shutdown | def shutdown(self, status='SUCCEEDED', diagnostics=None):
"""Shutdown the application.
Stop all running containers and shutdown the application.
Parameters
----------
status : FinalStatus, optional
The final application status. Default is 'SUCCEEDED'.
diagnostics : str, optional
The application exit message, usually used for diagnosing failures.
Can be seen in the YARN Web UI for completed applications under
"diagnostics", as well as the ``diagnostic`` field of
``ApplicationReport`` objects. If not provided, a default will be
used.
"""
req = proto.ShutdownRequest(final_status=str(FinalStatus(status)),
diagnostics=diagnostics)
self._call('shutdown', req) | python | def shutdown(self, status='SUCCEEDED', diagnostics=None):
"""Shutdown the application.
Stop all running containers and shutdown the application.
Parameters
----------
status : FinalStatus, optional
The final application status. Default is 'SUCCEEDED'.
diagnostics : str, optional
The application exit message, usually used for diagnosing failures.
Can be seen in the YARN Web UI for completed applications under
"diagnostics", as well as the ``diagnostic`` field of
``ApplicationReport`` objects. If not provided, a default will be
used.
"""
req = proto.ShutdownRequest(final_status=str(FinalStatus(status)),
diagnostics=diagnostics)
self._call('shutdown', req) | [
"def",
"shutdown",
"(",
"self",
",",
"status",
"=",
"'SUCCEEDED'",
",",
"diagnostics",
"=",
"None",
")",
":",
"req",
"=",
"proto",
".",
"ShutdownRequest",
"(",
"final_status",
"=",
"str",
"(",
"FinalStatus",
"(",
"status",
")",
")",
",",
"diagnostics",
"... | Shutdown the application.
Stop all running containers and shutdown the application.
Parameters
----------
status : FinalStatus, optional
The final application status. Default is 'SUCCEEDED'.
diagnostics : str, optional
The application exit message, usually used for diagnosing failures.
Can be seen in the YARN Web UI for completed applications under
"diagnostics", as well as the ``diagnostic`` field of
``ApplicationReport`` objects. If not provided, a default will be
used. | [
"Shutdown",
"the",
"application",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L855-L873 | train | 210,021 |
jcrist/skein | skein/core.py | ApplicationClient.get_specification | def get_specification(self):
"""Get the specification for the running application.
Returns
-------
spec : ApplicationSpec
"""
resp = self._call('getApplicationSpec', proto.Empty())
return ApplicationSpec.from_protobuf(resp) | python | def get_specification(self):
"""Get the specification for the running application.
Returns
-------
spec : ApplicationSpec
"""
resp = self._call('getApplicationSpec', proto.Empty())
return ApplicationSpec.from_protobuf(resp) | [
"def",
"get_specification",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_call",
"(",
"'getApplicationSpec'",
",",
"proto",
".",
"Empty",
"(",
")",
")",
"return",
"ApplicationSpec",
".",
"from_protobuf",
"(",
"resp",
")"
] | Get the specification for the running application.
Returns
-------
spec : ApplicationSpec | [
"Get",
"the",
"specification",
"for",
"the",
"running",
"application",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L910-L918 | train | 210,022 |
jcrist/skein | skein/core.py | ApplicationClient.scale | def scale(self, service, count=None, delta=None, **kwargs):
"""Scale a service to a requested number of instances.
Adds or removes containers to match the requested number of instances.
The number of instances for the service can be specified either as a
total count or a delta in that count.
When choosing which containers to remove, containers are removed in
order of state (``WAITING``, ``REQUESTED``, ``RUNNING``) followed by
age (oldest to newest).
When specified as a negative ``delta``, if the number of removed
containers is greater than the number of existing containers, all
containers are removed rather than throwing an error. This means that
``app.scale(delta=-1)`` will remove a container if one exists,
otherwise it will do nothing.
Parameters
----------
service : str
The service to scale.
count : int, optional
The number of instances to scale to.
delta : int, optional
The change in number of instances.
Returns
-------
containers : list of Container
A list of containers that were started or stopped.
"""
if 'instances' in kwargs:
count = kwargs.pop('instances')
warnings.warn("instances is deprecated, use count instead")
assert not kwargs
if count is not None and delta is not None:
raise context.ValueError("cannot specify both `count` and `delta`")
elif count is None and delta is None:
raise context.ValueError("must specify either `count` or `delta`")
if count and count < 0:
raise context.ValueError("count must be >= 0")
req = proto.ScaleRequest(service_name=service,
count=count,
delta=delta)
resp = self._call('scale', req)
return [Container.from_protobuf(c) for c in resp.containers] | python | def scale(self, service, count=None, delta=None, **kwargs):
"""Scale a service to a requested number of instances.
Adds or removes containers to match the requested number of instances.
The number of instances for the service can be specified either as a
total count or a delta in that count.
When choosing which containers to remove, containers are removed in
order of state (``WAITING``, ``REQUESTED``, ``RUNNING``) followed by
age (oldest to newest).
When specified as a negative ``delta``, if the number of removed
containers is greater than the number of existing containers, all
containers are removed rather than throwing an error. This means that
``app.scale(delta=-1)`` will remove a container if one exists,
otherwise it will do nothing.
Parameters
----------
service : str
The service to scale.
count : int, optional
The number of instances to scale to.
delta : int, optional
The change in number of instances.
Returns
-------
containers : list of Container
A list of containers that were started or stopped.
"""
if 'instances' in kwargs:
count = kwargs.pop('instances')
warnings.warn("instances is deprecated, use count instead")
assert not kwargs
if count is not None and delta is not None:
raise context.ValueError("cannot specify both `count` and `delta`")
elif count is None and delta is None:
raise context.ValueError("must specify either `count` or `delta`")
if count and count < 0:
raise context.ValueError("count must be >= 0")
req = proto.ScaleRequest(service_name=service,
count=count,
delta=delta)
resp = self._call('scale', req)
return [Container.from_protobuf(c) for c in resp.containers] | [
"def",
"scale",
"(",
"self",
",",
"service",
",",
"count",
"=",
"None",
",",
"delta",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'instances'",
"in",
"kwargs",
":",
"count",
"=",
"kwargs",
".",
"pop",
"(",
"'instances'",
")",
"warnings",
... | Scale a service to a requested number of instances.
Adds or removes containers to match the requested number of instances.
The number of instances for the service can be specified either as a
total count or a delta in that count.
When choosing which containers to remove, containers are removed in
order of state (``WAITING``, ``REQUESTED``, ``RUNNING``) followed by
age (oldest to newest).
When specified as a negative ``delta``, if the number of removed
containers is greater than the number of existing containers, all
containers are removed rather than throwing an error. This means that
``app.scale(delta=-1)`` will remove a container if one exists,
otherwise it will do nothing.
Parameters
----------
service : str
The service to scale.
count : int, optional
The number of instances to scale to.
delta : int, optional
The change in number of instances.
Returns
-------
containers : list of Container
A list of containers that were started or stopped. | [
"Scale",
"a",
"service",
"to",
"a",
"requested",
"number",
"of",
"instances",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L920-L966 | train | 210,023 |
jcrist/skein | skein/core.py | ApplicationClient.set_progress | def set_progress(self, progress):
"""Update the progress for this application.
For applications processing a fixed set of work it may be useful for
diagnostics to set the progress as the application processes.
Progress indicates job progression, and must be a float between 0 and
1. By default the progress is set at 0.1 for its duration, which is a
good default value for applications that don't know their progress,
(e.g. interactive applications).
Parameters
----------
progress : float
The application progress, must be a value between 0 and 1.
"""
if not (0 <= progress <= 1.0):
raise ValueError("progress must be between 0 and 1, got %.3f"
% progress)
self._call('SetProgress', proto.SetProgressRequest(progress=progress)) | python | def set_progress(self, progress):
"""Update the progress for this application.
For applications processing a fixed set of work it may be useful for
diagnostics to set the progress as the application processes.
Progress indicates job progression, and must be a float between 0 and
1. By default the progress is set at 0.1 for its duration, which is a
good default value for applications that don't know their progress,
(e.g. interactive applications).
Parameters
----------
progress : float
The application progress, must be a value between 0 and 1.
"""
if not (0 <= progress <= 1.0):
raise ValueError("progress must be between 0 and 1, got %.3f"
% progress)
self._call('SetProgress', proto.SetProgressRequest(progress=progress)) | [
"def",
"set_progress",
"(",
"self",
",",
"progress",
")",
":",
"if",
"not",
"(",
"0",
"<=",
"progress",
"<=",
"1.0",
")",
":",
"raise",
"ValueError",
"(",
"\"progress must be between 0 and 1, got %.3f\"",
"%",
"progress",
")",
"self",
".",
"_call",
"(",
"'Se... | Update the progress for this application.
For applications processing a fixed set of work it may be useful for
diagnostics to set the progress as the application processes.
Progress indicates job progression, and must be a float between 0 and
1. By default the progress is set at 0.1 for its duration, which is a
good default value for applications that don't know their progress,
(e.g. interactive applications).
Parameters
----------
progress : float
The application progress, must be a value between 0 and 1. | [
"Update",
"the",
"progress",
"for",
"this",
"application",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L968-L987 | train | 210,024 |
jcrist/skein | skein/core.py | ApplicationClient.from_current | def from_current(cls):
"""Create an application client from within a running container.
Useful for connecting to the application master from a running
container in a application.
"""
if properties.application_id is None:
raise context.ValueError("Not running inside a container")
return cls(properties.appmaster_address,
properties.application_id,
security=Security.from_default()) | python | def from_current(cls):
"""Create an application client from within a running container.
Useful for connecting to the application master from a running
container in a application.
"""
if properties.application_id is None:
raise context.ValueError("Not running inside a container")
return cls(properties.appmaster_address,
properties.application_id,
security=Security.from_default()) | [
"def",
"from_current",
"(",
"cls",
")",
":",
"if",
"properties",
".",
"application_id",
"is",
"None",
":",
"raise",
"context",
".",
"ValueError",
"(",
"\"Not running inside a container\"",
")",
"return",
"cls",
"(",
"properties",
".",
"appmaster_address",
",",
"... | Create an application client from within a running container.
Useful for connecting to the application master from a running
container in a application. | [
"Create",
"an",
"application",
"client",
"from",
"within",
"a",
"running",
"container",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L990-L1001 | train | 210,025 |
jcrist/skein | skein/core.py | ApplicationClient.get_containers | def get_containers(self, services=None, states=None):
"""Get information on containers in this application.
Parameters
----------
services : sequence of str, optional
If provided, containers will be filtered to these services.
Default is all services.
states : sequence of ContainerState, optional
If provided, containers will be filtered by these container states.
Default is ``['WAITING', 'REQUESTED', 'RUNNING']``.
Returns
-------
containers : list of Container
"""
if services is not None:
services = set(services)
if states is not None:
states = [str(ContainerState(s)) for s in states]
req = proto.ContainersRequest(services=services, states=states)
resp = self._call('getContainers', req)
return sorted((Container.from_protobuf(c) for c in resp.containers),
key=lambda x: (x.service_name, x.instance)) | python | def get_containers(self, services=None, states=None):
"""Get information on containers in this application.
Parameters
----------
services : sequence of str, optional
If provided, containers will be filtered to these services.
Default is all services.
states : sequence of ContainerState, optional
If provided, containers will be filtered by these container states.
Default is ``['WAITING', 'REQUESTED', 'RUNNING']``.
Returns
-------
containers : list of Container
"""
if services is not None:
services = set(services)
if states is not None:
states = [str(ContainerState(s)) for s in states]
req = proto.ContainersRequest(services=services, states=states)
resp = self._call('getContainers', req)
return sorted((Container.from_protobuf(c) for c in resp.containers),
key=lambda x: (x.service_name, x.instance)) | [
"def",
"get_containers",
"(",
"self",
",",
"services",
"=",
"None",
",",
"states",
"=",
"None",
")",
":",
"if",
"services",
"is",
"not",
"None",
":",
"services",
"=",
"set",
"(",
"services",
")",
"if",
"states",
"is",
"not",
"None",
":",
"states",
"=... | Get information on containers in this application.
Parameters
----------
services : sequence of str, optional
If provided, containers will be filtered to these services.
Default is all services.
states : sequence of ContainerState, optional
If provided, containers will be filtered by these container states.
Default is ``['WAITING', 'REQUESTED', 'RUNNING']``.
Returns
-------
containers : list of Container | [
"Get",
"information",
"on",
"containers",
"in",
"this",
"application",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L1003-L1027 | train | 210,026 |
jcrist/skein | skein/objects.py | ProtobufMessage.from_protobuf | def from_protobuf(cls, msg):
"""Create an instance from a protobuf message."""
if not isinstance(msg, cls._protobuf_cls):
raise TypeError("Expected message of type "
"%r" % cls._protobuf_cls.__name__)
kwargs = {k: getattr(msg, k) for k in cls._get_params()}
return cls(**kwargs) | python | def from_protobuf(cls, msg):
"""Create an instance from a protobuf message."""
if not isinstance(msg, cls._protobuf_cls):
raise TypeError("Expected message of type "
"%r" % cls._protobuf_cls.__name__)
kwargs = {k: getattr(msg, k) for k in cls._get_params()}
return cls(**kwargs) | [
"def",
"from_protobuf",
"(",
"cls",
",",
"msg",
")",
":",
"if",
"not",
"isinstance",
"(",
"msg",
",",
"cls",
".",
"_protobuf_cls",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected message of type \"",
"\"%r\"",
"%",
"cls",
".",
"_protobuf_cls",
".",
"__name_... | Create an instance from a protobuf message. | [
"Create",
"an",
"instance",
"from",
"a",
"protobuf",
"message",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/objects.py#L193-L199 | train | 210,027 |
jcrist/skein | skein/objects.py | ProtobufMessage.to_protobuf | def to_protobuf(self):
"""Convert object to a protobuf message"""
self._validate()
kwargs = {k: _convert(getattr(self, k), 'to_protobuf')
for k in self._get_params()}
return self._protobuf_cls(**kwargs) | python | def to_protobuf(self):
"""Convert object to a protobuf message"""
self._validate()
kwargs = {k: _convert(getattr(self, k), 'to_protobuf')
for k in self._get_params()}
return self._protobuf_cls(**kwargs) | [
"def",
"to_protobuf",
"(",
"self",
")",
":",
"self",
".",
"_validate",
"(",
")",
"kwargs",
"=",
"{",
"k",
":",
"_convert",
"(",
"getattr",
"(",
"self",
",",
"k",
")",
",",
"'to_protobuf'",
")",
"for",
"k",
"in",
"self",
".",
"_get_params",
"(",
")"... | Convert object to a protobuf message | [
"Convert",
"object",
"to",
"a",
"protobuf",
"message"
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/objects.py#L201-L206 | train | 210,028 |
jcrist/skein | skein/objects.py | Specification.to_dict | def to_dict(self, skip_nulls=True):
"""Convert object to a dict"""
self._validate()
out = {}
for k in self._get_params():
val = getattr(self, k)
if not skip_nulls or val is not None:
out[k] = _convert(val, 'to_dict', skip_nulls)
return out | python | def to_dict(self, skip_nulls=True):
"""Convert object to a dict"""
self._validate()
out = {}
for k in self._get_params():
val = getattr(self, k)
if not skip_nulls or val is not None:
out[k] = _convert(val, 'to_dict', skip_nulls)
return out | [
"def",
"to_dict",
"(",
"self",
",",
"skip_nulls",
"=",
"True",
")",
":",
"self",
".",
"_validate",
"(",
")",
"out",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_get_params",
"(",
")",
":",
"val",
"=",
"getattr",
"(",
"self",
",",
"k",
")",
"... | Convert object to a dict | [
"Convert",
"object",
"to",
"a",
"dict"
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/objects.py#L233-L241 | train | 210,029 |
jcrist/skein | skein/objects.py | Specification.to_json | def to_json(self, skip_nulls=True):
"""Convert object to a json string"""
return json.dumps(self.to_dict(skip_nulls=skip_nulls)) | python | def to_json(self, skip_nulls=True):
"""Convert object to a json string"""
return json.dumps(self.to_dict(skip_nulls=skip_nulls)) | [
"def",
"to_json",
"(",
"self",
",",
"skip_nulls",
"=",
"True",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"to_dict",
"(",
"skip_nulls",
"=",
"skip_nulls",
")",
")"
] | Convert object to a json string | [
"Convert",
"object",
"to",
"a",
"json",
"string"
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/objects.py#L243-L245 | train | 210,030 |
jcrist/skein | skein/objects.py | Specification.to_yaml | def to_yaml(self, skip_nulls=True):
"""Convert object to a yaml string"""
return yaml.safe_dump(self.to_dict(skip_nulls=skip_nulls),
default_flow_style=False) | python | def to_yaml(self, skip_nulls=True):
"""Convert object to a yaml string"""
return yaml.safe_dump(self.to_dict(skip_nulls=skip_nulls),
default_flow_style=False) | [
"def",
"to_yaml",
"(",
"self",
",",
"skip_nulls",
"=",
"True",
")",
":",
"return",
"yaml",
".",
"safe_dump",
"(",
"self",
".",
"to_dict",
"(",
"skip_nulls",
"=",
"skip_nulls",
")",
",",
"default_flow_style",
"=",
"False",
")"
] | Convert object to a yaml string | [
"Convert",
"object",
"to",
"a",
"yaml",
"string"
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/objects.py#L247-L250 | train | 210,031 |
jcrist/skein | examples/pricing_dashboard/dashboard.py | build_html | def build_html():
"""Build the html, to be served by IndexHandler"""
source = AjaxDataSource(data_url='./data',
polling_interval=INTERVAL,
method='GET')
# OHLC plot
p = figure(plot_height=400,
title='OHLC',
sizing_mode='scale_width',
tools="xpan,xwheel_zoom,xbox_zoom,reset",
x_axis_type=None,
y_axis_location="right",
y_axis_label="Price ($)")
p.x_range.follow = "end"
p.x_range.follow_interval = 100
p.x_range.range_padding = 0
p.line(x='time', y='average', alpha=0.25, line_width=3, color='black',
source=source)
p.line(x='time', y='ma', alpha=0.8, line_width=2, color='steelblue',
source=source)
p.segment(x0='time', y0='low', x1='time', y1='high', line_width=2,
color='black', source=source)
p.segment(x0='time', y0='open', x1='time', y1='close', line_width=8,
color='color', source=source, alpha=0.8)
# MACD plot
p2 = figure(plot_height=200,
title='MACD',
sizing_mode='scale_width',
x_range=p.x_range,
x_axis_label='Time (s)',
tools="xpan,xwheel_zoom,xbox_zoom,reset",
y_axis_location="right")
p2.line(x='time', y='macd', color='darkred', line_width=2, source=source)
p2.line(x='time', y='macd9', color='navy', line_width=2, source=source)
p2.segment(x0='time', y0=0, x1='time', y1='macdh', line_width=6, color='steelblue',
alpha=0.5, source=source)
# Combine plots together
plot = gridplot([[p], [p2]], toolbar_location="left", plot_width=1000)
# Compose html from plots and template
script, div = components(plot, theme=theme)
html = template.render(resources=CDN.render(), script=script, div=div)
return html | python | def build_html():
"""Build the html, to be served by IndexHandler"""
source = AjaxDataSource(data_url='./data',
polling_interval=INTERVAL,
method='GET')
# OHLC plot
p = figure(plot_height=400,
title='OHLC',
sizing_mode='scale_width',
tools="xpan,xwheel_zoom,xbox_zoom,reset",
x_axis_type=None,
y_axis_location="right",
y_axis_label="Price ($)")
p.x_range.follow = "end"
p.x_range.follow_interval = 100
p.x_range.range_padding = 0
p.line(x='time', y='average', alpha=0.25, line_width=3, color='black',
source=source)
p.line(x='time', y='ma', alpha=0.8, line_width=2, color='steelblue',
source=source)
p.segment(x0='time', y0='low', x1='time', y1='high', line_width=2,
color='black', source=source)
p.segment(x0='time', y0='open', x1='time', y1='close', line_width=8,
color='color', source=source, alpha=0.8)
# MACD plot
p2 = figure(plot_height=200,
title='MACD',
sizing_mode='scale_width',
x_range=p.x_range,
x_axis_label='Time (s)',
tools="xpan,xwheel_zoom,xbox_zoom,reset",
y_axis_location="right")
p2.line(x='time', y='macd', color='darkred', line_width=2, source=source)
p2.line(x='time', y='macd9', color='navy', line_width=2, source=source)
p2.segment(x0='time', y0=0, x1='time', y1='macdh', line_width=6, color='steelblue',
alpha=0.5, source=source)
# Combine plots together
plot = gridplot([[p], [p2]], toolbar_location="left", plot_width=1000)
# Compose html from plots and template
script, div = components(plot, theme=theme)
html = template.render(resources=CDN.render(), script=script, div=div)
return html | [
"def",
"build_html",
"(",
")",
":",
"source",
"=",
"AjaxDataSource",
"(",
"data_url",
"=",
"'./data'",
",",
"polling_interval",
"=",
"INTERVAL",
",",
"method",
"=",
"'GET'",
")",
"# OHLC plot",
"p",
"=",
"figure",
"(",
"plot_height",
"=",
"400",
",",
"titl... | Build the html, to be served by IndexHandler | [
"Build",
"the",
"html",
"to",
"be",
"served",
"by",
"IndexHandler"
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/examples/pricing_dashboard/dashboard.py#L156-L202 | train | 210,032 |
jcrist/skein | examples/pricing_dashboard/dashboard.py | SimulatedPricingData.update | def update(self):
"""Compute the next element in the stream, and update the plot data"""
# Update the simulated pricing data
self.t += 1000 / INTERVAL
self.average *= np.random.lognormal(0, 0.04)
high = self.average * np.exp(np.abs(np.random.gamma(1, 0.03)))
low = self.average / np.exp(np.abs(np.random.gamma(1, 0.03)))
delta = high - low
open = low + delta * np.random.uniform(0.05, 0.95)
close = low + delta * np.random.uniform(0.05, 0.95)
color = "darkgreen" if open < close else "darkred"
for k, point in [('time', self.t),
('average', self.average),
('open', open),
('high', high),
('low', low),
('close', close),
('color', color)]:
self.data[k].append(point)
ema12 = self._ema(self.data['close'], self.kernel12)
ema26 = self._ema(self.data['close'], self.kernel26)
macd = ema12 - ema26
self.data['ma'].append(ema12)
self.data['macd'].append(macd)
macd9 = self._ema(self.data['macd'], self.kernel9)
self.data['macd9'].append(macd9)
self.data['macdh'].append(macd - macd9) | python | def update(self):
"""Compute the next element in the stream, and update the plot data"""
# Update the simulated pricing data
self.t += 1000 / INTERVAL
self.average *= np.random.lognormal(0, 0.04)
high = self.average * np.exp(np.abs(np.random.gamma(1, 0.03)))
low = self.average / np.exp(np.abs(np.random.gamma(1, 0.03)))
delta = high - low
open = low + delta * np.random.uniform(0.05, 0.95)
close = low + delta * np.random.uniform(0.05, 0.95)
color = "darkgreen" if open < close else "darkred"
for k, point in [('time', self.t),
('average', self.average),
('open', open),
('high', high),
('low', low),
('close', close),
('color', color)]:
self.data[k].append(point)
ema12 = self._ema(self.data['close'], self.kernel12)
ema26 = self._ema(self.data['close'], self.kernel26)
macd = ema12 - ema26
self.data['ma'].append(ema12)
self.data['macd'].append(macd)
macd9 = self._ema(self.data['macd'], self.kernel9)
self.data['macd9'].append(macd9)
self.data['macdh'].append(macd - macd9) | [
"def",
"update",
"(",
"self",
")",
":",
"# Update the simulated pricing data",
"self",
".",
"t",
"+=",
"1000",
"/",
"INTERVAL",
"self",
".",
"average",
"*=",
"np",
".",
"random",
".",
"lognormal",
"(",
"0",
",",
"0.04",
")",
"high",
"=",
"self",
".",
"... | Compute the next element in the stream, and update the plot data | [
"Compute",
"the",
"next",
"element",
"in",
"the",
"stream",
"and",
"update",
"the",
"plot",
"data"
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/examples/pricing_dashboard/dashboard.py#L61-L93 | train | 210,033 |
jcrist/skein | skein/model.py | container_instance_from_string | def container_instance_from_string(id):
"""Create a ContainerInstance from an id string"""
try:
service, instance = id.rsplit('_', 1)
instance = int(instance)
except (TypeError, ValueError):
raise context.ValueError("Invalid container id %r" % id)
return _proto.ContainerInstance(service_name=service, instance=instance) | python | def container_instance_from_string(id):
"""Create a ContainerInstance from an id string"""
try:
service, instance = id.rsplit('_', 1)
instance = int(instance)
except (TypeError, ValueError):
raise context.ValueError("Invalid container id %r" % id)
return _proto.ContainerInstance(service_name=service, instance=instance) | [
"def",
"container_instance_from_string",
"(",
"id",
")",
":",
"try",
":",
"service",
",",
"instance",
"=",
"id",
".",
"rsplit",
"(",
"'_'",
",",
"1",
")",
"instance",
"=",
"int",
"(",
"instance",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
... | Create a ContainerInstance from an id string | [
"Create",
"a",
"ContainerInstance",
"from",
"an",
"id",
"string"
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/model.py#L44-L51 | train | 210,034 |
jcrist/skein | skein/model.py | parse_memory | def parse_memory(s):
"""Converts bytes expression to number of mebibytes.
If no unit is specified, ``MiB`` is used."""
if isinstance(s, integer):
out = s
elif isinstance(s, float):
out = math_ceil(s)
elif isinstance(s, string):
s = s.replace(' ', '')
if not s:
raise context.ValueError("Could not interpret %r as a byte unit" % s)
if s[0].isdigit():
for i, c in enumerate(reversed(s)):
if not c.isalpha():
break
index = len(s) - i
prefix = s[:index]
suffix = s[index:]
try:
n = float(prefix)
except ValueError:
raise context.ValueError("Could not interpret %r as a number" % prefix)
else:
n = 1
suffix = s
try:
multiplier = _byte_sizes[suffix.lower()]
except KeyError:
raise context.ValueError("Could not interpret %r as a byte unit" % suffix)
out = math_ceil(n * multiplier / (2 ** 20))
else:
raise context.TypeError("memory must be an integer, got %r"
% type(s).__name__)
if out < 0:
raise context.ValueError("memory must be positive")
return out | python | def parse_memory(s):
"""Converts bytes expression to number of mebibytes.
If no unit is specified, ``MiB`` is used."""
if isinstance(s, integer):
out = s
elif isinstance(s, float):
out = math_ceil(s)
elif isinstance(s, string):
s = s.replace(' ', '')
if not s:
raise context.ValueError("Could not interpret %r as a byte unit" % s)
if s[0].isdigit():
for i, c in enumerate(reversed(s)):
if not c.isalpha():
break
index = len(s) - i
prefix = s[:index]
suffix = s[index:]
try:
n = float(prefix)
except ValueError:
raise context.ValueError("Could not interpret %r as a number" % prefix)
else:
n = 1
suffix = s
try:
multiplier = _byte_sizes[suffix.lower()]
except KeyError:
raise context.ValueError("Could not interpret %r as a byte unit" % suffix)
out = math_ceil(n * multiplier / (2 ** 20))
else:
raise context.TypeError("memory must be an integer, got %r"
% type(s).__name__)
if out < 0:
raise context.ValueError("memory must be positive")
return out | [
"def",
"parse_memory",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"integer",
")",
":",
"out",
"=",
"s",
"elif",
"isinstance",
"(",
"s",
",",
"float",
")",
":",
"out",
"=",
"math_ceil",
"(",
"s",
")",
"elif",
"isinstance",
"(",
"s",
",... | Converts bytes expression to number of mebibytes.
If no unit is specified, ``MiB`` is used. | [
"Converts",
"bytes",
"expression",
"to",
"number",
"of",
"mebibytes",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/model.py#L59-L103 | train | 210,035 |
jcrist/skein | skein/model.py | Security.from_default | def from_default(cls):
"""The default security configuration.
Usually this loads the credentials stored in the configuration
directory (``~/.skein`` by default). If these credentials don't already
exist, new ones will be created.
When run in a YARN container started by Skein, this loads the same
security credentials as used for the current application.
"""
from .core import properties
# Are we in a container started by skein?
if properties.application_id is not None:
if properties.container_dir is not None:
cert_path = os.path.join(properties.container_dir, '.skein.crt')
key_path = os.path.join(properties.container_dir, '.skein.pem')
if os.path.exists(cert_path) and os.path.exists(key_path):
return Security(cert_file=cert_path, key_file=key_path)
raise context.FileNotFoundError(
"Failed to resolve .skein.{crt,pem} in 'LOCAL_DIRS'")
# Try to load from config_dir, and fallback to minting new credentials
try:
return cls.from_directory(properties.config_dir)
except FileNotFoundError:
pass
new = cls.new_credentials()
try:
out = new.to_directory(properties.config_dir)
context.warn("Skein global security credentials not found, "
"writing now to %r." % properties.config_dir)
except FileExistsError:
# Race condition between competing processes, use the credentials
# written by the other process.
out = cls.from_directory(properties.config_dir)
return out | python | def from_default(cls):
"""The default security configuration.
Usually this loads the credentials stored in the configuration
directory (``~/.skein`` by default). If these credentials don't already
exist, new ones will be created.
When run in a YARN container started by Skein, this loads the same
security credentials as used for the current application.
"""
from .core import properties
# Are we in a container started by skein?
if properties.application_id is not None:
if properties.container_dir is not None:
cert_path = os.path.join(properties.container_dir, '.skein.crt')
key_path = os.path.join(properties.container_dir, '.skein.pem')
if os.path.exists(cert_path) and os.path.exists(key_path):
return Security(cert_file=cert_path, key_file=key_path)
raise context.FileNotFoundError(
"Failed to resolve .skein.{crt,pem} in 'LOCAL_DIRS'")
# Try to load from config_dir, and fallback to minting new credentials
try:
return cls.from_directory(properties.config_dir)
except FileNotFoundError:
pass
new = cls.new_credentials()
try:
out = new.to_directory(properties.config_dir)
context.warn("Skein global security credentials not found, "
"writing now to %r." % properties.config_dir)
except FileExistsError:
# Race condition between competing processes, use the credentials
# written by the other process.
out = cls.from_directory(properties.config_dir)
return out | [
"def",
"from_default",
"(",
"cls",
")",
":",
"from",
".",
"core",
"import",
"properties",
"# Are we in a container started by skein?",
"if",
"properties",
".",
"application_id",
"is",
"not",
"None",
":",
"if",
"properties",
".",
"container_dir",
"is",
"not",
"None... | The default security configuration.
Usually this loads the credentials stored in the configuration
directory (``~/.skein`` by default). If these credentials don't already
exist, new ones will be created.
When run in a YARN container started by Skein, this loads the same
security credentials as used for the current application. | [
"The",
"default",
"security",
"configuration",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/model.py#L325-L362 | train | 210,036 |
jcrist/skein | skein/model.py | Security.from_directory | def from_directory(cls, directory):
"""Create a security object from a directory.
Relies on standard names for each file (``skein.crt`` and
``skein.pem``)."""
cert_path = os.path.join(directory, 'skein.crt')
key_path = os.path.join(directory, 'skein.pem')
for path, name in [(cert_path, 'cert'), (key_path, 'key')]:
if not os.path.exists(path):
raise context.FileNotFoundError(
"Security %s file not found at %r" % (name, path)
)
return Security(cert_file=cert_path, key_file=key_path) | python | def from_directory(cls, directory):
"""Create a security object from a directory.
Relies on standard names for each file (``skein.crt`` and
``skein.pem``)."""
cert_path = os.path.join(directory, 'skein.crt')
key_path = os.path.join(directory, 'skein.pem')
for path, name in [(cert_path, 'cert'), (key_path, 'key')]:
if not os.path.exists(path):
raise context.FileNotFoundError(
"Security %s file not found at %r" % (name, path)
)
return Security(cert_file=cert_path, key_file=key_path) | [
"def",
"from_directory",
"(",
"cls",
",",
"directory",
")",
":",
"cert_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'skein.crt'",
")",
"key_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'skein.pem'",
")",
"f... | Create a security object from a directory.
Relies on standard names for each file (``skein.crt`` and
``skein.pem``). | [
"Create",
"a",
"security",
"object",
"from",
"a",
"directory",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/model.py#L365-L377 | train | 210,037 |
jcrist/skein | skein/model.py | Security.to_directory | def to_directory(self, directory, force=False):
"""Write this security object to a directory.
Parameters
----------
directory : str
The directory to write the configuration to.
force : bool, optional
If security credentials already exist at this location, an error
will be raised by default. Set to True to overwrite existing files.
Returns
-------
security : Security
A new security object backed by the written files.
"""
self._validate()
# Create directory if it doesn't exist
makedirs(directory, exist_ok=True)
cert_path = os.path.join(directory, 'skein.crt')
key_path = os.path.join(directory, 'skein.pem')
cert_bytes = self._get_bytes('cert')
key_bytes = self._get_bytes('key')
lock_path = os.path.join(directory, 'skein.lock')
with lock_file(lock_path):
for path, name in [(cert_path, 'skein.crt'), (key_path, 'skein.pem')]:
if os.path.exists(path):
if force:
os.unlink(path)
else:
msg = ("%r file already exists, use `%s` to overwrite" %
(name, '--force' if context.is_cli else 'force'))
raise context.FileExistsError(msg)
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
for path, data in [(cert_path, cert_bytes), (key_path, key_bytes)]:
with os.fdopen(os.open(path, flags, 0o600), 'wb') as fil:
fil.write(data)
return Security(cert_file=cert_path, key_file=key_path) | python | def to_directory(self, directory, force=False):
"""Write this security object to a directory.
Parameters
----------
directory : str
The directory to write the configuration to.
force : bool, optional
If security credentials already exist at this location, an error
will be raised by default. Set to True to overwrite existing files.
Returns
-------
security : Security
A new security object backed by the written files.
"""
self._validate()
# Create directory if it doesn't exist
makedirs(directory, exist_ok=True)
cert_path = os.path.join(directory, 'skein.crt')
key_path = os.path.join(directory, 'skein.pem')
cert_bytes = self._get_bytes('cert')
key_bytes = self._get_bytes('key')
lock_path = os.path.join(directory, 'skein.lock')
with lock_file(lock_path):
for path, name in [(cert_path, 'skein.crt'), (key_path, 'skein.pem')]:
if os.path.exists(path):
if force:
os.unlink(path)
else:
msg = ("%r file already exists, use `%s` to overwrite" %
(name, '--force' if context.is_cli else 'force'))
raise context.FileExistsError(msg)
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
for path, data in [(cert_path, cert_bytes), (key_path, key_bytes)]:
with os.fdopen(os.open(path, flags, 0o600), 'wb') as fil:
fil.write(data)
return Security(cert_file=cert_path, key_file=key_path) | [
"def",
"to_directory",
"(",
"self",
",",
"directory",
",",
"force",
"=",
"False",
")",
":",
"self",
".",
"_validate",
"(",
")",
"# Create directory if it doesn't exist",
"makedirs",
"(",
"directory",
",",
"exist_ok",
"=",
"True",
")",
"cert_path",
"=",
"os",
... | Write this security object to a directory.
Parameters
----------
directory : str
The directory to write the configuration to.
force : bool, optional
If security credentials already exist at this location, an error
will be raised by default. Set to True to overwrite existing files.
Returns
-------
security : Security
A new security object backed by the written files. | [
"Write",
"this",
"security",
"object",
"to",
"a",
"directory",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/model.py#L379-L421 | train | 210,038 |
jcrist/skein | skein/model.py | ApplicationSpec._from_any | def _from_any(cls, spec):
"""Generic creation method for all types accepted as ``spec``"""
if isinstance(spec, str):
spec = cls.from_file(spec)
elif isinstance(spec, dict):
spec = cls.from_dict(spec)
elif not isinstance(spec, cls):
raise context.TypeError("spec must be either an ApplicationSpec, "
"path, or dict, got "
"%s" % type(spec).__name__)
return spec | python | def _from_any(cls, spec):
"""Generic creation method for all types accepted as ``spec``"""
if isinstance(spec, str):
spec = cls.from_file(spec)
elif isinstance(spec, dict):
spec = cls.from_dict(spec)
elif not isinstance(spec, cls):
raise context.TypeError("spec must be either an ApplicationSpec, "
"path, or dict, got "
"%s" % type(spec).__name__)
return spec | [
"def",
"_from_any",
"(",
"cls",
",",
"spec",
")",
":",
"if",
"isinstance",
"(",
"spec",
",",
"str",
")",
":",
"spec",
"=",
"cls",
".",
"from_file",
"(",
"spec",
")",
"elif",
"isinstance",
"(",
"spec",
",",
"dict",
")",
":",
"spec",
"=",
"cls",
".... | Generic creation method for all types accepted as ``spec`` | [
"Generic",
"creation",
"method",
"for",
"all",
"types",
"accepted",
"as",
"spec"
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/model.py#L1244-L1254 | train | 210,039 |
jcrist/skein | skein/model.py | ApplicationSpec.from_file | def from_file(cls, path, format='infer'):
"""Create an instance from a json or yaml file.
Parameters
----------
path : str
The path to the file to load.
format : {'infer', 'json', 'yaml'}, optional
The file format. By default the format is inferred from the file
extension.
"""
format = _infer_format(path, format=format)
origin = os.path.abspath(os.path.dirname(path))
with open(path) as f:
data = f.read()
if format == 'json':
obj = json.loads(data)
else:
obj = yaml.safe_load(data)
return cls.from_dict(obj, _origin=origin) | python | def from_file(cls, path, format='infer'):
"""Create an instance from a json or yaml file.
Parameters
----------
path : str
The path to the file to load.
format : {'infer', 'json', 'yaml'}, optional
The file format. By default the format is inferred from the file
extension.
"""
format = _infer_format(path, format=format)
origin = os.path.abspath(os.path.dirname(path))
with open(path) as f:
data = f.read()
if format == 'json':
obj = json.loads(data)
else:
obj = yaml.safe_load(data)
return cls.from_dict(obj, _origin=origin) | [
"def",
"from_file",
"(",
"cls",
",",
"path",
",",
"format",
"=",
"'infer'",
")",
":",
"format",
"=",
"_infer_format",
"(",
"path",
",",
"format",
"=",
"format",
")",
"origin",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"di... | Create an instance from a json or yaml file.
Parameters
----------
path : str
The path to the file to load.
format : {'infer', 'json', 'yaml'}, optional
The file format. By default the format is inferred from the file
extension. | [
"Create",
"an",
"instance",
"from",
"a",
"json",
"or",
"yaml",
"file",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/model.py#L1296-L1316 | train | 210,040 |
jcrist/skein | skein/model.py | ApplicationSpec.to_file | def to_file(self, path, format='infer', skip_nulls=True):
"""Write object to a file.
Parameters
----------
path : str
The path to the file to load.
format : {'infer', 'json', 'yaml'}, optional
The file format. By default the format is inferred from the file
extension.
skip_nulls : bool, optional
By default null values are skipped in the output. Set to True to
output all fields.
"""
format = _infer_format(path, format=format)
data = getattr(self, 'to_' + format)(skip_nulls=skip_nulls)
with open(path, mode='w') as f:
f.write(data) | python | def to_file(self, path, format='infer', skip_nulls=True):
"""Write object to a file.
Parameters
----------
path : str
The path to the file to load.
format : {'infer', 'json', 'yaml'}, optional
The file format. By default the format is inferred from the file
extension.
skip_nulls : bool, optional
By default null values are skipped in the output. Set to True to
output all fields.
"""
format = _infer_format(path, format=format)
data = getattr(self, 'to_' + format)(skip_nulls=skip_nulls)
with open(path, mode='w') as f:
f.write(data) | [
"def",
"to_file",
"(",
"self",
",",
"path",
",",
"format",
"=",
"'infer'",
",",
"skip_nulls",
"=",
"True",
")",
":",
"format",
"=",
"_infer_format",
"(",
"path",
",",
"format",
"=",
"format",
")",
"data",
"=",
"getattr",
"(",
"self",
",",
"'to_'",
"+... | Write object to a file.
Parameters
----------
path : str
The path to the file to load.
format : {'infer', 'json', 'yaml'}, optional
The file format. By default the format is inferred from the file
extension.
skip_nulls : bool, optional
By default null values are skipped in the output. Set to True to
output all fields. | [
"Write",
"object",
"to",
"a",
"file",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/model.py#L1318-L1335 | train | 210,041 |
jcrist/skein | skein/utils.py | lock_file | def lock_file(path):
"""File based lock on ``path``.
Creates a file based lock. When acquired, other processes or threads are
prevented from acquiring the same lock until it is released.
"""
with _paths_lock:
lock = _paths_to_locks.get(path)
if lock is None:
_paths_to_locks[path] = lock = _FileLock(path)
return lock | python | def lock_file(path):
"""File based lock on ``path``.
Creates a file based lock. When acquired, other processes or threads are
prevented from acquiring the same lock until it is released.
"""
with _paths_lock:
lock = _paths_to_locks.get(path)
if lock is None:
_paths_to_locks[path] = lock = _FileLock(path)
return lock | [
"def",
"lock_file",
"(",
"path",
")",
":",
"with",
"_paths_lock",
":",
"lock",
"=",
"_paths_to_locks",
".",
"get",
"(",
"path",
")",
"if",
"lock",
"is",
"None",
":",
"_paths_to_locks",
"[",
"path",
"]",
"=",
"lock",
"=",
"_FileLock",
"(",
"path",
")",
... | File based lock on ``path``.
Creates a file based lock. When acquired, other processes or threads are
prevented from acquiring the same lock until it is released. | [
"File",
"based",
"lock",
"on",
"path",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/utils.py#L25-L35 | train | 210,042 |
jcrist/skein | skein/utils.py | grpc_fork_support_disabled | def grpc_fork_support_disabled():
"""Temporarily disable fork support in gRPC.
Fork + exec has always been supported, but the recent fork handling code in
gRPC (>= 1.15) results in extraneous error logs currently. For now we
explicitly disable fork support for gRPC clients we create.
"""
if LooseVersion(GRPC_VERSION) < '1.18.0':
key = 'GRPC_ENABLE_FORK_SUPPORT'
try:
os.environ[key] = '0'
yield
finally:
del os.environ[key]
else:
yield | python | def grpc_fork_support_disabled():
"""Temporarily disable fork support in gRPC.
Fork + exec has always been supported, but the recent fork handling code in
gRPC (>= 1.15) results in extraneous error logs currently. For now we
explicitly disable fork support for gRPC clients we create.
"""
if LooseVersion(GRPC_VERSION) < '1.18.0':
key = 'GRPC_ENABLE_FORK_SUPPORT'
try:
os.environ[key] = '0'
yield
finally:
del os.environ[key]
else:
yield | [
"def",
"grpc_fork_support_disabled",
"(",
")",
":",
"if",
"LooseVersion",
"(",
"GRPC_VERSION",
")",
"<",
"'1.18.0'",
":",
"key",
"=",
"'GRPC_ENABLE_FORK_SUPPORT'",
"try",
":",
"os",
".",
"environ",
"[",
"key",
"]",
"=",
"'0'",
"yield",
"finally",
":",
"del",... | Temporarily disable fork support in gRPC.
Fork + exec has always been supported, but the recent fork handling code in
gRPC (>= 1.15) results in extraneous error logs currently. For now we
explicitly disable fork support for gRPC clients we create. | [
"Temporarily",
"disable",
"fork",
"support",
"in",
"gRPC",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/utils.py#L84-L99 | train | 210,043 |
jcrist/skein | skein/utils.py | humanize_timedelta | def humanize_timedelta(td):
"""Pretty-print a timedelta in a human readable format."""
secs = int(td.total_seconds())
hours, secs = divmod(secs, 60 * 60)
mins, secs = divmod(secs, 60)
if hours:
return '%dh %dm' % (hours, mins)
if mins:
return '%dm' % mins
return '%ds' % secs | python | def humanize_timedelta(td):
"""Pretty-print a timedelta in a human readable format."""
secs = int(td.total_seconds())
hours, secs = divmod(secs, 60 * 60)
mins, secs = divmod(secs, 60)
if hours:
return '%dh %dm' % (hours, mins)
if mins:
return '%dm' % mins
return '%ds' % secs | [
"def",
"humanize_timedelta",
"(",
"td",
")",
":",
"secs",
"=",
"int",
"(",
"td",
".",
"total_seconds",
"(",
")",
")",
"hours",
",",
"secs",
"=",
"divmod",
"(",
"secs",
",",
"60",
"*",
"60",
")",
"mins",
",",
"secs",
"=",
"divmod",
"(",
"secs",
",... | Pretty-print a timedelta in a human readable format. | [
"Pretty",
"-",
"print",
"a",
"timedelta",
"in",
"a",
"human",
"readable",
"format",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/utils.py#L129-L138 | train | 210,044 |
jcrist/skein | skein/utils.py | datetime_to_millis | def datetime_to_millis(x):
"""Convert a `datetime.datetime` to milliseconds since the epoch"""
if x is None:
return None
if hasattr(x, 'timestamp'):
# Python >= 3.3
secs = x.timestamp()
elif x.tzinfo is None:
# Timezone naive
secs = (time.mktime((x.year, x.month, x.day,
x.hour, x.minute, x.second,
-1, -1, -1)) + x.microsecond / 1e6)
else:
# Timezone aware
secs = (x - _EPOCH).total_seconds()
return int(secs * 1000) | python | def datetime_to_millis(x):
"""Convert a `datetime.datetime` to milliseconds since the epoch"""
if x is None:
return None
if hasattr(x, 'timestamp'):
# Python >= 3.3
secs = x.timestamp()
elif x.tzinfo is None:
# Timezone naive
secs = (time.mktime((x.year, x.month, x.day,
x.hour, x.minute, x.second,
-1, -1, -1)) + x.microsecond / 1e6)
else:
# Timezone aware
secs = (x - _EPOCH).total_seconds()
return int(secs * 1000) | [
"def",
"datetime_to_millis",
"(",
"x",
")",
":",
"if",
"x",
"is",
"None",
":",
"return",
"None",
"if",
"hasattr",
"(",
"x",
",",
"'timestamp'",
")",
":",
"# Python >= 3.3",
"secs",
"=",
"x",
".",
"timestamp",
"(",
")",
"elif",
"x",
".",
"tzinfo",
"is... | Convert a `datetime.datetime` to milliseconds since the epoch | [
"Convert",
"a",
"datetime",
".",
"datetime",
"to",
"milliseconds",
"since",
"the",
"epoch"
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/utils.py#L151-L166 | train | 210,045 |
jcrist/skein | skein/utils.py | format_table | def format_table(columns, rows):
"""Formats an ascii table for given columns and rows.
Parameters
----------
columns : list
The column names
rows : list of tuples
The rows in the table. Each tuple must be the same length as
``columns``.
"""
rows = [tuple(str(i) for i in r) for r in rows]
columns = tuple(str(i).upper() for i in columns)
if rows:
widths = tuple(max(max(map(len, x)), len(c))
for x, c in zip(zip(*rows), columns))
else:
widths = tuple(map(len, columns))
row_template = (' '.join('%%-%ds' for _ in columns)) % widths
header = (row_template % tuple(columns)).strip()
if rows:
data = '\n'.join((row_template % r).strip() for r in rows)
return '\n'.join([header, data])
else:
return header | python | def format_table(columns, rows):
"""Formats an ascii table for given columns and rows.
Parameters
----------
columns : list
The column names
rows : list of tuples
The rows in the table. Each tuple must be the same length as
``columns``.
"""
rows = [tuple(str(i) for i in r) for r in rows]
columns = tuple(str(i).upper() for i in columns)
if rows:
widths = tuple(max(max(map(len, x)), len(c))
for x, c in zip(zip(*rows), columns))
else:
widths = tuple(map(len, columns))
row_template = (' '.join('%%-%ds' for _ in columns)) % widths
header = (row_template % tuple(columns)).strip()
if rows:
data = '\n'.join((row_template % r).strip() for r in rows)
return '\n'.join([header, data])
else:
return header | [
"def",
"format_table",
"(",
"columns",
",",
"rows",
")",
":",
"rows",
"=",
"[",
"tuple",
"(",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"r",
")",
"for",
"r",
"in",
"rows",
"]",
"columns",
"=",
"tuple",
"(",
"str",
"(",
"i",
")",
".",
"upper",
"... | Formats an ascii table for given columns and rows.
Parameters
----------
columns : list
The column names
rows : list of tuples
The rows in the table. Each tuple must be the same length as
``columns``. | [
"Formats",
"an",
"ascii",
"table",
"for",
"given",
"columns",
"and",
"rows",
"."
] | 16f8b1d3b3d9f79f36e2f152e45893339a1793e8 | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/utils.py#L177-L201 | train | 210,046 |
applegrew/django-select2 | django_select2/forms.py | Select2Mixin.build_attrs | def build_attrs(self, *args, **kwargs):
"""Add select2 data attributes."""
attrs = super(Select2Mixin, self).build_attrs(*args, **kwargs)
if self.is_required:
attrs.setdefault('data-allow-clear', 'false')
else:
attrs.setdefault('data-allow-clear', 'true')
attrs.setdefault('data-placeholder', '')
attrs.setdefault('data-minimum-input-length', 0)
if 'class' in attrs:
attrs['class'] += ' django-select2'
else:
attrs['class'] = 'django-select2'
return attrs | python | def build_attrs(self, *args, **kwargs):
"""Add select2 data attributes."""
attrs = super(Select2Mixin, self).build_attrs(*args, **kwargs)
if self.is_required:
attrs.setdefault('data-allow-clear', 'false')
else:
attrs.setdefault('data-allow-clear', 'true')
attrs.setdefault('data-placeholder', '')
attrs.setdefault('data-minimum-input-length', 0)
if 'class' in attrs:
attrs['class'] += ' django-select2'
else:
attrs['class'] = 'django-select2'
return attrs | [
"def",
"build_attrs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"attrs",
"=",
"super",
"(",
"Select2Mixin",
",",
"self",
")",
".",
"build_attrs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"is_require... | Add select2 data attributes. | [
"Add",
"select2",
"data",
"attributes",
"."
] | 2bb6f3a9740a368e486e1ea01ff553d2d1954241 | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/forms.py#L73-L87 | train | 210,047 |
applegrew/django-select2 | django_select2/forms.py | Select2Mixin.optgroups | def optgroups(self, name, value, attrs=None):
"""Add empty option for clearable selects."""
if not self.is_required and not self.allow_multiple_selected:
self.choices = list(chain([('', '')], self.choices))
return super(Select2Mixin, self).optgroups(name, value, attrs=attrs) | python | def optgroups(self, name, value, attrs=None):
"""Add empty option for clearable selects."""
if not self.is_required and not self.allow_multiple_selected:
self.choices = list(chain([('', '')], self.choices))
return super(Select2Mixin, self).optgroups(name, value, attrs=attrs) | [
"def",
"optgroups",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_required",
"and",
"not",
"self",
".",
"allow_multiple_selected",
":",
"self",
".",
"choices",
"=",
"list",
"(",
"chain",
"(",... | Add empty option for clearable selects. | [
"Add",
"empty",
"option",
"for",
"clearable",
"selects",
"."
] | 2bb6f3a9740a368e486e1ea01ff553d2d1954241 | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/forms.py#L89-L93 | train | 210,048 |
applegrew/django-select2 | django_select2/forms.py | Select2Mixin._get_media | def _get_media(self):
"""
Construct Media as a dynamic property.
.. Note:: For more information visit
https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property
"""
lang = get_language()
select2_js = (settings.SELECT2_JS,) if settings.SELECT2_JS else ()
select2_css = (settings.SELECT2_CSS,) if settings.SELECT2_CSS else ()
i18n_name = SELECT2_TRANSLATIONS.get(lang)
if i18n_name not in settings.SELECT2_I18N_AVAILABLE_LANGUAGES:
i18n_name = None
i18n_file = ('%s/%s.js' % (settings.SELECT2_I18N_PATH, i18n_name),) if i18n_name else ()
return forms.Media(
js=select2_js + i18n_file + ('django_select2/django_select2.js',),
css={'screen': select2_css}
) | python | def _get_media(self):
"""
Construct Media as a dynamic property.
.. Note:: For more information visit
https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property
"""
lang = get_language()
select2_js = (settings.SELECT2_JS,) if settings.SELECT2_JS else ()
select2_css = (settings.SELECT2_CSS,) if settings.SELECT2_CSS else ()
i18n_name = SELECT2_TRANSLATIONS.get(lang)
if i18n_name not in settings.SELECT2_I18N_AVAILABLE_LANGUAGES:
i18n_name = None
i18n_file = ('%s/%s.js' % (settings.SELECT2_I18N_PATH, i18n_name),) if i18n_name else ()
return forms.Media(
js=select2_js + i18n_file + ('django_select2/django_select2.js',),
css={'screen': select2_css}
) | [
"def",
"_get_media",
"(",
"self",
")",
":",
"lang",
"=",
"get_language",
"(",
")",
"select2_js",
"=",
"(",
"settings",
".",
"SELECT2_JS",
",",
")",
"if",
"settings",
".",
"SELECT2_JS",
"else",
"(",
")",
"select2_css",
"=",
"(",
"settings",
".",
"SELECT2_... | Construct Media as a dynamic property.
.. Note:: For more information visit
https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property | [
"Construct",
"Media",
"as",
"a",
"dynamic",
"property",
"."
] | 2bb6f3a9740a368e486e1ea01ff553d2d1954241 | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/forms.py#L95-L115 | train | 210,049 |
applegrew/django-select2 | django_select2/forms.py | Select2TagMixin.build_attrs | def build_attrs(self, *args, **kwargs):
"""Add select2's tag attributes."""
self.attrs.setdefault('data-minimum-input-length', 1)
self.attrs.setdefault('data-tags', 'true')
self.attrs.setdefault('data-token-separators', '[",", " "]')
return super(Select2TagMixin, self).build_attrs(*args, **kwargs) | python | def build_attrs(self, *args, **kwargs):
"""Add select2's tag attributes."""
self.attrs.setdefault('data-minimum-input-length', 1)
self.attrs.setdefault('data-tags', 'true')
self.attrs.setdefault('data-token-separators', '[",", " "]')
return super(Select2TagMixin, self).build_attrs(*args, **kwargs) | [
"def",
"build_attrs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"attrs",
".",
"setdefault",
"(",
"'data-minimum-input-length'",
",",
"1",
")",
"self",
".",
"attrs",
".",
"setdefault",
"(",
"'data-tags'",
",",
"'true'"... | Add select2's tag attributes. | [
"Add",
"select2",
"s",
"tag",
"attributes",
"."
] | 2bb6f3a9740a368e486e1ea01ff553d2d1954241 | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/forms.py#L123-L128 | train | 210,050 |
applegrew/django-select2 | django_select2/forms.py | HeavySelect2Mixin.build_attrs | def build_attrs(self, *args, **kwargs):
"""Set select2's AJAX attributes."""
attrs = super(HeavySelect2Mixin, self).build_attrs(*args, **kwargs)
# encrypt instance Id
self.widget_id = signing.dumps(id(self))
attrs['data-field_id'] = self.widget_id
attrs.setdefault('data-ajax--url', self.get_url())
attrs.setdefault('data-ajax--cache', "true")
attrs.setdefault('data-ajax--type', "GET")
attrs.setdefault('data-minimum-input-length', 2)
if self.dependent_fields:
attrs.setdefault('data-select2-dependent-fields', " ".join(self.dependent_fields))
attrs['class'] += ' django-select2-heavy'
return attrs | python | def build_attrs(self, *args, **kwargs):
"""Set select2's AJAX attributes."""
attrs = super(HeavySelect2Mixin, self).build_attrs(*args, **kwargs)
# encrypt instance Id
self.widget_id = signing.dumps(id(self))
attrs['data-field_id'] = self.widget_id
attrs.setdefault('data-ajax--url', self.get_url())
attrs.setdefault('data-ajax--cache', "true")
attrs.setdefault('data-ajax--type', "GET")
attrs.setdefault('data-minimum-input-length', 2)
if self.dependent_fields:
attrs.setdefault('data-select2-dependent-fields', " ".join(self.dependent_fields))
attrs['class'] += ' django-select2-heavy'
return attrs | [
"def",
"build_attrs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"attrs",
"=",
"super",
"(",
"HeavySelect2Mixin",
",",
"self",
")",
".",
"build_attrs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# encrypt instance Id",
"sel... | Set select2's AJAX attributes. | [
"Set",
"select2",
"s",
"AJAX",
"attributes",
"."
] | 2bb6f3a9740a368e486e1ea01ff553d2d1954241 | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/forms.py#L229-L245 | train | 210,051 |
applegrew/django-select2 | django_select2/forms.py | HeavySelect2Mixin.render | def render(self, *args, **kwargs):
"""Render widget and register it in Django's cache."""
output = super(HeavySelect2Mixin, self).render(*args, **kwargs)
self.set_to_cache()
return output | python | def render(self, *args, **kwargs):
"""Render widget and register it in Django's cache."""
output = super(HeavySelect2Mixin, self).render(*args, **kwargs)
self.set_to_cache()
return output | [
"def",
"render",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"output",
"=",
"super",
"(",
"HeavySelect2Mixin",
",",
"self",
")",
".",
"render",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"set_to_cache",
"(",
... | Render widget and register it in Django's cache. | [
"Render",
"widget",
"and",
"register",
"it",
"in",
"Django",
"s",
"cache",
"."
] | 2bb6f3a9740a368e486e1ea01ff553d2d1954241 | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/forms.py#L247-L251 | train | 210,052 |
applegrew/django-select2 | django_select2/forms.py | HeavySelect2Mixin.set_to_cache | def set_to_cache(self):
"""
Add widget object to Django's cache.
You may need to overwrite this method, to pickle all information
that is required to serve your JSON response view.
"""
try:
cache.set(self._get_cache_key(), {
'widget': self,
'url': self.get_url(),
})
except (PicklingError, AttributeError):
msg = "You need to overwrite \"set_to_cache\" or ensure that %s is serialisable."
raise NotImplementedError(msg % self.__class__.__name__) | python | def set_to_cache(self):
"""
Add widget object to Django's cache.
You may need to overwrite this method, to pickle all information
that is required to serve your JSON response view.
"""
try:
cache.set(self._get_cache_key(), {
'widget': self,
'url': self.get_url(),
})
except (PicklingError, AttributeError):
msg = "You need to overwrite \"set_to_cache\" or ensure that %s is serialisable."
raise NotImplementedError(msg % self.__class__.__name__) | [
"def",
"set_to_cache",
"(",
"self",
")",
":",
"try",
":",
"cache",
".",
"set",
"(",
"self",
".",
"_get_cache_key",
"(",
")",
",",
"{",
"'widget'",
":",
"self",
",",
"'url'",
":",
"self",
".",
"get_url",
"(",
")",
",",
"}",
")",
"except",
"(",
"Pi... | Add widget object to Django's cache.
You may need to overwrite this method, to pickle all information
that is required to serve your JSON response view. | [
"Add",
"widget",
"object",
"to",
"Django",
"s",
"cache",
"."
] | 2bb6f3a9740a368e486e1ea01ff553d2d1954241 | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/forms.py#L256-L270 | train | 210,053 |
applegrew/django-select2 | django_select2/forms.py | ModelSelect2Mixin.set_to_cache | def set_to_cache(self):
"""
Add widget's attributes to Django's cache.
Split the QuerySet, to not pickle the result set.
"""
queryset = self.get_queryset()
cache.set(self._get_cache_key(), {
'queryset':
[
queryset.none(),
queryset.query,
],
'cls': self.__class__,
'search_fields': tuple(self.search_fields),
'max_results': int(self.max_results),
'url': str(self.get_url()),
'dependent_fields': dict(self.dependent_fields),
}) | python | def set_to_cache(self):
"""
Add widget's attributes to Django's cache.
Split the QuerySet, to not pickle the result set.
"""
queryset = self.get_queryset()
cache.set(self._get_cache_key(), {
'queryset':
[
queryset.none(),
queryset.query,
],
'cls': self.__class__,
'search_fields': tuple(self.search_fields),
'max_results': int(self.max_results),
'url': str(self.get_url()),
'dependent_fields': dict(self.dependent_fields),
}) | [
"def",
"set_to_cache",
"(",
"self",
")",
":",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"cache",
".",
"set",
"(",
"self",
".",
"_get_cache_key",
"(",
")",
",",
"{",
"'queryset'",
":",
"[",
"queryset",
".",
"none",
"(",
")",
",",
"querys... | Add widget's attributes to Django's cache.
Split the QuerySet, to not pickle the result set. | [
"Add",
"widget",
"s",
"attributes",
"to",
"Django",
"s",
"cache",
"."
] | 2bb6f3a9740a368e486e1ea01ff553d2d1954241 | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/forms.py#L350-L368 | train | 210,054 |
applegrew/django-select2 | django_select2/forms.py | ModelSelect2Mixin.filter_queryset | def filter_queryset(self, request, term, queryset=None, **dependent_fields):
"""
Return QuerySet filtered by search_fields matching the passed term.
Args:
request (django.http.request.HttpRequest): The request is being passed from
the JSON view and can be used to dynamically alter the response queryset.
term (str): Search term
queryset (django.db.models.query.QuerySet): QuerySet to select choices from.
**dependent_fields: Dependent fields and their values. If you want to inherit
from ModelSelect2Mixin and later call to this method, be sure to pop
everything from keyword arguments that is not a dependent field.
Returns:
QuerySet: Filtered QuerySet
"""
if queryset is None:
queryset = self.get_queryset()
search_fields = self.get_search_fields()
select = Q()
term = term.replace('\t', ' ')
term = term.replace('\n', ' ')
for t in [t for t in term.split(' ') if not t == '']:
select &= reduce(lambda x, y: x | Q(**{y: t}), search_fields,
Q(**{search_fields[0]: t}))
if dependent_fields:
select &= Q(**dependent_fields)
return queryset.filter(select).distinct() | python | def filter_queryset(self, request, term, queryset=None, **dependent_fields):
"""
Return QuerySet filtered by search_fields matching the passed term.
Args:
request (django.http.request.HttpRequest): The request is being passed from
the JSON view and can be used to dynamically alter the response queryset.
term (str): Search term
queryset (django.db.models.query.QuerySet): QuerySet to select choices from.
**dependent_fields: Dependent fields and their values. If you want to inherit
from ModelSelect2Mixin and later call to this method, be sure to pop
everything from keyword arguments that is not a dependent field.
Returns:
QuerySet: Filtered QuerySet
"""
if queryset is None:
queryset = self.get_queryset()
search_fields = self.get_search_fields()
select = Q()
term = term.replace('\t', ' ')
term = term.replace('\n', ' ')
for t in [t for t in term.split(' ') if not t == '']:
select &= reduce(lambda x, y: x | Q(**{y: t}), search_fields,
Q(**{search_fields[0]: t}))
if dependent_fields:
select &= Q(**dependent_fields)
return queryset.filter(select).distinct() | [
"def",
"filter_queryset",
"(",
"self",
",",
"request",
",",
"term",
",",
"queryset",
"=",
"None",
",",
"*",
"*",
"dependent_fields",
")",
":",
"if",
"queryset",
"is",
"None",
":",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"search_fields",
"... | Return QuerySet filtered by search_fields matching the passed term.
Args:
request (django.http.request.HttpRequest): The request is being passed from
the JSON view and can be used to dynamically alter the response queryset.
term (str): Search term
queryset (django.db.models.query.QuerySet): QuerySet to select choices from.
**dependent_fields: Dependent fields and their values. If you want to inherit
from ModelSelect2Mixin and later call to this method, be sure to pop
everything from keyword arguments that is not a dependent field.
Returns:
QuerySet: Filtered QuerySet | [
"Return",
"QuerySet",
"filtered",
"by",
"search_fields",
"matching",
"the",
"passed",
"term",
"."
] | 2bb6f3a9740a368e486e1ea01ff553d2d1954241 | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/forms.py#L370-L399 | train | 210,055 |
applegrew/django-select2 | django_select2/forms.py | ModelSelect2Mixin.get_search_fields | def get_search_fields(self):
"""Return list of lookup names."""
if self.search_fields:
return self.search_fields
raise NotImplementedError('%s, must implement "search_fields".' % self.__class__.__name__) | python | def get_search_fields(self):
"""Return list of lookup names."""
if self.search_fields:
return self.search_fields
raise NotImplementedError('%s, must implement "search_fields".' % self.__class__.__name__) | [
"def",
"get_search_fields",
"(",
"self",
")",
":",
"if",
"self",
".",
"search_fields",
":",
"return",
"self",
".",
"search_fields",
"raise",
"NotImplementedError",
"(",
"'%s, must implement \"search_fields\".'",
"%",
"self",
".",
"__class__",
".",
"__name__",
")"
] | Return list of lookup names. | [
"Return",
"list",
"of",
"lookup",
"names",
"."
] | 2bb6f3a9740a368e486e1ea01ff553d2d1954241 | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/forms.py#L423-L427 | train | 210,056 |
applegrew/django-select2 | django_select2/forms.py | ModelSelect2Mixin.optgroups | def optgroups(self, name, value, attrs=None):
"""Return only selected options and set QuerySet from `ModelChoicesIterator`."""
default = (None, [], 0)
groups = [default]
has_selected = False
selected_choices = {str(v) for v in value}
if not self.is_required and not self.allow_multiple_selected:
default[1].append(self.create_option(name, '', '', False, 0))
if not isinstance(self.choices, ModelChoiceIterator):
return super(ModelSelect2Mixin, self).optgroups(name, value, attrs=attrs)
selected_choices = {
c for c in selected_choices
if c not in self.choices.field.empty_values
}
field_name = self.choices.field.to_field_name or 'pk'
query = Q(**{'%s__in' % field_name: selected_choices})
for obj in self.choices.queryset.filter(query):
option_value = self.choices.choice(obj)[0]
option_label = self.label_from_instance(obj)
selected = (
str(option_value) in value and
(has_selected is False or self.allow_multiple_selected)
)
if selected is True and has_selected is False:
has_selected = True
index = len(default[1])
subgroup = default[1]
subgroup.append(self.create_option(name, option_value, option_label, selected_choices, index))
return groups | python | def optgroups(self, name, value, attrs=None):
"""Return only selected options and set QuerySet from `ModelChoicesIterator`."""
default = (None, [], 0)
groups = [default]
has_selected = False
selected_choices = {str(v) for v in value}
if not self.is_required and not self.allow_multiple_selected:
default[1].append(self.create_option(name, '', '', False, 0))
if not isinstance(self.choices, ModelChoiceIterator):
return super(ModelSelect2Mixin, self).optgroups(name, value, attrs=attrs)
selected_choices = {
c for c in selected_choices
if c not in self.choices.field.empty_values
}
field_name = self.choices.field.to_field_name or 'pk'
query = Q(**{'%s__in' % field_name: selected_choices})
for obj in self.choices.queryset.filter(query):
option_value = self.choices.choice(obj)[0]
option_label = self.label_from_instance(obj)
selected = (
str(option_value) in value and
(has_selected is False or self.allow_multiple_selected)
)
if selected is True and has_selected is False:
has_selected = True
index = len(default[1])
subgroup = default[1]
subgroup.append(self.create_option(name, option_value, option_label, selected_choices, index))
return groups | [
"def",
"optgroups",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
")",
":",
"default",
"=",
"(",
"None",
",",
"[",
"]",
",",
"0",
")",
"groups",
"=",
"[",
"default",
"]",
"has_selected",
"=",
"False",
"selected_choices",
"=",
"... | Return only selected options and set QuerySet from `ModelChoicesIterator`. | [
"Return",
"only",
"selected",
"options",
"and",
"set",
"QuerySet",
"from",
"ModelChoicesIterator",
"."
] | 2bb6f3a9740a368e486e1ea01ff553d2d1954241 | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/forms.py#L429-L458 | train | 210,057 |
applegrew/django-select2 | django_select2/views.py | AutoResponseView.get_queryset | def get_queryset(self):
"""Get QuerySet from cached widget."""
kwargs = {
model_field_name: self.request.GET.get(form_field_name)
for form_field_name, model_field_name in self.widget.dependent_fields.items()
if form_field_name in self.request.GET and self.request.GET.get(form_field_name, '') != ''
}
return self.widget.filter_queryset(self.request, self.term, self.queryset, **kwargs) | python | def get_queryset(self):
"""Get QuerySet from cached widget."""
kwargs = {
model_field_name: self.request.GET.get(form_field_name)
for form_field_name, model_field_name in self.widget.dependent_fields.items()
if form_field_name in self.request.GET and self.request.GET.get(form_field_name, '') != ''
}
return self.widget.filter_queryset(self.request, self.term, self.queryset, **kwargs) | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"model_field_name",
":",
"self",
".",
"request",
".",
"GET",
".",
"get",
"(",
"form_field_name",
")",
"for",
"form_field_name",
",",
"model_field_name",
"in",
"self",
".",
"widget",
".",
"de... | Get QuerySet from cached widget. | [
"Get",
"QuerySet",
"from",
"cached",
"widget",
"."
] | 2bb6f3a9740a368e486e1ea01ff553d2d1954241 | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/views.py#L50-L57 | train | 210,058 |
applegrew/django-select2 | django_select2/views.py | AutoResponseView.get_widget_or_404 | def get_widget_or_404(self):
"""
Get and return widget from cache.
Raises:
Http404: If if the widget can not be found or no id is provided.
Returns:
ModelSelect2Mixin: Widget from cache.
"""
field_id = self.kwargs.get('field_id', self.request.GET.get('field_id', None))
if not field_id:
raise Http404('No "field_id" provided.')
try:
key = signing.loads(field_id)
except BadSignature:
raise Http404('Invalid "field_id".')
else:
cache_key = '%s%s' % (settings.SELECT2_CACHE_PREFIX, key)
widget_dict = cache.get(cache_key)
if widget_dict is None:
raise Http404('field_id not found')
if widget_dict.pop('url') != self.request.path:
raise Http404('field_id was issued for the view.')
qs, qs.query = widget_dict.pop('queryset')
self.queryset = qs.all()
widget_dict['queryset'] = self.queryset
widget_cls = widget_dict.pop('cls')
return widget_cls(**widget_dict) | python | def get_widget_or_404(self):
"""
Get and return widget from cache.
Raises:
Http404: If if the widget can not be found or no id is provided.
Returns:
ModelSelect2Mixin: Widget from cache.
"""
field_id = self.kwargs.get('field_id', self.request.GET.get('field_id', None))
if not field_id:
raise Http404('No "field_id" provided.')
try:
key = signing.loads(field_id)
except BadSignature:
raise Http404('Invalid "field_id".')
else:
cache_key = '%s%s' % (settings.SELECT2_CACHE_PREFIX, key)
widget_dict = cache.get(cache_key)
if widget_dict is None:
raise Http404('field_id not found')
if widget_dict.pop('url') != self.request.path:
raise Http404('field_id was issued for the view.')
qs, qs.query = widget_dict.pop('queryset')
self.queryset = qs.all()
widget_dict['queryset'] = self.queryset
widget_cls = widget_dict.pop('cls')
return widget_cls(**widget_dict) | [
"def",
"get_widget_or_404",
"(",
"self",
")",
":",
"field_id",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"'field_id'",
",",
"self",
".",
"request",
".",
"GET",
".",
"get",
"(",
"'field_id'",
",",
"None",
")",
")",
"if",
"not",
"field_id",
":",
"ra... | Get and return widget from cache.
Raises:
Http404: If if the widget can not be found or no id is provided.
Returns:
ModelSelect2Mixin: Widget from cache. | [
"Get",
"and",
"return",
"widget",
"from",
"cache",
"."
] | 2bb6f3a9740a368e486e1ea01ff553d2d1954241 | https://github.com/applegrew/django-select2/blob/2bb6f3a9740a368e486e1ea01ff553d2d1954241/django_select2/views.py#L63-L92 | train | 210,059 |
marksweb/django-bleach | django_bleach/forms.py | load_widget | def load_widget(path):
""" Load custom widget for the form field """
i = path.rfind('.')
module, attr = path[:i], path[i + 1:]
try:
mod = import_module(module)
except (ImportError, ValueError) as e:
error_message = 'Error importing widget for BleachField %s: "%s"'
raise ImproperlyConfigured(error_message % (path, e))
try:
cls = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured(
'Module "%s" does not define a "%s" widget' % (module, attr)
)
return cls | python | def load_widget(path):
""" Load custom widget for the form field """
i = path.rfind('.')
module, attr = path[:i], path[i + 1:]
try:
mod = import_module(module)
except (ImportError, ValueError) as e:
error_message = 'Error importing widget for BleachField %s: "%s"'
raise ImproperlyConfigured(error_message % (path, e))
try:
cls = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured(
'Module "%s" does not define a "%s" widget' % (module, attr)
)
return cls | [
"def",
"load_widget",
"(",
"path",
")",
":",
"i",
"=",
"path",
".",
"rfind",
"(",
"'.'",
")",
"module",
",",
"attr",
"=",
"path",
"[",
":",
"i",
"]",
",",
"path",
"[",
"i",
"+",
"1",
":",
"]",
"try",
":",
"mod",
"=",
"import_module",
"(",
"mo... | Load custom widget for the form field | [
"Load",
"custom",
"widget",
"for",
"the",
"form",
"field"
] | 67ee429e783047ced75bc21944f550a805dcdcbc | https://github.com/marksweb/django-bleach/blob/67ee429e783047ced75bc21944f550a805dcdcbc/django_bleach/forms.py#L12-L29 | train | 210,060 |
marksweb/django-bleach | django_bleach/forms.py | get_default_widget | def get_default_widget():
""" Get the default widget or the widget defined in settings """
default_widget = forms.Textarea
if hasattr(settings, 'BLEACH_DEFAULT_WIDGET'):
default_widget = load_widget(settings.BLEACH_DEFAULT_WIDGET)
return default_widget | python | def get_default_widget():
""" Get the default widget or the widget defined in settings """
default_widget = forms.Textarea
if hasattr(settings, 'BLEACH_DEFAULT_WIDGET'):
default_widget = load_widget(settings.BLEACH_DEFAULT_WIDGET)
return default_widget | [
"def",
"get_default_widget",
"(",
")",
":",
"default_widget",
"=",
"forms",
".",
"Textarea",
"if",
"hasattr",
"(",
"settings",
",",
"'BLEACH_DEFAULT_WIDGET'",
")",
":",
"default_widget",
"=",
"load_widget",
"(",
"settings",
".",
"BLEACH_DEFAULT_WIDGET",
")",
"retu... | Get the default widget or the widget defined in settings | [
"Get",
"the",
"default",
"widget",
"or",
"the",
"widget",
"defined",
"in",
"settings"
] | 67ee429e783047ced75bc21944f550a805dcdcbc | https://github.com/marksweb/django-bleach/blob/67ee429e783047ced75bc21944f550a805dcdcbc/django_bleach/forms.py#L32-L37 | train | 210,061 |
marksweb/django-bleach | django_bleach/forms.py | BleachField.to_python | def to_python(self, value):
"""
Strips any dodgy HTML tags from the input
"""
if value in self.empty_values:
try:
return self.empty_value
except AttributeError:
# CharField.empty_value was introduced in Django 1.11; in prior
# versions a unicode string was returned for empty values in
# all cases.
return u''
return bleach.clean(value, **self.bleach_options) | python | def to_python(self, value):
"""
Strips any dodgy HTML tags from the input
"""
if value in self.empty_values:
try:
return self.empty_value
except AttributeError:
# CharField.empty_value was introduced in Django 1.11; in prior
# versions a unicode string was returned for empty values in
# all cases.
return u''
return bleach.clean(value, **self.bleach_options) | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"self",
".",
"empty_values",
":",
"try",
":",
"return",
"self",
".",
"empty_value",
"except",
"AttributeError",
":",
"# CharField.empty_value was introduced in Django 1.11; in prior",
"# v... | Strips any dodgy HTML tags from the input | [
"Strips",
"any",
"dodgy",
"HTML",
"tags",
"from",
"the",
"input"
] | 67ee429e783047ced75bc21944f550a805dcdcbc | https://github.com/marksweb/django-bleach/blob/67ee429e783047ced75bc21944f550a805dcdcbc/django_bleach/forms.py#L66-L78 | train | 210,062 |
getsentry/sentry-plugins | src/sentry_plugins/jira/plugin.py | JiraPlugin.build_dynamic_field | def build_dynamic_field(self, group, field_meta):
"""
Builds a field based on JIRA's meta field information
"""
schema = field_meta['schema']
# set up some defaults for form fields
fieldtype = 'text'
fkwargs = {
'label': field_meta['name'],
'required': field_meta['required'],
}
# override defaults based on field configuration
if (schema['type'] in ['securitylevel', 'priority']
or schema.get('custom') == JIRA_CUSTOM_FIELD_TYPES['select']):
fieldtype = 'select'
fkwargs['choices'] = self.make_choices(field_meta.get('allowedValues'))
elif field_meta.get('autoCompleteUrl') and \
(schema.get('items') == 'user' or schema['type'] == 'user'):
fieldtype = 'select'
sentry_url = '/api/0/issues/%s/plugins/%s/autocomplete' % (group.id, self.slug)
fkwargs['url'] = '%s?jira_url=%s' % (
sentry_url, quote_plus(field_meta['autoCompleteUrl']),
)
fkwargs['has_autocomplete'] = True
fkwargs['placeholder'] = 'Start typing to search for a user'
elif schema['type'] in ['timetracking']:
# TODO: Implement timetracking (currently unsupported alltogether)
return None
elif schema.get('items') in ['worklog', 'attachment']:
# TODO: Implement worklogs and attachments someday
return None
elif schema['type'] == 'array' and schema['items'] != 'string':
fieldtype = 'select'
fkwargs.update(
{
'multiple': True,
'choices': self.make_choices(field_meta.get('allowedValues')),
'default': []
}
)
# break this out, since multiple field types could additionally
# be configured to use a custom property instead of a default.
if schema.get('custom'):
if schema['custom'] == JIRA_CUSTOM_FIELD_TYPES['textarea']:
fieldtype = 'textarea'
fkwargs['type'] = fieldtype
return fkwargs | python | def build_dynamic_field(self, group, field_meta):
"""
Builds a field based on JIRA's meta field information
"""
schema = field_meta['schema']
# set up some defaults for form fields
fieldtype = 'text'
fkwargs = {
'label': field_meta['name'],
'required': field_meta['required'],
}
# override defaults based on field configuration
if (schema['type'] in ['securitylevel', 'priority']
or schema.get('custom') == JIRA_CUSTOM_FIELD_TYPES['select']):
fieldtype = 'select'
fkwargs['choices'] = self.make_choices(field_meta.get('allowedValues'))
elif field_meta.get('autoCompleteUrl') and \
(schema.get('items') == 'user' or schema['type'] == 'user'):
fieldtype = 'select'
sentry_url = '/api/0/issues/%s/plugins/%s/autocomplete' % (group.id, self.slug)
fkwargs['url'] = '%s?jira_url=%s' % (
sentry_url, quote_plus(field_meta['autoCompleteUrl']),
)
fkwargs['has_autocomplete'] = True
fkwargs['placeholder'] = 'Start typing to search for a user'
elif schema['type'] in ['timetracking']:
# TODO: Implement timetracking (currently unsupported alltogether)
return None
elif schema.get('items') in ['worklog', 'attachment']:
# TODO: Implement worklogs and attachments someday
return None
elif schema['type'] == 'array' and schema['items'] != 'string':
fieldtype = 'select'
fkwargs.update(
{
'multiple': True,
'choices': self.make_choices(field_meta.get('allowedValues')),
'default': []
}
)
# break this out, since multiple field types could additionally
# be configured to use a custom property instead of a default.
if schema.get('custom'):
if schema['custom'] == JIRA_CUSTOM_FIELD_TYPES['textarea']:
fieldtype = 'textarea'
fkwargs['type'] = fieldtype
return fkwargs | [
"def",
"build_dynamic_field",
"(",
"self",
",",
"group",
",",
"field_meta",
")",
":",
"schema",
"=",
"field_meta",
"[",
"'schema'",
"]",
"# set up some defaults for form fields",
"fieldtype",
"=",
"'text'",
"fkwargs",
"=",
"{",
"'label'",
":",
"field_meta",
"[",
... | Builds a field based on JIRA's meta field information | [
"Builds",
"a",
"field",
"based",
"on",
"JIRA",
"s",
"meta",
"field",
"information"
] | 2d65331bcb807e0bb16b5e7bdcae56b152bb0dda | https://github.com/getsentry/sentry-plugins/blob/2d65331bcb807e0bb16b5e7bdcae56b152bb0dda/src/sentry_plugins/jira/plugin.py#L71-L120 | train | 210,063 |
getsentry/sentry-plugins | src/sentry_plugins/vsts/plugin.py | VstsPlugin.create_issue | def create_issue(self, request, group, form_data, **kwargs):
"""
Creates the issue on the remote service and returns an issue ID.
"""
instance = self.get_option('instance', group.project)
project = (
form_data.get('project') or
self.get_option('default_project', group.project)
)
client = self.get_client(request.user)
title = form_data['title']
description = form_data['description']
link = absolute_uri(group.get_absolute_url(params={'referrer': 'vsts_plugin'}))
try:
created_item = client.create_work_item(
instance=instance,
project=project,
title=title,
comment=markdown(description),
link=link,
)
except Exception as e:
self.raise_error(e, identity=client.auth)
return {
'id': created_item['id'],
'url': created_item['_links']['html']['href'],
'title': title,
} | python | def create_issue(self, request, group, form_data, **kwargs):
"""
Creates the issue on the remote service and returns an issue ID.
"""
instance = self.get_option('instance', group.project)
project = (
form_data.get('project') or
self.get_option('default_project', group.project)
)
client = self.get_client(request.user)
title = form_data['title']
description = form_data['description']
link = absolute_uri(group.get_absolute_url(params={'referrer': 'vsts_plugin'}))
try:
created_item = client.create_work_item(
instance=instance,
project=project,
title=title,
comment=markdown(description),
link=link,
)
except Exception as e:
self.raise_error(e, identity=client.auth)
return {
'id': created_item['id'],
'url': created_item['_links']['html']['href'],
'title': title,
} | [
"def",
"create_issue",
"(",
"self",
",",
"request",
",",
"group",
",",
"form_data",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"self",
".",
"get_option",
"(",
"'instance'",
",",
"group",
".",
"project",
")",
"project",
"=",
"(",
"form_data",
"... | Creates the issue on the remote service and returns an issue ID. | [
"Creates",
"the",
"issue",
"on",
"the",
"remote",
"service",
"and",
"returns",
"an",
"issue",
"ID",
"."
] | 2d65331bcb807e0bb16b5e7bdcae56b152bb0dda | https://github.com/getsentry/sentry-plugins/blob/2d65331bcb807e0bb16b5e7bdcae56b152bb0dda/src/sentry_plugins/vsts/plugin.py#L102-L132 | train | 210,064 |
Nexmo/nexmo-python | nexmo/__init__.py | _format_date_param | def _format_date_param(params, key, format="%Y-%m-%d %H:%M:%S"):
"""
Utility function to convert datetime values to strings.
If the value is already a str, or is not in the dict, no change is made.
:param params: A `dict` of params that may contain a `datetime` value.
:param key: The datetime value to be converted to a `str`
:param format: The `strftime` format to be used to format the date. The default value is '%Y-%m-%d %H:%M:%S'
"""
if key in params:
param = params[key]
if hasattr(param, "strftime"):
params[key] = param.strftime(format) | python | def _format_date_param(params, key, format="%Y-%m-%d %H:%M:%S"):
"""
Utility function to convert datetime values to strings.
If the value is already a str, or is not in the dict, no change is made.
:param params: A `dict` of params that may contain a `datetime` value.
:param key: The datetime value to be converted to a `str`
:param format: The `strftime` format to be used to format the date. The default value is '%Y-%m-%d %H:%M:%S'
"""
if key in params:
param = params[key]
if hasattr(param, "strftime"):
params[key] = param.strftime(format) | [
"def",
"_format_date_param",
"(",
"params",
",",
"key",
",",
"format",
"=",
"\"%Y-%m-%d %H:%M:%S\"",
")",
":",
"if",
"key",
"in",
"params",
":",
"param",
"=",
"params",
"[",
"key",
"]",
"if",
"hasattr",
"(",
"param",
",",
"\"strftime\"",
")",
":",
"param... | Utility function to convert datetime values to strings.
If the value is already a str, or is not in the dict, no change is made.
:param params: A `dict` of params that may contain a `datetime` value.
:param key: The datetime value to be converted to a `str`
:param format: The `strftime` format to be used to format the date. The default value is '%Y-%m-%d %H:%M:%S' | [
"Utility",
"function",
"to",
"convert",
"datetime",
"values",
"to",
"strings",
"."
] | c5300541233f3dbd7319c7d2ca6d9f7f70404d11 | https://github.com/Nexmo/nexmo-python/blob/c5300541233f3dbd7319c7d2ca6d9f7f70404d11/nexmo/__init__.py#L605-L618 | train | 210,065 |
Nexmo/nexmo-python | nexmo/__init__.py | Client.submit_sms_conversion | def submit_sms_conversion(self, message_id, delivered=True, timestamp=None):
"""
Notify Nexmo that an SMS was successfully received.
:param message_id: The `message-id` str returned by the send_message call.
:param delivered: A `bool` indicating that the message was or was not successfully delivered.
:param timestamp: A `datetime` object containing the time the SMS arrived.
:return: The parsed response from the server. On success, the bytestring b'OK'
"""
params = {
"message-id": message_id,
"delivered": delivered,
"timestamp": timestamp or datetime.now(pytz.utc),
}
# Ensure timestamp is a string:
_format_date_param(params, "timestamp")
return self.post(self.api_host, "/conversions/sms", params) | python | def submit_sms_conversion(self, message_id, delivered=True, timestamp=None):
"""
Notify Nexmo that an SMS was successfully received.
:param message_id: The `message-id` str returned by the send_message call.
:param delivered: A `bool` indicating that the message was or was not successfully delivered.
:param timestamp: A `datetime` object containing the time the SMS arrived.
:return: The parsed response from the server. On success, the bytestring b'OK'
"""
params = {
"message-id": message_id,
"delivered": delivered,
"timestamp": timestamp or datetime.now(pytz.utc),
}
# Ensure timestamp is a string:
_format_date_param(params, "timestamp")
return self.post(self.api_host, "/conversions/sms", params) | [
"def",
"submit_sms_conversion",
"(",
"self",
",",
"message_id",
",",
"delivered",
"=",
"True",
",",
"timestamp",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"message-id\"",
":",
"message_id",
",",
"\"delivered\"",
":",
"delivered",
",",
"\"timestamp\"",
":",
... | Notify Nexmo that an SMS was successfully received.
:param message_id: The `message-id` str returned by the send_message call.
:param delivered: A `bool` indicating that the message was or was not successfully delivered.
:param timestamp: A `datetime` object containing the time the SMS arrived.
:return: The parsed response from the server. On success, the bytestring b'OK' | [
"Notify",
"Nexmo",
"that",
"an",
"SMS",
"was",
"successfully",
"received",
"."
] | c5300541233f3dbd7319c7d2ca6d9f7f70404d11 | https://github.com/Nexmo/nexmo-python/blob/c5300541233f3dbd7319c7d2ca6d9f7f70404d11/nexmo/__init__.py#L172-L188 | train | 210,066 |
mschwager/fierce | fierce/fierce.py | get_stripped_file_lines | def get_stripped_file_lines(filename):
"""
Return lines of a file with whitespace removed
"""
try:
lines = open(filename).readlines()
except FileNotFoundError:
fatal("Could not open file: {!r}".format(filename))
return [line.strip() for line in lines] | python | def get_stripped_file_lines(filename):
"""
Return lines of a file with whitespace removed
"""
try:
lines = open(filename).readlines()
except FileNotFoundError:
fatal("Could not open file: {!r}".format(filename))
return [line.strip() for line in lines] | [
"def",
"get_stripped_file_lines",
"(",
"filename",
")",
":",
"try",
":",
"lines",
"=",
"open",
"(",
"filename",
")",
".",
"readlines",
"(",
")",
"except",
"FileNotFoundError",
":",
"fatal",
"(",
"\"Could not open file: {!r}\"",
".",
"format",
"(",
"filename",
... | Return lines of a file with whitespace removed | [
"Return",
"lines",
"of",
"a",
"file",
"with",
"whitespace",
"removed"
] | 926c5555c3fab9950147a94a848ef9ab34d82587 | https://github.com/mschwager/fierce/blob/926c5555c3fab9950147a94a848ef9ab34d82587/fierce/fierce.py#L238-L247 | train | 210,067 |
FutureSharks/invokust | invokust/settings.py | create_settings | def create_settings(from_environment=False, locustfile=None,
classes=None, host=None, num_clients=None,
hatch_rate=None, reset_stats=False, run_time="3m"):
'''
Returns a settings object to be used by a LocalLocustRunner.
Arguments
from_environment: get settings from environment variables
locustfile: locustfile to use for loadtest
classes: locust classes to use for load test
host: host for load testing
num_clients: number of clients to simulate in load test
hatch_rate: number of clients per second to start
reset_stats: Whether to reset stats after all clients are hatched
run_time: The length of time to run the test for. Cannot exceed the duration limit set by lambda
If from_environment is set to True then this function will attempt to set
the attributes from environment variables. The environment variables are
named LOCUST_ + attribute name in upper case.
'''
settings = type('', (), {})()
settings.from_environment = from_environment
settings.locustfile = locustfile
settings.classes = classes
settings.host = host
settings.num_clients = num_clients
settings.hatch_rate = hatch_rate
settings.reset_stats = reset_stats
settings.run_time = run_time
# Default settings that are not to be changed
settings.no_web = True
settings.master = False
settings.show_task_ratio_json = False
settings.list_commands = False
settings.loglevel = 'INFO'
settings.slave = False
settings.only_summary = True
settings.logfile = None
settings.show_task_ratio = False
settings.print_stats = False
if from_environment:
for attribute in ['locustfile', 'classes', 'host', 'run_time', 'num_clients', 'hatch_rate']:
var_name = 'LOCUST_{0}'.format(attribute.upper())
var_value = os.environ.get(var_name)
if var_value:
setattr(settings, attribute, var_value)
if settings.locustfile is None and settings.classes is None:
raise Exception('One of locustfile or classes must be specified')
if settings.locustfile and settings.classes:
raise Exception('Only one of locustfile or classes can be specified')
if settings.locustfile:
docstring, classes = load_locustfile(settings.locustfile)
settings.classes = [classes[n] for n in classes]
else:
if isinstance(settings.classes, str):
settings.classes = settings.classes.split(',')
for idx, val in enumerate(settings.classes):
# This needs fixing
settings.classes[idx] = eval(val)
for attribute in ['classes', 'host', 'num_clients', 'hatch_rate']:
val = getattr(settings, attribute, None)
if not val:
raise Exception('configuration error, attribute not set: {0}'.format(attribute))
if isinstance(val, str) and val.isdigit():
setattr(settings, attribute, int(val))
return settings | python | def create_settings(from_environment=False, locustfile=None,
classes=None, host=None, num_clients=None,
hatch_rate=None, reset_stats=False, run_time="3m"):
'''
Returns a settings object to be used by a LocalLocustRunner.
Arguments
from_environment: get settings from environment variables
locustfile: locustfile to use for loadtest
classes: locust classes to use for load test
host: host for load testing
num_clients: number of clients to simulate in load test
hatch_rate: number of clients per second to start
reset_stats: Whether to reset stats after all clients are hatched
run_time: The length of time to run the test for. Cannot exceed the duration limit set by lambda
If from_environment is set to True then this function will attempt to set
the attributes from environment variables. The environment variables are
named LOCUST_ + attribute name in upper case.
'''
settings = type('', (), {})()
settings.from_environment = from_environment
settings.locustfile = locustfile
settings.classes = classes
settings.host = host
settings.num_clients = num_clients
settings.hatch_rate = hatch_rate
settings.reset_stats = reset_stats
settings.run_time = run_time
# Default settings that are not to be changed
settings.no_web = True
settings.master = False
settings.show_task_ratio_json = False
settings.list_commands = False
settings.loglevel = 'INFO'
settings.slave = False
settings.only_summary = True
settings.logfile = None
settings.show_task_ratio = False
settings.print_stats = False
if from_environment:
for attribute in ['locustfile', 'classes', 'host', 'run_time', 'num_clients', 'hatch_rate']:
var_name = 'LOCUST_{0}'.format(attribute.upper())
var_value = os.environ.get(var_name)
if var_value:
setattr(settings, attribute, var_value)
if settings.locustfile is None and settings.classes is None:
raise Exception('One of locustfile or classes must be specified')
if settings.locustfile and settings.classes:
raise Exception('Only one of locustfile or classes can be specified')
if settings.locustfile:
docstring, classes = load_locustfile(settings.locustfile)
settings.classes = [classes[n] for n in classes]
else:
if isinstance(settings.classes, str):
settings.classes = settings.classes.split(',')
for idx, val in enumerate(settings.classes):
# This needs fixing
settings.classes[idx] = eval(val)
for attribute in ['classes', 'host', 'num_clients', 'hatch_rate']:
val = getattr(settings, attribute, None)
if not val:
raise Exception('configuration error, attribute not set: {0}'.format(attribute))
if isinstance(val, str) and val.isdigit():
setattr(settings, attribute, int(val))
return settings | [
"def",
"create_settings",
"(",
"from_environment",
"=",
"False",
",",
"locustfile",
"=",
"None",
",",
"classes",
"=",
"None",
",",
"host",
"=",
"None",
",",
"num_clients",
"=",
"None",
",",
"hatch_rate",
"=",
"None",
",",
"reset_stats",
"=",
"False",
",",
... | Returns a settings object to be used by a LocalLocustRunner.
Arguments
from_environment: get settings from environment variables
locustfile: locustfile to use for loadtest
classes: locust classes to use for load test
host: host for load testing
num_clients: number of clients to simulate in load test
hatch_rate: number of clients per second to start
reset_stats: Whether to reset stats after all clients are hatched
run_time: The length of time to run the test for. Cannot exceed the duration limit set by lambda
If from_environment is set to True then this function will attempt to set
the attributes from environment variables. The environment variables are
named LOCUST_ + attribute name in upper case. | [
"Returns",
"a",
"settings",
"object",
"to",
"be",
"used",
"by",
"a",
"LocalLocustRunner",
"."
] | af0830ade8b08ebdd6ec2a0ea3188dee2b123a33 | https://github.com/FutureSharks/invokust/blob/af0830ade8b08ebdd6ec2a0ea3188dee2b123a33/invokust/settings.py#L8-L84 | train | 210,068 |
FutureSharks/invokust | invokust/aws_lambda/runtime_info.py | get_lambda_runtime_info | def get_lambda_runtime_info(context):
'''
Returns a dictionary of information about the AWS Lambda function invocation
Arguments
context: The context object from AWS Lambda.
'''
runtime_info = {
'remaining_time': context.get_remaining_time_in_millis(),
'function_name': context.function_name,
'function_version': context.function_version,
'invoked_function_arn': context.invoked_function_arn,
'memory_limit': context.memory_limit_in_mb,
'aws_request_id': context.aws_request_id,
'log_group_name': context.log_group_name,
'log_stream_name': context.log_stream_name
}
return runtime_info | python | def get_lambda_runtime_info(context):
'''
Returns a dictionary of information about the AWS Lambda function invocation
Arguments
context: The context object from AWS Lambda.
'''
runtime_info = {
'remaining_time': context.get_remaining_time_in_millis(),
'function_name': context.function_name,
'function_version': context.function_version,
'invoked_function_arn': context.invoked_function_arn,
'memory_limit': context.memory_limit_in_mb,
'aws_request_id': context.aws_request_id,
'log_group_name': context.log_group_name,
'log_stream_name': context.log_stream_name
}
return runtime_info | [
"def",
"get_lambda_runtime_info",
"(",
"context",
")",
":",
"runtime_info",
"=",
"{",
"'remaining_time'",
":",
"context",
".",
"get_remaining_time_in_millis",
"(",
")",
",",
"'function_name'",
":",
"context",
".",
"function_name",
",",
"'function_version'",
":",
"co... | Returns a dictionary of information about the AWS Lambda function invocation
Arguments
context: The context object from AWS Lambda. | [
"Returns",
"a",
"dictionary",
"of",
"information",
"about",
"the",
"AWS",
"Lambda",
"function",
"invocation"
] | af0830ade8b08ebdd6ec2a0ea3188dee2b123a33 | https://github.com/FutureSharks/invokust/blob/af0830ade8b08ebdd6ec2a0ea3188dee2b123a33/invokust/aws_lambda/runtime_info.py#L3-L23 | train | 210,069 |
bwohlberg/sporco | sporco/linalg.py | solvedbi_sm | def solvedbi_sm(ah, rho, b, c=None, axis=4):
r"""
Solve a diagonal block linear system with a scaled identity term
using the Sherman-Morrison equation.
The solution is obtained by independently solving a set of linear
systems of the form (see :cite:`wohlberg-2016-efficient`)
.. math::
(\rho I + \mathbf{a} \mathbf{a}^H ) \; \mathbf{x} = \mathbf{b} \;\;.
In this equation inner products and matrix products are taken along
the specified axis of the corresponding multi-dimensional arrays; the
solutions are independent over the other axes.
Parameters
----------
ah : array_like
Linear system component :math:`\mathbf{a}^H`
rho : float
Linear system parameter :math:`\rho`
b : array_like
Linear system component :math:`\mathbf{b}`
c : array_like, optional (default None)
Solution component :math:`\mathbf{c}` that may be pre-computed using
:func:`solvedbi_sm_c` and cached for re-use.
axis : int, optional (default 4)
Axis along which to solve the linear system
Returns
-------
x : ndarray
Linear system solution :math:`\mathbf{x}`
"""
a = np.conj(ah)
if c is None:
c = solvedbi_sm_c(ah, a, rho, axis)
if have_numexpr:
cb = inner(c, b, axis=axis)
return ne.evaluate('(b - (a * cb)) / rho')
else:
return (b - (a * inner(c, b, axis=axis))) / rho | python | def solvedbi_sm(ah, rho, b, c=None, axis=4):
r"""
Solve a diagonal block linear system with a scaled identity term
using the Sherman-Morrison equation.
The solution is obtained by independently solving a set of linear
systems of the form (see :cite:`wohlberg-2016-efficient`)
.. math::
(\rho I + \mathbf{a} \mathbf{a}^H ) \; \mathbf{x} = \mathbf{b} \;\;.
In this equation inner products and matrix products are taken along
the specified axis of the corresponding multi-dimensional arrays; the
solutions are independent over the other axes.
Parameters
----------
ah : array_like
Linear system component :math:`\mathbf{a}^H`
rho : float
Linear system parameter :math:`\rho`
b : array_like
Linear system component :math:`\mathbf{b}`
c : array_like, optional (default None)
Solution component :math:`\mathbf{c}` that may be pre-computed using
:func:`solvedbi_sm_c` and cached for re-use.
axis : int, optional (default 4)
Axis along which to solve the linear system
Returns
-------
x : ndarray
Linear system solution :math:`\mathbf{x}`
"""
a = np.conj(ah)
if c is None:
c = solvedbi_sm_c(ah, a, rho, axis)
if have_numexpr:
cb = inner(c, b, axis=axis)
return ne.evaluate('(b - (a * cb)) / rho')
else:
return (b - (a * inner(c, b, axis=axis))) / rho | [
"def",
"solvedbi_sm",
"(",
"ah",
",",
"rho",
",",
"b",
",",
"c",
"=",
"None",
",",
"axis",
"=",
"4",
")",
":",
"a",
"=",
"np",
".",
"conj",
"(",
"ah",
")",
"if",
"c",
"is",
"None",
":",
"c",
"=",
"solvedbi_sm_c",
"(",
"ah",
",",
"a",
",",
... | r"""
Solve a diagonal block linear system with a scaled identity term
using the Sherman-Morrison equation.
The solution is obtained by independently solving a set of linear
systems of the form (see :cite:`wohlberg-2016-efficient`)
.. math::
(\rho I + \mathbf{a} \mathbf{a}^H ) \; \mathbf{x} = \mathbf{b} \;\;.
In this equation inner products and matrix products are taken along
the specified axis of the corresponding multi-dimensional arrays; the
solutions are independent over the other axes.
Parameters
----------
ah : array_like
Linear system component :math:`\mathbf{a}^H`
rho : float
Linear system parameter :math:`\rho`
b : array_like
Linear system component :math:`\mathbf{b}`
c : array_like, optional (default None)
Solution component :math:`\mathbf{c}` that may be pre-computed using
:func:`solvedbi_sm_c` and cached for re-use.
axis : int, optional (default 4)
Axis along which to solve the linear system
Returns
-------
x : ndarray
Linear system solution :math:`\mathbf{x}` | [
"r",
"Solve",
"a",
"diagonal",
"block",
"linear",
"system",
"with",
"a",
"scaled",
"identity",
"term",
"using",
"the",
"Sherman",
"-",
"Morrison",
"equation",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/linalg.py#L472-L514 | train | 210,070 |
bwohlberg/sporco | sporco/linalg.py | solvedbd_sm | def solvedbd_sm(ah, d, b, c=None, axis=4):
r"""
Solve a diagonal block linear system with a diagonal term
using the Sherman-Morrison equation.
The solution is obtained by independently solving a set of linear
systems of the form (see :cite:`wohlberg-2016-efficient`)
.. math::
(\mathbf{d} + \mathbf{a} \mathbf{a}^H ) \; \mathbf{x} = \mathbf{b} \;\;.
In this equation inner products and matrix products are taken along
the specified axis of the corresponding multi-dimensional arrays; the
solutions are independent over the other axes.
Parameters
----------
ah : array_like
Linear system component :math:`\mathbf{a}^H`
d : array_like
Linear system parameter :math:`\mathbf{d}`
b : array_like
Linear system component :math:`\mathbf{b}`
c : array_like, optional (default None)
Solution component :math:`\mathbf{c}` that may be pre-computed using
:func:`solvedbd_sm_c` and cached for re-use.
axis : int, optional (default 4)
Axis along which to solve the linear system
Returns
-------
x : ndarray
Linear system solution :math:`\mathbf{x}`
"""
a = np.conj(ah)
if c is None:
c = solvedbd_sm_c(ah, a, d, axis)
if have_numexpr:
cb = inner(c, b, axis=axis)
return ne.evaluate('(b - (a * cb)) / d')
else:
return (b - (a * inner(c, b, axis=axis))) / d | python | def solvedbd_sm(ah, d, b, c=None, axis=4):
r"""
Solve a diagonal block linear system with a diagonal term
using the Sherman-Morrison equation.
The solution is obtained by independently solving a set of linear
systems of the form (see :cite:`wohlberg-2016-efficient`)
.. math::
(\mathbf{d} + \mathbf{a} \mathbf{a}^H ) \; \mathbf{x} = \mathbf{b} \;\;.
In this equation inner products and matrix products are taken along
the specified axis of the corresponding multi-dimensional arrays; the
solutions are independent over the other axes.
Parameters
----------
ah : array_like
Linear system component :math:`\mathbf{a}^H`
d : array_like
Linear system parameter :math:`\mathbf{d}`
b : array_like
Linear system component :math:`\mathbf{b}`
c : array_like, optional (default None)
Solution component :math:`\mathbf{c}` that may be pre-computed using
:func:`solvedbd_sm_c` and cached for re-use.
axis : int, optional (default 4)
Axis along which to solve the linear system
Returns
-------
x : ndarray
Linear system solution :math:`\mathbf{x}`
"""
a = np.conj(ah)
if c is None:
c = solvedbd_sm_c(ah, a, d, axis)
if have_numexpr:
cb = inner(c, b, axis=axis)
return ne.evaluate('(b - (a * cb)) / d')
else:
return (b - (a * inner(c, b, axis=axis))) / d | [
"def",
"solvedbd_sm",
"(",
"ah",
",",
"d",
",",
"b",
",",
"c",
"=",
"None",
",",
"axis",
"=",
"4",
")",
":",
"a",
"=",
"np",
".",
"conj",
"(",
"ah",
")",
"if",
"c",
"is",
"None",
":",
"c",
"=",
"solvedbd_sm_c",
"(",
"ah",
",",
"a",
",",
"... | r"""
Solve a diagonal block linear system with a diagonal term
using the Sherman-Morrison equation.
The solution is obtained by independently solving a set of linear
systems of the form (see :cite:`wohlberg-2016-efficient`)
.. math::
(\mathbf{d} + \mathbf{a} \mathbf{a}^H ) \; \mathbf{x} = \mathbf{b} \;\;.
In this equation inner products and matrix products are taken along
the specified axis of the corresponding multi-dimensional arrays; the
solutions are independent over the other axes.
Parameters
----------
ah : array_like
Linear system component :math:`\mathbf{a}^H`
d : array_like
Linear system parameter :math:`\mathbf{d}`
b : array_like
Linear system component :math:`\mathbf{b}`
c : array_like, optional (default None)
Solution component :math:`\mathbf{c}` that may be pre-computed using
:func:`solvedbd_sm_c` and cached for re-use.
axis : int, optional (default 4)
Axis along which to solve the linear system
Returns
-------
x : ndarray
Linear system solution :math:`\mathbf{x}` | [
"r",
"Solve",
"a",
"diagonal",
"block",
"linear",
"system",
"with",
"a",
"diagonal",
"term",
"using",
"the",
"Sherman",
"-",
"Morrison",
"equation",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/linalg.py#L543-L585 | train | 210,071 |
bwohlberg/sporco | sporco/linalg.py | Gax | def Gax(x, ax):
"""
Compute gradient of `x` along axis `ax`.
Parameters
----------
x : array_like
Input array
ax : int
Axis on which gradient is to be computed
Returns
-------
xg : ndarray
Output array
"""
slc = (slice(None),)*ax + (slice(-1, None),)
xg = np.roll(x, -1, axis=ax) - x
xg[slc] = 0.0
return xg | python | def Gax(x, ax):
"""
Compute gradient of `x` along axis `ax`.
Parameters
----------
x : array_like
Input array
ax : int
Axis on which gradient is to be computed
Returns
-------
xg : ndarray
Output array
"""
slc = (slice(None),)*ax + (slice(-1, None),)
xg = np.roll(x, -1, axis=ax) - x
xg[slc] = 0.0
return xg | [
"def",
"Gax",
"(",
"x",
",",
"ax",
")",
":",
"slc",
"=",
"(",
"slice",
"(",
"None",
")",
",",
")",
"*",
"ax",
"+",
"(",
"slice",
"(",
"-",
"1",
",",
"None",
")",
",",
")",
"xg",
"=",
"np",
".",
"roll",
"(",
"x",
",",
"-",
"1",
",",
"a... | Compute gradient of `x` along axis `ax`.
Parameters
----------
x : array_like
Input array
ax : int
Axis on which gradient is to be computed
Returns
-------
xg : ndarray
Output array | [
"Compute",
"gradient",
"of",
"x",
"along",
"axis",
"ax",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/linalg.py#L1081-L1101 | train | 210,072 |
bwohlberg/sporco | sporco/linalg.py | GTax | def GTax(x, ax):
"""
Compute transpose of gradient of `x` along axis `ax`.
Parameters
----------
x : array_like
Input array
ax : int
Axis on which gradient transpose is to be computed
Returns
-------
xg : ndarray
Output array
"""
slc0 = (slice(None),) * ax
xg = np.roll(x, 1, axis=ax) - x
xg[slc0 + (slice(0, 1),)] = -x[slc0 + (slice(0, 1),)]
xg[slc0 + (slice(-1, None),)] = x[slc0 + (slice(-2, -1),)]
return xg | python | def GTax(x, ax):
"""
Compute transpose of gradient of `x` along axis `ax`.
Parameters
----------
x : array_like
Input array
ax : int
Axis on which gradient transpose is to be computed
Returns
-------
xg : ndarray
Output array
"""
slc0 = (slice(None),) * ax
xg = np.roll(x, 1, axis=ax) - x
xg[slc0 + (slice(0, 1),)] = -x[slc0 + (slice(0, 1),)]
xg[slc0 + (slice(-1, None),)] = x[slc0 + (slice(-2, -1),)]
return xg | [
"def",
"GTax",
"(",
"x",
",",
"ax",
")",
":",
"slc0",
"=",
"(",
"slice",
"(",
"None",
")",
",",
")",
"*",
"ax",
"xg",
"=",
"np",
".",
"roll",
"(",
"x",
",",
"1",
",",
"axis",
"=",
"ax",
")",
"-",
"x",
"xg",
"[",
"slc0",
"+",
"(",
"slice... | Compute transpose of gradient of `x` along axis `ax`.
Parameters
----------
x : array_like
Input array
ax : int
Axis on which gradient transpose is to be computed
Returns
-------
xg : ndarray
Output array | [
"Compute",
"transpose",
"of",
"gradient",
"of",
"x",
"along",
"axis",
"ax",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/linalg.py#L1105-L1126 | train | 210,073 |
bwohlberg/sporco | sporco/linalg.py | GradientFilters | def GradientFilters(ndim, axes, axshp, dtype=None):
r"""
Construct a set of filters for computing gradients in the frequency
domain.
Parameters
----------
ndim : integer
Total number of dimensions in array in which gradients are to be
computed
axes : tuple of integers
Axes on which gradients are to be computed
axshp : tuple of integers
Shape of axes on which gradients are to be computed
dtype : dtype
Data type of output arrays
Returns
-------
Gf : ndarray
Frequency domain gradient operators :math:`\hat{G}_i`
GHGf : ndarray
Sum of products :math:`\sum_i \hat{G}_i^H \hat{G}_i`
"""
if dtype is None:
dtype = np.float32
g = np.zeros([2 if k in axes else 1 for k in range(ndim)] +
[len(axes),], dtype)
for k in axes:
g[(0,) * k + (slice(None),) + (0,) * (g.ndim - 2 - k) + (k,)] = \
np.array([1, -1])
Gf = rfftn(g, axshp, axes=axes)
GHGf = np.sum(np.conj(Gf) * Gf, axis=-1).real
return Gf, GHGf | python | def GradientFilters(ndim, axes, axshp, dtype=None):
r"""
Construct a set of filters for computing gradients in the frequency
domain.
Parameters
----------
ndim : integer
Total number of dimensions in array in which gradients are to be
computed
axes : tuple of integers
Axes on which gradients are to be computed
axshp : tuple of integers
Shape of axes on which gradients are to be computed
dtype : dtype
Data type of output arrays
Returns
-------
Gf : ndarray
Frequency domain gradient operators :math:`\hat{G}_i`
GHGf : ndarray
Sum of products :math:`\sum_i \hat{G}_i^H \hat{G}_i`
"""
if dtype is None:
dtype = np.float32
g = np.zeros([2 if k in axes else 1 for k in range(ndim)] +
[len(axes),], dtype)
for k in axes:
g[(0,) * k + (slice(None),) + (0,) * (g.ndim - 2 - k) + (k,)] = \
np.array([1, -1])
Gf = rfftn(g, axshp, axes=axes)
GHGf = np.sum(np.conj(Gf) * Gf, axis=-1).real
return Gf, GHGf | [
"def",
"GradientFilters",
"(",
"ndim",
",",
"axes",
",",
"axshp",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"np",
".",
"float32",
"g",
"=",
"np",
".",
"zeros",
"(",
"[",
"2",
"if",
"k",
"in",
"axes",
"... | r"""
Construct a set of filters for computing gradients in the frequency
domain.
Parameters
----------
ndim : integer
Total number of dimensions in array in which gradients are to be
computed
axes : tuple of integers
Axes on which gradients are to be computed
axshp : tuple of integers
Shape of axes on which gradients are to be computed
dtype : dtype
Data type of output arrays
Returns
-------
Gf : ndarray
Frequency domain gradient operators :math:`\hat{G}_i`
GHGf : ndarray
Sum of products :math:`\sum_i \hat{G}_i^H \hat{G}_i` | [
"r",
"Construct",
"a",
"set",
"of",
"filters",
"for",
"computing",
"gradients",
"in",
"the",
"frequency",
"domain",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/linalg.py#L1130-L1164 | train | 210,074 |
bwohlberg/sporco | sporco/linalg.py | promote16 | def promote16(u, fn=None, *args, **kwargs):
r"""
Utility function for use with functions that do not support arrays
of dtype ``np.float16``. This function has two distinct modes of
operation. If called with only the `u` parameter specified, the
returned value is either `u` itself if `u` is not of dtype
``np.float16``, or `u` promoted to ``np.float32`` dtype if it is. If
the function parameter `fn` is specified then `u` is conditionally
promoted as described above, passed as the first argument to
function `fn`, and the returned values are converted back to dtype
``np.float16`` if `u` is of that dtype. Note that if parameter `fn`
is specified, it may not be be specified as a keyword argument if it
is followed by any non-keyword arguments.
Parameters
----------
u : array_like
Array to be promoted to np.float32 if it is of dtype ``np.float16``
fn : function or None, optional (default None)
Function to be called with promoted `u` as first parameter and
\*args and \*\*kwargs as additional parameters
*args
Variable length list of arguments for function `fn`
**kwargs
Keyword arguments for function `fn`
Returns
-------
up : ndarray
Conditionally dtype-promoted version of `u` if `fn` is None,
or value(s) returned by `fn`, converted to the same dtype as `u`,
if `fn` is a function
"""
dtype = np.float32 if u.dtype == np.float16 else u.dtype
up = np.asarray(u, dtype=dtype)
if fn is None:
return up
else:
v = fn(up, *args, **kwargs)
if isinstance(v, tuple):
vp = tuple([np.asarray(vk, dtype=u.dtype) for vk in v])
else:
vp = np.asarray(v, dtype=u.dtype)
return vp | python | def promote16(u, fn=None, *args, **kwargs):
r"""
Utility function for use with functions that do not support arrays
of dtype ``np.float16``. This function has two distinct modes of
operation. If called with only the `u` parameter specified, the
returned value is either `u` itself if `u` is not of dtype
``np.float16``, or `u` promoted to ``np.float32`` dtype if it is. If
the function parameter `fn` is specified then `u` is conditionally
promoted as described above, passed as the first argument to
function `fn`, and the returned values are converted back to dtype
``np.float16`` if `u` is of that dtype. Note that if parameter `fn`
is specified, it may not be be specified as a keyword argument if it
is followed by any non-keyword arguments.
Parameters
----------
u : array_like
Array to be promoted to np.float32 if it is of dtype ``np.float16``
fn : function or None, optional (default None)
Function to be called with promoted `u` as first parameter and
\*args and \*\*kwargs as additional parameters
*args
Variable length list of arguments for function `fn`
**kwargs
Keyword arguments for function `fn`
Returns
-------
up : ndarray
Conditionally dtype-promoted version of `u` if `fn` is None,
or value(s) returned by `fn`, converted to the same dtype as `u`,
if `fn` is a function
"""
dtype = np.float32 if u.dtype == np.float16 else u.dtype
up = np.asarray(u, dtype=dtype)
if fn is None:
return up
else:
v = fn(up, *args, **kwargs)
if isinstance(v, tuple):
vp = tuple([np.asarray(vk, dtype=u.dtype) for vk in v])
else:
vp = np.asarray(v, dtype=u.dtype)
return vp | [
"def",
"promote16",
"(",
"u",
",",
"fn",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dtype",
"=",
"np",
".",
"float32",
"if",
"u",
".",
"dtype",
"==",
"np",
".",
"float16",
"else",
"u",
".",
"dtype",
"up",
"=",
"np",
".... | r"""
Utility function for use with functions that do not support arrays
of dtype ``np.float16``. This function has two distinct modes of
operation. If called with only the `u` parameter specified, the
returned value is either `u` itself if `u` is not of dtype
``np.float16``, or `u` promoted to ``np.float32`` dtype if it is. If
the function parameter `fn` is specified then `u` is conditionally
promoted as described above, passed as the first argument to
function `fn`, and the returned values are converted back to dtype
``np.float16`` if `u` is of that dtype. Note that if parameter `fn`
is specified, it may not be be specified as a keyword argument if it
is followed by any non-keyword arguments.
Parameters
----------
u : array_like
Array to be promoted to np.float32 if it is of dtype ``np.float16``
fn : function or None, optional (default None)
Function to be called with promoted `u` as first parameter and
\*args and \*\*kwargs as additional parameters
*args
Variable length list of arguments for function `fn`
**kwargs
Keyword arguments for function `fn`
Returns
-------
up : ndarray
Conditionally dtype-promoted version of `u` if `fn` is None,
or value(s) returned by `fn`, converted to the same dtype as `u`,
if `fn` is a function | [
"r",
"Utility",
"function",
"for",
"use",
"with",
"functions",
"that",
"do",
"not",
"support",
"arrays",
"of",
"dtype",
"np",
".",
"float16",
".",
"This",
"function",
"has",
"two",
"distinct",
"modes",
"of",
"operation",
".",
"If",
"called",
"with",
"only"... | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/linalg.py#L1221-L1265 | train | 210,075 |
bwohlberg/sporco | sporco/admm/tvl2.py | TVL2Denoise.LaplaceCentreWeight | def LaplaceCentreWeight(self):
"""Centre weighting matrix for TV Laplacian."""
sz = [1,] * self.S.ndim
for ax in self.axes:
sz[ax] = self.S.shape[ax]
lcw = 2*len(self.axes)*np.ones(sz, dtype=self.dtype)
for ax in self.axes:
lcw[(slice(None),)*ax + ([0, -1],)] -= 1.0
return lcw | python | def LaplaceCentreWeight(self):
"""Centre weighting matrix for TV Laplacian."""
sz = [1,] * self.S.ndim
for ax in self.axes:
sz[ax] = self.S.shape[ax]
lcw = 2*len(self.axes)*np.ones(sz, dtype=self.dtype)
for ax in self.axes:
lcw[(slice(None),)*ax + ([0, -1],)] -= 1.0
return lcw | [
"def",
"LaplaceCentreWeight",
"(",
"self",
")",
":",
"sz",
"=",
"[",
"1",
",",
"]",
"*",
"self",
".",
"S",
".",
"ndim",
"for",
"ax",
"in",
"self",
".",
"axes",
":",
"sz",
"[",
"ax",
"]",
"=",
"self",
".",
"S",
".",
"shape",
"[",
"ax",
"]",
... | Centre weighting matrix for TV Laplacian. | [
"Centre",
"weighting",
"matrix",
"for",
"TV",
"Laplacian",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/tvl2.py#L328-L337 | train | 210,076 |
bwohlberg/sporco | sporco/admm/tvl2.py | TVL2Denoise.GaussSeidelStep | def GaussSeidelStep(self, S, X, ATYU, rho, lcw, W2):
"""Gauss-Seidel step for linear system in TV problem."""
Xss = np.zeros_like(S, dtype=self.dtype)
for ax in self.axes:
Xss += sl.zpad(X[(slice(None),)*ax + (slice(0, -1),)],
(1, 0), ax)
Xss += sl.zpad(X[(slice(None),)*ax + (slice(1, None),)],
(0, 1), ax)
return (rho*(Xss + ATYU) + W2*S) / (W2 + rho*lcw) | python | def GaussSeidelStep(self, S, X, ATYU, rho, lcw, W2):
"""Gauss-Seidel step for linear system in TV problem."""
Xss = np.zeros_like(S, dtype=self.dtype)
for ax in self.axes:
Xss += sl.zpad(X[(slice(None),)*ax + (slice(0, -1),)],
(1, 0), ax)
Xss += sl.zpad(X[(slice(None),)*ax + (slice(1, None),)],
(0, 1), ax)
return (rho*(Xss + ATYU) + W2*S) / (W2 + rho*lcw) | [
"def",
"GaussSeidelStep",
"(",
"self",
",",
"S",
",",
"X",
",",
"ATYU",
",",
"rho",
",",
"lcw",
",",
"W2",
")",
":",
"Xss",
"=",
"np",
".",
"zeros_like",
"(",
"S",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"for",
"ax",
"in",
"self",
".",
... | Gauss-Seidel step for linear system in TV problem. | [
"Gauss",
"-",
"Seidel",
"step",
"for",
"linear",
"system",
"in",
"TV",
"problem",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/tvl2.py#L341-L350 | train | 210,077 |
bwohlberg/sporco | sporco/admm/admm.py | ADMM.runtime | def runtime(self):
"""Transitional property providing access to the new timer
mechanism. This will be removed in the future.
"""
warnings.warn("admm.ADMM.runtime attribute has been replaced by "
"an upgraded timer class: please see the documentation "
"for admm.ADMM.solve method and util.Timer class",
PendingDeprecationWarning)
return self.timer.elapsed('init') + self.timer.elapsed('solve') | python | def runtime(self):
"""Transitional property providing access to the new timer
mechanism. This will be removed in the future.
"""
warnings.warn("admm.ADMM.runtime attribute has been replaced by "
"an upgraded timer class: please see the documentation "
"for admm.ADMM.solve method and util.Timer class",
PendingDeprecationWarning)
return self.timer.elapsed('init') + self.timer.elapsed('solve') | [
"def",
"runtime",
"(",
"self",
")",
":",
"warnings",
".",
"warn",
"(",
"\"admm.ADMM.runtime attribute has been replaced by \"",
"\"an upgraded timer class: please see the documentation \"",
"\"for admm.ADMM.solve method and util.Timer class\"",
",",
"PendingDeprecationWarning",
")",
... | Transitional property providing access to the new timer
mechanism. This will be removed in the future. | [
"Transitional",
"property",
"providing",
"access",
"to",
"the",
"new",
"timer",
"mechanism",
".",
"This",
"will",
"be",
"removed",
"in",
"the",
"future",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/admm.py#L393-L402 | train | 210,078 |
bwohlberg/sporco | sporco/admm/admm.py | ADMM.ustep | def ustep(self):
"""Dual variable update."""
self.U += self.rsdl_r(self.AX, self.Y) | python | def ustep(self):
"""Dual variable update."""
self.U += self.rsdl_r(self.AX, self.Y) | [
"def",
"ustep",
"(",
"self",
")",
":",
"self",
".",
"U",
"+=",
"self",
".",
"rsdl_r",
"(",
"self",
".",
"AX",
",",
"self",
".",
"Y",
")"
] | Dual variable update. | [
"Dual",
"variable",
"update",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/admm.py#L433-L436 | train | 210,079 |
bwohlberg/sporco | sporco/admm/admm.py | ADMM.update_rho | def update_rho(self, k, r, s):
"""Automatic rho adjustment."""
if self.opt['AutoRho', 'Enabled']:
tau = self.rho_tau
mu = self.rho_mu
xi = self.rho_xi
if k != 0 and np.mod(k + 1, self.opt['AutoRho', 'Period']) == 0:
if self.opt['AutoRho', 'AutoScaling']:
if s == 0.0 or r == 0.0:
rhomlt = tau
else:
rhomlt = np.sqrt(r / (s * xi) if r > s * xi else
(s * xi) / r)
if rhomlt > tau:
rhomlt = tau
else:
rhomlt = tau
rsf = 1.0
if r > xi * mu * s:
rsf = rhomlt
elif s > (mu / xi) * r:
rsf = 1.0 / rhomlt
self.rho *= self.dtype.type(rsf)
self.U /= rsf
if rsf != 1.0:
self.rhochange() | python | def update_rho(self, k, r, s):
"""Automatic rho adjustment."""
if self.opt['AutoRho', 'Enabled']:
tau = self.rho_tau
mu = self.rho_mu
xi = self.rho_xi
if k != 0 and np.mod(k + 1, self.opt['AutoRho', 'Period']) == 0:
if self.opt['AutoRho', 'AutoScaling']:
if s == 0.0 or r == 0.0:
rhomlt = tau
else:
rhomlt = np.sqrt(r / (s * xi) if r > s * xi else
(s * xi) / r)
if rhomlt > tau:
rhomlt = tau
else:
rhomlt = tau
rsf = 1.0
if r > xi * mu * s:
rsf = rhomlt
elif s > (mu / xi) * r:
rsf = 1.0 / rhomlt
self.rho *= self.dtype.type(rsf)
self.U /= rsf
if rsf != 1.0:
self.rhochange() | [
"def",
"update_rho",
"(",
"self",
",",
"k",
",",
"r",
",",
"s",
")",
":",
"if",
"self",
".",
"opt",
"[",
"'AutoRho'",
",",
"'Enabled'",
"]",
":",
"tau",
"=",
"self",
".",
"rho_tau",
"mu",
"=",
"self",
".",
"rho_mu",
"xi",
"=",
"self",
".",
"rho... | Automatic rho adjustment. | [
"Automatic",
"rho",
"adjustment",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/admm.py#L548-L574 | train | 210,080 |
bwohlberg/sporco | sporco/admm/admm.py | ADMM.display_status | def display_status(self, fmtstr, itst):
"""Display current iteration status as selection of fields from
iteration stats tuple.
"""
if self.opt['Verbose']:
hdrtxt = type(self).hdrtxt()
hdrval = type(self).hdrval()
itdsp = tuple([getattr(itst, hdrval[col]) for col in hdrtxt])
if not self.opt['AutoRho', 'Enabled']:
itdsp = itdsp[0:-1]
print(fmtstr % itdsp) | python | def display_status(self, fmtstr, itst):
"""Display current iteration status as selection of fields from
iteration stats tuple.
"""
if self.opt['Verbose']:
hdrtxt = type(self).hdrtxt()
hdrval = type(self).hdrval()
itdsp = tuple([getattr(itst, hdrval[col]) for col in hdrtxt])
if not self.opt['AutoRho', 'Enabled']:
itdsp = itdsp[0:-1]
print(fmtstr % itdsp) | [
"def",
"display_status",
"(",
"self",
",",
"fmtstr",
",",
"itst",
")",
":",
"if",
"self",
".",
"opt",
"[",
"'Verbose'",
"]",
":",
"hdrtxt",
"=",
"type",
"(",
"self",
")",
".",
"hdrtxt",
"(",
")",
"hdrval",
"=",
"type",
"(",
"self",
")",
".",
"hdr... | Display current iteration status as selection of fields from
iteration stats tuple. | [
"Display",
"current",
"iteration",
"status",
"as",
"selection",
"of",
"fields",
"from",
"iteration",
"stats",
"tuple",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/admm.py#L604-L616 | train | 210,081 |
bwohlberg/sporco | sporco/admm/admm.py | ADMM.rsdl_sn | def rsdl_sn(self, U):
"""Compute dual residual normalisation term.
Overriding this method is required if methods :meth:`cnst_A`,
:meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not
overridden.
"""
return self.rho * np.linalg.norm(self.cnst_AT(U)) | python | def rsdl_sn(self, U):
"""Compute dual residual normalisation term.
Overriding this method is required if methods :meth:`cnst_A`,
:meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not
overridden.
"""
return self.rho * np.linalg.norm(self.cnst_AT(U)) | [
"def",
"rsdl_sn",
"(",
"self",
",",
"U",
")",
":",
"return",
"self",
".",
"rho",
"*",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"cnst_AT",
"(",
"U",
")",
")"
] | Compute dual residual normalisation term.
Overriding this method is required if methods :meth:`cnst_A`,
:meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not
overridden. | [
"Compute",
"dual",
"residual",
"normalisation",
"term",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/admm.py#L766-L774 | train | 210,082 |
bwohlberg/sporco | sporco/admm/admm.py | ADMMTwoBlockCnstrnt.getmin | def getmin(self):
"""Get minimiser after optimisation."""
if self.opt['ReturnVar'] == 'X':
return self.var_x()
elif self.opt['ReturnVar'] == 'Y0':
return self.var_y0()
elif self.opt['ReturnVar'] == 'Y1':
return self.var_y1()
else:
raise ValueError(self.opt['ReturnVar'] + ' is not a valid value'
'for option ReturnVar') | python | def getmin(self):
"""Get minimiser after optimisation."""
if self.opt['ReturnVar'] == 'X':
return self.var_x()
elif self.opt['ReturnVar'] == 'Y0':
return self.var_y0()
elif self.opt['ReturnVar'] == 'Y1':
return self.var_y1()
else:
raise ValueError(self.opt['ReturnVar'] + ' is not a valid value'
'for option ReturnVar') | [
"def",
"getmin",
"(",
"self",
")",
":",
"if",
"self",
".",
"opt",
"[",
"'ReturnVar'",
"]",
"==",
"'X'",
":",
"return",
"self",
".",
"var_x",
"(",
")",
"elif",
"self",
".",
"opt",
"[",
"'ReturnVar'",
"]",
"==",
"'Y0'",
":",
"return",
"self",
".",
... | Get minimiser after optimisation. | [
"Get",
"minimiser",
"after",
"optimisation",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/admm.py#L1112-L1123 | train | 210,083 |
bwohlberg/sporco | sporco/dictlrn/cbpdndlmd.py | cbpdnmsk_class_label_lookup | def cbpdnmsk_class_label_lookup(label):
"""Get a ConvBPDNMask class from a label string."""
clsmod = {'admm': admm_cbpdn.ConvBPDNMaskDcpl,
'fista': fista_cbpdn.ConvBPDNMask}
if label in clsmod:
return clsmod[label]
else:
raise ValueError('Unknown ConvBPDNMask solver method %s' % label) | python | def cbpdnmsk_class_label_lookup(label):
"""Get a ConvBPDNMask class from a label string."""
clsmod = {'admm': admm_cbpdn.ConvBPDNMaskDcpl,
'fista': fista_cbpdn.ConvBPDNMask}
if label in clsmod:
return clsmod[label]
else:
raise ValueError('Unknown ConvBPDNMask solver method %s' % label) | [
"def",
"cbpdnmsk_class_label_lookup",
"(",
"label",
")",
":",
"clsmod",
"=",
"{",
"'admm'",
":",
"admm_cbpdn",
".",
"ConvBPDNMaskDcpl",
",",
"'fista'",
":",
"fista_cbpdn",
".",
"ConvBPDNMask",
"}",
"if",
"label",
"in",
"clsmod",
":",
"return",
"clsmod",
"[",
... | Get a ConvBPDNMask class from a label string. | [
"Get",
"a",
"ConvBPDNMask",
"class",
"from",
"a",
"label",
"string",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/cbpdndlmd.py#L33-L41 | train | 210,084 |
bwohlberg/sporco | sporco/dictlrn/cbpdndlmd.py | ConvBPDNMaskOptionsDefaults | def ConvBPDNMaskOptionsDefaults(method='admm'):
"""Get defaults dict for the ConvBPDNMask class specified by the
``method`` parameter.
"""
dflt = copy.deepcopy(cbpdnmsk_class_label_lookup(method).Options.defaults)
if method == 'admm':
dflt.update({'MaxMainIter': 1, 'AutoRho':
{'Period': 10, 'AutoScaling': False,
'RsdlRatio': 10.0, 'Scaling': 2.0,
'RsdlTarget': 1.0}})
else:
dflt.update({'MaxMainIter': 1, 'BackTrack':
{'gamma_u': 1.2, 'MaxIter': 50}})
return dflt | python | def ConvBPDNMaskOptionsDefaults(method='admm'):
"""Get defaults dict for the ConvBPDNMask class specified by the
``method`` parameter.
"""
dflt = copy.deepcopy(cbpdnmsk_class_label_lookup(method).Options.defaults)
if method == 'admm':
dflt.update({'MaxMainIter': 1, 'AutoRho':
{'Period': 10, 'AutoScaling': False,
'RsdlRatio': 10.0, 'Scaling': 2.0,
'RsdlTarget': 1.0}})
else:
dflt.update({'MaxMainIter': 1, 'BackTrack':
{'gamma_u': 1.2, 'MaxIter': 50}})
return dflt | [
"def",
"ConvBPDNMaskOptionsDefaults",
"(",
"method",
"=",
"'admm'",
")",
":",
"dflt",
"=",
"copy",
".",
"deepcopy",
"(",
"cbpdnmsk_class_label_lookup",
"(",
"method",
")",
".",
"Options",
".",
"defaults",
")",
"if",
"method",
"==",
"'admm'",
":",
"dflt",
"."... | Get defaults dict for the ConvBPDNMask class specified by the
``method`` parameter. | [
"Get",
"defaults",
"dict",
"for",
"the",
"ConvBPDNMask",
"class",
"specified",
"by",
"the",
"method",
"parameter",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/cbpdndlmd.py#L45-L59 | train | 210,085 |
bwohlberg/sporco | sporco/dictlrn/cbpdndlmd.py | ccmodmsk_class_label_lookup | def ccmodmsk_class_label_lookup(label):
"""Get a ConvCnstrMODMask class from a label string."""
clsmod = {'ism': admm_ccmod.ConvCnstrMODMaskDcpl_IterSM,
'cg': admm_ccmod.ConvCnstrMODMaskDcpl_CG,
'cns': admm_ccmod.ConvCnstrMODMaskDcpl_Consensus,
'fista': fista_ccmod.ConvCnstrMODMask}
if label in clsmod:
return clsmod[label]
else:
raise ValueError('Unknown ConvCnstrMODMask solver method %s' % label) | python | def ccmodmsk_class_label_lookup(label):
"""Get a ConvCnstrMODMask class from a label string."""
clsmod = {'ism': admm_ccmod.ConvCnstrMODMaskDcpl_IterSM,
'cg': admm_ccmod.ConvCnstrMODMaskDcpl_CG,
'cns': admm_ccmod.ConvCnstrMODMaskDcpl_Consensus,
'fista': fista_ccmod.ConvCnstrMODMask}
if label in clsmod:
return clsmod[label]
else:
raise ValueError('Unknown ConvCnstrMODMask solver method %s' % label) | [
"def",
"ccmodmsk_class_label_lookup",
"(",
"label",
")",
":",
"clsmod",
"=",
"{",
"'ism'",
":",
"admm_ccmod",
".",
"ConvCnstrMODMaskDcpl_IterSM",
",",
"'cg'",
":",
"admm_ccmod",
".",
"ConvCnstrMODMaskDcpl_CG",
",",
"'cns'",
":",
"admm_ccmod",
".",
"ConvCnstrMODMaskD... | Get a ConvCnstrMODMask class from a label string. | [
"Get",
"a",
"ConvCnstrMODMask",
"class",
"from",
"a",
"label",
"string",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/cbpdndlmd.py#L128-L138 | train | 210,086 |
bwohlberg/sporco | sporco/dictlrn/cbpdndlmd.py | ConvCnstrMODMaskOptionsDefaults | def ConvCnstrMODMaskOptionsDefaults(method='fista'):
"""Get defaults dict for the ConvCnstrMODMask class specified by the
``method`` parameter.
"""
dflt = copy.deepcopy(ccmodmsk_class_label_lookup(method).Options.defaults)
if method == 'fista':
dflt.update({'MaxMainIter': 1, 'BackTrack':
{'gamma_u': 1.2, 'MaxIter': 50}})
else:
dflt.update({'MaxMainIter': 1, 'AutoRho':
{'Period': 10, 'AutoScaling': False,
'RsdlRatio': 10.0, 'Scaling': 2.0,
'RsdlTarget': 1.0}})
return dflt | python | def ConvCnstrMODMaskOptionsDefaults(method='fista'):
"""Get defaults dict for the ConvCnstrMODMask class specified by the
``method`` parameter.
"""
dflt = copy.deepcopy(ccmodmsk_class_label_lookup(method).Options.defaults)
if method == 'fista':
dflt.update({'MaxMainIter': 1, 'BackTrack':
{'gamma_u': 1.2, 'MaxIter': 50}})
else:
dflt.update({'MaxMainIter': 1, 'AutoRho':
{'Period': 10, 'AutoScaling': False,
'RsdlRatio': 10.0, 'Scaling': 2.0,
'RsdlTarget': 1.0}})
return dflt | [
"def",
"ConvCnstrMODMaskOptionsDefaults",
"(",
"method",
"=",
"'fista'",
")",
":",
"dflt",
"=",
"copy",
".",
"deepcopy",
"(",
"ccmodmsk_class_label_lookup",
"(",
"method",
")",
".",
"Options",
".",
"defaults",
")",
"if",
"method",
"==",
"'fista'",
":",
"dflt",... | Get defaults dict for the ConvCnstrMODMask class specified by the
``method`` parameter. | [
"Get",
"defaults",
"dict",
"for",
"the",
"ConvCnstrMODMask",
"class",
"specified",
"by",
"the",
"method",
"parameter",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/cbpdndlmd.py#L142-L156 | train | 210,087 |
bwohlberg/sporco | docs/source/docntbk.py | pathsplit | def pathsplit(pth, dropext=True):
"""Split a path into a tuple of all of its components."""
if dropext:
pth = os.path.splitext(pth)[0]
parts = os.path.split(pth)
if parts[0] == '':
return parts[1:]
elif len(parts[0]) == 1:
return parts
else:
return pathsplit(parts[0], dropext=False) + parts[1:] | python | def pathsplit(pth, dropext=True):
"""Split a path into a tuple of all of its components."""
if dropext:
pth = os.path.splitext(pth)[0]
parts = os.path.split(pth)
if parts[0] == '':
return parts[1:]
elif len(parts[0]) == 1:
return parts
else:
return pathsplit(parts[0], dropext=False) + parts[1:] | [
"def",
"pathsplit",
"(",
"pth",
",",
"dropext",
"=",
"True",
")",
":",
"if",
"dropext",
":",
"pth",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"pth",
")",
"[",
"0",
"]",
"parts",
"=",
"os",
".",
"path",
".",
"split",
"(",
"pth",
")",
"if",
... | Split a path into a tuple of all of its components. | [
"Split",
"a",
"path",
"into",
"a",
"tuple",
"of",
"all",
"of",
"its",
"components",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L34-L45 | train | 210,088 |
bwohlberg/sporco | docs/source/docntbk.py | update_required | def update_required(srcpth, dstpth):
"""
If the file at `dstpth` is generated from the file at `srcpth`,
determine whether an update is required. Returns True if `dstpth`
does not exist, or if `srcpth` has been more recently modified
than `dstpth`.
"""
return not os.path.exists(dstpth) or \
os.stat(srcpth).st_mtime > os.stat(dstpth).st_mtime | python | def update_required(srcpth, dstpth):
"""
If the file at `dstpth` is generated from the file at `srcpth`,
determine whether an update is required. Returns True if `dstpth`
does not exist, or if `srcpth` has been more recently modified
than `dstpth`.
"""
return not os.path.exists(dstpth) or \
os.stat(srcpth).st_mtime > os.stat(dstpth).st_mtime | [
"def",
"update_required",
"(",
"srcpth",
",",
"dstpth",
")",
":",
"return",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dstpth",
")",
"or",
"os",
".",
"stat",
"(",
"srcpth",
")",
".",
"st_mtime",
">",
"os",
".",
"stat",
"(",
"dstpth",
")",
".",
... | If the file at `dstpth` is generated from the file at `srcpth`,
determine whether an update is required. Returns True if `dstpth`
does not exist, or if `srcpth` has been more recently modified
than `dstpth`. | [
"If",
"the",
"file",
"at",
"dstpth",
"is",
"generated",
"from",
"the",
"file",
"at",
"srcpth",
"determine",
"whether",
"an",
"update",
"is",
"required",
".",
"Returns",
"True",
"if",
"dstpth",
"does",
"not",
"exist",
"or",
"if",
"srcpth",
"has",
"been",
... | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L49-L58 | train | 210,089 |
bwohlberg/sporco | docs/source/docntbk.py | read_sphinx_environment | def read_sphinx_environment(pth):
"""Read the sphinx environment.pickle file at path `pth`."""
with open(pth, 'rb') as fo:
env = pickle.load(fo)
return env | python | def read_sphinx_environment(pth):
"""Read the sphinx environment.pickle file at path `pth`."""
with open(pth, 'rb') as fo:
env = pickle.load(fo)
return env | [
"def",
"read_sphinx_environment",
"(",
"pth",
")",
":",
"with",
"open",
"(",
"pth",
",",
"'rb'",
")",
"as",
"fo",
":",
"env",
"=",
"pickle",
".",
"load",
"(",
"fo",
")",
"return",
"env"
] | Read the sphinx environment.pickle file at path `pth`. | [
"Read",
"the",
"sphinx",
"environment",
".",
"pickle",
"file",
"at",
"path",
"pth",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L85-L90 | train | 210,090 |
bwohlberg/sporco | docs/source/docntbk.py | parse_rst_index | def parse_rst_index(rstpth):
"""
Parse the top-level RST index file, at `rstpth`, for the example
python scripts. Returns a list of subdirectories in order of
appearance in the index file, and a dict mapping subdirectory name
to a description.
"""
pthidx = {}
pthlst = []
with open(rstpth) as fd:
lines = fd.readlines()
for i, l in enumerate(lines):
if i > 0:
if re.match(r'^ \w+', l) is not None and \
re.match(r'^\w+', lines[i - 1]) is not None:
# List of subdirectories in order of appearance in index.rst
pthlst.append(lines[i - 1][:-1])
# Dict mapping subdirectory name to description
pthidx[lines[i - 1][:-1]] = l[2:-1]
return pthlst, pthidx | python | def parse_rst_index(rstpth):
"""
Parse the top-level RST index file, at `rstpth`, for the example
python scripts. Returns a list of subdirectories in order of
appearance in the index file, and a dict mapping subdirectory name
to a description.
"""
pthidx = {}
pthlst = []
with open(rstpth) as fd:
lines = fd.readlines()
for i, l in enumerate(lines):
if i > 0:
if re.match(r'^ \w+', l) is not None and \
re.match(r'^\w+', lines[i - 1]) is not None:
# List of subdirectories in order of appearance in index.rst
pthlst.append(lines[i - 1][:-1])
# Dict mapping subdirectory name to description
pthidx[lines[i - 1][:-1]] = l[2:-1]
return pthlst, pthidx | [
"def",
"parse_rst_index",
"(",
"rstpth",
")",
":",
"pthidx",
"=",
"{",
"}",
"pthlst",
"=",
"[",
"]",
"with",
"open",
"(",
"rstpth",
")",
"as",
"fd",
":",
"lines",
"=",
"fd",
".",
"readlines",
"(",
")",
"for",
"i",
",",
"l",
"in",
"enumerate",
"("... | Parse the top-level RST index file, at `rstpth`, for the example
python scripts. Returns a list of subdirectories in order of
appearance in the index file, and a dict mapping subdirectory name
to a description. | [
"Parse",
"the",
"top",
"-",
"level",
"RST",
"index",
"file",
"at",
"rstpth",
"for",
"the",
"example",
"python",
"scripts",
".",
"Returns",
"a",
"list",
"of",
"subdirectories",
"in",
"order",
"of",
"appearance",
"in",
"the",
"index",
"file",
"and",
"a",
"... | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L94-L114 | train | 210,091 |
bwohlberg/sporco | docs/source/docntbk.py | preprocess_script_string | def preprocess_script_string(str):
"""
Process python script represented as string `str` in preparation
for conversion to a notebook. This processing includes removal of
the header comment, modification of the plotting configuration,
and replacement of certain sphinx cross-references with
appropriate links to online docs.
"""
# Remove header comment
str = re.sub(r'^(#[^#\n]+\n){5}\n*', r'', str)
# Insert notebook plotting configuration function
str = re.sub(r'from sporco import plot', r'from sporco import plot'
'\nplot.config_notebook_plotting()',
str, flags=re.MULTILINE)
# Remove final input statement and preceding comment
str = re.sub(r'\n*# Wait for enter on keyboard.*\ninput().*\n*',
r'', str, flags=re.MULTILINE)
return str | python | def preprocess_script_string(str):
"""
Process python script represented as string `str` in preparation
for conversion to a notebook. This processing includes removal of
the header comment, modification of the plotting configuration,
and replacement of certain sphinx cross-references with
appropriate links to online docs.
"""
# Remove header comment
str = re.sub(r'^(#[^#\n]+\n){5}\n*', r'', str)
# Insert notebook plotting configuration function
str = re.sub(r'from sporco import plot', r'from sporco import plot'
'\nplot.config_notebook_plotting()',
str, flags=re.MULTILINE)
# Remove final input statement and preceding comment
str = re.sub(r'\n*# Wait for enter on keyboard.*\ninput().*\n*',
r'', str, flags=re.MULTILINE)
return str | [
"def",
"preprocess_script_string",
"(",
"str",
")",
":",
"# Remove header comment",
"str",
"=",
"re",
".",
"sub",
"(",
"r'^(#[^#\\n]+\\n){5}\\n*'",
",",
"r''",
",",
"str",
")",
"# Insert notebook plotting configuration function",
"str",
"=",
"re",
".",
"sub",
"(",
... | Process python script represented as string `str` in preparation
for conversion to a notebook. This processing includes removal of
the header comment, modification of the plotting configuration,
and replacement of certain sphinx cross-references with
appropriate links to online docs. | [
"Process",
"python",
"script",
"represented",
"as",
"string",
"str",
"in",
"preparation",
"for",
"conversion",
"to",
"a",
"notebook",
".",
"This",
"processing",
"includes",
"removal",
"of",
"the",
"header",
"comment",
"modification",
"of",
"the",
"plotting",
"co... | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L118-L137 | train | 210,092 |
bwohlberg/sporco | docs/source/docntbk.py | script_string_to_notebook | def script_string_to_notebook(str, pth):
"""
Convert a python script represented as string `str` to a notebook
with filename `pth`.
"""
nb = py2jn.py_string_to_notebook(str)
py2jn.write_notebook(nb, pth) | python | def script_string_to_notebook(str, pth):
"""
Convert a python script represented as string `str` to a notebook
with filename `pth`.
"""
nb = py2jn.py_string_to_notebook(str)
py2jn.write_notebook(nb, pth) | [
"def",
"script_string_to_notebook",
"(",
"str",
",",
"pth",
")",
":",
"nb",
"=",
"py2jn",
".",
"py_string_to_notebook",
"(",
"str",
")",
"py2jn",
".",
"write_notebook",
"(",
"nb",
",",
"pth",
")"
] | Convert a python script represented as string `str` to a notebook
with filename `pth`. | [
"Convert",
"a",
"python",
"script",
"represented",
"as",
"string",
"str",
"to",
"a",
"notebook",
"with",
"filename",
"pth",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L151-L158 | train | 210,093 |
bwohlberg/sporco | docs/source/docntbk.py | script_to_notebook | def script_to_notebook(spth, npth, cr):
"""
Convert the script at `spth` to a notebook at `npth`. Parameter `cr`
is a CrossReferenceLookup object.
"""
# Read entire text of example script
with open(spth) as f:
stxt = f.read()
# Process script text
stxt = preprocess_script_string(stxt)
# If the notebook file exists and has been executed, try to
# update markdown cells without deleting output cells
if os.path.exists(npth) and notebook_executed(npth):
# Read current notebook file
nbold = nbformat.read(npth, as_version=4)
# Construct updated notebook
nbnew = script_string_to_notebook_object(stxt)
if cr is not None:
notebook_substitute_ref_with_url(nbnew, cr)
# If the code cells of the two notebooks match, try to
# update markdown cells without deleting output cells
if same_notebook_code(nbnew, nbold):
try:
replace_markdown_cells(nbnew, nbold)
except Exception:
script_string_to_notebook_with_links(stxt, npth, cr)
else:
with open(npth, 'wt') as f:
nbformat.write(nbold, f)
else:
# Write changed text to output notebook file
script_string_to_notebook_with_links(stxt, npth, cr)
else:
# Write changed text to output notebook file
script_string_to_notebook_with_links(stxt, npth, cr) | python | def script_to_notebook(spth, npth, cr):
"""
Convert the script at `spth` to a notebook at `npth`. Parameter `cr`
is a CrossReferenceLookup object.
"""
# Read entire text of example script
with open(spth) as f:
stxt = f.read()
# Process script text
stxt = preprocess_script_string(stxt)
# If the notebook file exists and has been executed, try to
# update markdown cells without deleting output cells
if os.path.exists(npth) and notebook_executed(npth):
# Read current notebook file
nbold = nbformat.read(npth, as_version=4)
# Construct updated notebook
nbnew = script_string_to_notebook_object(stxt)
if cr is not None:
notebook_substitute_ref_with_url(nbnew, cr)
# If the code cells of the two notebooks match, try to
# update markdown cells without deleting output cells
if same_notebook_code(nbnew, nbold):
try:
replace_markdown_cells(nbnew, nbold)
except Exception:
script_string_to_notebook_with_links(stxt, npth, cr)
else:
with open(npth, 'wt') as f:
nbformat.write(nbold, f)
else:
# Write changed text to output notebook file
script_string_to_notebook_with_links(stxt, npth, cr)
else:
# Write changed text to output notebook file
script_string_to_notebook_with_links(stxt, npth, cr) | [
"def",
"script_to_notebook",
"(",
"spth",
",",
"npth",
",",
"cr",
")",
":",
"# Read entire text of example script",
"with",
"open",
"(",
"spth",
")",
"as",
"f",
":",
"stxt",
"=",
"f",
".",
"read",
"(",
")",
"# Process script text",
"stxt",
"=",
"preprocess_s... | Convert the script at `spth` to a notebook at `npth`. Parameter `cr`
is a CrossReferenceLookup object. | [
"Convert",
"the",
"script",
"at",
"spth",
"to",
"a",
"notebook",
"at",
"npth",
".",
"Parameter",
"cr",
"is",
"a",
"CrossReferenceLookup",
"object",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L162-L198 | train | 210,094 |
bwohlberg/sporco | docs/source/docntbk.py | script_string_to_notebook_with_links | def script_string_to_notebook_with_links(str, pth, cr=None):
"""
Convert a python script represented as string `str` to a notebook
with filename `pth` and replace sphinx cross-references with links
to online docs. Parameter `cr` is a CrossReferenceLookup object.
"""
if cr is None:
script_string_to_notebook(str, pth)
else:
ntbk = script_string_to_notebook_object(str)
notebook_substitute_ref_with_url(ntbk, cr)
with open(pth, 'wt') as f:
nbformat.write(ntbk, f) | python | def script_string_to_notebook_with_links(str, pth, cr=None):
"""
Convert a python script represented as string `str` to a notebook
with filename `pth` and replace sphinx cross-references with links
to online docs. Parameter `cr` is a CrossReferenceLookup object.
"""
if cr is None:
script_string_to_notebook(str, pth)
else:
ntbk = script_string_to_notebook_object(str)
notebook_substitute_ref_with_url(ntbk, cr)
with open(pth, 'wt') as f:
nbformat.write(ntbk, f) | [
"def",
"script_string_to_notebook_with_links",
"(",
"str",
",",
"pth",
",",
"cr",
"=",
"None",
")",
":",
"if",
"cr",
"is",
"None",
":",
"script_string_to_notebook",
"(",
"str",
",",
"pth",
")",
"else",
":",
"ntbk",
"=",
"script_string_to_notebook_object",
"(",... | Convert a python script represented as string `str` to a notebook
with filename `pth` and replace sphinx cross-references with links
to online docs. Parameter `cr` is a CrossReferenceLookup object. | [
"Convert",
"a",
"python",
"script",
"represented",
"as",
"string",
"str",
"to",
"a",
"notebook",
"with",
"filename",
"pth",
"and",
"replace",
"sphinx",
"cross",
"-",
"references",
"with",
"links",
"to",
"online",
"docs",
".",
"Parameter",
"cr",
"is",
"a",
... | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L202-L215 | train | 210,095 |
bwohlberg/sporco | docs/source/docntbk.py | rst_to_notebook | def rst_to_notebook(infile, outfile):
"""Convert an rst file to a notebook file."""
# Read infile into a string
with open(infile, 'r') as fin:
rststr = fin.read()
# Convert string from rst to markdown
mdfmt = 'markdown_github+tex_math_dollars+fenced_code_attributes'
mdstr = pypandoc.convert_text(rststr, mdfmt, format='rst',
extra_args=['--atx-headers'])
# In links, replace .py extensions with .ipynb
mdstr = re.sub(r'\(([^\)]+).py\)', r'(\1.ipynb)', mdstr)
# Enclose the markdown within triple quotes and convert from
# python to notebook
mdstr = '"""' + mdstr + '"""'
nb = py2jn.py_string_to_notebook(mdstr)
py2jn.tools.write_notebook(nb, outfile, nbver=4) | python | def rst_to_notebook(infile, outfile):
"""Convert an rst file to a notebook file."""
# Read infile into a string
with open(infile, 'r') as fin:
rststr = fin.read()
# Convert string from rst to markdown
mdfmt = 'markdown_github+tex_math_dollars+fenced_code_attributes'
mdstr = pypandoc.convert_text(rststr, mdfmt, format='rst',
extra_args=['--atx-headers'])
# In links, replace .py extensions with .ipynb
mdstr = re.sub(r'\(([^\)]+).py\)', r'(\1.ipynb)', mdstr)
# Enclose the markdown within triple quotes and convert from
# python to notebook
mdstr = '"""' + mdstr + '"""'
nb = py2jn.py_string_to_notebook(mdstr)
py2jn.tools.write_notebook(nb, outfile, nbver=4) | [
"def",
"rst_to_notebook",
"(",
"infile",
",",
"outfile",
")",
":",
"# Read infile into a string",
"with",
"open",
"(",
"infile",
",",
"'r'",
")",
"as",
"fin",
":",
"rststr",
"=",
"fin",
".",
"read",
"(",
")",
"# Convert string from rst to markdown",
"mdfmt",
"... | Convert an rst file to a notebook file. | [
"Convert",
"an",
"rst",
"file",
"to",
"a",
"notebook",
"file",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L219-L235 | train | 210,096 |
bwohlberg/sporco | docs/source/docntbk.py | markdown_to_notebook | def markdown_to_notebook(infile, outfile):
"""Convert a markdown file to a notebook file."""
# Read infile into a string
with open(infile, 'r') as fin:
str = fin.read()
# Enclose the markdown within triple quotes and convert from
# python to notebook
str = '"""' + str + '"""'
nb = py2jn.py_string_to_notebook(str)
py2jn.tools.write_notebook(nb, outfile, nbver=4) | python | def markdown_to_notebook(infile, outfile):
"""Convert a markdown file to a notebook file."""
# Read infile into a string
with open(infile, 'r') as fin:
str = fin.read()
# Enclose the markdown within triple quotes and convert from
# python to notebook
str = '"""' + str + '"""'
nb = py2jn.py_string_to_notebook(str)
py2jn.tools.write_notebook(nb, outfile, nbver=4) | [
"def",
"markdown_to_notebook",
"(",
"infile",
",",
"outfile",
")",
":",
"# Read infile into a string",
"with",
"open",
"(",
"infile",
",",
"'r'",
")",
"as",
"fin",
":",
"str",
"=",
"fin",
".",
"read",
"(",
")",
"# Enclose the markdown within triple quotes and conv... | Convert a markdown file to a notebook file. | [
"Convert",
"a",
"markdown",
"file",
"to",
"a",
"notebook",
"file",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L239-L249 | train | 210,097 |
bwohlberg/sporco | docs/source/docntbk.py | rst_to_docs_rst | def rst_to_docs_rst(infile, outfile):
"""Convert an rst file to a sphinx docs rst file."""
# Read infile into a list of lines
with open(infile, 'r') as fin:
rst = fin.readlines()
# Inspect outfile path components to determine whether outfile
# is in the root of the examples directory or in a subdirectory
# thererof
ps = pathsplit(outfile)[-3:]
if ps[-2] == 'examples':
ps = ps[-2:]
idx = 'index'
else:
idx = ''
# Output string starts with a cross-reference anchor constructed from
# the file name and path
out = '.. _' + '_'.join(ps) + ':\n\n'
# Iterate over lines from infile
it = iter(rst)
for line in it:
if line[0:12] == '.. toc-start': # Line has start of toc marker
# Initialise current toc array and iterate over lines until
# end of toc marker encountered
toc = []
for line in it:
if line == '\n': # Drop newline lines
continue
elif line[0:10] == '.. toc-end': # End of toc marker
# Add toctree section to output string
out += '.. toctree::\n :maxdepth: 1\n\n'
for c in toc:
out += ' %s <%s>\n' % c
break
else: # Still within toc section
# Extract link text and target url and append to
# toc array
m = re.search(r'`(.*?)\s*<(.*?)(?:.py)?>`', line)
if m:
if idx == '':
toc.append((m.group(1), m.group(2)))
else:
toc.append((m.group(1),
os.path.join(m.group(2), idx)))
else: # Not within toc section
out += line
with open(outfile, 'w') as fout:
fout.write(out) | python | def rst_to_docs_rst(infile, outfile):
"""Convert an rst file to a sphinx docs rst file."""
# Read infile into a list of lines
with open(infile, 'r') as fin:
rst = fin.readlines()
# Inspect outfile path components to determine whether outfile
# is in the root of the examples directory or in a subdirectory
# thererof
ps = pathsplit(outfile)[-3:]
if ps[-2] == 'examples':
ps = ps[-2:]
idx = 'index'
else:
idx = ''
# Output string starts with a cross-reference anchor constructed from
# the file name and path
out = '.. _' + '_'.join(ps) + ':\n\n'
# Iterate over lines from infile
it = iter(rst)
for line in it:
if line[0:12] == '.. toc-start': # Line has start of toc marker
# Initialise current toc array and iterate over lines until
# end of toc marker encountered
toc = []
for line in it:
if line == '\n': # Drop newline lines
continue
elif line[0:10] == '.. toc-end': # End of toc marker
# Add toctree section to output string
out += '.. toctree::\n :maxdepth: 1\n\n'
for c in toc:
out += ' %s <%s>\n' % c
break
else: # Still within toc section
# Extract link text and target url and append to
# toc array
m = re.search(r'`(.*?)\s*<(.*?)(?:.py)?>`', line)
if m:
if idx == '':
toc.append((m.group(1), m.group(2)))
else:
toc.append((m.group(1),
os.path.join(m.group(2), idx)))
else: # Not within toc section
out += line
with open(outfile, 'w') as fout:
fout.write(out) | [
"def",
"rst_to_docs_rst",
"(",
"infile",
",",
"outfile",
")",
":",
"# Read infile into a list of lines",
"with",
"open",
"(",
"infile",
",",
"'r'",
")",
"as",
"fin",
":",
"rst",
"=",
"fin",
".",
"readlines",
"(",
")",
"# Inspect outfile path components to determin... | Convert an rst file to a sphinx docs rst file. | [
"Convert",
"an",
"rst",
"file",
"to",
"a",
"sphinx",
"docs",
"rst",
"file",
"."
] | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L253-L304 | train | 210,098 |
bwohlberg/sporco | docs/source/docntbk.py | parse_notebook_index | def parse_notebook_index(ntbkpth):
"""
Parse the top-level notebook index file at `ntbkpth`. Returns a
list of subdirectories in order of appearance in the index file,
and a dict mapping subdirectory name to a description.
"""
# Convert notebook to RST text in string
rex = RSTExporter()
rsttxt = rex.from_filename(ntbkpth)[0]
# Clean up trailing whitespace
rsttxt = re.sub(r'\n ', r'', rsttxt, re.M | re.S)
pthidx = {}
pthlst = []
lines = rsttxt.split('\n')
for l in lines:
m = re.match(r'^-\s+`([^<]+)\s+<([^>]+).ipynb>`__', l)
if m:
# List of subdirectories in order of appearance in index.rst
pthlst.append(m.group(2))
# Dict mapping subdirectory name to description
pthidx[m.group(2)] = m.group(1)
return pthlst, pthidx | python | def parse_notebook_index(ntbkpth):
"""
Parse the top-level notebook index file at `ntbkpth`. Returns a
list of subdirectories in order of appearance in the index file,
and a dict mapping subdirectory name to a description.
"""
# Convert notebook to RST text in string
rex = RSTExporter()
rsttxt = rex.from_filename(ntbkpth)[0]
# Clean up trailing whitespace
rsttxt = re.sub(r'\n ', r'', rsttxt, re.M | re.S)
pthidx = {}
pthlst = []
lines = rsttxt.split('\n')
for l in lines:
m = re.match(r'^-\s+`([^<]+)\s+<([^>]+).ipynb>`__', l)
if m:
# List of subdirectories in order of appearance in index.rst
pthlst.append(m.group(2))
# Dict mapping subdirectory name to description
pthidx[m.group(2)] = m.group(1)
return pthlst, pthidx | [
"def",
"parse_notebook_index",
"(",
"ntbkpth",
")",
":",
"# Convert notebook to RST text in string",
"rex",
"=",
"RSTExporter",
"(",
")",
"rsttxt",
"=",
"rex",
".",
"from_filename",
"(",
"ntbkpth",
")",
"[",
"0",
"]",
"# Clean up trailing whitespace",
"rsttxt",
"=",... | Parse the top-level notebook index file at `ntbkpth`. Returns a
list of subdirectories in order of appearance in the index file,
and a dict mapping subdirectory name to a description. | [
"Parse",
"the",
"top",
"-",
"level",
"notebook",
"index",
"file",
"at",
"ntbkpth",
".",
"Returns",
"a",
"list",
"of",
"subdirectories",
"in",
"order",
"of",
"appearance",
"in",
"the",
"index",
"file",
"and",
"a",
"dict",
"mapping",
"subdirectory",
"name",
... | 8946a04331106f4e39904fbdf2dc7351900baa04 | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/docntbk.py#L308-L330 | train | 210,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.