INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Just a simple generator that creates a network with n nodes and n_edges edges. Edges are assigned randomly only avoiding self loops.
def mygenerator(n=5, n_edges=5): ''' Just a simple generator that creates a network with n nodes and n_edges edges. Edges are assigned randomly, only avoiding self loops. ''' G = nx.Graph() for i in range(n): G.add_node(i) for i in range(n_edges): nodes = list(G.nodes) ...
Internal method to import instance variables data from a dictionary
def _import(self, datadict): """ Internal method to import instance variables data from a dictionary :param dict datadict: The dictionary containing variables values. """ self.GUID = datadict.get("GUID", uuid.uuid1()) self.FileName = datadict.get("FileName", "") ...
Creates a: class: ~vsgen. project. VSGProject from a: class: ~configparser. ConfigParser section.
def from_section(cls, config, section, **kwargs): """ Creates a :class:`~vsgen.project.VSGProject` from a :class:`~configparser.ConfigParser` section. :param ConfigParser config: A :class:`~configparser.ConfigParser` instance. :param str section: A :class:`~configparser.Conf...
Returns the: attr: ProjectHome relative to: attr: FileName directory.
def ProjectHomeRelative(self): """ Returns the :attr:`ProjectHome` relative to :attr:`FileName` directory. """ return os.path.relpath(self.ProjectHome, os.path.dirname(self.FileName))
Returns the: attr: StartupFile relative to: attr: ProjectHome directory.
def StartupFileRelative(self): """ Returns the :attr:`StartupFile` relative to :attr:`ProjectHome` directory. """ return os.path.relpath(self.StartupFile, self.ProjectHome) if self.StartupFile else self.StartupFile
Returns a generator iterating over the each file in: attr: ContentFiles relative to: attr: ProjectHome directory.
def ContentFilesRelative(self): """ Returns a generator iterating over the each file in :attr:`ContentFiles` relative to :attr:`ProjectHome` directory. """ return (os.path.relpath(path, self.ProjectHome) for path in sorted(self.ContentFiles, key=self.lower))
Returns a generator iterating over the each file in: attr: ContentFiles relative to: attr: ProjectHome directory.
def CompileFilesRelative(self): """ Returns a generator iterating over the each file in :attr:`ContentFiles` relative to :attr:`ProjectHome` directory. """ return (os.path.relpath(path, self.ProjectHome) for path in sorted(self.CompileFiles, key=self.lower))
Returns a generator iterating over the each directory referenced by the project relative to: attr: ProjectHome directory.
def DirectoriesRelative(self): """ Returns a generator iterating over the each directory referenced by the project, relative to :attr:`ProjectHome` directory. """ # Acquire all directories directories = itertools.chain(self.Directories, (os.path.dirname(f) for f in itertools.chai...
Inserts files by recursive traversing the rootpath and inserting files according the addition filter parameters.
def insert_files(self, rootpath, directoryInFilter=None, directoryExFilter=None, compileInFilter=None, compileExFilter=None, contentInFilter=None, contentExFilter=None): """ Inserts files by recursive traversing the rootpath and inserting files according the addition filter parameters. :param s...
Encrypt a third - party caveat.
def encode_caveat(condition, root_key, third_party_info, key, ns): '''Encrypt a third-party caveat. The third_party_info key holds information about the third party we're encrypting the caveat for; the key is the public/private key pair of the party that's adding the caveat. The caveat will be enc...
Create a JSON - encoded third - party caveat.
def _encode_caveat_v1(condition, root_key, third_party_pub_key, key): '''Create a JSON-encoded third-party caveat. The third_party_pub_key key represents the PublicKey of the third party we're encrypting the caveat for; the key is the public/private key pair of the party that's adding the caveat. ...
Create a version 2 or version 3 third - party caveat.
def _encode_caveat_v2_v3(version, condition, root_key, third_party_pub_key, key, ns): '''Create a version 2 or version 3 third-party caveat. The format has the following packed binary fields (note that all fields up to and including the nonce are the same as the v2 format): ...
Creates a version 2 or version 3 secret part of the third party caveat. The returned data is not encrypted.
def _encode_secret_part_v2_v3(version, condition, root_key, ns): '''Creates a version 2 or version 3 secret part of the third party caveat. The returned data is not encrypted. The format has the following packed binary fields: version 2 or 3 [1 byte] root key length [n: uvarint] root key [n byt...
Decode caveat by decrypting the encrypted part using key.
def decode_caveat(key, caveat): '''Decode caveat by decrypting the encrypted part using key. @param key the nacl private key to decode. @param caveat bytes. @return ThirdPartyCaveatInfo ''' if len(caveat) == 0: raise VerificationError('empty third party caveat') first = caveat[:1] ...
Decode a base64 encoded JSON id.
def _decode_caveat_v1(key, caveat): '''Decode a base64 encoded JSON id. @param key the nacl private key to decode. @param caveat a base64 encoded JSON string. ''' data = base64.b64decode(caveat).decode('utf-8') wrapper = json.loads(data) tp_public_key = nacl.public.PublicKey( base6...
Decodes a version 2 or version 3 caveat.
def _decode_caveat_v2_v3(version, key, caveat): '''Decodes a version 2 or version 3 caveat. ''' if (len(caveat) < 1 + _PUBLIC_KEY_PREFIX_LEN + _KEY_LEN + nacl.public.Box.NONCE_SIZE + 16): raise VerificationError('caveat id too short') original_caveat = caveat caveat = caveat[1:] ...
encodes integer into variable - length format into data.
def encode_uvarint(n, data): '''encodes integer into variable-length format into data.''' if n < 0: raise ValueError('only support positive integer') while True: this_byte = n & 127 n >>= 7 if n == 0: data.append(this_byte) break data.append(th...
Decode a variable - length integer.
def decode_uvarint(data): '''Decode a variable-length integer. Reads a sequence of unsigned integer byte and decodes them into an integer in variable-length format and returns it and the length read. ''' n = 0 shift = 0 length = 0 for b in data: if not isinstance(b, int): ...
Builds type dictionary for user - defined type converters used by: mod: parse module. This requires that each type converter has a name attribute.
def build_type_dict(converters): """ Builds type dictionary for user-defined type converters, used by :mod:`parse` module. This requires that each type converter has a "name" attribute. :param converters: List of type converters (parse_types) :return: Type converter dictionary """ more_...
Create a type converter for a list of items ( many: = 1.. * ). The parser accepts anything and the converter needs to fail on errors.
def make_list(cls, item_converter=None, listsep=','): """ Create a type converter for a list of items (many := 1..*). The parser accepts anything and the converter needs to fail on errors. :param item_converter: Type converter for an item. :param listsep: List separator to use...
Creates a type converter for an enumeration or text - to - value mapping.
def make_enum(enum_mappings): """ Creates a type converter for an enumeration or text-to-value mapping. :param enum_mappings: Defines enumeration names and values. :return: Type converter function object for the enum/mapping. """ if (inspect.isclass(enum_mappings) and ...
Creates a type - converter function to select one from a list of strings. The type - converter function returns the selected choice_text. The: param: transform () function is applied in the type converter. It can be used to enforce the case ( because parser uses re. IGNORECASE ).
def make_choice(cls, choices, transform=None, strict=None): """ Creates a type-converter function to select one from a list of strings. The type-converter function returns the selected choice_text. The :param:`transform()` function is applied in the type converter. It can be used...
Creates a type converter to select one item from a list of strings. The type converter function returns a tuple ( index choice_text ).
def make_choice2(cls, choices, transform=None, strict=None): """ Creates a type converter to select one item from a list of strings. The type converter function returns a tuple (index, choice_text). :param choices: List of strings as choice. :param transform: Optional, initial t...
Creates a type converter for a number of type converter alternatives. The first matching type converter is used.
def make_variant(cls, converters, re_opts=None, compiled=False, strict=True): """ Creates a type converter for a number of type converter alternatives. The first matching type converter is used. REQUIRES: type_converter.pattern attribute :param converters: List of type converte...
Carries out a conversion ( represented as a string ) and returns the result as a human - readable string.
def parseUnits(self, inp): """Carries out a conversion (represented as a string) and returns the result as a human-readable string. Args: inp (str): Text representing a unit conversion, which should include a magnitude, a description of the initial units, ...
Checks if a string represents a valid quantities unit.
def isValidUnit(self, w): """Checks if a string represents a valid quantities unit. Args: w (str): A string to be tested against the set of valid quantities units. Returns: True if the string can be used as a unit in the quantities module. ...
Collects all the valid units from an inp string. Works by appending consecutive words from the string and cross - referncing them with a set of valid units.
def extractUnits(self, inp): """Collects all the valid units from an inp string. Works by appending consecutive words from the string and cross-referncing them with a set of valid units. Args: inp (str): Some text which hopefully contains descriptions of diff...
Converts a string representation of some quantity of units into a quantities object.
def convert(self, inp): """Converts a string representation of some quantity of units into a quantities object. Args: inp (str): A textual representation of some quantity of units, e.g., "fifty kilograms". Returns: A quantities object representin...
Allow access to any ACL members that was equal to the user name.
def allow(self, ctx, acls): '''Allow access to any ACL members that was equal to the user name. That is, some user u is considered a member of group u and no other. ''' for acl in acls: if self._identity == acl: return True return False
Return an unique list of resources or collections from a list of paths. Supports fq_name and wilcards resolution.
def expand_paths(paths=None, predicate=None, filters=None, parent_uuid=None): """Return an unique list of resources or collections from a list of paths. Supports fq_name and wilcards resolution. >>> expand_paths(['virtual-network', 'floating-ip/2a0a54b4-a420-485e-8372-42f70a627ec9']) ...
Renders a Jinja2 template to text.
def render(self, template, filename, context={}, filters={}): """ Renders a Jinja2 template to text. """ filename = os.path.normpath(filename) path, file = os.path.split(filename) try: os.makedirs(path) except OSError as exception: if excep...
Executes the command.
def execute(self): """ Executes the command. """ from vsgen.util.logger import VSGLogger VSGLogger.info(self._logname, self._message) start = time.clock() VSGWriter.write(self._writables, self._parallel) end = time.clock() VSGLogger.info(self._log...
Utility method to spawn a VSGWriter for each element in a collection.
def write(pylist, parallel=True): """ Utility method to spawn a VSGWriter for each element in a collection. :param list pylist: A list of VSG objects (PrProjects, VSGSolutions, etc) :param bool parallel: Flag to enable asynchronous writing. """ threads = [VSGWriter(o) ...
Implement Interactor. interact by opening the browser window and waiting for the discharge token
def interact(self, ctx, location, ir_err): '''Implement Interactor.interact by opening the browser window and waiting for the discharge token''' p = ir_err.interaction_method(self.kind(), WebBrowserInteractionInfo) if not location.endswith('/'): location += '/' visit_...
Returns a token from a the wait token URL
def _wait_for_token(self, ctx, wait_token_url): ''' Returns a token from a the wait token URL @param wait_token_url URL to wait for (string) :return DischargeToken ''' resp = requests.get(wait_token_url) if resp.status_code != 200: raise InteractionError('cann...
Create a new instance of WebBrowserInteractionInfo as expected by the Error. interaction_method method.
def from_dict(cls, info_dict): '''Create a new instance of WebBrowserInteractionInfo, as expected by the Error.interaction_method method. @param info_dict The deserialized JSON object @return a new WebBrowserInteractionInfo object. ''' return WebBrowserInteractionInfo( ...
Returns a list of all the System objects to the cluster. Updates every time - no caching.: return: a list of all the System objects known to the cluster.: rtype: list
def get(self): """ Returns a `list` of all the `System` objects to the cluster. Updates every time - no caching. :return: a `list` of all the `System` objects known to the cluster. :rtype: list """ self.conn.connection._check_login() response = self.conn.connecti...
Set name for SDS: param name: Name of SDS: param sdsObj: ScaleIO SDS object: return: POST request response: rtype: Requests POST response object
def set_sds_name(self, name, sdsObj): """ Set name for SDS :param name: Name of SDS :param sdsObj: ScaleIO SDS object :return: POST request response :rtype: Requests POST response object """ # TODO: # Check if object parameters are the correct type...
Unregister SDS from MDM/ SIO Cluster: param sdsObj: ScaleIO SDS objecty: return: POST request response: rtype: Requests POST response object
def unregisterSds(self, sdsObj): """ Unregister SDS from MDM/SIO Cluster :param sdsObj: ScaleIO SDS objecty :return: POST request response :rtype: Requests POST response object """ self.conn.connection._check_login() response = self.conn.connection._do_pos...
Register SDS with MDM/ SIO Cluster: param sdsObj: ScaleIO SDS object: return: POST request response: rtype: Requests POST response object
def registerSds(self, sdsObj, **kwargs): """ Register SDS with MDM/SIO Cluster :param sdsObj: ScaleIO SDS object :return: POST request response :rtype: Requests POST response object """ # Register existing SDS running SDS binary (need to be installed manually but ...
Get list of SDS objects attached to a specific ScaleIO Faultset: param faultSetObj: ScaleIO Faultset object: rtype: list of SDS in specified Faultset
def get_sds_in_faultset(self, faultSetObj): """ Get list of SDS objects attached to a specific ScaleIO Faultset :param faultSetObj: ScaleIO Faultset object :rtype: list of SDS in specified Faultset """ self.conn.connection._check_login() response = self.conn.conne...
Get ScaleIO SDS object by its name: param name: Name of SDS: return: ScaleIO SDS object: raise KeyError: No SDS with specified name found: rtype: SDS object
def get_sds_by_name(self,name): """ Get ScaleIO SDS object by its name :param name: Name of SDS :return: ScaleIO SDS object :raise KeyError: No SDS with specified name found :rtype: SDS object """ for sds in self.sds: if sds.name == name: ...
Get ScaleIO SDS object by its ip address: param name: IP address of SDS: return: ScaleIO SDS object: raise KeyError: No SDS with specified ip found: rtype: SDS object
def get_sds_by_ip(self,ip): """ Get ScaleIO SDS object by its ip address :param name: IP address of SDS :return: ScaleIO SDS object :raise KeyError: No SDS with specified ip found :rtype: SDS object """ if self.conn.is_ip_addr(ip): for sds in s...
Get ScaleIO SDS object by its id: param name: ID of SDS: return: ScaleIO SDS object: raise KeyError: No SDS with specified id found: rtype: SDS object
def get_sds_by_id(self,id): """ Get ScaleIO SDS object by its id :param name: ID of SDS :return: ScaleIO SDS object :raise KeyError: No SDS with specified id found :rtype: SDS object """ for sds in self.sds: if sds.id == id: ret...
Sets a new value for a given configuration parameter.
def set(self, name, value, overwrite=False): """ Sets a new value for a given configuration parameter. If it already exists, an Exception is thrown. To overwrite an existing value, set overwrite to True. :param name: Unique name of the parameter :param value: Value of t...
Creates missing types for fields with a CardinalityField part. It is assumed that the primary type converter for cardinality = 1 is registered in the type dictionary.
def create_missing_types(cls, schema, type_dict, type_builder=None): """Creates missing types for fields with a CardinalityField part. It is assumed that the primary type converter for cardinality=1 is registered in the type dictionary. :param schema: Parse schema (or format) for parse...
Extract the type names for fields with CardinalityField part. Selects only the missing type names that are not in the type dictionary.
def extract_missing_special_type_names(schema, type_dict): """Extract the type names for fields with CardinalityField part. Selects only the missing type names that are not in the type dictionary. :param schema: Parse schema to use (as string). :param type_dict: Type dictionary wit...
Checks an allow or a deny caveat. The need_ops parameter specifies whether we require all the operations in the caveat to be declared in the context.
def _check_operations(ctx, need_ops, arg): ''' Checks an allow or a deny caveat. The need_ops parameter specifies whether we require all the operations in the caveat to be declared in the context. ''' ctx_ops = ctx.get(OP_KEY, []) if len(ctx_ops) == 0: if need_ops: f = arg.sp...
Checks the caveat against all registered caveat conditions.: return: error message string if any or None
def check_first_party_caveat(self, ctx, cav): ''' Checks the caveat against all registered caveat conditions. :return: error message string if any or None ''' try: cond, arg = parse_caveat(cav) except ValueError as ex: # If we can't parse it, perhaps it's ...
Returns information on all the registered checkers.
def info(self): ''' Returns information on all the registered checkers. Sorted by namespace and then name :returns a list of CheckerInfo ''' return sorted(self._checkers.values(), key=lambda x: (x.ns, x.name))
Registers the given condition ( string ) in the given namespace uri ( string ) to be checked with the given check function. The check function checks a caveat by passing an auth context a cond parameter ( string ) that holds the caveat condition including any namespace prefix and an arg parameter ( string ) that hold a...
def register(self, cond, uri, check): ''' Registers the given condition(string) in the given namespace uri (string) to be checked with the given check function. The check function checks a caveat by passing an auth context, a cond parameter(string) that holds the caveat condition includi...
Registers all the standard checkers in the given checker.
def register_std(self): ''' Registers all the standard checkers in the given checker. If not present already, the standard checkers schema (STD_NAMESPACE) is added to the checker's namespace with an empty prefix. ''' self._namespace.register(STD_NAMESPACE, '') for cond i...
Implements Authorizer. authorize by calling f with the given identity for each operation.
def authorize(self, ctx, identity, ops): '''Implements Authorizer.authorize by calling f with the given identity for each operation. ''' allowed = [] caveats = [] for op in ops: ok, fcaveats = self._f(ctx, identity, op) allowed.append(ok) ...
Implements Authorizer. authorize by calling identity. allow to determine whether the identity is a member of the ACLs associated with the given operations.
def authorize(self, ctx, identity, ops): '''Implements Authorizer.authorize by calling identity.allow to determine whether the identity is a member of the ACLs associated with the given operations. ''' if len(ops) == 0: # Anyone is allowed to do nothing. r...
Matches both the subject and action not necessarily the conditions.
def is_relevant(self, action, subject): """ Matches both the subject and action, not necessarily the conditions. """ return self.matches_action(action) and self.matches_subject(subject)
Check that a given HAL id is a valid one.
def is_valid(hal_id): """ Check that a given HAL id is a valid one. :param hal_id: The HAL id to be checked. :returns: Boolean indicating whether the HAL id is valid or not. >>> is_valid("hal-01258754, version 1") True >>> is_valid("hal-01258754") True >>> is_valid("hal-01258754v...
Extract HAL ids from a text.
def extract_from_text(text): """ Extract HAL ids from a text. :param text: The text to extract HAL ids from. :returns: A list of matching HAL ids. >>> sorted(extract_from_text("hal-01258754 hal-01258754v2 foobar")) ['hal-01258754', 'hal-01258754v2'] """ return tools.remove_duplicates([...
Creates a VSG solution from a configparser instance.
def _getsolution(self, config, section, **kwargs): """ Creates a VSG solution from a configparser instance. :param object config: The instance of the configparser class :param str section: The section name to read. :param kwargs: List of additional keyworded arguments to be pas...
Creates a VSG project from a configparser instance.
def _getproject(self, config, section, **kwargs): """ Creates a VSG project from a configparser instance. :param object config: The instance of the configparser class :param str section: The section name to read. :param kwargs: List of additional keyworded arguments to be passe...
Creates an VSGSuite instance from a filename.
def from_file(cls, filename): """ Creates an VSGSuite instance from a filename. :param str filename: The fully qualified path to the VSG configuration file. """ # Read the configuration file config = VSGConfigParser() if filename not in config.read([filename]): ...
Creates a: class: ~argparse. ArgumentParser instances to work with VSGSuite classes.
def make_parser(cls, **kwargs): """ Creates a :class:`~argparse.ArgumentParser` instances to work with VSGSuite classes. :param kwargs: List of additional keyworded arguments to be passed into the :class:`~argparse.ArgumentParser`. :return: A :class:`~argparse.ArgumentParser` instance...
Generates one or more VSGSuite instances from command line arguments.
def from_args(cls, **kwargs): """ Generates one or more VSGSuite instances from command line arguments. :param kwargs: List of additional keyworded arguments to be passed into the VSGSuite defined in the :meth:`~VSGSuite.make_parser` method. """ # Create a VSGSuite for each fil...
Creates an VSGSuite instance from a filename.
def from_directory(cls, directory, type, **kwargs): """ Creates an VSGSuite instance from a filename. :param str filename: The fully qualified path to the VSG configuration file. :param str type: The configuration type to generate. :param kwargs: List of additional keyworded ...
Writes the configuration to disk.
def write(self, parallel=True): """ Writes the configuration to disk. """ # Write the Solution files solutions = sorted(self._solutions, key=lambda x: x.Name) with VSGWriteCommand('Writing VSG Solution', solutions, parallel) as command: command.execute() ...
Return a plaintext representation of a bibitem from the. bbl file.
def bibitem_as_plaintext(bibitem): """ Return a plaintext representation of a bibitem from the ``.bbl`` file. .. note:: This plaintext representation can be super ugly, contain URLs and so \ on. .. note:: You need to have ``delatex`` installed system-wide, or to build it in \...
Parse a *. bbl file to get a clean list of plaintext citations.
def get_plaintext_citations(bbl): """ Parse a ``*.bbl`` file to get a clean list of plaintext citations. :param bbl: Either the path to the .bbl file or the content of a ``.bbl`` \ file. :returns: A list of cleaned plaintext citations. """ # Handle path or content if os.path.is...
Get ScaleIO ProtectionDomain object by its name: param name: Name of ProtectionDomain: return: ScaleIO ProtectionDomain object: raise KeyError: No ProtetionDomain with specified name found: rtype: ProtectionDomain object
def get_pd_by_name(self, name): """ Get ScaleIO ProtectionDomain object by its name :param name: Name of ProtectionDomain :return: ScaleIO ProtectionDomain object :raise KeyError: No ProtetionDomain with specified name found :rtype: ProtectionDomain object """ ...
Get ScaleIO ProtectionDomain object by its id: param name: ID of ProtectionDomain: return: ScaleIO ProctectionDomain object: raise KeyError: No ProtectionDomain with specified name found: rtype: ProtectionDomain object
def get_pd_by_id(self, id): """ Get ScaleIO ProtectionDomain object by its id :param name: ID of ProtectionDomain :return: ScaleIO ProctectionDomain object :raise KeyError: No ProtectionDomain with specified name found :rtype: ProtectionDomain object """ f...
: param pdObj: ID of ProtectionDomain type: POST Required: Protection Domain Object Return:
def delete_potection_domain(self, pdObj): """ :param pdObj: ID of ProtectionDomain type: POST Required: Protection Domain Object Return: """ self.conn.connection._check_login() response = self.conn.connection._do_post("{}/{}{}/{}".form...
Split type of a type name with CardinalityField suffix into its parts.
def split_type(cls, type_name): """Split type of a type name with CardinalityField suffix into its parts. :param type_name: Type name (as string). :return: Tuple (type_basename, cardinality) """ if cls.matches_type(type_name): basename = type_name[:-1] c...
Build new type name according to CardinalityField naming scheme.
def make_type(cls, basename, cardinality): """Build new type name according to CardinalityField naming scheme. :param basename: Type basename of primary type (as string). :param cardinality: Cardinality of the new type (as Cardinality item). :return: Type name with CardinalityField suf...
Create type variants for types with a cardinality field. The new type converters are based on the type converter with cardinality = 1.
def create_type_variant(cls, type_name, type_converter): """ Create type variants for types with a cardinality field. The new type converters are based on the type converter with cardinality=1. .. code-block:: python import parse @parse.with_pattern(r'\...
Create type variants for types with a cardinality field. The new type converters are based on the type converter with cardinality = 1.
def create_type_variants(cls, type_names, type_dict): """ Create type variants for types with a cardinality field. The new type converters are based on the type converter with cardinality=1. .. code-block:: python # -- USE: parse_number() type converter function. ...
Create missing type variants for types with a cardinality field.
def create_missing_type_variants(cls, type_names, type_dict): """ Create missing type variants for types with a cardinality field. :param type_names: List of type names with cardinality field suffix. :param type_dict: Type dictionary with named type converters. :return: Type di...
small static method to get logging level: param str level: string of the level e. g. INFO: returns logging. <LEVEL >: appropriate debug level
def _get_log_level(level): """ small static method to get logging level :param str level: string of the level e.g. "INFO" :returns logging.<LEVEL>: appropriate debug level """ # default to DEBUG if level is None or level == "DEBUG": return logging.DEBU...
Returns a list of all the System objects to the cluster. Updates every time - no caching.: return: a list of all the System objects known to the cluster.: rtype: list
def system(self): """ Returns a `list` of all the `System` objects to the cluster. Updates every time - no caching. :return: a `list` of all the `System` objects known to the cluster. :rtype: list """ self.connection._check_login() response = self.connection._do_...
Returns a list of all the System objects to the cluster. Updates every time - no caching.: return: a list of all the System objects known to the cluster.: rtype: list
def storage_pools(self): """ Returns a `list` of all the `System` objects to the cluster. Updates every time - no caching. :return: a `list` of all the `System` objects known to the cluster. :rtype: list """ self.connection._check_login() response = self.connecti...
Returns a list of all the ScaleIO_SDC known to the cluster. Updates every time - no caching.: return: a list of all the ScaleIO_SDC known to the cluster.: rtype: list
def sdc(self): """ Returns a `list` of all the `ScaleIO_SDC` known to the cluster. Updates every time - no caching. :return: a `list` of all the `ScaleIO_SDC` known to the cluster. :rtype: list """ self.connection._check_login() response = self.connection._do_get...
Returns a list of all the ScaleIO_SDS known to the cluster. Updates every time - no caching.: return: a list of all the ScaleIO_SDS known to the cluster.: rtype: list
def sds(self): """ Returns a `list` of all the `ScaleIO_SDS` known to the cluster. Updates every time - no caching. :return: a `list` of all the `ScaleIO_SDS` known to the cluster. :rtype: list """ self.connection._check_login() response = self.connection._do_get...
Returns a list of all the Volume known to the cluster. Updates every time - no caching.: return: a list of all the Volume known to the cluster.: rtype: list
def volumes(self): """ Returns a `list` of all the `Volume` known to the cluster. Updates every time - no caching. :return: a `list` of all the `Volume` known to the cluster. :rtype: list """ self.connection._check_login() response = self.connection._do_get("{}/{...
Get all Volumes of type Snapshot. Updates every time - no caching.: return: a list of all the ScaleIO_Volume that have a are of type Snapshot.: rtype: list
def snapshots(self): """ Get all Volumes of type Snapshot. Updates every time - no caching. :return: a `list` of all the `ScaleIO_Volume` that have a are of type Snapshot. :rtype: list """ self.connection._check_login() response = self.connection._do_get("{}/{}"....
: rtype: list of Protection Domains
def protection_domains(self): """ :rtype: list of Protection Domains """ self.connection._check_login() response = self.connection._do_get("{}/{}".format(self.connection._api_url, "types/ProtectionDomain/instances")).json() all_pds = [] for pd in response: ...
You can only create and configure Fault Sets before adding SDSs to the system and configuring them incorrectly may prevent the creation of volumes. An SDS can only be added to a Fault Set during the creation of the SDS.: rtype: list of Faultset objects
def fault_sets(self): """ You can only create and configure Fault Sets before adding SDSs to the system, and configuring them incorrectly may prevent the creation of volumes. An SDS can only be added to a Fault Set during the creation of the SDS. :rtype: list of Faultset objects ...
Get list of VTrees from ScaleIO cluster: return: List of VTree objects - Can be empty of no VTrees exist: rtype: VTree object
def vtrees(self): """ Get list of VTrees from ScaleIO cluster :return: List of VTree objects - Can be empty of no VTrees exist :rtype: VTree object """ self.connection._check_login() response = self.connection._do_get("{}/{}".format(self.connection._api_url, "type...
Convenience method to verify if string is an IP addr?: param ipstr: Stinrg containing IP address: rtype True if string is a valid IP address
def is_ip_addr(self, ipstr): """ Convenience method to verify if string is an IP addr? :param ipstr: Stinrg containing IP address :rtype True if string is a valid IP address """ ipstr_chunks = ipstr.split('.') if len(ipstr_chunks) != 4: return False ...
Put an ops only if not already there otherwise it s a no op.
def put_ops(self, key, time, ops): ''' Put an ops only if not already there, otherwise it's a no op. ''' if self._store.get(key) is None: self._store[key] = ops
Returns ops from the key if found otherwise raises a KeyError.
def get_ops(self, key): ''' Returns ops from the key if found otherwise raises a KeyError. ''' ops = self._store.get(key) if ops is None: raise KeyError( 'cannot get operations for {}'.format(key)) return ops
Parse a local caveat location as generated by LocalThirdPartyCaveat.
def _parse_local_location(loc): '''Parse a local caveat location as generated by LocalThirdPartyCaveat. This is of the form: local <version> <pubkey> where <version> is the bakery version of the client that we're adding the local caveat for. It returns None if the location does not repre...
Add a caveat to the macaroon.
def add_caveat(self, cav, key=None, loc=None): '''Add a caveat to the macaroon. It encrypts it using the given key pair and by looking up the location using the given locator. As a special case, if the caveat's Location field has the prefix "local " the caveat is added as a clie...
Add an array of caveats to the macaroon.
def add_caveats(self, cavs, key, loc): '''Add an array of caveats to the macaroon. This method does not mutate the current object. @param cavs arrary of caveats. @param key the PublicKey to encrypt third party caveat. @param loc locator to find the location object that has a met...
Return a dict representation of the macaroon data in JSON format.
def to_dict(self): '''Return a dict representation of the macaroon data in JSON format. @return a dict ''' if self.version < VERSION_3: if len(self._caveat_data) > 0: raise ValueError('cannot serialize pre-version3 macaroon with ' ...
Return a macaroon obtained from the given dictionary as deserialized from JSON.
def from_dict(cls, json_dict): '''Return a macaroon obtained from the given dictionary as deserialized from JSON. @param json_dict The deserialized JSON object. ''' json_macaroon = json_dict.get('m') if json_macaroon is None: # Try the v1 format if we don't ha...
Return a macaroon deserialized from a string
def deserialize_json(cls, serialized_json): '''Return a macaroon deserialized from a string @param serialized_json The string to decode {str} @return {Macaroon} ''' serialized = json.loads(serialized_json) return Macaroon.from_dict(serialized)
Return a third party caveat id
def _new_caveat_id(self, base): '''Return a third party caveat id This does not duplicate any third party caveat ids already inside macaroon. If base is non-empty, it is used as the id prefix. @param base bytes @return bytes ''' id = bytearray() if len(b...
Returns a copy of the macaroon. Note that the the new macaroon s namespace still points to the same underlying Namespace - copying the macaroon does not make a copy of the namespace.: return a Macaroon
def copy(self): ''' Returns a copy of the macaroon. Note that the the new macaroon's namespace still points to the same underlying Namespace - copying the macaroon does not make a copy of the namespace. :return a Macaroon ''' m1 = Macaroon(None, None, version=self._versio...
Return the hook function ( called when the response is received. )
def _prepare_discharge_hook(req, client): ''' Return the hook function (called when the response is received.) This allows us to intercept the response and do any necessary macaroon discharge before returning. ''' class Retry: # Define a local class so that we can use its class variable as ...
Returns an array of any macaroons found in the given slice of cookies. If the argument implements a get_header method that will be used instead of the get method to retrieve headers.
def extract_macaroons(headers_or_request): ''' Returns an array of any macaroons found in the given slice of cookies. If the argument implements a get_header method, that will be used instead of the get method to retrieve headers. @param headers_or_request: dict of headers or a urllib.request.Reques...
Set the given field to the given val ( bytes ) in the serialized dictionary. If the value isn t valid utf - 8 we base64 encode it and use field + 64 as the field name.
def _add_json_binary_field(b, serialized, field): '''' Set the given field to the given val (bytes) in the serialized dictionary. If the value isn't valid utf-8, we base64 encode it and use field+"64" as the field name. ''' try: val = b.decode('utf-8') serialized[field] = val ...
Returns a macaroon from a legacy wait endpoint.
def _wait_for_macaroon(wait_url): ''' Returns a macaroon from a legacy wait endpoint. ''' headers = { BAKERY_PROTOCOL_HEADER: str(bakery.LATEST_VERSION) } resp = requests.get(url=wait_url, headers=headers) if resp.status_code != 200: raise InteractionError('cannot get {}'.format(...
Queries a URL as found in an ErrInteractionRequired VisitURL field to find available interaction methods. It does this by sending a GET request to the URL with the Accept header set to application/ json and parsing the resulting response as a dict.
def _legacy_get_interaction_methods(u): ''' Queries a URL as found in an ErrInteractionRequired VisitURL field to find available interaction methods. It does this by sending a GET request to the URL with the Accept header set to "application/json" and parsing the resulting response as a dict. ''...