repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/network.py
Network.GetNetworkDetails
def GetNetworkDetails(network,alias=None,location=None): """Gets the details for a Network and its IP Addresses. https://t3n.zendesk.com/entries/21726312-Get-Network-Details :param network: network name :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides. If none will use account's primary datacenter """ if alias is None: alias = clc.v1.Account.GetAlias() if location is None: location = clc.v1.Account.GetLocation() r = clc.v1.API.Call('post','Network/GetNetworkDetails', { 'AccountAlias': alias, 'Location': location, 'Name': network }) if int(r['StatusCode']) == 0: return(r['NetworkDetails']['IPAddresses'])
python
def GetNetworkDetails(network,alias=None,location=None): """Gets the details for a Network and its IP Addresses. https://t3n.zendesk.com/entries/21726312-Get-Network-Details :param network: network name :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides. If none will use account's primary datacenter """ if alias is None: alias = clc.v1.Account.GetAlias() if location is None: location = clc.v1.Account.GetLocation() r = clc.v1.API.Call('post','Network/GetNetworkDetails', { 'AccountAlias': alias, 'Location': location, 'Name': network }) if int(r['StatusCode']) == 0: return(r['NetworkDetails']['IPAddresses'])
[ "def", "GetNetworkDetails", "(", "network", ",", "alias", "=", "None", ",", "location", "=", "None", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "if", "location", "is", "None", ":", "location", "=", "clc", ".", "v1", ".", "Account", ".", "GetLocation", "(", ")", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Network/GetNetworkDetails'", ",", "{", "'AccountAlias'", ":", "alias", ",", "'Location'", ":", "location", ",", "'Name'", ":", "network", "}", ")", "if", "int", "(", "r", "[", "'StatusCode'", "]", ")", "==", "0", ":", "return", "(", "r", "[", "'NetworkDetails'", "]", "[", "'IPAddresses'", "]", ")" ]
Gets the details for a Network and its IP Addresses. https://t3n.zendesk.com/entries/21726312-Get-Network-Details :param network: network name :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides. If none will use account's primary datacenter
[ "Gets", "the", "details", "for", "a", "Network", "and", "its", "IP", "Addresses", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/network.py#L30-L42
train
blag/django-secure-mail
secure_mail/handlers.py
get_variable_from_exception
def get_variable_from_exception(exception, variable_name): """ Grab the variable from closest frame in the stack """ for frame in reversed(trace()): try: # From http://stackoverflow.com/a/9059407/6461688 frame_variable = frame[0].f_locals[variable_name] except KeyError: pass else: return frame_variable else: raise KeyError("Variable '%s' not in any stack frames", variable_name)
python
def get_variable_from_exception(exception, variable_name): """ Grab the variable from closest frame in the stack """ for frame in reversed(trace()): try: # From http://stackoverflow.com/a/9059407/6461688 frame_variable = frame[0].f_locals[variable_name] except KeyError: pass else: return frame_variable else: raise KeyError("Variable '%s' not in any stack frames", variable_name)
[ "def", "get_variable_from_exception", "(", "exception", ",", "variable_name", ")", ":", "for", "frame", "in", "reversed", "(", "trace", "(", ")", ")", ":", "try", ":", "# From http://stackoverflow.com/a/9059407/6461688", "frame_variable", "=", "frame", "[", "0", "]", ".", "f_locals", "[", "variable_name", "]", "except", "KeyError", ":", "pass", "else", ":", "return", "frame_variable", "else", ":", "raise", "KeyError", "(", "\"Variable '%s' not in any stack frames\"", ",", "variable_name", ")" ]
Grab the variable from closest frame in the stack
[ "Grab", "the", "variable", "from", "closest", "frame", "in", "the", "stack" ]
52987b6ce829e6de2dc8ab38ed3190bc2752b341
https://github.com/blag/django-secure-mail/blob/52987b6ce829e6de2dc8ab38ed3190bc2752b341/secure_mail/handlers.py#L14-L27
train
blag/django-secure-mail
secure_mail/handlers.py
force_delete_key
def force_delete_key(address): """ Delete the key from the keyring and the Key and Address objects from the database """ address_object = Address.objects.get(address=address) address_object.key.delete() address_object.delete()
python
def force_delete_key(address): """ Delete the key from the keyring and the Key and Address objects from the database """ address_object = Address.objects.get(address=address) address_object.key.delete() address_object.delete()
[ "def", "force_delete_key", "(", "address", ")", ":", "address_object", "=", "Address", ".", "objects", ".", "get", "(", "address", "=", "address", ")", "address_object", ".", "key", ".", "delete", "(", ")", "address_object", ".", "delete", "(", ")" ]
Delete the key from the keyring and the Key and Address objects from the database
[ "Delete", "the", "key", "from", "the", "keyring", "and", "the", "Key", "and", "Address", "objects", "from", "the", "database" ]
52987b6ce829e6de2dc8ab38ed3190bc2752b341
https://github.com/blag/django-secure-mail/blob/52987b6ce829e6de2dc8ab38ed3190bc2752b341/secure_mail/handlers.py#L72-L79
train
uzumaxy/pyvalid
pyvalid/__accepts.py
Accepts.__wrap_accepted_val
def __wrap_accepted_val(self, value): """Wrap accepted value in the list if yet not wrapped. """ if isinstance(value, tuple): value = list(value) elif not isinstance(value, list): value = [value] return value
python
def __wrap_accepted_val(self, value): """Wrap accepted value in the list if yet not wrapped. """ if isinstance(value, tuple): value = list(value) elif not isinstance(value, list): value = [value] return value
[ "def", "__wrap_accepted_val", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "tuple", ")", ":", "value", "=", "list", "(", "value", ")", "elif", "not", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "[", "value", "]", "return", "value" ]
Wrap accepted value in the list if yet not wrapped.
[ "Wrap", "accepted", "value", "in", "the", "list", "if", "yet", "not", "wrapped", "." ]
74a1a64df1cc77cac55f12f0fe0f52292c6ae479
https://github.com/uzumaxy/pyvalid/blob/74a1a64df1cc77cac55f12f0fe0f52292c6ae479/pyvalid/__accepts.py#L44-L51
train
uzumaxy/pyvalid
pyvalid/__accepts.py
Accepts.__validate_args
def __validate_args(self, func_name, args, kwargs): """Compare value of each required argument with list of accepted values. Args: func_name (str): Function name. args (list): Collection of the position arguments. kwargs (dict): Collection of the keyword arguments. Raises: InvalidArgumentNumberError: When position or count of the arguments is incorrect. ArgumentValidationError: When encountered unexpected argument value. """ from pyvalid.validators import Validator for i, (arg_name, accepted_values) in enumerate(self.accepted_args): if i < len(args): value = args[i] else: if arg_name in kwargs: value = kwargs[arg_name] elif i in self.optional_args: continue else: raise InvalidArgumentNumberError(func_name) is_valid = False for accepted_val in accepted_values: is_validator = ( isinstance(accepted_val, Validator) or ( isinstance(accepted_val, MethodType) and hasattr(accepted_val, '__func__') and isinstance(accepted_val.__func__, Validator) ) ) if is_validator: is_valid = accepted_val(value) elif isinstance(accepted_val, type): is_valid = isinstance(value, accepted_val) else: is_valid = value == accepted_val if is_valid: break if not is_valid: ord_num = self.__ordinal(i + 1) raise ArgumentValidationError( ord_num, func_name, value, accepted_values )
python
def __validate_args(self, func_name, args, kwargs): """Compare value of each required argument with list of accepted values. Args: func_name (str): Function name. args (list): Collection of the position arguments. kwargs (dict): Collection of the keyword arguments. Raises: InvalidArgumentNumberError: When position or count of the arguments is incorrect. ArgumentValidationError: When encountered unexpected argument value. """ from pyvalid.validators import Validator for i, (arg_name, accepted_values) in enumerate(self.accepted_args): if i < len(args): value = args[i] else: if arg_name in kwargs: value = kwargs[arg_name] elif i in self.optional_args: continue else: raise InvalidArgumentNumberError(func_name) is_valid = False for accepted_val in accepted_values: is_validator = ( isinstance(accepted_val, Validator) or ( isinstance(accepted_val, MethodType) and hasattr(accepted_val, '__func__') and isinstance(accepted_val.__func__, Validator) ) ) if is_validator: is_valid = accepted_val(value) elif isinstance(accepted_val, type): is_valid = isinstance(value, accepted_val) else: is_valid = value == accepted_val if is_valid: break if not is_valid: ord_num = self.__ordinal(i + 1) raise ArgumentValidationError( ord_num, func_name, value, accepted_values )
[ "def", "__validate_args", "(", "self", ",", "func_name", ",", "args", ",", "kwargs", ")", ":", "from", "pyvalid", ".", "validators", "import", "Validator", "for", "i", ",", "(", "arg_name", ",", "accepted_values", ")", "in", "enumerate", "(", "self", ".", "accepted_args", ")", ":", "if", "i", "<", "len", "(", "args", ")", ":", "value", "=", "args", "[", "i", "]", "else", ":", "if", "arg_name", "in", "kwargs", ":", "value", "=", "kwargs", "[", "arg_name", "]", "elif", "i", "in", "self", ".", "optional_args", ":", "continue", "else", ":", "raise", "InvalidArgumentNumberError", "(", "func_name", ")", "is_valid", "=", "False", "for", "accepted_val", "in", "accepted_values", ":", "is_validator", "=", "(", "isinstance", "(", "accepted_val", ",", "Validator", ")", "or", "(", "isinstance", "(", "accepted_val", ",", "MethodType", ")", "and", "hasattr", "(", "accepted_val", ",", "'__func__'", ")", "and", "isinstance", "(", "accepted_val", ".", "__func__", ",", "Validator", ")", ")", ")", "if", "is_validator", ":", "is_valid", "=", "accepted_val", "(", "value", ")", "elif", "isinstance", "(", "accepted_val", ",", "type", ")", ":", "is_valid", "=", "isinstance", "(", "value", ",", "accepted_val", ")", "else", ":", "is_valid", "=", "value", "==", "accepted_val", "if", "is_valid", ":", "break", "if", "not", "is_valid", ":", "ord_num", "=", "self", ".", "__ordinal", "(", "i", "+", "1", ")", "raise", "ArgumentValidationError", "(", "ord_num", ",", "func_name", ",", "value", ",", "accepted_values", ")" ]
Compare value of each required argument with list of accepted values. Args: func_name (str): Function name. args (list): Collection of the position arguments. kwargs (dict): Collection of the keyword arguments. Raises: InvalidArgumentNumberError: When position or count of the arguments is incorrect. ArgumentValidationError: When encountered unexpected argument value.
[ "Compare", "value", "of", "each", "required", "argument", "with", "list", "of", "accepted", "values", "." ]
74a1a64df1cc77cac55f12f0fe0f52292c6ae479
https://github.com/uzumaxy/pyvalid/blob/74a1a64df1cc77cac55f12f0fe0f52292c6ae479/pyvalid/__accepts.py#L94-L145
train
uzumaxy/pyvalid
pyvalid/__accepts.py
Accepts.__ordinal
def __ordinal(self, num): """Returns the ordinal number of a given integer, as a string. eg. 1 -> 1st, 2 -> 2nd, 3 -> 3rd, etc. """ if 10 <= num % 100 < 20: return str(num) + 'th' else: ord_info = {1: 'st', 2: 'nd', 3: 'rd'}.get(num % 10, 'th') return '{}{}'.format(num, ord_info)
python
def __ordinal(self, num): """Returns the ordinal number of a given integer, as a string. eg. 1 -> 1st, 2 -> 2nd, 3 -> 3rd, etc. """ if 10 <= num % 100 < 20: return str(num) + 'th' else: ord_info = {1: 'st', 2: 'nd', 3: 'rd'}.get(num % 10, 'th') return '{}{}'.format(num, ord_info)
[ "def", "__ordinal", "(", "self", ",", "num", ")", ":", "if", "10", "<=", "num", "%", "100", "<", "20", ":", "return", "str", "(", "num", ")", "+", "'th'", "else", ":", "ord_info", "=", "{", "1", ":", "'st'", ",", "2", ":", "'nd'", ",", "3", ":", "'rd'", "}", ".", "get", "(", "num", "%", "10", ",", "'th'", ")", "return", "'{}{}'", ".", "format", "(", "num", ",", "ord_info", ")" ]
Returns the ordinal number of a given integer, as a string. eg. 1 -> 1st, 2 -> 2nd, 3 -> 3rd, etc.
[ "Returns", "the", "ordinal", "number", "of", "a", "given", "integer", "as", "a", "string", ".", "eg", ".", "1", "-", ">", "1st", "2", "-", ">", "2nd", "3", "-", ">", "3rd", "etc", "." ]
74a1a64df1cc77cac55f12f0fe0f52292c6ae479
https://github.com/uzumaxy/pyvalid/blob/74a1a64df1cc77cac55f12f0fe0f52292c6ae479/pyvalid/__accepts.py#L147-L155
train
sio2project/filetracker
filetracker/client/client.py
Client.get_file
def get_file(self, name, save_to, add_to_cache=True, force_refresh=False, _lock_exclusive=False): """Retrieves file identified by ``name``. The file is saved as ``save_to``. If ``add_to_cache`` is ``True``, the file is added to the local store. If ``force_refresh`` is ``True``, local cache is not examined if a remote store is configured. If a remote store is configured, but ``name`` does not contain a version, the local data store is not used, as we cannot guarantee that the version there is fresh. Local data store implemented in :class:`LocalDataStore` tries to not copy the entire file to ``save_to`` if possible, but instead uses hardlinking. Therefore you should not modify the file if you don't want to totally blow something. This method returns the full versioned name of the retrieved file. """ uname, version = split_name(name) lock = None if self.local_store: lock = self.lock_manager.lock_for(uname) if _lock_exclusive: lock.lock_exclusive() else: lock.lock_shared() else: add_to_cache = False t = time.time() logger.debug(' downloading %s', name) try: if not self.remote_store or (version is not None and not force_refresh): try: if self.local_store and self.local_store.exists(name): return self.local_store.get_file(name, save_to) except Exception: if self.remote_store: logger.warning("Error getting '%s' from local store", name, exc_info=True) else: raise if self.remote_store: if not _lock_exclusive and add_to_cache: if lock: lock.unlock() return self.get_file(name, save_to, add_to_cache, _lock_exclusive=True) vname = self.remote_store.get_file(name, save_to) if add_to_cache: self._add_to_cache(vname, save_to) return vname raise FiletrackerError("File not available: %s" % name) finally: if lock: lock.close() logger.debug(' processed %s in %.2fs', name, time.time() - t)
python
def get_file(self, name, save_to, add_to_cache=True, force_refresh=False, _lock_exclusive=False): """Retrieves file identified by ``name``. The file is saved as ``save_to``. If ``add_to_cache`` is ``True``, the file is added to the local store. If ``force_refresh`` is ``True``, local cache is not examined if a remote store is configured. If a remote store is configured, but ``name`` does not contain a version, the local data store is not used, as we cannot guarantee that the version there is fresh. Local data store implemented in :class:`LocalDataStore` tries to not copy the entire file to ``save_to`` if possible, but instead uses hardlinking. Therefore you should not modify the file if you don't want to totally blow something. This method returns the full versioned name of the retrieved file. """ uname, version = split_name(name) lock = None if self.local_store: lock = self.lock_manager.lock_for(uname) if _lock_exclusive: lock.lock_exclusive() else: lock.lock_shared() else: add_to_cache = False t = time.time() logger.debug(' downloading %s', name) try: if not self.remote_store or (version is not None and not force_refresh): try: if self.local_store and self.local_store.exists(name): return self.local_store.get_file(name, save_to) except Exception: if self.remote_store: logger.warning("Error getting '%s' from local store", name, exc_info=True) else: raise if self.remote_store: if not _lock_exclusive and add_to_cache: if lock: lock.unlock() return self.get_file(name, save_to, add_to_cache, _lock_exclusive=True) vname = self.remote_store.get_file(name, save_to) if add_to_cache: self._add_to_cache(vname, save_to) return vname raise FiletrackerError("File not available: %s" % name) finally: if lock: lock.close() logger.debug(' processed %s in %.2fs', name, time.time() - t)
[ "def", "get_file", "(", "self", ",", "name", ",", "save_to", ",", "add_to_cache", "=", "True", ",", "force_refresh", "=", "False", ",", "_lock_exclusive", "=", "False", ")", ":", "uname", ",", "version", "=", "split_name", "(", "name", ")", "lock", "=", "None", "if", "self", ".", "local_store", ":", "lock", "=", "self", ".", "lock_manager", ".", "lock_for", "(", "uname", ")", "if", "_lock_exclusive", ":", "lock", ".", "lock_exclusive", "(", ")", "else", ":", "lock", ".", "lock_shared", "(", ")", "else", ":", "add_to_cache", "=", "False", "t", "=", "time", ".", "time", "(", ")", "logger", ".", "debug", "(", "' downloading %s'", ",", "name", ")", "try", ":", "if", "not", "self", ".", "remote_store", "or", "(", "version", "is", "not", "None", "and", "not", "force_refresh", ")", ":", "try", ":", "if", "self", ".", "local_store", "and", "self", ".", "local_store", ".", "exists", "(", "name", ")", ":", "return", "self", ".", "local_store", ".", "get_file", "(", "name", ",", "save_to", ")", "except", "Exception", ":", "if", "self", ".", "remote_store", ":", "logger", ".", "warning", "(", "\"Error getting '%s' from local store\"", ",", "name", ",", "exc_info", "=", "True", ")", "else", ":", "raise", "if", "self", ".", "remote_store", ":", "if", "not", "_lock_exclusive", "and", "add_to_cache", ":", "if", "lock", ":", "lock", ".", "unlock", "(", ")", "return", "self", ".", "get_file", "(", "name", ",", "save_to", ",", "add_to_cache", ",", "_lock_exclusive", "=", "True", ")", "vname", "=", "self", ".", "remote_store", ".", "get_file", "(", "name", ",", "save_to", ")", "if", "add_to_cache", ":", "self", ".", "_add_to_cache", "(", "vname", ",", "save_to", ")", "return", "vname", "raise", "FiletrackerError", "(", "\"File not available: %s\"", "%", "name", ")", "finally", ":", "if", "lock", ":", "lock", ".", "close", "(", ")", "logger", ".", "debug", "(", "' processed %s in %.2fs'", ",", "name", ",", "time", ".", "time", "(", ")", "-", "t", ")" ]
Retrieves file identified by ``name``. The file is saved as ``save_to``. If ``add_to_cache`` is ``True``, the file is added to the local store. If ``force_refresh`` is ``True``, local cache is not examined if a remote store is configured. If a remote store is configured, but ``name`` does not contain a version, the local data store is not used, as we cannot guarantee that the version there is fresh. Local data store implemented in :class:`LocalDataStore` tries to not copy the entire file to ``save_to`` if possible, but instead uses hardlinking. Therefore you should not modify the file if you don't want to totally blow something. This method returns the full versioned name of the retrieved file.
[ "Retrieves", "file", "identified", "by", "name", "." ]
359b474850622e3d0c25ee2596d7242c02f84efb
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L91-L152
train
sio2project/filetracker
filetracker/client/client.py
Client.get_stream
def get_stream(self, name, force_refresh=False, serve_from_cache=False): """Retrieves file identified by ``name`` in streaming mode. Works like :meth:`get_file`, except that returns a tuple (file-like object, versioned name). When both remote_store and local_store are present, serve_from_cache can be used to ensure that the file will be downloaded and served from a local cache. If a full version is specified and the file exists in the cache a file will be always served locally. """ uname, version = split_name(name) lock = None if self.local_store: lock = self.lock_manager.lock_for(uname) lock.lock_shared() try: if not self.remote_store or (version is not None and not force_refresh): try: if self.local_store and self.local_store.exists(name): return self.local_store.get_stream(name) except Exception: if self.remote_store: logger.warning("Error getting '%s' from local store", name, exc_info=True) else: raise if self.remote_store: if self.local_store and serve_from_cache: if version is None: version = self.remote_store.file_version(name) if version: name = versioned_name(uname, version) if force_refresh or not self.local_store.exists(name): (stream, vname) = self.remote_store.get_stream(name) name = self.local_store.add_stream(vname, stream) return self.local_store.get_stream(name) return self.remote_store.get_stream(name) raise FiletrackerError("File not available: %s" % name) finally: if lock: lock.close()
python
def get_stream(self, name, force_refresh=False, serve_from_cache=False): """Retrieves file identified by ``name`` in streaming mode. Works like :meth:`get_file`, except that returns a tuple (file-like object, versioned name). When both remote_store and local_store are present, serve_from_cache can be used to ensure that the file will be downloaded and served from a local cache. If a full version is specified and the file exists in the cache a file will be always served locally. """ uname, version = split_name(name) lock = None if self.local_store: lock = self.lock_manager.lock_for(uname) lock.lock_shared() try: if not self.remote_store or (version is not None and not force_refresh): try: if self.local_store and self.local_store.exists(name): return self.local_store.get_stream(name) except Exception: if self.remote_store: logger.warning("Error getting '%s' from local store", name, exc_info=True) else: raise if self.remote_store: if self.local_store and serve_from_cache: if version is None: version = self.remote_store.file_version(name) if version: name = versioned_name(uname, version) if force_refresh or not self.local_store.exists(name): (stream, vname) = self.remote_store.get_stream(name) name = self.local_store.add_stream(vname, stream) return self.local_store.get_stream(name) return self.remote_store.get_stream(name) raise FiletrackerError("File not available: %s" % name) finally: if lock: lock.close()
[ "def", "get_stream", "(", "self", ",", "name", ",", "force_refresh", "=", "False", ",", "serve_from_cache", "=", "False", ")", ":", "uname", ",", "version", "=", "split_name", "(", "name", ")", "lock", "=", "None", "if", "self", ".", "local_store", ":", "lock", "=", "self", ".", "lock_manager", ".", "lock_for", "(", "uname", ")", "lock", ".", "lock_shared", "(", ")", "try", ":", "if", "not", "self", ".", "remote_store", "or", "(", "version", "is", "not", "None", "and", "not", "force_refresh", ")", ":", "try", ":", "if", "self", ".", "local_store", "and", "self", ".", "local_store", ".", "exists", "(", "name", ")", ":", "return", "self", ".", "local_store", ".", "get_stream", "(", "name", ")", "except", "Exception", ":", "if", "self", ".", "remote_store", ":", "logger", ".", "warning", "(", "\"Error getting '%s' from local store\"", ",", "name", ",", "exc_info", "=", "True", ")", "else", ":", "raise", "if", "self", ".", "remote_store", ":", "if", "self", ".", "local_store", "and", "serve_from_cache", ":", "if", "version", "is", "None", ":", "version", "=", "self", ".", "remote_store", ".", "file_version", "(", "name", ")", "if", "version", ":", "name", "=", "versioned_name", "(", "uname", ",", "version", ")", "if", "force_refresh", "or", "not", "self", ".", "local_store", ".", "exists", "(", "name", ")", ":", "(", "stream", ",", "vname", ")", "=", "self", ".", "remote_store", ".", "get_stream", "(", "name", ")", "name", "=", "self", ".", "local_store", ".", "add_stream", "(", "vname", ",", "stream", ")", "return", "self", ".", "local_store", ".", "get_stream", "(", "name", ")", "return", "self", ".", "remote_store", ".", "get_stream", "(", "name", ")", "raise", "FiletrackerError", "(", "\"File not available: %s\"", "%", "name", ")", "finally", ":", "if", "lock", ":", "lock", ".", "close", "(", ")" ]
Retrieves file identified by ``name`` in streaming mode. Works like :meth:`get_file`, except that returns a tuple (file-like object, versioned name). When both remote_store and local_store are present, serve_from_cache can be used to ensure that the file will be downloaded and served from a local cache. If a full version is specified and the file exists in the cache a file will be always served locally.
[ "Retrieves", "file", "identified", "by", "name", "in", "streaming", "mode", "." ]
359b474850622e3d0c25ee2596d7242c02f84efb
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L154-L199
train
sio2project/filetracker
filetracker/client/client.py
Client.file_version
def file_version(self, name): """Returns the newest available version number of the file. If the remote store is configured, it is queried, otherwise the local version is returned. It is assumed that the remote store always has the newest version of the file. If version is a part of ``name``, it is ignored. """ if self.remote_store: return self.remote_store.file_version(name) else: return self.local_store.file_version(name)
python
def file_version(self, name): """Returns the newest available version number of the file. If the remote store is configured, it is queried, otherwise the local version is returned. It is assumed that the remote store always has the newest version of the file. If version is a part of ``name``, it is ignored. """ if self.remote_store: return self.remote_store.file_version(name) else: return self.local_store.file_version(name)
[ "def", "file_version", "(", "self", ",", "name", ")", ":", "if", "self", ".", "remote_store", ":", "return", "self", ".", "remote_store", ".", "file_version", "(", "name", ")", "else", ":", "return", "self", ".", "local_store", ".", "file_version", "(", "name", ")" ]
Returns the newest available version number of the file. If the remote store is configured, it is queried, otherwise the local version is returned. It is assumed that the remote store always has the newest version of the file. If version is a part of ``name``, it is ignored.
[ "Returns", "the", "newest", "available", "version", "number", "of", "the", "file", "." ]
359b474850622e3d0c25ee2596d7242c02f84efb
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L201-L214
train
sio2project/filetracker
filetracker/client/client.py
Client.file_size
def file_size(self, name, force_refresh=False): """Returns the size of the file. For efficiency this operation does not use locking, so may return inconsistent data. Use it for informational purposes. """ uname, version = split_name(name) t = time.time() logger.debug(' querying size of %s', name) try: if not self.remote_store or (version is not None and not force_refresh): try: if self.local_store and self.local_store.exists(name): return self.local_store.file_size(name) except Exception: if self.remote_store: logger.warning("Error getting '%s' from local store", name, exc_info=True) else: raise if self.remote_store: return self.remote_store.file_size(name) raise FiletrackerError("File not available: %s" % name) finally: logger.debug(' processed %s in %.2fs', name, time.time() - t)
python
def file_size(self, name, force_refresh=False): """Returns the size of the file. For efficiency this operation does not use locking, so may return inconsistent data. Use it for informational purposes. """ uname, version = split_name(name) t = time.time() logger.debug(' querying size of %s', name) try: if not self.remote_store or (version is not None and not force_refresh): try: if self.local_store and self.local_store.exists(name): return self.local_store.file_size(name) except Exception: if self.remote_store: logger.warning("Error getting '%s' from local store", name, exc_info=True) else: raise if self.remote_store: return self.remote_store.file_size(name) raise FiletrackerError("File not available: %s" % name) finally: logger.debug(' processed %s in %.2fs', name, time.time() - t)
[ "def", "file_size", "(", "self", ",", "name", ",", "force_refresh", "=", "False", ")", ":", "uname", ",", "version", "=", "split_name", "(", "name", ")", "t", "=", "time", ".", "time", "(", ")", "logger", ".", "debug", "(", "' querying size of %s'", ",", "name", ")", "try", ":", "if", "not", "self", ".", "remote_store", "or", "(", "version", "is", "not", "None", "and", "not", "force_refresh", ")", ":", "try", ":", "if", "self", ".", "local_store", "and", "self", ".", "local_store", ".", "exists", "(", "name", ")", ":", "return", "self", ".", "local_store", ".", "file_size", "(", "name", ")", "except", "Exception", ":", "if", "self", ".", "remote_store", ":", "logger", ".", "warning", "(", "\"Error getting '%s' from local store\"", ",", "name", ",", "exc_info", "=", "True", ")", "else", ":", "raise", "if", "self", ".", "remote_store", ":", "return", "self", ".", "remote_store", ".", "file_size", "(", "name", ")", "raise", "FiletrackerError", "(", "\"File not available: %s\"", "%", "name", ")", "finally", ":", "logger", ".", "debug", "(", "' processed %s in %.2fs'", ",", "name", ",", "time", ".", "time", "(", ")", "-", "t", ")" ]
Returns the size of the file. For efficiency this operation does not use locking, so may return inconsistent data. Use it for informational purposes.
[ "Returns", "the", "size", "of", "the", "file", "." ]
359b474850622e3d0c25ee2596d7242c02f84efb
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L216-L243
train
sio2project/filetracker
filetracker/client/client.py
Client.put_file
def put_file(self, name, filename, to_local_store=True, to_remote_store=True, compress_hint=True): """Adds file ``filename`` to the filetracker under the name ``name``. If the file already exists, a new version is created. In practice if the store does not support versioning, the file is overwritten. The file may be added to local store only (if ``to_remote_store`` is ``False``), to remote store only (if ``to_local_store`` is ``False``) or both. If only one store is configured, the values of ``to_local_store`` and ``to_remote_store`` are ignored. Local data store implemented in :class:`LocalDataStore` tries to not directly copy the data to the final cache destination, but uses hardlinking. Therefore you should not modify the file in-place later as this would be disastrous. If ``compress_hint`` is set to False, file is compressed on the server, instead of the client. This is generally not recommended, unless you know what you're doing. """ if not to_local_store and not to_remote_store: raise ValueError("Neither to_local_store nor to_remote_store set " "in a call to filetracker.Client.put_file") check_name(name) lock = None if self.local_store: lock = self.lock_manager.lock_for(name) lock.lock_exclusive() try: if (to_local_store or not self.remote_store) and self.local_store: versioned_name = self.local_store.add_file(name, filename) if (to_remote_store or not self.local_store) and self.remote_store: versioned_name = self.remote_store.add_file( name, filename, compress_hint=compress_hint) finally: if lock: lock.close() return versioned_name
python
def put_file(self, name, filename, to_local_store=True, to_remote_store=True, compress_hint=True): """Adds file ``filename`` to the filetracker under the name ``name``. If the file already exists, a new version is created. In practice if the store does not support versioning, the file is overwritten. The file may be added to local store only (if ``to_remote_store`` is ``False``), to remote store only (if ``to_local_store`` is ``False``) or both. If only one store is configured, the values of ``to_local_store`` and ``to_remote_store`` are ignored. Local data store implemented in :class:`LocalDataStore` tries to not directly copy the data to the final cache destination, but uses hardlinking. Therefore you should not modify the file in-place later as this would be disastrous. If ``compress_hint`` is set to False, file is compressed on the server, instead of the client. This is generally not recommended, unless you know what you're doing. """ if not to_local_store and not to_remote_store: raise ValueError("Neither to_local_store nor to_remote_store set " "in a call to filetracker.Client.put_file") check_name(name) lock = None if self.local_store: lock = self.lock_manager.lock_for(name) lock.lock_exclusive() try: if (to_local_store or not self.remote_store) and self.local_store: versioned_name = self.local_store.add_file(name, filename) if (to_remote_store or not self.local_store) and self.remote_store: versioned_name = self.remote_store.add_file( name, filename, compress_hint=compress_hint) finally: if lock: lock.close() return versioned_name
[ "def", "put_file", "(", "self", ",", "name", ",", "filename", ",", "to_local_store", "=", "True", ",", "to_remote_store", "=", "True", ",", "compress_hint", "=", "True", ")", ":", "if", "not", "to_local_store", "and", "not", "to_remote_store", ":", "raise", "ValueError", "(", "\"Neither to_local_store nor to_remote_store set \"", "\"in a call to filetracker.Client.put_file\"", ")", "check_name", "(", "name", ")", "lock", "=", "None", "if", "self", ".", "local_store", ":", "lock", "=", "self", ".", "lock_manager", ".", "lock_for", "(", "name", ")", "lock", ".", "lock_exclusive", "(", ")", "try", ":", "if", "(", "to_local_store", "or", "not", "self", ".", "remote_store", ")", "and", "self", ".", "local_store", ":", "versioned_name", "=", "self", ".", "local_store", ".", "add_file", "(", "name", ",", "filename", ")", "if", "(", "to_remote_store", "or", "not", "self", ".", "local_store", ")", "and", "self", ".", "remote_store", ":", "versioned_name", "=", "self", ".", "remote_store", ".", "add_file", "(", "name", ",", "filename", ",", "compress_hint", "=", "compress_hint", ")", "finally", ":", "if", "lock", ":", "lock", ".", "close", "(", ")", "return", "versioned_name" ]
Adds file ``filename`` to the filetracker under the name ``name``. If the file already exists, a new version is created. In practice if the store does not support versioning, the file is overwritten. The file may be added to local store only (if ``to_remote_store`` is ``False``), to remote store only (if ``to_local_store`` is ``False``) or both. If only one store is configured, the values of ``to_local_store`` and ``to_remote_store`` are ignored. Local data store implemented in :class:`LocalDataStore` tries to not directly copy the data to the final cache destination, but uses hardlinking. Therefore you should not modify the file in-place later as this would be disastrous. If ``compress_hint`` is set to False, file is compressed on the server, instead of the client. This is generally not recommended, unless you know what you're doing.
[ "Adds", "file", "filename", "to", "the", "filetracker", "under", "the", "name", "name", "." ]
359b474850622e3d0c25ee2596d7242c02f84efb
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L245-L292
train
sio2project/filetracker
filetracker/client/client.py
Client.delete_file
def delete_file(self, name): """Deletes the file identified by ``name`` along with its metadata. The file is removed from both the local store and the remote store. """ if self.local_store: lock = self.lock_manager.lock_for(name) lock.lock_exclusive() try: self.local_store.delete_file(name) finally: lock.close() if self.remote_store: self.remote_store.delete_file(name)
python
def delete_file(self, name): """Deletes the file identified by ``name`` along with its metadata. The file is removed from both the local store and the remote store. """ if self.local_store: lock = self.lock_manager.lock_for(name) lock.lock_exclusive() try: self.local_store.delete_file(name) finally: lock.close() if self.remote_store: self.remote_store.delete_file(name)
[ "def", "delete_file", "(", "self", ",", "name", ")", ":", "if", "self", ".", "local_store", ":", "lock", "=", "self", ".", "lock_manager", ".", "lock_for", "(", "name", ")", "lock", ".", "lock_exclusive", "(", ")", "try", ":", "self", ".", "local_store", ".", "delete_file", "(", "name", ")", "finally", ":", "lock", ".", "close", "(", ")", "if", "self", ".", "remote_store", ":", "self", ".", "remote_store", ".", "delete_file", "(", "name", ")" ]
Deletes the file identified by ``name`` along with its metadata. The file is removed from both the local store and the remote store.
[ "Deletes", "the", "file", "identified", "by", "name", "along", "with", "its", "metadata", "." ]
359b474850622e3d0c25ee2596d7242c02f84efb
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L294-L307
train
sio2project/filetracker
filetracker/client/client.py
Client.list_local_files
def list_local_files(self): """Returns list of all stored local files. Each element of this list is of :class:`DataStore.FileInfoEntry` type. """ result = [] if self.local_store: result.extend(self.local_store.list_files()) return result
python
def list_local_files(self): """Returns list of all stored local files. Each element of this list is of :class:`DataStore.FileInfoEntry` type. """ result = [] if self.local_store: result.extend(self.local_store.list_files()) return result
[ "def", "list_local_files", "(", "self", ")", ":", "result", "=", "[", "]", "if", "self", ".", "local_store", ":", "result", ".", "extend", "(", "self", ".", "local_store", ".", "list_files", "(", ")", ")", "return", "result" ]
Returns list of all stored local files. Each element of this list is of :class:`DataStore.FileInfoEntry` type.
[ "Returns", "list", "of", "all", "stored", "local", "files", "." ]
359b474850622e3d0c25ee2596d7242c02f84efb
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/client.py#L309-L318
train
humangeo/preflyt
preflyt/__init__.py
load_checkers
def load_checkers(): """Load the checkers""" for loader, name, _ in pkgutil.iter_modules([os.path.join(__path__[0], 'checkers')]): loader.find_module(name).load_module(name)
python
def load_checkers(): """Load the checkers""" for loader, name, _ in pkgutil.iter_modules([os.path.join(__path__[0], 'checkers')]): loader.find_module(name).load_module(name)
[ "def", "load_checkers", "(", ")", ":", "for", "loader", ",", "name", ",", "_", "in", "pkgutil", ".", "iter_modules", "(", "[", "os", ".", "path", ".", "join", "(", "__path__", "[", "0", "]", ",", "'checkers'", ")", "]", ")", ":", "loader", ".", "find_module", "(", "name", ")", ".", "load_module", "(", "name", ")" ]
Load the checkers
[ "Load", "the", "checkers" ]
3174e6b8fc851ba5bd6c7fcf9becf36a6f6f6d93
https://github.com/humangeo/preflyt/blob/3174e6b8fc851ba5bd6c7fcf9becf36a6f6f6d93/preflyt/__init__.py#L17-L20
train
humangeo/preflyt
preflyt/__init__.py
check
def check(operations, loud=False): """Check all the things :param operations: The operations to check :param loud: `True` if checkers should prettyprint their status to stderr. `False` otherwise. :returns: A tuple of overall success, and a detailed execution log for all the operations """ if not CHECKERS: load_checkers() roll_call = [] everything_ok = True if loud and operations: title = "Preflyt Checklist" sys.stderr.write("{}\n{}\n".format(title, "=" * len(title))) for operation in operations: if operation.get('checker') not in CHECKERS: raise CheckerNotFoundError(operation) checker_cls = CHECKERS[operation['checker']] args = {k: v for k, v in operation.items() if k != 'checker'} checker = checker_cls(**args) success, message = checker.check() if not success: everything_ok = False roll_call.append({"check": operation, "success": success, "message": message}) if loud: sys.stderr.write(" {}\n".format(pformat_check(success, operation, message))) return everything_ok, roll_call
python
def check(operations, loud=False): """Check all the things :param operations: The operations to check :param loud: `True` if checkers should prettyprint their status to stderr. `False` otherwise. :returns: A tuple of overall success, and a detailed execution log for all the operations """ if not CHECKERS: load_checkers() roll_call = [] everything_ok = True if loud and operations: title = "Preflyt Checklist" sys.stderr.write("{}\n{}\n".format(title, "=" * len(title))) for operation in operations: if operation.get('checker') not in CHECKERS: raise CheckerNotFoundError(operation) checker_cls = CHECKERS[operation['checker']] args = {k: v for k, v in operation.items() if k != 'checker'} checker = checker_cls(**args) success, message = checker.check() if not success: everything_ok = False roll_call.append({"check": operation, "success": success, "message": message}) if loud: sys.stderr.write(" {}\n".format(pformat_check(success, operation, message))) return everything_ok, roll_call
[ "def", "check", "(", "operations", ",", "loud", "=", "False", ")", ":", "if", "not", "CHECKERS", ":", "load_checkers", "(", ")", "roll_call", "=", "[", "]", "everything_ok", "=", "True", "if", "loud", "and", "operations", ":", "title", "=", "\"Preflyt Checklist\"", "sys", ".", "stderr", ".", "write", "(", "\"{}\\n{}\\n\"", ".", "format", "(", "title", ",", "\"=\"", "*", "len", "(", "title", ")", ")", ")", "for", "operation", "in", "operations", ":", "if", "operation", ".", "get", "(", "'checker'", ")", "not", "in", "CHECKERS", ":", "raise", "CheckerNotFoundError", "(", "operation", ")", "checker_cls", "=", "CHECKERS", "[", "operation", "[", "'checker'", "]", "]", "args", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "operation", ".", "items", "(", ")", "if", "k", "!=", "'checker'", "}", "checker", "=", "checker_cls", "(", "*", "*", "args", ")", "success", ",", "message", "=", "checker", ".", "check", "(", ")", "if", "not", "success", ":", "everything_ok", "=", "False", "roll_call", ".", "append", "(", "{", "\"check\"", ":", "operation", ",", "\"success\"", ":", "success", ",", "\"message\"", ":", "message", "}", ")", "if", "loud", ":", "sys", ".", "stderr", ".", "write", "(", "\" {}\\n\"", ".", "format", "(", "pformat_check", "(", "success", ",", "operation", ",", "message", ")", ")", ")", "return", "everything_ok", ",", "roll_call" ]
Check all the things :param operations: The operations to check :param loud: `True` if checkers should prettyprint their status to stderr. `False` otherwise. :returns: A tuple of overall success, and a detailed execution log for all the operations
[ "Check", "all", "the", "things" ]
3174e6b8fc851ba5bd6c7fcf9becf36a6f6f6d93
https://github.com/humangeo/preflyt/blob/3174e6b8fc851ba5bd6c7fcf9becf36a6f6f6d93/preflyt/__init__.py#L22-L49
train
humangeo/preflyt
preflyt/__init__.py
verify
def verify(operations, loud=False): """Check all the things and be assertive about it :param operations: THe operations to check :param loud: `True` if checkers should prettyprint their status to stderr. `False` otherwise. :returns: The detailed execution log for the operations. """ everything_ok, roll_call = check(operations, loud=loud) if not everything_ok: raise CheckFailedException(roll_call) return roll_call
python
def verify(operations, loud=False): """Check all the things and be assertive about it :param operations: THe operations to check :param loud: `True` if checkers should prettyprint their status to stderr. `False` otherwise. :returns: The detailed execution log for the operations. """ everything_ok, roll_call = check(operations, loud=loud) if not everything_ok: raise CheckFailedException(roll_call) return roll_call
[ "def", "verify", "(", "operations", ",", "loud", "=", "False", ")", ":", "everything_ok", ",", "roll_call", "=", "check", "(", "operations", ",", "loud", "=", "loud", ")", "if", "not", "everything_ok", ":", "raise", "CheckFailedException", "(", "roll_call", ")", "return", "roll_call" ]
Check all the things and be assertive about it :param operations: THe operations to check :param loud: `True` if checkers should prettyprint their status to stderr. `False` otherwise. :returns: The detailed execution log for the operations.
[ "Check", "all", "the", "things", "and", "be", "assertive", "about", "it" ]
3174e6b8fc851ba5bd6c7fcf9becf36a6f6f6d93
https://github.com/humangeo/preflyt/blob/3174e6b8fc851ba5bd6c7fcf9becf36a6f6f6d93/preflyt/__init__.py#L51-L62
train
phn/angles
angles.py
deci2sexa
def deci2sexa(deci, pre=3, trunc=False, lower=None, upper=None, b=False, upper_trim=False): """Returns the sexagesimal representation of a decimal number. Parameters ---------- deci : float Decimal number to be converted into sexagesimal. If `lower` and `upper` are given then the number is normalized to the given range before converting to sexagesimal. pre : int The last part of the sexagesimal number is rounded to these many decimal places. This can be negative. Default is 3. trunc : bool If True then the last part of the sexagesimal number is truncated and not rounded to `pre` decimal places. Default is False. lower : int Lower bound of range to which number is to be normalized. upper : int Upper bound of range to which number is to be normalized. b : bool Affects type of normalization. See docstring for `normalize`. upper_trim : bool If `lower` and `upper` are given and this is True, then if the first part of the sexagesimal number is equal to `upper`, it is replaced with `lower` (value used is int(lower)). This converts numbers such as "24 00 00.000" to "00 00 00.000". Default value is False. Returns ------- s : 4 element tuple; (int, int, int, float) A tuple of sign and the three parts of the sexagesimal number. Sign is 1 for positive and -1 for negative values. The sign applies to the whole angle and not to any single part, i.e., all parts are positive and the sign multiplies the angle. The first and second parts of the sexagesimal number are integers and the last part is a float. Notes ----- The given decimal number `deci` is converted into a sexagesimal number. The last part of the sexagesimal number is rounded to `pre` number of decimal points. If `trunc == True` then instead of rounding, the last part is truncated. If `lower` and `upper` are given then the number is normalized to the given range before converting into sexagesimal format. The `b` argument determines the type of normalization. See docstring of the `normalize` function for details. If `upper_trim` is True then, if after convertion to sexagesimal the first part is equal to `upper`, it is replaced with `lower` (value used is int(lower)). This is useful in cases where numbers such as "24 00 00.00" needs to be converted into "00 00 00.00" The returned sign, first element of tuple, applies to the whole number and not just to a single part. Examples -------- >>> deci2sexa(-11.2345678) (-1, 11, 14, 4.444) >>> deci2sexa(-11.2345678, pre=5) (-1, 11, 14, 4.44408) >>> deci2sexa(-11.2345678, pre=4) (-1, 11, 14, 4.4441) >>> deci2sexa(-11.2345678, pre=4, trunc=True) (-1, 11, 14, 4.444) >>> deci2sexa(-11.2345678, pre=1) (-1, 11, 14, 4.4) >>> deci2sexa(-11.2345678, pre=0) (-1, 11, 14, 4.0) >>> deci2sexa(-11.2345678, pre=-1) (-1, 11, 14, 0.0) >>> x = 23+59/60.0+59.99999/3600.0 To 3 decimal places, this number is 24 or 0 hours. >>> deci2sexa(x, pre=3, lower=0, upper=24, upper_trim=True) (1, 0, 0, 0.0) >>> deci2sexa(x, pre=3, lower=0, upper=24, upper_trim=False) (1, 24, 0, 0.0) To 5 decimal places, we get back the full value. >>> deci2sexa(x, pre=5, lower=0, upper=24, upper_trim=True) (1, 23, 59, 59.99999) """ if lower is not None and upper is not None: deci = normalize(deci, lower=lower, upper=upper, b=b) sign = 1 if deci < 0: deci = abs(deci) sign = -1 hd, f1 = divmod(deci, 1) mm, f2 = divmod(f1 * 60.0, 1) sf = f2 * 60.0 # Find the seconds part to required precision. fp = 10 ** pre if trunc: ss, _ = divmod(sf * fp, 1) else: ss = round(sf * fp, 0) ss = int(ss) # If ss is 60 to given precision then update mm, and if necessary # hd. if ss == 60 * fp: mm += 1 ss = 0 if mm == 60: hd += 1 mm = 0 hd = int(hd) mm = int(mm) if lower is not None and upper is not None and upper_trim: # For example 24h0m0s => 0h0m0s. if hd == upper: hd = int(lower) if hd == 0 and mm == 0 and ss == 0: sign = 1 ss /= float(fp) # hd and mm parts are integer values but of type float return (sign, hd, mm, ss)
python
def deci2sexa(deci, pre=3, trunc=False, lower=None, upper=None, b=False, upper_trim=False): """Returns the sexagesimal representation of a decimal number. Parameters ---------- deci : float Decimal number to be converted into sexagesimal. If `lower` and `upper` are given then the number is normalized to the given range before converting to sexagesimal. pre : int The last part of the sexagesimal number is rounded to these many decimal places. This can be negative. Default is 3. trunc : bool If True then the last part of the sexagesimal number is truncated and not rounded to `pre` decimal places. Default is False. lower : int Lower bound of range to which number is to be normalized. upper : int Upper bound of range to which number is to be normalized. b : bool Affects type of normalization. See docstring for `normalize`. upper_trim : bool If `lower` and `upper` are given and this is True, then if the first part of the sexagesimal number is equal to `upper`, it is replaced with `lower` (value used is int(lower)). This converts numbers such as "24 00 00.000" to "00 00 00.000". Default value is False. Returns ------- s : 4 element tuple; (int, int, int, float) A tuple of sign and the three parts of the sexagesimal number. Sign is 1 for positive and -1 for negative values. The sign applies to the whole angle and not to any single part, i.e., all parts are positive and the sign multiplies the angle. The first and second parts of the sexagesimal number are integers and the last part is a float. Notes ----- The given decimal number `deci` is converted into a sexagesimal number. The last part of the sexagesimal number is rounded to `pre` number of decimal points. If `trunc == True` then instead of rounding, the last part is truncated. If `lower` and `upper` are given then the number is normalized to the given range before converting into sexagesimal format. The `b` argument determines the type of normalization. See docstring of the `normalize` function for details. If `upper_trim` is True then, if after convertion to sexagesimal the first part is equal to `upper`, it is replaced with `lower` (value used is int(lower)). This is useful in cases where numbers such as "24 00 00.00" needs to be converted into "00 00 00.00" The returned sign, first element of tuple, applies to the whole number and not just to a single part. Examples -------- >>> deci2sexa(-11.2345678) (-1, 11, 14, 4.444) >>> deci2sexa(-11.2345678, pre=5) (-1, 11, 14, 4.44408) >>> deci2sexa(-11.2345678, pre=4) (-1, 11, 14, 4.4441) >>> deci2sexa(-11.2345678, pre=4, trunc=True) (-1, 11, 14, 4.444) >>> deci2sexa(-11.2345678, pre=1) (-1, 11, 14, 4.4) >>> deci2sexa(-11.2345678, pre=0) (-1, 11, 14, 4.0) >>> deci2sexa(-11.2345678, pre=-1) (-1, 11, 14, 0.0) >>> x = 23+59/60.0+59.99999/3600.0 To 3 decimal places, this number is 24 or 0 hours. >>> deci2sexa(x, pre=3, lower=0, upper=24, upper_trim=True) (1, 0, 0, 0.0) >>> deci2sexa(x, pre=3, lower=0, upper=24, upper_trim=False) (1, 24, 0, 0.0) To 5 decimal places, we get back the full value. >>> deci2sexa(x, pre=5, lower=0, upper=24, upper_trim=True) (1, 23, 59, 59.99999) """ if lower is not None and upper is not None: deci = normalize(deci, lower=lower, upper=upper, b=b) sign = 1 if deci < 0: deci = abs(deci) sign = -1 hd, f1 = divmod(deci, 1) mm, f2 = divmod(f1 * 60.0, 1) sf = f2 * 60.0 # Find the seconds part to required precision. fp = 10 ** pre if trunc: ss, _ = divmod(sf * fp, 1) else: ss = round(sf * fp, 0) ss = int(ss) # If ss is 60 to given precision then update mm, and if necessary # hd. if ss == 60 * fp: mm += 1 ss = 0 if mm == 60: hd += 1 mm = 0 hd = int(hd) mm = int(mm) if lower is not None and upper is not None and upper_trim: # For example 24h0m0s => 0h0m0s. if hd == upper: hd = int(lower) if hd == 0 and mm == 0 and ss == 0: sign = 1 ss /= float(fp) # hd and mm parts are integer values but of type float return (sign, hd, mm, ss)
[ "def", "deci2sexa", "(", "deci", ",", "pre", "=", "3", ",", "trunc", "=", "False", ",", "lower", "=", "None", ",", "upper", "=", "None", ",", "b", "=", "False", ",", "upper_trim", "=", "False", ")", ":", "if", "lower", "is", "not", "None", "and", "upper", "is", "not", "None", ":", "deci", "=", "normalize", "(", "deci", ",", "lower", "=", "lower", ",", "upper", "=", "upper", ",", "b", "=", "b", ")", "sign", "=", "1", "if", "deci", "<", "0", ":", "deci", "=", "abs", "(", "deci", ")", "sign", "=", "-", "1", "hd", ",", "f1", "=", "divmod", "(", "deci", ",", "1", ")", "mm", ",", "f2", "=", "divmod", "(", "f1", "*", "60.0", ",", "1", ")", "sf", "=", "f2", "*", "60.0", "# Find the seconds part to required precision.", "fp", "=", "10", "**", "pre", "if", "trunc", ":", "ss", ",", "_", "=", "divmod", "(", "sf", "*", "fp", ",", "1", ")", "else", ":", "ss", "=", "round", "(", "sf", "*", "fp", ",", "0", ")", "ss", "=", "int", "(", "ss", ")", "# If ss is 60 to given precision then update mm, and if necessary", "# hd.", "if", "ss", "==", "60", "*", "fp", ":", "mm", "+=", "1", "ss", "=", "0", "if", "mm", "==", "60", ":", "hd", "+=", "1", "mm", "=", "0", "hd", "=", "int", "(", "hd", ")", "mm", "=", "int", "(", "mm", ")", "if", "lower", "is", "not", "None", "and", "upper", "is", "not", "None", "and", "upper_trim", ":", "# For example 24h0m0s => 0h0m0s.", "if", "hd", "==", "upper", ":", "hd", "=", "int", "(", "lower", ")", "if", "hd", "==", "0", "and", "mm", "==", "0", "and", "ss", "==", "0", ":", "sign", "=", "1", "ss", "/=", "float", "(", "fp", ")", "# hd and mm parts are integer values but of type float", "return", "(", "sign", ",", "hd", ",", "mm", ",", "ss", ")" ]
Returns the sexagesimal representation of a decimal number. Parameters ---------- deci : float Decimal number to be converted into sexagesimal. If `lower` and `upper` are given then the number is normalized to the given range before converting to sexagesimal. pre : int The last part of the sexagesimal number is rounded to these many decimal places. This can be negative. Default is 3. trunc : bool If True then the last part of the sexagesimal number is truncated and not rounded to `pre` decimal places. Default is False. lower : int Lower bound of range to which number is to be normalized. upper : int Upper bound of range to which number is to be normalized. b : bool Affects type of normalization. See docstring for `normalize`. upper_trim : bool If `lower` and `upper` are given and this is True, then if the first part of the sexagesimal number is equal to `upper`, it is replaced with `lower` (value used is int(lower)). This converts numbers such as "24 00 00.000" to "00 00 00.000". Default value is False. Returns ------- s : 4 element tuple; (int, int, int, float) A tuple of sign and the three parts of the sexagesimal number. Sign is 1 for positive and -1 for negative values. The sign applies to the whole angle and not to any single part, i.e., all parts are positive and the sign multiplies the angle. The first and second parts of the sexagesimal number are integers and the last part is a float. Notes ----- The given decimal number `deci` is converted into a sexagesimal number. The last part of the sexagesimal number is rounded to `pre` number of decimal points. If `trunc == True` then instead of rounding, the last part is truncated. If `lower` and `upper` are given then the number is normalized to the given range before converting into sexagesimal format. The `b` argument determines the type of normalization. See docstring of the `normalize` function for details. If `upper_trim` is True then, if after convertion to sexagesimal the first part is equal to `upper`, it is replaced with `lower` (value used is int(lower)). This is useful in cases where numbers such as "24 00 00.00" needs to be converted into "00 00 00.00" The returned sign, first element of tuple, applies to the whole number and not just to a single part. Examples -------- >>> deci2sexa(-11.2345678) (-1, 11, 14, 4.444) >>> deci2sexa(-11.2345678, pre=5) (-1, 11, 14, 4.44408) >>> deci2sexa(-11.2345678, pre=4) (-1, 11, 14, 4.4441) >>> deci2sexa(-11.2345678, pre=4, trunc=True) (-1, 11, 14, 4.444) >>> deci2sexa(-11.2345678, pre=1) (-1, 11, 14, 4.4) >>> deci2sexa(-11.2345678, pre=0) (-1, 11, 14, 4.0) >>> deci2sexa(-11.2345678, pre=-1) (-1, 11, 14, 0.0) >>> x = 23+59/60.0+59.99999/3600.0 To 3 decimal places, this number is 24 or 0 hours. >>> deci2sexa(x, pre=3, lower=0, upper=24, upper_trim=True) (1, 0, 0, 0.0) >>> deci2sexa(x, pre=3, lower=0, upper=24, upper_trim=False) (1, 24, 0, 0.0) To 5 decimal places, we get back the full value. >>> deci2sexa(x, pre=5, lower=0, upper=24, upper_trim=True) (1, 23, 59, 59.99999)
[ "Returns", "the", "sexagesimal", "representation", "of", "a", "decimal", "number", "." ]
5c30ed7c3a7412177daaed180bf3b2351b287589
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L269-L403
train
phn/angles
angles.py
sexa2deci
def sexa2deci(sign, hd, mm, ss, todeg=False): """Combine sexagesimal components into a decimal number. Parameters ---------- sign : int Sign of the number: 1 for +ve, -1 for negative. hd : float The hour or degree like part. mm : float The minute or arc-minute like part. ss : float The second or arc-second like part. todeg : bool If True then convert to degrees, assuming that the input value is in hours. Default is False. Returns ------- d : float The decimal equivalent of the sexagesimal number. Raises ------ ValueError This exception is raised if `sign` is not -1 or 1. Notes ----- The angle returned is:: sign * (hd + mm / 60.0 + ss / 3600.0) In sexagesimal notation the sign applies to the whole quantity and not to each part separately. So the `sign` is asked separately, and applied to the whole quantity. If the sexagesimal quantity is in hours, then we frequently want to convert it into degrees. If the `todeg == True` then the given value is assumed to be in hours, and the returned value will be in degrees. Examples -------- >>> d = sexa2deci(1,12,0,0.0) >>> d 12.0 >>> d = sexa2deci(1,12,0,0.0,todeg=True) >>> d 180.0 >>> x = sexa2deci(1,9,12.456,0.0) >>> assert round(x,4) == 9.2076 >>> x = sexa2deci(1,11,30,27.0) >>> assert round(x, 4) == 11.5075 """ divisors = [1.0, 60.0, 3600.0] d = 0.0 # sexages[0] is sign. if sign not in (-1, 1): raise ValueError("Sign has to be -1 or 1.") sexages = [sign, hd, mm, ss] for i, divis in zip(sexages[1:], divisors): d += i / divis # Add proper sign. d *= sexages[0] if todeg: d = h2d(d) return d
python
def sexa2deci(sign, hd, mm, ss, todeg=False): """Combine sexagesimal components into a decimal number. Parameters ---------- sign : int Sign of the number: 1 for +ve, -1 for negative. hd : float The hour or degree like part. mm : float The minute or arc-minute like part. ss : float The second or arc-second like part. todeg : bool If True then convert to degrees, assuming that the input value is in hours. Default is False. Returns ------- d : float The decimal equivalent of the sexagesimal number. Raises ------ ValueError This exception is raised if `sign` is not -1 or 1. Notes ----- The angle returned is:: sign * (hd + mm / 60.0 + ss / 3600.0) In sexagesimal notation the sign applies to the whole quantity and not to each part separately. So the `sign` is asked separately, and applied to the whole quantity. If the sexagesimal quantity is in hours, then we frequently want to convert it into degrees. If the `todeg == True` then the given value is assumed to be in hours, and the returned value will be in degrees. Examples -------- >>> d = sexa2deci(1,12,0,0.0) >>> d 12.0 >>> d = sexa2deci(1,12,0,0.0,todeg=True) >>> d 180.0 >>> x = sexa2deci(1,9,12.456,0.0) >>> assert round(x,4) == 9.2076 >>> x = sexa2deci(1,11,30,27.0) >>> assert round(x, 4) == 11.5075 """ divisors = [1.0, 60.0, 3600.0] d = 0.0 # sexages[0] is sign. if sign not in (-1, 1): raise ValueError("Sign has to be -1 or 1.") sexages = [sign, hd, mm, ss] for i, divis in zip(sexages[1:], divisors): d += i / divis # Add proper sign. d *= sexages[0] if todeg: d = h2d(d) return d
[ "def", "sexa2deci", "(", "sign", ",", "hd", ",", "mm", ",", "ss", ",", "todeg", "=", "False", ")", ":", "divisors", "=", "[", "1.0", ",", "60.0", ",", "3600.0", "]", "d", "=", "0.0", "# sexages[0] is sign.", "if", "sign", "not", "in", "(", "-", "1", ",", "1", ")", ":", "raise", "ValueError", "(", "\"Sign has to be -1 or 1.\"", ")", "sexages", "=", "[", "sign", ",", "hd", ",", "mm", ",", "ss", "]", "for", "i", ",", "divis", "in", "zip", "(", "sexages", "[", "1", ":", "]", ",", "divisors", ")", ":", "d", "+=", "i", "/", "divis", "# Add proper sign.", "d", "*=", "sexages", "[", "0", "]", "if", "todeg", ":", "d", "=", "h2d", "(", "d", ")", "return", "d" ]
Combine sexagesimal components into a decimal number. Parameters ---------- sign : int Sign of the number: 1 for +ve, -1 for negative. hd : float The hour or degree like part. mm : float The minute or arc-minute like part. ss : float The second or arc-second like part. todeg : bool If True then convert to degrees, assuming that the input value is in hours. Default is False. Returns ------- d : float The decimal equivalent of the sexagesimal number. Raises ------ ValueError This exception is raised if `sign` is not -1 or 1. Notes ----- The angle returned is:: sign * (hd + mm / 60.0 + ss / 3600.0) In sexagesimal notation the sign applies to the whole quantity and not to each part separately. So the `sign` is asked separately, and applied to the whole quantity. If the sexagesimal quantity is in hours, then we frequently want to convert it into degrees. If the `todeg == True` then the given value is assumed to be in hours, and the returned value will be in degrees. Examples -------- >>> d = sexa2deci(1,12,0,0.0) >>> d 12.0 >>> d = sexa2deci(1,12,0,0.0,todeg=True) >>> d 180.0 >>> x = sexa2deci(1,9,12.456,0.0) >>> assert round(x,4) == 9.2076 >>> x = sexa2deci(1,11,30,27.0) >>> assert round(x, 4) == 11.5075
[ "Combine", "sexagesimal", "components", "into", "a", "decimal", "number", "." ]
5c30ed7c3a7412177daaed180bf3b2351b287589
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L406-L477
train
phn/angles
angles.py
fmt_angle
def fmt_angle(val, s1=" ", s2=" ", s3="", pre=3, trunc=False, lower=None, upper=None, b=False, upper_trim=False): """Return sexagesimal string of given angle in degrees or hours. Parameters ---------- val : float The angle (in degrees or hours) that is to be converted into a sexagesimal string. s1 : str Character to be used between the first and second parts of the the sexagesimal representation. s2 : str Character to be used between the second and third parts of the the sexagesimal representation. s3 : str Character to be used after the third part of the sexagesimal representation. pre : int The final part of the sexagesimal number is rounded to these many decimal places. This can be negative. trunc : bool If True then the third part of the sexagesimal number is truncated to `pre` decimal places, instead of rounding. lower, upper : float If `lower` and `upper` are given then the given value is normalized into the this range before converting to sexagesimal string. b : bool This affect how the normalization is performed. See notes. This works exactly like that for the function `normalize()`. upper_trim : bool If `lower` and `upper` are given, then if the first part of the sexagesimal number equals `upper`, it is replaced with `lower`. For examples, "12 00 00" gets turned into "00 00 00". See also -------- normalize deci2sexa Examples -------- >>> fmt_angle(12.348978659, pre=4, trunc=True) '+12 20 56.3231' >>> fmt_angle(12.348978659, pre=5) '+12 20 56.32317' >>> fmt_angle(12.348978659, s1='HH ', s2='MM ', s3='SS', pre=5) '+12HH 20MM 56.32317SS' >>> x = 23+59/60.0+59.99999/3600.0 >>> fmt_angle(x) '+24 00 00.000' >>> fmt_angle(x, lower=0, upper=24, upper_trim=True) '+00 00 00.000' >>> fmt_angle(x, pre=5) '+23 59 59.99999' >>> fmt_angle(-x, lower=0, upper=24, upper_trim=True) '+00 00 00.000' >>> fmt_angle(-x) '-24 00 00.000' """ x = deci2sexa(val, pre=pre, trunc=trunc, lower=lower, upper=upper, upper_trim=upper_trim, b=b) left_digits_plus_deci_point = 3 if pre > 0 else 2 p = "{3:0" + "{0}.{1}".format(pre + left_digits_plus_deci_point, pre) + "f}" + s3 p = "{0}{1:02d}" + s1 + "{2:02d}" + s2 + p return p.format("-" if x[0] < 0 else "+", *x[1:])
python
def fmt_angle(val, s1=" ", s2=" ", s3="", pre=3, trunc=False, lower=None, upper=None, b=False, upper_trim=False): """Return sexagesimal string of given angle in degrees or hours. Parameters ---------- val : float The angle (in degrees or hours) that is to be converted into a sexagesimal string. s1 : str Character to be used between the first and second parts of the the sexagesimal representation. s2 : str Character to be used between the second and third parts of the the sexagesimal representation. s3 : str Character to be used after the third part of the sexagesimal representation. pre : int The final part of the sexagesimal number is rounded to these many decimal places. This can be negative. trunc : bool If True then the third part of the sexagesimal number is truncated to `pre` decimal places, instead of rounding. lower, upper : float If `lower` and `upper` are given then the given value is normalized into the this range before converting to sexagesimal string. b : bool This affect how the normalization is performed. See notes. This works exactly like that for the function `normalize()`. upper_trim : bool If `lower` and `upper` are given, then if the first part of the sexagesimal number equals `upper`, it is replaced with `lower`. For examples, "12 00 00" gets turned into "00 00 00". See also -------- normalize deci2sexa Examples -------- >>> fmt_angle(12.348978659, pre=4, trunc=True) '+12 20 56.3231' >>> fmt_angle(12.348978659, pre=5) '+12 20 56.32317' >>> fmt_angle(12.348978659, s1='HH ', s2='MM ', s3='SS', pre=5) '+12HH 20MM 56.32317SS' >>> x = 23+59/60.0+59.99999/3600.0 >>> fmt_angle(x) '+24 00 00.000' >>> fmt_angle(x, lower=0, upper=24, upper_trim=True) '+00 00 00.000' >>> fmt_angle(x, pre=5) '+23 59 59.99999' >>> fmt_angle(-x, lower=0, upper=24, upper_trim=True) '+00 00 00.000' >>> fmt_angle(-x) '-24 00 00.000' """ x = deci2sexa(val, pre=pre, trunc=trunc, lower=lower, upper=upper, upper_trim=upper_trim, b=b) left_digits_plus_deci_point = 3 if pre > 0 else 2 p = "{3:0" + "{0}.{1}".format(pre + left_digits_plus_deci_point, pre) + "f}" + s3 p = "{0}{1:02d}" + s1 + "{2:02d}" + s2 + p return p.format("-" if x[0] < 0 else "+", *x[1:])
[ "def", "fmt_angle", "(", "val", ",", "s1", "=", "\" \"", ",", "s2", "=", "\" \"", ",", "s3", "=", "\"\"", ",", "pre", "=", "3", ",", "trunc", "=", "False", ",", "lower", "=", "None", ",", "upper", "=", "None", ",", "b", "=", "False", ",", "upper_trim", "=", "False", ")", ":", "x", "=", "deci2sexa", "(", "val", ",", "pre", "=", "pre", ",", "trunc", "=", "trunc", ",", "lower", "=", "lower", ",", "upper", "=", "upper", ",", "upper_trim", "=", "upper_trim", ",", "b", "=", "b", ")", "left_digits_plus_deci_point", "=", "3", "if", "pre", ">", "0", "else", "2", "p", "=", "\"{3:0\"", "+", "\"{0}.{1}\"", ".", "format", "(", "pre", "+", "left_digits_plus_deci_point", ",", "pre", ")", "+", "\"f}\"", "+", "s3", "p", "=", "\"{0}{1:02d}\"", "+", "s1", "+", "\"{2:02d}\"", "+", "s2", "+", "p", "return", "p", ".", "format", "(", "\"-\"", "if", "x", "[", "0", "]", "<", "0", "else", "\"+\"", ",", "*", "x", "[", "1", ":", "]", ")" ]
Return sexagesimal string of given angle in degrees or hours. Parameters ---------- val : float The angle (in degrees or hours) that is to be converted into a sexagesimal string. s1 : str Character to be used between the first and second parts of the the sexagesimal representation. s2 : str Character to be used between the second and third parts of the the sexagesimal representation. s3 : str Character to be used after the third part of the sexagesimal representation. pre : int The final part of the sexagesimal number is rounded to these many decimal places. This can be negative. trunc : bool If True then the third part of the sexagesimal number is truncated to `pre` decimal places, instead of rounding. lower, upper : float If `lower` and `upper` are given then the given value is normalized into the this range before converting to sexagesimal string. b : bool This affect how the normalization is performed. See notes. This works exactly like that for the function `normalize()`. upper_trim : bool If `lower` and `upper` are given, then if the first part of the sexagesimal number equals `upper`, it is replaced with `lower`. For examples, "12 00 00" gets turned into "00 00 00". See also -------- normalize deci2sexa Examples -------- >>> fmt_angle(12.348978659, pre=4, trunc=True) '+12 20 56.3231' >>> fmt_angle(12.348978659, pre=5) '+12 20 56.32317' >>> fmt_angle(12.348978659, s1='HH ', s2='MM ', s3='SS', pre=5) '+12HH 20MM 56.32317SS' >>> x = 23+59/60.0+59.99999/3600.0 >>> fmt_angle(x) '+24 00 00.000' >>> fmt_angle(x, lower=0, upper=24, upper_trim=True) '+00 00 00.000' >>> fmt_angle(x, pre=5) '+23 59 59.99999' >>> fmt_angle(-x, lower=0, upper=24, upper_trim=True) '+00 00 00.000' >>> fmt_angle(-x) '-24 00 00.000'
[ "Return", "sexagesimal", "string", "of", "given", "angle", "in", "degrees", "or", "hours", "." ]
5c30ed7c3a7412177daaed180bf3b2351b287589
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L480-L551
train
phn/angles
angles.py
phmsdms
def phmsdms(hmsdms): """Parse a string containing a sexagesimal number. This can handle several types of delimiters and will process reasonably valid strings. See examples. Parameters ---------- hmsdms : str String containing a sexagesimal number. Returns ------- d : dict parts : a 3 element list of floats The three parts of the sexagesimal number that were identified. vals : 3 element list of floats The numerical values of the three parts of the sexagesimal number. sign : int Sign of the sexagesimal number; 1 for positive and -1 for negative. units : {"degrees", "hours"} The units of the sexagesimal number. This is infered from the characters present in the string. If it a pure number then units is "degrees". Examples -------- >>> phmsdms("12") == { ... 'parts': [12.0, None, None], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 0.0, 0.0] ... } True >>> phmsdms("12h") == { ... 'parts': [12.0, None, None], ... 'sign': 1, ... 'units': 'hours', ... 'vals': [12.0, 0.0, 0.0] ... } True >>> phmsdms("12d13m14.56") == { ... 'parts': [12.0, 13.0, 14.56], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 13.0, 14.56] ... } True >>> phmsdms("12d13m14.56") == { ... 'parts': [12.0, 13.0, 14.56], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 13.0, 14.56] ... } True >>> phmsdms("12d14.56ss") == { ... 'parts': [12.0, None, 14.56], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 0.0, 14.56] ... } True >>> phmsdms("14.56ss") == { ... 'parts': [None, None, 14.56], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [0.0, 0.0, 14.56] ... } True >>> phmsdms("12h13m12.4s") == { ... 'parts': [12.0, 13.0, 12.4], ... 'sign': 1, ... 'units': 'hours', ... 'vals': [12.0, 13.0, 12.4] ... } True >>> phmsdms("12:13:12.4s") == { ... 'parts': [12.0, 13.0, 12.4], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 13.0, 12.4] ... } True But `phmsdms("12:13mm:12.4s")` will not work. """ units = None sign = None # Floating point regex: # http://www.regular-expressions.info/floatingpoint.html # # pattern1: find a decimal number (int or float) and any # characters following it upto the next decimal number. [^0-9\-+]* # => keep gathering elements until we get to a digit, a - or a # +. These three indicates the possible start of the next number. pattern1 = re.compile(r"([-+]?[0-9]*\.?[0-9]+[^0-9\-+]*)") # pattern2: find decimal number (int or float) in string. pattern2 = re.compile(r"([-+]?[0-9]*\.?[0-9]+)") hmsdms = hmsdms.lower() hdlist = pattern1.findall(hmsdms) parts = [None, None, None] def _fill_right_not_none(): # Find the pos. where parts is not None. Next value must # be inserted to the right of this. If this is 2 then we have # already filled seconds part, raise exception. If this is 1 # then fill 2. If this is 0 fill 1. If none of these then fill # 0. rp = reversed(parts) for i, j in enumerate(rp): if j is not None: break if i == 0: # Seconds part already filled. raise ValueError("Invalid string.") elif i == 1: parts[2] = v elif i == 2: # Either parts[0] is None so fill it, or it is filled # and hence fill parts[1]. if parts[0] is None: parts[0] = v else: parts[1] = v for valun in hdlist: try: # See if this is pure number. v = float(valun) # Sexagesimal part cannot be determined. So guess it by # seeing which all parts have already been identified. _fill_right_not_none() except ValueError: # Not a pure number. Infer sexagesimal part from the # suffix. if "hh" in valun or "h" in valun: m = pattern2.search(valun) parts[0] = float(valun[m.start():m.end()]) units = "hours" if "dd" in valun or "d" in valun: m = pattern2.search(valun) parts[0] = float(valun[m.start():m.end()]) units = "degrees" if "mm" in valun or "m" in valun: m = pattern2.search(valun) parts[1] = float(valun[m.start():m.end()]) if "ss" in valun or "s" in valun: m = pattern2.search(valun) parts[2] = float(valun[m.start():m.end()]) if "'" in valun: m = pattern2.search(valun) parts[1] = float(valun[m.start():m.end()]) if '"' in valun: m = pattern2.search(valun) parts[2] = float(valun[m.start():m.end()]) if ":" in valun: # Sexagesimal part cannot be determined. So guess it by # seeing which all parts have already been identified. v = valun.replace(":", "") v = float(v) _fill_right_not_none() if not units: units = "degrees" # Find sign. Only the first identified part can have a -ve sign. for i in parts: if i and i < 0.0: if sign is None: sign = -1 else: raise ValueError("Only one number can be negative.") if sign is None: # None of these are negative. sign = 1 vals = [abs(i) if i is not None else 0.0 for i in parts] return dict(sign=sign, units=units, vals=vals, parts=parts)
python
def phmsdms(hmsdms): """Parse a string containing a sexagesimal number. This can handle several types of delimiters and will process reasonably valid strings. See examples. Parameters ---------- hmsdms : str String containing a sexagesimal number. Returns ------- d : dict parts : a 3 element list of floats The three parts of the sexagesimal number that were identified. vals : 3 element list of floats The numerical values of the three parts of the sexagesimal number. sign : int Sign of the sexagesimal number; 1 for positive and -1 for negative. units : {"degrees", "hours"} The units of the sexagesimal number. This is infered from the characters present in the string. If it a pure number then units is "degrees". Examples -------- >>> phmsdms("12") == { ... 'parts': [12.0, None, None], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 0.0, 0.0] ... } True >>> phmsdms("12h") == { ... 'parts': [12.0, None, None], ... 'sign': 1, ... 'units': 'hours', ... 'vals': [12.0, 0.0, 0.0] ... } True >>> phmsdms("12d13m14.56") == { ... 'parts': [12.0, 13.0, 14.56], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 13.0, 14.56] ... } True >>> phmsdms("12d13m14.56") == { ... 'parts': [12.0, 13.0, 14.56], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 13.0, 14.56] ... } True >>> phmsdms("12d14.56ss") == { ... 'parts': [12.0, None, 14.56], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 0.0, 14.56] ... } True >>> phmsdms("14.56ss") == { ... 'parts': [None, None, 14.56], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [0.0, 0.0, 14.56] ... } True >>> phmsdms("12h13m12.4s") == { ... 'parts': [12.0, 13.0, 12.4], ... 'sign': 1, ... 'units': 'hours', ... 'vals': [12.0, 13.0, 12.4] ... } True >>> phmsdms("12:13:12.4s") == { ... 'parts': [12.0, 13.0, 12.4], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 13.0, 12.4] ... } True But `phmsdms("12:13mm:12.4s")` will not work. """ units = None sign = None # Floating point regex: # http://www.regular-expressions.info/floatingpoint.html # # pattern1: find a decimal number (int or float) and any # characters following it upto the next decimal number. [^0-9\-+]* # => keep gathering elements until we get to a digit, a - or a # +. These three indicates the possible start of the next number. pattern1 = re.compile(r"([-+]?[0-9]*\.?[0-9]+[^0-9\-+]*)") # pattern2: find decimal number (int or float) in string. pattern2 = re.compile(r"([-+]?[0-9]*\.?[0-9]+)") hmsdms = hmsdms.lower() hdlist = pattern1.findall(hmsdms) parts = [None, None, None] def _fill_right_not_none(): # Find the pos. where parts is not None. Next value must # be inserted to the right of this. If this is 2 then we have # already filled seconds part, raise exception. If this is 1 # then fill 2. If this is 0 fill 1. If none of these then fill # 0. rp = reversed(parts) for i, j in enumerate(rp): if j is not None: break if i == 0: # Seconds part already filled. raise ValueError("Invalid string.") elif i == 1: parts[2] = v elif i == 2: # Either parts[0] is None so fill it, or it is filled # and hence fill parts[1]. if parts[0] is None: parts[0] = v else: parts[1] = v for valun in hdlist: try: # See if this is pure number. v = float(valun) # Sexagesimal part cannot be determined. So guess it by # seeing which all parts have already been identified. _fill_right_not_none() except ValueError: # Not a pure number. Infer sexagesimal part from the # suffix. if "hh" in valun or "h" in valun: m = pattern2.search(valun) parts[0] = float(valun[m.start():m.end()]) units = "hours" if "dd" in valun or "d" in valun: m = pattern2.search(valun) parts[0] = float(valun[m.start():m.end()]) units = "degrees" if "mm" in valun or "m" in valun: m = pattern2.search(valun) parts[1] = float(valun[m.start():m.end()]) if "ss" in valun or "s" in valun: m = pattern2.search(valun) parts[2] = float(valun[m.start():m.end()]) if "'" in valun: m = pattern2.search(valun) parts[1] = float(valun[m.start():m.end()]) if '"' in valun: m = pattern2.search(valun) parts[2] = float(valun[m.start():m.end()]) if ":" in valun: # Sexagesimal part cannot be determined. So guess it by # seeing which all parts have already been identified. v = valun.replace(":", "") v = float(v) _fill_right_not_none() if not units: units = "degrees" # Find sign. Only the first identified part can have a -ve sign. for i in parts: if i and i < 0.0: if sign is None: sign = -1 else: raise ValueError("Only one number can be negative.") if sign is None: # None of these are negative. sign = 1 vals = [abs(i) if i is not None else 0.0 for i in parts] return dict(sign=sign, units=units, vals=vals, parts=parts)
[ "def", "phmsdms", "(", "hmsdms", ")", ":", "units", "=", "None", "sign", "=", "None", "# Floating point regex:", "# http://www.regular-expressions.info/floatingpoint.html", "#", "# pattern1: find a decimal number (int or float) and any", "# characters following it upto the next decimal number. [^0-9\\-+]*", "# => keep gathering elements until we get to a digit, a - or a", "# +. These three indicates the possible start of the next number.", "pattern1", "=", "re", ".", "compile", "(", "r\"([-+]?[0-9]*\\.?[0-9]+[^0-9\\-+]*)\"", ")", "# pattern2: find decimal number (int or float) in string.", "pattern2", "=", "re", ".", "compile", "(", "r\"([-+]?[0-9]*\\.?[0-9]+)\"", ")", "hmsdms", "=", "hmsdms", ".", "lower", "(", ")", "hdlist", "=", "pattern1", ".", "findall", "(", "hmsdms", ")", "parts", "=", "[", "None", ",", "None", ",", "None", "]", "def", "_fill_right_not_none", "(", ")", ":", "# Find the pos. where parts is not None. Next value must", "# be inserted to the right of this. If this is 2 then we have", "# already filled seconds part, raise exception. If this is 1", "# then fill 2. If this is 0 fill 1. If none of these then fill", "# 0.", "rp", "=", "reversed", "(", "parts", ")", "for", "i", ",", "j", "in", "enumerate", "(", "rp", ")", ":", "if", "j", "is", "not", "None", ":", "break", "if", "i", "==", "0", ":", "# Seconds part already filled.", "raise", "ValueError", "(", "\"Invalid string.\"", ")", "elif", "i", "==", "1", ":", "parts", "[", "2", "]", "=", "v", "elif", "i", "==", "2", ":", "# Either parts[0] is None so fill it, or it is filled", "# and hence fill parts[1].", "if", "parts", "[", "0", "]", "is", "None", ":", "parts", "[", "0", "]", "=", "v", "else", ":", "parts", "[", "1", "]", "=", "v", "for", "valun", "in", "hdlist", ":", "try", ":", "# See if this is pure number.", "v", "=", "float", "(", "valun", ")", "# Sexagesimal part cannot be determined. So guess it by", "# seeing which all parts have already been identified.", "_fill_right_not_none", "(", ")", "except", "ValueError", ":", "# Not a pure number. Infer sexagesimal part from the", "# suffix.", "if", "\"hh\"", "in", "valun", "or", "\"h\"", "in", "valun", ":", "m", "=", "pattern2", ".", "search", "(", "valun", ")", "parts", "[", "0", "]", "=", "float", "(", "valun", "[", "m", ".", "start", "(", ")", ":", "m", ".", "end", "(", ")", "]", ")", "units", "=", "\"hours\"", "if", "\"dd\"", "in", "valun", "or", "\"d\"", "in", "valun", ":", "m", "=", "pattern2", ".", "search", "(", "valun", ")", "parts", "[", "0", "]", "=", "float", "(", "valun", "[", "m", ".", "start", "(", ")", ":", "m", ".", "end", "(", ")", "]", ")", "units", "=", "\"degrees\"", "if", "\"mm\"", "in", "valun", "or", "\"m\"", "in", "valun", ":", "m", "=", "pattern2", ".", "search", "(", "valun", ")", "parts", "[", "1", "]", "=", "float", "(", "valun", "[", "m", ".", "start", "(", ")", ":", "m", ".", "end", "(", ")", "]", ")", "if", "\"ss\"", "in", "valun", "or", "\"s\"", "in", "valun", ":", "m", "=", "pattern2", ".", "search", "(", "valun", ")", "parts", "[", "2", "]", "=", "float", "(", "valun", "[", "m", ".", "start", "(", ")", ":", "m", ".", "end", "(", ")", "]", ")", "if", "\"'\"", "in", "valun", ":", "m", "=", "pattern2", ".", "search", "(", "valun", ")", "parts", "[", "1", "]", "=", "float", "(", "valun", "[", "m", ".", "start", "(", ")", ":", "m", ".", "end", "(", ")", "]", ")", "if", "'\"'", "in", "valun", ":", "m", "=", "pattern2", ".", "search", "(", "valun", ")", "parts", "[", "2", "]", "=", "float", "(", "valun", "[", "m", ".", "start", "(", ")", ":", "m", ".", "end", "(", ")", "]", ")", "if", "\":\"", "in", "valun", ":", "# Sexagesimal part cannot be determined. So guess it by", "# seeing which all parts have already been identified.", "v", "=", "valun", ".", "replace", "(", "\":\"", ",", "\"\"", ")", "v", "=", "float", "(", "v", ")", "_fill_right_not_none", "(", ")", "if", "not", "units", ":", "units", "=", "\"degrees\"", "# Find sign. Only the first identified part can have a -ve sign.", "for", "i", "in", "parts", ":", "if", "i", "and", "i", "<", "0.0", ":", "if", "sign", "is", "None", ":", "sign", "=", "-", "1", "else", ":", "raise", "ValueError", "(", "\"Only one number can be negative.\"", ")", "if", "sign", "is", "None", ":", "# None of these are negative.", "sign", "=", "1", "vals", "=", "[", "abs", "(", "i", ")", "if", "i", "is", "not", "None", "else", "0.0", "for", "i", "in", "parts", "]", "return", "dict", "(", "sign", "=", "sign", ",", "units", "=", "units", ",", "vals", "=", "vals", ",", "parts", "=", "parts", ")" ]
Parse a string containing a sexagesimal number. This can handle several types of delimiters and will process reasonably valid strings. See examples. Parameters ---------- hmsdms : str String containing a sexagesimal number. Returns ------- d : dict parts : a 3 element list of floats The three parts of the sexagesimal number that were identified. vals : 3 element list of floats The numerical values of the three parts of the sexagesimal number. sign : int Sign of the sexagesimal number; 1 for positive and -1 for negative. units : {"degrees", "hours"} The units of the sexagesimal number. This is infered from the characters present in the string. If it a pure number then units is "degrees". Examples -------- >>> phmsdms("12") == { ... 'parts': [12.0, None, None], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 0.0, 0.0] ... } True >>> phmsdms("12h") == { ... 'parts': [12.0, None, None], ... 'sign': 1, ... 'units': 'hours', ... 'vals': [12.0, 0.0, 0.0] ... } True >>> phmsdms("12d13m14.56") == { ... 'parts': [12.0, 13.0, 14.56], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 13.0, 14.56] ... } True >>> phmsdms("12d13m14.56") == { ... 'parts': [12.0, 13.0, 14.56], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 13.0, 14.56] ... } True >>> phmsdms("12d14.56ss") == { ... 'parts': [12.0, None, 14.56], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 0.0, 14.56] ... } True >>> phmsdms("14.56ss") == { ... 'parts': [None, None, 14.56], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [0.0, 0.0, 14.56] ... } True >>> phmsdms("12h13m12.4s") == { ... 'parts': [12.0, 13.0, 12.4], ... 'sign': 1, ... 'units': 'hours', ... 'vals': [12.0, 13.0, 12.4] ... } True >>> phmsdms("12:13:12.4s") == { ... 'parts': [12.0, 13.0, 12.4], ... 'sign': 1, ... 'units': 'degrees', ... 'vals': [12.0, 13.0, 12.4] ... } True But `phmsdms("12:13mm:12.4s")` will not work.
[ "Parse", "a", "string", "containing", "a", "sexagesimal", "number", "." ]
5c30ed7c3a7412177daaed180bf3b2351b287589
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L554-L746
train
phn/angles
angles.py
pposition
def pposition(hd, details=False): """Parse string into angular position. A string containing 2 or 6 numbers is parsed, and the numbers are converted into decimal numbers. In the former case the numbers are assumed to be floats. In the latter case, the numbers are assumed to be sexagesimal. Parameters ---------- hd: str String containing 2 or 6 numbers. The numbers can be spearated with character or characters other than ".", "-", "+". The string must contain either 2 or 6 numbers. details: bool The detailed result from parsing the string is returned. See "Returns" section below. Default is False. Returns ------- x: (float, float) or dict A tuple containing decimal equivalents of the parsed numbers. If the string contains 6 numbers then they are assumed be sexagesimal components. If ``details`` is True then a dictionary with the following keys is returned: x: float The first number. y: float The second number numvals: int Number of items parsed; 2 or 6. raw_x: dict The result returned by ``phmsdms`` for the first number. raw_y: dict The result returned by ``phmsdms`` for the second number. It is up to the user to interpret the units of the numbers returned. Raises ------ ValueError: The exception is raised if the string cannot be interpreted as a sequence of 2 or 6 numbers. Examples -------- The position of M100 reported by SIMBAD is "12 22 54.899 +15 49 20.57". This can be easily parsed in the following manner. >>> from angles import pposition >>> ra, de = pposition("12 22 54.899 +15 49 20.57") >>> ra 12.38191638888889 >>> de 15.822380555555556 """ # :TODO: split two angles based on user entered separator and process each part separately. # Split at any character other than a digit, ".", "-", and "+". p = re.split(r"[^\d\-+.]*", hd) if len(p) not in [2, 6]: raise ValueError("Input must contain either 2 or 6 numbers.") # Two floating point numbers if string has 2 numbers. if len(p) == 2: x, y = float(p[0]), float(p[1]) if details: numvals = 2 raw_x = p[0] raw_y = p[1] # Two sexagesimal numbers if string has 6 numbers. elif len(p) == 6: x_p = phmsdms(" ".join(p[:3])) x = sexa2deci(x_p['sign'], *x_p['vals']) y_p = phmsdms(" ".join(p[3:])) y = sexa2deci(y_p['sign'], *y_p['vals']) if details: raw_x = x_p raw_y = y_p numvals = 6 if details: result = dict(x=x, y=y, numvals=numvals, raw_x=raw_x, raw_y=raw_y) else: result = x, y return result
python
def pposition(hd, details=False): """Parse string into angular position. A string containing 2 or 6 numbers is parsed, and the numbers are converted into decimal numbers. In the former case the numbers are assumed to be floats. In the latter case, the numbers are assumed to be sexagesimal. Parameters ---------- hd: str String containing 2 or 6 numbers. The numbers can be spearated with character or characters other than ".", "-", "+". The string must contain either 2 or 6 numbers. details: bool The detailed result from parsing the string is returned. See "Returns" section below. Default is False. Returns ------- x: (float, float) or dict A tuple containing decimal equivalents of the parsed numbers. If the string contains 6 numbers then they are assumed be sexagesimal components. If ``details`` is True then a dictionary with the following keys is returned: x: float The first number. y: float The second number numvals: int Number of items parsed; 2 or 6. raw_x: dict The result returned by ``phmsdms`` for the first number. raw_y: dict The result returned by ``phmsdms`` for the second number. It is up to the user to interpret the units of the numbers returned. Raises ------ ValueError: The exception is raised if the string cannot be interpreted as a sequence of 2 or 6 numbers. Examples -------- The position of M100 reported by SIMBAD is "12 22 54.899 +15 49 20.57". This can be easily parsed in the following manner. >>> from angles import pposition >>> ra, de = pposition("12 22 54.899 +15 49 20.57") >>> ra 12.38191638888889 >>> de 15.822380555555556 """ # :TODO: split two angles based on user entered separator and process each part separately. # Split at any character other than a digit, ".", "-", and "+". p = re.split(r"[^\d\-+.]*", hd) if len(p) not in [2, 6]: raise ValueError("Input must contain either 2 or 6 numbers.") # Two floating point numbers if string has 2 numbers. if len(p) == 2: x, y = float(p[0]), float(p[1]) if details: numvals = 2 raw_x = p[0] raw_y = p[1] # Two sexagesimal numbers if string has 6 numbers. elif len(p) == 6: x_p = phmsdms(" ".join(p[:3])) x = sexa2deci(x_p['sign'], *x_p['vals']) y_p = phmsdms(" ".join(p[3:])) y = sexa2deci(y_p['sign'], *y_p['vals']) if details: raw_x = x_p raw_y = y_p numvals = 6 if details: result = dict(x=x, y=y, numvals=numvals, raw_x=raw_x, raw_y=raw_y) else: result = x, y return result
[ "def", "pposition", "(", "hd", ",", "details", "=", "False", ")", ":", "# :TODO: split two angles based on user entered separator and process each part separately.", "# Split at any character other than a digit, \".\", \"-\", and \"+\".", "p", "=", "re", ".", "split", "(", "r\"[^\\d\\-+.]*\"", ",", "hd", ")", "if", "len", "(", "p", ")", "not", "in", "[", "2", ",", "6", "]", ":", "raise", "ValueError", "(", "\"Input must contain either 2 or 6 numbers.\"", ")", "# Two floating point numbers if string has 2 numbers.", "if", "len", "(", "p", ")", "==", "2", ":", "x", ",", "y", "=", "float", "(", "p", "[", "0", "]", ")", ",", "float", "(", "p", "[", "1", "]", ")", "if", "details", ":", "numvals", "=", "2", "raw_x", "=", "p", "[", "0", "]", "raw_y", "=", "p", "[", "1", "]", "# Two sexagesimal numbers if string has 6 numbers.", "elif", "len", "(", "p", ")", "==", "6", ":", "x_p", "=", "phmsdms", "(", "\" \"", ".", "join", "(", "p", "[", ":", "3", "]", ")", ")", "x", "=", "sexa2deci", "(", "x_p", "[", "'sign'", "]", ",", "*", "x_p", "[", "'vals'", "]", ")", "y_p", "=", "phmsdms", "(", "\" \"", ".", "join", "(", "p", "[", "3", ":", "]", ")", ")", "y", "=", "sexa2deci", "(", "y_p", "[", "'sign'", "]", ",", "*", "y_p", "[", "'vals'", "]", ")", "if", "details", ":", "raw_x", "=", "x_p", "raw_y", "=", "y_p", "numvals", "=", "6", "if", "details", ":", "result", "=", "dict", "(", "x", "=", "x", ",", "y", "=", "y", ",", "numvals", "=", "numvals", ",", "raw_x", "=", "raw_x", ",", "raw_y", "=", "raw_y", ")", "else", ":", "result", "=", "x", ",", "y", "return", "result" ]
Parse string into angular position. A string containing 2 or 6 numbers is parsed, and the numbers are converted into decimal numbers. In the former case the numbers are assumed to be floats. In the latter case, the numbers are assumed to be sexagesimal. Parameters ---------- hd: str String containing 2 or 6 numbers. The numbers can be spearated with character or characters other than ".", "-", "+". The string must contain either 2 or 6 numbers. details: bool The detailed result from parsing the string is returned. See "Returns" section below. Default is False. Returns ------- x: (float, float) or dict A tuple containing decimal equivalents of the parsed numbers. If the string contains 6 numbers then they are assumed be sexagesimal components. If ``details`` is True then a dictionary with the following keys is returned: x: float The first number. y: float The second number numvals: int Number of items parsed; 2 or 6. raw_x: dict The result returned by ``phmsdms`` for the first number. raw_y: dict The result returned by ``phmsdms`` for the second number. It is up to the user to interpret the units of the numbers returned. Raises ------ ValueError: The exception is raised if the string cannot be interpreted as a sequence of 2 or 6 numbers. Examples -------- The position of M100 reported by SIMBAD is "12 22 54.899 +15 49 20.57". This can be easily parsed in the following manner. >>> from angles import pposition >>> ra, de = pposition("12 22 54.899 +15 49 20.57") >>> ra 12.38191638888889 >>> de 15.822380555555556
[ "Parse", "string", "into", "angular", "position", "." ]
5c30ed7c3a7412177daaed180bf3b2351b287589
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L749-L845
train
phn/angles
angles.py
sep
def sep(a1, b1, a2, b2): """Angular spearation between two points on a unit sphere. This will be an angle between [0, π] radians. Parameters ---------- a1, b1 : float Longitude-like and latitude-like angles defining the first point. Both are in radians. a2, b2 : float Longitude-like and latitude-like angles defining the second point. Both are in radians. Notes ----- The great cicle angular separation of the second point from the first is returned as an angle in radians. the return value is always in the range [0, π]. Results agree with those from SLALIB routine sla_dsep. See test_sep_against_slalib_dsep() in test_angles.py. Examples -------- >>> r2d(sep(0, 0, 0, d2r(90.0))) 90.0 >>> r2d(sep(0, d2r(45.0), 0, d2r(90.0))) 45.00000000000001 >>> r2d(sep(0, d2r(-45.0), 0, d2r(90.0))) 135.0 >>> r2d(sep(0, d2r(-90.0), 0, d2r(90.0))) 180.0 >>> r2d(sep(d2r(45.0), d2r(-90.0), d2r(45.0), d2r(90.0))) 180.0 >>> r2d(sep(0, 0, d2r(90.0), 0)) 90.0 >>> r2d(sep(0, d2r(45.0), d2r(90.0), d2r(45.0))) 60.00000000000001 >>> import math >>> 90.0 * math.cos(d2r(45.0)) # Distance along latitude circle. 63.63961030678928 """ # Tolerance to decide if the calculated separation is zero. tol = 1e-15 v = CartesianVector.from_spherical(1.0, a1, b1) v2 = CartesianVector.from_spherical(1.0, a2, b2) d = v.dot(v2) c = v.cross(v2).mod res = math.atan2(c, d) if abs(res) < tol: return 0.0 else: return res
python
def sep(a1, b1, a2, b2): """Angular spearation between two points on a unit sphere. This will be an angle between [0, π] radians. Parameters ---------- a1, b1 : float Longitude-like and latitude-like angles defining the first point. Both are in radians. a2, b2 : float Longitude-like and latitude-like angles defining the second point. Both are in radians. Notes ----- The great cicle angular separation of the second point from the first is returned as an angle in radians. the return value is always in the range [0, π]. Results agree with those from SLALIB routine sla_dsep. See test_sep_against_slalib_dsep() in test_angles.py. Examples -------- >>> r2d(sep(0, 0, 0, d2r(90.0))) 90.0 >>> r2d(sep(0, d2r(45.0), 0, d2r(90.0))) 45.00000000000001 >>> r2d(sep(0, d2r(-45.0), 0, d2r(90.0))) 135.0 >>> r2d(sep(0, d2r(-90.0), 0, d2r(90.0))) 180.0 >>> r2d(sep(d2r(45.0), d2r(-90.0), d2r(45.0), d2r(90.0))) 180.0 >>> r2d(sep(0, 0, d2r(90.0), 0)) 90.0 >>> r2d(sep(0, d2r(45.0), d2r(90.0), d2r(45.0))) 60.00000000000001 >>> import math >>> 90.0 * math.cos(d2r(45.0)) # Distance along latitude circle. 63.63961030678928 """ # Tolerance to decide if the calculated separation is zero. tol = 1e-15 v = CartesianVector.from_spherical(1.0, a1, b1) v2 = CartesianVector.from_spherical(1.0, a2, b2) d = v.dot(v2) c = v.cross(v2).mod res = math.atan2(c, d) if abs(res) < tol: return 0.0 else: return res
[ "def", "sep", "(", "a1", ",", "b1", ",", "a2", ",", "b2", ")", ":", "# Tolerance to decide if the calculated separation is zero.", "tol", "=", "1e-15", "v", "=", "CartesianVector", ".", "from_spherical", "(", "1.0", ",", "a1", ",", "b1", ")", "v2", "=", "CartesianVector", ".", "from_spherical", "(", "1.0", ",", "a2", ",", "b2", ")", "d", "=", "v", ".", "dot", "(", "v2", ")", "c", "=", "v", ".", "cross", "(", "v2", ")", ".", "mod", "res", "=", "math", ".", "atan2", "(", "c", ",", "d", ")", "if", "abs", "(", "res", ")", "<", "tol", ":", "return", "0.0", "else", ":", "return", "res" ]
Angular spearation between two points on a unit sphere. This will be an angle between [0, π] radians. Parameters ---------- a1, b1 : float Longitude-like and latitude-like angles defining the first point. Both are in radians. a2, b2 : float Longitude-like and latitude-like angles defining the second point. Both are in radians. Notes ----- The great cicle angular separation of the second point from the first is returned as an angle in radians. the return value is always in the range [0, π]. Results agree with those from SLALIB routine sla_dsep. See test_sep_against_slalib_dsep() in test_angles.py. Examples -------- >>> r2d(sep(0, 0, 0, d2r(90.0))) 90.0 >>> r2d(sep(0, d2r(45.0), 0, d2r(90.0))) 45.00000000000001 >>> r2d(sep(0, d2r(-45.0), 0, d2r(90.0))) 135.0 >>> r2d(sep(0, d2r(-90.0), 0, d2r(90.0))) 180.0 >>> r2d(sep(d2r(45.0), d2r(-90.0), d2r(45.0), d2r(90.0))) 180.0 >>> r2d(sep(0, 0, d2r(90.0), 0)) 90.0 >>> r2d(sep(0, d2r(45.0), d2r(90.0), d2r(45.0))) 60.00000000000001 >>> import math >>> 90.0 * math.cos(d2r(45.0)) # Distance along latitude circle. 63.63961030678928
[ "Angular", "spearation", "between", "two", "points", "on", "a", "unit", "sphere", "." ]
5c30ed7c3a7412177daaed180bf3b2351b287589
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L848-L908
train
phn/angles
angles.py
normalize_sphere
def normalize_sphere(alpha, delta): """Normalize angles of a point on a sphere. Parameters ---------- alpha: float The alpha (right ascension/longitude like) angle in degrees. delta: float The delta (declination/latitude like) angle in degrees. Returns ------- (alpha, delta): (float, float) Normalized alpha (degrees) and delta (degrees). Notes ----- This function converts given position on a sphere into the simplest normalized values, considering that the points are on a sphere. Input position Output position (180, 91) (0, 89) (180, -91) (0, -89) (0, 91) (180, 89) (0, -91) (180, -89) (120, 280) (120, -80) (h2d(25), 45) (225, 45) (h2d(-25), -45) (345, -45) """ v = CartesianVector.from_spherical(r=1.0, alpha=d2r(alpha), delta=d2r(delta)) angles = v.normalized_angles return r2d(angles[0]), r2d(angles[1])
python
def normalize_sphere(alpha, delta): """Normalize angles of a point on a sphere. Parameters ---------- alpha: float The alpha (right ascension/longitude like) angle in degrees. delta: float The delta (declination/latitude like) angle in degrees. Returns ------- (alpha, delta): (float, float) Normalized alpha (degrees) and delta (degrees). Notes ----- This function converts given position on a sphere into the simplest normalized values, considering that the points are on a sphere. Input position Output position (180, 91) (0, 89) (180, -91) (0, -89) (0, 91) (180, 89) (0, -91) (180, -89) (120, 280) (120, -80) (h2d(25), 45) (225, 45) (h2d(-25), -45) (345, -45) """ v = CartesianVector.from_spherical(r=1.0, alpha=d2r(alpha), delta=d2r(delta)) angles = v.normalized_angles return r2d(angles[0]), r2d(angles[1])
[ "def", "normalize_sphere", "(", "alpha", ",", "delta", ")", ":", "v", "=", "CartesianVector", ".", "from_spherical", "(", "r", "=", "1.0", ",", "alpha", "=", "d2r", "(", "alpha", ")", ",", "delta", "=", "d2r", "(", "delta", ")", ")", "angles", "=", "v", ".", "normalized_angles", "return", "r2d", "(", "angles", "[", "0", "]", ")", ",", "r2d", "(", "angles", "[", "1", "]", ")" ]
Normalize angles of a point on a sphere. Parameters ---------- alpha: float The alpha (right ascension/longitude like) angle in degrees. delta: float The delta (declination/latitude like) angle in degrees. Returns ------- (alpha, delta): (float, float) Normalized alpha (degrees) and delta (degrees). Notes ----- This function converts given position on a sphere into the simplest normalized values, considering that the points are on a sphere. Input position Output position (180, 91) (0, 89) (180, -91) (0, -89) (0, 91) (180, 89) (0, -91) (180, -89) (120, 280) (120, -80) (h2d(25), 45) (225, 45) (h2d(-25), -45) (345, -45)
[ "Normalize", "angles", "of", "a", "point", "on", "a", "sphere", "." ]
5c30ed7c3a7412177daaed180bf3b2351b287589
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L1969-L2003
train
phn/angles
angles.py
CartesianVector.from_spherical
def from_spherical(cls, r=1.0, alpha=0.0, delta=0.0): """Construct Cartesian vector from spherical coordinates. alpha and delta must be in radians. """ x = r * math.cos(delta) * math.cos(alpha) y = r * math.cos(delta) * math.sin(alpha) z = r * math.sin(delta) return cls(x=x, y=y, z=z)
python
def from_spherical(cls, r=1.0, alpha=0.0, delta=0.0): """Construct Cartesian vector from spherical coordinates. alpha and delta must be in radians. """ x = r * math.cos(delta) * math.cos(alpha) y = r * math.cos(delta) * math.sin(alpha) z = r * math.sin(delta) return cls(x=x, y=y, z=z)
[ "def", "from_spherical", "(", "cls", ",", "r", "=", "1.0", ",", "alpha", "=", "0.0", ",", "delta", "=", "0.0", ")", ":", "x", "=", "r", "*", "math", ".", "cos", "(", "delta", ")", "*", "math", ".", "cos", "(", "alpha", ")", "y", "=", "r", "*", "math", ".", "cos", "(", "delta", ")", "*", "math", ".", "sin", "(", "alpha", ")", "z", "=", "r", "*", "math", ".", "sin", "(", "delta", ")", "return", "cls", "(", "x", "=", "x", ",", "y", "=", "y", ",", "z", "=", "z", ")" ]
Construct Cartesian vector from spherical coordinates. alpha and delta must be in radians.
[ "Construct", "Cartesian", "vector", "from", "spherical", "coordinates", "." ]
5c30ed7c3a7412177daaed180bf3b2351b287589
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L1908-L1916
train
phn/angles
angles.py
CartesianVector.cross
def cross(self, v): """Cross product of two vectors. Parameters ---------- v : CartesianVector The vector to take cross product with. Returns ------- v : CartesianVector Cross product of this vector and the given vector. """ n = self.__class__() n.x = self.y * v.z - self.z * v.y n.y = - (self.x * v.z - self.z * v.x) n.z = self.x * v.y - self.y * v.x return n
python
def cross(self, v): """Cross product of two vectors. Parameters ---------- v : CartesianVector The vector to take cross product with. Returns ------- v : CartesianVector Cross product of this vector and the given vector. """ n = self.__class__() n.x = self.y * v.z - self.z * v.y n.y = - (self.x * v.z - self.z * v.x) n.z = self.x * v.y - self.y * v.x return n
[ "def", "cross", "(", "self", ",", "v", ")", ":", "n", "=", "self", ".", "__class__", "(", ")", "n", ".", "x", "=", "self", ".", "y", "*", "v", ".", "z", "-", "self", ".", "z", "*", "v", ".", "y", "n", ".", "y", "=", "-", "(", "self", ".", "x", "*", "v", ".", "z", "-", "self", ".", "z", "*", "v", ".", "x", ")", "n", ".", "z", "=", "self", ".", "x", "*", "v", ".", "y", "-", "self", ".", "y", "*", "v", ".", "x", "return", "n" ]
Cross product of two vectors. Parameters ---------- v : CartesianVector The vector to take cross product with. Returns ------- v : CartesianVector Cross product of this vector and the given vector.
[ "Cross", "product", "of", "two", "vectors", "." ]
5c30ed7c3a7412177daaed180bf3b2351b287589
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L1921-L1940
train
phn/angles
angles.py
CartesianVector.mod
def mod(self): """Modulus of vector.""" return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
python
def mod(self): """Modulus of vector.""" return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
[ "def", "mod", "(", "self", ")", ":", "return", "math", ".", "sqrt", "(", "self", ".", "x", "**", "2", "+", "self", ".", "y", "**", "2", "+", "self", ".", "z", "**", "2", ")" ]
Modulus of vector.
[ "Modulus", "of", "vector", "." ]
5c30ed7c3a7412177daaed180bf3b2351b287589
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L1943-L1945
train
phn/angles
angles.py
AngularPosition.sep
def sep(self, p): """Angular spearation between objects in radians. Parameters ---------- p : AngularPosition The object to which the separation from the current object is to be calculated. Notes ----- This method calls the function sep(). See its docstring for details. See also -------- sep """ return sep(self.alpha.r, self.delta.r, p.alpha.r, p.delta.r)
python
def sep(self, p): """Angular spearation between objects in radians. Parameters ---------- p : AngularPosition The object to which the separation from the current object is to be calculated. Notes ----- This method calls the function sep(). See its docstring for details. See also -------- sep """ return sep(self.alpha.r, self.delta.r, p.alpha.r, p.delta.r)
[ "def", "sep", "(", "self", ",", "p", ")", ":", "return", "sep", "(", "self", ".", "alpha", ".", "r", ",", "self", ".", "delta", ".", "r", ",", "p", ".", "alpha", ".", "r", ",", "p", ".", "delta", ".", "r", ")" ]
Angular spearation between objects in radians. Parameters ---------- p : AngularPosition The object to which the separation from the current object is to be calculated. Notes ----- This method calls the function sep(). See its docstring for details. See also -------- sep
[ "Angular", "spearation", "between", "objects", "in", "radians", "." ]
5c30ed7c3a7412177daaed180bf3b2351b287589
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L2194-L2213
train
phn/angles
angles.py
AngularPosition.bear
def bear(self, p): """Find position angle between objects, in radians. Parameters ---------- p : AngularPosition The object to which bearing must be determined. Notes ----- This method calls the function bear(). See its docstring for details. See also -------- bear """ return bear(self.alpha.r, self.delta.r, p.alpha.r, p.delta.r)
python
def bear(self, p): """Find position angle between objects, in radians. Parameters ---------- p : AngularPosition The object to which bearing must be determined. Notes ----- This method calls the function bear(). See its docstring for details. See also -------- bear """ return bear(self.alpha.r, self.delta.r, p.alpha.r, p.delta.r)
[ "def", "bear", "(", "self", ",", "p", ")", ":", "return", "bear", "(", "self", ".", "alpha", ".", "r", ",", "self", ".", "delta", ".", "r", ",", "p", ".", "alpha", ".", "r", ",", "p", ".", "delta", ".", "r", ")" ]
Find position angle between objects, in radians. Parameters ---------- p : AngularPosition The object to which bearing must be determined. Notes ----- This method calls the function bear(). See its docstring for details. See also -------- bear
[ "Find", "position", "angle", "between", "objects", "in", "radians", "." ]
5c30ed7c3a7412177daaed180bf3b2351b287589
https://github.com/phn/angles/blob/5c30ed7c3a7412177daaed180bf3b2351b287589/angles.py#L2215-L2233
train
cltl/KafNafParserPy
KafNafParserPy/chunk_data.py
Cchunks.get_chunk
def get_chunk(self, chunk_id): """ Returns the chunk object for the supplied identifier @type chunk_id: string @param chunk_id: chunk identifier """ if chunk_id in self.idx: return Cchunk(self.idx[chunk_id], self.type) else: return None
python
def get_chunk(self, chunk_id): """ Returns the chunk object for the supplied identifier @type chunk_id: string @param chunk_id: chunk identifier """ if chunk_id in self.idx: return Cchunk(self.idx[chunk_id], self.type) else: return None
[ "def", "get_chunk", "(", "self", ",", "chunk_id", ")", ":", "if", "chunk_id", "in", "self", ".", "idx", ":", "return", "Cchunk", "(", "self", ".", "idx", "[", "chunk_id", "]", ",", "self", ".", "type", ")", "else", ":", "return", "None" ]
Returns the chunk object for the supplied identifier @type chunk_id: string @param chunk_id: chunk identifier
[ "Returns", "the", "chunk", "object", "for", "the", "supplied", "identifier" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/chunk_data.py#L191-L200
train
cltl/KafNafParserPy
KafNafParserPy/chunk_data.py
Cchunks.add_chunk
def add_chunk(self, chunk_obj): """ Adds a chunk object to the layer @type chunk_obj: L{Cchunk} @param chunk_obj: the chunk object """ if chunk_obj.get_id() in self.idx: raise ValueError("Chunk with id {} already exists!" .format(chunk_obj.get_id())) self.node.append(chunk_obj.get_node()) self.idx[chunk_obj.get_id()] = chunk_obj
python
def add_chunk(self, chunk_obj): """ Adds a chunk object to the layer @type chunk_obj: L{Cchunk} @param chunk_obj: the chunk object """ if chunk_obj.get_id() in self.idx: raise ValueError("Chunk with id {} already exists!" .format(chunk_obj.get_id())) self.node.append(chunk_obj.get_node()) self.idx[chunk_obj.get_id()] = chunk_obj
[ "def", "add_chunk", "(", "self", ",", "chunk_obj", ")", ":", "if", "chunk_obj", ".", "get_id", "(", ")", "in", "self", ".", "idx", ":", "raise", "ValueError", "(", "\"Chunk with id {} already exists!\"", ".", "format", "(", "chunk_obj", ".", "get_id", "(", ")", ")", ")", "self", ".", "node", ".", "append", "(", "chunk_obj", ".", "get_node", "(", ")", ")", "self", ".", "idx", "[", "chunk_obj", ".", "get_id", "(", ")", "]", "=", "chunk_obj" ]
Adds a chunk object to the layer @type chunk_obj: L{Cchunk} @param chunk_obj: the chunk object
[ "Adds", "a", "chunk", "object", "to", "the", "layer" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/chunk_data.py#L202-L212
train
thombashi/DataProperty
examples/py/to_column_dp_list.py
display_col_dp
def display_col_dp(dp_list, attr_name): """ show a value assocciated with an attribute for each DataProperty instance in the dp_list """ print() print("---------- {:s} ----------".format(attr_name)) print([getattr(dp, attr_name) for dp in dp_list])
python
def display_col_dp(dp_list, attr_name): """ show a value assocciated with an attribute for each DataProperty instance in the dp_list """ print() print("---------- {:s} ----------".format(attr_name)) print([getattr(dp, attr_name) for dp in dp_list])
[ "def", "display_col_dp", "(", "dp_list", ",", "attr_name", ")", ":", "print", "(", ")", "print", "(", "\"---------- {:s} ----------\"", ".", "format", "(", "attr_name", ")", ")", "print", "(", "[", "getattr", "(", "dp", ",", "attr_name", ")", "for", "dp", "in", "dp_list", "]", ")" ]
show a value assocciated with an attribute for each DataProperty instance in the dp_list
[ "show", "a", "value", "assocciated", "with", "an", "attribute", "for", "each", "DataProperty", "instance", "in", "the", "dp_list" ]
1d1a4c6abee87264c2f870a932c0194895d80a18
https://github.com/thombashi/DataProperty/blob/1d1a4c6abee87264c2f870a932c0194895d80a18/examples/py/to_column_dp_list.py#L16-L24
train
MacHu-GWU/macro-project
macro/bot.py
Bot.delay
def delay(self, dl=0): """Delay for ``dl`` seconds. """ if dl is None: time.sleep(self.dl) elif dl < 0: sys.stderr.write( "delay cannot less than zero, this takes no effects.\n") else: time.sleep(dl)
python
def delay(self, dl=0): """Delay for ``dl`` seconds. """ if dl is None: time.sleep(self.dl) elif dl < 0: sys.stderr.write( "delay cannot less than zero, this takes no effects.\n") else: time.sleep(dl)
[ "def", "delay", "(", "self", ",", "dl", "=", "0", ")", ":", "if", "dl", "is", "None", ":", "time", ".", "sleep", "(", "self", ".", "dl", ")", "elif", "dl", "<", "0", ":", "sys", ".", "stderr", ".", "write", "(", "\"delay cannot less than zero, this takes no effects.\\n\"", ")", "else", ":", "time", ".", "sleep", "(", "dl", ")" ]
Delay for ``dl`` seconds.
[ "Delay", "for", "dl", "seconds", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L134-L143
train
MacHu-GWU/macro-project
macro/bot.py
Bot.scroll_up
def scroll_up(self, n, pre_dl=None, post_dl=None): """Scroll up ``n`` times. **中文文档** 鼠标滚轮向上滚动n次。 """ self.delay(pre_dl) self.m.scroll(vertical=n) self.delay(post_dl)
python
def scroll_up(self, n, pre_dl=None, post_dl=None): """Scroll up ``n`` times. **中文文档** 鼠标滚轮向上滚动n次。 """ self.delay(pre_dl) self.m.scroll(vertical=n) self.delay(post_dl)
[ "def", "scroll_up", "(", "self", ",", "n", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "m", ".", "scroll", "(", "vertical", "=", "n", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Scroll up ``n`` times. **中文文档** 鼠标滚轮向上滚动n次。
[ "Scroll", "up", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L203-L212
train
MacHu-GWU/macro-project
macro/bot.py
Bot.scroll_right
def scroll_right(self, n, pre_dl=None, post_dl=None): """Scroll right ``n`` times. **中文文档** 鼠标滚轮向右滚动n次(如果可能的话)。 """ self.delay(pre_dl) self.m.scroll(horizontal=n) self.delay(post_dl)
python
def scroll_right(self, n, pre_dl=None, post_dl=None): """Scroll right ``n`` times. **中文文档** 鼠标滚轮向右滚动n次(如果可能的话)。 """ self.delay(pre_dl) self.m.scroll(horizontal=n) self.delay(post_dl)
[ "def", "scroll_right", "(", "self", ",", "n", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "m", ".", "scroll", "(", "horizontal", "=", "n", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Scroll right ``n`` times. **中文文档** 鼠标滚轮向右滚动n次(如果可能的话)。
[ "Scroll", "right", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L225-L234
train
MacHu-GWU/macro-project
macro/bot.py
Bot.tap_key
def tap_key(self, key_name, n=1, interval=0, pre_dl=None, post_dl=None): """Tap a key on keyboard for ``n`` times, with ``interval`` seconds of interval. Key is declared by it's name Example:: bot.tap_key("a") bot.tap_key(1) bot.tap_key("up") bot.tap_key("space") bot.tap_key("enter") bot.tap_key("tab") **中文文档** 以 ``interval`` 中定义的频率按下某个按键 ``n`` 次。接受按键名作为输入。 """ key = self._parse_key(key_name) self.delay(pre_dl) self.k.tap_key(key, n, interval) self.delay(post_dl)
python
def tap_key(self, key_name, n=1, interval=0, pre_dl=None, post_dl=None): """Tap a key on keyboard for ``n`` times, with ``interval`` seconds of interval. Key is declared by it's name Example:: bot.tap_key("a") bot.tap_key(1) bot.tap_key("up") bot.tap_key("space") bot.tap_key("enter") bot.tap_key("tab") **中文文档** 以 ``interval`` 中定义的频率按下某个按键 ``n`` 次。接受按键名作为输入。 """ key = self._parse_key(key_name) self.delay(pre_dl) self.k.tap_key(key, n, interval) self.delay(post_dl)
[ "def", "tap_key", "(", "self", ",", "key_name", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "key", "=", "self", ".", "_parse_key", "(", "key_name", ")", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "key", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Tap a key on keyboard for ``n`` times, with ``interval`` seconds of interval. Key is declared by it's name Example:: bot.tap_key("a") bot.tap_key(1) bot.tap_key("up") bot.tap_key("space") bot.tap_key("enter") bot.tap_key("tab") **中文文档** 以 ``interval`` 中定义的频率按下某个按键 ``n`` 次。接受按键名作为输入。
[ "Tap", "a", "key", "on", "keyboard", "for", "n", "times", "with", "interval", "seconds", "of", "interval", ".", "Key", "is", "declared", "by", "it", "s", "name" ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L273-L293
train
MacHu-GWU/macro-project
macro/bot.py
Bot.enter
def enter(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press enter key n times. **中文文档** 按回车键/换行键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.enter_key, n, interval) self.delay(post_dl)
python
def enter(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press enter key n times. **中文文档** 按回车键/换行键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.enter_key, n, interval) self.delay(post_dl)
[ "def", "enter", "(", "self", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "enter_key", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press enter key n times. **中文文档** 按回车键/换行键 n 次。
[ "Press", "enter", "key", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L295-L304
train
MacHu-GWU/macro-project
macro/bot.py
Bot.backspace
def backspace(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press backspace key n times. **中文文档** 按退格键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.backspace_key, n, interval) self.delay(post_dl)
python
def backspace(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press backspace key n times. **中文文档** 按退格键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.backspace_key, n, interval) self.delay(post_dl)
[ "def", "backspace", "(", "self", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "backspace_key", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press backspace key n times. **中文文档** 按退格键 n 次。
[ "Press", "backspace", "key", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L306-L315
train
MacHu-GWU/macro-project
macro/bot.py
Bot.space
def space(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press white space key n times. **中文文档** 按空格键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.space_key, n) self.delay(post_dl)
python
def space(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press white space key n times. **中文文档** 按空格键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.space_key, n) self.delay(post_dl)
[ "def", "space", "(", "self", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "space_key", ",", "n", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press white space key n times. **中文文档** 按空格键 n 次。
[ "Press", "white", "space", "key", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L317-L326
train
MacHu-GWU/macro-project
macro/bot.py
Bot.fn
def fn(self, i, n=1, interval=0, pre_dl=None, post_dl=None): """Press Fn key n times. **中文文档** 按 Fn 功能键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.function_keys[i], n, interval) self.delay(post_dl)
python
def fn(self, i, n=1, interval=0, pre_dl=None, post_dl=None): """Press Fn key n times. **中文文档** 按 Fn 功能键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.function_keys[i], n, interval) self.delay(post_dl)
[ "def", "fn", "(", "self", ",", "i", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "function_keys", "[", "i", "]", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press Fn key n times. **中文文档** 按 Fn 功能键 n 次。
[ "Press", "Fn", "key", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L328-L337
train
MacHu-GWU/macro-project
macro/bot.py
Bot.tab
def tab(self, n=1, interval=0, pre_dl=None, post_dl=None): """Tap ``tab`` key for ``n`` times, with ``interval`` seconds of interval. **中文文档** 以 ``interval`` 中定义的频率按下某个tab键 ``n`` 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.tab_key, n, interval) self.delay(post_dl)
python
def tab(self, n=1, interval=0, pre_dl=None, post_dl=None): """Tap ``tab`` key for ``n`` times, with ``interval`` seconds of interval. **中文文档** 以 ``interval`` 中定义的频率按下某个tab键 ``n`` 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.tab_key, n, interval) self.delay(post_dl)
[ "def", "tab", "(", "self", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "tab_key", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Tap ``tab`` key for ``n`` times, with ``interval`` seconds of interval. **中文文档** 以 ``interval`` 中定义的频率按下某个tab键 ``n`` 次。
[ "Tap", "tab", "key", "for", "n", "times", "with", "interval", "seconds", "of", "interval", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L339-L348
train
MacHu-GWU/macro-project
macro/bot.py
Bot.up
def up(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press up key n times. **中文文档** 按上方向键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.up_key, n, interval) self.delay(post_dl)
python
def up(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press up key n times. **中文文档** 按上方向键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.up_key, n, interval) self.delay(post_dl)
[ "def", "up", "(", "self", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "up_key", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press up key n times. **中文文档** 按上方向键 n 次。
[ "Press", "up", "key", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L350-L359
train
MacHu-GWU/macro-project
macro/bot.py
Bot.down
def down(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press down key n times. **中文文档** 按下方向键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.down_key, n, interval) self.delay(post_dl)
python
def down(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press down key n times. **中文文档** 按下方向键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.down_key, n, interval) self.delay(post_dl)
[ "def", "down", "(", "self", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "down_key", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press down key n times. **中文文档** 按下方向键 n 次。
[ "Press", "down", "key", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L361-L370
train
MacHu-GWU/macro-project
macro/bot.py
Bot.left
def left(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press left key n times **中文文档** 按左方向键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.left_key, n, interval) self.delay(post_dl)
python
def left(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press left key n times **中文文档** 按左方向键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.left_key, n, interval) self.delay(post_dl)
[ "def", "left", "(", "self", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "left_key", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press left key n times **中文文档** 按左方向键 n 次。
[ "Press", "left", "key", "n", "times" ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L372-L381
train
MacHu-GWU/macro-project
macro/bot.py
Bot.right
def right(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press right key n times. **中文文档** 按右方向键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.right_key, n, interval) self.delay(post_dl)
python
def right(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press right key n times. **中文文档** 按右方向键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.right_key, n, interval) self.delay(post_dl)
[ "def", "right", "(", "self", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "right_key", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press right key n times. **中文文档** 按右方向键 n 次。
[ "Press", "right", "key", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L383-L392
train
MacHu-GWU/macro-project
macro/bot.py
Bot.delete
def delete(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres delete key n times. **中文文档** 按 delete 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.delete_key, n, interval) self.delay(post_dl)
python
def delete(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres delete key n times. **中文文档** 按 delete 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.delete_key, n, interval) self.delay(post_dl)
[ "def", "delete", "(", "self", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "delete_key", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Pres delete key n times. **中文文档** 按 delete 键n次。
[ "Pres", "delete", "key", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L394-L403
train
MacHu-GWU/macro-project
macro/bot.py
Bot.insert
def insert(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres insert key n times. **中文文档** 按 insert 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.insert_key, n, interval) self.delay(post_dl)
python
def insert(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres insert key n times. **中文文档** 按 insert 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.insert_key, n, interval) self.delay(post_dl)
[ "def", "insert", "(", "self", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "insert_key", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Pres insert key n times. **中文文档** 按 insert 键n次。
[ "Pres", "insert", "key", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L405-L414
train
MacHu-GWU/macro-project
macro/bot.py
Bot.home
def home(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres home key n times. **中文文档** 按 home 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.home_key, n, interval) self.delay(post_dl)
python
def home(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres home key n times. **中文文档** 按 home 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.home_key, n, interval) self.delay(post_dl)
[ "def", "home", "(", "self", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "home_key", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Pres home key n times. **中文文档** 按 home 键n次。
[ "Pres", "home", "key", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L416-L425
train
MacHu-GWU/macro-project
macro/bot.py
Bot.end
def end(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press end key n times. **中文文档** 按 end 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.end_key, n, interval) self.delay(post_dl)
python
def end(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press end key n times. **中文文档** 按 end 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.end_key, n, interval) self.delay(post_dl)
[ "def", "end", "(", "self", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "end_key", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press end key n times. **中文文档** 按 end 键n次。
[ "Press", "end", "key", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L427-L436
train
MacHu-GWU/macro-project
macro/bot.py
Bot.page_up
def page_up(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres page_up key n times. **中文文档** 按 page_up 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.page_up_key, n, interval) self.delay(post_dl)
python
def page_up(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres page_up key n times. **中文文档** 按 page_up 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.page_up_key, n, interval) self.delay(post_dl)
[ "def", "page_up", "(", "self", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "page_up_key", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Pres page_up key n times. **中文文档** 按 page_up 键n次。
[ "Pres", "page_up", "key", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L438-L447
train
MacHu-GWU/macro-project
macro/bot.py
Bot.page_down
def page_down(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres page_down key n times. **中文文档** 按 page_down 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.page_down, n, interval) self.delay(post_dl)
python
def page_down(self, n=1, interval=0, pre_dl=None, post_dl=None): """Pres page_down key n times. **中文文档** 按 page_down 键n次。 """ self.delay(pre_dl) self.k.tap_key(self.k.page_down, n, interval) self.delay(post_dl)
[ "def", "page_down", "(", "self", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "page_down", ",", "n", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Pres page_down key n times. **中文文档** 按 page_down 键n次。
[ "Pres", "page_down", "key", "n", "times", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L449-L458
train
MacHu-GWU/macro-project
macro/bot.py
Bot.press_and_tap
def press_and_tap(self, press_key, tap_key, n=1, interval=0, pre_dl=None, post_dl=None): """Press combination of two keys, like Ctrl + C, Alt + F4. The second key could be tapped for multiple time. Examples:: bot.press_and_tap("ctrl", "c") bot.press_and_tap("shift", "1") **中文文档** 按下两个键的组合键。 """ press_key = self._parse_key(press_key) tap_key = self._parse_key(tap_key) self.delay(pre_dl) self.k.press_key(press_key) self.k.tap_key(tap_key, n, interval) self.k.release_key(press_key) self.delay(post_dl)
python
def press_and_tap(self, press_key, tap_key, n=1, interval=0, pre_dl=None, post_dl=None): """Press combination of two keys, like Ctrl + C, Alt + F4. The second key could be tapped for multiple time. Examples:: bot.press_and_tap("ctrl", "c") bot.press_and_tap("shift", "1") **中文文档** 按下两个键的组合键。 """ press_key = self._parse_key(press_key) tap_key = self._parse_key(tap_key) self.delay(pre_dl) self.k.press_key(press_key) self.k.tap_key(tap_key, n, interval) self.k.release_key(press_key) self.delay(post_dl)
[ "def", "press_and_tap", "(", "self", ",", "press_key", ",", "tap_key", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "press_key", "=", "self", ".", "_parse_key", "(", "press_key", ")", "tap_key", "=", "self", ".", "_parse_key", "(", "tap_key", ")", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "press_key", "(", "press_key", ")", "self", ".", "k", ".", "tap_key", "(", "tap_key", ",", "n", ",", "interval", ")", "self", ".", "k", ".", "release_key", "(", "press_key", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press combination of two keys, like Ctrl + C, Alt + F4. The second key could be tapped for multiple time. Examples:: bot.press_and_tap("ctrl", "c") bot.press_and_tap("shift", "1") **中文文档** 按下两个键的组合键。
[ "Press", "combination", "of", "two", "keys", "like", "Ctrl", "+", "C", "Alt", "+", "F4", ".", "The", "second", "key", "could", "be", "tapped", "for", "multiple", "time", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L461-L481
train
MacHu-GWU/macro-project
macro/bot.py
Bot.press_two_and_tap
def press_two_and_tap(self, press_key1, press_key2, tap_key, n=1, interval=0, pre_dl=None, post_dl=None): """Press combination of three keys, like Ctrl + Shift + C, The tap key could be tapped for multiple time. Examples:: bot.press_and_tap("ctrl", "shift", "c") **中文文档** 按下三个键的组合键。 """ press_key1 = self._parse_key(press_key1) press_key2 = self._parse_key(press_key2) tap_key = self._parse_key(tap_key) self.delay(pre_dl) self.k.press_key(press_key1) self.k.press_key(press_key2) self.k.tap_key(tap_key, n, interval) self.k.release_key(press_key1) self.k.release_key(press_key2) self.delay(post_dl)
python
def press_two_and_tap(self, press_key1, press_key2, tap_key, n=1, interval=0, pre_dl=None, post_dl=None): """Press combination of three keys, like Ctrl + Shift + C, The tap key could be tapped for multiple time. Examples:: bot.press_and_tap("ctrl", "shift", "c") **中文文档** 按下三个键的组合键。 """ press_key1 = self._parse_key(press_key1) press_key2 = self._parse_key(press_key2) tap_key = self._parse_key(tap_key) self.delay(pre_dl) self.k.press_key(press_key1) self.k.press_key(press_key2) self.k.tap_key(tap_key, n, interval) self.k.release_key(press_key1) self.k.release_key(press_key2) self.delay(post_dl)
[ "def", "press_two_and_tap", "(", "self", ",", "press_key1", ",", "press_key2", ",", "tap_key", ",", "n", "=", "1", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "press_key1", "=", "self", ".", "_parse_key", "(", "press_key1", ")", "press_key2", "=", "self", ".", "_parse_key", "(", "press_key2", ")", "tap_key", "=", "self", ".", "_parse_key", "(", "tap_key", ")", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "press_key", "(", "press_key1", ")", "self", ".", "k", ".", "press_key", "(", "press_key2", ")", "self", ".", "k", ".", "tap_key", "(", "tap_key", ",", "n", ",", "interval", ")", "self", ".", "k", ".", "release_key", "(", "press_key1", ")", "self", ".", "k", ".", "release_key", "(", "press_key2", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press combination of three keys, like Ctrl + Shift + C, The tap key could be tapped for multiple time. Examples:: bot.press_and_tap("ctrl", "shift", "c") **中文文档** 按下三个键的组合键。
[ "Press", "combination", "of", "three", "keys", "like", "Ctrl", "+", "Shift", "+", "C", "The", "tap", "key", "could", "be", "tapped", "for", "multiple", "time", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L483-L506
train
MacHu-GWU/macro-project
macro/bot.py
Bot.ctrl_c
def ctrl_c(self, pre_dl=None, post_dl=None): """Press Ctrl + C, usually for copy. **中文文档** 按下 Ctrl + C 组合键, 通常用于复制。 """ self.delay(pre_dl) self.k.press_key(self.k.control_key) self.k.tap_key("c") self.k.release_key(self.k.control_key) self.delay(post_dl)
python
def ctrl_c(self, pre_dl=None, post_dl=None): """Press Ctrl + C, usually for copy. **中文文档** 按下 Ctrl + C 组合键, 通常用于复制。 """ self.delay(pre_dl) self.k.press_key(self.k.control_key) self.k.tap_key("c") self.k.release_key(self.k.control_key) self.delay(post_dl)
[ "def", "ctrl_c", "(", "self", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "press_key", "(", "self", ".", "k", ".", "control_key", ")", "self", ".", "k", ".", "tap_key", "(", "\"c\"", ")", "self", ".", "k", ".", "release_key", "(", "self", ".", "k", ".", "control_key", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press Ctrl + C, usually for copy. **中文文档** 按下 Ctrl + C 组合键, 通常用于复制。
[ "Press", "Ctrl", "+", "C", "usually", "for", "copy", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L508-L519
train
MacHu-GWU/macro-project
macro/bot.py
Bot.ctrl_fn
def ctrl_fn(self, i, pre_dl=None, post_dl=None): """Press Ctrl + Fn1 ~ 12 once. **中文文档** 按下 Ctrl + Fn1 ~ 12 组合键。 """ self.delay(pre_dl) self.k.press_key(self.k.control_key) self.k.tap_key(self.k.function_keys[i]) self.k.release_key(self.k.control_key) self.delay(post_dl)
python
def ctrl_fn(self, i, pre_dl=None, post_dl=None): """Press Ctrl + Fn1 ~ 12 once. **中文文档** 按下 Ctrl + Fn1 ~ 12 组合键。 """ self.delay(pre_dl) self.k.press_key(self.k.control_key) self.k.tap_key(self.k.function_keys[i]) self.k.release_key(self.k.control_key) self.delay(post_dl)
[ "def", "ctrl_fn", "(", "self", ",", "i", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "press_key", "(", "self", ".", "k", ".", "control_key", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "function_keys", "[", "i", "]", ")", "self", ".", "k", ".", "release_key", "(", "self", ".", "k", ".", "control_key", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press Ctrl + Fn1 ~ 12 once. **中文文档** 按下 Ctrl + Fn1 ~ 12 组合键。
[ "Press", "Ctrl", "+", "Fn1", "~", "12", "once", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L599-L610
train
MacHu-GWU/macro-project
macro/bot.py
Bot.alt_fn
def alt_fn(self, i, pre_dl=None, post_dl=None): """Press Alt + Fn1 ~ 12 once. **中文文档** 按下 Alt + Fn1 ~ 12 组合键。 """ self.delay(pre_dl) self.k.press_key(self.k.alt_key) self.k.tap_key(self.k.function_keys[i]) self.k.release_key(self.k.alt_key) self.delay(post_dl)
python
def alt_fn(self, i, pre_dl=None, post_dl=None): """Press Alt + Fn1 ~ 12 once. **中文文档** 按下 Alt + Fn1 ~ 12 组合键。 """ self.delay(pre_dl) self.k.press_key(self.k.alt_key) self.k.tap_key(self.k.function_keys[i]) self.k.release_key(self.k.alt_key) self.delay(post_dl)
[ "def", "alt_fn", "(", "self", ",", "i", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "press_key", "(", "self", ".", "k", ".", "alt_key", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "function_keys", "[", "i", "]", ")", "self", ".", "k", ".", "release_key", "(", "self", ".", "k", ".", "alt_key", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press Alt + Fn1 ~ 12 once. **中文文档** 按下 Alt + Fn1 ~ 12 组合键。
[ "Press", "Alt", "+", "Fn1", "~", "12", "once", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L612-L623
train
MacHu-GWU/macro-project
macro/bot.py
Bot.shift_fn
def shift_fn(self, i, pre_dl=None, post_dl=None): """Press Shift + Fn1 ~ 12 once. **中文文档** 按下 Shift + Fn1 ~ 12 组合键。 """ self.delay(pre_dl) self.k.press_key(self.k.shift_key) self.k.tap_key(self.k.function_keys[i]) self.k.release_key(self.k.shift_key) self.delay(post_dl)
python
def shift_fn(self, i, pre_dl=None, post_dl=None): """Press Shift + Fn1 ~ 12 once. **中文文档** 按下 Shift + Fn1 ~ 12 组合键。 """ self.delay(pre_dl) self.k.press_key(self.k.shift_key) self.k.tap_key(self.k.function_keys[i]) self.k.release_key(self.k.shift_key) self.delay(post_dl)
[ "def", "shift_fn", "(", "self", ",", "i", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "press_key", "(", "self", ".", "k", ".", "shift_key", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "function_keys", "[", "i", "]", ")", "self", ".", "k", ".", "release_key", "(", "self", ".", "k", ".", "shift_key", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press Shift + Fn1 ~ 12 once. **中文文档** 按下 Shift + Fn1 ~ 12 组合键。
[ "Press", "Shift", "+", "Fn1", "~", "12", "once", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L625-L636
train
MacHu-GWU/macro-project
macro/bot.py
Bot.alt_tab
def alt_tab(self, n=1, pre_dl=None, post_dl=None): """Press Alt + Tab once, usually for switching between windows. Tab can be tapped for n times, default once. **中文文档** 按下 Alt + Tab 组合键, 其中Tab键按 n 次, 通常用于切换窗口。 """ self.delay(pre_dl) self.k.press_key(self.k.alt_key) self.k.tap_key(self.k.tab_key, n=n, interval=0.1) self.k.release_key(self.k.alt_key) self.delay(post_dl)
python
def alt_tab(self, n=1, pre_dl=None, post_dl=None): """Press Alt + Tab once, usually for switching between windows. Tab can be tapped for n times, default once. **中文文档** 按下 Alt + Tab 组合键, 其中Tab键按 n 次, 通常用于切换窗口。 """ self.delay(pre_dl) self.k.press_key(self.k.alt_key) self.k.tap_key(self.k.tab_key, n=n, interval=0.1) self.k.release_key(self.k.alt_key) self.delay(post_dl)
[ "def", "alt_tab", "(", "self", ",", "n", "=", "1", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "press_key", "(", "self", ".", "k", ".", "alt_key", ")", "self", ".", "k", ".", "tap_key", "(", "self", ".", "k", ".", "tab_key", ",", "n", "=", "n", ",", "interval", "=", "0.1", ")", "self", ".", "k", ".", "release_key", "(", "self", ".", "k", ".", "alt_key", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Press Alt + Tab once, usually for switching between windows. Tab can be tapped for n times, default once. **中文文档** 按下 Alt + Tab 组合键, 其中Tab键按 n 次, 通常用于切换窗口。
[ "Press", "Alt", "+", "Tab", "once", "usually", "for", "switching", "between", "windows", ".", "Tab", "can", "be", "tapped", "for", "n", "times", "default", "once", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L638-L650
train
MacHu-GWU/macro-project
macro/bot.py
Bot.type_string
def type_string(self, text, interval=0, pre_dl=None, post_dl=None): """Enter strings. **中文文档** 从键盘输入字符串, interval是字符间输入时间间隔, 单位是秒。 """ self.delay(pre_dl) self.k.type_string(text, interval) self.delay(post_dl)
python
def type_string(self, text, interval=0, pre_dl=None, post_dl=None): """Enter strings. **中文文档** 从键盘输入字符串, interval是字符间输入时间间隔, 单位是秒。 """ self.delay(pre_dl) self.k.type_string(text, interval) self.delay(post_dl)
[ "def", "type_string", "(", "self", ",", "text", ",", "interval", "=", "0", ",", "pre_dl", "=", "None", ",", "post_dl", "=", "None", ")", ":", "self", ".", "delay", "(", "pre_dl", ")", "self", ".", "k", ".", "type_string", "(", "text", ",", "interval", ")", "self", ".", "delay", "(", "post_dl", ")" ]
Enter strings. **中文文档** 从键盘输入字符串, interval是字符间输入时间间隔, 单位是秒。
[ "Enter", "strings", "." ]
dae909d2d28acbfa2be623aa2dffe988f3882d4d
https://github.com/MacHu-GWU/macro-project/blob/dae909d2d28acbfa2be623aa2dffe988f3882d4d/macro/bot.py#L653-L662
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Servers.Servers
def Servers(self,cached=True): """Returns list of server objects, populates if necessary. >>> clc.v2.Servers(["NY1BTDIPHYP0101","NY1BTDIWEB0101"]).Servers() [<clc.APIv2.server.Server object at 0x1065b0d50>, <clc.APIv2.server.Server object at 0x1065b0e50>] >>> print _[0] NY1BTDIPHYP0101 """ if not hasattr(self,'_servers') or not cached: self._servers = [] for server in self.servers_lst: self._servers.append(Server(id=server,alias=self.alias,session=self.session)) return(self._servers)
python
def Servers(self,cached=True): """Returns list of server objects, populates if necessary. >>> clc.v2.Servers(["NY1BTDIPHYP0101","NY1BTDIWEB0101"]).Servers() [<clc.APIv2.server.Server object at 0x1065b0d50>, <clc.APIv2.server.Server object at 0x1065b0e50>] >>> print _[0] NY1BTDIPHYP0101 """ if not hasattr(self,'_servers') or not cached: self._servers = [] for server in self.servers_lst: self._servers.append(Server(id=server,alias=self.alias,session=self.session)) return(self._servers)
[ "def", "Servers", "(", "self", ",", "cached", "=", "True", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_servers'", ")", "or", "not", "cached", ":", "self", ".", "_servers", "=", "[", "]", "for", "server", "in", "self", ".", "servers_lst", ":", "self", ".", "_servers", ".", "append", "(", "Server", "(", "id", "=", "server", ",", "alias", "=", "self", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")", "return", "(", "self", ".", "_servers", ")" ]
Returns list of server objects, populates if necessary. >>> clc.v2.Servers(["NY1BTDIPHYP0101","NY1BTDIWEB0101"]).Servers() [<clc.APIv2.server.Server object at 0x1065b0d50>, <clc.APIv2.server.Server object at 0x1065b0e50>] >>> print _[0] NY1BTDIPHYP0101
[ "Returns", "list", "of", "server", "objects", "populates", "if", "necessary", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L90-L105
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.Account
def Account(self): """Return account object for account containing this server. >>> clc.v2.Server("CA3BTDICNTRLM01").Account() <clc.APIv2.account.Account instance at 0x108789878> >>> print _ BTDI """ return(clc.v2.Account(alias=self.alias,session=self.session))
python
def Account(self): """Return account object for account containing this server. >>> clc.v2.Server("CA3BTDICNTRLM01").Account() <clc.APIv2.account.Account instance at 0x108789878> >>> print _ BTDI """ return(clc.v2.Account(alias=self.alias,session=self.session))
[ "def", "Account", "(", "self", ")", ":", "return", "(", "clc", ".", "v2", ".", "Account", "(", "alias", "=", "self", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Return account object for account containing this server. >>> clc.v2.Server("CA3BTDICNTRLM01").Account() <clc.APIv2.account.Account instance at 0x108789878> >>> print _ BTDI
[ "Return", "account", "object", "for", "account", "containing", "this", "server", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L232-L242
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.Group
def Group(self): """Return group object for group containing this server. >>> clc.v2.Server("CA3BTDICNTRLM01").Group() <clc.APIv2.group.Group object at 0x10b07b7d0> >>> print _ Ansible Managed Servers """ return(clc.v2.Group(id=self.groupId,alias=self.alias,session=self.session))
python
def Group(self): """Return group object for group containing this server. >>> clc.v2.Server("CA3BTDICNTRLM01").Group() <clc.APIv2.group.Group object at 0x10b07b7d0> >>> print _ Ansible Managed Servers """ return(clc.v2.Group(id=self.groupId,alias=self.alias,session=self.session))
[ "def", "Group", "(", "self", ")", ":", "return", "(", "clc", ".", "v2", ".", "Group", "(", "id", "=", "self", ".", "groupId", ",", "alias", "=", "self", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Return group object for group containing this server. >>> clc.v2.Server("CA3BTDICNTRLM01").Group() <clc.APIv2.group.Group object at 0x10b07b7d0> >>> print _ Ansible Managed Servers
[ "Return", "group", "object", "for", "group", "containing", "this", "server", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L245-L255
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.Disks
def Disks(self): """Return disks object associated with server. >>> clc.v2.Server("WA1BTDIX01").Disks() <clc.APIv2.disk.Disks object at 0x10feea190> """ if not self.disks: self.disks = clc.v2.Disks(server=self,disks_lst=self.data['details']['disks'],session=self.session) return(self.disks)
python
def Disks(self): """Return disks object associated with server. >>> clc.v2.Server("WA1BTDIX01").Disks() <clc.APIv2.disk.Disks object at 0x10feea190> """ if not self.disks: self.disks = clc.v2.Disks(server=self,disks_lst=self.data['details']['disks'],session=self.session) return(self.disks)
[ "def", "Disks", "(", "self", ")", ":", "if", "not", "self", ".", "disks", ":", "self", ".", "disks", "=", "clc", ".", "v2", ".", "Disks", "(", "server", "=", "self", ",", "disks_lst", "=", "self", ".", "data", "[", "'details'", "]", "[", "'disks'", "]", ",", "session", "=", "self", ".", "session", ")", "return", "(", "self", ".", "disks", ")" ]
Return disks object associated with server. >>> clc.v2.Server("WA1BTDIX01").Disks() <clc.APIv2.disk.Disks object at 0x10feea190>
[ "Return", "disks", "object", "associated", "with", "server", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L258-L268
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.PublicIPs
def PublicIPs(self): """Returns PublicIPs object associated with the server. """ if not self.public_ips: self.public_ips = clc.v2.PublicIPs(server=self,public_ips_lst=self.ip_addresses,session=self.session) return(self.public_ips)
python
def PublicIPs(self): """Returns PublicIPs object associated with the server. """ if not self.public_ips: self.public_ips = clc.v2.PublicIPs(server=self,public_ips_lst=self.ip_addresses,session=self.session) return(self.public_ips)
[ "def", "PublicIPs", "(", "self", ")", ":", "if", "not", "self", ".", "public_ips", ":", "self", ".", "public_ips", "=", "clc", ".", "v2", ".", "PublicIPs", "(", "server", "=", "self", ",", "public_ips_lst", "=", "self", ".", "ip_addresses", ",", "session", "=", "self", ".", "session", ")", "return", "(", "self", ".", "public_ips", ")" ]
Returns PublicIPs object associated with the server.
[ "Returns", "PublicIPs", "object", "associated", "with", "the", "server", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L271-L277
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.PriceUnits
def PriceUnits(self): """Returns the hourly unit component prices for this server. Total actual price is scaled by the unit quantity. >>> clc.v2.Server("NY1BTDIPHYP0101").PriceUnits() {'storage': 0.00021, 'cpu': 0.01, 'managed_os': 0.0, 'memory': 0.015} """ try: units = clc.v2.API.Call('GET','billing/%s/serverPricing/%s' % (self.alias,self.name),session=self.session) except clc.APIFailedResponse: raise(clc.ServerDeletedException) return({ 'cpu': units['cpu'], 'memory': units['memoryGB'], 'storage': units['storageGB'], 'managed_os': units['managedOS'], })
python
def PriceUnits(self): """Returns the hourly unit component prices for this server. Total actual price is scaled by the unit quantity. >>> clc.v2.Server("NY1BTDIPHYP0101").PriceUnits() {'storage': 0.00021, 'cpu': 0.01, 'managed_os': 0.0, 'memory': 0.015} """ try: units = clc.v2.API.Call('GET','billing/%s/serverPricing/%s' % (self.alias,self.name),session=self.session) except clc.APIFailedResponse: raise(clc.ServerDeletedException) return({ 'cpu': units['cpu'], 'memory': units['memoryGB'], 'storage': units['storageGB'], 'managed_os': units['managedOS'], })
[ "def", "PriceUnits", "(", "self", ")", ":", "try", ":", "units", "=", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'GET'", ",", "'billing/%s/serverPricing/%s'", "%", "(", "self", ".", "alias", ",", "self", ".", "name", ")", ",", "session", "=", "self", ".", "session", ")", "except", "clc", ".", "APIFailedResponse", ":", "raise", "(", "clc", ".", "ServerDeletedException", ")", "return", "(", "{", "'cpu'", ":", "units", "[", "'cpu'", "]", ",", "'memory'", ":", "units", "[", "'memoryGB'", "]", ",", "'storage'", ":", "units", "[", "'storageGB'", "]", ",", "'managed_os'", ":", "units", "[", "'managedOS'", "]", ",", "}", ")" ]
Returns the hourly unit component prices for this server. Total actual price is scaled by the unit quantity. >>> clc.v2.Server("NY1BTDIPHYP0101").PriceUnits() {'storage': 0.00021, 'cpu': 0.01, 'managed_os': 0.0, 'memory': 0.015}
[ "Returns", "the", "hourly", "unit", "component", "prices", "for", "this", "server", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L290-L311
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.PriceHourly
def PriceHourly(self): """Returns the total hourly price for the server. Sums unit prices with unit volumes. >>> clc.v2.Server("NY1BTDIPHYP0101").PriceHourly() 0.02857 """ units = self.PriceUnits() return(units['cpu']*self.cpu+units['memory']*self.memory+units['storage']*self.storage+units['managed_os'])
python
def PriceHourly(self): """Returns the total hourly price for the server. Sums unit prices with unit volumes. >>> clc.v2.Server("NY1BTDIPHYP0101").PriceHourly() 0.02857 """ units = self.PriceUnits() return(units['cpu']*self.cpu+units['memory']*self.memory+units['storage']*self.storage+units['managed_os'])
[ "def", "PriceHourly", "(", "self", ")", ":", "units", "=", "self", ".", "PriceUnits", "(", ")", "return", "(", "units", "[", "'cpu'", "]", "*", "self", ".", "cpu", "+", "units", "[", "'memory'", "]", "*", "self", ".", "memory", "+", "units", "[", "'storage'", "]", "*", "self", ".", "storage", "+", "units", "[", "'managed_os'", "]", ")" ]
Returns the total hourly price for the server. Sums unit prices with unit volumes. >>> clc.v2.Server("NY1BTDIPHYP0101").PriceHourly() 0.02857
[ "Returns", "the", "total", "hourly", "price", "for", "the", "server", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L314-L326
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.Credentials
def Credentials(self): """Returns the administrative credentials for this server. >>> clc.v2.Server("NY1BTDIPHYP0101").Credentials() {u'userName': u'administrator', u'password': u'dszkjh498s^'} """ return(clc.v2.API.Call('GET','servers/%s/%s/credentials' % (self.alias,self.name),session=self.session))
python
def Credentials(self): """Returns the administrative credentials for this server. >>> clc.v2.Server("NY1BTDIPHYP0101").Credentials() {u'userName': u'administrator', u'password': u'dszkjh498s^'} """ return(clc.v2.API.Call('GET','servers/%s/%s/credentials' % (self.alias,self.name),session=self.session))
[ "def", "Credentials", "(", "self", ")", ":", "return", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'GET'", ",", "'servers/%s/%s/credentials'", "%", "(", "self", ".", "alias", ",", "self", ".", "name", ")", ",", "session", "=", "self", ".", "session", ")", ")" ]
Returns the administrative credentials for this server. >>> clc.v2.Server("NY1BTDIPHYP0101").Credentials() {u'userName': u'administrator', u'password': u'dszkjh498s^'}
[ "Returns", "the", "administrative", "credentials", "for", "this", "server", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L329-L337
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.ExecutePackage
def ExecutePackage(self,package_id,parameters={}): """Execute an existing Bluerprint package on the server. https://t3n.zendesk.com/entries/59727040-Execute-Package Requires package ID, currently only available by browsing control and browsing for the package itself. The UUID parameter is the package ID we need. >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT06'). \ ExecutePackage(package_id="77ab3844-579d-4c8d-8955-c69a94a2ba1a",parameters={}). \ WaitUntilComplete() 0 """ return(clc.v2.Requests(clc.v2.API.Call('POST','operations/%s/servers/executePackage' % (self.alias), json.dumps({'servers': [self.id], 'package': {'packageId': package_id, 'parameters': parameters}}), session=self.session), alias=self.alias, session=self.session))
python
def ExecutePackage(self,package_id,parameters={}): """Execute an existing Bluerprint package on the server. https://t3n.zendesk.com/entries/59727040-Execute-Package Requires package ID, currently only available by browsing control and browsing for the package itself. The UUID parameter is the package ID we need. >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT06'). \ ExecutePackage(package_id="77ab3844-579d-4c8d-8955-c69a94a2ba1a",parameters={}). \ WaitUntilComplete() 0 """ return(clc.v2.Requests(clc.v2.API.Call('POST','operations/%s/servers/executePackage' % (self.alias), json.dumps({'servers': [self.id], 'package': {'packageId': package_id, 'parameters': parameters}}), session=self.session), alias=self.alias, session=self.session))
[ "def", "ExecutePackage", "(", "self", ",", "package_id", ",", "parameters", "=", "{", "}", ")", ":", "return", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'POST'", ",", "'operations/%s/servers/executePackage'", "%", "(", "self", ".", "alias", ")", ",", "json", ".", "dumps", "(", "{", "'servers'", ":", "[", "self", ".", "id", "]", ",", "'package'", ":", "{", "'packageId'", ":", "package_id", ",", "'parameters'", ":", "parameters", "}", "}", ")", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Execute an existing Bluerprint package on the server. https://t3n.zendesk.com/entries/59727040-Execute-Package Requires package ID, currently only available by browsing control and browsing for the package itself. The UUID parameter is the package ID we need. >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT06'). \ ExecutePackage(package_id="77ab3844-579d-4c8d-8955-c69a94a2ba1a",parameters={}). \ WaitUntilComplete() 0
[ "Execute", "an", "existing", "Bluerprint", "package", "on", "the", "server", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L387-L406
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.AddNIC
def AddNIC(self,network_id,ip=''): """Add a NIC from the provided network to server and, if provided, assign a provided IP address https://www.ctl.io/api-docs/v2/#servers-add-secondary-network Requires package ID, currently only available by browsing control and browsing for the package itself. The UUID parameter is the package ID we need. network_id - ID associated with the network to add ip - Explicit IP address to assign (optional) Need to reinstantiate the server object after execution completes to see the assigned IP address. >>> network = clc.v2.Networks(location="VA1").Get("10.128.166.0/24") >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT06'). \ AddNIC(network_id=network.id,ip=''). \ WaitUntilComplete() 0 """ return(clc.v2.Requests(clc.v2.API.Call('POST','servers/%s/%s/networks' % (self.alias,self.id), json.dumps({'networkId': network_id, 'ipAddress': ip}), session=self.session), alias=self.alias, session=self.session))
python
def AddNIC(self,network_id,ip=''): """Add a NIC from the provided network to server and, if provided, assign a provided IP address https://www.ctl.io/api-docs/v2/#servers-add-secondary-network Requires package ID, currently only available by browsing control and browsing for the package itself. The UUID parameter is the package ID we need. network_id - ID associated with the network to add ip - Explicit IP address to assign (optional) Need to reinstantiate the server object after execution completes to see the assigned IP address. >>> network = clc.v2.Networks(location="VA1").Get("10.128.166.0/24") >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT06'). \ AddNIC(network_id=network.id,ip=''). \ WaitUntilComplete() 0 """ return(clc.v2.Requests(clc.v2.API.Call('POST','servers/%s/%s/networks' % (self.alias,self.id), json.dumps({'networkId': network_id, 'ipAddress': ip}), session=self.session), alias=self.alias, session=self.session))
[ "def", "AddNIC", "(", "self", ",", "network_id", ",", "ip", "=", "''", ")", ":", "return", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'POST'", ",", "'servers/%s/%s/networks'", "%", "(", "self", ".", "alias", ",", "self", ".", "id", ")", ",", "json", ".", "dumps", "(", "{", "'networkId'", ":", "network_id", ",", "'ipAddress'", ":", "ip", "}", ")", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Add a NIC from the provided network to server and, if provided, assign a provided IP address https://www.ctl.io/api-docs/v2/#servers-add-secondary-network Requires package ID, currently only available by browsing control and browsing for the package itself. The UUID parameter is the package ID we need. network_id - ID associated with the network to add ip - Explicit IP address to assign (optional) Need to reinstantiate the server object after execution completes to see the assigned IP address. >>> network = clc.v2.Networks(location="VA1").Get("10.128.166.0/24") >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT06'). \ AddNIC(network_id=network.id,ip=''). \ WaitUntilComplete() 0
[ "Add", "a", "NIC", "from", "the", "provided", "network", "to", "server", "and", "if", "provided", "assign", "a", "provided", "IP", "address" ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L409-L435
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.RemoveNIC
def RemoveNIC(self,network_id): """Remove the NIC associated with the provided network from the server. https://www.ctl.io/api-docs/v2/#servers-remove-secondary-network network_id - ID associated with the network to remove >>> network = clc.v2.Networks(location="VA1").Get("10.128.166.0/24") >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT06'). \ RemoveNIC(network_id=network.id). \ WaitUntilComplete() 0 """ return( clc.v2.Requests( clc.v2.API.Call('DELETE','servers/%s/%s/networks/%s' % (self.alias,self.id,network_id), session=self.session), alias=self.alias, session=self.session ))
python
def RemoveNIC(self,network_id): """Remove the NIC associated with the provided network from the server. https://www.ctl.io/api-docs/v2/#servers-remove-secondary-network network_id - ID associated with the network to remove >>> network = clc.v2.Networks(location="VA1").Get("10.128.166.0/24") >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT06'). \ RemoveNIC(network_id=network.id). \ WaitUntilComplete() 0 """ return( clc.v2.Requests( clc.v2.API.Call('DELETE','servers/%s/%s/networks/%s' % (self.alias,self.id,network_id), session=self.session), alias=self.alias, session=self.session ))
[ "def", "RemoveNIC", "(", "self", ",", "network_id", ")", ":", "return", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'DELETE'", ",", "'servers/%s/%s/networks/%s'", "%", "(", "self", ".", "alias", ",", "self", ".", "id", ",", "network_id", ")", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Remove the NIC associated with the provided network from the server. https://www.ctl.io/api-docs/v2/#servers-remove-secondary-network network_id - ID associated with the network to remove >>> network = clc.v2.Networks(location="VA1").Get("10.128.166.0/24") >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT06'). \ RemoveNIC(network_id=network.id). \ WaitUntilComplete() 0
[ "Remove", "the", "NIC", "associated", "with", "the", "provided", "network", "from", "the", "server", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L437-L459
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.DeleteSnapshot
def DeleteSnapshot(self,names=None): """Removes an existing Hypervisor level snapshot. Supply one or more snapshot names to delete them concurrently. If no snapshot names are supplied will delete all existing snapshots. >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').DeleteSnapshot().WaitUntilComplete() 0 """ if names is None: names = self.GetSnapshots() requests_lst = [] for name in names: name_links = [obj['links'] for obj in self.data['details']['snapshots'] if obj['name']==name][0] requests_lst.append( clc.v2.Requests( clc.v2.API.Call('DELETE', [obj['href'] for obj in name_links if obj['rel']=='delete'][0], session=self.session), alias=self.alias, session=self.session)) return(sum(requests_lst))
python
def DeleteSnapshot(self,names=None): """Removes an existing Hypervisor level snapshot. Supply one or more snapshot names to delete them concurrently. If no snapshot names are supplied will delete all existing snapshots. >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').DeleteSnapshot().WaitUntilComplete() 0 """ if names is None: names = self.GetSnapshots() requests_lst = [] for name in names: name_links = [obj['links'] for obj in self.data['details']['snapshots'] if obj['name']==name][0] requests_lst.append( clc.v2.Requests( clc.v2.API.Call('DELETE', [obj['href'] for obj in name_links if obj['rel']=='delete'][0], session=self.session), alias=self.alias, session=self.session)) return(sum(requests_lst))
[ "def", "DeleteSnapshot", "(", "self", ",", "names", "=", "None", ")", ":", "if", "names", "is", "None", ":", "names", "=", "self", ".", "GetSnapshots", "(", ")", "requests_lst", "=", "[", "]", "for", "name", "in", "names", ":", "name_links", "=", "[", "obj", "[", "'links'", "]", "for", "obj", "in", "self", ".", "data", "[", "'details'", "]", "[", "'snapshots'", "]", "if", "obj", "[", "'name'", "]", "==", "name", "]", "[", "0", "]", "requests_lst", ".", "append", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'DELETE'", ",", "[", "obj", "[", "'href'", "]", "for", "obj", "in", "name_links", "if", "obj", "[", "'rel'", "]", "==", "'delete'", "]", "[", "0", "]", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")", "return", "(", "sum", "(", "requests_lst", ")", ")" ]
Removes an existing Hypervisor level snapshot. Supply one or more snapshot names to delete them concurrently. If no snapshot names are supplied will delete all existing snapshots. >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').DeleteSnapshot().WaitUntilComplete() 0
[ "Removes", "an", "existing", "Hypervisor", "level", "snapshot", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L495-L519
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.RestoreSnapshot
def RestoreSnapshot(self,name=None): """Restores an existing Hypervisor level snapshot. Supply snapshot name to restore If no snapshot name is supplied will restore the first snapshot found >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').RestoreSnapshot().WaitUntilComplete() 0 """ if not len(self.data['details']['snapshots']): raise(clc.CLCException("No snapshots exist")) if name is None: name = self.GetSnapshots()[0] name_links = [obj['links'] for obj in self.data['details']['snapshots'] if obj['name']==name][0] return(clc.v2.Requests(clc.v2.API.Call('POST', [obj['href'] for obj in name_links if obj['rel']=='restore'][0], session=self.session), alias=self.alias, session=self.session))
python
def RestoreSnapshot(self,name=None): """Restores an existing Hypervisor level snapshot. Supply snapshot name to restore If no snapshot name is supplied will restore the first snapshot found >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').RestoreSnapshot().WaitUntilComplete() 0 """ if not len(self.data['details']['snapshots']): raise(clc.CLCException("No snapshots exist")) if name is None: name = self.GetSnapshots()[0] name_links = [obj['links'] for obj in self.data['details']['snapshots'] if obj['name']==name][0] return(clc.v2.Requests(clc.v2.API.Call('POST', [obj['href'] for obj in name_links if obj['rel']=='restore'][0], session=self.session), alias=self.alias, session=self.session))
[ "def", "RestoreSnapshot", "(", "self", ",", "name", "=", "None", ")", ":", "if", "not", "len", "(", "self", ".", "data", "[", "'details'", "]", "[", "'snapshots'", "]", ")", ":", "raise", "(", "clc", ".", "CLCException", "(", "\"No snapshots exist\"", ")", ")", "if", "name", "is", "None", ":", "name", "=", "self", ".", "GetSnapshots", "(", ")", "[", "0", "]", "name_links", "=", "[", "obj", "[", "'links'", "]", "for", "obj", "in", "self", ".", "data", "[", "'details'", "]", "[", "'snapshots'", "]", "if", "obj", "[", "'name'", "]", "==", "name", "]", "[", "0", "]", "return", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'POST'", ",", "[", "obj", "[", "'href'", "]", "for", "obj", "in", "name_links", "if", "obj", "[", "'rel'", "]", "==", "'restore'", "]", "[", "0", "]", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Restores an existing Hypervisor level snapshot. Supply snapshot name to restore If no snapshot name is supplied will restore the first snapshot found >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').RestoreSnapshot().WaitUntilComplete() 0
[ "Restores", "an", "existing", "Hypervisor", "level", "snapshot", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L522-L541
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.Create
def Create(name,template,group_id,network_id,cpu=None,memory=None,alias=None,password=None,ip_address=None, storage_type="standard",type="standard",primary_dns=None,secondary_dns=None, additional_disks=[],custom_fields=[],ttl=None,managed_os=False,description=None, source_server_password=None,cpu_autoscale_policy_id=None,anti_affinity_policy_id=None, packages=[],configuration_id=None,session=None): """Creates a new server. https://www.centurylinkcloud.com/api-docs/v2/#servers-create-server cpu and memory are optional and if not provided we pull from the default server size values associated with the provided group_id. Set ttl as number of seconds before server is to be terminated. Must be >3600 >>> d = clc.v2.Datacenter() >>> clc.v2.Server.Create(name="api2",cpu=1,memory=1, group_id=d.Groups().Get("Default Group").id, template=d.Templates().Search("centos-6-64")[0].id, network_id=d.Networks().networks[0].id).WaitUntilComplete() 0 """ if not alias: alias = clc.v2.Account.GetAlias(session=session) if not description: description = name if type.lower() != "baremetal": if not cpu or not memory: group = clc.v2.Group(id=group_id,alias=alias,session=session) if not cpu and group.Defaults("cpu"): cpu = group.Defaults("cpu") elif not cpu: raise(clc.CLCException("No default CPU defined")) if not memory and group.Defaults("memory"): memory = group.Defaults("memory") elif not memory: raise(clc.CLCException("No default Memory defined")) if type.lower() == "standard" and storage_type.lower() not in ("standard","premium"): raise(clc.CLCException("Invalid type/storage_type combo")) if type.lower() == "hyperscale" and storage_type.lower() != "hyperscale": raise(clc.CLCException("Invalid type/storage_type combo")) if type.lower() == "baremetal": type = "bareMetal" if ttl and ttl<=3600: raise(clc.CLCException("ttl must be greater than 3600 seconds")) if ttl: ttl = clc.v2.time_utils.SecondsToZuluTS(int(time.time())+ttl) # TODO - validate custom_fields as a list of dicts with an id and a value key # TODO - validate template exists # TODO - validate additional_disks as a list of dicts with a path, sizeGB, and type (partitioned,raw) keys # TODO - validate addition_disks path not in template reserved paths # TODO - validate antiaffinity policy id set only with type=hyperscale payload = { 'name': name, 'description': description, 'groupId': group_id, 'primaryDNS': primary_dns, 'secondaryDNS': secondary_dns, 'networkId': network_id, 'password': password, 'type': type, 'customFields': custom_fields } if type == 'bareMetal': payload.update({'configurationId': configuration_id, 'osType': template}) else: payload.update({'sourceServerId': template, 'isManagedOS': managed_os, 'ipAddress': ip_address, 'sourceServerPassword': source_server_password, 'cpu': cpu, 'cpuAutoscalePolicyId': cpu_autoscale_policy_id, 'memoryGB': memory, 'storageType': storage_type, 'antiAffinityPolicyId': anti_affinity_policy_id, 'additionalDisks': additional_disks, 'ttl': ttl, 'packages': packages}) return clc.v2.Requests(clc.v2.API.Call('POST','servers/%s' % (alias), json.dumps(payload), session=session), alias=alias, session=session)
python
def Create(name,template,group_id,network_id,cpu=None,memory=None,alias=None,password=None,ip_address=None, storage_type="standard",type="standard",primary_dns=None,secondary_dns=None, additional_disks=[],custom_fields=[],ttl=None,managed_os=False,description=None, source_server_password=None,cpu_autoscale_policy_id=None,anti_affinity_policy_id=None, packages=[],configuration_id=None,session=None): """Creates a new server. https://www.centurylinkcloud.com/api-docs/v2/#servers-create-server cpu and memory are optional and if not provided we pull from the default server size values associated with the provided group_id. Set ttl as number of seconds before server is to be terminated. Must be >3600 >>> d = clc.v2.Datacenter() >>> clc.v2.Server.Create(name="api2",cpu=1,memory=1, group_id=d.Groups().Get("Default Group").id, template=d.Templates().Search("centos-6-64")[0].id, network_id=d.Networks().networks[0].id).WaitUntilComplete() 0 """ if not alias: alias = clc.v2.Account.GetAlias(session=session) if not description: description = name if type.lower() != "baremetal": if not cpu or not memory: group = clc.v2.Group(id=group_id,alias=alias,session=session) if not cpu and group.Defaults("cpu"): cpu = group.Defaults("cpu") elif not cpu: raise(clc.CLCException("No default CPU defined")) if not memory and group.Defaults("memory"): memory = group.Defaults("memory") elif not memory: raise(clc.CLCException("No default Memory defined")) if type.lower() == "standard" and storage_type.lower() not in ("standard","premium"): raise(clc.CLCException("Invalid type/storage_type combo")) if type.lower() == "hyperscale" and storage_type.lower() != "hyperscale": raise(clc.CLCException("Invalid type/storage_type combo")) if type.lower() == "baremetal": type = "bareMetal" if ttl and ttl<=3600: raise(clc.CLCException("ttl must be greater than 3600 seconds")) if ttl: ttl = clc.v2.time_utils.SecondsToZuluTS(int(time.time())+ttl) # TODO - validate custom_fields as a list of dicts with an id and a value key # TODO - validate template exists # TODO - validate additional_disks as a list of dicts with a path, sizeGB, and type (partitioned,raw) keys # TODO - validate addition_disks path not in template reserved paths # TODO - validate antiaffinity policy id set only with type=hyperscale payload = { 'name': name, 'description': description, 'groupId': group_id, 'primaryDNS': primary_dns, 'secondaryDNS': secondary_dns, 'networkId': network_id, 'password': password, 'type': type, 'customFields': custom_fields } if type == 'bareMetal': payload.update({'configurationId': configuration_id, 'osType': template}) else: payload.update({'sourceServerId': template, 'isManagedOS': managed_os, 'ipAddress': ip_address, 'sourceServerPassword': source_server_password, 'cpu': cpu, 'cpuAutoscalePolicyId': cpu_autoscale_policy_id, 'memoryGB': memory, 'storageType': storage_type, 'antiAffinityPolicyId': anti_affinity_policy_id, 'additionalDisks': additional_disks, 'ttl': ttl, 'packages': packages}) return clc.v2.Requests(clc.v2.API.Call('POST','servers/%s' % (alias), json.dumps(payload), session=session), alias=alias, session=session)
[ "def", "Create", "(", "name", ",", "template", ",", "group_id", ",", "network_id", ",", "cpu", "=", "None", ",", "memory", "=", "None", ",", "alias", "=", "None", ",", "password", "=", "None", ",", "ip_address", "=", "None", ",", "storage_type", "=", "\"standard\"", ",", "type", "=", "\"standard\"", ",", "primary_dns", "=", "None", ",", "secondary_dns", "=", "None", ",", "additional_disks", "=", "[", "]", ",", "custom_fields", "=", "[", "]", ",", "ttl", "=", "None", ",", "managed_os", "=", "False", ",", "description", "=", "None", ",", "source_server_password", "=", "None", ",", "cpu_autoscale_policy_id", "=", "None", ",", "anti_affinity_policy_id", "=", "None", ",", "packages", "=", "[", "]", ",", "configuration_id", "=", "None", ",", "session", "=", "None", ")", ":", "if", "not", "alias", ":", "alias", "=", "clc", ".", "v2", ".", "Account", ".", "GetAlias", "(", "session", "=", "session", ")", "if", "not", "description", ":", "description", "=", "name", "if", "type", ".", "lower", "(", ")", "!=", "\"baremetal\"", ":", "if", "not", "cpu", "or", "not", "memory", ":", "group", "=", "clc", ".", "v2", ".", "Group", "(", "id", "=", "group_id", ",", "alias", "=", "alias", ",", "session", "=", "session", ")", "if", "not", "cpu", "and", "group", ".", "Defaults", "(", "\"cpu\"", ")", ":", "cpu", "=", "group", ".", "Defaults", "(", "\"cpu\"", ")", "elif", "not", "cpu", ":", "raise", "(", "clc", ".", "CLCException", "(", "\"No default CPU defined\"", ")", ")", "if", "not", "memory", "and", "group", ".", "Defaults", "(", "\"memory\"", ")", ":", "memory", "=", "group", ".", "Defaults", "(", "\"memory\"", ")", "elif", "not", "memory", ":", "raise", "(", "clc", ".", "CLCException", "(", "\"No default Memory defined\"", ")", ")", "if", "type", ".", "lower", "(", ")", "==", "\"standard\"", "and", "storage_type", ".", "lower", "(", ")", "not", "in", "(", "\"standard\"", ",", "\"premium\"", ")", ":", "raise", "(", "clc", ".", "CLCException", "(", "\"Invalid type/storage_type combo\"", ")", ")", "if", "type", ".", "lower", "(", ")", "==", "\"hyperscale\"", "and", "storage_type", ".", "lower", "(", ")", "!=", "\"hyperscale\"", ":", "raise", "(", "clc", ".", "CLCException", "(", "\"Invalid type/storage_type combo\"", ")", ")", "if", "type", ".", "lower", "(", ")", "==", "\"baremetal\"", ":", "type", "=", "\"bareMetal\"", "if", "ttl", "and", "ttl", "<=", "3600", ":", "raise", "(", "clc", ".", "CLCException", "(", "\"ttl must be greater than 3600 seconds\"", ")", ")", "if", "ttl", ":", "ttl", "=", "clc", ".", "v2", ".", "time_utils", ".", "SecondsToZuluTS", "(", "int", "(", "time", ".", "time", "(", ")", ")", "+", "ttl", ")", "# TODO - validate custom_fields as a list of dicts with an id and a value key", "# TODO - validate template exists", "# TODO - validate additional_disks as a list of dicts with a path, sizeGB, and type (partitioned,raw) keys", "# TODO - validate addition_disks path not in template reserved paths", "# TODO - validate antiaffinity policy id set only with type=hyperscale", "payload", "=", "{", "'name'", ":", "name", ",", "'description'", ":", "description", ",", "'groupId'", ":", "group_id", ",", "'primaryDNS'", ":", "primary_dns", ",", "'secondaryDNS'", ":", "secondary_dns", ",", "'networkId'", ":", "network_id", ",", "'password'", ":", "password", ",", "'type'", ":", "type", ",", "'customFields'", ":", "custom_fields", "}", "if", "type", "==", "'bareMetal'", ":", "payload", ".", "update", "(", "{", "'configurationId'", ":", "configuration_id", ",", "'osType'", ":", "template", "}", ")", "else", ":", "payload", ".", "update", "(", "{", "'sourceServerId'", ":", "template", ",", "'isManagedOS'", ":", "managed_os", ",", "'ipAddress'", ":", "ip_address", ",", "'sourceServerPassword'", ":", "source_server_password", ",", "'cpu'", ":", "cpu", ",", "'cpuAutoscalePolicyId'", ":", "cpu_autoscale_policy_id", ",", "'memoryGB'", ":", "memory", ",", "'storageType'", ":", "storage_type", ",", "'antiAffinityPolicyId'", ":", "anti_affinity_policy_id", ",", "'additionalDisks'", ":", "additional_disks", ",", "'ttl'", ":", "ttl", ",", "'packages'", ":", "packages", "}", ")", "return", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'POST'", ",", "'servers/%s'", "%", "(", "alias", ")", ",", "json", ".", "dumps", "(", "payload", ")", ",", "session", "=", "session", ")", ",", "alias", "=", "alias", ",", "session", "=", "session", ")" ]
Creates a new server. https://www.centurylinkcloud.com/api-docs/v2/#servers-create-server cpu and memory are optional and if not provided we pull from the default server size values associated with the provided group_id. Set ttl as number of seconds before server is to be terminated. Must be >3600 >>> d = clc.v2.Datacenter() >>> clc.v2.Server.Create(name="api2",cpu=1,memory=1, group_id=d.Groups().Get("Default Group").id, template=d.Templates().Search("centos-6-64")[0].id, network_id=d.Networks().networks[0].id).WaitUntilComplete() 0
[ "Creates", "a", "new", "server", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L545-L617
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.Clone
def Clone(self,network_id,name=None,cpu=None,memory=None,group_id=None,alias=None,password=None,ip_address=None, storage_type=None,type=None,primary_dns=None,secondary_dns=None, custom_fields=None,ttl=None,managed_os=False,description=None, source_server_password=None,cpu_autoscale_policy_id=None,anti_affinity_policy_id=None, packages=[],count=1): """Creates one or more clones of existing server. https://www.centurylinkcloud.com/api-docs/v2/#servers-create-server Set ttl as number of seconds before server is to be terminated. * - network_id is currently a required parameter. This will change to optional once APIs are available to return the network id of self. * - if no password is supplied will reuse the password of self. Is this the expected behavior? Take note there is no way to for a system generated password with this pattern since we cannot leave as None * - any DNS settings from self aren't propogated to clone since they are unknown at system level and the clone process will touch them * - no change to the disk layout we will clone all * - clone will not replicate managed OS setting from self so this must be explicitly set >>> d = clc.v2.Datacenter() >>> clc.v2.Server(alias='BTDI',id='WA1BTDIAPI207').Clone(network_id=d.Networks().networks[0].id,count=2) 0 """ if not name: name = re.search("%s(.+)\d{2}$" % self.alias,self.name).group(1) #if not description and self.description: description = self.description if not cpu: cpu = self.cpu if not memory: memory = self.memory if not group_id: group_id = self.group_id if not alias: alias = self.alias if not source_server_password: source_server_password = self.Credentials()['password'] if not password: password = source_server_password # is this the expected behavior? if not storage_type: storage_type = self.storage_type if not type: type = self.type if not storage_type: storage_type = self.storage_type if not custom_fields and len(self.custom_fields): custom_fields = self.custom_fields if not description: description = self.description # TODO - #if not cpu_autoscale_policy_id: cpu_autoscale_policy_id = # TODO - #if not anti_affinity_policy_id: anti_affinity_policy_id = # TODO - need to get network_id of self, not currently exposed via API :( requests_lst = [] for i in range(0,count): requests_lst.append(Server.Create( \ name=name,cpu=cpu,memory=memory,group_id=group_id,network_id=network_id,alias=self.alias, password=password,ip_address=ip_address,storage_type=storage_type,type=type, primary_dns=primary_dns,secondary_dns=secondary_dns, custom_fields=custom_fields,ttl=ttl,managed_os=managed_os,description=description, source_server_password=source_server_password,cpu_autoscale_policy_id=cpu_autoscale_policy_id, anti_affinity_policy_id=anti_affinity_policy_id,packages=packages, template=self.id,session=self.session)) return(sum(requests_lst))
python
def Clone(self,network_id,name=None,cpu=None,memory=None,group_id=None,alias=None,password=None,ip_address=None, storage_type=None,type=None,primary_dns=None,secondary_dns=None, custom_fields=None,ttl=None,managed_os=False,description=None, source_server_password=None,cpu_autoscale_policy_id=None,anti_affinity_policy_id=None, packages=[],count=1): """Creates one or more clones of existing server. https://www.centurylinkcloud.com/api-docs/v2/#servers-create-server Set ttl as number of seconds before server is to be terminated. * - network_id is currently a required parameter. This will change to optional once APIs are available to return the network id of self. * - if no password is supplied will reuse the password of self. Is this the expected behavior? Take note there is no way to for a system generated password with this pattern since we cannot leave as None * - any DNS settings from self aren't propogated to clone since they are unknown at system level and the clone process will touch them * - no change to the disk layout we will clone all * - clone will not replicate managed OS setting from self so this must be explicitly set >>> d = clc.v2.Datacenter() >>> clc.v2.Server(alias='BTDI',id='WA1BTDIAPI207').Clone(network_id=d.Networks().networks[0].id,count=2) 0 """ if not name: name = re.search("%s(.+)\d{2}$" % self.alias,self.name).group(1) #if not description and self.description: description = self.description if not cpu: cpu = self.cpu if not memory: memory = self.memory if not group_id: group_id = self.group_id if not alias: alias = self.alias if not source_server_password: source_server_password = self.Credentials()['password'] if not password: password = source_server_password # is this the expected behavior? if not storage_type: storage_type = self.storage_type if not type: type = self.type if not storage_type: storage_type = self.storage_type if not custom_fields and len(self.custom_fields): custom_fields = self.custom_fields if not description: description = self.description # TODO - #if not cpu_autoscale_policy_id: cpu_autoscale_policy_id = # TODO - #if not anti_affinity_policy_id: anti_affinity_policy_id = # TODO - need to get network_id of self, not currently exposed via API :( requests_lst = [] for i in range(0,count): requests_lst.append(Server.Create( \ name=name,cpu=cpu,memory=memory,group_id=group_id,network_id=network_id,alias=self.alias, password=password,ip_address=ip_address,storage_type=storage_type,type=type, primary_dns=primary_dns,secondary_dns=secondary_dns, custom_fields=custom_fields,ttl=ttl,managed_os=managed_os,description=description, source_server_password=source_server_password,cpu_autoscale_policy_id=cpu_autoscale_policy_id, anti_affinity_policy_id=anti_affinity_policy_id,packages=packages, template=self.id,session=self.session)) return(sum(requests_lst))
[ "def", "Clone", "(", "self", ",", "network_id", ",", "name", "=", "None", ",", "cpu", "=", "None", ",", "memory", "=", "None", ",", "group_id", "=", "None", ",", "alias", "=", "None", ",", "password", "=", "None", ",", "ip_address", "=", "None", ",", "storage_type", "=", "None", ",", "type", "=", "None", ",", "primary_dns", "=", "None", ",", "secondary_dns", "=", "None", ",", "custom_fields", "=", "None", ",", "ttl", "=", "None", ",", "managed_os", "=", "False", ",", "description", "=", "None", ",", "source_server_password", "=", "None", ",", "cpu_autoscale_policy_id", "=", "None", ",", "anti_affinity_policy_id", "=", "None", ",", "packages", "=", "[", "]", ",", "count", "=", "1", ")", ":", "if", "not", "name", ":", "name", "=", "re", ".", "search", "(", "\"%s(.+)\\d{2}$\"", "%", "self", ".", "alias", ",", "self", ".", "name", ")", ".", "group", "(", "1", ")", "#if not description and self.description: description = self.description", "if", "not", "cpu", ":", "cpu", "=", "self", ".", "cpu", "if", "not", "memory", ":", "memory", "=", "self", ".", "memory", "if", "not", "group_id", ":", "group_id", "=", "self", ".", "group_id", "if", "not", "alias", ":", "alias", "=", "self", ".", "alias", "if", "not", "source_server_password", ":", "source_server_password", "=", "self", ".", "Credentials", "(", ")", "[", "'password'", "]", "if", "not", "password", ":", "password", "=", "source_server_password", "# is this the expected behavior?", "if", "not", "storage_type", ":", "storage_type", "=", "self", ".", "storage_type", "if", "not", "type", ":", "type", "=", "self", ".", "type", "if", "not", "storage_type", ":", "storage_type", "=", "self", ".", "storage_type", "if", "not", "custom_fields", "and", "len", "(", "self", ".", "custom_fields", ")", ":", "custom_fields", "=", "self", ".", "custom_fields", "if", "not", "description", ":", "description", "=", "self", ".", "description", "# TODO - #if not cpu_autoscale_policy_id: cpu_autoscale_policy_id =", "# TODO - #if not anti_affinity_policy_id: anti_affinity_policy_id =", "# TODO - need to get network_id of self, not currently exposed via API :(", "requests_lst", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "count", ")", ":", "requests_lst", ".", "append", "(", "Server", ".", "Create", "(", "name", "=", "name", ",", "cpu", "=", "cpu", ",", "memory", "=", "memory", ",", "group_id", "=", "group_id", ",", "network_id", "=", "network_id", ",", "alias", "=", "self", ".", "alias", ",", "password", "=", "password", ",", "ip_address", "=", "ip_address", ",", "storage_type", "=", "storage_type", ",", "type", "=", "type", ",", "primary_dns", "=", "primary_dns", ",", "secondary_dns", "=", "secondary_dns", ",", "custom_fields", "=", "custom_fields", ",", "ttl", "=", "ttl", ",", "managed_os", "=", "managed_os", ",", "description", "=", "description", ",", "source_server_password", "=", "source_server_password", ",", "cpu_autoscale_policy_id", "=", "cpu_autoscale_policy_id", ",", "anti_affinity_policy_id", "=", "anti_affinity_policy_id", ",", "packages", "=", "packages", ",", "template", "=", "self", ".", "id", ",", "session", "=", "self", ".", "session", ")", ")", "return", "(", "sum", "(", "requests_lst", ")", ")" ]
Creates one or more clones of existing server. https://www.centurylinkcloud.com/api-docs/v2/#servers-create-server Set ttl as number of seconds before server is to be terminated. * - network_id is currently a required parameter. This will change to optional once APIs are available to return the network id of self. * - if no password is supplied will reuse the password of self. Is this the expected behavior? Take note there is no way to for a system generated password with this pattern since we cannot leave as None * - any DNS settings from self aren't propogated to clone since they are unknown at system level and the clone process will touch them * - no change to the disk layout we will clone all * - clone will not replicate managed OS setting from self so this must be explicitly set >>> d = clc.v2.Datacenter() >>> clc.v2.Server(alias='BTDI',id='WA1BTDIAPI207').Clone(network_id=d.Networks().networks[0].id,count=2) 0
[ "Creates", "one", "or", "more", "clones", "of", "existing", "server", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L620-L674
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.ConvertToTemplate
def ConvertToTemplate(self,visibility,description=None,password=None): """Converts existing server to a template. visibility is one of private or shared. >>> d = clc.v2.Datacenter() >>> clc.v2.Server(alias='BTDI',id='WA1BTDIAPI207').ConvertToTemplate("private","my template") 0 """ if visibility not in ('private','shared'): raise(clc.CLCException("Invalid visibility - must be private or shared")) if not password: password = self.Credentials()['password'] if not description: description = self.description return(clc.v2.Requests(clc.v2.API.Call('POST','servers/%s/%s/convertToTemplate' % (self.alias,self.id), json.dumps({"description": description, "visibility": visibility, "password": password}), session=self.session), alias=self.alias, session=self.session))
python
def ConvertToTemplate(self,visibility,description=None,password=None): """Converts existing server to a template. visibility is one of private or shared. >>> d = clc.v2.Datacenter() >>> clc.v2.Server(alias='BTDI',id='WA1BTDIAPI207').ConvertToTemplate("private","my template") 0 """ if visibility not in ('private','shared'): raise(clc.CLCException("Invalid visibility - must be private or shared")) if not password: password = self.Credentials()['password'] if not description: description = self.description return(clc.v2.Requests(clc.v2.API.Call('POST','servers/%s/%s/convertToTemplate' % (self.alias,self.id), json.dumps({"description": description, "visibility": visibility, "password": password}), session=self.session), alias=self.alias, session=self.session))
[ "def", "ConvertToTemplate", "(", "self", ",", "visibility", ",", "description", "=", "None", ",", "password", "=", "None", ")", ":", "if", "visibility", "not", "in", "(", "'private'", ",", "'shared'", ")", ":", "raise", "(", "clc", ".", "CLCException", "(", "\"Invalid visibility - must be private or shared\"", ")", ")", "if", "not", "password", ":", "password", "=", "self", ".", "Credentials", "(", ")", "[", "'password'", "]", "if", "not", "description", ":", "description", "=", "self", ".", "description", "return", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'POST'", ",", "'servers/%s/%s/convertToTemplate'", "%", "(", "self", ".", "alias", ",", "self", ".", "id", ")", ",", "json", ".", "dumps", "(", "{", "\"description\"", ":", "description", ",", "\"visibility\"", ":", "visibility", ",", "\"password\"", ":", "password", "}", ")", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Converts existing server to a template. visibility is one of private or shared. >>> d = clc.v2.Datacenter() >>> clc.v2.Server(alias='BTDI',id='WA1BTDIAPI207').ConvertToTemplate("private","my template") 0
[ "Converts", "existing", "server", "to", "a", "template", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L678-L697
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.Change
def Change(self,cpu=None,memory=None,description=None,group_id=None): """Change existing server object. One more more fields can be set and method will return with a requests object for all queued activities. This is a convenience function - all each of these changes requires a seperate API call. Some API calls are synchronous (e.g. changing group ID or password) while others are async. """ if group_id: groupId = group_id else: groupId = None payloads = [] requests = [] for key in ("cpu","memory","description","groupId"): if locals()[key]: requests.append(clc.v2.Requests(clc.v2.API.Call('PATCH','servers/%s/%s' % (self.alias,self.id), json.dumps([{"op": "set", "member": key, "value": locals()[key]}]), session=self.session), alias=self.alias, session=self.session)) if len(requests): self.dirty = True return(sum(requests))
python
def Change(self,cpu=None,memory=None,description=None,group_id=None): """Change existing server object. One more more fields can be set and method will return with a requests object for all queued activities. This is a convenience function - all each of these changes requires a seperate API call. Some API calls are synchronous (e.g. changing group ID or password) while others are async. """ if group_id: groupId = group_id else: groupId = None payloads = [] requests = [] for key in ("cpu","memory","description","groupId"): if locals()[key]: requests.append(clc.v2.Requests(clc.v2.API.Call('PATCH','servers/%s/%s' % (self.alias,self.id), json.dumps([{"op": "set", "member": key, "value": locals()[key]}]), session=self.session), alias=self.alias, session=self.session)) if len(requests): self.dirty = True return(sum(requests))
[ "def", "Change", "(", "self", ",", "cpu", "=", "None", ",", "memory", "=", "None", ",", "description", "=", "None", ",", "group_id", "=", "None", ")", ":", "if", "group_id", ":", "groupId", "=", "group_id", "else", ":", "groupId", "=", "None", "payloads", "=", "[", "]", "requests", "=", "[", "]", "for", "key", "in", "(", "\"cpu\"", ",", "\"memory\"", ",", "\"description\"", ",", "\"groupId\"", ")", ":", "if", "locals", "(", ")", "[", "key", "]", ":", "requests", ".", "append", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'PATCH'", ",", "'servers/%s/%s'", "%", "(", "self", ".", "alias", ",", "self", ".", "id", ")", ",", "json", ".", "dumps", "(", "[", "{", "\"op\"", ":", "\"set\"", ",", "\"member\"", ":", "key", ",", "\"value\"", ":", "locals", "(", ")", "[", "key", "]", "}", "]", ")", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")", "if", "len", "(", "requests", ")", ":", "self", ".", "dirty", "=", "True", "return", "(", "sum", "(", "requests", ")", ")" ]
Change existing server object. One more more fields can be set and method will return with a requests object for all queued activities. This is a convenience function - all each of these changes requires a seperate API call. Some API calls are synchronous (e.g. changing group ID or password) while others are async.
[ "Change", "existing", "server", "object", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L701-L727
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.SetPassword
def SetPassword(self,password): """Request change of password. The API request requires supplying the current password. For this we issue a call to retrieve the credentials so note there will be an activity log for retrieving the credentials associated with any SetPassword entry >>> s.SetPassword("newpassword") """ # 0: {op: "set", member: "password", value: {current: " r`5Mun/vT:qZ]2?z", password: "Savvis123!"}} if self.data['status'] != "active": raise(clc.CLCException("Server must be powered on to change password")) return(clc.v2.Requests(clc.v2.API.Call('PATCH','servers/%s/%s' % (self.alias,self.id), json.dumps([{"op": "set", "member": "password", "value": {"current": self.Credentials()['password'], "password": password}}]), session=self.session), alias=self.alias, session=self.session))
python
def SetPassword(self,password): """Request change of password. The API request requires supplying the current password. For this we issue a call to retrieve the credentials so note there will be an activity log for retrieving the credentials associated with any SetPassword entry >>> s.SetPassword("newpassword") """ # 0: {op: "set", member: "password", value: {current: " r`5Mun/vT:qZ]2?z", password: "Savvis123!"}} if self.data['status'] != "active": raise(clc.CLCException("Server must be powered on to change password")) return(clc.v2.Requests(clc.v2.API.Call('PATCH','servers/%s/%s' % (self.alias,self.id), json.dumps([{"op": "set", "member": "password", "value": {"current": self.Credentials()['password'], "password": password}}]), session=self.session), alias=self.alias, session=self.session))
[ "def", "SetPassword", "(", "self", ",", "password", ")", ":", "# 0: {op: \"set\", member: \"password\", value: {current: \" r`5Mun/vT:qZ]2?z\", password: \"Savvis123!\"}}", "if", "self", ".", "data", "[", "'status'", "]", "!=", "\"active\"", ":", "raise", "(", "clc", ".", "CLCException", "(", "\"Server must be powered on to change password\"", ")", ")", "return", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'PATCH'", ",", "'servers/%s/%s'", "%", "(", "self", ".", "alias", ",", "self", ".", "id", ")", ",", "json", ".", "dumps", "(", "[", "{", "\"op\"", ":", "\"set\"", ",", "\"member\"", ":", "\"password\"", ",", "\"value\"", ":", "{", "\"current\"", ":", "self", ".", "Credentials", "(", ")", "[", "'password'", "]", ",", "\"password\"", ":", "password", "}", "}", "]", ")", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Request change of password. The API request requires supplying the current password. For this we issue a call to retrieve the credentials so note there will be an activity log for retrieving the credentials associated with any SetPassword entry >>> s.SetPassword("newpassword")
[ "Request", "change", "of", "password", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L736-L754
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
Server.Delete
def Delete(self): """Delete server. https://t3n.zendesk.com/entries/59220824-Delete-Server >>> clc.v2.Server("WA1BTDIAPI219").Delete().WaitUntilComplete() 0 """ return(clc.v2.Requests(clc.v2.API.Call('DELETE','servers/%s/%s' % (self.alias,self.id),session=self.session),alias=self.alias,session=self.session))
python
def Delete(self): """Delete server. https://t3n.zendesk.com/entries/59220824-Delete-Server >>> clc.v2.Server("WA1BTDIAPI219").Delete().WaitUntilComplete() 0 """ return(clc.v2.Requests(clc.v2.API.Call('DELETE','servers/%s/%s' % (self.alias,self.id),session=self.session),alias=self.alias,session=self.session))
[ "def", "Delete", "(", "self", ")", ":", "return", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'DELETE'", ",", "'servers/%s/%s'", "%", "(", "self", ".", "alias", ",", "self", ".", "id", ")", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Delete server. https://t3n.zendesk.com/entries/59220824-Delete-Server >>> clc.v2.Server("WA1BTDIAPI219").Delete().WaitUntilComplete() 0
[ "Delete", "server", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L757-L766
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/public_ip.py
PublicIPs.Get
def Get(self,key): """Get public_ip by providing either the public or the internal IP address.""" for public_ip in self.public_ips: if public_ip.id == key: return(public_ip) elif key == public_ip.internal: return(public_ip)
python
def Get(self,key): """Get public_ip by providing either the public or the internal IP address.""" for public_ip in self.public_ips: if public_ip.id == key: return(public_ip) elif key == public_ip.internal: return(public_ip)
[ "def", "Get", "(", "self", ",", "key", ")", ":", "for", "public_ip", "in", "self", ".", "public_ips", ":", "if", "public_ip", ".", "id", "==", "key", ":", "return", "(", "public_ip", ")", "elif", "key", "==", "public_ip", ".", "internal", ":", "return", "(", "public_ip", ")" ]
Get public_ip by providing either the public or the internal IP address.
[ "Get", "public_ip", "by", "providing", "either", "the", "public", "or", "the", "internal", "IP", "address", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L54-L59
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/public_ip.py
PublicIPs.Add
def Add(self,ports,source_restrictions=None,private_ip=None): """Add new public_ip. Specify one or more ports using a list of dicts with the following keys: protocol - TCP, UDP, or ICMP port - int 0-65534 port_to - (optional) if specifying a range of ports then the rqange end. int 0-65534 Optionally specify one or more source restrictions using a list of dicts with the following keys: cidr - string with CIDR notation for the subnet (e.g. "132.200.20.0/24") private_ip is the existing private IP address to NAT to (optional) # New public IP with single port >>> p = clc.v2.Server(alias='BTDI',id='WA1BTDIX03').PublicIPs() >>> p.Add(ports=[{"protocol": "TCP","port":5}]).WaitUntilComplete() 0 # New public IP with port range >>> p.Add([{"protocol": "UDP","port":10,"port_to":50}]).WaitUntilComplete() 0 # Map existing private IP to single port >>> p.Add(ports=[{"protocol": "TCP","port":22}],k source_restrictions=[{'cidr': "132.200.20.0/24"}], private_ip="10.80.148.13").WaitUntilComplete() 0 * Note this API is subject to revision to make ports and source restrictions access to parallel that used for accessors. * public_ips.public_ips will not be updated to reflect this addition. Recreate object after request completes to access new info including getting the IP itself """ payload = {'ports': []} for port in ports: if 'port_to' in port: payload['ports'].append({'protocol':port['protocol'], 'port':port['port'], 'portTo':port['port_to']}) else: payload['ports'].append({'protocol':port['protocol'], 'port':port['port']}) if source_restrictions: payload['sourceRestrictions'] = source_restrictions if private_ip: payload['internalIPAddress'] = private_ip return(clc.v2.Requests(clc.v2.API.Call('POST','servers/%s/%s/publicIPAddresses' % (self.server.alias,self.server.id), json.dumps(payload),session=self.session), alias=self.server.alias,session=self.session))
python
def Add(self,ports,source_restrictions=None,private_ip=None): """Add new public_ip. Specify one or more ports using a list of dicts with the following keys: protocol - TCP, UDP, or ICMP port - int 0-65534 port_to - (optional) if specifying a range of ports then the rqange end. int 0-65534 Optionally specify one or more source restrictions using a list of dicts with the following keys: cidr - string with CIDR notation for the subnet (e.g. "132.200.20.0/24") private_ip is the existing private IP address to NAT to (optional) # New public IP with single port >>> p = clc.v2.Server(alias='BTDI',id='WA1BTDIX03').PublicIPs() >>> p.Add(ports=[{"protocol": "TCP","port":5}]).WaitUntilComplete() 0 # New public IP with port range >>> p.Add([{"protocol": "UDP","port":10,"port_to":50}]).WaitUntilComplete() 0 # Map existing private IP to single port >>> p.Add(ports=[{"protocol": "TCP","port":22}],k source_restrictions=[{'cidr': "132.200.20.0/24"}], private_ip="10.80.148.13").WaitUntilComplete() 0 * Note this API is subject to revision to make ports and source restrictions access to parallel that used for accessors. * public_ips.public_ips will not be updated to reflect this addition. Recreate object after request completes to access new info including getting the IP itself """ payload = {'ports': []} for port in ports: if 'port_to' in port: payload['ports'].append({'protocol':port['protocol'], 'port':port['port'], 'portTo':port['port_to']}) else: payload['ports'].append({'protocol':port['protocol'], 'port':port['port']}) if source_restrictions: payload['sourceRestrictions'] = source_restrictions if private_ip: payload['internalIPAddress'] = private_ip return(clc.v2.Requests(clc.v2.API.Call('POST','servers/%s/%s/publicIPAddresses' % (self.server.alias,self.server.id), json.dumps(payload),session=self.session), alias=self.server.alias,session=self.session))
[ "def", "Add", "(", "self", ",", "ports", ",", "source_restrictions", "=", "None", ",", "private_ip", "=", "None", ")", ":", "payload", "=", "{", "'ports'", ":", "[", "]", "}", "for", "port", "in", "ports", ":", "if", "'port_to'", "in", "port", ":", "payload", "[", "'ports'", "]", ".", "append", "(", "{", "'protocol'", ":", "port", "[", "'protocol'", "]", ",", "'port'", ":", "port", "[", "'port'", "]", ",", "'portTo'", ":", "port", "[", "'port_to'", "]", "}", ")", "else", ":", "payload", "[", "'ports'", "]", ".", "append", "(", "{", "'protocol'", ":", "port", "[", "'protocol'", "]", ",", "'port'", ":", "port", "[", "'port'", "]", "}", ")", "if", "source_restrictions", ":", "payload", "[", "'sourceRestrictions'", "]", "=", "source_restrictions", "if", "private_ip", ":", "payload", "[", "'internalIPAddress'", "]", "=", "private_ip", "return", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'POST'", ",", "'servers/%s/%s/publicIPAddresses'", "%", "(", "self", ".", "server", ".", "alias", ",", "self", ".", "server", ".", "id", ")", ",", "json", ".", "dumps", "(", "payload", ")", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "server", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Add new public_ip. Specify one or more ports using a list of dicts with the following keys: protocol - TCP, UDP, or ICMP port - int 0-65534 port_to - (optional) if specifying a range of ports then the rqange end. int 0-65534 Optionally specify one or more source restrictions using a list of dicts with the following keys: cidr - string with CIDR notation for the subnet (e.g. "132.200.20.0/24") private_ip is the existing private IP address to NAT to (optional) # New public IP with single port >>> p = clc.v2.Server(alias='BTDI',id='WA1BTDIX03').PublicIPs() >>> p.Add(ports=[{"protocol": "TCP","port":5}]).WaitUntilComplete() 0 # New public IP with port range >>> p.Add([{"protocol": "UDP","port":10,"port_to":50}]).WaitUntilComplete() 0 # Map existing private IP to single port >>> p.Add(ports=[{"protocol": "TCP","port":22}],k source_restrictions=[{'cidr': "132.200.20.0/24"}], private_ip="10.80.148.13").WaitUntilComplete() 0 * Note this API is subject to revision to make ports and source restrictions access to parallel that used for accessors. * public_ips.public_ips will not be updated to reflect this addition. Recreate object after request completes to access new info including getting the IP itself
[ "Add", "new", "public_ip", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L62-L109
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/public_ip.py
PublicIP._Load
def _Load(self,cached=True): """Performs a full load of all PublicIP metadata.""" if not self.data or not cached: self.data = clc.v2.API.Call('GET','servers/%s/%s/publicIPAddresses/%s' % (self.parent.server.alias,self.parent.server.id,self.id), session=self.session) # build ports self.data['_ports'] = self.data['ports'] self.data['ports'] = [] for port in self.data['_ports']: if 'portTo' in port: self.ports.append(Port(self,port['protocol'],port['port'],port['portTo'])) else: self.ports.append(Port(self,port['protocol'],port['port'])) # build source restriction self.data['_source_restrictions'] = self.data['sourceRestrictions'] self.data['source_restrictions'] = [] for source_restriction in self.data['_source_restrictions']: self.source_restrictions.append(SourceRestriction(self,source_restriction['cidr'])) return(self.data)
python
def _Load(self,cached=True): """Performs a full load of all PublicIP metadata.""" if not self.data or not cached: self.data = clc.v2.API.Call('GET','servers/%s/%s/publicIPAddresses/%s' % (self.parent.server.alias,self.parent.server.id,self.id), session=self.session) # build ports self.data['_ports'] = self.data['ports'] self.data['ports'] = [] for port in self.data['_ports']: if 'portTo' in port: self.ports.append(Port(self,port['protocol'],port['port'],port['portTo'])) else: self.ports.append(Port(self,port['protocol'],port['port'])) # build source restriction self.data['_source_restrictions'] = self.data['sourceRestrictions'] self.data['source_restrictions'] = [] for source_restriction in self.data['_source_restrictions']: self.source_restrictions.append(SourceRestriction(self,source_restriction['cidr'])) return(self.data)
[ "def", "_Load", "(", "self", ",", "cached", "=", "True", ")", ":", "if", "not", "self", ".", "data", "or", "not", "cached", ":", "self", ".", "data", "=", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'GET'", ",", "'servers/%s/%s/publicIPAddresses/%s'", "%", "(", "self", ".", "parent", ".", "server", ".", "alias", ",", "self", ".", "parent", ".", "server", ".", "id", ",", "self", ".", "id", ")", ",", "session", "=", "self", ".", "session", ")", "# build ports", "self", ".", "data", "[", "'_ports'", "]", "=", "self", ".", "data", "[", "'ports'", "]", "self", ".", "data", "[", "'ports'", "]", "=", "[", "]", "for", "port", "in", "self", ".", "data", "[", "'_ports'", "]", ":", "if", "'portTo'", "in", "port", ":", "self", ".", "ports", ".", "append", "(", "Port", "(", "self", ",", "port", "[", "'protocol'", "]", ",", "port", "[", "'port'", "]", ",", "port", "[", "'portTo'", "]", ")", ")", "else", ":", "self", ".", "ports", ".", "append", "(", "Port", "(", "self", ",", "port", "[", "'protocol'", "]", ",", "port", "[", "'port'", "]", ")", ")", "# build source restriction", "self", ".", "data", "[", "'_source_restrictions'", "]", "=", "self", ".", "data", "[", "'sourceRestrictions'", "]", "self", ".", "data", "[", "'source_restrictions'", "]", "=", "[", "]", "for", "source_restriction", "in", "self", ".", "data", "[", "'_source_restrictions'", "]", ":", "self", ".", "source_restrictions", ".", "append", "(", "SourceRestriction", "(", "self", ",", "source_restriction", "[", "'cidr'", "]", ")", ")", "return", "(", "self", ".", "data", ")" ]
Performs a full load of all PublicIP metadata.
[ "Performs", "a", "full", "load", "of", "all", "PublicIP", "metadata", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L125-L145
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/public_ip.py
PublicIP.Delete
def Delete(self): """Delete public IP. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Delete().WaitUntilComplete() 0 """ public_ip_set = [{'public_ipId': o.id} for o in self.parent.public_ips if o!=self] self.parent.public_ips = [o for o in self.parent.public_ips if o!=self] return(clc.v2.Requests(clc.v2.API.Call('DELETE','servers/%s/%s/publicIPAddresses/%s' % (self.parent.server.alias,self.parent.server.id,self.id), session=self.session), alias=self.parent.server.alias, session=self.session))
python
def Delete(self): """Delete public IP. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Delete().WaitUntilComplete() 0 """ public_ip_set = [{'public_ipId': o.id} for o in self.parent.public_ips if o!=self] self.parent.public_ips = [o for o in self.parent.public_ips if o!=self] return(clc.v2.Requests(clc.v2.API.Call('DELETE','servers/%s/%s/publicIPAddresses/%s' % (self.parent.server.alias,self.parent.server.id,self.id), session=self.session), alias=self.parent.server.alias, session=self.session))
[ "def", "Delete", "(", "self", ")", ":", "public_ip_set", "=", "[", "{", "'public_ipId'", ":", "o", ".", "id", "}", "for", "o", "in", "self", ".", "parent", ".", "public_ips", "if", "o", "!=", "self", "]", "self", ".", "parent", ".", "public_ips", "=", "[", "o", "for", "o", "in", "self", ".", "parent", ".", "public_ips", "if", "o", "!=", "self", "]", "return", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'DELETE'", ",", "'servers/%s/%s/publicIPAddresses/%s'", "%", "(", "self", ".", "parent", ".", "server", ".", "alias", ",", "self", ".", "parent", ".", "server", ".", "id", ",", "self", ".", "id", ")", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "parent", ".", "server", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Delete public IP. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Delete().WaitUntilComplete() 0
[ "Delete", "public", "IP", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L148-L161
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/public_ip.py
PublicIP.Update
def Update(self): """Commit current PublicIP definition to cloud. Usually called by the class to commit changes to port and source restriction policies. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Update().WaitUntilComplete() 0 """ return(clc.v2.Requests(clc.v2.API.Call('PUT','servers/%s/%s/publicIPAddresses/%s' % (self.parent.server.alias,self.parent.server.id,self.id), json.dumps({'ports': [o.ToDict() for o in self.ports], 'sourceRestrictions': [o.ToDict() for o in self.source_restrictions] }), session=self.session), alias=self.parent.server.alias, session=self.session))
python
def Update(self): """Commit current PublicIP definition to cloud. Usually called by the class to commit changes to port and source restriction policies. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Update().WaitUntilComplete() 0 """ return(clc.v2.Requests(clc.v2.API.Call('PUT','servers/%s/%s/publicIPAddresses/%s' % (self.parent.server.alias,self.parent.server.id,self.id), json.dumps({'ports': [o.ToDict() for o in self.ports], 'sourceRestrictions': [o.ToDict() for o in self.source_restrictions] }), session=self.session), alias=self.parent.server.alias, session=self.session))
[ "def", "Update", "(", "self", ")", ":", "return", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'PUT'", ",", "'servers/%s/%s/publicIPAddresses/%s'", "%", "(", "self", ".", "parent", ".", "server", ".", "alias", ",", "self", ".", "parent", ".", "server", ".", "id", ",", "self", ".", "id", ")", ",", "json", ".", "dumps", "(", "{", "'ports'", ":", "[", "o", ".", "ToDict", "(", ")", "for", "o", "in", "self", ".", "ports", "]", ",", "'sourceRestrictions'", ":", "[", "o", ".", "ToDict", "(", ")", "for", "o", "in", "self", ".", "source_restrictions", "]", "}", ")", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "parent", ".", "server", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Commit current PublicIP definition to cloud. Usually called by the class to commit changes to port and source restriction policies. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Update().WaitUntilComplete() 0
[ "Commit", "current", "PublicIP", "definition", "to", "cloud", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L164-L179
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/public_ip.py
PublicIP.AddPort
def AddPort(self,protocol,port,port_to=None): """Add and commit a single port. # Add single port >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].AddPort(protocol='TCP',port='22').WaitUntilComplete() 0 # Add port range >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].AddPort(protocol='UDP',port='10000',port_to='15000').WaitUntilComplete() 0 """ self.ports.append(Port(self,protocol,port,port_to)) return(self.Update())
python
def AddPort(self,protocol,port,port_to=None): """Add and commit a single port. # Add single port >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].AddPort(protocol='TCP',port='22').WaitUntilComplete() 0 # Add port range >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].AddPort(protocol='UDP',port='10000',port_to='15000').WaitUntilComplete() 0 """ self.ports.append(Port(self,protocol,port,port_to)) return(self.Update())
[ "def", "AddPort", "(", "self", ",", "protocol", ",", "port", ",", "port_to", "=", "None", ")", ":", "self", ".", "ports", ".", "append", "(", "Port", "(", "self", ",", "protocol", ",", "port", ",", "port_to", ")", ")", "return", "(", "self", ".", "Update", "(", ")", ")" ]
Add and commit a single port. # Add single port >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].AddPort(protocol='TCP',port='22').WaitUntilComplete() 0 # Add port range >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].AddPort(protocol='UDP',port='10000',port_to='15000').WaitUntilComplete() 0
[ "Add", "and", "commit", "a", "single", "port", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L182-L197
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/public_ip.py
PublicIP.AddPorts
def AddPorts(self,ports): """Create one or more port access policies. Include a list of dicts with protocol, port, and port_to (optional - for range) keys. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0] .AddPorts([{'protocol': 'TCP', 'port': '80' }, {'protocol': 'UDP', 'port': '10000', 'port_to': '15000'}]).WaitUntilComplete() 0 """ for port in ports: if 'port_to' in port: self.ports.append(Port(self,port['protocol'],port['port'],port['port_to'])) else: self.ports.append(Port(self,port['protocol'],port['port'])) return(self.Update())
python
def AddPorts(self,ports): """Create one or more port access policies. Include a list of dicts with protocol, port, and port_to (optional - for range) keys. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0] .AddPorts([{'protocol': 'TCP', 'port': '80' }, {'protocol': 'UDP', 'port': '10000', 'port_to': '15000'}]).WaitUntilComplete() 0 """ for port in ports: if 'port_to' in port: self.ports.append(Port(self,port['protocol'],port['port'],port['port_to'])) else: self.ports.append(Port(self,port['protocol'],port['port'])) return(self.Update())
[ "def", "AddPorts", "(", "self", ",", "ports", ")", ":", "for", "port", "in", "ports", ":", "if", "'port_to'", "in", "port", ":", "self", ".", "ports", ".", "append", "(", "Port", "(", "self", ",", "port", "[", "'protocol'", "]", ",", "port", "[", "'port'", "]", ",", "port", "[", "'port_to'", "]", ")", ")", "else", ":", "self", ".", "ports", ".", "append", "(", "Port", "(", "self", ",", "port", "[", "'protocol'", "]", ",", "port", "[", "'port'", "]", ")", ")", "return", "(", "self", ".", "Update", "(", ")", ")" ]
Create one or more port access policies. Include a list of dicts with protocol, port, and port_to (optional - for range) keys. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0] .AddPorts([{'protocol': 'TCP', 'port': '80' }, {'protocol': 'UDP', 'port': '10000', 'port_to': '15000'}]).WaitUntilComplete() 0
[ "Create", "one", "or", "more", "port", "access", "policies", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L200-L216
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/public_ip.py
PublicIP.AddSourceRestriction
def AddSourceRestriction(self,cidr): """Add and commit a single source IP restriction policy. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0] .AddSourceRestriction(cidr="132.200.20.1/32").WaitUntilComplete() 0 """ self.source_restrictions.append(SourceRestriction(self,cidr)) return(self.Update())
python
def AddSourceRestriction(self,cidr): """Add and commit a single source IP restriction policy. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0] .AddSourceRestriction(cidr="132.200.20.1/32").WaitUntilComplete() 0 """ self.source_restrictions.append(SourceRestriction(self,cidr)) return(self.Update())
[ "def", "AddSourceRestriction", "(", "self", ",", "cidr", ")", ":", "self", ".", "source_restrictions", ".", "append", "(", "SourceRestriction", "(", "self", ",", "cidr", ")", ")", "return", "(", "self", ".", "Update", "(", ")", ")" ]
Add and commit a single source IP restriction policy. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0] .AddSourceRestriction(cidr="132.200.20.1/32").WaitUntilComplete() 0
[ "Add", "and", "commit", "a", "single", "source", "IP", "restriction", "policy", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L219-L230
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/public_ip.py
PublicIP.AddSourceRestrictions
def AddSourceRestrictions(self,cidrs): """Create one or more CIDR source restriction policies. Include a list of CIDR strings. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0] .AddSourceRestrictions(cidrs=["132.200.20.1/32","132.200.20.100/32"]).WaitUntilComplete() 0 """ for cidr in cidrs: self.source_restrictions.append(SourceRestriction(self,cidr)) return(self.Update())
python
def AddSourceRestrictions(self,cidrs): """Create one or more CIDR source restriction policies. Include a list of CIDR strings. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0] .AddSourceRestrictions(cidrs=["132.200.20.1/32","132.200.20.100/32"]).WaitUntilComplete() 0 """ for cidr in cidrs: self.source_restrictions.append(SourceRestriction(self,cidr)) return(self.Update())
[ "def", "AddSourceRestrictions", "(", "self", ",", "cidrs", ")", ":", "for", "cidr", "in", "cidrs", ":", "self", ".", "source_restrictions", ".", "append", "(", "SourceRestriction", "(", "self", ",", "cidr", ")", ")", "return", "(", "self", ".", "Update", "(", ")", ")" ]
Create one or more CIDR source restriction policies. Include a list of CIDR strings. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0] .AddSourceRestrictions(cidrs=["132.200.20.1/32","132.200.20.100/32"]).WaitUntilComplete() 0
[ "Create", "one", "or", "more", "CIDR", "source", "restriction", "policies", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L233-L246
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/public_ip.py
Port.Delete
def Delete(self): """Delete this port and commit change to cloud. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].ports[0].Delete().WaitUntilComplete() 0 """ self.public_ip.ports = [o for o in self.public_ip.ports if o!=self] return(self.public_ip.Update())
python
def Delete(self): """Delete this port and commit change to cloud. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].ports[0].Delete().WaitUntilComplete() 0 """ self.public_ip.ports = [o for o in self.public_ip.ports if o!=self] return(self.public_ip.Update())
[ "def", "Delete", "(", "self", ")", ":", "self", ".", "public_ip", ".", "ports", "=", "[", "o", "for", "o", "in", "self", ".", "public_ip", ".", "ports", "if", "o", "!=", "self", "]", "return", "(", "self", ".", "public_ip", ".", "Update", "(", ")", ")" ]
Delete this port and commit change to cloud. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].ports[0].Delete().WaitUntilComplete() 0
[ "Delete", "this", "port", "and", "commit", "change", "to", "cloud", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L274-L284
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/public_ip.py
SourceRestriction.Delete
def Delete(self): """Delete this source restriction and commit change to cloud. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].source_restrictions[0].Delete().WaitUntilComplete() 0 """ self.public_ip.source_restrictions = [o for o in self.public_ip.source_restrictions if o!=self] return(self.public_ip.Update())
python
def Delete(self): """Delete this source restriction and commit change to cloud. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].source_restrictions[0].Delete().WaitUntilComplete() 0 """ self.public_ip.source_restrictions = [o for o in self.public_ip.source_restrictions if o!=self] return(self.public_ip.Update())
[ "def", "Delete", "(", "self", ")", ":", "self", ".", "public_ip", ".", "source_restrictions", "=", "[", "o", "for", "o", "in", "self", ".", "public_ip", ".", "source_restrictions", "if", "o", "!=", "self", "]", "return", "(", "self", ".", "public_ip", ".", "Update", "(", ")", ")" ]
Delete this source restriction and commit change to cloud. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].source_restrictions[0].Delete().WaitUntilComplete() 0
[ "Delete", "this", "source", "restriction", "and", "commit", "change", "to", "cloud", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L308-L318
train
kamicut/tilepie
tilepie/proj.py
GoogleProjection.tile_bbox
def tile_bbox(self, tile_indices): """ Returns the WGS84 bbox of the specified tile """ (z, x, y) = tile_indices topleft = (x * self.tilesize, (y + 1) * self.tilesize) bottomright = ((x + 1) * self.tilesize, y * self.tilesize) nw = self.unproject_pixels(topleft, z) se = self.unproject_pixels(bottomright, z) return nw + se
python
def tile_bbox(self, tile_indices): """ Returns the WGS84 bbox of the specified tile """ (z, x, y) = tile_indices topleft = (x * self.tilesize, (y + 1) * self.tilesize) bottomright = ((x + 1) * self.tilesize, y * self.tilesize) nw = self.unproject_pixels(topleft, z) se = self.unproject_pixels(bottomright, z) return nw + se
[ "def", "tile_bbox", "(", "self", ",", "tile_indices", ")", ":", "(", "z", ",", "x", ",", "y", ")", "=", "tile_indices", "topleft", "=", "(", "x", "*", "self", ".", "tilesize", ",", "(", "y", "+", "1", ")", "*", "self", ".", "tilesize", ")", "bottomright", "=", "(", "(", "x", "+", "1", ")", "*", "self", ".", "tilesize", ",", "y", "*", "self", ".", "tilesize", ")", "nw", "=", "self", ".", "unproject_pixels", "(", "topleft", ",", "z", ")", "se", "=", "self", ".", "unproject_pixels", "(", "bottomright", ",", "z", ")", "return", "nw", "+", "se" ]
Returns the WGS84 bbox of the specified tile
[ "Returns", "the", "WGS84", "bbox", "of", "the", "specified", "tile" ]
103ae2be1c3c4e6f7ec4a3bdd265ffcddee92b96
https://github.com/kamicut/tilepie/blob/103ae2be1c3c4e6f7ec4a3bdd265ffcddee92b96/tilepie/proj.py#L73-L82
train
kamicut/tilepie
tilepie/proj.py
GoogleProjection.unproject
def unproject(self, xy): """ Returns the coordinates from position in meters """ (x, y) = xy lng = x/EARTH_RADIUS * RAD_TO_DEG lat = 2 * atan(exp(y/EARTH_RADIUS)) - pi/2 * RAD_TO_DEG return (lng, lat)
python
def unproject(self, xy): """ Returns the coordinates from position in meters """ (x, y) = xy lng = x/EARTH_RADIUS * RAD_TO_DEG lat = 2 * atan(exp(y/EARTH_RADIUS)) - pi/2 * RAD_TO_DEG return (lng, lat)
[ "def", "unproject", "(", "self", ",", "xy", ")", ":", "(", "x", ",", "y", ")", "=", "xy", "lng", "=", "x", "/", "EARTH_RADIUS", "*", "RAD_TO_DEG", "lat", "=", "2", "*", "atan", "(", "exp", "(", "y", "/", "EARTH_RADIUS", ")", ")", "-", "pi", "/", "2", "*", "RAD_TO_DEG", "return", "(", "lng", ",", "lat", ")" ]
Returns the coordinates from position in meters
[ "Returns", "the", "coordinates", "from", "position", "in", "meters" ]
103ae2be1c3c4e6f7ec4a3bdd265ffcddee92b96
https://github.com/kamicut/tilepie/blob/103ae2be1c3c4e6f7ec4a3bdd265ffcddee92b96/tilepie/proj.py#L95-L102
train
nuclio/nuclio-sdk-py
nuclio_sdk/response.py
Response.from_entrypoint_output
def from_entrypoint_output(json_encoder, handler_output): """Given a handler output's type, generates a response towards the processor""" response = { 'body': '', 'content_type': 'text/plain', 'headers': {}, 'status_code': 200, 'body_encoding': 'text', } # if the type of the output is a string, just return that and 200 if isinstance(handler_output, str): response['body'] = handler_output # if it's a tuple of 2 elements, first is status second is body elif isinstance(handler_output, tuple) and len(handler_output) == 2: response['status_code'] = handler_output[0] if isinstance(handler_output[1], str): response['body'] = handler_output[1] else: response['body'] = json_encoder(handler_output[1]) response['content_type'] = 'application/json' # if it's a dict, populate the response and set content type to json elif isinstance(handler_output, dict) or isinstance(handler_output, list): response['content_type'] = 'application/json' response['body'] = json_encoder(handler_output) # if it's a response object, populate the response elif isinstance(handler_output, Response): if isinstance(handler_output.body, dict): response['body'] = json.dumps(handler_output.body) response['content_type'] = 'application/json' else: response['body'] = handler_output.body response['content_type'] = handler_output.content_type response['headers'] = handler_output.headers response['status_code'] = handler_output.status_code else: response['body'] = handler_output if isinstance(response['body'], bytes): response['body'] = base64.b64encode(response['body']).decode('ascii') response['body_encoding'] = 'base64' return response
python
def from_entrypoint_output(json_encoder, handler_output): """Given a handler output's type, generates a response towards the processor""" response = { 'body': '', 'content_type': 'text/plain', 'headers': {}, 'status_code': 200, 'body_encoding': 'text', } # if the type of the output is a string, just return that and 200 if isinstance(handler_output, str): response['body'] = handler_output # if it's a tuple of 2 elements, first is status second is body elif isinstance(handler_output, tuple) and len(handler_output) == 2: response['status_code'] = handler_output[0] if isinstance(handler_output[1], str): response['body'] = handler_output[1] else: response['body'] = json_encoder(handler_output[1]) response['content_type'] = 'application/json' # if it's a dict, populate the response and set content type to json elif isinstance(handler_output, dict) or isinstance(handler_output, list): response['content_type'] = 'application/json' response['body'] = json_encoder(handler_output) # if it's a response object, populate the response elif isinstance(handler_output, Response): if isinstance(handler_output.body, dict): response['body'] = json.dumps(handler_output.body) response['content_type'] = 'application/json' else: response['body'] = handler_output.body response['content_type'] = handler_output.content_type response['headers'] = handler_output.headers response['status_code'] = handler_output.status_code else: response['body'] = handler_output if isinstance(response['body'], bytes): response['body'] = base64.b64encode(response['body']).decode('ascii') response['body_encoding'] = 'base64' return response
[ "def", "from_entrypoint_output", "(", "json_encoder", ",", "handler_output", ")", ":", "response", "=", "{", "'body'", ":", "''", ",", "'content_type'", ":", "'text/plain'", ",", "'headers'", ":", "{", "}", ",", "'status_code'", ":", "200", ",", "'body_encoding'", ":", "'text'", ",", "}", "# if the type of the output is a string, just return that and 200", "if", "isinstance", "(", "handler_output", ",", "str", ")", ":", "response", "[", "'body'", "]", "=", "handler_output", "# if it's a tuple of 2 elements, first is status second is body", "elif", "isinstance", "(", "handler_output", ",", "tuple", ")", "and", "len", "(", "handler_output", ")", "==", "2", ":", "response", "[", "'status_code'", "]", "=", "handler_output", "[", "0", "]", "if", "isinstance", "(", "handler_output", "[", "1", "]", ",", "str", ")", ":", "response", "[", "'body'", "]", "=", "handler_output", "[", "1", "]", "else", ":", "response", "[", "'body'", "]", "=", "json_encoder", "(", "handler_output", "[", "1", "]", ")", "response", "[", "'content_type'", "]", "=", "'application/json'", "# if it's a dict, populate the response and set content type to json", "elif", "isinstance", "(", "handler_output", ",", "dict", ")", "or", "isinstance", "(", "handler_output", ",", "list", ")", ":", "response", "[", "'content_type'", "]", "=", "'application/json'", "response", "[", "'body'", "]", "=", "json_encoder", "(", "handler_output", ")", "# if it's a response object, populate the response", "elif", "isinstance", "(", "handler_output", ",", "Response", ")", ":", "if", "isinstance", "(", "handler_output", ".", "body", ",", "dict", ")", ":", "response", "[", "'body'", "]", "=", "json", ".", "dumps", "(", "handler_output", ".", "body", ")", "response", "[", "'content_type'", "]", "=", "'application/json'", "else", ":", "response", "[", "'body'", "]", "=", "handler_output", ".", "body", "response", "[", "'content_type'", "]", "=", "handler_output", ".", "content_type", "response", "[", "'headers'", "]", "=", "handler_output", ".", "headers", "response", "[", "'status_code'", "]", "=", "handler_output", ".", "status_code", "else", ":", "response", "[", "'body'", "]", "=", "handler_output", "if", "isinstance", "(", "response", "[", "'body'", "]", ",", "bytes", ")", ":", "response", "[", "'body'", "]", "=", "base64", ".", "b64encode", "(", "response", "[", "'body'", "]", ")", ".", "decode", "(", "'ascii'", ")", "response", "[", "'body_encoding'", "]", "=", "'base64'", "return", "response" ]
Given a handler output's type, generates a response towards the processor
[ "Given", "a", "handler", "output", "s", "type", "generates", "a", "response", "towards", "the", "processor" ]
5af9ffc19a0d96255ff430bc358be9cd7a57f424
https://github.com/nuclio/nuclio-sdk-py/blob/5af9ffc19a0d96255ff430bc358be9cd7a57f424/nuclio_sdk/response.py#L34-L83
train
mjirik/imtools
imtools/sample_data.py
check_python_architecture
def check_python_architecture(pythondir, target_arch_str): """ functions check architecture of target python """ pyth_str = subprocess.check_output( [pythondir + 'python', '-c', 'import platform; print platform.architecture()[0]']) if pyth_str[:2] != target_arch_str: raise Exception( "Wrong architecture of target python. Expected arch is" + target_arch_str)
python
def check_python_architecture(pythondir, target_arch_str): """ functions check architecture of target python """ pyth_str = subprocess.check_output( [pythondir + 'python', '-c', 'import platform; print platform.architecture()[0]']) if pyth_str[:2] != target_arch_str: raise Exception( "Wrong architecture of target python. Expected arch is" + target_arch_str)
[ "def", "check_python_architecture", "(", "pythondir", ",", "target_arch_str", ")", ":", "pyth_str", "=", "subprocess", ".", "check_output", "(", "[", "pythondir", "+", "'python'", ",", "'-c'", ",", "'import platform; print platform.architecture()[0]'", "]", ")", "if", "pyth_str", "[", ":", "2", "]", "!=", "target_arch_str", ":", "raise", "Exception", "(", "\"Wrong architecture of target python. Expected arch is\"", "+", "target_arch_str", ")" ]
functions check architecture of target python
[ "functions", "check", "architecture", "of", "target", "python" ]
eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a
https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/sample_data.py#L42-L52
train
mjirik/imtools
imtools/sample_data.py
downzip
def downzip(url, destination='./sample_data/'): """ Download, unzip and delete. """ # url = "http://147.228.240.61/queetech/sample-data/jatra_06mm_jenjatra.zip" logmsg = "downloading from '" + url + "'" print(logmsg) logger.debug(logmsg) local_file_name = os.path.join(destination, 'tmp.zip') urllibr.urlretrieve(url, local_file_name) datafile = zipfile.ZipFile(local_file_name) datafile.extractall(destination) remove(local_file_name)
python
def downzip(url, destination='./sample_data/'): """ Download, unzip and delete. """ # url = "http://147.228.240.61/queetech/sample-data/jatra_06mm_jenjatra.zip" logmsg = "downloading from '" + url + "'" print(logmsg) logger.debug(logmsg) local_file_name = os.path.join(destination, 'tmp.zip') urllibr.urlretrieve(url, local_file_name) datafile = zipfile.ZipFile(local_file_name) datafile.extractall(destination) remove(local_file_name)
[ "def", "downzip", "(", "url", ",", "destination", "=", "'./sample_data/'", ")", ":", "# url = \"http://147.228.240.61/queetech/sample-data/jatra_06mm_jenjatra.zip\"", "logmsg", "=", "\"downloading from '\"", "+", "url", "+", "\"'\"", "print", "(", "logmsg", ")", "logger", ".", "debug", "(", "logmsg", ")", "local_file_name", "=", "os", ".", "path", ".", "join", "(", "destination", ",", "'tmp.zip'", ")", "urllibr", ".", "urlretrieve", "(", "url", ",", "local_file_name", ")", "datafile", "=", "zipfile", ".", "ZipFile", "(", "local_file_name", ")", "datafile", ".", "extractall", "(", "destination", ")", "remove", "(", "local_file_name", ")" ]
Download, unzip and delete.
[ "Download", "unzip", "and", "delete", "." ]
eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a
https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/sample_data.py#L64-L77
train
mjirik/imtools
imtools/sample_data.py
checksum
def checksum(path, hashfunc='md5'): """ Return checksum given by path. Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'. :param path: :param hashfunc: :return: """ import checksumdir hash_func = checksumdir.HASH_FUNCS.get(hashfunc) if not hash_func: raise NotImplementedError('{} not implemented.'.format(hashfunc)) if os.path.isdir(path): return checksumdir.dirhash(path, hashfunc=hashfunc) hashvalues = [] path_list = glob.glob(path) logger.debug("path_list " + str(path_list)) for path in path_list: if os.path.isfile(path): hashvalues.append(checksumdir._filehash(path, hashfunc=hash_func)) logger.debug(str(hashvalues)) hash = checksumdir._reduce_hash(hashvalues, hashfunc=hash_func) return hash
python
def checksum(path, hashfunc='md5'): """ Return checksum given by path. Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'. :param path: :param hashfunc: :return: """ import checksumdir hash_func = checksumdir.HASH_FUNCS.get(hashfunc) if not hash_func: raise NotImplementedError('{} not implemented.'.format(hashfunc)) if os.path.isdir(path): return checksumdir.dirhash(path, hashfunc=hashfunc) hashvalues = [] path_list = glob.glob(path) logger.debug("path_list " + str(path_list)) for path in path_list: if os.path.isfile(path): hashvalues.append(checksumdir._filehash(path, hashfunc=hash_func)) logger.debug(str(hashvalues)) hash = checksumdir._reduce_hash(hashvalues, hashfunc=hash_func) return hash
[ "def", "checksum", "(", "path", ",", "hashfunc", "=", "'md5'", ")", ":", "import", "checksumdir", "hash_func", "=", "checksumdir", ".", "HASH_FUNCS", ".", "get", "(", "hashfunc", ")", "if", "not", "hash_func", ":", "raise", "NotImplementedError", "(", "'{} not implemented.'", ".", "format", "(", "hashfunc", ")", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "return", "checksumdir", ".", "dirhash", "(", "path", ",", "hashfunc", "=", "hashfunc", ")", "hashvalues", "=", "[", "]", "path_list", "=", "glob", ".", "glob", "(", "path", ")", "logger", ".", "debug", "(", "\"path_list \"", "+", "str", "(", "path_list", ")", ")", "for", "path", "in", "path_list", ":", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "hashvalues", ".", "append", "(", "checksumdir", ".", "_filehash", "(", "path", ",", "hashfunc", "=", "hash_func", ")", ")", "logger", ".", "debug", "(", "str", "(", "hashvalues", ")", ")", "hash", "=", "checksumdir", ".", "_reduce_hash", "(", "hashvalues", ",", "hashfunc", "=", "hash_func", ")", "return", "hash" ]
Return checksum given by path. Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'. :param path: :param hashfunc: :return:
[ "Return", "checksum", "given", "by", "path", ".", "Wildcards", "can", "be", "used", "in", "check", "sum", ".", "Function", "is", "strongly", "dependent", "on", "checksumdir", "package", "by", "cakepietoast", "." ]
eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a
https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/sample_data.py#L166-L191
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/disk.py
Disks.Get
def Get(self,key): """Get disk by providing mount point or ID If key is not unique and finds multiple matches only the first will be returned """ for disk in self.disks: if disk.id == key: return(disk) elif key in disk.partition_paths: return(disk)
python
def Get(self,key): """Get disk by providing mount point or ID If key is not unique and finds multiple matches only the first will be returned """ for disk in self.disks: if disk.id == key: return(disk) elif key in disk.partition_paths: return(disk)
[ "def", "Get", "(", "self", ",", "key", ")", ":", "for", "disk", "in", "self", ".", "disks", ":", "if", "disk", ".", "id", "==", "key", ":", "return", "(", "disk", ")", "elif", "key", "in", "disk", ".", "partition_paths", ":", "return", "(", "disk", ")" ]
Get disk by providing mount point or ID If key is not unique and finds multiple matches only the first will be returned
[ "Get", "disk", "by", "providing", "mount", "point", "or", "ID" ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/disk.py#L31-L40
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/disk.py
Disks.Search
def Search(self,key): """Search disk list by partial mount point or ID """ results = [] for disk in self.disks: if disk.id.lower().find(key.lower()) != -1: results.append(disk) # TODO - search in list to match partial mount points elif key.lower() in disk.partition_paths: results.append(disk) return(results)
python
def Search(self,key): """Search disk list by partial mount point or ID """ results = [] for disk in self.disks: if disk.id.lower().find(key.lower()) != -1: results.append(disk) # TODO - search in list to match partial mount points elif key.lower() in disk.partition_paths: results.append(disk) return(results)
[ "def", "Search", "(", "self", ",", "key", ")", ":", "results", "=", "[", "]", "for", "disk", "in", "self", ".", "disks", ":", "if", "disk", ".", "id", ".", "lower", "(", ")", ".", "find", "(", "key", ".", "lower", "(", ")", ")", "!=", "-", "1", ":", "results", ".", "append", "(", "disk", ")", "# TODO - search in list to match partial mount points", "elif", "key", ".", "lower", "(", ")", "in", "disk", ".", "partition_paths", ":", "results", ".", "append", "(", "disk", ")", "return", "(", "results", ")" ]
Search disk list by partial mount point or ID
[ "Search", "disk", "list", "by", "partial", "mount", "point", "or", "ID" ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/disk.py#L43-L54
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/disk.py
Disks.Add
def Add(self,size,path=None,type="partitioned"): """Add new disk. This request will error if disk is protected and cannot be removed (e.g. a system disk) # Partitioned disk >>> clc.v2.Server("WA1BTDIX01").Disks().Add(size=20,path=None,type="raw").WaitUntilComplete() 0 # Raw disk >>> clc.v2.Server("WA1BTDIX01").Disks().Add(size=20,path=None,type="raw").WaitUntilComplete() 0 """ if type=="partitioned" and not path: raise(clc.CLCException("Must specify path to mount new disk")) # TODO - Raise exception if too many disks # TODO - Raise exception if too much total size (4TB standard, 1TB HS) disk_set = [{'diskId': o.id, 'sizeGB': o.size} for o in self.disks] disk_set.append({'sizeGB': size, 'type': type, 'path': path}) self.disks.append(Disk(id=int(time.time()),parent=self,disk_obj={'sizeGB': size,'partitionPaths': [path]},session=self.session)) self.size = size self.server.dirty = True return(clc.v2.Requests(clc.v2.API.Call('PATCH','servers/%s/%s' % (self.server.alias,self.server.id), json.dumps([{"op": "set", "member": "disks", "value": disk_set}]), session=self.session), alias=self.server.alias, session=self.session))
python
def Add(self,size,path=None,type="partitioned"): """Add new disk. This request will error if disk is protected and cannot be removed (e.g. a system disk) # Partitioned disk >>> clc.v2.Server("WA1BTDIX01").Disks().Add(size=20,path=None,type="raw").WaitUntilComplete() 0 # Raw disk >>> clc.v2.Server("WA1BTDIX01").Disks().Add(size=20,path=None,type="raw").WaitUntilComplete() 0 """ if type=="partitioned" and not path: raise(clc.CLCException("Must specify path to mount new disk")) # TODO - Raise exception if too many disks # TODO - Raise exception if too much total size (4TB standard, 1TB HS) disk_set = [{'diskId': o.id, 'sizeGB': o.size} for o in self.disks] disk_set.append({'sizeGB': size, 'type': type, 'path': path}) self.disks.append(Disk(id=int(time.time()),parent=self,disk_obj={'sizeGB': size,'partitionPaths': [path]},session=self.session)) self.size = size self.server.dirty = True return(clc.v2.Requests(clc.v2.API.Call('PATCH','servers/%s/%s' % (self.server.alias,self.server.id), json.dumps([{"op": "set", "member": "disks", "value": disk_set}]), session=self.session), alias=self.server.alias, session=self.session))
[ "def", "Add", "(", "self", ",", "size", ",", "path", "=", "None", ",", "type", "=", "\"partitioned\"", ")", ":", "if", "type", "==", "\"partitioned\"", "and", "not", "path", ":", "raise", "(", "clc", ".", "CLCException", "(", "\"Must specify path to mount new disk\"", ")", ")", "# TODO - Raise exception if too many disks", "# TODO - Raise exception if too much total size (4TB standard, 1TB HS)", "disk_set", "=", "[", "{", "'diskId'", ":", "o", ".", "id", ",", "'sizeGB'", ":", "o", ".", "size", "}", "for", "o", "in", "self", ".", "disks", "]", "disk_set", ".", "append", "(", "{", "'sizeGB'", ":", "size", ",", "'type'", ":", "type", ",", "'path'", ":", "path", "}", ")", "self", ".", "disks", ".", "append", "(", "Disk", "(", "id", "=", "int", "(", "time", ".", "time", "(", ")", ")", ",", "parent", "=", "self", ",", "disk_obj", "=", "{", "'sizeGB'", ":", "size", ",", "'partitionPaths'", ":", "[", "path", "]", "}", ",", "session", "=", "self", ".", "session", ")", ")", "self", ".", "size", "=", "size", "self", ".", "server", ".", "dirty", "=", "True", "return", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'PATCH'", ",", "'servers/%s/%s'", "%", "(", "self", ".", "server", ".", "alias", ",", "self", ".", "server", ".", "id", ")", ",", "json", ".", "dumps", "(", "[", "{", "\"op\"", ":", "\"set\"", ",", "\"member\"", ":", "\"disks\"", ",", "\"value\"", ":", "disk_set", "}", "]", ")", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "server", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Add new disk. This request will error if disk is protected and cannot be removed (e.g. a system disk) # Partitioned disk >>> clc.v2.Server("WA1BTDIX01").Disks().Add(size=20,path=None,type="raw").WaitUntilComplete() 0 # Raw disk >>> clc.v2.Server("WA1BTDIX01").Disks().Add(size=20,path=None,type="raw").WaitUntilComplete() 0
[ "Add", "new", "disk", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/disk.py#L57-L86
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/disk.py
Disk.Grow
def Grow(self,size): """Grow disk to the newly specified size. Size must be less than 1024 and must be greater than the current size. >>> clc.v2.Server("WA1BTDIX01").Disks().disks[2].Grow(30).WaitUntilComplete() 0 """ if size>1024: raise(clc.CLCException("Cannot grow disk beyond 1024GB")) if size<=self.size: raise(clc.CLCException("New size must exceed current disk size")) # TODO - Raise exception if too much total size (4TB standard, 1TB HS) disk_set = [{'diskId': o.id, 'sizeGB': o.size} for o in self.parent.disks if o!=self] self.size = size disk_set.append({'diskId': self.id, 'sizeGB': self.size}) self.parent.server.dirty = True return(clc.v2.Requests(clc.v2.API.Call('PATCH','servers/%s/%s' % (self.parent.server.alias,self.parent.server.id), json.dumps([{"op": "set", "member": "disks", "value": disk_set}]), session=self.session), alias=self.parent.server.alias, session=self.session))
python
def Grow(self,size): """Grow disk to the newly specified size. Size must be less than 1024 and must be greater than the current size. >>> clc.v2.Server("WA1BTDIX01").Disks().disks[2].Grow(30).WaitUntilComplete() 0 """ if size>1024: raise(clc.CLCException("Cannot grow disk beyond 1024GB")) if size<=self.size: raise(clc.CLCException("New size must exceed current disk size")) # TODO - Raise exception if too much total size (4TB standard, 1TB HS) disk_set = [{'diskId': o.id, 'sizeGB': o.size} for o in self.parent.disks if o!=self] self.size = size disk_set.append({'diskId': self.id, 'sizeGB': self.size}) self.parent.server.dirty = True return(clc.v2.Requests(clc.v2.API.Call('PATCH','servers/%s/%s' % (self.parent.server.alias,self.parent.server.id), json.dumps([{"op": "set", "member": "disks", "value": disk_set}]), session=self.session), alias=self.parent.server.alias, session=self.session))
[ "def", "Grow", "(", "self", ",", "size", ")", ":", "if", "size", ">", "1024", ":", "raise", "(", "clc", ".", "CLCException", "(", "\"Cannot grow disk beyond 1024GB\"", ")", ")", "if", "size", "<=", "self", ".", "size", ":", "raise", "(", "clc", ".", "CLCException", "(", "\"New size must exceed current disk size\"", ")", ")", "# TODO - Raise exception if too much total size (4TB standard, 1TB HS)", "disk_set", "=", "[", "{", "'diskId'", ":", "o", ".", "id", ",", "'sizeGB'", ":", "o", ".", "size", "}", "for", "o", "in", "self", ".", "parent", ".", "disks", "if", "o", "!=", "self", "]", "self", ".", "size", "=", "size", "disk_set", ".", "append", "(", "{", "'diskId'", ":", "self", ".", "id", ",", "'sizeGB'", ":", "self", ".", "size", "}", ")", "self", ".", "parent", ".", "server", ".", "dirty", "=", "True", "return", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'PATCH'", ",", "'servers/%s/%s'", "%", "(", "self", ".", "parent", ".", "server", ".", "alias", ",", "self", ".", "parent", ".", "server", ".", "id", ")", ",", "json", ".", "dumps", "(", "[", "{", "\"op\"", ":", "\"set\"", ",", "\"member\"", ":", "\"disks\"", ",", "\"value\"", ":", "disk_set", "}", "]", ")", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "parent", ".", "server", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Grow disk to the newly specified size. Size must be less than 1024 and must be greater than the current size. >>> clc.v2.Server("WA1BTDIX01").Disks().disks[2].Grow(30).WaitUntilComplete() 0
[ "Grow", "disk", "to", "the", "newly", "specified", "size", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/disk.py#L102-L125
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/disk.py
Disk.Delete
def Delete(self): """Delete disk. This request will error if disk is protected and cannot be removed (e.g. a system disk) >>> clc.v2.Server("WA1BTDIX01").Disks().disks[2].Delete().WaitUntilComplete() 0 """ disk_set = [{'diskId': o.id, 'sizeGB': o.size} for o in self.parent.disks if o!=self] self.parent.disks = [o for o in self.parent.disks if o!=self] self.parent.server.dirty = True return(clc.v2.Requests(clc.v2.API.Call('PATCH','servers/%s/%s' % (self.parent.server.alias,self.parent.server.id), json.dumps([{"op": "set", "member": "disks", "value": disk_set}]), session=self.session), alias=self.parent.server.alias, session=self.session))
python
def Delete(self): """Delete disk. This request will error if disk is protected and cannot be removed (e.g. a system disk) >>> clc.v2.Server("WA1BTDIX01").Disks().disks[2].Delete().WaitUntilComplete() 0 """ disk_set = [{'diskId': o.id, 'sizeGB': o.size} for o in self.parent.disks if o!=self] self.parent.disks = [o for o in self.parent.disks if o!=self] self.parent.server.dirty = True return(clc.v2.Requests(clc.v2.API.Call('PATCH','servers/%s/%s' % (self.parent.server.alias,self.parent.server.id), json.dumps([{"op": "set", "member": "disks", "value": disk_set}]), session=self.session), alias=self.parent.server.alias, session=self.session))
[ "def", "Delete", "(", "self", ")", ":", "disk_set", "=", "[", "{", "'diskId'", ":", "o", ".", "id", ",", "'sizeGB'", ":", "o", ".", "size", "}", "for", "o", "in", "self", ".", "parent", ".", "disks", "if", "o", "!=", "self", "]", "self", ".", "parent", ".", "disks", "=", "[", "o", "for", "o", "in", "self", ".", "parent", ".", "disks", "if", "o", "!=", "self", "]", "self", ".", "parent", ".", "server", ".", "dirty", "=", "True", "return", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'PATCH'", ",", "'servers/%s/%s'", "%", "(", "self", ".", "parent", ".", "server", ".", "alias", ",", "self", ".", "parent", ".", "server", ".", "id", ")", ",", "json", ".", "dumps", "(", "[", "{", "\"op\"", ":", "\"set\"", ",", "\"member\"", ":", "\"disks\"", ",", "\"value\"", ":", "disk_set", "}", "]", ")", ",", "session", "=", "self", ".", "session", ")", ",", "alias", "=", "self", ".", "parent", ".", "server", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
Delete disk. This request will error if disk is protected and cannot be removed (e.g. a system disk) >>> clc.v2.Server("WA1BTDIX01").Disks().disks[2].Delete().WaitUntilComplete() 0
[ "Delete", "disk", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/disk.py#L128-L145
train
sio2project/filetracker
filetracker/utils.py
file_digest
def file_digest(source): """Calculates SHA256 digest of a file. Args: source: either a file-like object or a path to file """ hash_sha256 = hashlib.sha256() should_close = False if isinstance(source, six.string_types): should_close = True source = open(source, 'rb') for chunk in iter(lambda: source.read(_BUFFER_SIZE), b''): hash_sha256.update(chunk) if should_close: source.close() return hash_sha256.hexdigest()
python
def file_digest(source): """Calculates SHA256 digest of a file. Args: source: either a file-like object or a path to file """ hash_sha256 = hashlib.sha256() should_close = False if isinstance(source, six.string_types): should_close = True source = open(source, 'rb') for chunk in iter(lambda: source.read(_BUFFER_SIZE), b''): hash_sha256.update(chunk) if should_close: source.close() return hash_sha256.hexdigest()
[ "def", "file_digest", "(", "source", ")", ":", "hash_sha256", "=", "hashlib", ".", "sha256", "(", ")", "should_close", "=", "False", "if", "isinstance", "(", "source", ",", "six", ".", "string_types", ")", ":", "should_close", "=", "True", "source", "=", "open", "(", "source", ",", "'rb'", ")", "for", "chunk", "in", "iter", "(", "lambda", ":", "source", ".", "read", "(", "_BUFFER_SIZE", ")", ",", "b''", ")", ":", "hash_sha256", ".", "update", "(", "chunk", ")", "if", "should_close", ":", "source", ".", "close", "(", ")", "return", "hash_sha256", ".", "hexdigest", "(", ")" ]
Calculates SHA256 digest of a file. Args: source: either a file-like object or a path to file
[ "Calculates", "SHA256", "digest", "of", "a", "file", "." ]
359b474850622e3d0c25ee2596d7242c02f84efb
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/utils.py#L68-L88
train