Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _with_env(self, env): res = self._browse(env, self._ids) return res
[ "As the `with_env` class method but for recordset." ]
Please provide a description of the function:def _init_values(self, context=None): if context is None: context = self.env.context # Get basic fields (no relational ones) basic_fields = [] for field_name in self._columns: field = self._columns[field_name] ...
[ "Retrieve field values from the server.\n May be used to restore the original values in the purpose to cancel\n all changes made.\n " ]
Please provide a description of the function:def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]: if unit.lower() not in units: raise ValueError( "Unknown unit. Must be one of {0}".format("/".join(units.keys())) ) if number == 0: return 0 if number...
[ "\n Takes a number of wei and converts it to any other ether unit.\n " ]
Please provide a description of the function:def to_wei(number: int, unit: str) -> int: if unit.lower() not in units: raise ValueError( "Unknown unit. Must be one of {0}".format("/".join(units.keys())) ) if is_integer(number) or is_string(number): d_number = decimal.De...
[ "\n Takes a number of a unit and converts it to wei.\n " ]
Please provide a description of the function:def to_hex( primitive: Primitives = None, hexstr: HexStr = None, text: str = None ) -> HexStr: if hexstr is not None: return HexStr(add_0x_prefix(hexstr.lower())) if text is not None: return HexStr(encode_hex(text.encode("utf-8"))) if i...
[ "\n Auto converts any supported value into its hex representation.\n Trims leading zeros, as defined in:\n https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding\n " ]
Please provide a description of the function:def to_int( primitive: Primitives = None, hexstr: HexStr = None, text: str = None ) -> int: if hexstr is not None: return int(hexstr, 16) elif text is not None: return int(text) elif isinstance(primitive, (bytes, bytearray)): retu...
[ "\n Converts value to its integer representation.\n Values are converted this way:\n\n * primitive:\n\n * bytes, bytearrays: big-endian integer\n * bool: True => 1, False => 0\n * hexstr: interpret hex as integer\n * text: interpret as string of digits, like '12' => 12\n " ]
Please provide a description of the function:def text_if_str( to_type: Callable[..., T], text_or_primitive: Union[bytes, int, str] ) -> T: if isinstance(text_or_primitive, str): return to_type(text=text_or_primitive) else: return to_type(text_or_primitive)
[ "\n Convert to a type, assuming that strings can be only unicode text (not a hexstr)\n\n :param to_type function: takes the arguments (primitive, hexstr=hexstr, text=text),\n eg~ to_bytes, to_text, to_hex, to_int, etc\n :param text_or_primitive bytes, str, int: value to convert\n " ]
Please provide a description of the function:def hexstr_if_str( to_type: Callable[..., T], hexstr_or_primitive: Union[bytes, int, str] ) -> T: if isinstance(hexstr_or_primitive, str): if remove_0x_prefix(hexstr_or_primitive) and not is_hex(hexstr_or_primitive): raise ValueError( ...
[ "\n Convert to a type, assuming that strings can be only hexstr (not unicode text)\n\n :param to_type function: takes the arguments (primitive, hexstr=hexstr, text=text),\n eg~ to_bytes, to_text, to_hex, to_int, etc\n :param hexstr_or_primitive bytes, str, int: value to convert\n " ]
Please provide a description of the function:def validate_conversion_arguments(to_wrap): @functools.wraps(to_wrap) def wrapper(*args, **kwargs): _assert_one_val(*args, **kwargs) if kwargs: _validate_supported_kwarg(kwargs) if len(args) == 0 and "primitive" not in kwarg...
[ "\n Validates arguments for conversion functions.\n - Only a single argument is present\n - Kwarg must be 'primitive' 'hexstr' or 'text'\n - If it is 'hexstr' or 'text' that it is a text type\n " ]
Please provide a description of the function:def return_arg_type(at_position): def decorator(to_wrap): @functools.wraps(to_wrap) def wrapper(*args, **kwargs): result = to_wrap(*args, **kwargs) ReturnType = type(args[at_position]) return ReturnType(result) ...
[ "\n Wrap the return value with the result of `type(args[at_position])`\n " ]
Please provide a description of the function:def replace_exceptions( old_to_new_exceptions: Dict[Type[BaseException], Type[BaseException]] ) -> Callable[..., Any]: old_exceptions = tuple(old_to_new_exceptions.keys()) def decorator(to_wrap: Callable[..., Any]) -> Callable[..., Any]: @functools....
[ "\n Replaces old exceptions with new exceptions to be raised in their place.\n " ]
Please provide a description of the function:def collapse_if_tuple(abi): typ = abi["type"] if not typ.startswith("tuple"): return typ delimited = ",".join(collapse_if_tuple(c) for c in abi["components"]) # Whatever comes after "tuple" is the array dims. The ABI spec states that # this...
[ "Converts a tuple from a dict to a parenthesized list of its types.\n\n >>> from eth_utils.abi import collapse_if_tuple\n >>> collapse_if_tuple(\n ... {\n ... 'components': [\n ... {'name': 'anAddress', 'type': 'address'},\n ... {'name': 'anInt', 'type': 'uint25...
Please provide a description of the function:def is_hex_address(value: Any) -> bool: if not is_text(value): return False elif not is_hex(value): return False else: unprefixed = remove_0x_prefix(value) return len(unprefixed) == 40
[ "\n Checks if the given string of text type is an address in hexadecimal encoded form.\n " ]
Please provide a description of the function:def is_binary_address(value: Any) -> bool: if not is_bytes(value): return False elif len(value) != 20: return False else: return True
[ "\n Checks if the given string is an address in raw bytes form.\n " ]
Please provide a description of the function:def is_address(value: Any) -> bool: if is_checksum_formatted_address(value): return is_checksum_address(value) elif is_hex_address(value): return True elif is_binary_address(value): return True else: return False
[ "\n Checks if the given string in a supported value\n is an address in any of the known formats.\n " ]
Please provide a description of the function:def to_normalized_address(value: AnyStr) -> HexAddress: try: hex_address = hexstr_if_str(to_hex, value).lower() except AttributeError: raise TypeError( "Value must be any string, instead got type {}".format(type(value)) ) ...
[ "\n Converts an address to its normalized hexadecimal representation.\n " ]
Please provide a description of the function:def is_normalized_address(value: Any) -> bool: if not is_address(value): return False else: return value == to_normalized_address(value)
[ "\n Returns whether the provided value is an address in its normalized form.\n " ]
Please provide a description of the function:def is_canonical_address(address: Any) -> bool: if not is_bytes(address) or len(address) != 20: return False return address == to_canonical_address(address)
[ "\n Returns `True` if the `value` is an address in its canonical form.\n " ]
Please provide a description of the function:def is_same_address(left: AnyAddress, right: AnyAddress) -> bool: if not is_address(left) or not is_address(right): raise ValueError("Both values must be valid addresses") else: return to_normalized_address(left) == to_normalized_address(right)
[ "\n Checks if both addresses are same or not.\n " ]
Please provide a description of the function:def to_checksum_address(value: AnyStr) -> ChecksumAddress: norm_address = to_normalized_address(value) address_hash = encode_hex(keccak(text=remove_0x_prefix(norm_address))) checksum_address = add_0x_prefix( "".join( ( no...
[ "\n Makes a checksum address given a supported format.\n " ]
Please provide a description of the function:def get_msi_token(resource, port=50342, msi_conf=None): request_uri = os.environ.get("MSI_ENDPOINT", 'http://localhost:{}/oauth2/token'.format(port)) payload = { 'resource': resource } if msi_conf: if len(msi_conf) > 1: raise ...
[ "Get MSI token if MSI_ENDPOINT is set.\n\n IF MSI_ENDPOINT is not set, will try legacy access through 'http://localhost:{}/oauth2/token'.format(port).\n\n If msi_conf is used, must be a dict of one key in [\"client_id\", \"object_id\", \"msi_res_id\"]\n\n :param str resource: The resource where the token w...
Please provide a description of the function:def get_msi_token_webapp(resource): try: msi_endpoint = os.environ['MSI_ENDPOINT'] msi_secret = os.environ['MSI_SECRET'] except KeyError as err: err_msg = "{} required env variable was not found. You might need to restart your app/functio...
[ "Get a MSI token from inside a webapp or functions.\n\n Env variable will look like:\n\n - MSI_ENDPOINT = http://127.0.0.1:41741/MSI/token/\n - MSI_SECRET = 69418689F1E342DD946CB82994CDA3CB\n " ]
Please provide a description of the function:def _configure(self, **kwargs): if kwargs.get('china'): err_msg = ("china parameter is deprecated, " "please use " "cloud_environment=msrestazure.azure_cloud.AZURE_CHINA_CLOUD") warnings.w...
[ "Configure authentication endpoint.\n\n Optional kwargs may include:\n\n - cloud_environment (msrestazure.azure_cloud.Cloud): A targeted cloud environment\n - china (bool): Configure auth for China-based service,\n default is 'False'.\n - tenant (str): Alternativ...
Please provide a description of the function:def _convert_token(self, token): # Beware that ADAL returns a pointer to its own dict, do # NOT change it in place token = token.copy() # If it's from ADAL, expiresOn will be in ISO form. # Bring it back to float, using expir...
[ "Convert token fields from camel case.\n\n :param dict token: An authentication token.\n :rtype: dict\n " ]
Please provide a description of the function:def signed_session(self, session=None): self.set_token() # Adal does the caching. self._parse_token() return super(AADMixin, self).signed_session(session)
[ "Create token-friendly Requests session, using auto-refresh.\n Used internally when a request is made.\n\n If a session object is provided, configure it directly. Otherwise,\n create a new session and return it.\n\n :param session: The session to configure for authentication\n :ty...
Please provide a description of the function:def refresh_session(self, session=None): if 'refresh_token' in self.token: try: token = self._context.acquire_token_with_refresh_token( self.token['refresh_token'], self.id, ...
[ "Return updated session if token has expired, attempts to\n refresh using newly acquired token.\n\n If a session object is provided, configure it directly. Otherwise,\n create a new session and return it.\n\n :param session: The session to configure for authentication\n :type sess...
Please provide a description of the function:def set_token(self): super(UserPassCredentials, self).set_token() try: token = self._context.acquire_token_with_username_password( self.resource, self.username, self.password, ...
[ "Get token using Username/Password credentials.\n\n :raises: AuthenticationError if credentials invalid, or call fails.\n " ]
Please provide a description of the function:def set_token(self): super(ServicePrincipalCredentials, self).set_token() try: token = self._context.acquire_token_with_client_credentials( self.resource, self.id, self.secret ) ...
[ "Get token using Client ID/Secret credentials.\n\n :raises: AuthenticationError if credentials invalid, or call fails.\n " ]
Please provide a description of the function:def signed_session(self, session=None): session = super(AdalAuthentication, self).signed_session(session) try: raw_token = self._adal_method(*self._args, **self._kwargs) except adal.AdalError as err: # pylint: disable...
[ "Create requests session with any required auth headers applied.\n\n If a session object is provided, configure it directly. Otherwise,\n create a new session and return it.\n\n :param session: The session to configure for authentication\n :type session: requests.Session\n :rtype:...
Please provide a description of the function:def signed_session(self, session=None): # Token cache is handled by the VM extension, call each time to avoid expiration self.set_token() return super(MSIAuthentication, self).signed_session(session)
[ "Create requests session with any required auth headers applied.\n\n If a session object is provided, configure it directly. Otherwise,\n create a new session and return it.\n\n :param session: The session to configure for authentication\n :type session: requests.Session\n :rtype:...
Please provide a description of the function:def _validate(url): if url is None: return parsed = urlparse(url) if not parsed.scheme or not parsed.netloc: raise ValueError("Invalid URL header")
[ "Validate a url.\n\n :param str url: Polling URL extracted from response header.\n :raises: ValueError if URL has no scheme or host.\n " ]
Please provide a description of the function:def _get_header_url(response, header_name): url = response.headers.get(header_name) try: _validate(url) except ValueError: return None else: return url
[ "Get a URL from a header requests.\n\n :param requests.Response response: REST call response.\n :param str header_name: Header name.\n :returns: URL if not None AND valid, None otherwise\n " ]
Please provide a description of the function:def _raise_if_bad_http_status_and_method(self, response): code = response.status_code if code in {200, 202} or \ (code == 201 and self.method in {'PUT', 'PATCH'}) or \ (code == 204 and self.method in {'DELETE', 'POST'}): ...
[ "Check response status code is valid for a Put or Patch\n request. Must be 200, 201, 202, or 204.\n\n :raises: BadStatus if invalid status.\n " ]
Please provide a description of the function:def _is_empty(self, response): if not response.content: return True try: body = response.json() return not body except ValueError: raise DeserializationError( "Error occurred in ...
[ "Check if response body contains meaningful content.\n\n :rtype: bool\n :raises: DeserializationError if response body contains invalid\n json data.\n " ]
Please provide a description of the function:def _deserialize(self, response): # Hacking response with initial status_code previous_status = response.status_code response.status_code = self.initial_status_code resource = self.get_outputs(response) response.status_code = ...
[ "Attempt to deserialize resource from response.\n\n :param requests.Response response: latest REST call response.\n " ]
Please provide a description of the function:def _get_async_status(self, response): if self._is_empty(response): return None body = response.json() return body.get('status')
[ "Attempt to find status info in response body.\n\n :param requests.Response response: latest REST call response.\n :rtype: str\n :returns: Status if found, else 'None'.\n " ]
Please provide a description of the function:def _get_provisioning_state(self, response): if self._is_empty(response): return None body = response.json() return body.get("properties", {}).get("provisioningState")
[ "\n Attempt to get provisioning state from resource.\n :param requests.Response response: latest REST call response.\n :returns: Status if found, else 'None'.\n " ]
Please provide a description of the function:def get_status_from_location(self, response): self._raise_if_bad_http_status_and_method(response) code = response.status_code if code == 202: self.status = "InProgress" else: self.status = 'Succeeded' ...
[ "Process the latest status update retrieved from a 'location'\n header.\n\n :param requests.Response response: latest REST call response.\n :raises: BadResponse if response has no body and not status 202.\n " ]
Please provide a description of the function: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 running operation ' 'does not contain a...
[ "Process the latest status update retrieved from the same URL as\n the previous request.\n\n :param requests.Response response: latest REST call response.\n :raises: BadResponse if status not 200 or 204.\n " ]
Please provide a description of the function:def _start(self, update_cmd): try: self._poll(update_cmd) except BadStatus: self._operation.status = 'Failed' self._exception = CloudError(self._response) except BadResponse as err: self._oper...
[ "Start the long running operation.\n On completion, runs any callbacks.\n\n :param callable update_cmd: The API reuqest to check the status of\n the operation.\n " ]
Please provide a description of the function:def _polling_cookie(self): parsed_url = urlparse(self._response.request.url) host = parsed_url.hostname.strip('.') if host == 'localhost': return {'cookie': self._response.headers.get('set-cookie', '')} return {}
[ "Collect retry cookie - we only want to do this for the test server\n at this point, unless we implement a proper cookie policy.\n\n :returns: Dictionary containing a cookie header if required,\n otherwise an empty dictionary.\n " ]
Please provide a description of the function:def _poll(self, update_cmd): initial_url = self._response.request.url while not finished(self.status()): self._delay() headers = self._polling_cookie() if self._operation.async_url: self._response...
[ "Poll status of operation so long as operation is incomplete and\n we have an endpoint to query.\n\n :param callable update_cmd: The function to call to retrieve the\n latest status of the long running operation.\n :raises: OperationFailed if operation status 'Failed' or 'Cancelled'.\n ...
Please provide a description of the function:def add_done_callback(self, func): if self._done is None or self._done.is_set(): raise ValueError("Process is complete.") self._callbacks.append(func)
[ "Add callback function to be run once the long running operation\n has completed - regardless of the status of the operation.\n\n :param callable func: Callback function that takes at least one\n argument, a completed LongRunningOperation.\n :raises: ValueError if the long running opera...
Please provide a description of the function:def remove_done_callback(self, func): if self._done is None or self._done.is_set(): raise ValueError("Process is complete.") self._callbacks = [c for c in self._callbacks if c != func]
[ "Remove a callback from the long running operation.\n\n :param callable func: The function to be removed from the callbacks.\n :raises: ValueError if the long running operation has already\n completed.\n " ]
Please provide a description of the function: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: session = kwargs['msrest']['session'] url_prefix = _extract_subscription_url(r.req...
[ "This is a requests hook to register RP automatically.\n\n You should not use this command manually, this is added automatically\n by the SDK.\n\n See requests documentation for details of the signature of this function.\n http://docs.python-requests.org/en/master/user/advanced/#event-hooks\n " ]
Please provide a description of the function:def _extract_subscription_url(url): match = re.match(r".*/subscriptions/[a-f0-9-]+/", url, re.IGNORECASE) if not match: raise ValueError("Unable to extract subscription ID from URL") return match.group(0)
[ "Extract the first part of the URL, just after subscription:\n https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/\n " ]
Please provide a description of the function: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".format(url_prefix, rp_name) _LOGGER.warning("Resource provider '%s' used...
[ "Synchronously register the RP is paremeter.\n \n Return False if we have a reason to believe this didn't work\n " ]
Please provide a description of the function:def parse_resource_id(rid): if not rid: return {} match = _ARMID_RE.match(rid) if match: result = match.groupdict() children = _CHILDREN_RE.finditer(result['children'] or '') count = None for count, child in enumerate(...
[ "Parses a resource_id into its various parts.\n\n Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id.\n\n :param rid: The resource id being parsed\n :type rid: str\n :returns: A dictionary with with following key/value pairs (if found):\n\n - subscription: ...
Please provide a description of the function:def _populate_alternate_kwargs(kwargs): resource_namespace = kwargs['namespace'] resource_type = kwargs.get('child_type_{}'.format(kwargs['last_child_num'])) or kwargs['type'] resource_name = kwargs.get('child_name_{}'.format(kwargs['last_child_num'])) or k...
[ " Translates the parsed arguments into a format used by generic ARM commands\n such as the resource and lock commands.\n " ]
Please provide a description of the function:def _get_parents_from_parts(kwargs): 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_namespace = kwargs.get('...
[ " Get the parents given all the children parameters.\n " ]
Please provide a description of the function:def resource_id(**kwargs): kwargs = {k: v for k, v in kwargs.items() if v is not None} rid_builder = ['/subscriptions/{subscription}'.format(**kwargs)] try: try: rid_builder.append('resourceGroups/{resource_group}'.format(**kwargs)) ...
[ "Create a valid resource id string from the given parts.\n\n This method builds the resource id from the left until the next required id parameter\n to be appended is not found. It then returns the built up id.\n\n :param dict kwargs: The keyword arguments that will make up the id.\n\n The method ac...
Please provide a description of the function:def is_valid_resource_id(rid, exception_type=None): is_valid = False try: is_valid = rid and resource_id(**parse_resource_id(rid)).lower() == rid.lower() except KeyError: pass if not is_valid and exception_type: raise exception_ty...
[ "Validates the given resource id.\n\n :param rid: The resource id being validated.\n :type rid: str\n :param exception_type: Raises this Exception if invalid.\n :type exception_type: :class:`Exception`\n :returns: A boolean describing whether the id is valid.\n :rtype: bool\n " ]
Please provide a description of the function:def is_valid_resource_name(rname, exception_type=None): match = _ARMNAME_RE.match(rname) if match: return True if exception_type: raise exception_type() return False
[ "Validates the given resource name to ARM guidelines, individual services may be more restrictive.\n\n :param rname: The resource name being validated.\n :type rname: str\n :param exception_type: Raises this Exception if invalid.\n :type exception_type: :class:`Exception`\n :returns: A boolean descri...
Please provide a description of the function:def save(self, filepath): self._config.add_section("Azure") self._config.set("Azure", "long_running_operation_timeout", self.long_running_operation_timeout) return super(AzureConfiguration, se...
[ "Save current configuration to file.\n\n :param str filepath: Path to save file to.\n :raises: ValueError if supplied filepath cannot be written to.\n " ]
Please provide a description of the function:def load(self, filepath): try: self._config.read(filepath) self.long_running_operation_timeout = self._config.getint( "Azure", "long_running_operation_timeout") except (ValueError, EnvironmentError, NoOptionErr...
[ "Load configuration from existing file.\n\n :param str filepath: Path to existing config file.\n :raises: ValueError if supplied config file is invalid.\n " ]
Please provide a description of the function:async def _poll(self): while not self.finished(): await self._delay() await self.update_status() if failed(self._operation.status): raise OperationFailed("Operation failed or cancelled") elif self._opera...
[ "Poll status of operation so long as operation is incomplete and\n we have an endpoint to query.\n\n :param callable update_cmd: The function to call to retrieve the\n latest status of the long running operation.\n :raises: OperationFailed if operation status 'Failed' or 'Cancelled'.\n ...
Please provide a description of the function:async def _delay(self): if self._response is None: await asyncio.sleep(0) if self._response.headers.get('retry-after'): await asyncio.sleep(int(self._response.headers['retry-after'])) else: await asyncio.sl...
[ "Check for a 'retry-after' header to set timeout,\n otherwise use configured timeout.\n " ]
Please provide a description of the function:async def update_status(self): 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_from_as...
[ "Update the current status of the LRO.\n " ]
Please provide a description of the function: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.request.headers['x-ms-client-request-id'] ...
[ "Do a simple GET to this status link.\n\n This method re-inject 'x-ms-client-request-id'.\n\n :rtype: requests.Response\n " ]
Please provide a description of the function:def message(self, value): try: import ast value = ast.literal_eval(value) except (SyntaxError, TypeError, ValueError): pass try: value = value.get('value', value) msg_data = value.sp...
[ "Attempt to deconstruct error message to retrieve further\n error data.\n " ]
Please provide a description of the function:def get_cloud_from_metadata_endpoint(arm_endpoint, name=None, session=None): cloud = Cloud(name or arm_endpoint) cloud.endpoints.management = arm_endpoint cloud.endpoints.resource_manager = arm_endpoint _populate_from_metadata_endpoint(cloud, arm_endpoin...
[ "Get a Cloud object from an ARM endpoint.\n\n .. versionadded:: 0.4.11\n\n :Example:\n\n .. code:: python\n\n get_cloud_from_metadata_endpoint(https://management.azure.com/, \"Public Azure\")\n\n :param str arm_endpoint: The ARM management endpoint\n :param str name: An optional name for the C...
Please provide a description of the function:def get_header_url(response, header_name): url = response.headers.get(header_name) try: _validate(url) except ValueError: return None else: return url
[ "Get a URL from a header requests.\n\n :param requests.Response response: REST call response.\n :param str header_name: Header name.\n :returns: URL if not None AND valid, None otherwise\n " ]
Please provide a description of the function: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.text if not content: return True try: ...
[ "Check if response body contains meaningful content.\n\n :rtype: bool\n :raises: DeserializationError if response body contains invalid json data.\n " ]
Please provide a description of the function: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.text try: return json.loads(content) except Valu...
[ "Assuming this is not empty, return the content as JSON.\n\n Result/exceptions is not determined if you call this method without testing _is_empty.\n\n :raises: DeserializationError if response body contains invalid json data.\n " ]
Please provide a description of the function: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.\n\n :param requests.Response response: latest REST call response.\n :rtype: str\n :returns: Status if found, else 'None'.\n " ]
Please provide a description of the function:def _get_provisioning_state(self, response): if self._is_empty(response): return None body = self._as_json(response) return body.get("properties", {}).get("provisioningState")
[ "\n Attempt to get provisioning state from resource.\n :param requests.Response response: latest REST call response.\n :returns: Status if found, else 'None'.\n " ]
Please provide a description of the function:def should_do_final_get(self): return ((self.async_url or not self.resource) and self.method in {'PUT', 'PATCH'}) \ or (self.lro_options['final-state-via'] == _LOCATION_FINAL_STATE and self.location_url and self.async_url and self.method == '...
[ "Check whether the polling should end doing a final GET.\n\n :param requests.Response response: latest REST call response.\n :rtype: bool\n " ]
Please provide a description of the function: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: self.resource = self._deserialize(response) ...
[ "Process first response after initiating long running\n operation and set self.status attribute.\n\n :param requests.Response response: initial REST call response.\n " ]
Please provide a description of the function: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 running operation ' 'does not contain a...
[ "Process the latest status update retrieved from the same URL as\n the previous request.\n\n :param requests.Response response: latest REST call response.\n :raises: BadResponse if status not 200 or 204.\n " ]
Please provide a description of the function:def parse_resource(self, response): self._raise_if_bad_http_status_and_method(response) if not self._is_empty(response): self.resource = self._deserialize(response) else: self.resource = None
[ "Assuming this response is a resource, use the deserialization callback to parse it.\n If body is empty, assuming no resource to return.\n " ]
Please provide a description of the function: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 running operation ' 'does not contain a bo...
[ "Process the latest status update retrieved from a\n 'azure-asyncoperation' header.\n\n :param requests.Response response: latest REST call response.\n :raises: BadResponse if response has no body, or body does not\n contain status.\n " ]
Please provide a description of the function:def initialize(self, client, initial_response, deserialization_callback): self._client = client self._response = initial_response self._operation = LongRunningOperation(initial_response, deserialization_callback, self._lro_options) tr...
[ "Set the initial status of this LRO.\n\n :param initial_response: The initial response of the poller\n :raises: CloudError if initial status is incorrect LRO state\n " ]
Please provide a description of the function:def worker(): 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.master...
[ " Initialize the distributed environment. " ]
Please provide a description of the function: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 pattern is error-prone)" if backend_name == 'aws': _backend ...
[ "Sets backend (local or aws)" ]
Please provide a description of the function:def make_job(name: str = '', run_name: str = '', num_tasks: int = 0, install_script: str = '', **kwargs ) -> backend.Job: return _backend.make_job(name=name, run_name=run_name, num_tasks=num_tasks, ...
[ "\n Create a job using current backend. Blocks until all tasks are up and initialized.\n\n Args:\n name: name of the job\n run_name: name of the run (auto-assigned if empty)\n num_tasks: number of tasks\n install_script: bash-runnable script\n **kwargs:\n\n Returns:\n backend.Job\n " ]
Please provide a description of the function:def make_task(name='', run_name='', **kwargs) -> Task: 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('.', '=') tm...
[ "Create task, also create dummy run if not specified." ]
Please provide a description of the function: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: for i in range(max(self.tmux_available...
[ "\n Switches currently active tmux window for given task. 0 is the default window\n Args:\n window_id: integer id of tmux window to use\n " ]
Please provide a description of the function: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_errors: self.log(f"command ({cmd}) failed.") assert False, "_run_raw faile...
[ "Runs command directly, skipping tmux interface" ]
Please provide a description of the function: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_fn): self.upload(local_subfn) return if remote_fn is None: remote_fn = os.pat...
[ "Uploads file to remote instance. If location not specified, dumps it\n into default directory. Creates missing directories in path name." ]
Please provide a description of the function: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 single task in a group creates the logdir if ncluster_globals.is_chief(self, ru...
[ "Returns logging directory, creating one if necessary. See \"Logdir\" section of design doc on naming convention." ]
Please provide a description of the function: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 = ncluster_globals.LOGDIR_ROOT assert logdir_root self.run(f'mkdir -p {logdi...
[ "Create logdir for task/job/run. No-op if the task is not chief (0'th task of 0'th job of run)\n " ]
Please provide a description of the function:def run(self, *args, **kwargs): for job in self.jobs: job.run(*args, **kwargs)
[ "Runs command on every job in the run." ]
Please provide a description of the function: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." ]
Please provide a description of the function:def _run_raw(self, *args, **kwargs): for job in self.jobs: job._run_raw(*args, **kwargs)
[ "_run_raw on every job in the run." ]
Please provide a description of the function:def upload(self, *args, **kwargs): for job in self.jobs: job.upload(*args, **kwargs)
[ "Runs command on every job in the run." ]
Please provide a description of the function: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() zones = u.get_zones() # create VPC from scratch. Remove this if default VPC...
[ "Creates VPC if it doesn't already exists, configures it for public\n internet access, returns vpc, subnet, security_group" ]
Please provide a description of the function:def keypair_setup(): 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: print("Reusing keypair " + keypair_name) # check...
[ "Creates keypair if necessary, saves private key locally, returns contents\n of private key file." ]
Please provide a description of the function: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 group.state == 'available' assert group.strategy == 'cluster' print("Reusing group ...
[ "Creates placement_group group if necessary. Returns True if new placement_group\n group was created, False otherwise." ]
Please provide a description of the function: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) start_time = time.time() while True: if time.time() - start_time > max_wait_sec: util...
[ "\n Waits for file maximum of max_wait_sec. Returns True if file was detected within specified max_wait_sec\n Args:\n fn: filename on task machine\n max_wait_sec: how long to wait in seconds\n check_interval: how often to check in seconds\n Returns:\n False if waiting was was cut short ...
Please provide a description of the function: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\n into task current directory with the same name.\n\n Args:\n local_fn: location of file locally\n remote_fn: location of file on task\n dont_overwrite: if True, will be no-op if target file exists\n " ]
Please provide a description of the function:def _non_blocking_wrapper(self, method, *args, **kwargs): exceptions = [] def task_run(task): try: getattr(task, method)(*args, **kwargs) except Exception as e: exceptions.append(e) threads = [threading.Thread(name=f'task_{meth...
[ "Runs given method on every task in the job. Blocks until all tasks finish. Propagates exception from first\n failed task." ]
Please provide a description of the function:def get_vpc_dict(): client = get_ec2_client() response = client.describe_vpcs() assert is_good_response(response) result = OrderedDict() ec2 = get_ec2_resource() for vpc_response in response['Vpcs']: key = get_name(vpc_response.get('Tags', [])) if no...
[ "Returns dictionary of named VPCs {name: vpc}\n\n Assert fails if there's more than one VPC with same name." ]
Please provide a description of the function:def get_default_vpc(): ec2 = get_ec2_resource() for vpc in ec2.vpcs.all(): if vpc.is_default: return vpc
[ "\n Return default VPC or none if not present\n\n " ]
Please provide a description of the function:def get_subnet_dict(): 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 return subnet_dict
[ "Returns dictionary of \"availability zone\" -> subnet for current VPC." ]
Please provide a description of the function: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(efs_client.describe_file_systems, ...
[ "Returns dictionary of {efs_name: efs_id}" ]
Please provide a description of the function:def get_placement_group_dict(): 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['PlacementGroups']: key = p...
[ "Returns dictionary of {placement_group_name: (state, strategy)}" ]
Please provide a description of the function:def get_security_group_dict(): 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['SecurityGroups']: key = get_n...
[ "Returns dictionary of named security groups {name: securitygroup}." ]
Please provide a description of the function:def get_keypair_dict(): 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 keypair_...
[ "Returns dictionary of {keypairname: keypair}" ]
Please provide a description of the function: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,\n (name of EFS, VPC, keypair prefixes), can be changed through $NCLUSTER_PREFIX for debugging purposes. " ]
Please provide a description of the function:def get_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
[ "Returns current keypair name." ]