docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Makes a POST request to create a resource when no request body is required. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its completion. custom_headers: Allows set s...
def create_with_zero_body(self, uri=None, timeout=-1, custom_headers=None): if not uri: uri = self.URI logger.debug('Create with zero body (uri = %s)' % uri) resource_data = self._helper.do_post(uri, {}, timeout, custom_headers) return resource_data
495,422
Makes a PUT request to update a resource when no request body is required. Args: uri: Allows to use a different URI other than resource URI timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stop...
def update_with_zero_body(self, uri=None, timeout=-1, custom_headers=None): if not uri: uri = self.data['uri'] logger.debug('Update with zero length body (uri = %s)' % uri) resource_data = self._helper.do_put(uri, None, timeout, custom_headers) return resource_data
495,423
Retrieves a collection of resources. Use this function when the 'start' and 'count' parameters are not allowed in the GET call. Otherwise, use get_all instead. Optional filtering criteria may be specified. Args: id_or_uri: Can be either the resource ID or the resource URI....
def get_collection(self, id_or_uri, filter=''): if filter: filter = self.__make_query_filter(filter) filter = "?" + filter[1:] uri = "{uri}{filter}".format(uri=self.build_uri(id_or_uri), filter=filter) logger.debug('Get resource collection (uri = %s)' % uri) ...
495,431
Makes a multipart request. Args: file_path: File to upload. uri: A specific URI (optional). timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; ...
def upload(self, file_path, uri=None, timeout=-1): if not uri: uri = self._uri upload_file_name = os.path.basename(file_path) task, entity = self._connection.post_multipart_with_response_handling(uri, file_path, upload_file_name) if not task: return ent...
495,436
Uses the PATCH to update a resource. Only one operation can be performed in each PATCH call. Args: id_or_uri: Can be either the resource ID or the resource URI. body: Patch request body timeout: Timeout in seconds. Wait for task completion by default. The timeout do...
def patch_request(self, id_or_uri, body, timeout=-1, custom_headers=None): uri = self.build_uri(id_or_uri) logger.debug('Patch resource (uri = %s, data = %s)' % (uri, body)) custom_headers_copy = custom_headers.copy() if custom_headers else {} if self._connection._apiVersion >...
495,438
This function uses get_all passing a filter. The search is case-insensitive. Args: field: Field name to filter. value: Value to filter. uri: Resource uri. Returns: dict
def get_by(self, field, value, uri=None): if not field: logger.exception(RESOURCE_CLIENT_INVALID_FIELD) raise ValueError(RESOURCE_CLIENT_INVALID_FIELD) if not uri: uri = self._uri self.__validate_resource_uri(uri) logger.debug('Get by (uri =...
495,439
Gets the list of firmware baseline resources managed by the appliance. Optional parameters can be used to filter the list of resources returned. The search is case-insensitive. Args: field: Field name to filter. value: Value to filter. Returns: list...
def get_by(self, field, value): firmwares = self.get_all() matches = [] for item in firmwares: if item.get(field) == value: matches.append(item) return matches
495,449
Updates one or more attributes for a server hardware type resource. Args: data (dict): Object to update. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its co...
def update(self, data, timeout=-1, force=False): uri = self.data["uri"] self.data = self._helper.update(data, uri=uri, timeout=timeout, force=force) return self
495,451
Gets the statistics from an interconnect. Args: id_or_uri: Can be either the interconnect id or the interconnect uri. port_name (str): A specific port name of an interconnect. Returns: dict: The statistics for the interconnect that matches id.
def get_statistics(self, id_or_uri, port_name=''): uri = self._client.build_uri(id_or_uri) + "/statistics" if port_name: uri = uri + "/" + port_name return self._client.get(uri)
495,452
Gets the subport statistics on an interconnect. Args: id_or_uri: Can be either the interconnect id or the interconnect uri. port_name (str): A specific port name of an interconnect. subport_number (int): The subport. Returns: dict: The statistics for t...
def get_subport_statistics(self, id_or_uri, port_name, subport_number): uri = self._client.build_uri(id_or_uri) + "/statistics/{0}/subport/{1}".format(port_name, subport_number) return self._client.get(uri)
495,453
Gets the named servers for an interconnect. Args: id_or_uri: Can be either the interconnect id or the interconnect uri. Returns: dict: the name servers for an interconnect.
def get_name_servers(self, id_or_uri): uri = self._client.build_uri(id_or_uri) + "/nameServers" return self._client.get(uri)
495,454
Updates an interconnect port. Args: id_or_uri: Can be either the interconnect id or the interconnect uri. port_information (dict): object to update timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in O...
def update_port(self, port_information, id_or_uri, timeout=-1): uri = self._client.build_uri(id_or_uri) + "/ports" return self._client.update(port_information, uri, timeout)
495,455
Updates the interconnect ports. Args: id_or_uri: Can be either the interconnect id or the interconnect uri. ports (list): Ports to update. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; i...
def update_ports(self, ports, id_or_uri, timeout=-1): resources = merge_default_values(ports, {'type': 'port'}) uri = self._client.build_uri(id_or_uri) + "/update-ports" return self._client.update(resources, uri, timeout)
495,456
Triggers a reset of port protection. Cause port protection to be reset on all the interconnects of the logical interconnect that matches ID. Args: id_or_uri: Can be either the interconnect id or the interconnect uri. timeout: Timeout in seconds. Wait for task completion by defa...
def reset_port_protection(self, id_or_uri, timeout=-1): uri = self._client.build_uri(id_or_uri) + "/resetportprotection" return self._client.update_with_zero_body(uri, timeout)
495,457
Gets an interconnect port. Args: id_or_uri: Can be either the interconnect id or uri. port_id_or_uri: The interconnect port id or uri. Returns: dict: The interconnect port.
def get_port(self, id_or_uri, port_id_or_uri): uri = self._client.build_subresource_uri(id_or_uri, port_id_or_uri, "ports") return self._client.get(uri)
495,459
Gets all the pluggable module information. Args: id_or_uri: Can be either the interconnect id or uri. Returns: array: dicts of the pluggable module information.
def get_pluggable_module_information(self, id_or_uri): uri = self._client.build_uri(id_or_uri) + "/pluggableModuleInformation" return self._client.get(uri)
495,460
Updates a registered Device Manager. Args: resource (dict): Object to update. id_or_uri: Can be either the Device manager ID or URI. Returns: dict: The device manager resource.
def update(self, resource, id_or_uri): return self._client.update(resource=resource, uri=id_or_uri)
495,463
Adds a Device Manager under the specified provider. Args: resource (dict): Object to add. provider_uri_or_id: ID or URI of provider. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in ...
def add(self, resource, provider_uri_or_id, timeout=-1): uri = self._provider_client.build_uri(provider_uri_or_id) + "/device-managers" return self._client.create(resource=resource, uri=uri, timeout=timeout)
495,464
Gets uri for a specific provider. Args: provider_display_name: Display name of the provider. Returns: uri
def get_provider_uri(self, provider_display_name): providers = self._provider_client.get_by('displayName', provider_display_name) return providers[0]['uri'] if providers else None
495,465
Gets default connection info for a specific provider. Args: provider_name: Name of the provider. Returns: dict: Default connection information.
def get_default_connection_info(self, provider_name): provider = self._provider_client.get_by_name(provider_name) if provider: return provider['defaultConnectionInfo'] else: return {}
495,466
Gets a SAN Manager by name. Args: name: Name of the SAN Manager Returns: dict: SAN Manager.
def get_by_name(self, name): san_managers = self._client.get_all() result = [x for x in san_managers if x['name'] == name] return result[0] if result else None
495,467
Gets a SAN Manager by provider display name. Args: provider_display_name: Name of the Provider Display Name Returns: dict: SAN Manager.
def get_by_provider_display_name(self, provider_display_name): san_managers = self._client.get_all() result = [x for x in san_managers if x['providerDisplayName'] == provider_display_name] return result[0] if result else None
495,468
Updates the metrics configuration with the new values. Overwrites the existing configuration. Args: configuration (dict): Dictionary with a list of objects which contain frequency, sample interval, and source type for each resource-type. Returns: ...
def update_configuration(self, configuration): return self._client.update(configuration, uri=self.URI + "/configuration")
495,470
Delete an SNMPv3 User based on User name specified in filter. The user will be deleted only if it has no associated destinations. Args: username: ID or URI of SNMPv3 user. filter: A general filter/query string to narrow the list of items returned. The default is no f...
def delete_all(self, filter=None, timeout=-1): return self._client.delete_all(filter=filter, timeout=timeout)
495,471
Updates the switch ports. Only the ports under the management of OneView and those that are unlinked are supported for update. Note: This method is available for API version 300 or later. Args: ports: List of Switch Ports. id_or_uri: Can be either the switch...
def update_ports(self, ports, id_or_uri): ports = merge_default_values(ports, {'type': 'port'}) uri = self._client.build_uri(id_or_uri) + "/update-ports" return self._client.update(uri=uri, resource=ports)
495,472
Construct OneViewClient using a json file. Args: file_name: json full path. Returns: OneViewClient:
def from_json_file(cls, file_name): with open(file_name) as json_data: config = json.load(json_data) return cls(config)
495,474
Set proxy if needed Args: config: Config dict
def __set_proxy(self, config): if "proxy" in config and config["proxy"]: proxy = config["proxy"] splitted = proxy.split(':') if len(splitted) != 2: raise ValueError(ONEVIEW_CLIENT_INVALID_PROXY) proxy_host = splitted[0] proxy_...
495,476
Makes a POST request to create a resource when a request body is required. Args: data: Additional fields can be passed to create the resource. uri: Resouce uri timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation ...
def create(self, data=None, uri=None, timeout=-1, force=True): if not data: data = {} default_values = self._get_default_values() for key, value in default_values.items(): if not data.get(key): data[key] = value resource_data = self._hel...
495,546
Updates server profile template. Args: data: Data to update the resource. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its completion. force: Force the update ...
def update(self, data=None, timeout=-1, force=True): uri = self.data['uri'] resource = deepcopy(self.data) resource.update(data) self.data = self._helper.update(resource, uri, force, timeout) return self
495,547
Gets the logical downlink with the specified ID without ethernet. Args: id_or_uri: Can be either the logical downlink id or the logical downlink uri. Returns: dict
def get_without_ethernet(self, id_or_uri): uri = self._client.build_uri(id_or_uri) + "/withoutEthernet" return self._client.get(uri)
495,552
Installs firmware to the member interconnects of a SAS Logical Interconnect. Args: firmware_information: Options to install firmware to a SAS Logical Interconnect. force: If sets to true, the operation completes despite any problems with the network connectivy or the erros...
def update_firmware(self, firmware_information, force=False): firmware_uri = "{}/firmware".format(self.data["uri"]) result = self._helper.update(firmware_information, firmware_uri, force=force) self.refresh() return result
495,554
Returns SAS Logical Interconnects to a consistent state. The current SAS Logical Interconnect state is compared to the associated SAS Logical Interconnect group. Args: information: Can be either the resource ID or URI. timeout: Timeout in seconds. Wait for task completion by def...
def update_compliance_all(self, information, timeout=-1): uri = self.URI + "/compliance" result = self._helper.update(information, uri, timeout=timeout) return result
495,556
When a drive enclosure has been physically replaced, initiate the replacement operation that enables the new drive enclosure to take over as a replacement for the prior drive enclosure. The request requires specification of both the serial numbers of the original drive enclosure and its replacement to b...
def replace_drive_enclosure(self, information): uri = "{}/replaceDriveEnclosure".format(self.data["uri"]) result = self._helper.create(information, uri) self.refresh() return result
495,557
Formats a scan result to XML format. Arguments: result (dict): Dictionary with a scan result. Return: Result as xml element object.
def get_result_xml(result): result_xml = Element('result') for name, value in [('name', result['name']), ('type', ResultType.get_str(result['type'])), ('severity', result['severity']), ('host', result['host']), ...
496,743
Creates an OSP response XML string. Arguments: command (str): OSP Command to respond to. status (int): Status of the response. status_text (str): Status text of the response. content (str): Text part of the response XML element. Return: String of response in xml format.
def simple_response_str(command, status, status_text, content=""): response = Element('%s_response' % command) for name, value in [('status', str(status)), ('status_text', status_text)]: response.set(name, str(value)) if isinstance(content, list): for elem in content: respon...
496,744
Parse a string containing one or more filters and return a list of filters Arguments: vt_filter (string): String containing filters separated with semicolon. Return: List with filters. Each filters is a list with 3 elements e.g. [arg, operator...
def parse_filters(self, vt_filter): filter_list = vt_filter.split(';') filters = list() for single_filter in filter_list: filter_aux = re.split('(\W)', single_filter, 1) if len(filter_aux) < 3: raise OSPDError("Invalid number of argument in the f...
496,799
Calls the specific function to format value, depending on the given element. Arguments: element (string): The element of the VT to be formatted. value (dictionary): The element value. Returns: Returns a formatted value.
def format_filter_value(self, element, value): format_func = self.allowed_filter.get(element) return format_func(value)
496,800
Gets a collection of vulnerability test from the vts dictionary, which match the filter. Arguments: vt_filter (string): Filter to apply to the vts collection. vts (dictionary): The complete vts collection. Returns: Dictionary with filtered vulnerability test...
def get_filtered_vts_list(self, vts, vt_filter): if not vt_filter: raise RequiredArgument('vt_filter: A valid filter is required.') filters = self.parse_filters(vt_filter) if not filters: return None _vts_aux = vts.copy() for _element, _oper, _f...
496,801
Calculate the cvss base score from a cvss base vector for cvss version 2. Arguments: cvss_base_vector (str) Cvss base vector v2. Return the calculated score
def cvss_base_v2_value(cls, cvss_base_vector): if not cvss_base_vector: return None _av, _ac, _au, _c, _i, _a = cls._parse_cvss_base_vector( cvss_base_vector) _impact = 10.41 * (1 - (1 - cvss_v2_metrics['C'].get(_c)) * (1 - cvss_v2_me...
496,802
Calculate the cvss base score from a cvss base vector for cvss version 3. Arguments: cvss_base_vector (str) Cvss base vector v3. Return the calculated score, None on fail.
def cvss_base_v3_value(cls, cvss_base_vector): if not cvss_base_vector: return None _ver, _av, _ac, _pr, _ui, _s, _c, _i, _a = cls._parse_cvss_base_vector( cvss_base_vector) scope_changed = cvss_v3_metrics['S'].get(_s) isc_base = 1 - ( (1 - ...
496,803
Method decorator that waits for JavaScript dependencies before executing `function`. If the function is not a method, the decorator has no effect. Args: function (callable): Method to decorate. Returns: Decorated method
def wait_for_js(function): @functools.wraps(function) def wrapper(*args, **kwargs): # pylint: disable=missing-docstring # If not a method, then just call the function if len(args) < 1: return function(*args, **kwargs) # Otherwise, retrieve `self` as the first arg ...
497,023
Decorator that calls self._verify_page() before executing the decorated method Args: method (callable): The method to decorate. Returns: Decorated method
def pre_verify(method): @wraps(method) def wrapper(self, *args, **kwargs): # pylint: disable=missing-docstring self._verify_page() # pylint: disable=protected-access return method(self, *args, **kwargs) return wrapper
497,029
Configure the broken promise error. Args: promise (Promise): The promise that was not satisfied.
def __init__(self, promise): super(BrokenPromise, self).__init__() self._promise = promise
497,037
Save the rendered HTML of the browser. The location of the source can be configured by the environment variable `SAVED_SOURCE_DIR`. If not set, this defaults to the current working directory. Args: driver (selenium.webdriver): The Selenium-controlled browser. name (str): A name to use...
def save_source(driver, name): source = driver.page_source file_name = os.path.join(os.environ.get('SAVED_SOURCE_DIR'), '{name}.html'.format(name=name)) try: with open(file_name, 'wb') as output_file: output_file.write(source.encode('utf-8')) except...
497,052
Save a screenshot of the browser. The location of the screenshot can be configured by the environment variable `SCREENSHOT_DIR`. If not set, this defaults to the current working directory. Args: driver (selenium.webdriver): The Selenium-controlled browser. name (str): A name for the s...
def save_screenshot(driver, name): if hasattr(driver, 'save_screenshot'): screenshot_dir = os.environ.get('SCREENSHOT_DIR') if not screenshot_dir: LOGGER.warning('The SCREENSHOT_DIR environment variable was not set; not saving a screenshot') return elif not os.pa...
497,053
Save the selenium driver logs. The location of the driver log files can be configured by the environment variable `SELENIUM_DRIVER_LOG_DIR`. If not set, this defaults to the current working directory. Args: driver (selenium.webdriver): The Selenium-controlled browser. prefix (str): A ...
def save_driver_logs(driver, prefix): browser_name = os.environ.get('SELENIUM_BROWSER', 'firefox') log_dir = os.environ.get('SELENIUM_DRIVER_LOG_DIR') if not log_dir: LOGGER.warning('The SELENIUM_DRIVER_LOG_DIR environment variable was not set; not saving logs') return elif not os.p...
497,054
Configure the `Query`. Args: seed_fn (callable): Callable with no arguments that produces a list of values. Keyword Args: desc (str): A description of the query, used in log messages. If not provided, defaults to the name of the seed function. Returns: ...
def __init__(self, seed_fn, desc=None): # pylint: disable=super-init-not-called if desc is None: desc = u'Query({})'.format(getattr(seed_fn, '__name__', '')) self.seed_fn = seed_fn self.transforms = [] self.desc_stack = [] self.desc = desc
497,063
Create a copy of this query, transformed by `transform`. Args: transform (callable): Callable that takes an iterable of values and returns an iterable of transformed values. Keyword Args: desc (str): A description of the transform, to use in log messages. ...
def transform(self, transform, desc=None): if desc is None: desc = u'transform({})'.format(getattr(transform, '__name__', '')) return self.replace( transforms=self.transforms + [transform], desc_stack=self.desc_stack + [desc] )
497,065
Return a copy of this query, with the values mapped through `map_fn`. Args: map_fn (callable): A callable that takes a single argument and returns a new value. Keyword Args: desc (str): A description of the mapping transform, for use in log message. Defaults to ...
def map(self, map_fn, desc=None): if desc is None: desc = getattr(map_fn, '__name__', '') desc = u'map({})'.format(desc) return self.transform(lambda xs: (map_fn(x) for x in xs), desc=desc)
497,066
Return a query that selects the element at `index` (starts from 0). If no elements are available, returns a query with no results. Example usage: .. code:: python >> q = Query(lambda: list(range(5))) >> q.nth(2).results [2] Args: index ...
def nth(self, index): def _transform(xs): # pylint: disable=missing-docstring, invalid-name try: return [next(islice(iter(xs), index, None))] # Gracefully handle (a) running out of elements, and (b) negative indices except (StopIteration, ValueError...
497,071
Generate a query over a browser. Args: browser (selenium.webdriver): A Selenium-controlled browser. Keyword Args: css (str): A CSS selector. xpath (str): An XPath selector. Returns: BrowserQuery Raises: TypeError: The query ...
def __init__(self, browser, **kwargs): if len(kwargs) > 1: raise TypeError('BrowserQuery() takes at most 1 keyword argument.') if not kwargs: raise TypeError('Must pass a query keyword argument to BrowserQuery().') query_name, query_value = list(kwargs.items())...
497,072
Retrieve HTML attribute values from the elements matched by the query. Example usage: .. code:: python # Assume that the query matches html elements: # <div class="foo"> and <div class="bar"> >> q.attrs('class') ['foo', 'bar'] Args: ...
def attrs(self, attribute_name): desc = u'attrs({!r})'.format(attribute_name) return self.map(lambda el: el.get_attribute(attribute_name), desc).results
497,073
Set the text value of each matched element to `text`. Example usage: .. code:: python # Set the text of the first element matched by the query to "Foo" q.first.fill('Foo') Args: text (str): The text used to fill the element (usually a text field or text ar...
def fill(self, text): def _fill(elem): # pylint: disable=missing-docstring elem.clear() elem.send_keys(text) self.map(_fill, u'fill({!r})'.format(text)).execute()
497,077
Create an Infoblox object of type 'obj_type' Args: obj_type (str): Infoblox object type, e.g. 'network', 'range', etc. payload (dict): Payload with data to send return_fields (list): List of fields to be returned Returns...
def create_object(self, obj_type, payload, return_fields=None): self._validate_obj_type_or_die(obj_type) query_params = self._build_query_params(return_fields=return_fields) url = self._construct_url(obj_type, query_params) opts = self._get_request_options(data=payload) ...
497,171
Update an Infoblox object Args: ref (str): Infoblox object reference payload (dict): Payload with data to send Returns: The object reference of the updated object Raises: InfobloxException
def update_object(self, ref, payload, return_fields=None): query_params = self._build_query_params(return_fields=return_fields) opts = self._get_request_options(data=payload) url = self._construct_url(ref, query_params) self._log_request('put', url, opts) r = self.sessi...
497,174
Remove an Infoblox object Args: ref (str): Object reference delete_arguments (dict): Extra delete arguments Returns: The object reference of the removed object Raises: InfobloxException
def delete_object(self, ref, delete_arguments=None): opts = self._get_request_options() if not isinstance(delete_arguments, dict): delete_arguments = {} url = self._construct_url(ref, query_params=delete_arguments) self._log_request('delete', url, opts) r = s...
497,175
Matches the given input againts the available file type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if type matches. Otherwise None. Raises: TypeError: if obj is not a supported type.
def match(obj, matchers=TYPES): buf = get_bytes(obj) for matcher in matchers: if matcher.match(buf): return matcher return None
497,389
Returns the first 262 bytes of the given bytearray as part of the file header signature. Args: array: bytearray to extract the header signature. Returns: First 262 bytes of the file content as bytearray type.
def signature(array): length = len(array) index = _NUM_SIGNATURE_BYTES if length > _NUM_SIGNATURE_BYTES else length return array[:index]
497,394
Infers the input type and reads the first 262 bytes, returning a sliced bytearray. Args: obj: path to readable, file, bytes or bytearray. Returns: First 262 bytes of the file content as bytearray type. Raises: TypeError: if obj is not a supported type.
def get_bytes(obj): try: obj = obj.read(_NUM_SIGNATURE_BYTES) except AttributeError: # duck-typing as readable failed - we'll try the other options pass kind = type(obj) if kind is bytearray: return signature(obj) if kind is str: return get_signature_b...
497,395
Returns the file type instance searching by MIME type or file extension. Args: ext: file extension string. E.g: jpg, png, mp4, mp3 mime: MIME string. E.g: image/jpeg, video/mpeg Returns: The matched file type instance. Otherwise None.
def get_type(mime=None, ext=None): for kind in types: if kind.extension is ext or kind.mime is mime: return kind return None
497,396
If arg is a list with 1 element that corresponds to a valid file path, use set_io.grp to read the grp file. Otherwise, check that arg is a list of strings. Args: arg (list or None) Returns: arg_out (list or None)
def _read_arg(arg): # If arg is None, just return it back if arg is None: arg_out = arg else: # If len(arg) == 1 and arg[0] is a valid filepath, read it as a grp file if len(arg) == 1 and os.path.exists(arg[0]): arg_out = grp.read(arg[0]) else: ...
497,558
Read a gmt file at the path specified by file_path. Args: file_path (string): path to gmt file Returns: gmt (GMT object): list of dicts, where each dict corresponds to one line of the GMT file
def read(file_path): # Read in file actual_file_path = os.path.expanduser(file_path) with open(actual_file_path, 'r') as f: lines = f.readlines() # Create GMT object gmt = [] # Iterate over each line for line_num, line in enumerate(lines): # Separate along tabs...
497,561
Make sure that set ids are unique. Args: gmt (GMT object): list of dicts Returns: None
def verify_gmt_integrity(gmt): # Verify that set ids are unique set_ids = [d[SET_IDENTIFIER_FIELD] for d in gmt] assert len(set(set_ids)) == len(set_ids), ( "Set identifiers should be unique. set_ids: {}".format(set_ids))
497,562
Write a GMT to a text file. Args: gmt (GMT object): list of dicts out_path (string): output path Returns: None
def write(gmt, out_path): with open(out_path, 'w') as f: for _, each_dict in enumerate(gmt): f.write(each_dict[SET_IDENTIFIER_FIELD] + '\t') f.write(each_dict[SET_DESC_FIELD] + '\t') f.write('\t'.join([str(entry) for entry in each_dict[SET_MEMBERS_FIELD]])) ...
497,563
Replace -666, -666.0, and optionally "-666". Args: meta_df (pandas df): convert_neg_666 (bool): Returns: out_df (pandas df): updated meta_df
def replace_666(meta_df, convert_neg_666): if convert_neg_666: out_df = meta_df.replace([-666, "-666", -666.0], np.nan) else: out_df = meta_df.replace([-666, -666.0], "-666") return out_df
497,574
determine if genes are present in the API Args: my_clue_api_client: gene_symbols: collection of gene symbols to query the API with Returns: set of the found gene symbols
def are_genes_in_api(my_clue_api_client, gene_symbols): if len(gene_symbols) > 0: query_gene_symbols = gene_symbols if type(gene_symbols) is list else list(gene_symbols) query_result = my_clue_api_client.run_filter_query(resource_name, {"where":{"gene_symbol":{"inq":query_gene_symb...
497,595
Write first two lines of gct file. Args: version (string): 1.3 by default dims (list of strings): length = 4 f (file handle): handle of output file Returns: nothing
def write_version_and_dims(version, dims, f): f.write(("#" + version + "\n")) f.write((dims[0] + "\t" + dims[1] + "\t" + dims[2] + "\t" + dims[3] + "\n"))
497,598
Write the top half of the gct file: top-left filler values, row metadata headers, and top-right column metadata. Args: f (file handle): handle for output file row_metadata_df (pandas df) col_metadata_df (pandas df) metadata_null (string): how to represent missing values in the m...
def write_top_half(f, row_metadata_df, col_metadata_df, metadata_null, filler_null): # Initialize the top half of the gct including the third line size_of_top_half_df = (1 + col_metadata_df.shape[1], 1 + row_metadata_df.shape[1] + col_metadata_df.shape[0]) top_half_df = pd.D...
497,599
Write the bottom half of the gct file: row metadata and data. Args: f (file handle): handle for output file row_metadata_df (pandas df) data_df (pandas df) data_null (string): how to represent missing values in the data metadata_null (string): how to represent missing values...
def write_bottom_half(f, row_metadata_df, data_df, data_null, data_float_format, metadata_null): # create the left side of the bottom half of the gct (for the row metadata) size_of_left_bottom_half_df = (row_metadata_df.shape[0], 1 + row_metadata_df.shape[1]) left_bottom_h...
497,600
Append dimensions and file extension to output filename. N.B. Dimensions are cols x rows. Args: fname (string): output filename data_df (pandas df) Returns: out_fname (string): output filename with matrix dims and .gct appended
def append_dims_and_file_extension(fname, data_df): # If there's no .gct at the end of output file name, add the dims and .gct if not fname.endswith(".gct"): out_fname = '{0}_n{1}x{2}.gct'.format(fname, data_df.shape[1], data_df.shape[0]) return out_fname # Otherwise, only add the dims...
497,601
Robustly z-score a pandas df along the rows. Args: mat (pandas df): Matrix of data that z-scoring will be applied to ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs (e.g. vehicle control) min_mad (float): Minimum MAD to threshold to; tiny MAD values will cause ...
def robust_zscore(mat, ctrl_mat=None, min_mad=0.1): # If optional df exists, calc medians and mads from it if ctrl_mat is not None: medians = ctrl_mat.median(axis=1) median_devs = abs(ctrl_mat.subtract(medians, axis=0)) # Else just use plate medians else: medians = mat.med...
497,603
Extract upper triangle from a square matrix. Negative values are set to 0. Args: correlation_matrix (pandas df): Correlations between all replicates Returns: upper_tri_df (pandas df): Upper triangle extracted from correlation_matrix; rid is the row index, cid is the column index, c...
def get_upper_triangle(correlation_matrix): upper_triangle = correlation_matrix.where(np.triu(np.ones(correlation_matrix.shape), k=1).astype(np.bool)) # convert matrix into long form description upper_tri_df = upper_triangle.stack().reset_index(level=1) upper_tri_df.columns = ['rid', 'corr'] ...
497,613
Calculate a weight for each profile based on its correlation to other replicates. Negative correlations are clipped to 0, and weights are clipped to be min_wt at the least. Args: correlation_matrix (pandas df): Correlations between all replicates min_wt (float): Minimum raw weight when calculating ...
def calculate_weights(correlation_matrix, min_wt): # fill diagonal of correlation_matrix with np.nan np.fill_diagonal(correlation_matrix.values, np.nan) # remove negative values correlation_matrix = correlation_matrix.clip(lower=0) # get average correlation for each profile (will ignore NaN) ...
497,614
Search for files to be concatenated. Currently very basic, but could expand to be more sophisticated. Args: wildcard (regular expression string) Returns: files (list of full file paths)
def get_file_list(wildcard): files = glob.glob(os.path.expanduser(wildcard)) return files
497,619
Assemble the common metadata dfs together. Both indices are sorted. Fields that are not in all the dfs are dropped. Args: common_meta_dfs (list of pandas dfs) fields_to_remove (list of strings): fields to be removed from the common metadata because they don't agree across files ...
def assemble_common_meta(common_meta_dfs, fields_to_remove, sources, remove_all_metadata_fields, error_report_file): all_meta_df, all_meta_df_with_dups = build_common_all_meta_df(common_meta_dfs, fields_to_remove, remove_all_metadata_fields) if not all_meta_df.index.is_unique: all_report_df = buil...
497,621
Assemble the concatenated metadata dfs together. For example, if horizontally concatenating, the concatenated metadata dfs are the column metadata dfs. Both indices are sorted. Args: concated_meta_dfs (list of pandas dfs) Returns: all_concated_meta_df_sorted (pandas df)
def assemble_concatenated_meta(concated_meta_dfs, remove_all_metadata_fields): # Concatenate the concated_meta_dfs if remove_all_metadata_fields: for df in concated_meta_dfs: df.drop(df.columns, axis=1, inplace=True) all_concated_meta_df = pd.concat(concated_meta_dfs, axis=0) ...
497,624
Assemble the data dfs together. Both indices are sorted. Args: data_dfs (list of pandas dfs) concat_direction (string): 'horiz' or 'vert' Returns: all_data_df_sorted (pandas df)
def assemble_data(data_dfs, concat_direction): if concat_direction == "horiz": # Concatenate the data_dfs horizontally all_data_df = pd.concat(data_dfs, axis=1) # Sanity check: the number of columns in all_data_df should # correspond to the sum of the number of columns in the i...
497,625
Reset ids in concatenated metadata and data dfs to unique integers and save the old ids in a metadata column. Note that the dataframes are modified in-place. Args: concatenated_meta_df (pandas df) data_df (pandas df) concat_direction (string): 'horiz' or 'vert' Returns: ...
def do_reset_ids(concatenated_meta_df, data_df, concat_direction): if concat_direction == "horiz": # Make sure cids agree between data_df and concatenated_meta_df assert concatenated_meta_df.index.equals(data_df.columns), ( "cids in concatenated_meta_df do not agree with cids in da...
497,626
Figure out based on the possible row inputs which rows to keep. Args: gctoo (GCToo object): rid (list of strings): row_bool (boolean array): ridx (list of integers): exclude_rid (list of strings): Returns: rows_to_keep (list of strings): row ids to be kept
def get_rows_to_keep(gctoo, rid=None, row_bool=None, ridx=None, exclude_rid=None): # Use rid if provided if rid is not None: assert type(rid) == list, "rid must be a list. rid: {}".format(rid) rows_to_keep = [gctoo_row for gctoo_row in gctoo.data_df.index if gctoo_row in rid] # Te...
497,629
Figure out based on the possible columns inputs which columns to keep. Args: gctoo (GCToo object): cid (list of strings): col_bool (boolean array): cidx (list of integers): exclude_cid (list of strings): Returns: cols_to_keep (list of strings): col ids to be kep...
def get_cols_to_keep(gctoo, cid=None, col_bool=None, cidx=None, exclude_cid=None): # Use cid if provided if cid is not None: assert type(cid) == list, "cid must be a list. cid: {}".format(cid) cols_to_keep = [gctoo_col for gctoo_col in gctoo.data_df.columns if gctoo_col in cid] #...
497,630
Read a grp file at the path specified by in_path. Args: in_path (string): path to GRP file Returns: grp (list)
def read(in_path): assert os.path.exists(in_path), "The following GRP file can't be found. in_path: {}".format(in_path) with open(in_path, "r") as f: lines = f.readlines() # need the second conditional to ignore comment lines grp = [line.strip() for line in lines if line and not re...
497,631
Write a GRP to a text file. Args: grp (list): GRP object to write to new-line delimited text file out_path (string): output path Returns: None
def write(grp, out_path): with open(out_path, "w") as f: for x in grp: f.write(str(x) + "\n")
497,632
run a query (get) against the CLUE api, using the API and user key fields of self and the fitler_clause provided Args: resource_name: str - name of the resource / collection to query - e.g. genes, perts, cells etc. filter_clause: dictionary - contains filter to pass to API to; uses loop...
def run_filter_query(self, resource_name, filter_clause): url = self.base_url + "/" + resource_name params = {"filter":json.dumps(filter_clause)} r = requests.get(url, headers=self.headers, params=params) logger.debug("requests.get result r.status_code: {}".format(r.status_cod...
497,637
Queries for work items based on their criteria. Args: queue_name: Optional queue name to restrict to. build_id: Optional build ID to restrict to. release_id: Optional release ID to restrict to. run_id: Optional run ID to restrict to. count: How many tasks to fetch. Defaults ...
def _query(queue_name=None, build_id=None, release_id=None, run_id=None, count=None): assert queue_name or build_id or release_id or run_id q = WorkQueue.query if queue_name: q = q.filter_by(queue_name=queue_name) if build_id: q = q.filter_by(build_id=build_id) if re...
497,662
Cancels work items based on their criteria. Args: **kwargs: Same parameters as the query() method. Returns: The number of tasks that were canceled.
def cancel(**kwargs): task_list = _query(**kwargs) for task in task_list: task.status = WorkQueue.CANCELED task.finished = datetime.datetime.utcnow() db.session.add(task) return len(task_list)
497,664
Initializer. Args: log_path: Where to write the verbose logging output. config_path: Path to the screenshot config file to pass to PhantomJs. output_path: Where the output screenshot should be written.
def __init__(self, log_path, config_path, output_path): if FLAGS.phantomjs_timeout is not None: logging.info( 'Using FLAGS.phantomjs_timeout which is deprecated in favor' 'of FLAGS.capture_timeout - please update your config') capture_timeout = FL...
497,686
Build a CaptureAndDiffWorkflowItem for a test. Args: test_config: See test.yaml for structure of test_config. Returns: A CaptureAndDiffWorkflowItem
def run(self, test_config, ref_dir, tmp_dir, mode, heartbeat=None, num_attempts=0): assert 'name' in test_config name = test_config['name'] if 'ref' in test_config: # This test has different ref/run arms. assert 'run' in test_config arm_config = { 'n...
497,715
Initializer. Args: input_queue: Queue this worker consumes work from. output_queue: Queue where this worker puts new work items, if any.
def __init__(self, input_queue, output_queue): super(WorkerThread, self).__init__() self.daemon = True self.input_queue = input_queue self.output_queue = output_queue self.interrupted = False self.polltime = FLAGS.polltime
497,759
Initializer. Args: workflow: WorkflowItem instance this is for. generator: Current state of the WorkflowItem's generator. work: Next set of work to do. May be a single WorkItem object or a list or tuple that contains a set of WorkItems to run in ...
def __init__(self, workflow, generator, work): super(Barrier, self).__init__() self.workflow = workflow self.generator = generator if isinstance(work, (list, tuple)): self[:] = list(work) self.was_list = True self.wait_any = False eli...
497,763
Initializer. Args: input_queue: Queue this worker consumes work from. These should be WorkflowItems to process, or any WorkItems registered with this class using the register() method. output_queue: Queue where this worker puts finished work items, ...
def __init__(self, input_queue, output_queue): super(WorkflowThread, self).__init__(input_queue, output_queue) self.pending = PendingBarriers() self.worker_threads = [] self.register(WorkflowItem, input_queue)
497,769
Initializer. Args: max_attempts: Maximum number of attempts to make for this task, inclusive. So 2 means try two times and then retire the task. *args, **kwargs: Optional Exception arguments.
def __init__(self, max_attempts, *args, **kwargs): Exception.__init__(self, *args, **kwargs) self.max_attempts = max_attempts
497,776
Determines if the current user can access the build ID in the request. Args: param_name: Parameter name to use for getting the build ID from the request. Will fetch from GET or POST requests. Returns: The build the user has access to.
def can_user_access_build(param_name): build_id = ( request.args.get(param_name, type=int) or request.form.get(param_name, type=int) or request.json[param_name]) if not build_id: logging.debug('Build ID in param_name=%r was missing', param_name) abort(400) ops =...
497,784
Determines if the current API key can access the build in the request. Args: param_name: Parameter name to use for getting the build ID from the request. Will fetch from GET or POST requests. Returns: (api_key, build) The API Key and the Build it has access to.
def can_api_key_access_build(param_name): build_id = ( request.args.get(param_name, type=int) or request.form.get(param_name, type=int) or request.json[param_name]) utils.jsonify_assert(build_id, 'build_id required') if app.config.get('IGNORE_AUTH'): api_key = models.Ap...
497,788
Exits the program if the binary from the given flag doesn't run. Args: flag_name: Name of the flag that should be the path to the binary. process_args: Args to pass to the binary to do nothing but verify that it's working correctly (something like "--version") is good. Optio...
def verify_binary(flag_name, process_args=None): if process_args is None: process_args = [] path = getattr(FLAGS, flag_name) if not path: logging.error('Flag %r not set' % flag_name) sys.exit(1) with open(os.devnull, 'w') as dev_null: try: subprocess.ch...
497,798
Initializer. Args: log_path: Where to write the verbose logging output. ref_path: Path to reference screenshot to diff. run_path: Path to the most recent run screenshot to diff. output_path: Where the diff image should be written, if any.
def __init__(self, log_path, ref_path, run_path, output_path): process_worker.ProcessWorkflow.__init__( self, log_path, timeout_seconds=FLAGS.pdiff_timeout) self.ref_path = ref_path self.run_path = run_path self.output_path = output_path
497,817
Construct a CourseLocator Args: version_guid (string or ObjectId): optional unique id for the version org, course, run (string): the standard definition. Optional only if version_guid given branch (string): the branch such as 'draft', 'published', 'staged', 'beta'
def __init__(self, org=None, course=None, run=None, branch=None, version_guid=None, deprecated=False, **kwargs): offering_arg = kwargs.pop('offering', None) if offering_arg: warnings.warn( "offering is deprecated! Use course and run instead.", Depreca...
499,669
Construct a LibraryLocator Args: version_guid (string or ObjectId): optional unique id for the version org, library: the standard definition. Optional only if version_guid given. branch (string): the optional branch such as 'draft', 'published', 'staged', 'beta'
def __init__(self, org=None, library=None, branch=None, version_guid=None, **kwargs): if 'offering' in kwargs: raise ValueError("'offering' is not a valid field for a LibraryLocator.") if 'course' in kwargs: if library is not None: raise ValueError("Cann...
499,678
Return an instance of `cls` parsed from its `serialized` form. Args: cls: The :class:`OpaqueKey` subclass. serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed. Raises: InvalidKeyError: Should be raised if `serialized` is not a valid...
def _from_string(cls, serialized): if ':' not in serialized: raise InvalidKeyError( "BlockTypeKeyV1 keys must contain ':' separating the block family from the block_type.", serialized) family, __, block_type = serialized.partition(':') return cls(family, bloc...
499,733
Return an instance of `cls` parsed from its `serialized` form. Args: cls: The :class:`OpaqueKey` subclass. serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed. Raises: InvalidKeyError: Should be raised if `serialized` is not a valid...
def _from_string(cls, serialized): try: def_key, aside_type = _split_keys_v2(serialized) return cls(DefinitionKey.from_string(def_key), aside_type) except ValueError as exc: raise InvalidKeyError(cls, exc.args)
499,742
Return a new :class:`UsageKey` or :class:`AssetKey` representing this usage inside the course identified by the supplied :class:`CourseKey`. It returns the same type as `self` Args: course_key (:class:`CourseKey`): The course to map this object into. Returns: A ...
def map_into_course(self, course_key): return self.replace(usage_key=self.usage_key.map_into_course(course_key))
499,745