repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
Azure/msrestazure-for-python | msrestazure/azure_operation.py | AzureOperationPoller.remove_done_callback | def remove_done_callback(self, func):
"""Remove a callback from the long running operation.
:param callable func: The function to be removed from the callbacks.
:raises: ValueError if the long running operation has already
completed.
"""
if self._done is None or self._d... | python | def remove_done_callback(self, func):
"""Remove a callback from the long running operation.
:param callable func: The function to be removed from the callbacks.
:raises: ValueError if the long running operation has already
completed.
"""
if self._done is None or self._d... | [
"def",
"remove_done_callback",
"(",
"self",
",",
"func",
")",
":",
"if",
"self",
".",
"_done",
"is",
"None",
"or",
"self",
".",
"_done",
".",
"is_set",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Process is complete.\"",
")",
"self",
".",
"_callbacks",
... | Remove a callback from the long running operation.
:param callable func: The function to be removed from the callbacks.
:raises: ValueError if the long running operation has already
completed. | [
"Remove",
"a",
"callback",
"from",
"the",
"long",
"running",
"operation",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L532-L541 |
Azure/msrestazure-for-python | msrestazure/tools.py | register_rp_hook | def register_rp_hook(r, *args, **kwargs):
"""This is a requests hook to register RP automatically.
You should not use this command manually, this is added automatically
by the SDK.
See requests documentation for details of the signature of this function.
http://docs.python-requests.org/en/master/u... | python | def register_rp_hook(r, *args, **kwargs):
"""This is a requests hook to register RP automatically.
You should not use this command manually, this is added automatically
by the SDK.
See requests documentation for details of the signature of this function.
http://docs.python-requests.org/en/master/u... | [
"def",
"register_rp_hook",
"(",
"r",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"r",
".",
"status_code",
"==",
"409",
"and",
"'msrest'",
"in",
"kwargs",
":",
"rp_name",
"=",
"_check_rp_not_registered_err",
"(",
"r",
")",
"if",
"rp_name",
... | This is a requests hook to register RP automatically.
You should not use this command manually, this is added automatically
by the SDK.
See requests documentation for details of the signature of this function.
http://docs.python-requests.org/en/master/user/advanced/#event-hooks | [
"This",
"is",
"a",
"requests",
"hook",
"to",
"register",
"RP",
"automatically",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L43-L64 |
Azure/msrestazure-for-python | msrestazure/tools.py | _extract_subscription_url | def _extract_subscription_url(url):
"""Extract the first part of the URL, just after subscription:
https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
"""
match = re.match(r".*/subscriptions/[a-f0-9-]+/", url, re.IGNORECASE)
if not match:
raise ValueError("Unable... | python | def _extract_subscription_url(url):
"""Extract the first part of the URL, just after subscription:
https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
"""
match = re.match(r".*/subscriptions/[a-f0-9-]+/", url, re.IGNORECASE)
if not match:
raise ValueError("Unable... | [
"def",
"_extract_subscription_url",
"(",
"url",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r\".*/subscriptions/[a-f0-9-]+/\"",
",",
"url",
",",
"re",
".",
"IGNORECASE",
")",
"if",
"not",
"match",
":",
"raise",
"ValueError",
"(",
"\"Unable to extract subsc... | Extract the first part of the URL, just after subscription:
https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ | [
"Extract",
"the",
"first",
"part",
"of",
"the",
"URL",
"just",
"after",
"subscription",
":",
"https",
":",
"//",
"management",
".",
"azure",
".",
"com",
"/",
"subscriptions",
"/",
"00000000",
"-",
"0000",
"-",
"0000",
"-",
"0000",
"-",
"000000000000",
"/... | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L76-L83 |
Azure/msrestazure-for-python | msrestazure/tools.py | _register_rp | def _register_rp(session, url_prefix, rp_name):
"""Synchronously register the RP is paremeter.
Return False if we have a reason to believe this didn't work
"""
post_url = "{}providers/{}/register?api-version=2016-02-01".format(url_prefix, rp_name)
get_url = "{}providers/{}?api-version=2016-02-0... | python | def _register_rp(session, url_prefix, rp_name):
"""Synchronously register the RP is paremeter.
Return False if we have a reason to believe this didn't work
"""
post_url = "{}providers/{}/register?api-version=2016-02-01".format(url_prefix, rp_name)
get_url = "{}providers/{}?api-version=2016-02-0... | [
"def",
"_register_rp",
"(",
"session",
",",
"url_prefix",
",",
"rp_name",
")",
":",
"post_url",
"=",
"\"{}providers/{}/register?api-version=2016-02-01\"",
".",
"format",
"(",
"url_prefix",
",",
"rp_name",
")",
"get_url",
"=",
"\"{}providers/{}?api-version=2016-02-01\"",
... | Synchronously register the RP is paremeter.
Return False if we have a reason to believe this didn't work | [
"Synchronously",
"register",
"the",
"RP",
"is",
"paremeter",
".",
"Return",
"False",
"if",
"we",
"have",
"a",
"reason",
"to",
"believe",
"this",
"didn",
"t",
"work"
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L85-L104 |
Azure/msrestazure-for-python | msrestazure/tools.py | parse_resource_id | def parse_resource_id(rid):
"""Parses a resource_id into its various parts.
Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id.
:param rid: The resource id being parsed
:type rid: str
:returns: A dictionary with with following key/value pairs (if found):
... | python | def parse_resource_id(rid):
"""Parses a resource_id into its various parts.
Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id.
:param rid: The resource id being parsed
:type rid: str
:returns: A dictionary with with following key/value pairs (if found):
... | [
"def",
"parse_resource_id",
"(",
"rid",
")",
":",
"if",
"not",
"rid",
":",
"return",
"{",
"}",
"match",
"=",
"_ARMID_RE",
".",
"match",
"(",
"rid",
")",
"if",
"match",
":",
"result",
"=",
"match",
".",
"groupdict",
"(",
")",
"children",
"=",
"_CHILDR... | Parses a resource_id into its various parts.
Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id.
:param rid: The resource id being parsed
:type rid: str
:returns: A dictionary with with following key/value pairs (if found):
- subscription: Subscr... | [
"Parses",
"a",
"resource_id",
"into",
"its",
"various",
"parts",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L106-L147 |
Azure/msrestazure-for-python | msrestazure/tools.py | _populate_alternate_kwargs | def _populate_alternate_kwargs(kwargs):
""" Translates the parsed arguments into a format used by generic ARM commands
such as the resource and lock commands.
"""
resource_namespace = kwargs['namespace']
resource_type = kwargs.get('child_type_{}'.format(kwargs['last_child_num'])) or kwargs['type']
... | python | def _populate_alternate_kwargs(kwargs):
""" Translates the parsed arguments into a format used by generic ARM commands
such as the resource and lock commands.
"""
resource_namespace = kwargs['namespace']
resource_type = kwargs.get('child_type_{}'.format(kwargs['last_child_num'])) or kwargs['type']
... | [
"def",
"_populate_alternate_kwargs",
"(",
"kwargs",
")",
":",
"resource_namespace",
"=",
"kwargs",
"[",
"'namespace'",
"]",
"resource_type",
"=",
"kwargs",
".",
"get",
"(",
"'child_type_{}'",
".",
"format",
"(",
"kwargs",
"[",
"'last_child_num'",
"]",
")",
")",
... | Translates the parsed arguments into a format used by generic ARM commands
such as the resource and lock commands. | [
"Translates",
"the",
"parsed",
"arguments",
"into",
"a",
"format",
"used",
"by",
"generic",
"ARM",
"commands",
"such",
"as",
"the",
"resource",
"and",
"lock",
"commands",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L149-L162 |
Azure/msrestazure-for-python | msrestazure/tools.py | _get_parents_from_parts | def _get_parents_from_parts(kwargs):
""" Get the parents given all the children parameters.
"""
parent_builder = []
if kwargs['last_child_num'] is not None:
parent_builder.append('{type}/{name}/'.format(**kwargs))
for index in range(1, kwargs['last_child_num']):
child_namespa... | python | def _get_parents_from_parts(kwargs):
""" Get the parents given all the children parameters.
"""
parent_builder = []
if kwargs['last_child_num'] is not None:
parent_builder.append('{type}/{name}/'.format(**kwargs))
for index in range(1, kwargs['last_child_num']):
child_namespa... | [
"def",
"_get_parents_from_parts",
"(",
"kwargs",
")",
":",
"parent_builder",
"=",
"[",
"]",
"if",
"kwargs",
"[",
"'last_child_num'",
"]",
"is",
"not",
"None",
":",
"parent_builder",
".",
"append",
"(",
"'{type}/{name}/'",
".",
"format",
"(",
"*",
"*",
"kwarg... | Get the parents given all the children parameters. | [
"Get",
"the",
"parents",
"given",
"all",
"the",
"children",
"parameters",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L164-L183 |
Azure/msrestazure-for-python | msrestazure/tools.py | resource_id | def resource_id(**kwargs):
"""Create a valid resource id string from the given parts.
This method builds the resource id from the left until the next required id parameter
to be appended is not found. It then returns the built up id.
:param dict kwargs: The keyword arguments that will make up the id.
... | python | def resource_id(**kwargs):
"""Create a valid resource id string from the given parts.
This method builds the resource id from the left until the next required id parameter
to be appended is not found. It then returns the built up id.
:param dict kwargs: The keyword arguments that will make up the id.
... | [
"def",
"resource_id",
"(",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"v",
"is",
"not",
"None",
"}",
"rid_builder",
"=",
"[",
"'/subscriptions/{subscription}'",... | Create a valid resource id string from the given parts.
This method builds the resource id from the left until the next required id parameter
to be appended is not found. It then returns the built up id.
:param dict kwargs: The keyword arguments that will make up the id.
The method accepts the fo... | [
"Create",
"a",
"valid",
"resource",
"id",
"string",
"from",
"the",
"given",
"parts",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L185-L228 |
Azure/msrestazure-for-python | msrestazure/tools.py | is_valid_resource_id | def is_valid_resource_id(rid, exception_type=None):
"""Validates the given resource id.
:param rid: The resource id being validated.
:type rid: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whether the id is ... | python | def is_valid_resource_id(rid, exception_type=None):
"""Validates the given resource id.
:param rid: The resource id being validated.
:type rid: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whether the id is ... | [
"def",
"is_valid_resource_id",
"(",
"rid",
",",
"exception_type",
"=",
"None",
")",
":",
"is_valid",
"=",
"False",
"try",
":",
"is_valid",
"=",
"rid",
"and",
"resource_id",
"(",
"*",
"*",
"parse_resource_id",
"(",
"rid",
")",
")",
".",
"lower",
"(",
")",... | Validates the given resource id.
:param rid: The resource id being validated.
:type rid: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whether the id is valid.
:rtype: bool | [
"Validates",
"the",
"given",
"resource",
"id",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L230-L247 |
Azure/msrestazure-for-python | msrestazure/tools.py | is_valid_resource_name | def is_valid_resource_name(rname, exception_type=None):
"""Validates the given resource name to ARM guidelines, individual services may be more restrictive.
:param rname: The resource name being validated.
:type rname: str
:param exception_type: Raises this Exception if invalid.
:type exception_typ... | python | def is_valid_resource_name(rname, exception_type=None):
"""Validates the given resource name to ARM guidelines, individual services may be more restrictive.
:param rname: The resource name being validated.
:type rname: str
:param exception_type: Raises this Exception if invalid.
:type exception_typ... | [
"def",
"is_valid_resource_name",
"(",
"rname",
",",
"exception_type",
"=",
"None",
")",
":",
"match",
"=",
"_ARMNAME_RE",
".",
"match",
"(",
"rname",
")",
"if",
"match",
":",
"return",
"True",
"if",
"exception_type",
":",
"raise",
"exception_type",
"(",
")",... | Validates the given resource name to ARM guidelines, individual services may be more restrictive.
:param rname: The resource name being validated.
:type rname: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whethe... | [
"Validates",
"the",
"given",
"resource",
"name",
"to",
"ARM",
"guidelines",
"individual",
"services",
"may",
"be",
"more",
"restrictive",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L250-L267 |
Azure/msrestazure-for-python | msrestazure/azure_configuration.py | AzureConfiguration.save | def save(self, filepath):
"""Save current configuration to file.
:param str filepath: Path to save file to.
:raises: ValueError if supplied filepath cannot be written to.
"""
self._config.add_section("Azure")
self._config.set("Azure",
"long_runni... | python | def save(self, filepath):
"""Save current configuration to file.
:param str filepath: Path to save file to.
:raises: ValueError if supplied filepath cannot be written to.
"""
self._config.add_section("Azure")
self._config.set("Azure",
"long_runni... | [
"def",
"save",
"(",
"self",
",",
"filepath",
")",
":",
"self",
".",
"_config",
".",
"add_section",
"(",
"\"Azure\"",
")",
"self",
".",
"_config",
".",
"set",
"(",
"\"Azure\"",
",",
"\"long_running_operation_timeout\"",
",",
"self",
".",
"long_running_operation... | Save current configuration to file.
:param str filepath: Path to save file to.
:raises: ValueError if supplied filepath cannot be written to. | [
"Save",
"current",
"configuration",
"to",
"file",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_configuration.py#L70-L80 |
Azure/msrestazure-for-python | msrestazure/azure_configuration.py | AzureConfiguration.load | def load(self, filepath):
"""Load configuration from existing file.
:param str filepath: Path to existing config file.
:raises: ValueError if supplied config file is invalid.
"""
try:
self._config.read(filepath)
self.long_running_operation_timeout = self.... | python | def load(self, filepath):
"""Load configuration from existing file.
:param str filepath: Path to existing config file.
:raises: ValueError if supplied config file is invalid.
"""
try:
self._config.read(filepath)
self.long_running_operation_timeout = self.... | [
"def",
"load",
"(",
"self",
",",
"filepath",
")",
":",
"try",
":",
"self",
".",
"_config",
".",
"read",
"(",
"filepath",
")",
"self",
".",
"long_running_operation_timeout",
"=",
"self",
".",
"_config",
".",
"getint",
"(",
"\"Azure\"",
",",
"\"long_running_... | Load configuration from existing file.
:param str filepath: Path to existing config file.
:raises: ValueError if supplied config file is invalid. | [
"Load",
"configuration",
"from",
"existing",
"file",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_configuration.py#L82-L97 |
Azure/msrestazure-for-python | msrestazure/polling/async_arm_polling.py | AsyncARMPolling._poll | async def _poll(self):
"""Poll status of operation so long as operation is incomplete and
we have an endpoint to query.
:param callable update_cmd: The function to call to retrieve the
latest status of the long running operation.
:raises: OperationFailed if operation status 'Fa... | python | async def _poll(self):
"""Poll status of operation so long as operation is incomplete and
we have an endpoint to query.
:param callable update_cmd: The function to call to retrieve the
latest status of the long running operation.
:raises: OperationFailed if operation status 'Fa... | [
"async",
"def",
"_poll",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"finished",
"(",
")",
":",
"await",
"self",
".",
"_delay",
"(",
")",
"await",
"self",
".",
"update_status",
"(",
")",
"if",
"failed",
"(",
"self",
".",
"_operation",
".",
... | Poll status of operation so long as operation is incomplete and
we have an endpoint to query.
:param callable update_cmd: The function to call to retrieve the
latest status of the long running operation.
:raises: OperationFailed if operation status 'Failed' or 'Cancelled'.
:rai... | [
"Poll",
"status",
"of",
"operation",
"so",
"long",
"as",
"operation",
"is",
"incomplete",
"and",
"we",
"have",
"an",
"endpoint",
"to",
"query",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/async_arm_polling.py#L57-L81 |
Azure/msrestazure-for-python | msrestazure/polling/async_arm_polling.py | AsyncARMPolling._delay | async def _delay(self):
"""Check for a 'retry-after' header to set timeout,
otherwise use configured timeout.
"""
if self._response is None:
await asyncio.sleep(0)
if self._response.headers.get('retry-after'):
await asyncio.sleep(int(self._response.headers... | python | async def _delay(self):
"""Check for a 'retry-after' header to set timeout,
otherwise use configured timeout.
"""
if self._response is None:
await asyncio.sleep(0)
if self._response.headers.get('retry-after'):
await asyncio.sleep(int(self._response.headers... | [
"async",
"def",
"_delay",
"(",
"self",
")",
":",
"if",
"self",
".",
"_response",
"is",
"None",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"0",
")",
"if",
"self",
".",
"_response",
".",
"headers",
".",
"get",
"(",
"'retry-after'",
")",
":",
"await",
... | Check for a 'retry-after' header to set timeout,
otherwise use configured timeout. | [
"Check",
"for",
"a",
"retry",
"-",
"after",
"header",
"to",
"set",
"timeout",
"otherwise",
"use",
"configured",
"timeout",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/async_arm_polling.py#L83-L92 |
Azure/msrestazure-for-python | msrestazure/polling/async_arm_polling.py | AsyncARMPolling.update_status | async def update_status(self):
"""Update the current status of the LRO.
"""
if self._operation.async_url:
self._response = await self.request_status(self._operation.async_url)
self._operation.set_async_url_if_present(self._response)
self._operation.get_status_... | python | async def update_status(self):
"""Update the current status of the LRO.
"""
if self._operation.async_url:
self._response = await self.request_status(self._operation.async_url)
self._operation.set_async_url_if_present(self._response)
self._operation.get_status_... | [
"async",
"def",
"update_status",
"(",
"self",
")",
":",
"if",
"self",
".",
"_operation",
".",
"async_url",
":",
"self",
".",
"_response",
"=",
"await",
"self",
".",
"request_status",
"(",
"self",
".",
"_operation",
".",
"async_url",
")",
"self",
".",
"_o... | Update the current status of the LRO. | [
"Update",
"the",
"current",
"status",
"of",
"the",
"LRO",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/async_arm_polling.py#L94-L111 |
Azure/msrestazure-for-python | msrestazure/polling/async_arm_polling.py | AsyncARMPolling.request_status | async def request_status(self, status_link):
"""Do a simple GET to this status link.
This method re-inject 'x-ms-client-request-id'.
:rtype: requests.Response
"""
# ARM requires to re-inject 'x-ms-client-request-id' while polling
header_parameters = {
'x-ms-... | python | async def request_status(self, status_link):
"""Do a simple GET to this status link.
This method re-inject 'x-ms-client-request-id'.
:rtype: requests.Response
"""
# ARM requires to re-inject 'x-ms-client-request-id' while polling
header_parameters = {
'x-ms-... | [
"async",
"def",
"request_status",
"(",
"self",
",",
"status_link",
")",
":",
"# ARM requires to re-inject 'x-ms-client-request-id' while polling",
"header_parameters",
"=",
"{",
"'x-ms-client-request-id'",
":",
"self",
".",
"_operation",
".",
"initial_response",
".",
"reque... | Do a simple GET to this status link.
This method re-inject 'x-ms-client-request-id'.
:rtype: requests.Response | [
"Do",
"a",
"simple",
"GET",
"to",
"this",
"status",
"link",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/async_arm_polling.py#L113-L125 |
Azure/msrestazure-for-python | msrestazure/azure_exceptions.py | CloudErrorData.message | def message(self, value):
"""Attempt to deconstruct error message to retrieve further
error data.
"""
try:
import ast
value = ast.literal_eval(value)
except (SyntaxError, TypeError, ValueError):
pass
try:
value = value.get('... | python | def message(self, value):
"""Attempt to deconstruct error message to retrieve further
error data.
"""
try:
import ast
value = ast.literal_eval(value)
except (SyntaxError, TypeError, ValueError):
pass
try:
value = value.get('... | [
"def",
"message",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"import",
"ast",
"value",
"=",
"ast",
".",
"literal_eval",
"(",
"value",
")",
"except",
"(",
"SyntaxError",
",",
"TypeError",
",",
"ValueError",
")",
":",
"pass",
"try",
":",
"value",
... | Attempt to deconstruct error message to retrieve further
error data. | [
"Attempt",
"to",
"deconstruct",
"error",
"message",
"to",
"retrieve",
"further",
"error",
"data",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_exceptions.py#L119-L141 |
Azure/msrestazure-for-python | msrestazure/azure_cloud.py | get_cloud_from_metadata_endpoint | def get_cloud_from_metadata_endpoint(arm_endpoint, name=None, session=None):
"""Get a Cloud object from an ARM endpoint.
.. versionadded:: 0.4.11
:Example:
.. code:: python
get_cloud_from_metadata_endpoint(https://management.azure.com/, "Public Azure")
:param str arm_endpoint: The ARM m... | python | def get_cloud_from_metadata_endpoint(arm_endpoint, name=None, session=None):
"""Get a Cloud object from an ARM endpoint.
.. versionadded:: 0.4.11
:Example:
.. code:: python
get_cloud_from_metadata_endpoint(https://management.azure.com/, "Public Azure")
:param str arm_endpoint: The ARM m... | [
"def",
"get_cloud_from_metadata_endpoint",
"(",
"arm_endpoint",
",",
"name",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"cloud",
"=",
"Cloud",
"(",
"name",
"or",
"arm_endpoint",
")",
"cloud",
".",
"endpoints",
".",
"management",
"=",
"arm_endpoint",
... | Get a Cloud object from an ARM endpoint.
.. versionadded:: 0.4.11
:Example:
.. code:: python
get_cloud_from_metadata_endpoint(https://management.azure.com/, "Public Azure")
:param str arm_endpoint: The ARM management endpoint
:param str name: An optional name for the Cloud object. Other... | [
"Get",
"a",
"Cloud",
"object",
"from",
"an",
"ARM",
"endpoint",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_cloud.py#L229-L251 |
Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | get_header_url | def get_header_url(response, header_name):
"""Get a URL from a header requests.
:param requests.Response response: REST call response.
:param str header_name: Header name.
:returns: URL if not None AND valid, None otherwise
"""
url = response.headers.get(header_name)
try:
_validate(... | python | def get_header_url(response, header_name):
"""Get a URL from a header requests.
:param requests.Response response: REST call response.
:param str header_name: Header name.
:returns: URL if not None AND valid, None otherwise
"""
url = response.headers.get(header_name)
try:
_validate(... | [
"def",
"get_header_url",
"(",
"response",
",",
"header_name",
")",
":",
"url",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"header_name",
")",
"try",
":",
"_validate",
"(",
"url",
")",
"except",
"ValueError",
":",
"return",
"None",
"else",
":",
"re... | Get a URL from a header requests.
:param requests.Response response: REST call response.
:param str header_name: Header name.
:returns: URL if not None AND valid, None otherwise | [
"Get",
"a",
"URL",
"from",
"a",
"header",
"requests",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L87-L100 |
Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | LongRunningOperation._is_empty | def _is_empty(self, response):
"""Check if response body contains meaningful content.
:rtype: bool
:raises: DeserializationError if response body contains invalid json data.
"""
# Assume ClientResponse has "body", and otherwise it's a requests.Response
content = response... | python | def _is_empty(self, response):
"""Check if response body contains meaningful content.
:rtype: bool
:raises: DeserializationError if response body contains invalid json data.
"""
# Assume ClientResponse has "body", and otherwise it's a requests.Response
content = response... | [
"def",
"_is_empty",
"(",
"self",
",",
"response",
")",
":",
"# Assume ClientResponse has \"body\", and otherwise it's a requests.Response",
"content",
"=",
"response",
".",
"text",
"(",
")",
"if",
"hasattr",
"(",
"response",
",",
"\"body\"",
")",
"else",
"response",
... | Check if response body contains meaningful content.
:rtype: bool
:raises: DeserializationError if response body contains invalid json data. | [
"Check",
"if",
"response",
"body",
"contains",
"meaningful",
"content",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L142-L156 |
Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | LongRunningOperation._as_json | def _as_json(self, response):
"""Assuming this is not empty, return the content as JSON.
Result/exceptions is not determined if you call this method without testing _is_empty.
:raises: DeserializationError if response body contains invalid json data.
"""
# Assume ClientResponse... | python | def _as_json(self, response):
"""Assuming this is not empty, return the content as JSON.
Result/exceptions is not determined if you call this method without testing _is_empty.
:raises: DeserializationError if response body contains invalid json data.
"""
# Assume ClientResponse... | [
"def",
"_as_json",
"(",
"self",
",",
"response",
")",
":",
"# Assume ClientResponse has \"body\", and otherwise it's a requests.Response",
"content",
"=",
"response",
".",
"text",
"(",
")",
"if",
"hasattr",
"(",
"response",
",",
"\"body\"",
")",
"else",
"response",
... | Assuming this is not empty, return the content as JSON.
Result/exceptions is not determined if you call this method without testing _is_empty.
:raises: DeserializationError if response body contains invalid json data. | [
"Assuming",
"this",
"is",
"not",
"empty",
"return",
"the",
"content",
"as",
"JSON",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L158-L171 |
Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | LongRunningOperation._get_async_status | def _get_async_status(self, response):
"""Attempt to find status info in response body.
:param requests.Response response: latest REST call response.
:rtype: str
:returns: Status if found, else 'None'.
"""
if self._is_empty(response):
return None
body... | python | def _get_async_status(self, response):
"""Attempt to find status info in response body.
:param requests.Response response: latest REST call response.
:rtype: str
:returns: Status if found, else 'None'.
"""
if self._is_empty(response):
return None
body... | [
"def",
"_get_async_status",
"(",
"self",
",",
"response",
")",
":",
"if",
"self",
".",
"_is_empty",
"(",
"response",
")",
":",
"return",
"None",
"body",
"=",
"self",
".",
"_as_json",
"(",
"response",
")",
"return",
"body",
".",
"get",
"(",
"'status'",
... | Attempt to find status info in response body.
:param requests.Response response: latest REST call response.
:rtype: str
:returns: Status if found, else 'None'. | [
"Attempt",
"to",
"find",
"status",
"info",
"in",
"response",
"body",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L180-L190 |
Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | LongRunningOperation._get_provisioning_state | def _get_provisioning_state(self, response):
"""
Attempt to get provisioning state from resource.
:param requests.Response response: latest REST call response.
:returns: Status if found, else 'None'.
"""
if self._is_empty(response):
return None
body = ... | python | def _get_provisioning_state(self, response):
"""
Attempt to get provisioning state from resource.
:param requests.Response response: latest REST call response.
:returns: Status if found, else 'None'.
"""
if self._is_empty(response):
return None
body = ... | [
"def",
"_get_provisioning_state",
"(",
"self",
",",
"response",
")",
":",
"if",
"self",
".",
"_is_empty",
"(",
"response",
")",
":",
"return",
"None",
"body",
"=",
"self",
".",
"_as_json",
"(",
"response",
")",
"return",
"body",
".",
"get",
"(",
"\"prope... | Attempt to get provisioning state from resource.
:param requests.Response response: latest REST call response.
:returns: Status if found, else 'None'. | [
"Attempt",
"to",
"get",
"provisioning",
"state",
"from",
"resource",
".",
":",
"param",
"requests",
".",
"Response",
"response",
":",
"latest",
"REST",
"call",
"response",
".",
":",
"returns",
":",
"Status",
"if",
"found",
"else",
"None",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L192-L201 |
Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | LongRunningOperation.should_do_final_get | def should_do_final_get(self):
"""Check whether the polling should end doing a final GET.
:param requests.Response response: latest REST call response.
:rtype: bool
"""
return ((self.async_url or not self.resource) and self.method in {'PUT', 'PATCH'}) \
or (self.... | python | def should_do_final_get(self):
"""Check whether the polling should end doing a final GET.
:param requests.Response response: latest REST call response.
:rtype: bool
"""
return ((self.async_url or not self.resource) and self.method in {'PUT', 'PATCH'}) \
or (self.... | [
"def",
"should_do_final_get",
"(",
"self",
")",
":",
"return",
"(",
"(",
"self",
".",
"async_url",
"or",
"not",
"self",
".",
"resource",
")",
"and",
"self",
".",
"method",
"in",
"{",
"'PUT'",
",",
"'PATCH'",
"}",
")",
"or",
"(",
"self",
".",
"lro_opt... | Check whether the polling should end doing a final GET.
:param requests.Response response: latest REST call response.
:rtype: bool | [
"Check",
"whether",
"the",
"polling",
"should",
"end",
"doing",
"a",
"final",
"GET",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L203-L210 |
Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | LongRunningOperation.set_initial_status | def set_initial_status(self, response):
"""Process first response after initiating long running
operation and set self.status attribute.
:param requests.Response response: initial REST call response.
"""
self._raise_if_bad_http_status_and_method(response)
if self._is_em... | python | def set_initial_status(self, response):
"""Process first response after initiating long running
operation and set self.status attribute.
:param requests.Response response: initial REST call response.
"""
self._raise_if_bad_http_status_and_method(response)
if self._is_em... | [
"def",
"set_initial_status",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_raise_if_bad_http_status_and_method",
"(",
"response",
")",
"if",
"self",
".",
"_is_empty",
"(",
"response",
")",
":",
"self",
".",
"resource",
"=",
"None",
"else",
":",
"try... | Process first response after initiating long running
operation and set self.status attribute.
:param requests.Response response: initial REST call response. | [
"Process",
"first",
"response",
"after",
"initiating",
"long",
"running",
"operation",
"and",
"set",
"self",
".",
"status",
"attribute",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L212-L245 |
Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | LongRunningOperation.get_status_from_resource | def get_status_from_resource(self, response):
"""Process the latest status update retrieved from the same URL as
the previous request.
:param requests.Response response: latest REST call response.
:raises: BadResponse if status not 200 or 204.
"""
self._raise_if_bad_http... | python | def get_status_from_resource(self, response):
"""Process the latest status update retrieved from the same URL as
the previous request.
:param requests.Response response: latest REST call response.
:raises: BadResponse if status not 200 or 204.
"""
self._raise_if_bad_http... | [
"def",
"get_status_from_resource",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_raise_if_bad_http_status_and_method",
"(",
"response",
")",
"if",
"self",
".",
"_is_empty",
"(",
"response",
")",
":",
"raise",
"BadResponse",
"(",
"'The response from long run... | Process the latest status update retrieved from the same URL as
the previous request.
:param requests.Response response: latest REST call response.
:raises: BadResponse if status not 200 or 204. | [
"Process",
"the",
"latest",
"status",
"update",
"retrieved",
"from",
"the",
"same",
"URL",
"as",
"the",
"previous",
"request",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L265-L280 |
Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | LongRunningOperation.parse_resource | def parse_resource(self, response):
"""Assuming this response is a resource, use the deserialization callback to parse it.
If body is empty, assuming no resource to return.
"""
self._raise_if_bad_http_status_and_method(response)
if not self._is_empty(response):
self.r... | python | def parse_resource(self, response):
"""Assuming this response is a resource, use the deserialization callback to parse it.
If body is empty, assuming no resource to return.
"""
self._raise_if_bad_http_status_and_method(response)
if not self._is_empty(response):
self.r... | [
"def",
"parse_resource",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_raise_if_bad_http_status_and_method",
"(",
"response",
")",
"if",
"not",
"self",
".",
"_is_empty",
"(",
"response",
")",
":",
"self",
".",
"resource",
"=",
"self",
".",
"_deseria... | Assuming this response is a resource, use the deserialization callback to parse it.
If body is empty, assuming no resource to return. | [
"Assuming",
"this",
"response",
"is",
"a",
"resource",
"use",
"the",
"deserialization",
"callback",
"to",
"parse",
"it",
".",
"If",
"body",
"is",
"empty",
"assuming",
"no",
"resource",
"to",
"return",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L282-L290 |
Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | LongRunningOperation.get_status_from_async | def get_status_from_async(self, response):
"""Process the latest status update retrieved from a
'azure-asyncoperation' header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body, or body does not
contain status.
""... | python | def get_status_from_async(self, response):
"""Process the latest status update retrieved from a
'azure-asyncoperation' header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body, or body does not
contain status.
""... | [
"def",
"get_status_from_async",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_raise_if_bad_http_status_and_method",
"(",
"response",
")",
"if",
"self",
".",
"_is_empty",
"(",
"response",
")",
":",
"raise",
"BadResponse",
"(",
"'The response from long runnin... | Process the latest status update retrieved from a
'azure-asyncoperation' header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body, or body does not
contain status. | [
"Process",
"the",
"latest",
"status",
"update",
"retrieved",
"from",
"a",
"azure",
"-",
"asyncoperation",
"header",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L292-L319 |
Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | ARMPolling.initialize | def initialize(self, client, initial_response, deserialization_callback):
"""Set the initial status of this LRO.
:param initial_response: The initial response of the poller
:raises: CloudError if initial status is incorrect LRO state
"""
self._client = client
self._respo... | python | def initialize(self, client, initial_response, deserialization_callback):
"""Set the initial status of this LRO.
:param initial_response: The initial response of the poller
:raises: CloudError if initial status is incorrect LRO state
"""
self._client = client
self._respo... | [
"def",
"initialize",
"(",
"self",
",",
"client",
",",
"initial_response",
",",
"deserialization_callback",
")",
":",
"self",
".",
"_client",
"=",
"client",
"self",
".",
"_response",
"=",
"initial_response",
"self",
".",
"_operation",
"=",
"LongRunningOperation",
... | Set the initial status of this LRO.
:param initial_response: The initial response of the poller
:raises: CloudError if initial status is incorrect LRO state | [
"Set",
"the",
"initial",
"status",
"of",
"this",
"LRO",
"."
] | train | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L368-L386 |
diux-dev/ncluster | benchmarks/pytorch_two_machines.py | worker | def worker():
""" Initialize the distributed environment. """
import torch
import torch.distributed as dist
from torch.multiprocessing import Process
import numpy as np
print("Initializing distributed pytorch")
os.environ['MASTER_ADDR'] = str(args.master_addr)
os.environ['MASTER_PORT'] = str(args.mast... | python | def worker():
""" Initialize the distributed environment. """
import torch
import torch.distributed as dist
from torch.multiprocessing import Process
import numpy as np
print("Initializing distributed pytorch")
os.environ['MASTER_ADDR'] = str(args.master_addr)
os.environ['MASTER_PORT'] = str(args.mast... | [
"def",
"worker",
"(",
")",
":",
"import",
"torch",
"import",
"torch",
".",
"distributed",
"as",
"dist",
"from",
"torch",
".",
"multiprocessing",
"import",
"Process",
"import",
"numpy",
"as",
"np",
"print",
"(",
"\"Initializing distributed pytorch\"",
")",
"os",
... | Initialize the distributed environment. | [
"Initialize",
"the",
"distributed",
"environment",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/benchmarks/pytorch_two_machines.py#L61-L100 |
diux-dev/ncluster | ncluster/ncluster.py | set_backend | def set_backend(backend_name: str):
"""Sets backend (local or aws)"""
global _backend, _backend_name
_backend_name = backend_name
assert not ncluster_globals.task_launched, "Not allowed to change backend after launching a task (this pattern is error-prone)"
if backend_name == 'aws':
_backend = aws_backen... | python | def set_backend(backend_name: str):
"""Sets backend (local or aws)"""
global _backend, _backend_name
_backend_name = backend_name
assert not ncluster_globals.task_launched, "Not allowed to change backend after launching a task (this pattern is error-prone)"
if backend_name == 'aws':
_backend = aws_backen... | [
"def",
"set_backend",
"(",
"backend_name",
":",
"str",
")",
":",
"global",
"_backend",
",",
"_backend_name",
"_backend_name",
"=",
"backend_name",
"assert",
"not",
"ncluster_globals",
".",
"task_launched",
",",
"\"Not allowed to change backend after launching a task (this p... | Sets backend (local or aws) | [
"Sets",
"backend",
"(",
"local",
"or",
"aws",
")"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/ncluster.py#L21-L33 |
diux-dev/ncluster | ncluster/ncluster.py | make_job | def make_job(name: str = '',
run_name: str = '',
num_tasks: int = 0,
install_script: str = '',
**kwargs
) -> backend.Job:
"""
Create a job using current backend. Blocks until all tasks are up and initialized.
Args:
name: name of the job
run... | python | def make_job(name: str = '',
run_name: str = '',
num_tasks: int = 0,
install_script: str = '',
**kwargs
) -> backend.Job:
"""
Create a job using current backend. Blocks until all tasks are up and initialized.
Args:
name: name of the job
run... | [
"def",
"make_job",
"(",
"name",
":",
"str",
"=",
"''",
",",
"run_name",
":",
"str",
"=",
"''",
",",
"num_tasks",
":",
"int",
"=",
"0",
",",
"install_script",
":",
"str",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
"->",
"backend",
".",
"Job",
":",
... | Create a job using current backend. Blocks until all tasks are up and initialized.
Args:
name: name of the job
run_name: name of the run (auto-assigned if empty)
num_tasks: number of tasks
install_script: bash-runnable script
**kwargs:
Returns:
backend.Job | [
"Create",
"a",
"job",
"using",
"current",
"backend",
".",
"Blocks",
"until",
"all",
"tasks",
"are",
"up",
"and",
"initialized",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/ncluster.py#L86-L106 |
diux-dev/ncluster | ncluster/local_backend.py | make_task | def make_task(name='',
run_name='',
**kwargs) -> Task:
"""Create task, also create dummy run if not specified."""
ncluster_globals.task_launched = True
name = ncluster_globals.auto_assign_task_name_if_needed(name)
# tmux can't use . for session names
tmux_session = name.replace('... | python | def make_task(name='',
run_name='',
**kwargs) -> Task:
"""Create task, also create dummy run if not specified."""
ncluster_globals.task_launched = True
name = ncluster_globals.auto_assign_task_name_if_needed(name)
# tmux can't use . for session names
tmux_session = name.replace('... | [
"def",
"make_task",
"(",
"name",
"=",
"''",
",",
"run_name",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
"->",
"Task",
":",
"ncluster_globals",
".",
"task_launched",
"=",
"True",
"name",
"=",
"ncluster_globals",
".",
"auto_assign_task_name_if_needed",
"(",
"nam... | Create task, also create dummy run if not specified. | [
"Create",
"task",
"also",
"create",
"dummy",
"run",
"if",
"not",
"specified",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L447-L469 |
diux-dev/ncluster | ncluster/local_backend.py | Task.switch_window | def switch_window(self, window_id: int):
"""
Switches currently active tmux window for given task. 0 is the default window
Args:
window_id: integer id of tmux window to use
"""
# windows are numbered sequentially 0, 1, 2, ...
# create any missing windows and make them point to the same di... | python | def switch_window(self, window_id: int):
"""
Switches currently active tmux window for given task. 0 is the default window
Args:
window_id: integer id of tmux window to use
"""
# windows are numbered sequentially 0, 1, 2, ...
# create any missing windows and make them point to the same di... | [
"def",
"switch_window",
"(",
"self",
",",
"window_id",
":",
"int",
")",
":",
"# windows are numbered sequentially 0, 1, 2, ...",
"# create any missing windows and make them point to the same directory",
"if",
"window_id",
"not",
"in",
"self",
".",
"tmux_available_window_ids",
"... | Switches currently active tmux window for given task. 0 is the default window
Args:
window_id: integer id of tmux window to use | [
"Switches",
"currently",
"active",
"tmux",
"window",
"for",
"given",
"task",
".",
"0",
"is",
"the",
"default",
"window",
"Args",
":",
"window_id",
":",
"integer",
"id",
"of",
"tmux",
"window",
"to",
"use"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L185-L204 |
diux-dev/ncluster | ncluster/local_backend.py | Task._run_raw | def _run_raw(self, cmd, ignore_errors=False):
"""Runs command directly, skipping tmux interface"""
# TODO: capture stdout/stderr for feature parity with aws_backend
result = os.system(cmd)
if result != 0:
if ignore_errors:
self.log(f"command ({cmd}) failed.")
assert False, "_run_ra... | python | def _run_raw(self, cmd, ignore_errors=False):
"""Runs command directly, skipping tmux interface"""
# TODO: capture stdout/stderr for feature parity with aws_backend
result = os.system(cmd)
if result != 0:
if ignore_errors:
self.log(f"command ({cmd}) failed.")
assert False, "_run_ra... | [
"def",
"_run_raw",
"(",
"self",
",",
"cmd",
",",
"ignore_errors",
"=",
"False",
")",
":",
"# TODO: capture stdout/stderr for feature parity with aws_backend",
"result",
"=",
"os",
".",
"system",
"(",
"cmd",
")",
"if",
"result",
"!=",
"0",
":",
"if",
"ignore_erro... | Runs command directly, skipping tmux interface | [
"Runs",
"command",
"directly",
"skipping",
"tmux",
"interface"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L270-L277 |
diux-dev/ncluster | ncluster/local_backend.py | Task.upload | def upload(self, local_fn, remote_fn=None, dont_overwrite=False):
"""Uploads file to remote instance. If location not specified, dumps it
into default directory. Creates missing directories in path name."""
# support wildcard through glob
if '*' in local_fn:
for local_subfn in glob.glob(local_fn)... | python | def upload(self, local_fn, remote_fn=None, dont_overwrite=False):
"""Uploads file to remote instance. If location not specified, dumps it
into default directory. Creates missing directories in path name."""
# support wildcard through glob
if '*' in local_fn:
for local_subfn in glob.glob(local_fn)... | [
"def",
"upload",
"(",
"self",
",",
"local_fn",
",",
"remote_fn",
"=",
"None",
",",
"dont_overwrite",
"=",
"False",
")",
":",
"# support wildcard through glob",
"if",
"'*'",
"in",
"local_fn",
":",
"for",
"local_subfn",
"in",
"glob",
".",
"glob",
"(",
"local_f... | Uploads file to remote instance. If location not specified, dumps it
into default directory. Creates missing directories in path name. | [
"Uploads",
"file",
"to",
"remote",
"instance",
".",
"If",
"location",
"not",
"specified",
"dumps",
"it",
"into",
"default",
"directory",
".",
"Creates",
"missing",
"directories",
"in",
"path",
"name",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L279-L303 |
diux-dev/ncluster | ncluster/local_backend.py | Task.logdir | def logdir(self):
"""Returns logging directory, creating one if necessary. See "Logdir" section of design doc on naming convention."""
run_name = ncluster_globals.get_run_for_task(self)
logdir = ncluster_globals.get_logdir(run_name)
if logdir:
return logdir
# create logdir. Only single task... | python | def logdir(self):
"""Returns logging directory, creating one if necessary. See "Logdir" section of design doc on naming convention."""
run_name = ncluster_globals.get_run_for_task(self)
logdir = ncluster_globals.get_logdir(run_name)
if logdir:
return logdir
# create logdir. Only single task... | [
"def",
"logdir",
"(",
"self",
")",
":",
"run_name",
"=",
"ncluster_globals",
".",
"get_run_for_task",
"(",
"self",
")",
"logdir",
"=",
"ncluster_globals",
".",
"get_logdir",
"(",
"run_name",
")",
"if",
"logdir",
":",
"return",
"logdir",
"# create logdir. Only si... | Returns logging directory, creating one if necessary. See "Logdir" section of design doc on naming convention. | [
"Returns",
"logging",
"directory",
"creating",
"one",
"if",
"necessary",
".",
"See",
"Logdir",
"section",
"of",
"design",
"doc",
"on",
"naming",
"convention",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L351-L366 |
diux-dev/ncluster | ncluster/local_backend.py | Task.setup_logdir | def setup_logdir(self):
# todo: locking on logdir creation
"""Create logdir for task/job/run. No-op if the task is not chief (0'th task of 0'th job of run)
"""
run_name = ncluster_globals.get_run_for_task(self)
self.log("Creating logdir for run "+run_name)
logdir_root = ncluster_globals.LOGDIR_... | python | def setup_logdir(self):
# todo: locking on logdir creation
"""Create logdir for task/job/run. No-op if the task is not chief (0'th task of 0'th job of run)
"""
run_name = ncluster_globals.get_run_for_task(self)
self.log("Creating logdir for run "+run_name)
logdir_root = ncluster_globals.LOGDIR_... | [
"def",
"setup_logdir",
"(",
"self",
")",
":",
"# todo: locking on logdir creation",
"run_name",
"=",
"ncluster_globals",
".",
"get_run_for_task",
"(",
"self",
")",
"self",
".",
"log",
"(",
"\"Creating logdir for run \"",
"+",
"run_name",
")",
"logdir_root",
"=",
"nc... | Create logdir for task/job/run. No-op if the task is not chief (0'th task of 0'th job of run) | [
"Create",
"logdir",
"for",
"task",
"/",
"job",
"/",
"run",
".",
"No",
"-",
"op",
"if",
"the",
"task",
"is",
"not",
"chief",
"(",
"0",
"th",
"task",
"of",
"0",
"th",
"job",
"of",
"run",
")"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L369-L394 |
diux-dev/ncluster | ncluster/local_backend.py | Run.run | def run(self, *args, **kwargs):
"""Runs command on every job in the run."""
for job in self.jobs:
job.run(*args, **kwargs) | python | def run(self, *args, **kwargs):
"""Runs command on every job in the run."""
for job in self.jobs:
job.run(*args, **kwargs) | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"job",
"in",
"self",
".",
"jobs",
":",
"job",
".",
"run",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Runs command on every job in the run. | [
"Runs",
"command",
"on",
"every",
"job",
"in",
"the",
"run",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L422-L426 |
diux-dev/ncluster | ncluster/local_backend.py | Run.run_with_output | def run_with_output(self, *args, **kwargs):
"""Runs command on every first job in the run, returns stdout."""
for job in self.jobs:
job.run_with_output(*args, **kwargs) | python | def run_with_output(self, *args, **kwargs):
"""Runs command on every first job in the run, returns stdout."""
for job in self.jobs:
job.run_with_output(*args, **kwargs) | [
"def",
"run_with_output",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"job",
"in",
"self",
".",
"jobs",
":",
"job",
".",
"run_with_output",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Runs command on every first job in the run, returns stdout. | [
"Runs",
"command",
"on",
"every",
"first",
"job",
"in",
"the",
"run",
"returns",
"stdout",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L428-L431 |
diux-dev/ncluster | ncluster/local_backend.py | Run._run_raw | def _run_raw(self, *args, **kwargs):
"""_run_raw on every job in the run."""
for job in self.jobs:
job._run_raw(*args, **kwargs) | python | def _run_raw(self, *args, **kwargs):
"""_run_raw on every job in the run."""
for job in self.jobs:
job._run_raw(*args, **kwargs) | [
"def",
"_run_raw",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"job",
"in",
"self",
".",
"jobs",
":",
"job",
".",
"_run_raw",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | _run_raw on every job in the run. | [
"_run_raw",
"on",
"every",
"job",
"in",
"the",
"run",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L433-L436 |
diux-dev/ncluster | ncluster/local_backend.py | Run.upload | def upload(self, *args, **kwargs):
"""Runs command on every job in the run."""
for job in self.jobs:
job.upload(*args, **kwargs) | python | def upload(self, *args, **kwargs):
"""Runs command on every job in the run."""
for job in self.jobs:
job.upload(*args, **kwargs) | [
"def",
"upload",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"job",
"in",
"self",
".",
"jobs",
":",
"job",
".",
"upload",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Runs command on every job in the run. | [
"Runs",
"command",
"on",
"every",
"job",
"in",
"the",
"run",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L438-L441 |
diux-dev/ncluster | ncluster/aws_create_resources.py | network_setup | def network_setup():
"""Creates VPC if it doesn't already exists, configures it for public
internet access, returns vpc, subnet, security_group"""
# from https://gist.github.com/nguyendv/8cfd92fc8ed32ebb78e366f44c2daea6
ec2 = u.get_ec2_resource()
client = u.get_ec2_client()
existing_vpcs = u.get_vpc_dict(... | python | def network_setup():
"""Creates VPC if it doesn't already exists, configures it for public
internet access, returns vpc, subnet, security_group"""
# from https://gist.github.com/nguyendv/8cfd92fc8ed32ebb78e366f44c2daea6
ec2 = u.get_ec2_resource()
client = u.get_ec2_client()
existing_vpcs = u.get_vpc_dict(... | [
"def",
"network_setup",
"(",
")",
":",
"# from https://gist.github.com/nguyendv/8cfd92fc8ed32ebb78e366f44c2daea6",
"ec2",
"=",
"u",
".",
"get_ec2_resource",
"(",
")",
"client",
"=",
"u",
".",
"get_ec2_client",
"(",
")",
"existing_vpcs",
"=",
"u",
".",
"get_vpc_dict",
... | Creates VPC if it doesn't already exists, configures it for public
internet access, returns vpc, subnet, security_group | [
"Creates",
"VPC",
"if",
"it",
"doesn",
"t",
"already",
"exists",
"configures",
"it",
"for",
"public",
"internet",
"access",
"returns",
"vpc",
"subnet",
"security_group"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_create_resources.py#L35-L223 |
diux-dev/ncluster | ncluster/aws_create_resources.py | keypair_setup | def keypair_setup():
"""Creates keypair if necessary, saves private key locally, returns contents
of private key file."""
os.system('mkdir -p ' + u.PRIVATE_KEY_LOCATION)
keypair_name = u.get_keypair_name()
keypair = u.get_keypair_dict().get(keypair_name, None)
keypair_fn = u.get_keypair_fn()
if keypair:... | python | def keypair_setup():
"""Creates keypair if necessary, saves private key locally, returns contents
of private key file."""
os.system('mkdir -p ' + u.PRIVATE_KEY_LOCATION)
keypair_name = u.get_keypair_name()
keypair = u.get_keypair_dict().get(keypair_name, None)
keypair_fn = u.get_keypair_fn()
if keypair:... | [
"def",
"keypair_setup",
"(",
")",
":",
"os",
".",
"system",
"(",
"'mkdir -p '",
"+",
"u",
".",
"PRIVATE_KEY_LOCATION",
")",
"keypair_name",
"=",
"u",
".",
"get_keypair_name",
"(",
")",
"keypair",
"=",
"u",
".",
"get_keypair_dict",
"(",
")",
".",
"get",
"... | Creates keypair if necessary, saves private key locally, returns contents
of private key file. | [
"Creates",
"keypair",
"if",
"necessary",
"saves",
"private",
"key",
"locally",
"returns",
"contents",
"of",
"private",
"key",
"file",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_create_resources.py#L226-L254 |
diux-dev/ncluster | ncluster/aws_create_resources.py | placement_group_setup | def placement_group_setup(group_name):
"""Creates placement_group group if necessary. Returns True if new placement_group
group was created, False otherwise."""
existing_placement_groups = u.get_placement_group_dict()
group = existing_placement_groups.get(group_name, None)
if group:
assert group.state =... | python | def placement_group_setup(group_name):
"""Creates placement_group group if necessary. Returns True if new placement_group
group was created, False otherwise."""
existing_placement_groups = u.get_placement_group_dict()
group = existing_placement_groups.get(group_name, None)
if group:
assert group.state =... | [
"def",
"placement_group_setup",
"(",
"group_name",
")",
":",
"existing_placement_groups",
"=",
"u",
".",
"get_placement_group_dict",
"(",
")",
"group",
"=",
"existing_placement_groups",
".",
"get",
"(",
"group_name",
",",
"None",
")",
"if",
"group",
":",
"assert",... | Creates placement_group group if necessary. Returns True if new placement_group
group was created, False otherwise. | [
"Creates",
"placement_group",
"group",
"if",
"necessary",
".",
"Returns",
"True",
"if",
"new",
"placement_group",
"group",
"was",
"created",
"False",
"otherwise",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_create_resources.py#L257-L273 |
diux-dev/ncluster | ncluster/backend.py | Task.wait_for_file | def wait_for_file(self, fn: str, max_wait_sec: int = 3600 * 24 * 365,
check_interval: float = 0.02) -> bool:
"""
Waits for file maximum of max_wait_sec. Returns True if file was detected within specified max_wait_sec
Args:
fn: filename on task machine
max_wait_sec: how long t... | python | def wait_for_file(self, fn: str, max_wait_sec: int = 3600 * 24 * 365,
check_interval: float = 0.02) -> bool:
"""
Waits for file maximum of max_wait_sec. Returns True if file was detected within specified max_wait_sec
Args:
fn: filename on task machine
max_wait_sec: how long t... | [
"def",
"wait_for_file",
"(",
"self",
",",
"fn",
":",
"str",
",",
"max_wait_sec",
":",
"int",
"=",
"3600",
"*",
"24",
"*",
"365",
",",
"check_interval",
":",
"float",
"=",
"0.02",
")",
"->",
"bool",
":",
"print",
"(",
"\"Waiting for file\"",
",",
"fn",
... | Waits for file maximum of max_wait_sec. Returns True if file was detected within specified max_wait_sec
Args:
fn: filename on task machine
max_wait_sec: how long to wait in seconds
check_interval: how often to check in seconds
Returns:
False if waiting was was cut short by max_wait_sec l... | [
"Waits",
"for",
"file",
"maximum",
"of",
"max_wait_sec",
".",
"Returns",
"True",
"if",
"file",
"was",
"detected",
"within",
"specified",
"max_wait_sec",
"Args",
":",
"fn",
":",
"filename",
"on",
"task",
"machine",
"max_wait_sec",
":",
"how",
"long",
"to",
"w... | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/backend.py#L111-L133 |
diux-dev/ncluster | ncluster/backend.py | Task.upload | def upload(self, local_fn: str, remote_fn: str = '',
dont_overwrite: bool = False):
"""Uploads given file to the task. If remote_fn is not specified, dumps it
into task current directory with the same name.
Args:
local_fn: location of file locally
remote_fn: location of file on tas... | python | def upload(self, local_fn: str, remote_fn: str = '',
dont_overwrite: bool = False):
"""Uploads given file to the task. If remote_fn is not specified, dumps it
into task current directory with the same name.
Args:
local_fn: location of file locally
remote_fn: location of file on tas... | [
"def",
"upload",
"(",
"self",
",",
"local_fn",
":",
"str",
",",
"remote_fn",
":",
"str",
"=",
"''",
",",
"dont_overwrite",
":",
"bool",
"=",
"False",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | Uploads given file to the task. If remote_fn is not specified, dumps it
into task current directory with the same name.
Args:
local_fn: location of file locally
remote_fn: location of file on task
dont_overwrite: if True, will be no-op if target file exists | [
"Uploads",
"given",
"file",
"to",
"the",
"task",
".",
"If",
"remote_fn",
"is",
"not",
"specified",
"dumps",
"it",
"into",
"task",
"current",
"directory",
"with",
"the",
"same",
"name",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/backend.py#L139-L149 |
diux-dev/ncluster | ncluster/backend.py | Job._non_blocking_wrapper | def _non_blocking_wrapper(self, method, *args, **kwargs):
"""Runs given method on every task in the job. Blocks until all tasks finish. Propagates exception from first
failed task."""
exceptions = []
def task_run(task):
try:
getattr(task, method)(*args, **kwargs)
except Exception a... | python | def _non_blocking_wrapper(self, method, *args, **kwargs):
"""Runs given method on every task in the job. Blocks until all tasks finish. Propagates exception from first
failed task."""
exceptions = []
def task_run(task):
try:
getattr(task, method)(*args, **kwargs)
except Exception a... | [
"def",
"_non_blocking_wrapper",
"(",
"self",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"exceptions",
"=",
"[",
"]",
"def",
"task_run",
"(",
"task",
")",
":",
"try",
":",
"getattr",
"(",
"task",
",",
"method",
")",
"(",
"*"... | Runs given method on every task in the job. Blocks until all tasks finish. Propagates exception from first
failed task. | [
"Runs",
"given",
"method",
"on",
"every",
"task",
"in",
"the",
"job",
".",
"Blocks",
"until",
"all",
"tasks",
"finish",
".",
"Propagates",
"exception",
"from",
"first",
"failed",
"task",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/backend.py#L202-L222 |
diux-dev/ncluster | ncluster/aws_util.py | get_vpc_dict | def get_vpc_dict():
"""Returns dictionary of named VPCs {name: vpc}
Assert fails if there's more than one VPC with same name."""
client = get_ec2_client()
response = client.describe_vpcs()
assert is_good_response(response)
result = OrderedDict()
ec2 = get_ec2_resource()
for vpc_response in response['... | python | def get_vpc_dict():
"""Returns dictionary of named VPCs {name: vpc}
Assert fails if there's more than one VPC with same name."""
client = get_ec2_client()
response = client.describe_vpcs()
assert is_good_response(response)
result = OrderedDict()
ec2 = get_ec2_resource()
for vpc_response in response['... | [
"def",
"get_vpc_dict",
"(",
")",
":",
"client",
"=",
"get_ec2_client",
"(",
")",
"response",
"=",
"client",
".",
"describe_vpcs",
"(",
")",
"assert",
"is_good_response",
"(",
"response",
")",
"result",
"=",
"OrderedDict",
"(",
")",
"ec2",
"=",
"get_ec2_resou... | Returns dictionary of named VPCs {name: vpc}
Assert fails if there's more than one VPC with same name. | [
"Returns",
"dictionary",
"of",
"named",
"VPCs",
"{",
"name",
":",
"vpc",
"}"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L50-L72 |
diux-dev/ncluster | ncluster/aws_util.py | get_default_vpc | def get_default_vpc():
"""
Return default VPC or none if not present
"""
ec2 = get_ec2_resource()
for vpc in ec2.vpcs.all():
if vpc.is_default:
return vpc | python | def get_default_vpc():
"""
Return default VPC or none if not present
"""
ec2 = get_ec2_resource()
for vpc in ec2.vpcs.all():
if vpc.is_default:
return vpc | [
"def",
"get_default_vpc",
"(",
")",
":",
"ec2",
"=",
"get_ec2_resource",
"(",
")",
"for",
"vpc",
"in",
"ec2",
".",
"vpcs",
".",
"all",
"(",
")",
":",
"if",
"vpc",
".",
"is_default",
":",
"return",
"vpc"
] | Return default VPC or none if not present | [
"Return",
"default",
"VPC",
"or",
"none",
"if",
"not",
"present"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L75-L83 |
diux-dev/ncluster | ncluster/aws_util.py | get_subnet_dict | def get_subnet_dict():
"""Returns dictionary of "availability zone" -> subnet for current VPC."""
subnet_dict = {}
vpc = get_vpc()
for subnet in vpc.subnets.all():
zone = subnet.availability_zone
assert zone not in subnet_dict, "More than one subnet in %s, why?" % (zone,)
subnet_dict[zone] = subnet
... | python | def get_subnet_dict():
"""Returns dictionary of "availability zone" -> subnet for current VPC."""
subnet_dict = {}
vpc = get_vpc()
for subnet in vpc.subnets.all():
zone = subnet.availability_zone
assert zone not in subnet_dict, "More than one subnet in %s, why?" % (zone,)
subnet_dict[zone] = subnet
... | [
"def",
"get_subnet_dict",
"(",
")",
":",
"subnet_dict",
"=",
"{",
"}",
"vpc",
"=",
"get_vpc",
"(",
")",
"for",
"subnet",
"in",
"vpc",
".",
"subnets",
".",
"all",
"(",
")",
":",
"zone",
"=",
"subnet",
".",
"availability_zone",
"assert",
"zone",
"not",
... | Returns dictionary of "availability zone" -> subnet for current VPC. | [
"Returns",
"dictionary",
"of",
"availability",
"zone",
"-",
">",
"subnet",
"for",
"current",
"VPC",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L86-L94 |
diux-dev/ncluster | ncluster/aws_util.py | get_efs_dict | def get_efs_dict():
"""Returns dictionary of {efs_name: efs_id}"""
# there's no EC2 resource for EFS objects, so return EFS_ID instead
# https://stackoverflow.com/questions/47870342/no-ec2-resource-for-efs-objects
efs_client = get_efs_client()
response = call_with_retries(efs_client.describe_file_systems,
... | python | def get_efs_dict():
"""Returns dictionary of {efs_name: efs_id}"""
# there's no EC2 resource for EFS objects, so return EFS_ID instead
# https://stackoverflow.com/questions/47870342/no-ec2-resource-for-efs-objects
efs_client = get_efs_client()
response = call_with_retries(efs_client.describe_file_systems,
... | [
"def",
"get_efs_dict",
"(",
")",
":",
"# there's no EC2 resource for EFS objects, so return EFS_ID instead",
"# https://stackoverflow.com/questions/47870342/no-ec2-resource-for-efs-objects",
"efs_client",
"=",
"get_efs_client",
"(",
")",
"response",
"=",
"call_with_retries",
"(",
"ef... | Returns dictionary of {efs_name: efs_id} | [
"Returns",
"dictionary",
"of",
"{",
"efs_name",
":",
"efs_id",
"}"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L103-L126 |
diux-dev/ncluster | ncluster/aws_util.py | get_placement_group_dict | def get_placement_group_dict():
"""Returns dictionary of {placement_group_name: (state, strategy)}"""
client = get_ec2_client()
response = client.describe_placement_groups()
assert is_good_response(response)
result = OrderedDict()
ec2 = get_ec2_resource()
for placement_group_response in response['Placem... | python | def get_placement_group_dict():
"""Returns dictionary of {placement_group_name: (state, strategy)}"""
client = get_ec2_client()
response = client.describe_placement_groups()
assert is_good_response(response)
result = OrderedDict()
ec2 = get_ec2_resource()
for placement_group_response in response['Placem... | [
"def",
"get_placement_group_dict",
"(",
")",
":",
"client",
"=",
"get_ec2_client",
"(",
")",
"response",
"=",
"client",
".",
"describe_placement_groups",
"(",
")",
"assert",
"is_good_response",
"(",
"response",
")",
"result",
"=",
"OrderedDict",
"(",
")",
"ec2",... | Returns dictionary of {placement_group_name: (state, strategy)} | [
"Returns",
"dictionary",
"of",
"{",
"placement_group_name",
":",
"(",
"state",
"strategy",
")",
"}"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L129-L145 |
diux-dev/ncluster | ncluster/aws_util.py | get_security_group_dict | def get_security_group_dict():
"""Returns dictionary of named security groups {name: securitygroup}."""
client = get_ec2_client()
response = client.describe_security_groups()
assert is_good_response(response)
result = OrderedDict()
ec2 = get_ec2_resource()
for security_group_response in response['Securi... | python | def get_security_group_dict():
"""Returns dictionary of named security groups {name: securitygroup}."""
client = get_ec2_client()
response = client.describe_security_groups()
assert is_good_response(response)
result = OrderedDict()
ec2 = get_ec2_resource()
for security_group_response in response['Securi... | [
"def",
"get_security_group_dict",
"(",
")",
":",
"client",
"=",
"get_ec2_client",
"(",
")",
"response",
"=",
"client",
".",
"describe_security_groups",
"(",
")",
"assert",
"is_good_response",
"(",
"response",
")",
"result",
"=",
"OrderedDict",
"(",
")",
"ec2",
... | Returns dictionary of named security groups {name: securitygroup}. | [
"Returns",
"dictionary",
"of",
"named",
"security",
"groups",
"{",
"name",
":",
"securitygroup",
"}",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L148-L168 |
diux-dev/ncluster | ncluster/aws_util.py | get_keypair_dict | def get_keypair_dict():
"""Returns dictionary of {keypairname: keypair}"""
client = get_ec2_client()
response = client.describe_key_pairs()
assert is_good_response(response)
result = {}
ec2 = get_ec2_resource()
for keypair in response['KeyPairs']:
keypair_name = keypair.get('KeyName', '')
if key... | python | def get_keypair_dict():
"""Returns dictionary of {keypairname: keypair}"""
client = get_ec2_client()
response = client.describe_key_pairs()
assert is_good_response(response)
result = {}
ec2 = get_ec2_resource()
for keypair in response['KeyPairs']:
keypair_name = keypair.get('KeyName', '')
if key... | [
"def",
"get_keypair_dict",
"(",
")",
":",
"client",
"=",
"get_ec2_client",
"(",
")",
"response",
"=",
"client",
".",
"describe_key_pairs",
"(",
")",
"assert",
"is_good_response",
"(",
"response",
")",
"result",
"=",
"{",
"}",
"ec2",
"=",
"get_ec2_resource",
... | Returns dictionary of {keypairname: keypair} | [
"Returns",
"dictionary",
"of",
"{",
"keypairname",
":",
"keypair",
"}"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L171-L187 |
diux-dev/ncluster | ncluster/aws_util.py | get_prefix | def get_prefix():
"""Global prefix to identify ncluster created resources name used to identify ncluster created resources,
(name of EFS, VPC, keypair prefixes), can be changed through $NCLUSTER_PREFIX for debugging purposes. """
name = os.environ.get('NCLUSTER_PREFIX', DEFAULT_PREFIX)
if name != DEFAULT_PREFI... | python | def get_prefix():
"""Global prefix to identify ncluster created resources name used to identify ncluster created resources,
(name of EFS, VPC, keypair prefixes), can be changed through $NCLUSTER_PREFIX for debugging purposes. """
name = os.environ.get('NCLUSTER_PREFIX', DEFAULT_PREFIX)
if name != DEFAULT_PREFI... | [
"def",
"get_prefix",
"(",
")",
":",
"name",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'NCLUSTER_PREFIX'",
",",
"DEFAULT_PREFIX",
")",
"if",
"name",
"!=",
"DEFAULT_PREFIX",
":",
"validate_prefix",
"(",
"name",
")",
"return",
"name"
] | Global prefix to identify ncluster created resources name used to identify ncluster created resources,
(name of EFS, VPC, keypair prefixes), can be changed through $NCLUSTER_PREFIX for debugging purposes. | [
"Global",
"prefix",
"to",
"identify",
"ncluster",
"created",
"resources",
"name",
"used",
"to",
"identify",
"ncluster",
"created",
"resources",
"(",
"name",
"of",
"EFS",
"VPC",
"keypair",
"prefixes",
")",
"can",
"be",
"changed",
"through",
"$NCLUSTER_PREFIX",
"f... | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L190-L197 |
diux-dev/ncluster | ncluster/aws_util.py | get_keypair_name | def get_keypair_name():
"""Returns current keypair name."""
username = get_username()
assert '-' not in username, "username must not contain -, change $USER"
validate_aws_name(username)
assert len(username) < 30 # to avoid exceeding AWS 127 char limit
return get_prefix() + '-' + username | python | def get_keypair_name():
"""Returns current keypair name."""
username = get_username()
assert '-' not in username, "username must not contain -, change $USER"
validate_aws_name(username)
assert len(username) < 30 # to avoid exceeding AWS 127 char limit
return get_prefix() + '-' + username | [
"def",
"get_keypair_name",
"(",
")",
":",
"username",
"=",
"get_username",
"(",
")",
"assert",
"'-'",
"not",
"in",
"username",
",",
"\"username must not contain -, change $USER\"",
"validate_aws_name",
"(",
"username",
")",
"assert",
"len",
"(",
"username",
")",
"... | Returns current keypair name. | [
"Returns",
"current",
"keypair",
"name",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L247-L254 |
diux-dev/ncluster | ncluster/aws_util.py | get_keypair_fn | def get_keypair_fn():
"""Location of .pem file for current keypair"""
keypair_name = get_keypair_name()
account = get_account_number()
region = get_region()
fn = f'{PRIVATE_KEY_LOCATION}/{keypair_name}-{account}-{region}.pem'
return fn | python | def get_keypair_fn():
"""Location of .pem file for current keypair"""
keypair_name = get_keypair_name()
account = get_account_number()
region = get_region()
fn = f'{PRIVATE_KEY_LOCATION}/{keypair_name}-{account}-{region}.pem'
return fn | [
"def",
"get_keypair_fn",
"(",
")",
":",
"keypair_name",
"=",
"get_keypair_name",
"(",
")",
"account",
"=",
"get_account_number",
"(",
")",
"region",
"=",
"get_region",
"(",
")",
"fn",
"=",
"f'{PRIVATE_KEY_LOCATION}/{keypair_name}-{account}-{region}.pem'",
"return",
"f... | Location of .pem file for current keypair | [
"Location",
"of",
".",
"pem",
"file",
"for",
"current",
"keypair"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L266-L273 |
diux-dev/ncluster | ncluster/aws_util.py | lookup_image | def lookup_image(wildcard):
"""Returns unique ec2.Image whose name matches wildcard
lookup_ami('pytorch*').name => ami-29fa
https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#image
Assert fails if multiple images match or no images match.
"""
ec2 = get_ec2_resource()
filter_ = {'Name'... | python | def lookup_image(wildcard):
"""Returns unique ec2.Image whose name matches wildcard
lookup_ami('pytorch*').name => ami-29fa
https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#image
Assert fails if multiple images match or no images match.
"""
ec2 = get_ec2_resource()
filter_ = {'Name'... | [
"def",
"lookup_image",
"(",
"wildcard",
")",
":",
"ec2",
"=",
"get_ec2_resource",
"(",
")",
"filter_",
"=",
"{",
"'Name'",
":",
"'name'",
",",
"'Values'",
":",
"[",
"wildcard",
"]",
"}",
"images",
"=",
"list",
"(",
"ec2",
".",
"images",
".",
"filter",
... | Returns unique ec2.Image whose name matches wildcard
lookup_ami('pytorch*').name => ami-29fa
https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#image
Assert fails if multiple images match or no images match. | [
"Returns",
"unique",
"ec2",
".",
"Image",
"whose",
"name",
"matches",
"wildcard",
"lookup_ami",
"(",
"pytorch",
"*",
")",
".",
"name",
"=",
">",
"ami",
"-",
"29fa",
"https",
":",
"//",
"boto3",
".",
"readthedocs",
".",
"io",
"/",
"en",
"/",
"latest",
... | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L304-L323 |
diux-dev/ncluster | ncluster/aws_util.py | lookup_instance | def lookup_instance(name: str, instance_type: str = '', image_name: str = '',
states: tuple = ('running', 'stopped', 'initializing')):
"""Looks up AWS instance for given instance name, like
simple.worker. If no instance found in current AWS environment, returns None. """
ec2 = get_ec2_resour... | python | def lookup_instance(name: str, instance_type: str = '', image_name: str = '',
states: tuple = ('running', 'stopped', 'initializing')):
"""Looks up AWS instance for given instance name, like
simple.worker. If no instance found in current AWS environment, returns None. """
ec2 = get_ec2_resour... | [
"def",
"lookup_instance",
"(",
"name",
":",
"str",
",",
"instance_type",
":",
"str",
"=",
"''",
",",
"image_name",
":",
"str",
"=",
"''",
",",
"states",
":",
"tuple",
"=",
"(",
"'running'",
",",
"'stopped'",
",",
"'initializing'",
")",
")",
":",
"ec2",... | Looks up AWS instance for given instance name, like
simple.worker. If no instance found in current AWS environment, returns None. | [
"Looks",
"up",
"AWS",
"instance",
"for",
"given",
"instance",
"name",
"like",
"simple",
".",
"worker",
".",
"If",
"no",
"instance",
"found",
"in",
"current",
"AWS",
"environment",
"returns",
"None",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L326-L366 |
diux-dev/ncluster | ncluster/aws_util.py | ssh_to_task | def ssh_to_task(task) -> paramiko.SSHClient:
"""Create ssh connection to task's machine
returns Paramiko SSH client connected to host.
"""
username = task.ssh_username
hostname = task.public_ip
ssh_key_fn = get_keypair_fn()
print(f"ssh -i {ssh_key_fn} {username}@{hostname}")
pkey = paramiko.RSAKey.fr... | python | def ssh_to_task(task) -> paramiko.SSHClient:
"""Create ssh connection to task's machine
returns Paramiko SSH client connected to host.
"""
username = task.ssh_username
hostname = task.public_ip
ssh_key_fn = get_keypair_fn()
print(f"ssh -i {ssh_key_fn} {username}@{hostname}")
pkey = paramiko.RSAKey.fr... | [
"def",
"ssh_to_task",
"(",
"task",
")",
"->",
"paramiko",
".",
"SSHClient",
":",
"username",
"=",
"task",
".",
"ssh_username",
"hostname",
"=",
"task",
".",
"public_ip",
"ssh_key_fn",
"=",
"get_keypair_fn",
"(",
")",
"print",
"(",
"f\"ssh -i {ssh_key_fn} {userna... | Create ssh connection to task's machine
returns Paramiko SSH client connected to host. | [
"Create",
"ssh",
"connection",
"to",
"task",
"s",
"machine"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L369-L398 |
diux-dev/ncluster | ncluster/aws_util.py | validate_aws_name | def validate_aws_name(name):
"""Validate resource name using AWS name restrictions from # http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-restrictions"""
assert len(name) <= 127
# disallow unicode characters to avoid pain
assert name == name.encode('ascii').decode('ascii')
assert aws_na... | python | def validate_aws_name(name):
"""Validate resource name using AWS name restrictions from # http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-restrictions"""
assert len(name) <= 127
# disallow unicode characters to avoid pain
assert name == name.encode('ascii').decode('ascii')
assert aws_na... | [
"def",
"validate_aws_name",
"(",
"name",
")",
":",
"assert",
"len",
"(",
"name",
")",
"<=",
"127",
"# disallow unicode characters to avoid pain",
"assert",
"name",
"==",
"name",
".",
"encode",
"(",
"'ascii'",
")",
".",
"decode",
"(",
"'ascii'",
")",
"assert",
... | Validate resource name using AWS name restrictions from # http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-restrictions | [
"Validate",
"resource",
"name",
"using",
"AWS",
"name",
"restrictions",
"from",
"#",
"http",
":",
"//",
"docs",
".",
"aws",
".",
"amazon",
".",
"com",
"/",
"AWSEC2",
"/",
"latest",
"/",
"UserGuide",
"/",
"Using_Tags",
".",
"html#tag",
"-",
"restrictions"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L415-L420 |
diux-dev/ncluster | ncluster/aws_util.py | delete_efs_by_id | def delete_efs_by_id(efs_id):
"""Deletion sometimes fails, try several times."""
start_time = time.time()
efs_client = get_efs_client()
sys.stdout.write("deleting %s ... " % (efs_id,))
while True:
try:
response = efs_client.delete_file_system(FileSystemId=efs_id)
if is_good_response(response):... | python | def delete_efs_by_id(efs_id):
"""Deletion sometimes fails, try several times."""
start_time = time.time()
efs_client = get_efs_client()
sys.stdout.write("deleting %s ... " % (efs_id,))
while True:
try:
response = efs_client.delete_file_system(FileSystemId=efs_id)
if is_good_response(response):... | [
"def",
"delete_efs_by_id",
"(",
"efs_id",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"efs_client",
"=",
"get_efs_client",
"(",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"deleting %s ... \"",
"%",
"(",
"efs_id",
",",
")",
")",
"whil... | Deletion sometimes fails, try several times. | [
"Deletion",
"sometimes",
"fails",
"try",
"several",
"times",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L488-L507 |
diux-dev/ncluster | ncluster/aws_util.py | extract_attr_for_match | def extract_attr_for_match(items, **kwargs):
"""Helper method to get attribute value for an item matching some criterion.
Specify target criteria value as dict, with target attribute having value -1
Example:
to extract state of vpc matching given vpc id
response = [{'State': 'available', 'VpcId': 'vpc-2bb... | python | def extract_attr_for_match(items, **kwargs):
"""Helper method to get attribute value for an item matching some criterion.
Specify target criteria value as dict, with target attribute having value -1
Example:
to extract state of vpc matching given vpc id
response = [{'State': 'available', 'VpcId': 'vpc-2bb... | [
"def",
"extract_attr_for_match",
"(",
"items",
",",
"*",
"*",
"kwargs",
")",
":",
"# find the value of attribute to return",
"query_arg",
"=",
"None",
"for",
"arg",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"value",
"==",
"-",
"1",
"... | Helper method to get attribute value for an item matching some criterion.
Specify target criteria value as dict, with target attribute having value -1
Example:
to extract state of vpc matching given vpc id
response = [{'State': 'available', 'VpcId': 'vpc-2bb1584c'}]
extract_attr_for_match(response, State=... | [
"Helper",
"method",
"to",
"get",
"attribute",
"value",
"for",
"an",
"item",
"matching",
"some",
"criterion",
".",
"Specify",
"target",
"criteria",
"value",
"as",
"dict",
"with",
"target",
"attribute",
"having",
"value",
"-",
"1"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L510-L548 |
diux-dev/ncluster | ncluster/aws_util.py | get_instance_property | def get_instance_property(instance, property_name):
"""Retrieves property of an instance, keeps retrying until getting a non-None"""
name = get_name(instance)
while True:
try:
value = getattr(instance, property_name)
if value is not None:
break
print(f"retrieving {property_name} on ... | python | def get_instance_property(instance, property_name):
"""Retrieves property of an instance, keeps retrying until getting a non-None"""
name = get_name(instance)
while True:
try:
value = getattr(instance, property_name)
if value is not None:
break
print(f"retrieving {property_name} on ... | [
"def",
"get_instance_property",
"(",
"instance",
",",
"property_name",
")",
":",
"name",
"=",
"get_name",
"(",
"instance",
")",
"while",
"True",
":",
"try",
":",
"value",
"=",
"getattr",
"(",
"instance",
",",
"property_name",
")",
"if",
"value",
"is",
"not... | Retrieves property of an instance, keeps retrying until getting a non-None | [
"Retrieves",
"property",
"of",
"an",
"instance",
"keeps",
"retrying",
"until",
"getting",
"a",
"non",
"-",
"None"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L565-L587 |
diux-dev/ncluster | ncluster/aws_util.py | get_name | def get_name(tags_or_instance_or_id):
"""Helper utility to extract name out of tags dictionary or intancce.
[{'Key': 'Name', 'Value': 'nexus'}] -> 'nexus'
Assert fails if there's more than one name.
Returns '' if there's less than one name.
"""
ec2 = get_ec2_resource()
if hasattr(tags_or_inst... | python | def get_name(tags_or_instance_or_id):
"""Helper utility to extract name out of tags dictionary or intancce.
[{'Key': 'Name', 'Value': 'nexus'}] -> 'nexus'
Assert fails if there's more than one name.
Returns '' if there's less than one name.
"""
ec2 = get_ec2_resource()
if hasattr(tags_or_inst... | [
"def",
"get_name",
"(",
"tags_or_instance_or_id",
")",
":",
"ec2",
"=",
"get_ec2_resource",
"(",
")",
"if",
"hasattr",
"(",
"tags_or_instance_or_id",
",",
"'tags'",
")",
":",
"tags",
"=",
"tags_or_instance_or_id",
".",
"tags",
"elif",
"isinstance",
"(",
"tags_or... | Helper utility to extract name out of tags dictionary or intancce.
[{'Key': 'Name', 'Value': 'nexus'}] -> 'nexus'
Assert fails if there's more than one name.
Returns '' if there's less than one name. | [
"Helper",
"utility",
"to",
"extract",
"name",
"out",
"of",
"tags",
"dictionary",
"or",
"intancce",
".",
"[",
"{",
"Key",
":",
"Name",
"Value",
":",
"nexus",
"}",
"]",
"-",
">",
"nexus",
"Assert",
"fails",
"if",
"there",
"s",
"more",
"than",
"one",
"n... | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L645-L672 |
diux-dev/ncluster | ncluster/aws_util.py | wait_until_available | def wait_until_available(resource):
"""Waits until interval state becomes 'available'"""
while True:
resource.load()
if resource.state == 'available':
break
time.sleep(RETRY_INTERVAL_SEC) | python | def wait_until_available(resource):
"""Waits until interval state becomes 'available'"""
while True:
resource.load()
if resource.state == 'available':
break
time.sleep(RETRY_INTERVAL_SEC) | [
"def",
"wait_until_available",
"(",
"resource",
")",
":",
"while",
"True",
":",
"resource",
".",
"load",
"(",
")",
"if",
"resource",
".",
"state",
"==",
"'available'",
":",
"break",
"time",
".",
"sleep",
"(",
"RETRY_INTERVAL_SEC",
")"
] | Waits until interval state becomes 'available | [
"Waits",
"until",
"interval",
"state",
"becomes",
"available"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L675-L681 |
diux-dev/ncluster | ncluster/aws_util.py | maybe_create_placement_group | def maybe_create_placement_group(name='', max_retries=10):
"""Creates placement_group group or reuses existing one. Crash if unable to create
placement_group group. If name is empty, ignores request."""
if not name:
return
client = get_ec2_client()
while True:
try:
client.describe_placement_... | python | def maybe_create_placement_group(name='', max_retries=10):
"""Creates placement_group group or reuses existing one. Crash if unable to create
placement_group group. If name is empty, ignores request."""
if not name:
return
client = get_ec2_client()
while True:
try:
client.describe_placement_... | [
"def",
"maybe_create_placement_group",
"(",
"name",
"=",
"''",
",",
"max_retries",
"=",
"10",
")",
":",
"if",
"not",
"name",
":",
"return",
"client",
"=",
"get_ec2_client",
"(",
")",
"while",
"True",
":",
"try",
":",
"client",
".",
"describe_placement_groups... | Creates placement_group group or reuses existing one. Crash if unable to create
placement_group group. If name is empty, ignores request. | [
"Creates",
"placement_group",
"group",
"or",
"reuses",
"existing",
"one",
".",
"Crash",
"if",
"unable",
"to",
"create",
"placement_group",
"group",
".",
"If",
"name",
"is",
"empty",
"ignores",
"request",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L684-L719 |
diux-dev/ncluster | ncluster/aws_util.py | lookup_instances | def lookup_instances(fragment, verbose=True, filter_by_key=True):
"""Returns ec2.Instance object whose name contains fragment, in reverse order of launching (ie,
most recent intance first). Optionally filters by key, only including instances launched with
key_name matching current username.
args:
verbose: ... | python | def lookup_instances(fragment, verbose=True, filter_by_key=True):
"""Returns ec2.Instance object whose name contains fragment, in reverse order of launching (ie,
most recent intance first). Optionally filters by key, only including instances launched with
key_name matching current username.
args:
verbose: ... | [
"def",
"lookup_instances",
"(",
"fragment",
",",
"verbose",
"=",
"True",
",",
"filter_by_key",
"=",
"True",
")",
":",
"def",
"vprint",
"(",
"*",
"args",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"*",
"args",
")",
"region",
"=",
"get_region",
"(",
... | Returns ec2.Instance object whose name contains fragment, in reverse order of launching (ie,
most recent intance first). Optionally filters by key, only including instances launched with
key_name matching current username.
args:
verbose: print information about all matching instances found
filter_by_key... | [
"Returns",
"ec2",
".",
"Instance",
"object",
"whose",
"name",
"contains",
"fragment",
"in",
"reverse",
"order",
"of",
"launching",
"(",
"ie",
"most",
"recent",
"intance",
"first",
")",
".",
"Optionally",
"filters",
"by",
"key",
"only",
"including",
"instances"... | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L730-L770 |
diux-dev/ncluster | ncluster/aws_util.py | create_spot_instances | def create_spot_instances(launch_specs, spot_price=26, expiration_mins=15):
"""
args:
spot_price: default is $26 which is right above p3.16xlarge on demand price
expiration_mins: this request only valid for this many mins from now
"""
ec2c = get_ec2_client()
num_tasks = launch_specs['Mi... | python | def create_spot_instances(launch_specs, spot_price=26, expiration_mins=15):
"""
args:
spot_price: default is $26 which is right above p3.16xlarge on demand price
expiration_mins: this request only valid for this many mins from now
"""
ec2c = get_ec2_client()
num_tasks = launch_specs['Mi... | [
"def",
"create_spot_instances",
"(",
"launch_specs",
",",
"spot_price",
"=",
"26",
",",
"expiration_mins",
"=",
"15",
")",
":",
"ec2c",
"=",
"get_ec2_client",
"(",
")",
"num_tasks",
"=",
"launch_specs",
"[",
"'MinCount'",
"]",
"or",
"1",
"if",
"'MinCount'",
... | args:
spot_price: default is $26 which is right above p3.16xlarge on demand price
expiration_mins: this request only valid for this many mins from now | [
"args",
":",
"spot_price",
":",
"default",
"is",
"$26",
"which",
"is",
"right",
"above",
"p3",
".",
"16xlarge",
"on",
"demand",
"price",
"expiration_mins",
":",
"this",
"request",
"only",
"valid",
"for",
"this",
"many",
"mins",
"from",
"now"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L772-L819 |
diux-dev/ncluster | ncluster/ncluster_globals.py | is_chief | def is_chief(task: backend.Task, run_name: str):
"""Returns True if task is chief task in the corresponding run"""
global run_task_dict
if run_name not in run_task_dict:
return True
task_list = run_task_dict[run_name]
assert task in task_list, f"Task {task.name} doesn't belong to run {run_name}"
return ... | python | def is_chief(task: backend.Task, run_name: str):
"""Returns True if task is chief task in the corresponding run"""
global run_task_dict
if run_name not in run_task_dict:
return True
task_list = run_task_dict[run_name]
assert task in task_list, f"Task {task.name} doesn't belong to run {run_name}"
return ... | [
"def",
"is_chief",
"(",
"task",
":",
"backend",
".",
"Task",
",",
"run_name",
":",
"str",
")",
":",
"global",
"run_task_dict",
"if",
"run_name",
"not",
"in",
"run_task_dict",
":",
"return",
"True",
"task_list",
"=",
"run_task_dict",
"[",
"run_name",
"]",
"... | Returns True if task is chief task in the corresponding run | [
"Returns",
"True",
"if",
"task",
"is",
"chief",
"task",
"in",
"the",
"corresponding",
"run"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/ncluster_globals.py#L88-L95 |
diux-dev/ncluster | benchmarks/util.py | ossystem | def ossystem(cmd):
"""Like os.system, but returns output of command as string."""
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
(stdout, stderr) = p.communicate()
return stdout.decode('ascii') | python | def ossystem(cmd):
"""Like os.system, but returns output of command as string."""
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
(stdout, stderr) = p.communicate()
return stdout.decode('ascii') | [
"def",
"ossystem",
"(",
"cmd",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"(",
"stdout",
",",
"stderr",
... | Like os.system, but returns output of command as string. | [
"Like",
"os",
".",
"system",
"but",
"returns",
"output",
"of",
"command",
"as",
"string",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/benchmarks/util.py#L40-L45 |
diux-dev/ncluster | ncluster/aws_backend.py | make_task | def make_task(
name: str = '',
run_name: str = '',
install_script: str = '',
instance_type: str = '',
image_name: str = '',
disk_size: int = 0,
preemptible=None,
logging_task: backend.Task = None,
create_resources=True,
spot=False
) -> Task... | python | def make_task(
name: str = '',
run_name: str = '',
install_script: str = '',
instance_type: str = '',
image_name: str = '',
disk_size: int = 0,
preemptible=None,
logging_task: backend.Task = None,
create_resources=True,
spot=False
) -> Task... | [
"def",
"make_task",
"(",
"name",
":",
"str",
"=",
"''",
",",
"run_name",
":",
"str",
"=",
"''",
",",
"install_script",
":",
"str",
"=",
"''",
",",
"instance_type",
":",
"str",
"=",
"''",
",",
"image_name",
":",
"str",
"=",
"''",
",",
"disk_size",
"... | Create task on AWS.
Automatically places it in singleton Run/singleton Job objects, see Run/Job/Task hierarchy for details
https://docs.google.com/document/d/1Gg4T243cYrDUW1YDCikmqp7fzSQDU3rZxOkJr9ohhs8/edit#heading=h.j4td4oixogib
Args:
disk_size: default size of root disk, in GBs
create_resources: whe... | [
"Create",
"task",
"on",
"AWS",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L641-L810 |
diux-dev/ncluster | ncluster/aws_backend.py | make_job | def make_job(
name: str = '',
run_name: str = '',
num_tasks: int = 1,
install_script: str = '',
instance_type: str = '',
image_name: str = '',
create_resources=True,
**kwargs) -> Job:
"""
Args:
create_resources: if True, will create resources if ne... | python | def make_job(
name: str = '',
run_name: str = '',
num_tasks: int = 1,
install_script: str = '',
instance_type: str = '',
image_name: str = '',
create_resources=True,
**kwargs) -> Job:
"""
Args:
create_resources: if True, will create resources if ne... | [
"def",
"make_job",
"(",
"name",
":",
"str",
"=",
"''",
",",
"run_name",
":",
"str",
"=",
"''",
",",
"num_tasks",
":",
"int",
"=",
"1",
",",
"install_script",
":",
"str",
"=",
"''",
",",
"instance_type",
":",
"str",
"=",
"''",
",",
"image_name",
":"... | Args:
create_resources: if True, will create resources if necessary
name: see backend.make_task
run_name: see backend.make_task
num_tasks: number of tasks to launch
install_script: see make_task
instance_type: see make_task
image_name: see make_task
Returns: | [
"Args",
":",
"create_resources",
":",
"if",
"True",
"will",
"create",
"resources",
"if",
"necessary",
"name",
":",
"see",
"backend",
".",
"make_task",
"run_name",
":",
"see",
"backend",
".",
"make_task",
"num_tasks",
":",
"number",
"of",
"tasks",
"to",
"laun... | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L813-L892 |
diux-dev/ncluster | ncluster/aws_backend.py | _maybe_start_instance | def _maybe_start_instance(instance):
"""Starts instance if it's stopped, no-op otherwise."""
if not instance:
return
if instance.state['Name'] == 'stopped':
instance.start()
while True:
print(f"Waiting for {instance} to start.")
instance.reload()
if instance.state['Name'] == 'runn... | python | def _maybe_start_instance(instance):
"""Starts instance if it's stopped, no-op otherwise."""
if not instance:
return
if instance.state['Name'] == 'stopped':
instance.start()
while True:
print(f"Waiting for {instance} to start.")
instance.reload()
if instance.state['Name'] == 'runn... | [
"def",
"_maybe_start_instance",
"(",
"instance",
")",
":",
"if",
"not",
"instance",
":",
"return",
"if",
"instance",
".",
"state",
"[",
"'Name'",
"]",
"==",
"'stopped'",
":",
"instance",
".",
"start",
"(",
")",
"while",
"True",
":",
"print",
"(",
"f\"Wai... | Starts instance if it's stopped, no-op otherwise. | [
"Starts",
"instance",
"if",
"it",
"s",
"stopped",
"no",
"-",
"op",
"otherwise",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L902-L915 |
diux-dev/ncluster | ncluster/aws_backend.py | _maybe_wait_for_initializing_instance | def _maybe_wait_for_initializing_instance(instance):
"""Starts instance if it's stopped, no-op otherwise."""
if not instance:
return
if instance.state['Name'] == 'initializing':
while True:
print(f"Waiting for {instance} to leave state 'initializing'.")
instance.reload()
if instance.s... | python | def _maybe_wait_for_initializing_instance(instance):
"""Starts instance if it's stopped, no-op otherwise."""
if not instance:
return
if instance.state['Name'] == 'initializing':
while True:
print(f"Waiting for {instance} to leave state 'initializing'.")
instance.reload()
if instance.s... | [
"def",
"_maybe_wait_for_initializing_instance",
"(",
"instance",
")",
":",
"if",
"not",
"instance",
":",
"return",
"if",
"instance",
".",
"state",
"[",
"'Name'",
"]",
"==",
"'initializing'",
":",
"while",
"True",
":",
"print",
"(",
"f\"Waiting for {instance} to l... | Starts instance if it's stopped, no-op otherwise. | [
"Starts",
"instance",
"if",
"it",
"s",
"stopped",
"no",
"-",
"op",
"otherwise",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L918-L930 |
diux-dev/ncluster | ncluster/aws_backend.py | _maybe_create_resources | def _maybe_create_resources(logging_task: Task = None):
"""Use heuristics to decide to possibly create resources"""
def log(*args):
if logging_task:
logging_task.log(*args)
else:
util.log(*args)
def should_create_resources():
"""Check if gateway, keypair, vpc exist."""
prefix = u.get... | python | def _maybe_create_resources(logging_task: Task = None):
"""Use heuristics to decide to possibly create resources"""
def log(*args):
if logging_task:
logging_task.log(*args)
else:
util.log(*args)
def should_create_resources():
"""Check if gateway, keypair, vpc exist."""
prefix = u.get... | [
"def",
"_maybe_create_resources",
"(",
"logging_task",
":",
"Task",
"=",
"None",
")",
":",
"def",
"log",
"(",
"*",
"args",
")",
":",
"if",
"logging_task",
":",
"logging_task",
".",
"log",
"(",
"*",
"args",
")",
"else",
":",
"util",
".",
"log",
"(",
"... | Use heuristics to decide to possibly create resources | [
"Use",
"heuristics",
"to",
"decide",
"to",
"possibly",
"create",
"resources"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L933-L990 |
diux-dev/ncluster | ncluster/aws_backend.py | _set_aws_environment | def _set_aws_environment(task: Task = None):
"""Sets up AWS environment from NCLUSTER environment variables"""
current_zone = os.environ.get('NCLUSTER_ZONE', '')
current_region = os.environ.get('AWS_DEFAULT_REGION', '')
def log(*args):
if task:
task.log(*args)
else:
util.log(*args)
if cu... | python | def _set_aws_environment(task: Task = None):
"""Sets up AWS environment from NCLUSTER environment variables"""
current_zone = os.environ.get('NCLUSTER_ZONE', '')
current_region = os.environ.get('AWS_DEFAULT_REGION', '')
def log(*args):
if task:
task.log(*args)
else:
util.log(*args)
if cu... | [
"def",
"_set_aws_environment",
"(",
"task",
":",
"Task",
"=",
"None",
")",
":",
"current_zone",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'NCLUSTER_ZONE'",
",",
"''",
")",
"current_region",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'AWS_DEFAULT_REGIO... | Sets up AWS environment from NCLUSTER environment variables | [
"Sets",
"up",
"AWS",
"environment",
"from",
"NCLUSTER",
"environment",
"variables"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L993-L1030 |
diux-dev/ncluster | ncluster/aws_backend.py | Task.join | def join(self, ignore_errors=False):
"""Waits until last executed command completed."""
assert self._status_fn, "Asked to join a task which hasn't had any commands executed on it"
check_interval = 0.2
status_fn = self._status_fn
if not self.wait_for_file(status_fn, max_wait_sec=30):
self.log(f... | python | def join(self, ignore_errors=False):
"""Waits until last executed command completed."""
assert self._status_fn, "Asked to join a task which hasn't had any commands executed on it"
check_interval = 0.2
status_fn = self._status_fn
if not self.wait_for_file(status_fn, max_wait_sec=30):
self.log(f... | [
"def",
"join",
"(",
"self",
",",
"ignore_errors",
"=",
"False",
")",
":",
"assert",
"self",
".",
"_status_fn",
",",
"\"Asked to join a task which hasn't had any commands executed on it\"",
"check_interval",
"=",
"0.2",
"status_fn",
"=",
"self",
".",
"_status_fn",
"if"... | Waits until last executed command completed. | [
"Waits",
"until",
"last",
"executed",
"command",
"completed",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L272-L302 |
diux-dev/ncluster | ncluster/aws_backend.py | Task._run_with_output_on_failure | def _run_with_output_on_failure(self, cmd, non_blocking=False,
ignore_errors=False,
max_wait_sec=365 * 24 * 3600,
check_interval=0.2) -> str:
"""Experimental version of run propagates error messages to client. This... | python | def _run_with_output_on_failure(self, cmd, non_blocking=False,
ignore_errors=False,
max_wait_sec=365 * 24 * 3600,
check_interval=0.2) -> str:
"""Experimental version of run propagates error messages to client. This... | [
"def",
"_run_with_output_on_failure",
"(",
"self",
",",
"cmd",
",",
"non_blocking",
"=",
"False",
",",
"ignore_errors",
"=",
"False",
",",
"max_wait_sec",
"=",
"365",
"*",
"24",
"*",
"3600",
",",
"check_interval",
"=",
"0.2",
")",
"->",
"str",
":",
"if",
... | Experimental version of run propagates error messages to client. This command will be default "run" eventually | [
"Experimental",
"version",
"of",
"run",
"propagates",
"error",
"messages",
"to",
"client",
".",
"This",
"command",
"will",
"be",
"default",
"run",
"eventually"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L304-L373 |
diux-dev/ncluster | ncluster/aws_backend.py | Task._run_raw | def _run_raw(self, cmd: str, ignore_errors=False) -> Tuple[str, str]:
"""Runs given cmd in the task using current SSH session, returns
stdout/stderr as strings. Because it blocks until cmd is done, use it for
short cmds. Silently ignores failing commands.
This is a barebones method to be used during in... | python | def _run_raw(self, cmd: str, ignore_errors=False) -> Tuple[str, str]:
"""Runs given cmd in the task using current SSH session, returns
stdout/stderr as strings. Because it blocks until cmd is done, use it for
short cmds. Silently ignores failing commands.
This is a barebones method to be used during in... | [
"def",
"_run_raw",
"(",
"self",
",",
"cmd",
":",
"str",
",",
"ignore_errors",
"=",
"False",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"# self._log(\"run_ssh: %s\"%(cmd,))",
"stdin",
",",
"stdout",
",",
"stderr",
"=",
"u",
".",
"call_with_ret... | Runs given cmd in the task using current SSH session, returns
stdout/stderr as strings. Because it blocks until cmd is done, use it for
short cmds. Silently ignores failing commands.
This is a barebones method to be used during initialization that have
minimal dependencies (no tmux) | [
"Runs",
"given",
"cmd",
"in",
"the",
"task",
"using",
"current",
"SSH",
"session",
"returns",
"stdout",
"/",
"stderr",
"as",
"strings",
".",
"Because",
"it",
"blocks",
"until",
"cmd",
"is",
"done",
"use",
"it",
"for",
"short",
"cmds",
".",
"Silently",
"i... | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L375-L396 |
diux-dev/ncluster | ncluster/aws_backend.py | Task.upload | def upload(self, local_fn: str, remote_fn: str = '',
dont_overwrite: bool = False) -> None:
"""Uploads file to remote instance. If location not specified, dumps it
into default directory. If remote location has files or directories with the
same name, behavior is undefined."""
# support w... | python | def upload(self, local_fn: str, remote_fn: str = '',
dont_overwrite: bool = False) -> None:
"""Uploads file to remote instance. If location not specified, dumps it
into default directory. If remote location has files or directories with the
same name, behavior is undefined."""
# support w... | [
"def",
"upload",
"(",
"self",
",",
"local_fn",
":",
"str",
",",
"remote_fn",
":",
"str",
"=",
"''",
",",
"dont_overwrite",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"# support wildcard through glob",
"if",
"'*'",
"in",
"local_fn",
":",
"for",
"l... | Uploads file to remote instance. If location not specified, dumps it
into default directory. If remote location has files or directories with the
same name, behavior is undefined. | [
"Uploads",
"file",
"to",
"remote",
"instance",
".",
"If",
"location",
"not",
"specified",
"dumps",
"it",
"into",
"default",
"directory",
".",
"If",
"remote",
"location",
"has",
"files",
"or",
"directories",
"with",
"the",
"same",
"name",
"behavior",
"is",
"u... | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L398-L475 |
diux-dev/ncluster | ncluster/aws_backend.py | Task.switch_window | def switch_window(self, window_id: int):
"""
Switches currently active tmux window for given task. 0 is the default window
Args:
window_id: integer id of tmux window to use
"""
# windows are numbered sequentially 0, 1, 2, ...
# create any missing windows and make them point to the same di... | python | def switch_window(self, window_id: int):
"""
Switches currently active tmux window for given task. 0 is the default window
Args:
window_id: integer id of tmux window to use
"""
# windows are numbered sequentially 0, 1, 2, ...
# create any missing windows and make them point to the same di... | [
"def",
"switch_window",
"(",
"self",
",",
"window_id",
":",
"int",
")",
":",
"# windows are numbered sequentially 0, 1, 2, ...",
"# create any missing windows and make them point to the same directory",
"if",
"window_id",
"not",
"in",
"self",
".",
"tmux_available_window_ids",
"... | Switches currently active tmux window for given task. 0 is the default window
Args:
window_id: integer id of tmux window to use | [
"Switches",
"currently",
"active",
"tmux",
"window",
"for",
"given",
"task",
".",
"0",
"is",
"the",
"default",
"window",
"Args",
":",
"window_id",
":",
"integer",
"id",
"of",
"tmux",
"window",
"to",
"use"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L508-L522 |
diux-dev/ncluster | examples/gpubox.py | _replace_lines | def _replace_lines(fn, startswith, new_line):
"""Replace lines starting with starts_with in fn with new_line."""
new_lines = []
for line in open(fn):
if line.startswith(startswith):
new_lines.append(new_line)
else:
new_lines.append(line)
with open(fn, 'w') as f:
f.write('\n'.join(new_lin... | python | def _replace_lines(fn, startswith, new_line):
"""Replace lines starting with starts_with in fn with new_line."""
new_lines = []
for line in open(fn):
if line.startswith(startswith):
new_lines.append(new_line)
else:
new_lines.append(line)
with open(fn, 'w') as f:
f.write('\n'.join(new_lin... | [
"def",
"_replace_lines",
"(",
"fn",
",",
"startswith",
",",
"new_line",
")",
":",
"new_lines",
"=",
"[",
"]",
"for",
"line",
"in",
"open",
"(",
"fn",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"startswith",
")",
":",
"new_lines",
".",
"append",
... | Replace lines starting with starts_with in fn with new_line. | [
"Replace",
"lines",
"starting",
"with",
"starts_with",
"in",
"fn",
"with",
"new_line",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/examples/gpubox.py#L59-L68 |
diux-dev/ncluster | ncluster/util.py | now_micros | def now_micros(absolute=False) -> int:
"""Return current micros since epoch as integer."""
micros = int(time.time() * 1e6)
if absolute:
return micros
return micros - EPOCH_MICROS | python | def now_micros(absolute=False) -> int:
"""Return current micros since epoch as integer."""
micros = int(time.time() * 1e6)
if absolute:
return micros
return micros - EPOCH_MICROS | [
"def",
"now_micros",
"(",
"absolute",
"=",
"False",
")",
"->",
"int",
":",
"micros",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1e6",
")",
"if",
"absolute",
":",
"return",
"micros",
"return",
"micros",
"-",
"EPOCH_MICROS"
] | Return current micros since epoch as integer. | [
"Return",
"current",
"micros",
"since",
"epoch",
"as",
"integer",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L23-L28 |
diux-dev/ncluster | ncluster/util.py | now_millis | def now_millis(absolute=False) -> int:
"""Return current millis since epoch as integer."""
millis = int(time.time() * 1e3)
if absolute:
return millis
return millis - EPOCH_MICROS // 1000 | python | def now_millis(absolute=False) -> int:
"""Return current millis since epoch as integer."""
millis = int(time.time() * 1e3)
if absolute:
return millis
return millis - EPOCH_MICROS // 1000 | [
"def",
"now_millis",
"(",
"absolute",
"=",
"False",
")",
"->",
"int",
":",
"millis",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1e3",
")",
"if",
"absolute",
":",
"return",
"millis",
"return",
"millis",
"-",
"EPOCH_MICROS",
"//",
"1000"
] | Return current millis since epoch as integer. | [
"Return",
"current",
"millis",
"since",
"epoch",
"as",
"integer",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L31-L36 |
diux-dev/ncluster | ncluster/util.py | install_pdb_handler | def install_pdb_handler():
"""Make CTRL+\ break into gdb."""
import signal
import pdb
def handler(_signum, _frame):
pdb.set_trace()
signal.signal(signal.SIGQUIT, handler) | python | def install_pdb_handler():
"""Make CTRL+\ break into gdb."""
import signal
import pdb
def handler(_signum, _frame):
pdb.set_trace()
signal.signal(signal.SIGQUIT, handler) | [
"def",
"install_pdb_handler",
"(",
")",
":",
"import",
"signal",
"import",
"pdb",
"def",
"handler",
"(",
"_signum",
",",
"_frame",
")",
":",
"pdb",
".",
"set_trace",
"(",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGQUIT",
",",
"handler",
")"
] | Make CTRL+\ break into gdb. | [
"Make",
"CTRL",
"+",
"\\",
"break",
"into",
"gdb",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L56-L65 |
diux-dev/ncluster | ncluster/util.py | shell_add_echo | def shell_add_echo(script):
"""Goes over each line script, adds "echo cmd" in front of each cmd.
ls a
becomes
echo * ls a
ls a
"""
new_script = ""
for cmd in script.split('\n'):
cmd = cmd.strip()
if not cmd:
continue
new_script += "echo \\* " + shlex.quote(cmd) + "\n"
new_script... | python | def shell_add_echo(script):
"""Goes over each line script, adds "echo cmd" in front of each cmd.
ls a
becomes
echo * ls a
ls a
"""
new_script = ""
for cmd in script.split('\n'):
cmd = cmd.strip()
if not cmd:
continue
new_script += "echo \\* " + shlex.quote(cmd) + "\n"
new_script... | [
"def",
"shell_add_echo",
"(",
"script",
")",
":",
"new_script",
"=",
"\"\"",
"for",
"cmd",
"in",
"script",
".",
"split",
"(",
"'\\n'",
")",
":",
"cmd",
"=",
"cmd",
".",
"strip",
"(",
")",
"if",
"not",
"cmd",
":",
"continue",
"new_script",
"+=",
"\"ec... | Goes over each line script, adds "echo cmd" in front of each cmd.
ls a
becomes
echo * ls a
ls a | [
"Goes",
"over",
"each",
"line",
"script",
"adds",
"echo",
"cmd",
"in",
"front",
"of",
"each",
"cmd",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L68-L85 |
diux-dev/ncluster | ncluster/util.py | random_id | def random_id(k=5):
"""Random id to use for AWS identifiers."""
# https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=k)) | python | def random_id(k=5):
"""Random id to use for AWS identifiers."""
# https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=k)) | [
"def",
"random_id",
"(",
"k",
"=",
"5",
")",
":",
"# https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choices",
"(",
"string",
".",
"ascii_lowercase",
"+",
... | Random id to use for AWS identifiers. | [
"Random",
"id",
"to",
"use",
"for",
"AWS",
"identifiers",
"."
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L96-L99 |
diux-dev/ncluster | ncluster/util.py | alphanumeric_hash | def alphanumeric_hash(s: str, size=5):
"""Short alphanumeric string derived from hash of given string"""
import hashlib
import base64
hash_object = hashlib.md5(s.encode('ascii'))
s = base64.b32encode(hash_object.digest())
result = s[:size].decode('ascii').lower()
return result | python | def alphanumeric_hash(s: str, size=5):
"""Short alphanumeric string derived from hash of given string"""
import hashlib
import base64
hash_object = hashlib.md5(s.encode('ascii'))
s = base64.b32encode(hash_object.digest())
result = s[:size].decode('ascii').lower()
return result | [
"def",
"alphanumeric_hash",
"(",
"s",
":",
"str",
",",
"size",
"=",
"5",
")",
":",
"import",
"hashlib",
"import",
"base64",
"hash_object",
"=",
"hashlib",
".",
"md5",
"(",
"s",
".",
"encode",
"(",
"'ascii'",
")",
")",
"s",
"=",
"base64",
".",
"b32enc... | Short alphanumeric string derived from hash of given string | [
"Short",
"alphanumeric",
"string",
"derived",
"from",
"hash",
"of",
"given",
"string"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L102-L109 |
diux-dev/ncluster | ncluster/util.py | reverse_taskname | def reverse_taskname(name: str) -> str:
"""
Reverses components in the name of task. Reversed convention is used for filenames since
it groups log/scratch files of related tasks together
0.somejob.somerun -> somerun.somejob.0
0.somejob -> somejob.0
somename -> somename
Args:
name: name of task
""... | python | def reverse_taskname(name: str) -> str:
"""
Reverses components in the name of task. Reversed convention is used for filenames since
it groups log/scratch files of related tasks together
0.somejob.somerun -> somerun.somejob.0
0.somejob -> somejob.0
somename -> somename
Args:
name: name of task
""... | [
"def",
"reverse_taskname",
"(",
"name",
":",
"str",
")",
"->",
"str",
":",
"components",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"assert",
"len",
"(",
"components",
")",
"<=",
"3",
"return",
"'.'",
".",
"join",
"(",
"components",
"[",
":",
":",
... | Reverses components in the name of task. Reversed convention is used for filenames since
it groups log/scratch files of related tasks together
0.somejob.somerun -> somerun.somejob.0
0.somejob -> somejob.0
somename -> somename
Args:
name: name of task | [
"Reverses",
"components",
"in",
"the",
"name",
"of",
"task",
".",
"Reversed",
"convention",
"is",
"used",
"for",
"filenames",
"since",
"it",
"groups",
"log",
"/",
"scratch",
"files",
"of",
"related",
"tasks",
"together"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L112-L127 |
diux-dev/ncluster | ncluster/util.py | is_bash_builtin | def is_bash_builtin(cmd):
"""Return true if command is invoking bash built-in
"""
# from compgen -b
bash_builtins = ['alias', 'bg', 'bind', 'alias', 'bg', 'bind', 'break',
'builtin', 'caller', 'cd', 'command', 'compgen', 'complete',
'compopt', 'continue', 'declare', 'dirs',... | python | def is_bash_builtin(cmd):
"""Return true if command is invoking bash built-in
"""
# from compgen -b
bash_builtins = ['alias', 'bg', 'bind', 'alias', 'bg', 'bind', 'break',
'builtin', 'caller', 'cd', 'command', 'compgen', 'complete',
'compopt', 'continue', 'declare', 'dirs',... | [
"def",
"is_bash_builtin",
"(",
"cmd",
")",
":",
"# from compgen -b",
"bash_builtins",
"=",
"[",
"'alias'",
",",
"'bg'",
",",
"'bind'",
",",
"'alias'",
",",
"'bg'",
",",
"'bind'",
",",
"'break'",
",",
"'builtin'",
",",
"'caller'",
",",
"'cd'",
",",
"'comman... | Return true if command is invoking bash built-in | [
"Return",
"true",
"if",
"command",
"is",
"invoking",
"bash",
"built",
"-",
"in"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L130-L147 |
diux-dev/ncluster | ncluster/util.py | is_set | def is_set(name):
"""Helper method to check if given property is set"""
val = os.environ.get(name, '0')
assert val == '0' or val == '1', f"env var {name} has value {val}, expected 0 or 1"
return val == '1' | python | def is_set(name):
"""Helper method to check if given property is set"""
val = os.environ.get(name, '0')
assert val == '0' or val == '1', f"env var {name} has value {val}, expected 0 or 1"
return val == '1' | [
"def",
"is_set",
"(",
"name",
")",
":",
"val",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
",",
"'0'",
")",
"assert",
"val",
"==",
"'0'",
"or",
"val",
"==",
"'1'",
",",
"f\"env var {name} has value {val}, expected 0 or 1\"",
"return",
"val",
"==",
... | Helper method to check if given property is set | [
"Helper",
"method",
"to",
"check",
"if",
"given",
"property",
"is",
"set"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L150-L154 |
diux-dev/ncluster | ncluster/util.py | assert_script_in_current_directory | def assert_script_in_current_directory():
"""Assert fail if current directory is different from location of the script"""
script = sys.argv[0]
assert os.path.abspath(os.path.dirname(script)) == os.path.abspath(
'.'), f"Change into directory of script {script} and run again." | python | def assert_script_in_current_directory():
"""Assert fail if current directory is different from location of the script"""
script = sys.argv[0]
assert os.path.abspath(os.path.dirname(script)) == os.path.abspath(
'.'), f"Change into directory of script {script} and run again." | [
"def",
"assert_script_in_current_directory",
"(",
")",
":",
"script",
"=",
"sys",
".",
"argv",
"[",
"0",
"]",
"assert",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"script",
")",
")",
"==",
"os",
".",
"path",
".",
... | Assert fail if current directory is different from location of the script | [
"Assert",
"fail",
"if",
"current",
"directory",
"is",
"different",
"from",
"location",
"of",
"the",
"script"
] | train | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L157-L162 |
croach/Flask-Fixtures | flask_fixtures/__init__.py | push_ctx | def push_ctx(app=None):
"""Creates new test context(s) for the given app
If the app is not None, it overrides any existing app and/or request
context. In other words, we will use the app that was passed in to create
a new test request context on the top of the stack. If, however, nothing
was passed... | python | def push_ctx(app=None):
"""Creates new test context(s) for the given app
If the app is not None, it overrides any existing app and/or request
context. In other words, we will use the app that was passed in to create
a new test request context on the top of the stack. If, however, nothing
was passed... | [
"def",
"push_ctx",
"(",
"app",
"=",
"None",
")",
":",
"if",
"app",
"is",
"not",
"None",
":",
"ctx",
"=",
"app",
".",
"test_request_context",
"(",
")",
"ctx",
".",
"fixtures_request_context",
"=",
"True",
"ctx",
".",
"push",
"(",
")",
"if",
"_app_ctx_st... | Creates new test context(s) for the given app
If the app is not None, it overrides any existing app and/or request
context. In other words, we will use the app that was passed in to create
a new test request context on the top of the stack. If, however, nothing
was passed in, we will assume that anothe... | [
"Creates",
"new",
"test",
"context",
"(",
"s",
")",
"for",
"the",
"given",
"app"
] | train | https://github.com/croach/Flask-Fixtures/blob/b34597d165b33cc47cdd632ac0f3cf8a07428675/flask_fixtures/__init__.py#L50-L71 |
croach/Flask-Fixtures | flask_fixtures/__init__.py | pop_ctx | def pop_ctx():
"""Removes the test context(s) from the current stack(s)
"""
if getattr(_request_ctx_stack.top, 'fixtures_request_context', False):
_request_ctx_stack.pop()
if _app_ctx_stack is not None and getattr(_app_ctx_stack.top, 'fixtures_app_context', False):
_app_ctx_stack.pop() | python | def pop_ctx():
"""Removes the test context(s) from the current stack(s)
"""
if getattr(_request_ctx_stack.top, 'fixtures_request_context', False):
_request_ctx_stack.pop()
if _app_ctx_stack is not None and getattr(_app_ctx_stack.top, 'fixtures_app_context', False):
_app_ctx_stack.pop() | [
"def",
"pop_ctx",
"(",
")",
":",
"if",
"getattr",
"(",
"_request_ctx_stack",
".",
"top",
",",
"'fixtures_request_context'",
",",
"False",
")",
":",
"_request_ctx_stack",
".",
"pop",
"(",
")",
"if",
"_app_ctx_stack",
"is",
"not",
"None",
"and",
"getattr",
"("... | Removes the test context(s) from the current stack(s) | [
"Removes",
"the",
"test",
"context",
"(",
"s",
")",
"from",
"the",
"current",
"stack",
"(",
"s",
")"
] | train | https://github.com/croach/Flask-Fixtures/blob/b34597d165b33cc47cdd632ac0f3cf8a07428675/flask_fixtures/__init__.py#L74-L80 |
croach/Flask-Fixtures | flask_fixtures/__init__.py | load_fixtures | def load_fixtures(db, fixtures):
"""Loads the given fixtures into the database.
"""
conn = db.engine.connect()
metadata = db.metadata
for fixture in fixtures:
if 'model' in fixture:
module_name, class_name = fixture['model'].rsplit('.', 1)
module = importlib.import_m... | python | def load_fixtures(db, fixtures):
"""Loads the given fixtures into the database.
"""
conn = db.engine.connect()
metadata = db.metadata
for fixture in fixtures:
if 'model' in fixture:
module_name, class_name = fixture['model'].rsplit('.', 1)
module = importlib.import_m... | [
"def",
"load_fixtures",
"(",
"db",
",",
"fixtures",
")",
":",
"conn",
"=",
"db",
".",
"engine",
".",
"connect",
"(",
")",
"metadata",
"=",
"db",
".",
"metadata",
"for",
"fixture",
"in",
"fixtures",
":",
"if",
"'model'",
"in",
"fixture",
":",
"module_na... | Loads the given fixtures into the database. | [
"Loads",
"the",
"given",
"fixtures",
"into",
"the",
"database",
"."
] | train | https://github.com/croach/Flask-Fixtures/blob/b34597d165b33cc47cdd632ac0f3cf8a07428675/flask_fixtures/__init__.py#L130-L149 |
croach/Flask-Fixtures | flask_fixtures/__init__.py | MetaFixturesMixin.setup_handler | def setup_handler(setup_fixtures_fn, setup_fn):
"""Returns a function that adds fixtures handling to the setup method.
Makes sure that fixtures are setup before calling the given setup method.
"""
def handler(obj):
setup_fixtures_fn(obj)
setup_fn(obj)
ret... | python | def setup_handler(setup_fixtures_fn, setup_fn):
"""Returns a function that adds fixtures handling to the setup method.
Makes sure that fixtures are setup before calling the given setup method.
"""
def handler(obj):
setup_fixtures_fn(obj)
setup_fn(obj)
ret... | [
"def",
"setup_handler",
"(",
"setup_fixtures_fn",
",",
"setup_fn",
")",
":",
"def",
"handler",
"(",
"obj",
")",
":",
"setup_fixtures_fn",
"(",
"obj",
")",
"setup_fn",
"(",
"obj",
")",
"return",
"handler"
] | Returns a function that adds fixtures handling to the setup method.
Makes sure that fixtures are setup before calling the given setup method. | [
"Returns",
"a",
"function",
"that",
"adds",
"fixtures",
"handling",
"to",
"the",
"setup",
"method",
"."
] | train | https://github.com/croach/Flask-Fixtures/blob/b34597d165b33cc47cdd632ac0f3cf8a07428675/flask_fixtures/__init__.py#L180-L188 |
croach/Flask-Fixtures | flask_fixtures/__init__.py | MetaFixturesMixin.teardown_handler | def teardown_handler(teardown_fixtures_fn, teardown_fn):
"""Returns a function that adds fixtures handling to the teardown method.
Calls the given teardown method first before calling the fixtures teardown.
"""
def handler(obj):
teardown_fn(obj)
teardown_fixtures... | python | def teardown_handler(teardown_fixtures_fn, teardown_fn):
"""Returns a function that adds fixtures handling to the teardown method.
Calls the given teardown method first before calling the fixtures teardown.
"""
def handler(obj):
teardown_fn(obj)
teardown_fixtures... | [
"def",
"teardown_handler",
"(",
"teardown_fixtures_fn",
",",
"teardown_fn",
")",
":",
"def",
"handler",
"(",
"obj",
")",
":",
"teardown_fn",
"(",
"obj",
")",
"teardown_fixtures_fn",
"(",
"obj",
")",
"return",
"handler"
] | Returns a function that adds fixtures handling to the teardown method.
Calls the given teardown method first before calling the fixtures teardown. | [
"Returns",
"a",
"function",
"that",
"adds",
"fixtures",
"handling",
"to",
"the",
"teardown",
"method",
"."
] | train | https://github.com/croach/Flask-Fixtures/blob/b34597d165b33cc47cdd632ac0f3cf8a07428675/flask_fixtures/__init__.py#L191-L199 |
croach/Flask-Fixtures | flask_fixtures/__init__.py | MetaFixturesMixin.get_child_fn | def get_child_fn(attrs, names, bases):
"""Returns a function from the child class that matches one of the names.
Searches the child class's set of methods (i.e., the attrs dict) for all
the functions matching the given list of names. If more than one is found,
an exception is raised, if... | python | def get_child_fn(attrs, names, bases):
"""Returns a function from the child class that matches one of the names.
Searches the child class's set of methods (i.e., the attrs dict) for all
the functions matching the given list of names. If more than one is found,
an exception is raised, if... | [
"def",
"get_child_fn",
"(",
"attrs",
",",
"names",
",",
"bases",
")",
":",
"def",
"call_method",
"(",
"obj",
",",
"method",
")",
":",
"\"\"\"Calls a method as either a class method or an instance method.\n \"\"\"",
"# The __get__ method takes an instance and an owner... | Returns a function from the child class that matches one of the names.
Searches the child class's set of methods (i.e., the attrs dict) for all
the functions matching the given list of names. If more than one is found,
an exception is raised, if one is found, it is returned, and if none are
... | [
"Returns",
"a",
"function",
"from",
"the",
"child",
"class",
"that",
"matches",
"one",
"of",
"the",
"names",
"."
] | train | https://github.com/croach/Flask-Fixtures/blob/b34597d165b33cc47cdd632ac0f3cf8a07428675/flask_fixtures/__init__.py#L202-L252 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.