sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def remove_triple( self, subj: URIRef, pred: URIRef, obj: Union[URIRef, Literal] ) -> None: """ Removes triple from rdflib Graph You must input the triple in its URIRef or Literal form for each node exactly the way it was inputed or it wil...
Removes triple from rdflib Graph You must input the triple in its URIRef or Literal form for each node exactly the way it was inputed or it will not delete the triple. Args: subj: Entity subject to be removed it its the only node with this subject; else this is just...
entailment
def print_graph(self, format: str = 'turtle') -> str: """ prints serialized formated rdflib Graph """ print(self.g.serialize(format=format).decode('utf-8'))
prints serialized formated rdflib Graph
entailment
def identifierSearches(self, ids=None, LIMIT=25, _print=True, crawl=False): """parameters( data = "list of term_ids" )""" url_base = self.base_url + '/api/1/term/view/{id}' + '?key=' + self.api_ke...
parameters( data = "list of term_ids" )
entailment
def ilxSearches(self, ilx_ids=None, LIMIT=25, _print=True, crawl=False): """parameters( data = "list of ilx_ids" )""" url_base = self.base_url + "/api/1/ilx/search/identifier/{identifier}?key={APIKEY}" urls = [url_ba...
parameters( data = "list of ilx_ids" )
entailment
def updateTerms(self, data:list, LIMIT:int=20, _print:bool=True, crawl:bool=False,) -> list: """ Updates existing entities Args: data: needs: id <str> ilx_id <str> options: ...
Updates existing entities Args: data: needs: id <str> ilx_id <str> options: definition <str> #bug with qutations superclasses ...
entailment
def addTerms(self, data, LIMIT=25, _print=True, crawl=False): """ need: label <str> type term, cde, anntation, or relationship <str> options: definition <str> #bug with qutations sup...
need: label <str> type term, cde, anntation, or relationship <str> options: definition <str> #bug with qutations superclasses [{'id':<int>}] synonyms [{'literal':<str>}] ...
entailment
def getAnnotations_via_tid(self, tids, LIMIT=25, _print=True, crawl=False): """ tids = list of term ids that possess the annoations """ url_base = self.base_url + \...
tids = list of term ids that possess the annoations
entailment
def getAnnotations_via_id(self, annotation_ids, LIMIT=25, _print=True, crawl=False): """tids = list of strings or ints that are the ids of the annotations themselves""" url_base = self...
tids = list of strings or ints that are the ids of the annotations themselves
entailment
def updateAnnotations(self, data, LIMIT=25, _print=True, crawl=False,): """data = [{'id', 'tid', 'annotation_tid', 'value', 'comment', 'upvote', 'downvote', 'curator_status', 'withdrawn', 'term_versio...
data = [{'id', 'tid', 'annotation_tid', 'value', 'comment', 'upvote', 'downvote', 'curator_status', 'withdrawn', 'term_version', 'annotation_term_version', 'orig_uid', 'orig_time'}]
entailment
def deleteAnnotations(self, annotation_ids, LIMIT=25, _print=True, crawl=False,): """data = list of ids""" url_base = self.base_url + \ '/api/1/term/edit-annotation/{annotation_id}' # id ...
data = list of ids
entailment
def addRelationships( self, data: list, LIMIT: int = 20, _print: bool = True, crawl: bool = False, ) -> list: """ data = [{ "term1_id", "term2_id", "relationship_tid", "term1_version", "term2_version", "relationship_term...
data = [{ "term1_id", "term2_id", "relationship_tid", "term1_version", "term2_version", "relationship_term_version",}]
entailment
def deprecate_entity( self, ilx_id: str, note = None, ) -> None: """ Tagged term in interlex to warn this term is no longer used There isn't an proper way to delete a term and so we have to mark it so I can extrapolate that in mysql/ttl loads. Args: ...
Tagged term in interlex to warn this term is no longer used There isn't an proper way to delete a term and so we have to mark it so I can extrapolate that in mysql/ttl loads. Args: term_id: id of the term of which to be deprecated term_version: version of the term of wh...
entailment
def force_add_term(self, entity: dict): """ Need to add an entity that already has a label existing in InterLex? Well this is the function for you! entity: need: label <str> type term, cde, pde, fde, an...
Need to add an entity that already has a label existing in InterLex? Well this is the function for you! entity: need: label <str> type term, cde, pde, fde, anntation, or relationship <str> optio...
entailment
def create_df_file_with_query(self, query, output): """ Dumps in df in chunks to avoid crashes. """ chunk_size = 100000 offset = 0 data = defaultdict(lambda : defaultdict(list)) with open(output, 'wb') as outfile: query = query.replace(';', '') qu...
Dumps in df in chunks to avoid crashes.
entailment
def diff(s1, s2): ''' --word-diff=porcelain clone''' delta = difflib.Differ().compare(s1.split(), s2.split()) difflist = [] fullline = '' for line in delta: if line[0] == '?': continue elif line[0] == ' ': fullline += line.strip() + ' ' else: ...
--word-diff=porcelain clone
entailment
def diffcolor(s1, s2): ''' --word-diff=color clone ''' string = '' for line in diff(s1, s2): if line[0] == '-': string += ' ' + TermColors.red(line[2:]) elif line[0] == '+': string += ' ' + TermColors.green(line[2:]) else: string += ' ' + line ...
--word-diff=color clone
entailment
def create_html(s1, s2, output='test.html'): ''' creates basic html based on the diff of 2 strings ''' html = difflib.HtmlDiff().make_file(s1.split(), s2.split()) with open(output, 'w') as f: f.write(html)
creates basic html based on the diff of 2 strings
entailment
def traverse_data(obj, key_target): ''' will traverse nested list and dicts until key_target equals the current dict key ''' if isinstance(obj, str) and '.json' in str(obj): obj = json.load(open(obj, 'r')) if isinstance(obj, list): queue = obj.copy() elif isinstance(obj, dict): q...
will traverse nested list and dicts until key_target equals the current dict key
entailment
def json_diff(json1, json2, key_target, get_just_diff=True, porcelain=False): ''' creates a (keyname + diff) key within the json of the same layer which key_target resides. Ex: json1={'definition':'data of key_target'}, json2={'definition':'data of key_target'} key_target = 'definition' Usage: ...
creates a (keyname + diff) key within the json of the same layer which key_target resides. Ex: json1={'definition':'data of key_target'}, json2={'definition':'data of key_target'} key_target = 'definition' Usage: json_diff ( json_data1, json_data1 can be both [{..}] ...
entailment
def memoryCheck(vms_max_kb): """ Lookup vms_max using getCurrentVMSKb """ safety_factor = 1.2 vms_max = vms_max_kb vms_gigs = vms_max / 1024 ** 2 buffer = safety_factor * vms_max buffer_gigs = buffer / 1024 ** 2 vm = psutil.virtual_memory() free_gigs = vm.available / 1024 ** 2 if vm....
Lookup vms_max using getCurrentVMSKb
entailment
def _sequence_query(self): """ query all sequence rows """ klass = self.__class__ query = klass.select().where(klass.sequence.is_null(False)) seq_scope_field_names =\ (self.__seq_scope_field_name__ or '').split(',') for name in seq_scope_field_names: ...
query all sequence rows
entailment
def update_sheet_values(spreadsheet_name, sheet_name, values, spreadsheet_service=None): SPREADSHEET_ID = devconfig.secrets(spreadsheet_name) if spreadsheet_service is None: service = get_oauth_service(readonly=False) ss = service.spreadsheets() else: ss = spreadsheet_service """...
requests = [ {'updateCells': { 'start': {'sheetId': TODO, 'rowIndex': 0, 'columnIndex': 0} 'rows': {'values'} } }] response = ss.batchUpdate( spreadsheetId=SPREADSHEET_ID, range=sheet_name, body=body).execute...
entailment
def fetch(self, fetch_notes=None): """ update remote values (called automatically at __init__) """ if fetch_notes is None: fetch_notes = self.fetch_notes values, notes_index = get_sheet_values(self.name, self.sheet_name, spreadsheet_serv...
update remote values (called automatically at __init__)
entailment
def add_types(graph, phenotypes): # TODO missing expression phenotypes! also basket type somehow :( """ Add disjoint union classes so that it is possible to see the invariants associated with individual phenotypes """ collect = defaultdict(set) def recurse(id_, start, level=0): #print(leve...
Add disjoint union classes so that it is possible to see the invariants associated with individual phenotypes
entailment
def _rest_make_phenotypes(): #phenotype sources neuroner = Path(devconfig.git_local_base, 'neuroNER/resources/bluima/neuroner/hbp_morphology_ontology.obo').as_posix() neuroner1 = Path(devconfig.git_local_base, 'neuroNER/resources/bluima/neuroner/hbp_electrophysiology_ontolog...
print stuff print('matches') pprint(exact) pprint(similar) #print('EXACT', exact) print() for k, v in s2.items(): print(k) for k, v2 in sorted(v.items()): print(' ', k, ':', v2) #
entailment
def config(self): """ Allows changing the config on the fly """ # TODO more efficient to read once and put watch on the file config = {} if self.config_file.exists(): with open(self.config_file.as_posix(), 'rt') as f: # 3.5/pypy3 can't open Path directly conf...
Allows changing the config on the fly
entailment
def _get_service_account_info(self): """Retrieve json dict from service account file.""" with open(self.service_account_file, 'r') as f: info = json.load(f) self.service_account_email = info.get('client_email') if not self.service_account_email: raise GCECloudExc...
Retrieve json dict from service account file.
entailment
def _get_driver(self): """Get authenticated GCE driver.""" ComputeEngine = get_driver(Provider.GCE) return ComputeEngine( self.service_account_email, self.service_account_file, project=self.service_account_project )
Get authenticated GCE driver.
entailment
def _get_instance(self): """Retrieve instance matching instance_id.""" try: instance = self.compute_driver.ex_get_node( self.running_instance_id, zone=self.region ) except ResourceNotFoundError as e: raise GCECloudException( ...
Retrieve instance matching instance_id.
entailment
def _get_ssh_public_key(self): """Generate SSH public key from private key.""" key = ipa_utils.generate_public_ssh_key(self.ssh_private_key_file) return '{user}:{key} {user}'.format( user=self.ssh_user, key=key.decode() )
Generate SSH public key from private key.
entailment
def _launch_instance(self): """Launch an instance of the given image.""" metadata = {'key': 'ssh-keys', 'value': self.ssh_public_key} self.running_instance_id = ipa_utils.generate_instance_name( 'gce-ipa-test' ) self.logger.debug('ID of instance: %s' % self.running_in...
Launch an instance of the given image.
entailment
def _validate_region(self): """Validate region was passed in and is a valid GCE zone.""" if not self.region: raise GCECloudException( 'Zone is required for GCE cloud framework: ' 'Example: us-west1-a' ) try: zone = self.compute...
Validate region was passed in and is a valid GCE zone.
entailment
def _set_instance_ip(self): """Retrieve and set the instance ip address.""" instance = self._get_instance() if instance.public_ips: self.instance_ip = instance.public_ips[0] elif instance.private_ips: self.instance_ip = instance.private_ips[0] else: ...
Retrieve and set the instance ip address.
entailment
def _start_instance(self): """Start the instance.""" instance = self._get_instance() self.compute_driver.ex_start_node(instance) self.compute_driver.wait_until_running( [instance], timeout=self.timeout )
Start the instance.
entailment
def _stop_instance(self): """Stop the instance.""" instance = self._get_instance() self.compute_driver.ex_stop_node(instance) self._wait_on_instance('stopped', timeout=self.timeout)
Stop the instance.
entailment
def grab_rdflib_graph_version(g: Graph) -> str: ''' Crap-shot for ontology iri if its properly in the header and correctly formated ''' version = g.subject_objects( predicate = URIRef( OWL.versionIRI ) ) version = [o for s, o in version] if len(version) != 1: print('versionin...
Crap-shot for ontology iri if its properly in the header and correctly formated
entailment
def fix_ilx(self, ilx_id: str) -> str: ''' Database only excepts lower case and underscore version of ID ''' ilx_id = ilx_id.replace('http://uri.interlex.org/base/', '') if ilx_id[:4] not in ['TMP:', 'tmp_', 'ILX:', 'ilx_']: raise ValueError( 'Need to provide ilx ID w...
Database only excepts lower case and underscore version of ID
entailment
def pull_int_tail(self, string: str) -> str: ''' Useful for IDs that have giberish in the front of the real ID ''' int_tail = '' for element in string[::-1]: try: int(element) int_tail = element + int_tail except: pass ...
Useful for IDs that have giberish in the front of the real ID
entailment
def extract_fragment(self, iri: str) -> str: ''' Pulls only for code/ID from the iri I only add the str() conversion for the iri because rdflib objects need to be converted. ''' fragment = str(iri).rsplit('/')[-1].split(':', 1)[-1].split('#', 1)[-1].split('_', 1)[-1] return frag...
Pulls only for code/ID from the iri I only add the str() conversion for the iri because rdflib objects need to be converted.
entailment
def curie_search(self, curie:str) -> dict: ''' Returns the row in InterLex associated with the curie Note: Pressumed to not have duplicate curies in InterLex Args: curie: The "prefix:fragment_id" of the existing_id pertaining to the ontology Returns: ...
Returns the row in InterLex associated with the curie Note: Pressumed to not have duplicate curies in InterLex Args: curie: The "prefix:fragment_id" of the existing_id pertaining to the ontology Returns: None or dict
entailment
def fragment_search(self, fragement:str) -> List[dict]: ''' Returns the rows in InterLex associated with the fragment Note: Pressumed to have duplicate fragements in InterLex Args: fragment: The fragment_id of the curie pertaining to the ontology Returns: ...
Returns the rows in InterLex associated with the fragment Note: Pressumed to have duplicate fragements in InterLex Args: fragment: The fragment_id of the curie pertaining to the ontology Returns: None or List[dict]
entailment
def label_search(self, label:str) -> List[dict]: ''' Returns the rows in InterLex associated with that label Note: Pressumed to have duplicated labels in InterLex Args: label: label of the entity you want to find Returns: None or List[dict] ''...
Returns the rows in InterLex associated with that label Note: Pressumed to have duplicated labels in InterLex Args: label: label of the entity you want to find Returns: None or List[dict]
entailment
def readyup_entity( self, label: str, type: str, uid: Union[int, str] = None, comment: str = None, definition: str = None, superclass: str = None, synonyms: list = None, existing_ids: List[dict] = None, ) -> dict: ''' Setups the entity to b...
Setups the entity to be InterLex ready Args: label: name of entity type: entities type Can be any of the following: term, cde, fde, pde, annotation, relationship uid: usually fine and auto completes to api user ID, but if you provide one with a ...
entailment
def __exhaustive_diff(self, check_list:List[dict]) -> List[List[dict]]: ''' Helper for exhaustive checks to see if there any matches at all besides the anchor OUTPUT: [ { 'external_ontology_row' : {}, 'interlex_row' ...
Helper for exhaustive checks to see if there any matches at all besides the anchor OUTPUT: [ { 'external_ontology_row' : {}, 'interlex_row' : {}, 'same': {}, }, ...
entailment
def exhaustive_label_check( self, ontology:pd.DataFrame, label_predicate='rdfs:label', diff:bool=True, ) -> Tuple[list]: ''' All entities with conflicting labels gets a full diff Args: on...
All entities with conflicting labels gets a full diff Args: ontology: pandas DataFrame created from an ontology where the colnames are predicates and if classes exist it is also thrown into a the colnames. label_predicate: usually in qname form and is the...
entailment
def exhaustive_iri_check( self, ontology:pd.DataFrame, iri_predicate:str, diff:bool=True, ) -> Tuple[list]: ''' All entities with conflicting iris gets a full diff to see if they belong Args: o...
All entities with conflicting iris gets a full diff to see if they belong Args: ontology: pandas DataFrame created from an ontology where the colnames are predicates and if classes exist it is also thrown into a the colnames. iri_predicate: usually in qna...
entailment
def exhaustive_curie_check( self, ontology:pd.DataFrame, curie_predicate:str, curie_prefix:str, diff:bool=True, ) -> Tuple[list]: ''' All entities with conflicting curies gets a full d...
All entities with conflicting curies gets a full diff to see if they belong Args: ontology: pandas DataFrame created from an ontology where the colnames are predicates and if classes exist it is also thrown into a the colnames. curie_predicate: usually in...
entailment
def exhaustive_fragment_check( self, ontology:pd.DataFrame, iri_curie_fragment_predicate:str = 'iri', cross_reference_iris:bool = False, cross_reference_fragments:bool = False, ...
All entities with conflicting fragments gets a full diff to see if they belong Args: ontology: pandas DataFrame created from an ontology where the colnames are predicates and if classes exist it is also thrown into a the colnames. iri_curie_fragment_predi...
entailment
def exhaustive_ontology_ilx_diff_row_only( self, ontology_row: dict ) -> dict: ''' WARNING RUNTIME IS AWEFUL ''' results = [] header = ['Index'] + list(self.existing_ids.columns) for row in self.existing_ids.itertuples(): row = {header[i]:val for i, val in enumerate(row)} ...
WARNING RUNTIME IS AWEFUL
entailment
def combo_exhaustive_label_definition_check( self, ontology: pd.DataFrame, label_predicate:str, definition_predicates:str, d...
Combo of label & definition exhaustive check out of convenience Args: ontology: pandas DataFrame created from an ontology where the colnames are predicates and if classes exist it is also thrown into a the colnames. label_predicate: usually in qname form ...
entailment
def clear_cache(ip=None): """Clear the client cache or remove key matching the given ip.""" if ip: with ignored(Exception): client = CLIENT_CACHE[ip] del CLIENT_CACHE[ip] client.close() else: for client in CLIENT_CACHE.values(): with ignored(Ex...
Clear the client cache or remove key matching the given ip.
entailment
def establish_ssh_connection(ip, ssh_private_key_file, ssh_user, port, attempts=5, timeout=None): """ Establish ssh connection and return paramiko client. Raises:...
Establish ssh connection and return paramiko client. Raises: IpaSSHException: If connection cannot be established in given number of attempts.
entailment
def execute_ssh_command(client, cmd): """ Execute given command using paramiko. Returns: String output of cmd execution. Raises: IpaSSHException: If stderr returns a non-empty string. """ try: stdin, stdout, stderr = client.exec_command(cmd) err = stderr.read() ...
Execute given command using paramiko. Returns: String output of cmd execution. Raises: IpaSSHException: If stderr returns a non-empty string.
entailment
def extract_archive(client, archive_path, extract_path=None): """ Extract the archive in current path using the provided client. If extract_path is provided extract the archive there. """ command = 'tar -xf {path}'.format(path=archive_path) if extract_path: command += ' -C {extract_pat...
Extract the archive in current path using the provided client. If extract_path is provided extract the archive there.
entailment
def generate_public_ssh_key(ssh_private_key_file): """Generate SSH public key from private key file.""" try: with open(ssh_private_key_file, "rb") as key_file: key = key_file.read() except FileNotFoundError: raise IpaUtilsException( 'SSH private key file: %s cannot be...
Generate SSH public key from private key file.
entailment
def get_config_values(config_path, section, default='default'): """ Parse ini config file and return a dict of values. The provided section overrides any values in default section. """ values = {} if not os.path.isfile(config_path): raise IpaUtilsException( 'Config file not...
Parse ini config file and return a dict of values. The provided section overrides any values in default section.
entailment
def get_ssh_client(ip, ssh_private_key_file, ssh_user='root', port=22, timeout=600, wait_period=10): """Attempt to establish and test ssh connection.""" if ip in CLIENT_CACHE: return CLIENT_CACHE[ip] star...
Attempt to establish and test ssh connection.
entailment
def get_yaml_config(config_path): """ Load yaml config file and return dictionary. Todo: * This will need refactoring similar to the test search. """ config_path = os.path.expanduser(config_path) if not os.path.isfile(config_path): raise IpaUtilsException( 'Config fi...
Load yaml config file and return dictionary. Todo: * This will need refactoring similar to the test search.
entailment
def parse_sync_points(names, tests): """ Slice list of test names on sync points. If test is test file find full path to file. Returns: A list of test file sets and sync point strings. Examples: ['test_hard_reboot'] [set('test1', 'test2')] [set('test1', 'test2'), 't...
Slice list of test names on sync points. If test is test file find full path to file. Returns: A list of test file sets and sync point strings. Examples: ['test_hard_reboot'] [set('test1', 'test2')] [set('test1', 'test2'), 'test_soft_reboot'] [set('test1', 'test2'),...
entailment
def put_file(client, source_file, destination_file): """ Copy file to instance using Paramiko client connection. """ try: sftp_client = client.open_sftp() sftp_client.put(source_file, destination_file) except Exception as error: raise IpaUtilsException( 'Error cop...
Copy file to instance using Paramiko client connection.
entailment
def redirect_output(fileobj): """Redirect standard out to file.""" old = sys.stdout sys.stdout = fileobj try: yield fileobj finally: sys.stdout = old
Redirect standard out to file.
entailment
def ssh_config(ssh_user, ssh_private_key_file): """Create temporary ssh config file.""" try: ssh_file = NamedTemporaryFile(delete=False, mode='w+') ssh_file.write('Host *\n') ssh_file.write(' IdentityFile %s\n' % ssh_private_key_file) ssh_file.write(' User %s' % ssh_user) ...
Create temporary ssh config file.
entailment
def update_history_log(history_log, clear=False, description=None, test_log=None): """ Update the history log file with item. If clear flag is provided the log file is deleted. """ if not test_log and not clear: raise IpaUt...
Update the history log file with item. If clear flag is provided the log file is deleted.
entailment
def validate(self, value): """Validate string by regex :param value: str :return: """ if not self._compiled_regex.match(value): raise ValidationError( 'value {:s} not match r"{:s}"'.format(value, self._regex))
Validate string by regex :param value: str :return:
entailment
def ontology2df(self): '''Updates self.g or self.path bc you could only choose 1''' if isinstance(self.path, str) or isinstance(self.path, p): self.path = str(self.path) filetype = p(self.path).suffix if filetype == '.json': self.g = None ...
Updates self.g or self.path bc you could only choose 1
entailment
def create_pred2common(self): ''' Takes list linked to common name and maps common name to accepted predicate and their respected suffixes to decrease sensitivity. ''' self.pred2common = {} for common_name, ext_preds in self.common2preds.items(): for pred in ext_p...
Takes list linked to common name and maps common name to accepted predicate and their respected suffixes to decrease sensitivity.
entailment
def clean_pred(self, pred, ignore_warning=False): ''' Takes the predicate and returns the suffix, lower case, stripped version ''' original_pred = pred pred = pred.lower().strip() if 'http' in pred: pred = pred.split('/')[-1] elif ':' in pred: if p...
Takes the predicate and returns the suffix, lower case, stripped version
entailment
def get_common_pred(self, pred): ''' Gets version of predicate and sees if we have a translation to a common relation. INPUT: pred = predicate from the triple OUTPUT: Common relationship or None ''' pred = self.clean_pred(pred) comm...
Gets version of predicate and sees if we have a translation to a common relation. INPUT: pred = predicate from the triple OUTPUT: Common relationship or None
entailment
def _create_network_interface( self, ip_config_name, nic_name, public_ip, region, resource_group_name, subnet, accelerated_networking=False ): """ Create a network interface in the resource group. Attach NIC to the subnet and public IP provided. """ nic_confi...
Create a network interface in the resource group. Attach NIC to the subnet and public IP provided.
entailment
def _create_public_ip(self, public_ip_name, resource_group_name, region): """ Create dynamic public IP address in the resource group. """ public_ip_config = { 'location': region, 'public_ip_allocation_method': 'Dynamic' } try: public_i...
Create dynamic public IP address in the resource group.
entailment
def _create_resource_group(self, region, resource_group_name): """ Create resource group if it does not exist. """ resource_group_config = {'location': region} try: self.resource.resource_groups.create_or_update( resource_group_name, resource_group_co...
Create resource group if it does not exist.
entailment
def _create_storage_profile(self): """ Create the storage profile for the instance. Image reference can be a custom image name or a published urn. """ if self.image_publisher: storage_profile = { 'image_reference': { 'publisher': s...
Create the storage profile for the instance. Image reference can be a custom image name or a published urn.
entailment
def _create_subnet(self, resource_group_name, subnet_id, vnet_name): """ Create a subnet in the provided vnet and resource group. """ subnet_config = {'address_prefix': '10.0.0.0/29'} try: subnet_setup = self.network.subnets.create_or_update( resource...
Create a subnet in the provided vnet and resource group.
entailment
def _create_virtual_network(self, region, resource_group_name, vnet_name): """ Create a vnet in the given resource group with default address space. """ vnet_config = { 'location': region, 'address_space': { 'address_prefixes': ['10.0.0.0/27'] ...
Create a vnet in the given resource group with default address space.
entailment
def _create_vm(self, vm_config): """ Attempt to create or update VM instance based on vm_parameters config. """ try: vm_setup = self.compute.virtual_machines.create_or_update( self.running_instance_id, self.running_instance_id, vm_config ...
Attempt to create or update VM instance based on vm_parameters config.
entailment
def _create_vm_config(self, interface): """ Create the VM config dictionary. Requires an existing network interface object. """ # Split image ID into it's components. self._process_image_id() hardware_profile = { 'vm_size': self.instance_type or AZUR...
Create the VM config dictionary. Requires an existing network interface object.
entailment
def _get_instance(self): """ Return the instance matching the running_instance_id. """ try: instance = self.compute.virtual_machines.get( self.running_instance_id, self.running_instance_id, expand='instanceView' ) except Exc...
Return the instance matching the running_instance_id.
entailment
def _get_instance_state(self): """ Retrieve state of instance. """ instance = self._get_instance() statuses = instance.instance_view.statuses for status in statuses: if status.code.startswith('PowerState'): return status.display_status
Retrieve state of instance.
entailment
def _get_management_client(self, client_class): """ Return instance of resource management client. """ try: client = get_client_from_auth_file( client_class, auth_path=self.service_account_file ) except ValueError as error: rais...
Return instance of resource management client.
entailment
def _launch_instance(self): """ Create new test instance in a resource group with the same name. """ self.running_instance_id = ipa_utils.generate_instance_name( 'azure-ipa-test' ) self.logger.debug('ID of instance: %s' % self.running_instance_id) self...
Create new test instance in a resource group with the same name.
entailment
def _process_image_id(self): """ Split image id into component values. Example: SUSE:SLES:12-SP3:2018.01.04 Publisher:Offer:Sku:Version Raises: If image_id is not a valid format. """ try: image_info = self.image_id.strip().split(...
Split image id into component values. Example: SUSE:SLES:12-SP3:2018.01.04 Publisher:Offer:Sku:Version Raises: If image_id is not a valid format.
entailment
def _set_default_resource_names(self): """ Generate names for resources based on the running_instance_id. """ self.ip_config_name = ''.join([ self.running_instance_id, '-ip-config' ]) self.nic_name = ''.join([self.running_instance_id, '-nic']) self.pub...
Generate names for resources based on the running_instance_id.
entailment
def _set_image_id(self): """ If an existing instance is used get image id from deployment. """ instance = self._get_instance() image_info = instance.storage_profile.image_reference if image_info.publisher: self.image_id = ':'.join([ image_info...
If an existing instance is used get image id from deployment.
entailment
def _set_instance_ip(self): """ Get the IP address based on instance ID. If public IP address not found attempt to get private IP. """ try: ip_address = self.network.public_ip_addresses.get( self.running_instance_id, self.public_ip_name )....
Get the IP address based on instance ID. If public IP address not found attempt to get private IP.
entailment
def _start_instance(self): """ Start the instance. """ try: vm_start = self.compute.virtual_machines.start( self.running_instance_id, self.running_instance_id ) except Exception as error: raise AzureCloudException( ...
Start the instance.
entailment
def _stop_instance(self): """ Stop the instance. """ try: vm_stop = self.compute.virtual_machines.power_off( self.running_instance_id, self.running_instance_id ) except Exception as error: raise AzureCloudException( ...
Stop the instance.
entailment
def _terminate_instance(self): """ Terminate the resource group and instance. """ try: self.resource.resource_groups.delete(self.running_instance_id) except Exception as error: raise AzureCloudException( 'Unable to terminate resource group:...
Terminate the resource group and instance.
entailment
def preferred_change(data): ''' Determines preferred existing id based on curie prefix in the ranking list ''' ranking = [ 'CHEBI', 'NCBITaxon', 'COGPO', 'CAO', 'DICOM', 'UBERON', 'NLX', 'NLXANAT', 'NLXCELL', 'NLXFUNC', 'NLX...
Determines preferred existing id based on curie prefix in the ranking list
entailment
def merge(new, old): ''' synonyms and existing_ids are part of an object bug that can create duplicates if in the same batch ''' for k, vals in new.items(): if k == 'synonyms': new_synonyms = vals if old['synonyms']: old_literals = [syn['literal'].lower().strip(...
synonyms and existing_ids are part of an object bug that can create duplicates if in the same batch
entailment
def main(context, no_color): """ Ipa provides a Python API and command line utility for testing images. It can be used to test images in the Public Cloud (AWS, Azure, GCE, etc.). """ if context.obj is None: context.obj = {} context.obj['no_color'] = no_color
Ipa provides a Python API and command line utility for testing images. It can be used to test images in the Public Cloud (AWS, Azure, GCE, etc.).
entailment
def results(context, history_log): """Process provided history log and results files.""" if context.obj is None: context.obj = {} context.obj['history_log'] = history_log if context.invoked_subcommand is None: context.invoke(show, item=1)
Process provided history log and results files.
entailment
def archive(context, clear_log, items, path, name): """ Archive the history log and all results/log files. After archive is created optionally clear the history log. """ history_log = context.obj['history_log'] no_color = context.obj['no_color'] with open(history_log, 'r') as f: # ...
Archive the history log and all results/log files. After archive is created optionally clear the history log.
entailment
def delete(context, item): """ Delete the specified history item from the history log. """ history_log = context.obj['history_log'] no_color = context.obj['no_color'] try: with open(history_log, 'r+') as f: lines = f.readlines() history = lines.pop(len(lines) - it...
Delete the specified history item from the history log.
entailment
def show(context, log, results_file, verbose, item): """ Print test results info from provided results json file. If no results file is supplied echo results from most recent test in history if it exists. If verbose option selected, echo all test cases. If ...
Print test results info from provided results json file. If no results file is supplied echo results from most recent test in history if it exists. If verbose option selected, echo all test cases. If log option selected echo test log.
entailment
def _get_ssh_client(self): """Return a new or existing SSH client for given ip.""" return ipa_utils.get_ssh_client( self.instance_ip, self.ssh_private_key_file, self.ssh_user, timeout=self.timeout )
Return a new or existing SSH client for given ip.
entailment
def _log_info(self): """Output test run information to top of log file.""" if self.cloud == 'ssh': self.results['info'] = { 'platform': self.cloud, 'distro': self.distro_name, 'image': self.instance_ip, 'timestamp': self.time_st...
Output test run information to top of log file.
entailment
def _write_to_log(self, output): """Write the output string to the log file.""" with open(self.log_file, 'a') as log_file: log_file.write('\n') log_file.write(output) log_file.write('\n')
Write the output string to the log file.
entailment
def _merge_results(self, results): """Combine results of test run with exisiting dict.""" self.results['tests'] += results['tests'] for key, value in results['summary'].items(): self.results['summary'][key] += value
Combine results of test run with exisiting dict.
entailment
def _save_results(self): """Save results dictionary to json file.""" with open(self.results_file, 'w') as results_file: json.dump(self.results, results_file)
Save results dictionary to json file.
entailment
def _set_distro(self): """Determine distro for image and create instance of class.""" if self.distro_name == 'sles': self.distro = SLES() elif self.distro_name == 'opensuse_leap': self.distro = openSUSE_Leap() else: raise IpaCloudException( ...
Determine distro for image and create instance of class.
entailment