repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
tgbugs/pyontutils | ilxutils/ilxutils/simple_rdflib.py | SimpleGraph.print_graph | def print_graph(self, format: str = 'turtle') -> str:
""" prints serialized formated rdflib Graph """
print(self.g.serialize(format=format).decode('utf-8')) | python | def print_graph(self, format: str = 'turtle') -> str:
""" prints serialized formated rdflib Graph """
print(self.g.serialize(format=format).decode('utf-8')) | [
"def",
"print_graph",
"(",
"self",
",",
"format",
":",
"str",
"=",
"'turtle'",
")",
"->",
"str",
":",
"print",
"(",
"self",
".",
"g",
".",
"serialize",
"(",
"format",
"=",
"format",
")",
".",
"decode",
"(",
"'utf-8'",
")",
")"
] | prints serialized formated rdflib Graph | [
"prints",
"serialized",
"formated",
"rdflib",
"Graph"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_rdflib.py#L310-L312 | train | 39,100 |
tgbugs/pyontutils | ilxutils/ilxutils/scicrunch_client.py | scicrunch.updateTerms | 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:
definition <str> #bug with qutations
superclasses [{'id':<int>}]
type term, cde, anntation, or relationship <str>
synonyms {'literal':<str>}
existing_ids {'iri':<str>,'curie':<str>','change':<bool>, 'delete':<bool>}
LIMIT:
limit of concurrent
_print:
prints label of data presented
crawl:
True: Uses linear requests.
False: Uses concurrent requests from the asyncio and aiohttp modules
Returns:
List of filled in data parallel with the input data. If any entity failed with an
ignorable reason, it will return empty for the item in the list returned.
"""
url_base = self.base_url + '/api/1/term/edit/{id}'
merged_data = []
# PHP on the server is is LOADED with bugs. Best to just duplicate entity data and change
# what you need in it before re-upserting the data.
old_data = self.identifierSearches(
[d['id'] for d in data], # just need the ids
LIMIT = LIMIT,
_print = _print,
crawl = crawl,
)
for d in data: # d for dictionary
url = url_base.format(id=str(d['id']))
# Reason this exists is to avoid contradictions in case you are using a local reference
if d['ilx'] != old_data[int(d['id'])]['ilx']:
print(d['ilx'], old_data[int(d['id'])]['ilx'])
exit('You might be using beta insead of production!')
merged = scicrunch_client_helper.merge(new=d, old=old_data[int(d['id'])])
merged = scicrunch_client_helper.superclasses_bug_fix(merged) # BUG: superclass output diff than input needed
merged_data.append((url, merged))
resp = self.post(
merged_data,
LIMIT = LIMIT,
action = 'Updating Terms', # forced input from each function
_print = _print,
crawl = crawl,
)
return resp | python | 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:
definition <str> #bug with qutations
superclasses [{'id':<int>}]
type term, cde, anntation, or relationship <str>
synonyms {'literal':<str>}
existing_ids {'iri':<str>,'curie':<str>','change':<bool>, 'delete':<bool>}
LIMIT:
limit of concurrent
_print:
prints label of data presented
crawl:
True: Uses linear requests.
False: Uses concurrent requests from the asyncio and aiohttp modules
Returns:
List of filled in data parallel with the input data. If any entity failed with an
ignorable reason, it will return empty for the item in the list returned.
"""
url_base = self.base_url + '/api/1/term/edit/{id}'
merged_data = []
# PHP on the server is is LOADED with bugs. Best to just duplicate entity data and change
# what you need in it before re-upserting the data.
old_data = self.identifierSearches(
[d['id'] for d in data], # just need the ids
LIMIT = LIMIT,
_print = _print,
crawl = crawl,
)
for d in data: # d for dictionary
url = url_base.format(id=str(d['id']))
# Reason this exists is to avoid contradictions in case you are using a local reference
if d['ilx'] != old_data[int(d['id'])]['ilx']:
print(d['ilx'], old_data[int(d['id'])]['ilx'])
exit('You might be using beta insead of production!')
merged = scicrunch_client_helper.merge(new=d, old=old_data[int(d['id'])])
merged = scicrunch_client_helper.superclasses_bug_fix(merged) # BUG: superclass output diff than input needed
merged_data.append((url, merged))
resp = self.post(
merged_data,
LIMIT = LIMIT,
action = 'Updating Terms', # forced input from each function
_print = _print,
crawl = crawl,
)
return resp | [
"def",
"updateTerms",
"(",
"self",
",",
"data",
":",
"list",
",",
"LIMIT",
":",
"int",
"=",
"20",
",",
"_print",
":",
"bool",
"=",
"True",
",",
"crawl",
":",
"bool",
"=",
"False",
",",
")",
"->",
"list",
":",
"url_base",
"=",
"self",
".",
"base_u... | Updates existing entities
Args:
data:
needs:
id <str>
ilx_id <str>
options:
definition <str> #bug with qutations
superclasses [{'id':<int>}]
type term, cde, anntation, or relationship <str>
synonyms {'literal':<str>}
existing_ids {'iri':<str>,'curie':<str>','change':<bool>, 'delete':<bool>}
LIMIT:
limit of concurrent
_print:
prints label of data presented
crawl:
True: Uses linear requests.
False: Uses concurrent requests from the asyncio and aiohttp modules
Returns:
List of filled in data parallel with the input data. If any entity failed with an
ignorable reason, it will return empty for the item in the list returned. | [
"Updates",
"existing",
"entities"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/scicrunch_client.py#L340-L398 | train | 39,101 |
tgbugs/pyontutils | ilxutils/ilxutils/scicrunch_client.py | scicrunch.getAnnotations_via_tid | 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 + \
'/api/1/term/get-annotations/{tid}?key=' + self.api_key
urls = [url_base.format(tid=str(tid)) for tid in tids]
return self.get(urls,
LIMIT=LIMIT,
_print=_print,
crawl=crawl) | python | 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 + \
'/api/1/term/get-annotations/{tid}?key=' + self.api_key
urls = [url_base.format(tid=str(tid)) for tid in tids]
return self.get(urls,
LIMIT=LIMIT,
_print=_print,
crawl=crawl) | [
"def",
"getAnnotations_via_tid",
"(",
"self",
",",
"tids",
",",
"LIMIT",
"=",
"25",
",",
"_print",
"=",
"True",
",",
"crawl",
"=",
"False",
")",
":",
"url_base",
"=",
"self",
".",
"base_url",
"+",
"'/api/1/term/get-annotations/{tid}?key='",
"+",
"self",
".",... | tids = list of term ids that possess the annoations | [
"tids",
"=",
"list",
"of",
"term",
"ids",
"that",
"possess",
"the",
"annoations"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/scicrunch_client.py#L502-L516 | train | 39,102 |
tgbugs/pyontutils | ilxutils/ilxutils/scicrunch_client.py | scicrunch.getAnnotations_via_id | 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.base_url + \
'/api/1/term/get-annotation/{id}?key=' + self.api_key
urls = [
url_base.format(id=str(annotation_id))
for annotation_id in annotation_ids
]
return self.get(urls, LIMIT=LIMIT, _print=_print, crawl=crawl) | python | 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.base_url + \
'/api/1/term/get-annotation/{id}?key=' + self.api_key
urls = [
url_base.format(id=str(annotation_id))
for annotation_id in annotation_ids
]
return self.get(urls, LIMIT=LIMIT, _print=_print, crawl=crawl) | [
"def",
"getAnnotations_via_id",
"(",
"self",
",",
"annotation_ids",
",",
"LIMIT",
"=",
"25",
",",
"_print",
"=",
"True",
",",
"crawl",
"=",
"False",
")",
":",
"url_base",
"=",
"self",
".",
"base_url",
"+",
"'/api/1/term/get-annotation/{id}?key='",
"+",
"self",... | tids = list of strings or ints that are the ids of the annotations themselves | [
"tids",
"=",
"list",
"of",
"strings",
"or",
"ints",
"that",
"are",
"the",
"ids",
"of",
"the",
"annotations",
"themselves"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/scicrunch_client.py#L518-L530 | train | 39,103 |
tgbugs/pyontutils | ilxutils/ilxutils/scicrunch_client.py | scicrunch.deleteAnnotations | 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 of annotation not term id; thx past troy!
annotations = self.getAnnotations_via_id(annotation_ids,
LIMIT=LIMIT,
_print=_print,
crawl=crawl)
annotations_to_delete = []
for annotation_id in annotation_ids:
annotation = annotations[int(annotation_id)]
params = {
'value': ' ', # for delete
'annotation_tid': ' ', # for delete
'tid': ' ', # for delete
'term_version': '1',
'annotation_term_version': '1',
}
url = url_base.format(annotation_id=annotation_id)
annotation.update({**params})
annotations_to_delete.append((url, annotation))
return self.post(annotations_to_delete,
LIMIT=LIMIT,
_print=_print,
crawl=crawl) | python | 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 of annotation not term id; thx past troy!
annotations = self.getAnnotations_via_id(annotation_ids,
LIMIT=LIMIT,
_print=_print,
crawl=crawl)
annotations_to_delete = []
for annotation_id in annotation_ids:
annotation = annotations[int(annotation_id)]
params = {
'value': ' ', # for delete
'annotation_tid': ' ', # for delete
'tid': ' ', # for delete
'term_version': '1',
'annotation_term_version': '1',
}
url = url_base.format(annotation_id=annotation_id)
annotation.update({**params})
annotations_to_delete.append((url, annotation))
return self.post(annotations_to_delete,
LIMIT=LIMIT,
_print=_print,
crawl=crawl) | [
"def",
"deleteAnnotations",
"(",
"self",
",",
"annotation_ids",
",",
"LIMIT",
"=",
"25",
",",
"_print",
"=",
"True",
",",
"crawl",
"=",
"False",
",",
")",
":",
"url_base",
"=",
"self",
".",
"base_url",
"+",
"'/api/1/term/edit-annotation/{annotation_id}'",
"# i... | data = list of ids | [
"data",
"=",
"list",
"of",
"ids"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/scicrunch_client.py#L560-L588 | train | 39,104 |
tgbugs/pyontutils | ilxutils/ilxutils/scicrunch_client.py | scicrunch.deprecate_entity | 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:
term_id: id of the term of which to be deprecated
term_version: version of the term of which to be deprecated
Example: deprecateTerm('ilx_0101431', '6')
"""
term_id, term_version = [(d['id'], d['version'])
for d in self.ilxSearches([ilx_id], crawl=True, _print=False).values()][0]
annotations = [{
'tid': term_id,
'annotation_tid': '306375', # id for annotation "deprecated"
'value': 'True',
'term_version': term_version,
'annotation_term_version': '1', # term version for annotation "deprecated"
}]
if note:
editor_note = {
'tid': term_id,
'annotation_tid': '306378', # id for annotation "editorNote"
'value': note,
'term_version': term_version,
'annotation_term_version': '1', # term version for annotation "deprecated"
}
annotations.append(editor_note)
self.addAnnotations(annotations, crawl=True, _print=False)
print(annotations) | python | 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:
term_id: id of the term of which to be deprecated
term_version: version of the term of which to be deprecated
Example: deprecateTerm('ilx_0101431', '6')
"""
term_id, term_version = [(d['id'], d['version'])
for d in self.ilxSearches([ilx_id], crawl=True, _print=False).values()][0]
annotations = [{
'tid': term_id,
'annotation_tid': '306375', # id for annotation "deprecated"
'value': 'True',
'term_version': term_version,
'annotation_term_version': '1', # term version for annotation "deprecated"
}]
if note:
editor_note = {
'tid': term_id,
'annotation_tid': '306378', # id for annotation "editorNote"
'value': note,
'term_version': term_version,
'annotation_term_version': '1', # term version for annotation "deprecated"
}
annotations.append(editor_note)
self.addAnnotations(annotations, crawl=True, _print=False)
print(annotations) | [
"def",
"deprecate_entity",
"(",
"self",
",",
"ilx_id",
":",
"str",
",",
"note",
"=",
"None",
",",
")",
"->",
"None",
":",
"term_id",
",",
"term_version",
"=",
"[",
"(",
"d",
"[",
"'id'",
"]",
",",
"d",
"[",
"'version'",
"]",
")",
"for",
"d",
"in"... | 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 which to be deprecated
Example: deprecateTerm('ilx_0101431', '6') | [
"Tagged",
"term",
"in",
"interlex",
"to",
"warn",
"this",
"term",
"is",
"no",
"longer",
"used"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/scicrunch_client.py#L647-L684 | train | 39,105 |
tgbugs/pyontutils | ilxutils/ilxutils/scicrunch_client.py | scicrunch.force_add_term | 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, anntation, or relationship <str>
options:
definition <str>
superclasses [{'id':<int>}]
synonyms [{'literal':<str>}]
existing_ids [{'iri':<str>,'curie':<str>'}]
ontologies [{'id':<int>}]
example:
entity = [{
'type':'term',
'label':'brain',
'existing_ids': [{
'iri':'http://ncbi.org/123',
'curie':'NCBI:123'
}]
}]
"""
needed = set([
'label',
'type',
])
url_ilx_add = self.base_url + '/api/1/ilx/add'
url_term_add = self.base_url + '/api/1/term/add'
url_term_update = self.base_url + '/api/1/term/edit/{id}'
if (set(list(entity)) & needed) != needed:
exit('You need keys: '+ str(needed - set(list(d))))
# to ensure uniqueness
random_string = ''.join(random.choices(string.ascii_uppercase + string.digits, k=25))
real_label = entity['label']
entity['label'] = entity['label'] + '_' + random_string
entity['term'] = entity.pop('label') # ilx only accepts term, will need to replaced back
primer_response = self.post([(url_ilx_add, entity.copy())], _print=False, crawl=True)[0]
entity['label'] = entity.pop('term')
entity['ilx'] = primer_response['fragment'] if primer_response.get('fragment') else primer_response['ilx']
entity = scicrunch_client_helper.superclasses_bug_fix(entity)
response = self.post([(url_term_add, entity.copy())], _print=False, crawl=True)[0]
old_data = self.identifierSearches(
[response['id']], # just need the ids
_print = False,
crawl = True,
)[response['id']]
old_data['label'] = real_label
entity = old_data.copy()
url_term_update = url_term_update.format(id=entity['id'])
return self.post([(url_term_update, entity)], _print=False, crawl=True) | python | 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, anntation, or relationship <str>
options:
definition <str>
superclasses [{'id':<int>}]
synonyms [{'literal':<str>}]
existing_ids [{'iri':<str>,'curie':<str>'}]
ontologies [{'id':<int>}]
example:
entity = [{
'type':'term',
'label':'brain',
'existing_ids': [{
'iri':'http://ncbi.org/123',
'curie':'NCBI:123'
}]
}]
"""
needed = set([
'label',
'type',
])
url_ilx_add = self.base_url + '/api/1/ilx/add'
url_term_add = self.base_url + '/api/1/term/add'
url_term_update = self.base_url + '/api/1/term/edit/{id}'
if (set(list(entity)) & needed) != needed:
exit('You need keys: '+ str(needed - set(list(d))))
# to ensure uniqueness
random_string = ''.join(random.choices(string.ascii_uppercase + string.digits, k=25))
real_label = entity['label']
entity['label'] = entity['label'] + '_' + random_string
entity['term'] = entity.pop('label') # ilx only accepts term, will need to replaced back
primer_response = self.post([(url_ilx_add, entity.copy())], _print=False, crawl=True)[0]
entity['label'] = entity.pop('term')
entity['ilx'] = primer_response['fragment'] if primer_response.get('fragment') else primer_response['ilx']
entity = scicrunch_client_helper.superclasses_bug_fix(entity)
response = self.post([(url_term_add, entity.copy())], _print=False, crawl=True)[0]
old_data = self.identifierSearches(
[response['id']], # just need the ids
_print = False,
crawl = True,
)[response['id']]
old_data['label'] = real_label
entity = old_data.copy()
url_term_update = url_term_update.format(id=entity['id'])
return self.post([(url_term_update, entity)], _print=False, crawl=True) | [
"def",
"force_add_term",
"(",
"self",
",",
"entity",
":",
"dict",
")",
":",
"needed",
"=",
"set",
"(",
"[",
"'label'",
",",
"'type'",
",",
"]",
")",
"url_ilx_add",
"=",
"self",
".",
"base_url",
"+",
"'/api/1/ilx/add'",
"url_term_add",
"=",
"self",
".",
... | 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>
options:
definition <str>
superclasses [{'id':<int>}]
synonyms [{'literal':<str>}]
existing_ids [{'iri':<str>,'curie':<str>'}]
ontologies [{'id':<int>}]
example:
entity = [{
'type':'term',
'label':'brain',
'existing_ids': [{
'iri':'http://ncbi.org/123',
'curie':'NCBI:123'
}]
}] | [
"Need",
"to",
"add",
"an",
"entity",
"that",
"already",
"has",
"a",
"label",
"existing",
"in",
"InterLex?",
"Well",
"this",
"is",
"the",
"function",
"for",
"you!"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/scicrunch_client.py#L783-L841 | train | 39,106 |
tgbugs/pyontutils | ilxutils/ilxutils/mydifflib.py | create_html | 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) | python | 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) | [
"def",
"create_html",
"(",
"s1",
",",
"s2",
",",
"output",
"=",
"'test.html'",
")",
":",
"html",
"=",
"difflib",
".",
"HtmlDiff",
"(",
")",
".",
"make_file",
"(",
"s1",
".",
"split",
"(",
")",
",",
"s2",
".",
"split",
"(",
")",
")",
"with",
"open... | creates basic html based on the diff of 2 strings | [
"creates",
"basic",
"html",
"based",
"on",
"the",
"diff",
"of",
"2",
"strings"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/mydifflib.py#L45-L49 | train | 39,107 |
tgbugs/pyontutils | ilxutils/ilxutils/mydifflib.py | traverse_data | 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):
queue = [obj.copy()]
else:
sys.exit('obj needs to be a list or dict')
count = 0
''' BFS '''
while not queue or count != 1000:
count += 1
curr_obj = queue.pop()
if isinstance(curr_obj, dict):
for key, value in curr_obj.items():
if key == key_target:
return curr_obj
else:
queue.append(curr_obj[key])
elif isinstance(curr_obj, list):
for co in curr_obj:
queue.append(co)
if count == 1000:
sys.exit('traverse_data needs to be updated...')
return False | python | 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):
queue = [obj.copy()]
else:
sys.exit('obj needs to be a list or dict')
count = 0
''' BFS '''
while not queue or count != 1000:
count += 1
curr_obj = queue.pop()
if isinstance(curr_obj, dict):
for key, value in curr_obj.items():
if key == key_target:
return curr_obj
else:
queue.append(curr_obj[key])
elif isinstance(curr_obj, list):
for co in curr_obj:
queue.append(co)
if count == 1000:
sys.exit('traverse_data needs to be updated...')
return False | [
"def",
"traverse_data",
"(",
"obj",
",",
"key_target",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
"and",
"'.json'",
"in",
"str",
"(",
"obj",
")",
":",
"obj",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"obj",
",",
"'r'",
")",
")",... | will traverse nested list and dicts until key_target equals the current dict key | [
"will",
"traverse",
"nested",
"list",
"and",
"dicts",
"until",
"key_target",
"equals",
"the",
"current",
"dict",
"key"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/mydifflib.py#L52-L78 | train | 39,108 |
tgbugs/pyontutils | pyontutils/utils_extra.py | memoryCheck | 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.available < buffer:
raise MemoryError('Running this requires quite a bit of memory ~ '
f'{vms_gigs:.2f}, you have {free_gigs:.2f} of the '
f'{buffer_gigs:.2f} needed') | python | 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.available < buffer:
raise MemoryError('Running this requires quite a bit of memory ~ '
f'{vms_gigs:.2f}, you have {free_gigs:.2f} of the '
f'{buffer_gigs:.2f} needed') | [
"def",
"memoryCheck",
"(",
"vms_max_kb",
")",
":",
"safety_factor",
"=",
"1.2",
"vms_max",
"=",
"vms_max_kb",
"vms_gigs",
"=",
"vms_max",
"/",
"1024",
"**",
"2",
"buffer",
"=",
"safety_factor",
"*",
"vms_max",
"buffer_gigs",
"=",
"buffer",
"/",
"1024",
"**",... | Lookup vms_max using getCurrentVMSKb | [
"Lookup",
"vms_max",
"using",
"getCurrentVMSKb"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/utils_extra.py#L76-L88 | train | 39,109 |
shanbay/peeweext | peeweext/mixins.py | SequenceMixin._sequence_query | 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:
seq_scope_field = getattr(klass, name, None)
if seq_scope_field:
seq_scope_field_value = getattr(self, name)
query = query.where(seq_scope_field == seq_scope_field_value)
return query | python | 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:
seq_scope_field = getattr(klass, name, None)
if seq_scope_field:
seq_scope_field_value = getattr(self, name)
query = query.where(seq_scope_field == seq_scope_field_value)
return query | [
"def",
"_sequence_query",
"(",
"self",
")",
":",
"klass",
"=",
"self",
".",
"__class__",
"query",
"=",
"klass",
".",
"select",
"(",
")",
".",
"where",
"(",
"klass",
".",
"sequence",
".",
"is_null",
"(",
"False",
")",
")",
"seq_scope_field_names",
"=",
... | query all sequence rows | [
"query",
"all",
"sequence",
"rows"
] | ff62a3d01e4584d50fde1944b9616c3b4236ecf0 | https://github.com/shanbay/peeweext/blob/ff62a3d01e4584d50fde1944b9616c3b4236ecf0/peeweext/mixins.py#L29-L42 | train | 39,110 |
tgbugs/pyontutils | neurondm/neurondm/build.py | add_types | 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(level)
for t in graph.g.triples((None, None, id_)):
if level == 0:
if t[1] != rdflib.term.URIRef('http://www.w3.org/2002/07/owl#someValuesFrom'):
continue
if type_check(t, (rdflib.term.URIRef, rdflib.term.URIRef, rdflib.term.BNode)):
#print(start, t[0])
collect[start].add(t[0])
return # we're done here, otherwise we hit instantiated subclasses
if level > 1:
if t[1] == rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#first') or \
t[1] == rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#rest'):
continue
recurse(t[0], start, level + 1)
for phenotype in phenotypes:
recurse(phenotype, phenotype)
return collect | python | 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(level)
for t in graph.g.triples((None, None, id_)):
if level == 0:
if t[1] != rdflib.term.URIRef('http://www.w3.org/2002/07/owl#someValuesFrom'):
continue
if type_check(t, (rdflib.term.URIRef, rdflib.term.URIRef, rdflib.term.BNode)):
#print(start, t[0])
collect[start].add(t[0])
return # we're done here, otherwise we hit instantiated subclasses
if level > 1:
if t[1] == rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#first') or \
t[1] == rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#rest'):
continue
recurse(t[0], start, level + 1)
for phenotype in phenotypes:
recurse(phenotype, phenotype)
return collect | [
"def",
"add_types",
"(",
"graph",
",",
"phenotypes",
")",
":",
"# TODO missing expression phenotypes! also basket type somehow :(",
"collect",
"=",
"defaultdict",
"(",
"set",
")",
"def",
"recurse",
"(",
"id_",
",",
"start",
",",
"level",
"=",
"0",
")",
":",
"#pr... | Add disjoint union classes so that it is possible to see the invariants
associated with individual phenotypes | [
"Add",
"disjoint",
"union",
"classes",
"so",
"that",
"it",
"is",
"possible",
"to",
"see",
"the",
"invariants",
"associated",
"with",
"individual",
"phenotypes"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/neurondm/neurondm/build.py#L144-L170 | train | 39,111 |
tgbugs/pyontutils | pyontutils/config.py | DevConfig.config | 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
config = {k:self._override[k] if
k in self._override else
v for k, v in yaml.safe_load(f).items()}
return config | python | 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
config = {k:self._override[k] if
k in self._override else
v for k, v in yaml.safe_load(f).items()}
return config | [
"def",
"config",
"(",
"self",
")",
":",
"# 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",
"... | Allows changing the config on the fly | [
"Allows",
"changing",
"the",
"config",
"on",
"the",
"fly"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/config.py#L234-L244 | train | 39,112 |
SUSE-Enceladus/ipa | ipa/ipa_gce.py | GCECloud._get_service_account_info | 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 GCECloudException(
'Service account JSON file is invalid for GCE. '
'client_email key is expected. See getting started '
'docs for information on GCE configuration.'
)
self.service_account_project = info.get('project_id')
if not self.service_account_project:
raise GCECloudException(
'Service account JSON file is invalid for GCE. '
'project_id key is expected. See getting started '
'docs for information on GCE configuration.'
) | python | 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 GCECloudException(
'Service account JSON file is invalid for GCE. '
'client_email key is expected. See getting started '
'docs for information on GCE configuration.'
)
self.service_account_project = info.get('project_id')
if not self.service_account_project:
raise GCECloudException(
'Service account JSON file is invalid for GCE. '
'project_id key is expected. See getting started '
'docs for information on GCE configuration.'
) | [
"def",
"_get_service_account_info",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"service_account_file",
",",
"'r'",
")",
"as",
"f",
":",
"info",
"=",
"json",
".",
"load",
"(",
"f",
")",
"self",
".",
"service_account_email",
"=",
"info",
".",... | Retrieve json dict from service account file. | [
"Retrieve",
"json",
"dict",
"from",
"service",
"account",
"file",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_gce.py#L122-L141 | train | 39,113 |
SUSE-Enceladus/ipa | ipa/ipa_gce.py | GCECloud._get_driver | 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
) | python | 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
) | [
"def",
"_get_driver",
"(",
"self",
")",
":",
"ComputeEngine",
"=",
"get_driver",
"(",
"Provider",
".",
"GCE",
")",
"return",
"ComputeEngine",
"(",
"self",
".",
"service_account_email",
",",
"self",
".",
"service_account_file",
",",
"project",
"=",
"self",
".",... | Get authenticated GCE driver. | [
"Get",
"authenticated",
"GCE",
"driver",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_gce.py#L143-L150 | train | 39,114 |
SUSE-Enceladus/ipa | ipa/ipa_gce.py | GCECloud._get_ssh_public_key | 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()
) | python | 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()
) | [
"def",
"_get_ssh_public_key",
"(",
"self",
")",
":",
"key",
"=",
"ipa_utils",
".",
"generate_public_ssh_key",
"(",
"self",
".",
"ssh_private_key_file",
")",
"return",
"'{user}:{key} {user}'",
".",
"format",
"(",
"user",
"=",
"self",
".",
"ssh_user",
",",
"key",
... | Generate SSH public key from private key. | [
"Generate",
"SSH",
"public",
"key",
"from",
"private",
"key",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_gce.py#L168-L174 | train | 39,115 |
SUSE-Enceladus/ipa | ipa/ipa_gce.py | GCECloud._validate_region | 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_driver.ex_get_zone(self.region)
except Exception:
zone = None
if not zone:
raise GCECloudException(
'{region} is not a valid GCE zone. '
'Example: us-west1-a'.format(
region=self.region
)
) | python | 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_driver.ex_get_zone(self.region)
except Exception:
zone = None
if not zone:
raise GCECloudException(
'{region} is not a valid GCE zone. '
'Example: us-west1-a'.format(
region=self.region
)
) | [
"def",
"_validate_region",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"region",
":",
"raise",
"GCECloudException",
"(",
"'Zone is required for GCE cloud framework: '",
"'Example: us-west1-a'",
")",
"try",
":",
"zone",
"=",
"self",
".",
"compute_driver",
".",
... | Validate region was passed in and is a valid GCE zone. | [
"Validate",
"region",
"was",
"passed",
"in",
"and",
"is",
"a",
"valid",
"GCE",
"zone",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_gce.py#L244-L263 | train | 39,116 |
SUSE-Enceladus/ipa | ipa/ipa_gce.py | GCECloud._set_instance_ip | 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:
raise GCECloudException(
'IP address for instance: %s cannot be found.'
% self.running_instance_id
) | python | 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:
raise GCECloudException(
'IP address for instance: %s cannot be found.'
% self.running_instance_id
) | [
"def",
"_set_instance_ip",
"(",
"self",
")",
":",
"instance",
"=",
"self",
".",
"_get_instance",
"(",
")",
"if",
"instance",
".",
"public_ips",
":",
"self",
".",
"instance_ip",
"=",
"instance",
".",
"public_ips",
"[",
"0",
"]",
"elif",
"instance",
".",
"... | Retrieve and set the instance ip address. | [
"Retrieve",
"and",
"set",
"the",
"instance",
"ip",
"address",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_gce.py#L274-L286 | train | 39,117 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_ingestion.py | InterLexIngestion.grab_rdflib_graph_version | 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('versioning isn\'t correct')
else:
version = str(version[0])
return version | python | 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('versioning isn\'t correct')
else:
version = str(version[0])
return version | [
"def",
"grab_rdflib_graph_version",
"(",
"g",
":",
"Graph",
")",
"->",
"str",
":",
"version",
"=",
"g",
".",
"subject_objects",
"(",
"predicate",
"=",
"URIRef",
"(",
"OWL",
".",
"versionIRI",
")",
")",
"version",
"=",
"[",
"o",
"for",
"s",
",",
"o",
... | Crap-shot for ontology iri if its properly in the header and correctly formated | [
"Crap",
"-",
"shot",
"for",
"ontology",
"iri",
"if",
"its",
"properly",
"in",
"the",
"header",
"and",
"correctly",
"formated"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_ingestion.py#L33-L41 | train | 39,118 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_ingestion.py | InterLexIngestion.fix_ilx | 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 with format ilx_# or ILX:# for given ID ' + ilx_id)
return ilx_id.replace('ILX:', 'ilx_').replace('TMP:', 'tmp_') | python | 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 with format ilx_# or ILX:# for given ID ' + ilx_id)
return ilx_id.replace('ILX:', 'ilx_').replace('TMP:', 'tmp_') | [
"def",
"fix_ilx",
"(",
"self",
",",
"ilx_id",
":",
"str",
")",
"->",
"str",
":",
"ilx_id",
"=",
"ilx_id",
".",
"replace",
"(",
"'http://uri.interlex.org/base/'",
",",
"''",
")",
"if",
"ilx_id",
"[",
":",
"4",
"]",
"not",
"in",
"[",
"'TMP:'",
",",
"'t... | Database only excepts lower case and underscore version of ID | [
"Database",
"only",
"excepts",
"lower",
"case",
"and",
"underscore",
"version",
"of",
"ID"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_ingestion.py#L43-L49 | train | 39,119 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_ingestion.py | InterLexIngestion.pull_int_tail | 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
return int_tail | python | 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
return int_tail | [
"def",
"pull_int_tail",
"(",
"self",
",",
"string",
":",
"str",
")",
"->",
"str",
":",
"int_tail",
"=",
"''",
"for",
"element",
"in",
"string",
"[",
":",
":",
"-",
"1",
"]",
":",
"try",
":",
"int",
"(",
"element",
")",
"int_tail",
"=",
"element",
... | Useful for IDs that have giberish in the front of the real ID | [
"Useful",
"for",
"IDs",
"that",
"have",
"giberish",
"in",
"the",
"front",
"of",
"the",
"real",
"ID"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_ingestion.py#L51-L60 | train | 39,120 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_ingestion.py | InterLexIngestion.curie_search | 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:
None or dict
'''
ilx_row = self.curie2row.get(curie)
if not ilx_row:
return None
else:
return ilx_row | python | 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:
None or dict
'''
ilx_row = self.curie2row.get(curie)
if not ilx_row:
return None
else:
return ilx_row | [
"def",
"curie_search",
"(",
"self",
",",
"curie",
":",
"str",
")",
"->",
"dict",
":",
"ilx_row",
"=",
"self",
".",
"curie2row",
".",
"get",
"(",
"curie",
")",
"if",
"not",
"ilx_row",
":",
"return",
"None",
"else",
":",
"return",
"ilx_row"
] | 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 | [
"Returns",
"the",
"row",
"in",
"InterLex",
"associated",
"with",
"the",
"curie"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_ingestion.py#L70-L84 | train | 39,121 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_ingestion.py | InterLexIngestion.fragment_search | 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:
None or List[dict]
'''
fragement = self.extract_fragment(fragement)
ilx_rows = self.fragment2rows.get(fragement)
if not ilx_rows:
return None
else:
return ilx_rows | python | 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:
None or List[dict]
'''
fragement = self.extract_fragment(fragement)
ilx_rows = self.fragment2rows.get(fragement)
if not ilx_rows:
return None
else:
return ilx_rows | [
"def",
"fragment_search",
"(",
"self",
",",
"fragement",
":",
"str",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"fragement",
"=",
"self",
".",
"extract_fragment",
"(",
"fragement",
")",
"ilx_rows",
"=",
"self",
".",
"fragment2rows",
".",
"get",
"(",
"frag... | 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] | [
"Returns",
"the",
"rows",
"in",
"InterLex",
"associated",
"with",
"the",
"fragment"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_ingestion.py#L86-L101 | train | 39,122 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_ingestion.py | InterLexIngestion.label_search | 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]
'''
ilx_rows = self.label2rows(self.local_degrade(label))
if not ilx_rows:
return None
else:
return ilx_rows | python | 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]
'''
ilx_rows = self.label2rows(self.local_degrade(label))
if not ilx_rows:
return None
else:
return ilx_rows | [
"def",
"label_search",
"(",
"self",
",",
"label",
":",
"str",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"ilx_rows",
"=",
"self",
".",
"label2rows",
"(",
"self",
".",
"local_degrade",
"(",
"label",
")",
")",
"if",
"not",
"ilx_rows",
":",
"return",
"No... | 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"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_ingestion.py#L103-L117 | train | 39,123 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_ingestion.py | InterLexIngestion.readyup_entity | 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 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
clearance higher than 0 you can make your own custom. Good for mass imports by one
person to avoid label collides.
definition: entities definition
comment: a foot note regarding either the interpretation of the data or the data itself
superclass: entity is a sub-part of this entity
Example: Organ is a superclass to Brain
synonyms: entity synonyms
existing_ids: existing curie/iris that link data | couldnt format this easier
Returns:
dict
'''
entity = dict(
label = label,
type = type,
)
if uid:
entity['uid'] = uid
if definition:
entity['definition'] = definition
if comment:
entity['comment'] = comment
if superclass:
entity['superclass'] = {'ilx_id':self.fix_ilx(superclass)}
if synonyms:
entity['synonyms'] = [{'literal': syn} for syn in synonyms]
if existing_ids:
if existing_ids[0].get('curie') and existing_ids[0].get('iri'):
pass
else:
exit('Need curie and iri for existing_ids in List[dict] form')
entity['existing_ids'] = existing_ids
return entity | python | 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 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
clearance higher than 0 you can make your own custom. Good for mass imports by one
person to avoid label collides.
definition: entities definition
comment: a foot note regarding either the interpretation of the data or the data itself
superclass: entity is a sub-part of this entity
Example: Organ is a superclass to Brain
synonyms: entity synonyms
existing_ids: existing curie/iris that link data | couldnt format this easier
Returns:
dict
'''
entity = dict(
label = label,
type = type,
)
if uid:
entity['uid'] = uid
if definition:
entity['definition'] = definition
if comment:
entity['comment'] = comment
if superclass:
entity['superclass'] = {'ilx_id':self.fix_ilx(superclass)}
if synonyms:
entity['synonyms'] = [{'literal': syn} for syn in synonyms]
if existing_ids:
if existing_ids[0].get('curie') and existing_ids[0].get('iri'):
pass
else:
exit('Need curie and iri for existing_ids in List[dict] form')
entity['existing_ids'] = existing_ids
return entity | [
"def",
"readyup_entity",
"(",
"self",
",",
"label",
":",
"str",
",",
"type",
":",
"str",
",",
"uid",
":",
"Union",
"[",
"int",
",",
"str",
"]",
"=",
"None",
",",
"comment",
":",
"str",
"=",
"None",
",",
"definition",
":",
"str",
"=",
"None",
",",... | 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
clearance higher than 0 you can make your own custom. Good for mass imports by one
person to avoid label collides.
definition: entities definition
comment: a foot note regarding either the interpretation of the data or the data itself
superclass: entity is a sub-part of this entity
Example: Organ is a superclass to Brain
synonyms: entity synonyms
existing_ids: existing curie/iris that link data | couldnt format this easier
Returns:
dict | [
"Setups",
"the",
"entity",
"to",
"be",
"InterLex",
"ready"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_ingestion.py#L119-L175 | train | 39,124 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_ingestion.py | InterLexIngestion.exhaustive_label_check | 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:
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 colname of the DataFrame for the label
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only '''
inside, outside = [], []
header = ['Index'] + list(ontology.columns)
for row in ontology.itertuples():
row = {header[i]:val for i, val in enumerate(row)}
label_obj = row[label_predicate]
if isinstance(label_obj, list):
if len(label_obj) != 1:
exit('Need to have only 1 label in the cell from the onotology.')
else:
label_obj = label_obj[0]
entity_label = self.local_degrade(label_obj)
ilx_rows = self.label2rows.get(entity_label)
if ilx_rows:
inside.append({
'external_ontology_row': row,
'ilx_rows': ilx_rows,
})
else:
outside.append(row)
if diff:
diff = self.__exhaustive_diff(inside)
return inside, outside, diff
return inside, outside | python | 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:
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 colname of the DataFrame for the label
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only '''
inside, outside = [], []
header = ['Index'] + list(ontology.columns)
for row in ontology.itertuples():
row = {header[i]:val for i, val in enumerate(row)}
label_obj = row[label_predicate]
if isinstance(label_obj, list):
if len(label_obj) != 1:
exit('Need to have only 1 label in the cell from the onotology.')
else:
label_obj = label_obj[0]
entity_label = self.local_degrade(label_obj)
ilx_rows = self.label2rows.get(entity_label)
if ilx_rows:
inside.append({
'external_ontology_row': row,
'ilx_rows': ilx_rows,
})
else:
outside.append(row)
if diff:
diff = self.__exhaustive_diff(inside)
return inside, outside, diff
return inside, outside | [
"def",
"exhaustive_label_check",
"(",
"self",
",",
"ontology",
":",
"pd",
".",
"DataFrame",
",",
"label_predicate",
"=",
"'rdfs:label'",
",",
"diff",
":",
"bool",
"=",
"True",
",",
")",
"->",
"Tuple",
"[",
"list",
"]",
":",
"inside",
",",
"outside",
"=",... | 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 colname of the DataFrame for the label
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only | [
"All",
"entities",
"with",
"conflicting",
"labels",
"gets",
"a",
"full",
"diff"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_ingestion.py#L246-L286 | train | 39,125 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_ingestion.py | InterLexIngestion.exhaustive_iri_check | 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:
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 qname form and is the colname of the DataFrame for iri
Default is "iri" for graph2pandas module
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only '''
inside, outside = [], []
header = ['Index'] + list(ontology.columns)
for row in ontology.itertuples():
row = {header[i]:val for i, val in enumerate(row)}
entity_iri = row[iri_predicate]
if isinstance(entity_iri, list):
if len(entity_iri) != 0:
exit('Need to have only 1 iri in the cell from the onotology.')
else:
entity_iri = entity_iri[0]
ilx_row = self.iri2row.get(entity_iri)
if ilx_row:
inside.append({
'external_ontology_row': row,
'ilx_rows': [ilx_row],
})
else:
outside.append(row)
if diff:
diff = self.__exhaustive_diff(inside)
return inside, outside, diff
return inside, outside | python | 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:
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 qname form and is the colname of the DataFrame for iri
Default is "iri" for graph2pandas module
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only '''
inside, outside = [], []
header = ['Index'] + list(ontology.columns)
for row in ontology.itertuples():
row = {header[i]:val for i, val in enumerate(row)}
entity_iri = row[iri_predicate]
if isinstance(entity_iri, list):
if len(entity_iri) != 0:
exit('Need to have only 1 iri in the cell from the onotology.')
else:
entity_iri = entity_iri[0]
ilx_row = self.iri2row.get(entity_iri)
if ilx_row:
inside.append({
'external_ontology_row': row,
'ilx_rows': [ilx_row],
})
else:
outside.append(row)
if diff:
diff = self.__exhaustive_diff(inside)
return inside, outside, diff
return inside, outside | [
"def",
"exhaustive_iri_check",
"(",
"self",
",",
"ontology",
":",
"pd",
".",
"DataFrame",
",",
"iri_predicate",
":",
"str",
",",
"diff",
":",
"bool",
"=",
"True",
",",
")",
"->",
"Tuple",
"[",
"list",
"]",
":",
"inside",
",",
"outside",
"=",
"[",
"]"... | 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 qname form and is the colname of the DataFrame for iri
Default is "iri" for graph2pandas module
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only | [
"All",
"entities",
"with",
"conflicting",
"iris",
"gets",
"a",
"full",
"diff",
"to",
"see",
"if",
"they",
"belong"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_ingestion.py#L288-L329 | train | 39,126 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_ingestion.py | InterLexIngestion.exhaustive_curie_check | 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 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 qname form and is the colname of the DataFrame
curie_prefix: Not all cells in the DataFrame will have complete curies so we extract
the fragement from the cell and use the prefix to complete it.
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only '''
inside, outside = [], []
curie_prefix = curie_prefix.replace(':', '') # just in case I forget a colon isnt in a prefix
header = ['Index'] + list(ontology.columns)
for row in ontology.itertuples():
row = {header[i]:val for i, val in enumerate(row)}
entity_curie = row[curie_predicate]
if isinstance(entity_curie, list):
if len(entity_curie) != 0:
exit('Need to have only 1 iri in the cell from the onotology.')
else:
entity_curie = entity_curie[0]
entity_curie = curie_prefix + ':' + self.extract_fragment(entity_curie)
ilx_row = self.curie2row.get(entity_curie)
if ilx_row:
inside.append({
'external_ontology_row': row,
'ilx_rows': [ilx_row],
})
else:
outside.append(row)
if diff:
diff = self.__exhaustive_diff(inside)
return inside, outside, diff
return inside, outside | python | 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 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 qname form and is the colname of the DataFrame
curie_prefix: Not all cells in the DataFrame will have complete curies so we extract
the fragement from the cell and use the prefix to complete it.
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only '''
inside, outside = [], []
curie_prefix = curie_prefix.replace(':', '') # just in case I forget a colon isnt in a prefix
header = ['Index'] + list(ontology.columns)
for row in ontology.itertuples():
row = {header[i]:val for i, val in enumerate(row)}
entity_curie = row[curie_predicate]
if isinstance(entity_curie, list):
if len(entity_curie) != 0:
exit('Need to have only 1 iri in the cell from the onotology.')
else:
entity_curie = entity_curie[0]
entity_curie = curie_prefix + ':' + self.extract_fragment(entity_curie)
ilx_row = self.curie2row.get(entity_curie)
if ilx_row:
inside.append({
'external_ontology_row': row,
'ilx_rows': [ilx_row],
})
else:
outside.append(row)
if diff:
diff = self.__exhaustive_diff(inside)
return inside, outside, diff
return inside, outside | [
"def",
"exhaustive_curie_check",
"(",
"self",
",",
"ontology",
":",
"pd",
".",
"DataFrame",
",",
"curie_predicate",
":",
"str",
",",
"curie_prefix",
":",
"str",
",",
"diff",
":",
"bool",
"=",
"True",
",",
")",
"->",
"Tuple",
"[",
"list",
"]",
":",
"ins... | 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 qname form and is the colname of the DataFrame
curie_prefix: Not all cells in the DataFrame will have complete curies so we extract
the fragement from the cell and use the prefix to complete it.
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only | [
"All",
"entities",
"with",
"conflicting",
"curies",
"gets",
"a",
"full",
"diff",
"to",
"see",
"if",
"they",
"belong"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_ingestion.py#L331-L373 | train | 39,127 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_ingestion.py | InterLexIngestion.exhaustive_fragment_check | def exhaustive_fragment_check( self,
ontology:pd.DataFrame,
iri_curie_fragment_predicate:str = 'iri',
cross_reference_iris:bool = False,
cross_reference_fragments:bool = False,
diff:bool = True, ) -> Tuple[list]:
''' 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_predicate: usually in qname form and is the colname of the DataFrame for iri
Default is "iri" for graph2pandas module
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only '''
inside, outside = [], []
header = ['Index'] + list(ontology.columns)
for row in ontology.itertuples():
row = {header[i]:val for i, val in enumerate(row)}
entity_suffix = row[iri_curie_fragment_predicate]
if isinstance(entity_suffix, list):
if len(entity_suffix) != 0:
exit('Need to have only 1 iri in the cell from the onotology.')
else:
entity_suffix = entity_suffix[0]
entity_fragment = self.extract_fragment(entity_suffix)
ilx_rows = self.fragment2rows.get(entity_fragment)
if cross_reference_fragments and ilx_rows:
ilx_rows = [row for row in ilx_rows if entity_fragment.lower() in row['iri'].lower()]
if cross_reference_iris and ilx_rows:
# true suffix of iris
ilx_rows = [row for row in ilx_rows if entity_suffix.rsplit('/', 1)[-1].lower() in row['iri'].lower()]
if ilx_rows:
inside.append({
'external_ontology_row': row,
'ilx_rows': ilx_rows,
})
else:
outside.append(row)
if diff:
diff = self.__exhaustive_diff(inside)
return inside, outside, diff
return inside, outside | python | def exhaustive_fragment_check( self,
ontology:pd.DataFrame,
iri_curie_fragment_predicate:str = 'iri',
cross_reference_iris:bool = False,
cross_reference_fragments:bool = False,
diff:bool = True, ) -> Tuple[list]:
''' 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_predicate: usually in qname form and is the colname of the DataFrame for iri
Default is "iri" for graph2pandas module
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only '''
inside, outside = [], []
header = ['Index'] + list(ontology.columns)
for row in ontology.itertuples():
row = {header[i]:val for i, val in enumerate(row)}
entity_suffix = row[iri_curie_fragment_predicate]
if isinstance(entity_suffix, list):
if len(entity_suffix) != 0:
exit('Need to have only 1 iri in the cell from the onotology.')
else:
entity_suffix = entity_suffix[0]
entity_fragment = self.extract_fragment(entity_suffix)
ilx_rows = self.fragment2rows.get(entity_fragment)
if cross_reference_fragments and ilx_rows:
ilx_rows = [row for row in ilx_rows if entity_fragment.lower() in row['iri'].lower()]
if cross_reference_iris and ilx_rows:
# true suffix of iris
ilx_rows = [row for row in ilx_rows if entity_suffix.rsplit('/', 1)[-1].lower() in row['iri'].lower()]
if ilx_rows:
inside.append({
'external_ontology_row': row,
'ilx_rows': ilx_rows,
})
else:
outside.append(row)
if diff:
diff = self.__exhaustive_diff(inside)
return inside, outside, diff
return inside, outside | [
"def",
"exhaustive_fragment_check",
"(",
"self",
",",
"ontology",
":",
"pd",
".",
"DataFrame",
",",
"iri_curie_fragment_predicate",
":",
"str",
"=",
"'iri'",
",",
"cross_reference_iris",
":",
"bool",
"=",
"False",
",",
"cross_reference_fragments",
":",
"bool",
"="... | 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_predicate: usually in qname form and is the colname of the DataFrame for iri
Default is "iri" for graph2pandas module
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only | [
"All",
"entities",
"with",
"conflicting",
"fragments",
"gets",
"a",
"full",
"diff",
"to",
"see",
"if",
"they",
"belong"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_ingestion.py#L375-L421 | train | 39,128 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_ingestion.py | InterLexIngestion.exhaustive_ontology_ilx_diff_row_only | 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)}
check_list = [
{
'external_ontology_row': ontology_row,
'ilx_rows': [row],
},
]
# First layer for each external row. Second is for each potential ilx row. It's simple here 1-1.
result = self.__exhaustive_diff(check_list)[0][0]
if result['same']:
results.append(result)
return results | python | 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)}
check_list = [
{
'external_ontology_row': ontology_row,
'ilx_rows': [row],
},
]
# First layer for each external row. Second is for each potential ilx row. It's simple here 1-1.
result = self.__exhaustive_diff(check_list)[0][0]
if result['same']:
results.append(result)
return results | [
"def",
"exhaustive_ontology_ilx_diff_row_only",
"(",
"self",
",",
"ontology_row",
":",
"dict",
")",
"->",
"dict",
":",
"results",
"=",
"[",
"]",
"header",
"=",
"[",
"'Index'",
"]",
"+",
"list",
"(",
"self",
".",
"existing_ids",
".",
"columns",
")",
"for",
... | WARNING RUNTIME IS AWEFUL | [
"WARNING",
"RUNTIME",
"IS",
"AWEFUL"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_ingestion.py#L423-L439 | train | 39,129 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_ingestion.py | InterLexIngestion.combo_exhaustive_label_definition_check | def combo_exhaustive_label_definition_check( self,
ontology: pd.DataFrame,
label_predicate:str,
definition_predicates:str,
diff = True) -> List[List[dict]]:
''' 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 and is the colname of the DataFrame for the label
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only '''
inside, outside = [], []
header = ['Index'] + list(ontology.columns)
for row in ontology.itertuples():
row = {header[i]:val for i, val in enumerate(row)}
label_obj = row[label_predicate]
if isinstance(label_obj, list):
if len(label_obj) != 1:
exit('Need to have only 1 label in the cell from the onotology.')
else:
label_obj = label_obj[0]
entity_label = self.local_degrade(label_obj)
label_search_results = self.label2rows.get(entity_label)
label_ilx_rows = label_search_results if label_search_results else []
definition_ilx_rows = []
for definition_predicate in definition_predicates:
definition_objs = row[definition_predicate]
if not definition_objs:
continue
definition_objs = [definition_objs] if not isinstance(definition_objs, list) else definition_objs
for definition_obj in definition_objs:
definition_obj = self.local_degrade(definition_obj)
definition_search_results = self.definition2rows.get(definition_obj)
if definition_search_results:
definition_ilx_rows.extend(definition_search_results)
ilx_rows = [dict(t) for t in {tuple(d.items()) for d in (label_ilx_rows + definition_ilx_rows)}]
if ilx_rows:
inside.append({
'external_ontology_row': row,
'ilx_rows': ilx_rows,
})
else:
outside.append(row)
if diff:
diff = self.__exhaustive_diff(inside)
return inside, outside, diff
return inside, outside | python | def combo_exhaustive_label_definition_check( self,
ontology: pd.DataFrame,
label_predicate:str,
definition_predicates:str,
diff = True) -> List[List[dict]]:
''' 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 and is the colname of the DataFrame for the label
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only '''
inside, outside = [], []
header = ['Index'] + list(ontology.columns)
for row in ontology.itertuples():
row = {header[i]:val for i, val in enumerate(row)}
label_obj = row[label_predicate]
if isinstance(label_obj, list):
if len(label_obj) != 1:
exit('Need to have only 1 label in the cell from the onotology.')
else:
label_obj = label_obj[0]
entity_label = self.local_degrade(label_obj)
label_search_results = self.label2rows.get(entity_label)
label_ilx_rows = label_search_results if label_search_results else []
definition_ilx_rows = []
for definition_predicate in definition_predicates:
definition_objs = row[definition_predicate]
if not definition_objs:
continue
definition_objs = [definition_objs] if not isinstance(definition_objs, list) else definition_objs
for definition_obj in definition_objs:
definition_obj = self.local_degrade(definition_obj)
definition_search_results = self.definition2rows.get(definition_obj)
if definition_search_results:
definition_ilx_rows.extend(definition_search_results)
ilx_rows = [dict(t) for t in {tuple(d.items()) for d in (label_ilx_rows + definition_ilx_rows)}]
if ilx_rows:
inside.append({
'external_ontology_row': row,
'ilx_rows': ilx_rows,
})
else:
outside.append(row)
if diff:
diff = self.__exhaustive_diff(inside)
return inside, outside, diff
return inside, outside | [
"def",
"combo_exhaustive_label_definition_check",
"(",
"self",
",",
"ontology",
":",
"pd",
".",
"DataFrame",
",",
"label_predicate",
":",
"str",
",",
"definition_predicates",
":",
"str",
",",
"diff",
"=",
"True",
")",
"->",
"List",
"[",
"List",
"[",
"dict",
... | 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 and is the colname of the DataFrame for the label
diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2
Returns:
inside: entities that are inside of InterLex
outside: entities NOT in InterLex
diff (optional): List[List[dict]]... so complicated but usefull diff between matches only | [
"Combo",
"of",
"label",
"&",
"definition",
"exhaustive",
"check",
"out",
"of",
"convenience"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_ingestion.py#L441-L498 | train | 39,130 |
SUSE-Enceladus/ipa | ipa/ipa_utils.py | clear_cache | 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(Exception):
client.close()
CLIENT_CACHE.clear() | python | 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(Exception):
client.close()
CLIENT_CACHE.clear() | [
"def",
"clear_cache",
"(",
"ip",
"=",
"None",
")",
":",
"if",
"ip",
":",
"with",
"ignored",
"(",
"Exception",
")",
":",
"client",
"=",
"CLIENT_CACHE",
"[",
"ip",
"]",
"del",
"CLIENT_CACHE",
"[",
"ip",
"]",
"client",
".",
"close",
"(",
")",
"else",
... | Clear the client cache or remove key matching the given ip. | [
"Clear",
"the",
"client",
"cache",
"or",
"remove",
"key",
"matching",
"the",
"given",
"ip",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_utils.py#L47-L58 | train | 39,131 |
SUSE-Enceladus/ipa | ipa/ipa_utils.py | establish_ssh_connection | def establish_ssh_connection(ip,
ssh_private_key_file,
ssh_user,
port,
attempts=5,
timeout=None):
"""
Establish ssh connection and return paramiko client.
Raises:
IpaSSHException: If connection cannot be established
in given number of attempts.
"""
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
while attempts:
try:
client.connect(
ip,
port=port,
username=ssh_user,
key_filename=ssh_private_key_file,
timeout=timeout
)
except: # noqa: E722
attempts -= 1
time.sleep(10)
else:
return client
raise IpaSSHException(
'Failed to establish SSH connection to instance.'
) | python | def establish_ssh_connection(ip,
ssh_private_key_file,
ssh_user,
port,
attempts=5,
timeout=None):
"""
Establish ssh connection and return paramiko client.
Raises:
IpaSSHException: If connection cannot be established
in given number of attempts.
"""
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
while attempts:
try:
client.connect(
ip,
port=port,
username=ssh_user,
key_filename=ssh_private_key_file,
timeout=timeout
)
except: # noqa: E722
attempts -= 1
time.sleep(10)
else:
return client
raise IpaSSHException(
'Failed to establish SSH connection to instance.'
) | [
"def",
"establish_ssh_connection",
"(",
"ip",
",",
"ssh_private_key_file",
",",
"ssh_user",
",",
"port",
",",
"attempts",
"=",
"5",
",",
"timeout",
"=",
"None",
")",
":",
"client",
"=",
"paramiko",
".",
"SSHClient",
"(",
")",
"client",
".",
"set_missing_host... | Establish ssh connection and return paramiko client.
Raises:
IpaSSHException: If connection cannot be established
in given number of attempts. | [
"Establish",
"ssh",
"connection",
"and",
"return",
"paramiko",
"client",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_utils.py#L61-L94 | train | 39,132 |
SUSE-Enceladus/ipa | ipa/ipa_utils.py | execute_ssh_command | 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()
out = stdout.read()
if err:
raise IpaSSHException(out.decode() + err.decode())
except: # noqa: E722
raise
return out.decode() | python | 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()
out = stdout.read()
if err:
raise IpaSSHException(out.decode() + err.decode())
except: # noqa: E722
raise
return out.decode() | [
"def",
"execute_ssh_command",
"(",
"client",
",",
"cmd",
")",
":",
"try",
":",
"stdin",
",",
"stdout",
",",
"stderr",
"=",
"client",
".",
"exec_command",
"(",
"cmd",
")",
"err",
"=",
"stderr",
".",
"read",
"(",
")",
"out",
"=",
"stdout",
".",
"read",... | Execute given command using paramiko.
Returns:
String output of cmd execution.
Raises:
IpaSSHException: If stderr returns a non-empty string. | [
"Execute",
"given",
"command",
"using",
"paramiko",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_utils.py#L97-L114 | train | 39,133 |
SUSE-Enceladus/ipa | ipa/ipa_utils.py | extract_archive | 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_path}'.format(extract_path=extract_path)
out = execute_ssh_command(client, command)
return out | python | 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_path}'.format(extract_path=extract_path)
out = execute_ssh_command(client, command)
return out | [
"def",
"extract_archive",
"(",
"client",
",",
"archive_path",
",",
"extract_path",
"=",
"None",
")",
":",
"command",
"=",
"'tar -xf {path}'",
".",
"format",
"(",
"path",
"=",
"archive_path",
")",
"if",
"extract_path",
":",
"command",
"+=",
"' -C {extract_path}'"... | Extract the archive in current path using the provided client.
If extract_path is provided extract the archive there. | [
"Extract",
"the",
"archive",
"in",
"current",
"path",
"using",
"the",
"provided",
"client",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_utils.py#L150-L162 | train | 39,134 |
SUSE-Enceladus/ipa | ipa/ipa_utils.py | generate_public_ssh_key | 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 found.' % ssh_private_key_file
)
try:
private_key = serialization.load_pem_private_key(
key,
password=None,
backend=default_backend()
)
except ValueError:
raise IpaUtilsException(
'SSH private key file: %s is not a valid key file.'
% ssh_private_key_file
)
return private_key.public_key().public_bytes(
serialization.Encoding.OpenSSH,
serialization.PublicFormat.OpenSSH
) | python | 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 found.' % ssh_private_key_file
)
try:
private_key = serialization.load_pem_private_key(
key,
password=None,
backend=default_backend()
)
except ValueError:
raise IpaUtilsException(
'SSH private key file: %s is not a valid key file.'
% ssh_private_key_file
)
return private_key.public_key().public_bytes(
serialization.Encoding.OpenSSH,
serialization.PublicFormat.OpenSSH
) | [
"def",
"generate_public_ssh_key",
"(",
"ssh_private_key_file",
")",
":",
"try",
":",
"with",
"open",
"(",
"ssh_private_key_file",
",",
"\"rb\"",
")",
"as",
"key_file",
":",
"key",
"=",
"key_file",
".",
"read",
"(",
")",
"except",
"FileNotFoundError",
":",
"rai... | Generate SSH public key from private key file. | [
"Generate",
"SSH",
"public",
"key",
"from",
"private",
"key",
"file",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_utils.py#L196-L221 | train | 39,135 |
SUSE-Enceladus/ipa | ipa/ipa_utils.py | get_config_values | 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 found: %s' % config_path
)
config = configparser.ConfigParser()
try:
config.read(config_path)
except Exception:
raise IpaUtilsException(
'Config file format invalid.'
)
try:
values.update(config.items(default))
except Exception:
pass
try:
values.update(config.items(section))
except Exception:
pass
return values | python | 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 found: %s' % config_path
)
config = configparser.ConfigParser()
try:
config.read(config_path)
except Exception:
raise IpaUtilsException(
'Config file format invalid.'
)
try:
values.update(config.items(default))
except Exception:
pass
try:
values.update(config.items(section))
except Exception:
pass
return values | [
"def",
"get_config_values",
"(",
"config_path",
",",
"section",
",",
"default",
"=",
"'default'",
")",
":",
"values",
"=",
"{",
"}",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"config_path",
")",
":",
"raise",
"IpaUtilsException",
"(",
"'Config fi... | Parse ini config file and return a dict of values.
The provided section overrides any values in default section. | [
"Parse",
"ini",
"config",
"file",
"and",
"return",
"a",
"dict",
"of",
"values",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_utils.py#L224-L256 | train | 39,136 |
SUSE-Enceladus/ipa | ipa/ipa_utils.py | get_ssh_client | 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]
start = time.time()
end = start + timeout
client = None
while time.time() < end:
try:
client = establish_ssh_connection(
ip,
ssh_private_key_file,
ssh_user,
port,
timeout=wait_period
)
execute_ssh_command(client, 'ls')
except: # noqa: E722
if client:
client.close()
wait_period += wait_period
else:
CLIENT_CACHE[ip] = client
return client
raise IpaSSHException(
'Attempt to establish SSH connection failed.'
) | python | 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]
start = time.time()
end = start + timeout
client = None
while time.time() < end:
try:
client = establish_ssh_connection(
ip,
ssh_private_key_file,
ssh_user,
port,
timeout=wait_period
)
execute_ssh_command(client, 'ls')
except: # noqa: E722
if client:
client.close()
wait_period += wait_period
else:
CLIENT_CACHE[ip] = client
return client
raise IpaSSHException(
'Attempt to establish SSH connection failed.'
) | [
"def",
"get_ssh_client",
"(",
"ip",
",",
"ssh_private_key_file",
",",
"ssh_user",
"=",
"'root'",
",",
"port",
"=",
"22",
",",
"timeout",
"=",
"600",
",",
"wait_period",
"=",
"10",
")",
":",
"if",
"ip",
"in",
"CLIENT_CACHE",
":",
"return",
"CLIENT_CACHE",
... | Attempt to establish and test ssh connection. | [
"Attempt",
"to",
"establish",
"and",
"test",
"ssh",
"connection",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_utils.py#L271-L305 | train | 39,137 |
SUSE-Enceladus/ipa | ipa/ipa_utils.py | get_yaml_config | 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 file not found: %s' % config_path
)
with open(config_path, 'r') as f:
config = yaml.safe_load(f)
return config | python | 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 file not found: %s' % config_path
)
with open(config_path, 'r') as f:
config = yaml.safe_load(f)
return config | [
"def",
"get_yaml_config",
"(",
"config_path",
")",
":",
"config_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"config_path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"config_path",
")",
":",
"raise",
"IpaUtilsException",
"(",
"'Con... | Load yaml config file and return dictionary.
Todo:
* This will need refactoring similar to the test search. | [
"Load",
"yaml",
"config",
"file",
"and",
"return",
"dictionary",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_utils.py#L408-L423 | train | 39,138 |
SUSE-Enceladus/ipa | ipa/ipa_utils.py | parse_sync_points | 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'), 'test_soft_reboot']
[set('test1', 'test2'), 'test_soft_reboot', set('test3')]
"""
test_files = []
section = set()
for name in names:
if name in SYNC_POINTS:
if section:
test_files.append(section)
test_files.append(name)
section = set()
else:
section.add(find_test_file(name, tests))
if section:
test_files.append(section)
return test_files | python | 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'), 'test_soft_reboot']
[set('test1', 'test2'), 'test_soft_reboot', set('test3')]
"""
test_files = []
section = set()
for name in names:
if name in SYNC_POINTS:
if section:
test_files.append(section)
test_files.append(name)
section = set()
else:
section.add(find_test_file(name, tests))
if section:
test_files.append(section)
return test_files | [
"def",
"parse_sync_points",
"(",
"names",
",",
"tests",
")",
":",
"test_files",
"=",
"[",
"]",
"section",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"names",
":",
"if",
"name",
"in",
"SYNC_POINTS",
":",
"if",
"section",
":",
"test_files",
".",
"append"... | 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'), 'test_soft_reboot', set('test3')] | [
"Slice",
"list",
"of",
"test",
"names",
"on",
"sync",
"points",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_utils.py#L435-L464 | train | 39,139 |
SUSE-Enceladus/ipa | ipa/ipa_utils.py | put_file | 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 copying file to instance: {0}.'.format(error)
)
finally:
with ignored(Exception):
sftp_client.close() | python | 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 copying file to instance: {0}.'.format(error)
)
finally:
with ignored(Exception):
sftp_client.close() | [
"def",
"put_file",
"(",
"client",
",",
"source_file",
",",
"destination_file",
")",
":",
"try",
":",
"sftp_client",
"=",
"client",
".",
"open_sftp",
"(",
")",
"sftp_client",
".",
"put",
"(",
"source_file",
",",
"destination_file",
")",
"except",
"Exception",
... | Copy file to instance using Paramiko client connection. | [
"Copy",
"file",
"to",
"instance",
"using",
"Paramiko",
"client",
"connection",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_utils.py#L482-L495 | train | 39,140 |
SUSE-Enceladus/ipa | ipa/ipa_utils.py | redirect_output | def redirect_output(fileobj):
"""Redirect standard out to file."""
old = sys.stdout
sys.stdout = fileobj
try:
yield fileobj
finally:
sys.stdout = old | python | def redirect_output(fileobj):
"""Redirect standard out to file."""
old = sys.stdout
sys.stdout = fileobj
try:
yield fileobj
finally:
sys.stdout = old | [
"def",
"redirect_output",
"(",
"fileobj",
")",
":",
"old",
"=",
"sys",
".",
"stdout",
"sys",
".",
"stdout",
"=",
"fileobj",
"try",
":",
"yield",
"fileobj",
"finally",
":",
"sys",
".",
"stdout",
"=",
"old"
] | Redirect standard out to file. | [
"Redirect",
"standard",
"out",
"to",
"file",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_utils.py#L499-L506 | train | 39,141 |
SUSE-Enceladus/ipa | ipa/ipa_utils.py | ssh_config | 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)
ssh_file.close()
yield ssh_file.name
finally:
with ignored(OSError):
os.remove(ssh_file.name) | python | 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)
ssh_file.close()
yield ssh_file.name
finally:
with ignored(OSError):
os.remove(ssh_file.name) | [
"def",
"ssh_config",
"(",
"ssh_user",
",",
"ssh_private_key_file",
")",
":",
"try",
":",
"ssh_file",
"=",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
",",
"mode",
"=",
"'w+'",
")",
"ssh_file",
".",
"write",
"(",
"'Host *\\n'",
")",
"ssh_file",
".",
... | Create temporary ssh config file. | [
"Create",
"temporary",
"ssh",
"config",
"file",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_utils.py#L510-L521 | train | 39,142 |
SUSE-Enceladus/ipa | ipa/ipa_utils.py | update_history_log | 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 IpaUtilsException(
'A test log or clear flag must be provided.'
)
if clear:
with ignored(OSError):
os.remove(history_log)
else:
history_dir = os.path.dirname(history_log)
if not os.path.isdir(history_dir):
try:
os.makedirs(history_dir)
except OSError as error:
raise IpaUtilsException(
'Unable to create directory: %s' % error
)
with open(history_log, 'a+') as f:
# Using append mode creates file if it does not exist
if description:
description = '"%s"' % description
out = '{} {}'.format(
test_log,
description or ''
)
f.write(out.strip() + '\n') | python | 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 IpaUtilsException(
'A test log or clear flag must be provided.'
)
if clear:
with ignored(OSError):
os.remove(history_log)
else:
history_dir = os.path.dirname(history_log)
if not os.path.isdir(history_dir):
try:
os.makedirs(history_dir)
except OSError as error:
raise IpaUtilsException(
'Unable to create directory: %s' % error
)
with open(history_log, 'a+') as f:
# Using append mode creates file if it does not exist
if description:
description = '"%s"' % description
out = '{} {}'.format(
test_log,
description or ''
)
f.write(out.strip() + '\n') | [
"def",
"update_history_log",
"(",
"history_log",
",",
"clear",
"=",
"False",
",",
"description",
"=",
"None",
",",
"test_log",
"=",
"None",
")",
":",
"if",
"not",
"test_log",
"and",
"not",
"clear",
":",
"raise",
"IpaUtilsException",
"(",
"'A test log or clear ... | Update the history log file with item.
If clear flag is provided the log file is deleted. | [
"Update",
"the",
"history",
"log",
"file",
"with",
"item",
".",
"If",
"clear",
"flag",
"is",
"provided",
"the",
"log",
"file",
"is",
"deleted",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_utils.py#L524-L560 | train | 39,143 |
tgbugs/pyontutils | ilxutils/ontoutils/create_strict_records_from_ontology.py | CommonPredMap.create_pred2common | 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_preds:
pred = pred.lower().strip()
self.pred2common[pred] = common_name | python | 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_preds:
pred = pred.lower().strip()
self.pred2common[pred] = common_name | [
"def",
"create_pred2common",
"(",
"self",
")",
":",
"self",
".",
"pred2common",
"=",
"{",
"}",
"for",
"common_name",
",",
"ext_preds",
"in",
"self",
".",
"common2preds",
".",
"items",
"(",
")",
":",
"for",
"pred",
"in",
"ext_preds",
":",
"pred",
"=",
"... | Takes list linked to common name and maps common name to accepted predicate
and their respected suffixes to decrease sensitivity. | [
"Takes",
"list",
"linked",
"to",
"common",
"name",
"and",
"maps",
"common",
"name",
"to",
"accepted",
"predicate",
"and",
"their",
"respected",
"suffixes",
"to",
"decrease",
"sensitivity",
"."
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ontoutils/create_strict_records_from_ontology.py#L177-L185 | train | 39,144 |
tgbugs/pyontutils | ilxutils/ontoutils/create_strict_records_from_ontology.py | CommonPredMap.clean_pred | 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 pred[-1] != ':': # some matches are "prefix:" only
pred = pred.split(':')[-1]
else:
if not ignore_warning:
exit('Not a valid predicate: ' + original_pred + '. Needs to be an iri "/" or curie ":".')
return pred | python | 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 pred[-1] != ':': # some matches are "prefix:" only
pred = pred.split(':')[-1]
else:
if not ignore_warning:
exit('Not a valid predicate: ' + original_pred + '. Needs to be an iri "/" or curie ":".')
return pred | [
"def",
"clean_pred",
"(",
"self",
",",
"pred",
",",
"ignore_warning",
"=",
"False",
")",
":",
"original_pred",
"=",
"pred",
"pred",
"=",
"pred",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"if",
"'http'",
"in",
"pred",
":",
"pred",
"=",
"pred",
... | Takes the predicate and returns the suffix, lower case, stripped version | [
"Takes",
"the",
"predicate",
"and",
"returns",
"the",
"suffix",
"lower",
"case",
"stripped",
"version"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ontoutils/create_strict_records_from_ontology.py#L187-L200 | train | 39,145 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._create_network_interface | 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_config = {
'location': region,
'ip_configurations': [{
'name': ip_config_name,
'private_ip_allocation_method': 'Dynamic',
'subnet': {
'id': subnet.id
},
'public_ip_address': {
'id': public_ip.id
},
}]
}
if accelerated_networking:
nic_config['enable_accelerated_networking'] = True
try:
nic_setup = self.network.network_interfaces.create_or_update(
resource_group_name, nic_name, nic_config
)
except Exception as error:
raise AzureCloudException(
'Unable to create network interface: {0}.'.format(
error
)
)
return nic_setup.result() | python | 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_config = {
'location': region,
'ip_configurations': [{
'name': ip_config_name,
'private_ip_allocation_method': 'Dynamic',
'subnet': {
'id': subnet.id
},
'public_ip_address': {
'id': public_ip.id
},
}]
}
if accelerated_networking:
nic_config['enable_accelerated_networking'] = True
try:
nic_setup = self.network.network_interfaces.create_or_update(
resource_group_name, nic_name, nic_config
)
except Exception as error:
raise AzureCloudException(
'Unable to create network interface: {0}.'.format(
error
)
)
return nic_setup.result() | [
"def",
"_create_network_interface",
"(",
"self",
",",
"ip_config_name",
",",
"nic_name",
",",
"public_ip",
",",
"region",
",",
"resource_group_name",
",",
"subnet",
",",
"accelerated_networking",
"=",
"False",
")",
":",
"nic_config",
"=",
"{",
"'location'",
":",
... | Create a network interface in the resource group.
Attach NIC to the subnet and public IP provided. | [
"Create",
"a",
"network",
"interface",
"in",
"the",
"resource",
"group",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L140-L177 | train | 39,146 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._create_public_ip | 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_ip_setup = \
self.network.public_ip_addresses.create_or_update(
resource_group_name, public_ip_name, public_ip_config
)
except Exception as error:
raise AzureCloudException(
'Unable to create public IP: {0}.'.format(error)
)
return public_ip_setup.result() | python | 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_ip_setup = \
self.network.public_ip_addresses.create_or_update(
resource_group_name, public_ip_name, public_ip_config
)
except Exception as error:
raise AzureCloudException(
'Unable to create public IP: {0}.'.format(error)
)
return public_ip_setup.result() | [
"def",
"_create_public_ip",
"(",
"self",
",",
"public_ip_name",
",",
"resource_group_name",
",",
"region",
")",
":",
"public_ip_config",
"=",
"{",
"'location'",
":",
"region",
",",
"'public_ip_allocation_method'",
":",
"'Dynamic'",
"}",
"try",
":",
"public_ip_setup"... | Create dynamic public IP address in the resource group. | [
"Create",
"dynamic",
"public",
"IP",
"address",
"in",
"the",
"resource",
"group",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L179-L198 | train | 39,147 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._create_resource_group | 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_config
)
except Exception as error:
raise AzureCloudException(
'Unable to create resource group: {0}.'.format(error)
) | python | 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_config
)
except Exception as error:
raise AzureCloudException(
'Unable to create resource group: {0}.'.format(error)
) | [
"def",
"_create_resource_group",
"(",
"self",
",",
"region",
",",
"resource_group_name",
")",
":",
"resource_group_config",
"=",
"{",
"'location'",
":",
"region",
"}",
"try",
":",
"self",
".",
"resource",
".",
"resource_groups",
".",
"create_or_update",
"(",
"re... | Create resource group if it does not exist. | [
"Create",
"resource",
"group",
"if",
"it",
"does",
"not",
"exist",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L200-L213 | train | 39,148 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._create_storage_profile | 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': self.image_publisher,
'offer': self.image_offer,
'sku': self.image_sku,
'version': self.image_version
},
}
else:
for image in self.compute.images.list():
if image.name == self.image_id:
image_id = image.id
break
else:
raise AzureCloudException(
'Image with name {0} not found.'.format(self.image_id)
)
storage_profile = {
'image_reference': {
'id': image_id
}
}
return storage_profile | python | 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': self.image_publisher,
'offer': self.image_offer,
'sku': self.image_sku,
'version': self.image_version
},
}
else:
for image in self.compute.images.list():
if image.name == self.image_id:
image_id = image.id
break
else:
raise AzureCloudException(
'Image with name {0} not found.'.format(self.image_id)
)
storage_profile = {
'image_reference': {
'id': image_id
}
}
return storage_profile | [
"def",
"_create_storage_profile",
"(",
"self",
")",
":",
"if",
"self",
".",
"image_publisher",
":",
"storage_profile",
"=",
"{",
"'image_reference'",
":",
"{",
"'publisher'",
":",
"self",
".",
"image_publisher",
",",
"'offer'",
":",
"self",
".",
"image_offer",
... | Create the storage profile for the instance.
Image reference can be a custom image name or a published urn. | [
"Create",
"the",
"storage",
"profile",
"for",
"the",
"instance",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L215-L246 | train | 39,149 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._create_subnet | 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_group_name, vnet_name, subnet_id, subnet_config
)
except Exception as error:
raise AzureCloudException(
'Unable to create subnet: {0}.'.format(error)
)
return subnet_setup.result() | python | 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_group_name, vnet_name, subnet_id, subnet_config
)
except Exception as error:
raise AzureCloudException(
'Unable to create subnet: {0}.'.format(error)
)
return subnet_setup.result() | [
"def",
"_create_subnet",
"(",
"self",
",",
"resource_group_name",
",",
"subnet_id",
",",
"vnet_name",
")",
":",
"subnet_config",
"=",
"{",
"'address_prefix'",
":",
"'10.0.0.0/29'",
"}",
"try",
":",
"subnet_setup",
"=",
"self",
".",
"network",
".",
"subnets",
"... | Create a subnet in the provided vnet and resource group. | [
"Create",
"a",
"subnet",
"in",
"the",
"provided",
"vnet",
"and",
"resource",
"group",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L248-L263 | train | 39,150 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._create_virtual_network | 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']
}
}
try:
vnet_setup = self.network.virtual_networks.create_or_update(
resource_group_name, vnet_name, vnet_config
)
except Exception as error:
raise AzureCloudException(
'Unable to create vnet: {0}.'.format(error)
)
vnet_setup.wait() | python | 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']
}
}
try:
vnet_setup = self.network.virtual_networks.create_or_update(
resource_group_name, vnet_name, vnet_config
)
except Exception as error:
raise AzureCloudException(
'Unable to create vnet: {0}.'.format(error)
)
vnet_setup.wait() | [
"def",
"_create_virtual_network",
"(",
"self",
",",
"region",
",",
"resource_group_name",
",",
"vnet_name",
")",
":",
"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. | [
"Create",
"a",
"vnet",
"in",
"the",
"given",
"resource",
"group",
"with",
"default",
"address",
"space",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L265-L285 | train | 39,151 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._create_vm | 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
)
except Exception as error:
raise AzureCloudException(
'An exception occurred creating virtual machine: {0}'.format(
error
)
)
vm_setup.wait() | python | 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
)
except Exception as error:
raise AzureCloudException(
'An exception occurred creating virtual machine: {0}'.format(
error
)
)
vm_setup.wait() | [
"def",
"_create_vm",
"(",
"self",
",",
"vm_config",
")",
":",
"try",
":",
"vm_setup",
"=",
"self",
".",
"compute",
".",
"virtual_machines",
".",
"create_or_update",
"(",
"self",
".",
"running_instance_id",
",",
"self",
".",
"running_instance_id",
",",
"vm_conf... | Attempt to create or update VM instance based on vm_parameters config. | [
"Attempt",
"to",
"create",
"or",
"update",
"VM",
"instance",
"based",
"on",
"vm_parameters",
"config",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L287-L303 | train | 39,152 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._create_vm_config | 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 AZURE_DEFAULT_TYPE
}
network_profile = {
'network_interfaces': [{
'id': interface.id,
'primary': True
}]
}
storage_profile = self._create_storage_profile()
os_profile = {
'computer_name': self.running_instance_id,
'admin_username': self.ssh_user,
'linux_configuration': {
'disable_password_authentication': True,
'ssh': {
'public_keys': [{
'path': '/home/{0}/.ssh/authorized_keys'.format(
self.ssh_user
),
'key_data': self.ssh_public_key
}]
}
}
}
vm_config = {
'location': self.region,
'os_profile': os_profile,
'hardware_profile': hardware_profile,
'storage_profile': storage_profile,
'network_profile': network_profile
}
return vm_config | python | 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 AZURE_DEFAULT_TYPE
}
network_profile = {
'network_interfaces': [{
'id': interface.id,
'primary': True
}]
}
storage_profile = self._create_storage_profile()
os_profile = {
'computer_name': self.running_instance_id,
'admin_username': self.ssh_user,
'linux_configuration': {
'disable_password_authentication': True,
'ssh': {
'public_keys': [{
'path': '/home/{0}/.ssh/authorized_keys'.format(
self.ssh_user
),
'key_data': self.ssh_public_key
}]
}
}
}
vm_config = {
'location': self.region,
'os_profile': os_profile,
'hardware_profile': hardware_profile,
'storage_profile': storage_profile,
'network_profile': network_profile
}
return vm_config | [
"def",
"_create_vm_config",
"(",
"self",
",",
"interface",
")",
":",
"# Split image ID into it's components.",
"self",
".",
"_process_image_id",
"(",
")",
"hardware_profile",
"=",
"{",
"'vm_size'",
":",
"self",
".",
"instance_type",
"or",
"AZURE_DEFAULT_TYPE",
"}",
... | Create the VM config dictionary.
Requires an existing network interface object. | [
"Create",
"the",
"VM",
"config",
"dictionary",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L305-L351 | train | 39,153 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._get_instance | 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 Exception as error:
raise AzureCloudException(
'Unable to retrieve instance: {0}'.format(error)
)
return instance | python | 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 Exception as error:
raise AzureCloudException(
'Unable to retrieve instance: {0}'.format(error)
)
return instance | [
"def",
"_get_instance",
"(",
"self",
")",
":",
"try",
":",
"instance",
"=",
"self",
".",
"compute",
".",
"virtual_machines",
".",
"get",
"(",
"self",
".",
"running_instance_id",
",",
"self",
".",
"running_instance_id",
",",
"expand",
"=",
"'instanceView'",
"... | Return the instance matching the running_instance_id. | [
"Return",
"the",
"instance",
"matching",
"the",
"running_instance_id",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L353-L367 | train | 39,154 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._get_instance_state | 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 | python | 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 | [
"def",
"_get_instance_state",
"(",
"self",
")",
":",
"instance",
"=",
"self",
".",
"_get_instance",
"(",
")",
"statuses",
"=",
"instance",
".",
"instance_view",
".",
"statuses",
"for",
"status",
"in",
"statuses",
":",
"if",
"status",
".",
"code",
".",
"sta... | Retrieve state of instance. | [
"Retrieve",
"state",
"of",
"instance",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L369-L378 | train | 39,155 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._get_management_client | 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:
raise AzureCloudException(
'Service account file format is invalid: {0}.'.format(error)
)
except KeyError as error:
raise AzureCloudException(
'Service account file missing key: {0}.'.format(error)
)
except Exception as error:
raise AzureCloudException(
'Unable to create resource management client: '
'{0}.'.format(error)
)
return client | python | 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:
raise AzureCloudException(
'Service account file format is invalid: {0}.'.format(error)
)
except KeyError as error:
raise AzureCloudException(
'Service account file missing key: {0}.'.format(error)
)
except Exception as error:
raise AzureCloudException(
'Unable to create resource management client: '
'{0}.'.format(error)
)
return client | [
"def",
"_get_management_client",
"(",
"self",
",",
"client_class",
")",
":",
"try",
":",
"client",
"=",
"get_client_from_auth_file",
"(",
"client_class",
",",
"auth_path",
"=",
"self",
".",
"service_account_file",
")",
"except",
"ValueError",
"as",
"error",
":",
... | Return instance of resource management client. | [
"Return",
"instance",
"of",
"resource",
"management",
"client",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L380-L402 | train | 39,156 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._launch_instance | 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._set_default_resource_names()
try:
# Try block acts as a transaction. If an exception is raised
# attempt to cleanup the resource group and all created resources.
# Create resource group.
self._create_resource_group(self.region, self.running_instance_id)
if self.subnet_id:
# Use existing vnet/subnet.
subnet = self.network.subnets.get(
self.vnet_resource_group, self.vnet_name, self.subnet_id
)
else:
self.subnet_id = ''.join([self.running_instance_id, '-subnet'])
self.vnet_name = ''.join([self.running_instance_id, '-vnet'])
# Create new vnet
self._create_virtual_network(
self.region, self.running_instance_id, self.vnet_name
)
# Create new subnet in new vnet
subnet = self._create_subnet(
self.running_instance_id, self.subnet_id, self.vnet_name
)
# Setup interface and public ip in resource group.
public_ip = self._create_public_ip(
self.public_ip_name, self.running_instance_id, self.region
)
interface = self._create_network_interface(
self.ip_config_name, self.nic_name, public_ip, self.region,
self.running_instance_id, subnet, self.accelerated_networking
)
# Get dictionary of VM parameters and create instance.
vm_config = self._create_vm_config(interface)
self._create_vm(vm_config)
except Exception:
try:
self._terminate_instance()
except Exception:
pass
raise
else:
# Ensure VM is in the running state.
self._wait_on_instance('VM running', timeout=self.timeout) | python | 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._set_default_resource_names()
try:
# Try block acts as a transaction. If an exception is raised
# attempt to cleanup the resource group and all created resources.
# Create resource group.
self._create_resource_group(self.region, self.running_instance_id)
if self.subnet_id:
# Use existing vnet/subnet.
subnet = self.network.subnets.get(
self.vnet_resource_group, self.vnet_name, self.subnet_id
)
else:
self.subnet_id = ''.join([self.running_instance_id, '-subnet'])
self.vnet_name = ''.join([self.running_instance_id, '-vnet'])
# Create new vnet
self._create_virtual_network(
self.region, self.running_instance_id, self.vnet_name
)
# Create new subnet in new vnet
subnet = self._create_subnet(
self.running_instance_id, self.subnet_id, self.vnet_name
)
# Setup interface and public ip in resource group.
public_ip = self._create_public_ip(
self.public_ip_name, self.running_instance_id, self.region
)
interface = self._create_network_interface(
self.ip_config_name, self.nic_name, public_ip, self.region,
self.running_instance_id, subnet, self.accelerated_networking
)
# Get dictionary of VM parameters and create instance.
vm_config = self._create_vm_config(interface)
self._create_vm(vm_config)
except Exception:
try:
self._terminate_instance()
except Exception:
pass
raise
else:
# Ensure VM is in the running state.
self._wait_on_instance('VM running', timeout=self.timeout) | [
"def",
"_launch_instance",
"(",
"self",
")",
":",
"self",
".",
"running_instance_id",
"=",
"ipa_utils",
".",
"generate_instance_name",
"(",
"'azure-ipa-test'",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'ID of instance: %s'",
"%",
"self",
".",
"running_instan... | Create new test instance in a resource group with the same name. | [
"Create",
"new",
"test",
"instance",
"in",
"a",
"resource",
"group",
"with",
"the",
"same",
"name",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L417-L473 | train | 39,157 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._process_image_id | 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(':')
self.image_publisher = image_info[0]
self.image_offer = image_info[1]
self.image_sku = image_info[2]
self.image_version = image_info[3]
except Exception:
self.image_publisher = None | python | 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(':')
self.image_publisher = image_info[0]
self.image_offer = image_info[1]
self.image_sku = image_info[2]
self.image_version = image_info[3]
except Exception:
self.image_publisher = None | [
"def",
"_process_image_id",
"(",
"self",
")",
":",
"try",
":",
"image_info",
"=",
"self",
".",
"image_id",
".",
"strip",
"(",
")",
".",
"split",
"(",
"':'",
")",
"self",
".",
"image_publisher",
"=",
"image_info",
"[",
"0",
"]",
"self",
".",
"image_offe... | 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. | [
"Split",
"image",
"id",
"into",
"component",
"values",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L475-L492 | train | 39,158 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._set_default_resource_names | 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.public_ip_name = ''.join([self.running_instance_id, '-public-ip']) | python | 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.public_ip_name = ''.join([self.running_instance_id, '-public-ip']) | [
"def",
"_set_default_resource_names",
"(",
"self",
")",
":",
"self",
".",
"ip_config_name",
"=",
"''",
".",
"join",
"(",
"[",
"self",
".",
"running_instance_id",
",",
"'-ip-config'",
"]",
")",
"self",
".",
"nic_name",
"=",
"''",
".",
"join",
"(",
"[",
"s... | Generate names for resources based on the running_instance_id. | [
"Generate",
"names",
"for",
"resources",
"based",
"on",
"the",
"running_instance_id",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L494-L502 | train | 39,159 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._set_image_id | 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.publisher, image_info.offer,
image_info.sku, image_info.version
])
else:
self.image_id = image_info.id.rsplit('/', maxsplit=1)[1] | python | 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.publisher, image_info.offer,
image_info.sku, image_info.version
])
else:
self.image_id = image_info.id.rsplit('/', maxsplit=1)[1] | [
"def",
"_set_image_id",
"(",
"self",
")",
":",
"instance",
"=",
"self",
".",
"_get_instance",
"(",
")",
"image_info",
"=",
"instance",
".",
"storage_profile",
".",
"image_reference",
"if",
"image_info",
".",
"publisher",
":",
"self",
".",
"image_id",
"=",
"'... | If an existing instance is used get image id from deployment. | [
"If",
"an",
"existing",
"instance",
"is",
"used",
"get",
"image",
"id",
"from",
"deployment",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L504-L517 | train | 39,160 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._set_instance_ip | 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
).ip_address
except Exception:
try:
ip_address = self.network.network_interfaces.get(
self.running_instance_id, self.nic_name
).ip_configurations[0].private_ip_address
except Exception as error:
raise AzureCloudException(
'Unable to retrieve instance IP address: {0}.'.format(
error
)
)
self.instance_ip = ip_address | python | 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
).ip_address
except Exception:
try:
ip_address = self.network.network_interfaces.get(
self.running_instance_id, self.nic_name
).ip_configurations[0].private_ip_address
except Exception as error:
raise AzureCloudException(
'Unable to retrieve instance IP address: {0}.'.format(
error
)
)
self.instance_ip = ip_address | [
"def",
"_set_instance_ip",
"(",
"self",
")",
":",
"try",
":",
"ip_address",
"=",
"self",
".",
"network",
".",
"public_ip_addresses",
".",
"get",
"(",
"self",
".",
"running_instance_id",
",",
"self",
".",
"public_ip_name",
")",
".",
"ip_address",
"except",
"E... | Get the IP address based on instance ID.
If public IP address not found attempt to get private IP. | [
"Get",
"the",
"IP",
"address",
"based",
"on",
"instance",
"ID",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L519-L541 | train | 39,161 |
SUSE-Enceladus/ipa | ipa/ipa_azure.py | AzureCloud._terminate_instance | 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: {0}.'.format(error)
) | python | 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: {0}.'.format(error)
) | [
"def",
"_terminate_instance",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"resource",
".",
"resource_groups",
".",
"delete",
"(",
"self",
".",
"running_instance_id",
")",
"except",
"Exception",
"as",
"error",
":",
"raise",
"AzureCloudException",
"(",
"'Una... | Terminate the resource group and instance. | [
"Terminate",
"the",
"resource",
"group",
"and",
"instance",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_azure.py#L573-L582 | train | 39,162 |
tgbugs/pyontutils | ilxutils/ilxutils/scicrunch_client_helper.py | preferred_change | 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',
'NLXINV',
'NLXORG',
'NLXRES',
'NLXSUB'
'BIRNLEX',
'SAO',
'NDA.CDE',
'PR',
'IAO',
'NIFEXT',
'OEN',
'ILX',
]
mock_rank = ranking[::-1]
score = []
old_pref_index = None
for i, d in enumerate(data['existing_ids']):
if not d.get('preferred'): # db allows None or '' which will cause a problem
d['preferred'] = 0
if int(d['preferred']) == 1:
old_pref_index = i
if d.get('curie'):
pref = d['curie'].split(':')[0]
if pref in mock_rank:
score.append(mock_rank.index(pref))
else:
score.append(-1)
else:
score.append(-1)
new_pref_index = score.index(max(score))
new_pref_iri = data['existing_ids'][new_pref_index]['iri']
if new_pref_iri.rsplit('/', 1)[0] == 'http://uri.interlex.org/base':
if old_pref_index:
if old_pref_index != new_pref_index:
return data
for e in data['existing_ids']:
e['preferred'] = 0
data['existing_ids'][new_pref_index]['preferred'] = 1
return data | python | 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',
'NLXINV',
'NLXORG',
'NLXRES',
'NLXSUB'
'BIRNLEX',
'SAO',
'NDA.CDE',
'PR',
'IAO',
'NIFEXT',
'OEN',
'ILX',
]
mock_rank = ranking[::-1]
score = []
old_pref_index = None
for i, d in enumerate(data['existing_ids']):
if not d.get('preferred'): # db allows None or '' which will cause a problem
d['preferred'] = 0
if int(d['preferred']) == 1:
old_pref_index = i
if d.get('curie'):
pref = d['curie'].split(':')[0]
if pref in mock_rank:
score.append(mock_rank.index(pref))
else:
score.append(-1)
else:
score.append(-1)
new_pref_index = score.index(max(score))
new_pref_iri = data['existing_ids'][new_pref_index]['iri']
if new_pref_iri.rsplit('/', 1)[0] == 'http://uri.interlex.org/base':
if old_pref_index:
if old_pref_index != new_pref_index:
return data
for e in data['existing_ids']:
e['preferred'] = 0
data['existing_ids'][new_pref_index]['preferred'] = 1
return data | [
"def",
"preferred_change",
"(",
"data",
")",
":",
"ranking",
"=",
"[",
"'CHEBI'",
",",
"'NCBITaxon'",
",",
"'COGPO'",
",",
"'CAO'",
",",
"'DICOM'",
",",
"'UBERON'",
",",
"'NLX'",
",",
"'NLXANAT'",
",",
"'NLXCELL'",
",",
"'NLXFUNC'",
",",
"'NLXINV'",
",",
... | Determines preferred existing id based on curie prefix in the ranking list | [
"Determines",
"preferred",
"existing",
"id",
"based",
"on",
"curie",
"prefix",
"in",
"the",
"ranking",
"list"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/scicrunch_client_helper.py#L16-L68 | train | 39,163 |
SUSE-Enceladus/ipa | ipa/scripts/cli.py | main | 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 | python | 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 | [
"def",
"main",
"(",
"context",
",",
"no_color",
")",
":",
"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.). | [
"Ipa",
"provides",
"a",
"Python",
"API",
"and",
"command",
"line",
"utility",
"for",
"testing",
"images",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/scripts/cli.py#L73-L81 | train | 39,164 |
SUSE-Enceladus/ipa | ipa/scripts/cli.py | results | 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) | python | 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) | [
"def",
"results",
"(",
"context",
",",
"history_log",
")",
":",
"if",
"context",
".",
"obj",
"is",
"None",
":",
"context",
".",
"obj",
"=",
"{",
"}",
"context",
".",
"obj",
"[",
"'history_log'",
"]",
"=",
"history_log",
"if",
"context",
".",
"invoked_s... | Process provided history log and results files. | [
"Process",
"provided",
"history",
"log",
"and",
"results",
"files",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/scripts/cli.py#L347-L354 | train | 39,165 |
SUSE-Enceladus/ipa | ipa/scripts/cli.py | delete | 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) - item)
f.seek(0)
f.write(''.join(lines))
f.flush()
f.truncate()
except IndexError:
echo_style(
'History result at index %s does not exist.' % item,
no_color,
fg='red'
)
sys.exit(1)
except Exception as error:
echo_style(
'Unable to delete result item {0}. {1}'.format(item, error),
no_color,
fg='red'
)
sys.exit(1)
log_file = get_log_file_from_item(history)
try:
os.remove(log_file)
except Exception:
echo_style(
'Unable to delete results file for item {0}.'.format(item),
no_color,
fg='red'
)
try:
os.remove(log_file.rsplit('.', 1)[0] + '.results')
except Exception:
echo_style(
'Unable to delete log file for item {0}.'.format(item),
no_color,
fg='red'
) | python | 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) - item)
f.seek(0)
f.write(''.join(lines))
f.flush()
f.truncate()
except IndexError:
echo_style(
'History result at index %s does not exist.' % item,
no_color,
fg='red'
)
sys.exit(1)
except Exception as error:
echo_style(
'Unable to delete result item {0}. {1}'.format(item, error),
no_color,
fg='red'
)
sys.exit(1)
log_file = get_log_file_from_item(history)
try:
os.remove(log_file)
except Exception:
echo_style(
'Unable to delete results file for item {0}.'.format(item),
no_color,
fg='red'
)
try:
os.remove(log_file.rsplit('.', 1)[0] + '.results')
except Exception:
echo_style(
'Unable to delete log file for item {0}.'.format(item),
no_color,
fg='red'
) | [
"def",
"delete",
"(",
"context",
",",
"item",
")",
":",
"history_log",
"=",
"context",
".",
"obj",
"[",
"'history_log'",
"]",
"no_color",
"=",
"context",
".",
"obj",
"[",
"'no_color'",
"]",
"try",
":",
"with",
"open",
"(",
"history_log",
",",
"'r+'",
"... | Delete the specified history item from the history log. | [
"Delete",
"the",
"specified",
"history",
"item",
"from",
"the",
"history",
"log",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/scripts/cli.py#L447-L493 | train | 39,166 |
SUSE-Enceladus/ipa | ipa/scripts/cli.py | show | 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 log option selected echo test log.
"""
history_log = context.obj['history_log']
no_color = context.obj['no_color']
if not results_file:
# Find results/log file from history
# Default -1 is most recent test run
try:
with open(history_log, 'r') as f:
lines = f.readlines()
history = lines[len(lines) - item]
except IndexError:
echo_style(
'History result at index %s does not exist.' % item,
no_color,
fg='red'
)
sys.exit(1)
except Exception:
echo_style(
'Unable to retrieve results history, '
'provide results file or re-run test.',
no_color,
fg='red'
)
sys.exit(1)
log_file = get_log_file_from_item(history)
if log:
echo_log(log_file, no_color)
else:
echo_results_file(
log_file.rsplit('.', 1)[0] + '.results',
no_color,
verbose
)
elif log:
# Log file provided
echo_log(results_file, no_color)
else:
# Results file provided
echo_results_file(results_file, no_color, verbose) | python | 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 log option selected echo test log.
"""
history_log = context.obj['history_log']
no_color = context.obj['no_color']
if not results_file:
# Find results/log file from history
# Default -1 is most recent test run
try:
with open(history_log, 'r') as f:
lines = f.readlines()
history = lines[len(lines) - item]
except IndexError:
echo_style(
'History result at index %s does not exist.' % item,
no_color,
fg='red'
)
sys.exit(1)
except Exception:
echo_style(
'Unable to retrieve results history, '
'provide results file or re-run test.',
no_color,
fg='red'
)
sys.exit(1)
log_file = get_log_file_from_item(history)
if log:
echo_log(log_file, no_color)
else:
echo_results_file(
log_file.rsplit('.', 1)[0] + '.results',
no_color,
verbose
)
elif log:
# Log file provided
echo_log(results_file, no_color)
else:
# Results file provided
echo_results_file(results_file, no_color, verbose) | [
"def",
"show",
"(",
"context",
",",
"log",
",",
"results_file",
",",
"verbose",
",",
"item",
")",
":",
"history_log",
"=",
"context",
".",
"obj",
"[",
"'history_log'",
"]",
"no_color",
"=",
"context",
".",
"obj",
"[",
"'no_color'",
"]",
"if",
"not",
"r... | 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. | [
"Print",
"test",
"results",
"info",
"from",
"provided",
"results",
"json",
"file",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/scripts/cli.py#L528-L583 | train | 39,167 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud._get_ssh_client | 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
) | python | 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
) | [
"def",
"_get_ssh_client",
"(",
"self",
")",
":",
"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. | [
"Return",
"a",
"new",
"or",
"existing",
"SSH",
"client",
"for",
"given",
"ip",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L197-L204 | train | 39,168 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud._log_info | 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_stamp,
'log_file': self.log_file,
'results_file': self.results_file
}
else:
self.results['info'] = {
'platform': self.cloud,
'region': self.region,
'distro': self.distro_name,
'image': self.image_id,
'instance': self.running_instance_id,
'timestamp': self.time_stamp,
'log_file': self.log_file,
'results_file': self.results_file
}
self._write_to_log(
'\n'.join(
'%s: %s' % (key, val) for key, val
in self.results['info'].items()
)
) | python | 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_stamp,
'log_file': self.log_file,
'results_file': self.results_file
}
else:
self.results['info'] = {
'platform': self.cloud,
'region': self.region,
'distro': self.distro_name,
'image': self.image_id,
'instance': self.running_instance_id,
'timestamp': self.time_stamp,
'log_file': self.log_file,
'results_file': self.results_file
}
self._write_to_log(
'\n'.join(
'%s: %s' % (key, val) for key, val
in self.results['info'].items()
)
) | [
"def",
"_log_info",
"(",
"self",
")",
":",
"if",
"self",
".",
"cloud",
"==",
"'ssh'",
":",
"self",
".",
"results",
"[",
"'info'",
"]",
"=",
"{",
"'platform'",
":",
"self",
".",
"cloud",
",",
"'distro'",
":",
"self",
".",
"distro_name",
",",
"'image'"... | Output test run information to top of log file. | [
"Output",
"test",
"run",
"information",
"to",
"top",
"of",
"log",
"file",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L212-L240 | train | 39,169 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud._write_to_log | 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') | python | 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') | [
"def",
"_write_to_log",
"(",
"self",
",",
"output",
")",
":",
"with",
"open",
"(",
"self",
".",
"log_file",
",",
"'a'",
")",
"as",
"log_file",
":",
"log_file",
".",
"write",
"(",
"'\\n'",
")",
"log_file",
".",
"write",
"(",
"output",
")",
"log_file",
... | Write the output string to the log file. | [
"Write",
"the",
"output",
"string",
"to",
"the",
"log",
"file",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L242-L247 | train | 39,170 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud._merge_results | 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 | python | 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 | [
"def",
"_merge_results",
"(",
"self",
",",
"results",
")",
":",
"self",
".",
"results",
"[",
"'tests'",
"]",
"+=",
"results",
"[",
"'tests'",
"]",
"for",
"key",
",",
"value",
"in",
"results",
"[",
"'summary'",
"]",
".",
"items",
"(",
")",
":",
"self"... | Combine results of test run with exisiting dict. | [
"Combine",
"results",
"of",
"test",
"run",
"with",
"exisiting",
"dict",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L249-L254 | train | 39,171 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud._save_results | 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) | python | 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) | [
"def",
"_save_results",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"results_file",
",",
"'w'",
")",
"as",
"results_file",
":",
"json",
".",
"dump",
"(",
"self",
".",
"results",
",",
"results_file",
")"
] | Save results dictionary to json file. | [
"Save",
"results",
"dictionary",
"to",
"json",
"file",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L346-L349 | train | 39,172 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud._set_distro | 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(
'Distribution: %s, not supported.' % self.distro_name
) | python | 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(
'Distribution: %s, not supported.' % self.distro_name
) | [
"def",
"_set_distro",
"(",
"self",
")",
":",
"if",
"self",
".",
"distro_name",
"==",
"'sles'",
":",
"self",
".",
"distro",
"=",
"SLES",
"(",
")",
"elif",
"self",
".",
"distro_name",
"==",
"'opensuse_leap'",
":",
"self",
".",
"distro",
"=",
"openSUSE_Leap... | Determine distro for image and create instance of class. | [
"Determine",
"distro",
"for",
"image",
"and",
"create",
"instance",
"of",
"class",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L351-L360 | train | 39,173 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud._set_results_dir | def _set_results_dir(self):
"""Create results directory if not exists."""
if self.running_instance_id:
self.results_dir = os.path.join(
self.results_dir,
self.cloud,
self.image_id,
self.running_instance_id
)
else:
self.results_dir = os.path.join(
self.results_dir,
self.cloud,
self.instance_ip
)
try:
os.makedirs(self.results_dir)
except OSError as error:
if not os.path.isdir(self.results_dir):
raise IpaCloudException(
'Unable to create ipa results directory: %s' % error
)
self.time_stamp = datetime.now().strftime('%Y%m%d%H%M%S')
self.log_file = ''.join(
[self.results_dir, os.sep, self.time_stamp, '.log']
)
self.logger.debug('Created log file %s' % self.log_file)
self.results_file = ''.join(
[self.results_dir, os.sep, self.time_stamp, '.results']
)
self.logger.debug('Created results file %s' % self.results_file)
# Add log file handler
file_handler = logging.FileHandler(self.log_file)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter('\n%(message)s\n'))
self.logger.addHandler(file_handler) | python | def _set_results_dir(self):
"""Create results directory if not exists."""
if self.running_instance_id:
self.results_dir = os.path.join(
self.results_dir,
self.cloud,
self.image_id,
self.running_instance_id
)
else:
self.results_dir = os.path.join(
self.results_dir,
self.cloud,
self.instance_ip
)
try:
os.makedirs(self.results_dir)
except OSError as error:
if not os.path.isdir(self.results_dir):
raise IpaCloudException(
'Unable to create ipa results directory: %s' % error
)
self.time_stamp = datetime.now().strftime('%Y%m%d%H%M%S')
self.log_file = ''.join(
[self.results_dir, os.sep, self.time_stamp, '.log']
)
self.logger.debug('Created log file %s' % self.log_file)
self.results_file = ''.join(
[self.results_dir, os.sep, self.time_stamp, '.results']
)
self.logger.debug('Created results file %s' % self.results_file)
# Add log file handler
file_handler = logging.FileHandler(self.log_file)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter('\n%(message)s\n'))
self.logger.addHandler(file_handler) | [
"def",
"_set_results_dir",
"(",
"self",
")",
":",
"if",
"self",
".",
"running_instance_id",
":",
"self",
".",
"results_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"results_dir",
",",
"self",
".",
"cloud",
",",
"self",
".",
"image_id",
... | Create results directory if not exists. | [
"Create",
"results",
"directory",
"if",
"not",
"exists",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L368-L407 | train | 39,174 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud._collect_vm_info | def _collect_vm_info(self):
"""
Gather basic info about VM
"""
self.logger.info('Collecting basic info about VM')
client = self._get_ssh_client()
out = self.distro.get_vm_info(client)
self._write_to_log(out) | python | def _collect_vm_info(self):
"""
Gather basic info about VM
"""
self.logger.info('Collecting basic info about VM')
client = self._get_ssh_client()
out = self.distro.get_vm_info(client)
self._write_to_log(out) | [
"def",
"_collect_vm_info",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Collecting basic info about VM'",
")",
"client",
"=",
"self",
".",
"_get_ssh_client",
"(",
")",
"out",
"=",
"self",
".",
"distro",
".",
"get_vm_info",
"(",
"client",... | Gather basic info about VM | [
"Gather",
"basic",
"info",
"about",
"VM"
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L427-L435 | train | 39,175 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud._update_history | def _update_history(self):
"""Save the current test information to history json."""
ipa_utils.update_history_log(
self.history_log,
description=self.description,
test_log=self.log_file
) | python | def _update_history(self):
"""Save the current test information to history json."""
ipa_utils.update_history_log(
self.history_log,
description=self.description,
test_log=self.log_file
) | [
"def",
"_update_history",
"(",
"self",
")",
":",
"ipa_utils",
".",
"update_history_log",
"(",
"self",
".",
"history_log",
",",
"description",
"=",
"self",
".",
"description",
",",
"test_log",
"=",
"self",
".",
"log_file",
")"
] | Save the current test information to history json. | [
"Save",
"the",
"current",
"test",
"information",
"to",
"history",
"json",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L437-L443 | train | 39,176 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud._wait_on_instance | def _wait_on_instance(self, state, timeout=600, wait_period=10):
"""Wait until instance is in given state."""
current_state = 'Undefined'
start = time.time()
end = start + timeout
while time.time() < end:
current_state = self._get_instance_state()
if state.lower() == current_state.lower():
return
time.sleep(wait_period)
raise IpaCloudException(
'Instance has not arrived at the given state: {state}'.format(
state=state
)
) | python | def _wait_on_instance(self, state, timeout=600, wait_period=10):
"""Wait until instance is in given state."""
current_state = 'Undefined'
start = time.time()
end = start + timeout
while time.time() < end:
current_state = self._get_instance_state()
if state.lower() == current_state.lower():
return
time.sleep(wait_period)
raise IpaCloudException(
'Instance has not arrived at the given state: {state}'.format(
state=state
)
) | [
"def",
"_wait_on_instance",
"(",
"self",
",",
"state",
",",
"timeout",
"=",
"600",
",",
"wait_period",
"=",
"10",
")",
":",
"current_state",
"=",
"'Undefined'",
"start",
"=",
"time",
".",
"time",
"(",
")",
"end",
"=",
"start",
"+",
"timeout",
"while",
... | Wait until instance is in given state. | [
"Wait",
"until",
"instance",
"is",
"in",
"given",
"state",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L445-L463 | train | 39,177 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud.execute_ssh_command | def execute_ssh_command(self, client, command):
"""Execute the provided command and log output."""
try:
out = ipa_utils.execute_ssh_command(client, command)
except Exception as error:
raise IpaCloudException(
'Command: "{0}", failed execution: {1}.'.format(
command, error
)
)
else:
self._write_to_log(out) | python | def execute_ssh_command(self, client, command):
"""Execute the provided command and log output."""
try:
out = ipa_utils.execute_ssh_command(client, command)
except Exception as error:
raise IpaCloudException(
'Command: "{0}", failed execution: {1}.'.format(
command, error
)
)
else:
self._write_to_log(out) | [
"def",
"execute_ssh_command",
"(",
"self",
",",
"client",
",",
"command",
")",
":",
"try",
":",
"out",
"=",
"ipa_utils",
".",
"execute_ssh_command",
"(",
"client",
",",
"command",
")",
"except",
"Exception",
"as",
"error",
":",
"raise",
"IpaCloudException",
... | Execute the provided command and log output. | [
"Execute",
"the",
"provided",
"command",
"and",
"log",
"output",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L465-L476 | train | 39,178 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud.extract_archive | def extract_archive(self, client, archive_path, extract_path=None):
"""Extract the archive files using the client in the current path."""
try:
out = ipa_utils.extract_archive(client, archive_path, extract_path)
except Exception as error:
raise IpaCloudException(
'Failed to extract archive, "{0}": {1}.'.format(
archive_path, error
)
)
else:
self._write_to_log(out) | python | def extract_archive(self, client, archive_path, extract_path=None):
"""Extract the archive files using the client in the current path."""
try:
out = ipa_utils.extract_archive(client, archive_path, extract_path)
except Exception as error:
raise IpaCloudException(
'Failed to extract archive, "{0}": {1}.'.format(
archive_path, error
)
)
else:
self._write_to_log(out) | [
"def",
"extract_archive",
"(",
"self",
",",
"client",
",",
"archive_path",
",",
"extract_path",
"=",
"None",
")",
":",
"try",
":",
"out",
"=",
"ipa_utils",
".",
"extract_archive",
"(",
"client",
",",
"archive_path",
",",
"extract_path",
")",
"except",
"Excep... | Extract the archive files using the client in the current path. | [
"Extract",
"the",
"archive",
"files",
"using",
"the",
"client",
"in",
"the",
"current",
"path",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L478-L490 | train | 39,179 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud.hard_reboot_instance | def hard_reboot_instance(self):
"""Stop then start the instance."""
self._stop_instance()
self._start_instance()
self._set_instance_ip()
self.logger.debug('IP of instance: %s' % self.instance_ip)
ipa_utils.clear_cache() | python | def hard_reboot_instance(self):
"""Stop then start the instance."""
self._stop_instance()
self._start_instance()
self._set_instance_ip()
self.logger.debug('IP of instance: %s' % self.instance_ip)
ipa_utils.clear_cache() | [
"def",
"hard_reboot_instance",
"(",
"self",
")",
":",
"self",
".",
"_stop_instance",
"(",
")",
"self",
".",
"_start_instance",
"(",
")",
"self",
".",
"_set_instance_ip",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'IP of instance: %s'",
"%",
"self",... | Stop then start the instance. | [
"Stop",
"then",
"start",
"the",
"instance",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L492-L498 | train | 39,180 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud.install_package | def install_package(self, client, package):
"""
Install package using distro specific install method.
"""
try:
out = self.distro.install_package(client, package)
except Exception as error:
raise IpaCloudException(
'Failed installing package, "{0}"; {1}.'.format(
package, error
)
)
else:
self._write_to_log(out) | python | def install_package(self, client, package):
"""
Install package using distro specific install method.
"""
try:
out = self.distro.install_package(client, package)
except Exception as error:
raise IpaCloudException(
'Failed installing package, "{0}"; {1}.'.format(
package, error
)
)
else:
self._write_to_log(out) | [
"def",
"install_package",
"(",
"self",
",",
"client",
",",
"package",
")",
":",
"try",
":",
"out",
"=",
"self",
".",
"distro",
".",
"install_package",
"(",
"client",
",",
"package",
")",
"except",
"Exception",
"as",
"error",
":",
"raise",
"IpaCloudExceptio... | Install package using distro specific install method. | [
"Install",
"package",
"using",
"distro",
"specific",
"install",
"method",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L500-L513 | train | 39,181 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud.process_injection_file | def process_injection_file(self, client):
"""
Load yaml file and process injection configuration.
There are 5 injection options:
:inject_packages: an rpm path or list of rpm paths which will be
copied and installed on the test instance.
:inject_archives: an archive or list of archives which will
be copied and extracted on the test instance.
:inject_files: a file path or list of file paths which
will be copied to the test instance.
:execute: a command or list of commands to run on the test instance.
:install: a package name or list of package names to
install from an existing repo on the test instance.
The order of processing is as follows: inject_packages,
inject_archives, inject_files, execute, install.
"""
configuration = ipa_utils.get_yaml_config(self.inject)
if configuration.get('inject_packages'):
inject_packages = configuration['inject_packages']
if not isinstance(inject_packages, list):
inject_packages = [inject_packages]
for package in inject_packages:
package_path = self.put_file(client, package)
self.install_package(client, package_path)
if configuration.get('inject_archives'):
inject_archives = configuration['inject_archives']
if not isinstance(inject_archives, list):
inject_archives = [inject_archives]
for archive in inject_archives:
archive_path = self.put_file(client, archive)
self.extract_archive(client, archive_path)
if configuration.get('inject_files'):
inject_files = configuration['inject_files']
if not isinstance(inject_files, list):
inject_files = [inject_files]
for file_path in inject_files:
self.put_file(client, file_path)
if configuration.get('execute'):
execute = configuration['execute']
if not isinstance(execute, list):
execute = [execute]
for command in execute:
self.execute_ssh_command(client, command)
if configuration.get('install'):
install = configuration['install']
if not isinstance(install, list):
install = [install]
for package in install:
self.install_package(client, package) | python | def process_injection_file(self, client):
"""
Load yaml file and process injection configuration.
There are 5 injection options:
:inject_packages: an rpm path or list of rpm paths which will be
copied and installed on the test instance.
:inject_archives: an archive or list of archives which will
be copied and extracted on the test instance.
:inject_files: a file path or list of file paths which
will be copied to the test instance.
:execute: a command or list of commands to run on the test instance.
:install: a package name or list of package names to
install from an existing repo on the test instance.
The order of processing is as follows: inject_packages,
inject_archives, inject_files, execute, install.
"""
configuration = ipa_utils.get_yaml_config(self.inject)
if configuration.get('inject_packages'):
inject_packages = configuration['inject_packages']
if not isinstance(inject_packages, list):
inject_packages = [inject_packages]
for package in inject_packages:
package_path = self.put_file(client, package)
self.install_package(client, package_path)
if configuration.get('inject_archives'):
inject_archives = configuration['inject_archives']
if not isinstance(inject_archives, list):
inject_archives = [inject_archives]
for archive in inject_archives:
archive_path = self.put_file(client, archive)
self.extract_archive(client, archive_path)
if configuration.get('inject_files'):
inject_files = configuration['inject_files']
if not isinstance(inject_files, list):
inject_files = [inject_files]
for file_path in inject_files:
self.put_file(client, file_path)
if configuration.get('execute'):
execute = configuration['execute']
if not isinstance(execute, list):
execute = [execute]
for command in execute:
self.execute_ssh_command(client, command)
if configuration.get('install'):
install = configuration['install']
if not isinstance(install, list):
install = [install]
for package in install:
self.install_package(client, package) | [
"def",
"process_injection_file",
"(",
"self",
",",
"client",
")",
":",
"configuration",
"=",
"ipa_utils",
".",
"get_yaml_config",
"(",
"self",
".",
"inject",
")",
"if",
"configuration",
".",
"get",
"(",
"'inject_packages'",
")",
":",
"inject_packages",
"=",
"c... | Load yaml file and process injection configuration.
There are 5 injection options:
:inject_packages: an rpm path or list of rpm paths which will be
copied and installed on the test instance.
:inject_archives: an archive or list of archives which will
be copied and extracted on the test instance.
:inject_files: a file path or list of file paths which
will be copied to the test instance.
:execute: a command or list of commands to run on the test instance.
:install: a package name or list of package names to
install from an existing repo on the test instance.
The order of processing is as follows: inject_packages,
inject_archives, inject_files, execute, install. | [
"Load",
"yaml",
"file",
"and",
"process",
"injection",
"configuration",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L515-L581 | train | 39,182 |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | IpaCloud.put_file | def put_file(self, client, source_file):
"""
Put file on instance in default SSH directory.
"""
try:
file_name = os.path.basename(source_file)
ipa_utils.put_file(client, source_file, file_name)
except Exception as error:
raise IpaCloudException(
'Failed copying file, "{0}"; {1}.'.format(
source_file, error
)
)
else:
return file_name | python | def put_file(self, client, source_file):
"""
Put file on instance in default SSH directory.
"""
try:
file_name = os.path.basename(source_file)
ipa_utils.put_file(client, source_file, file_name)
except Exception as error:
raise IpaCloudException(
'Failed copying file, "{0}"; {1}.'.format(
source_file, error
)
)
else:
return file_name | [
"def",
"put_file",
"(",
"self",
",",
"client",
",",
"source_file",
")",
":",
"try",
":",
"file_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"source_file",
")",
"ipa_utils",
".",
"put_file",
"(",
"client",
",",
"source_file",
",",
"file_name",
")"... | Put file on instance in default SSH directory. | [
"Put",
"file",
"on",
"instance",
"in",
"default",
"SSH",
"directory",
"."
] | 0845eed0ea25a27dbb059ad1016105fa60002228 | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L583-L597 | train | 39,183 |
tgbugs/pyontutils | nifstd/nifstd_tools/ilx_utils.py | decodeIlxResp | def decodeIlxResp(resp):
""" We need this until we can get json back directly and this is SUPER nasty"""
lines = [_ for _ in resp.text.split('\n') if _] # strip empties
if 'successfull' in lines[0]:
return [(_.split('"')[1],
ilxIdFix(_.split(': ')[-1]))
for _ in lines[1:]]
elif 'errors' in lines[0]:
return [(_.split('"')[1],
ilxIdFix(_.split('(')[1].split(')')[0]))
for _ in lines[1:]] | python | def decodeIlxResp(resp):
""" We need this until we can get json back directly and this is SUPER nasty"""
lines = [_ for _ in resp.text.split('\n') if _] # strip empties
if 'successfull' in lines[0]:
return [(_.split('"')[1],
ilxIdFix(_.split(': ')[-1]))
for _ in lines[1:]]
elif 'errors' in lines[0]:
return [(_.split('"')[1],
ilxIdFix(_.split('(')[1].split(')')[0]))
for _ in lines[1:]] | [
"def",
"decodeIlxResp",
"(",
"resp",
")",
":",
"lines",
"=",
"[",
"_",
"for",
"_",
"in",
"resp",
".",
"text",
".",
"split",
"(",
"'\\n'",
")",
"if",
"_",
"]",
"# strip empties",
"if",
"'successfull'",
"in",
"lines",
"[",
"0",
"]",
":",
"return",
"[... | We need this until we can get json back directly and this is SUPER nasty | [
"We",
"need",
"this",
"until",
"we",
"can",
"get",
"json",
"back",
"directly",
"and",
"this",
"is",
"SUPER",
"nasty"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/nifstd/nifstd_tools/ilx_utils.py#L154-L165 | train | 39,184 |
tgbugs/pyontutils | nifstd/nifstd_tools/ilx_utils.py | getSubOrder | def getSubOrder(existing):
""" Alpha sort by the full chain of parents. """
alpha = list(zip(*sorted(((k, v['rec']['label']) for k, v in existing.items()), key=lambda a: a[1])))[0]
depths = {}
def getDepth(id_):
if id_ in depths:
return depths[id_]
else:
if id_ in existing:
names_above = getDepth(existing[id_]['sc'])
depths[id_] = names_above + [existing[id_]['rec']['label']]
return depths[id_]
else:
return ['']
for id_ in existing:
getDepth(id_)
print(sorted(depths.values()))
def key_(id_):
return depths[id_]
return sorted(depths, key=key_) | python | def getSubOrder(existing):
""" Alpha sort by the full chain of parents. """
alpha = list(zip(*sorted(((k, v['rec']['label']) for k, v in existing.items()), key=lambda a: a[1])))[0]
depths = {}
def getDepth(id_):
if id_ in depths:
return depths[id_]
else:
if id_ in existing:
names_above = getDepth(existing[id_]['sc'])
depths[id_] = names_above + [existing[id_]['rec']['label']]
return depths[id_]
else:
return ['']
for id_ in existing:
getDepth(id_)
print(sorted(depths.values()))
def key_(id_):
return depths[id_]
return sorted(depths, key=key_) | [
"def",
"getSubOrder",
"(",
"existing",
")",
":",
"alpha",
"=",
"list",
"(",
"zip",
"(",
"*",
"sorted",
"(",
"(",
"(",
"k",
",",
"v",
"[",
"'rec'",
"]",
"[",
"'label'",
"]",
")",
"for",
"k",
",",
"v",
"in",
"existing",
".",
"items",
"(",
")",
... | Alpha sort by the full chain of parents. | [
"Alpha",
"sort",
"by",
"the",
"full",
"chain",
"of",
"parents",
"."
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/nifstd/nifstd_tools/ilx_utils.py#L294-L317 | train | 39,185 |
tgbugs/pyontutils | nifstd/nifstd_tools/hbp_cells.py | ilx_conv | def ilx_conv(graph, prefix, ilx_start):
""" convert a set of temporary identifiers to ilx and modify the graph in place """
to_sub = set()
for subject in graph.subjects(rdflib.RDF.type, rdflib.OWL.Class):
if PREFIXES[prefix] in subject:
to_sub.add(subject)
ilx_base = 'ilx_{:0>7}'
ILX_base = 'ILX:{:0>7}' # ah rdflib/owlapi, you infuriate me
ilx_labels = {}
replace = {}
for sub in sorted(to_sub):
ilx_format = ilx_base.format(ilx_start)
ILX_format = ILX_base.format(ilx_start)
ilx_start += 1
prefix, url, suffix = graph.namespace_manager.compute_qname(sub)
curie = prefix + ':' + suffix
replace[curie] = ILX_format
label = [_ for _ in graph.objects(sub, rdflib.RDFS.label)][0]
ilx_labels[ilx_format] = label
new_sub = expand('ilx:' + ilx_format)
for p, o in graph.predicate_objects(sub):
graph.remove((sub, p, o))
graph.add((new_sub, p, o))
for s, p in graph.subject_predicates(sub):
graph.remove((s, p, sub))
graph.add((s, p, new_sub))
return ilx_labels, replace | python | def ilx_conv(graph, prefix, ilx_start):
""" convert a set of temporary identifiers to ilx and modify the graph in place """
to_sub = set()
for subject in graph.subjects(rdflib.RDF.type, rdflib.OWL.Class):
if PREFIXES[prefix] in subject:
to_sub.add(subject)
ilx_base = 'ilx_{:0>7}'
ILX_base = 'ILX:{:0>7}' # ah rdflib/owlapi, you infuriate me
ilx_labels = {}
replace = {}
for sub in sorted(to_sub):
ilx_format = ilx_base.format(ilx_start)
ILX_format = ILX_base.format(ilx_start)
ilx_start += 1
prefix, url, suffix = graph.namespace_manager.compute_qname(sub)
curie = prefix + ':' + suffix
replace[curie] = ILX_format
label = [_ for _ in graph.objects(sub, rdflib.RDFS.label)][0]
ilx_labels[ilx_format] = label
new_sub = expand('ilx:' + ilx_format)
for p, o in graph.predicate_objects(sub):
graph.remove((sub, p, o))
graph.add((new_sub, p, o))
for s, p in graph.subject_predicates(sub):
graph.remove((s, p, sub))
graph.add((s, p, new_sub))
return ilx_labels, replace | [
"def",
"ilx_conv",
"(",
"graph",
",",
"prefix",
",",
"ilx_start",
")",
":",
"to_sub",
"=",
"set",
"(",
")",
"for",
"subject",
"in",
"graph",
".",
"subjects",
"(",
"rdflib",
".",
"RDF",
".",
"type",
",",
"rdflib",
".",
"OWL",
".",
"Class",
")",
":",... | convert a set of temporary identifiers to ilx and modify the graph in place | [
"convert",
"a",
"set",
"of",
"temporary",
"identifiers",
"to",
"ilx",
"and",
"modify",
"the",
"graph",
"in",
"place"
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/nifstd/nifstd_tools/hbp_cells.py#L62-L93 | train | 39,186 |
tgbugs/pyontutils | neurondm/neurondm/lang.py | config | def config(remote_base= 'https://raw.githubusercontent.com/SciCrunch/NIF-Ontology/',
local_base= None, # devconfig.ontology_local_repo by default
branch= devconfig.neurons_branch,
core_graph_paths= ['ttl/phenotype-core.ttl',
'ttl/phenotypes.ttl'],
core_graph= None,
in_graph_paths= tuple(),
out_graph_path= '/tmp/_Neurons.ttl',
out_imports= ['ttl/phenotype-core.ttl'],
out_graph= None,
prefixes= tuple(),
force_remote= False,
checkout_ok= ont_checkout_ok,
scigraph= None, # defaults to devconfig.scigraph_api
iri= None,
sources= tuple(),
source_file= None,
use_local_import_paths=True,
ignore_existing= True):
""" Wraps graphBase.configGraphIO to provide a set of sane defaults
for input ontologies and output files. """
graphBase.configGraphIO(remote_base=remote_base,
local_base=local_base,
branch=branch,
core_graph_paths=core_graph_paths,
core_graph=core_graph,
in_graph_paths=in_graph_paths,
out_graph_path=out_graph_path,
out_imports=out_imports,
out_graph=out_graph,
prefixes=prefixes,
force_remote=force_remote,
checkout_ok=checkout_ok,
scigraph=scigraph,
iri=iri,
sources=sources,
source_file=source_file,
use_local_import_paths=use_local_import_paths,
ignore_existing=ignore_existing)
pred = graphBase._predicates
return pred | python | def config(remote_base= 'https://raw.githubusercontent.com/SciCrunch/NIF-Ontology/',
local_base= None, # devconfig.ontology_local_repo by default
branch= devconfig.neurons_branch,
core_graph_paths= ['ttl/phenotype-core.ttl',
'ttl/phenotypes.ttl'],
core_graph= None,
in_graph_paths= tuple(),
out_graph_path= '/tmp/_Neurons.ttl',
out_imports= ['ttl/phenotype-core.ttl'],
out_graph= None,
prefixes= tuple(),
force_remote= False,
checkout_ok= ont_checkout_ok,
scigraph= None, # defaults to devconfig.scigraph_api
iri= None,
sources= tuple(),
source_file= None,
use_local_import_paths=True,
ignore_existing= True):
""" Wraps graphBase.configGraphIO to provide a set of sane defaults
for input ontologies and output files. """
graphBase.configGraphIO(remote_base=remote_base,
local_base=local_base,
branch=branch,
core_graph_paths=core_graph_paths,
core_graph=core_graph,
in_graph_paths=in_graph_paths,
out_graph_path=out_graph_path,
out_imports=out_imports,
out_graph=out_graph,
prefixes=prefixes,
force_remote=force_remote,
checkout_ok=checkout_ok,
scigraph=scigraph,
iri=iri,
sources=sources,
source_file=source_file,
use_local_import_paths=use_local_import_paths,
ignore_existing=ignore_existing)
pred = graphBase._predicates
return pred | [
"def",
"config",
"(",
"remote_base",
"=",
"'https://raw.githubusercontent.com/SciCrunch/NIF-Ontology/'",
",",
"local_base",
"=",
"None",
",",
"# devconfig.ontology_local_repo by default",
"branch",
"=",
"devconfig",
".",
"neurons_branch",
",",
"core_graph_paths",
"=",
"[",
... | Wraps graphBase.configGraphIO to provide a set of sane defaults
for input ontologies and output files. | [
"Wraps",
"graphBase",
".",
"configGraphIO",
"to",
"provide",
"a",
"set",
"of",
"sane",
"defaults",
"for",
"input",
"ontologies",
"and",
"output",
"files",
"."
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/neurondm/neurondm/lang.py#L34-L75 | train | 39,187 |
tgbugs/pyontutils | pyontutils/ontutils.py | add_version_iri | def add_version_iri(graph, epoch):
""" Also remove the previous versionIRI if there was one."""
for ont in graph.subjects(rdf.type, owl.Ontology):
for versionIRI in graph.objects(ont, owl.versionIRI):
graph.remove((ont, owl.versionIRI, versionIRI))
t = ont, owl.versionIRI, make_version_iri_from_iri(ont, epoch)
graph.add(t) | python | def add_version_iri(graph, epoch):
""" Also remove the previous versionIRI if there was one."""
for ont in graph.subjects(rdf.type, owl.Ontology):
for versionIRI in graph.objects(ont, owl.versionIRI):
graph.remove((ont, owl.versionIRI, versionIRI))
t = ont, owl.versionIRI, make_version_iri_from_iri(ont, epoch)
graph.add(t) | [
"def",
"add_version_iri",
"(",
"graph",
",",
"epoch",
")",
":",
"for",
"ont",
"in",
"graph",
".",
"subjects",
"(",
"rdf",
".",
"type",
",",
"owl",
".",
"Ontology",
")",
":",
"for",
"versionIRI",
"in",
"graph",
".",
"objects",
"(",
"ont",
",",
"owl",
... | Also remove the previous versionIRI if there was one. | [
"Also",
"remove",
"the",
"previous",
"versionIRI",
"if",
"there",
"was",
"one",
"."
] | 3d913db29c177db39151592909a4f56170ef8b35 | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/ontutils.py#L323-L329 | train | 39,188 |
Sheeprider/BitBucket-api | bitbucket/bitbucket.py | Bitbucket.auth | def auth(self):
""" Return credentials for current Bitbucket user. """
if self.oauth:
return self.oauth
return (self.username, self.password) | python | def auth(self):
""" Return credentials for current Bitbucket user. """
if self.oauth:
return self.oauth
return (self.username, self.password) | [
"def",
"auth",
"(",
"self",
")",
":",
"if",
"self",
".",
"oauth",
":",
"return",
"self",
".",
"oauth",
"return",
"(",
"self",
".",
"username",
",",
"self",
".",
"password",
")"
] | Return credentials for current Bitbucket user. | [
"Return",
"credentials",
"for",
"current",
"Bitbucket",
"user",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/bitbucket.py#L71-L75 | train | 39,189 |
Sheeprider/BitBucket-api | bitbucket/bitbucket.py | Bitbucket.authorize | def authorize(self, consumer_key, consumer_secret, callback_url=None,
access_token=None, access_token_secret=None):
"""
Call this with your consumer key, secret and callback URL, to
generate a token for verification.
"""
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
if not access_token and not access_token_secret:
if not callback_url:
return (False, "Callback URL required")
oauth = OAuth1(
consumer_key,
client_secret=consumer_secret,
callback_uri=callback_url)
r = requests.post(self.url('REQUEST_TOKEN'), auth=oauth)
if r.status_code == 200:
creds = parse_qs(r.content)
self.access_token = creds.get('oauth_token')[0]
self.access_token_secret = creds.get('oauth_token_secret')[0]
else:
return (False, r.content)
else:
self.finalize_oauth(access_token, access_token_secret)
return (True, None) | python | def authorize(self, consumer_key, consumer_secret, callback_url=None,
access_token=None, access_token_secret=None):
"""
Call this with your consumer key, secret and callback URL, to
generate a token for verification.
"""
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
if not access_token and not access_token_secret:
if not callback_url:
return (False, "Callback URL required")
oauth = OAuth1(
consumer_key,
client_secret=consumer_secret,
callback_uri=callback_url)
r = requests.post(self.url('REQUEST_TOKEN'), auth=oauth)
if r.status_code == 200:
creds = parse_qs(r.content)
self.access_token = creds.get('oauth_token')[0]
self.access_token_secret = creds.get('oauth_token_secret')[0]
else:
return (False, r.content)
else:
self.finalize_oauth(access_token, access_token_secret)
return (True, None) | [
"def",
"authorize",
"(",
"self",
",",
"consumer_key",
",",
"consumer_secret",
",",
"callback_url",
"=",
"None",
",",
"access_token",
"=",
"None",
",",
"access_token_secret",
"=",
"None",
")",
":",
"self",
".",
"consumer_key",
"=",
"consumer_key",
"self",
".",
... | Call this with your consumer key, secret and callback URL, to
generate a token for verification. | [
"Call",
"this",
"with",
"your",
"consumer",
"key",
"secret",
"and",
"callback",
"URL",
"to",
"generate",
"a",
"token",
"for",
"verification",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/bitbucket.py#L143-L170 | train | 39,190 |
Sheeprider/BitBucket-api | bitbucket/bitbucket.py | Bitbucket.verify | def verify(self, verifier, consumer_key=None, consumer_secret=None,
access_token=None, access_token_secret=None):
"""
After converting the token into verifier, call this to finalize the
authorization.
"""
# Stored values can be supplied to verify
self.consumer_key = consumer_key or self.consumer_key
self.consumer_secret = consumer_secret or self.consumer_secret
self.access_token = access_token or self.access_token
self.access_token_secret = access_token_secret or self.access_token_secret
oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.access_token,
resource_owner_secret=self.access_token_secret,
verifier=verifier)
r = requests.post(self.url('ACCESS_TOKEN'), auth=oauth)
if r.status_code == 200:
creds = parse_qs(r.content)
else:
return (False, r.content)
self.finalize_oauth(creds.get('oauth_token')[0],
creds.get('oauth_token_secret')[0])
return (True, None) | python | def verify(self, verifier, consumer_key=None, consumer_secret=None,
access_token=None, access_token_secret=None):
"""
After converting the token into verifier, call this to finalize the
authorization.
"""
# Stored values can be supplied to verify
self.consumer_key = consumer_key or self.consumer_key
self.consumer_secret = consumer_secret or self.consumer_secret
self.access_token = access_token or self.access_token
self.access_token_secret = access_token_secret or self.access_token_secret
oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.access_token,
resource_owner_secret=self.access_token_secret,
verifier=verifier)
r = requests.post(self.url('ACCESS_TOKEN'), auth=oauth)
if r.status_code == 200:
creds = parse_qs(r.content)
else:
return (False, r.content)
self.finalize_oauth(creds.get('oauth_token')[0],
creds.get('oauth_token_secret')[0])
return (True, None) | [
"def",
"verify",
"(",
"self",
",",
"verifier",
",",
"consumer_key",
"=",
"None",
",",
"consumer_secret",
"=",
"None",
",",
"access_token",
"=",
"None",
",",
"access_token_secret",
"=",
"None",
")",
":",
"# Stored values can be supplied to verify",
"self",
".",
"... | After converting the token into verifier, call this to finalize the
authorization. | [
"After",
"converting",
"the",
"token",
"into",
"verifier",
"call",
"this",
"to",
"finalize",
"the",
"authorization",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/bitbucket.py#L172-L198 | train | 39,191 |
Sheeprider/BitBucket-api | bitbucket/bitbucket.py | Bitbucket.finalize_oauth | def finalize_oauth(self, access_token, access_token_secret):
""" Called internally once auth process is complete. """
self.access_token = access_token
self.access_token_secret = access_token_secret
# Final OAuth object
self.oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.access_token,
resource_owner_secret=self.access_token_secret) | python | def finalize_oauth(self, access_token, access_token_secret):
""" Called internally once auth process is complete. """
self.access_token = access_token
self.access_token_secret = access_token_secret
# Final OAuth object
self.oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.access_token,
resource_owner_secret=self.access_token_secret) | [
"def",
"finalize_oauth",
"(",
"self",
",",
"access_token",
",",
"access_token_secret",
")",
":",
"self",
".",
"access_token",
"=",
"access_token",
"self",
".",
"access_token_secret",
"=",
"access_token_secret",
"# Final OAuth object",
"self",
".",
"oauth",
"=",
"OAu... | Called internally once auth process is complete. | [
"Called",
"internally",
"once",
"auth",
"process",
"is",
"complete",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/bitbucket.py#L200-L210 | train | 39,192 |
Sheeprider/BitBucket-api | bitbucket/bitbucket.py | Bitbucket.dispatch | def dispatch(self, method, url, auth=None, params=None, **kwargs):
""" Send HTTP request, with given method,
credentials and data to the given URL,
and return the success and the result on success.
"""
r = Request(
method=method,
url=url,
auth=auth,
params=params,
data=kwargs)
s = Session()
resp = s.send(r.prepare())
status = resp.status_code
text = resp.text
error = resp.reason
if status >= 200 and status < 300:
if text:
try:
return (True, json.loads(text))
except TypeError:
pass
except ValueError:
pass
return (True, text)
elif status >= 300 and status < 400:
return (
False,
'Unauthorized access, '
'please check your credentials.')
elif status >= 400 and status < 500:
return (False, 'Service not found.')
elif status >= 500 and status < 600:
return (False, 'Server error.')
else:
return (False, error) | python | def dispatch(self, method, url, auth=None, params=None, **kwargs):
""" Send HTTP request, with given method,
credentials and data to the given URL,
and return the success and the result on success.
"""
r = Request(
method=method,
url=url,
auth=auth,
params=params,
data=kwargs)
s = Session()
resp = s.send(r.prepare())
status = resp.status_code
text = resp.text
error = resp.reason
if status >= 200 and status < 300:
if text:
try:
return (True, json.loads(text))
except TypeError:
pass
except ValueError:
pass
return (True, text)
elif status >= 300 and status < 400:
return (
False,
'Unauthorized access, '
'please check your credentials.')
elif status >= 400 and status < 500:
return (False, 'Service not found.')
elif status >= 500 and status < 600:
return (False, 'Server error.')
else:
return (False, error) | [
"def",
"dispatch",
"(",
"self",
",",
"method",
",",
"url",
",",
"auth",
"=",
"None",
",",
"params",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"Request",
"(",
"method",
"=",
"method",
",",
"url",
"=",
"url",
",",
"auth",
"=",
"au... | Send HTTP request, with given method,
credentials and data to the given URL,
and return the success and the result on success. | [
"Send",
"HTTP",
"request",
"with",
"given",
"method",
"credentials",
"and",
"data",
"to",
"the",
"given",
"URL",
"and",
"return",
"the",
"success",
"and",
"the",
"result",
"on",
"success",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/bitbucket.py#L216-L251 | train | 39,193 |
Sheeprider/BitBucket-api | bitbucket/bitbucket.py | Bitbucket.url | def url(self, action, **kwargs):
""" Construct and return the URL for a specific API service. """
# TODO : should be static method ?
return self.URLS['BASE'] % self.URLS[action] % kwargs | python | def url(self, action, **kwargs):
""" Construct and return the URL for a specific API service. """
# TODO : should be static method ?
return self.URLS['BASE'] % self.URLS[action] % kwargs | [
"def",
"url",
"(",
"self",
",",
"action",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO : should be static method ?",
"return",
"self",
".",
"URLS",
"[",
"'BASE'",
"]",
"%",
"self",
".",
"URLS",
"[",
"action",
"]",
"%",
"kwargs"
] | Construct and return the URL for a specific API service. | [
"Construct",
"and",
"return",
"the",
"URL",
"for",
"a",
"specific",
"API",
"service",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/bitbucket.py#L253-L256 | train | 39,194 |
Sheeprider/BitBucket-api | bitbucket/bitbucket.py | Bitbucket.get_user | def get_user(self, username=None):
""" Returns user informations.
If username is not defined, tries to return own informations.
"""
username = username or self.username or ''
url = self.url('GET_USER', username=username)
response = self.dispatch('GET', url)
try:
return (response[0], response[1]['user'])
except TypeError:
pass
return response | python | def get_user(self, username=None):
""" Returns user informations.
If username is not defined, tries to return own informations.
"""
username = username or self.username or ''
url = self.url('GET_USER', username=username)
response = self.dispatch('GET', url)
try:
return (response[0], response[1]['user'])
except TypeError:
pass
return response | [
"def",
"get_user",
"(",
"self",
",",
"username",
"=",
"None",
")",
":",
"username",
"=",
"username",
"or",
"self",
".",
"username",
"or",
"''",
"url",
"=",
"self",
".",
"url",
"(",
"'GET_USER'",
",",
"username",
"=",
"username",
")",
"response",
"=",
... | Returns user informations.
If username is not defined, tries to return own informations. | [
"Returns",
"user",
"informations",
".",
"If",
"username",
"is",
"not",
"defined",
"tries",
"to",
"return",
"own",
"informations",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/bitbucket.py#L262-L273 | train | 39,195 |
Sheeprider/BitBucket-api | bitbucket/bitbucket.py | Bitbucket.get_tags | def get_tags(self, repo_slug=None):
""" Get a single repository on Bitbucket and return its tags."""
repo_slug = repo_slug or self.repo_slug or ''
url = self.url('GET_TAGS', username=self.username, repo_slug=repo_slug)
return self.dispatch('GET', url, auth=self.auth) | python | def get_tags(self, repo_slug=None):
""" Get a single repository on Bitbucket and return its tags."""
repo_slug = repo_slug or self.repo_slug or ''
url = self.url('GET_TAGS', username=self.username, repo_slug=repo_slug)
return self.dispatch('GET', url, auth=self.auth) | [
"def",
"get_tags",
"(",
"self",
",",
"repo_slug",
"=",
"None",
")",
":",
"repo_slug",
"=",
"repo_slug",
"or",
"self",
".",
"repo_slug",
"or",
"''",
"url",
"=",
"self",
".",
"url",
"(",
"'GET_TAGS'",
",",
"username",
"=",
"self",
".",
"username",
",",
... | Get a single repository on Bitbucket and return its tags. | [
"Get",
"a",
"single",
"repository",
"on",
"Bitbucket",
"and",
"return",
"its",
"tags",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/bitbucket.py#L275-L279 | train | 39,196 |
Sheeprider/BitBucket-api | bitbucket/bitbucket.py | Bitbucket.get_branches | def get_branches(self, repo_slug=None):
""" Get a single repository on Bitbucket and return its branches."""
repo_slug = repo_slug or self.repo_slug or ''
url = self.url('GET_BRANCHES',
username=self.username,
repo_slug=repo_slug)
return self.dispatch('GET', url, auth=self.auth) | python | def get_branches(self, repo_slug=None):
""" Get a single repository on Bitbucket and return its branches."""
repo_slug = repo_slug or self.repo_slug or ''
url = self.url('GET_BRANCHES',
username=self.username,
repo_slug=repo_slug)
return self.dispatch('GET', url, auth=self.auth) | [
"def",
"get_branches",
"(",
"self",
",",
"repo_slug",
"=",
"None",
")",
":",
"repo_slug",
"=",
"repo_slug",
"or",
"self",
".",
"repo_slug",
"or",
"''",
"url",
"=",
"self",
".",
"url",
"(",
"'GET_BRANCHES'",
",",
"username",
"=",
"self",
".",
"username",
... | Get a single repository on Bitbucket and return its branches. | [
"Get",
"a",
"single",
"repository",
"on",
"Bitbucket",
"and",
"return",
"its",
"branches",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/bitbucket.py#L281-L287 | train | 39,197 |
Sheeprider/BitBucket-api | bitbucket/bitbucket.py | Bitbucket.get_privileges | def get_privileges(self):
""" Get privledges for this user. """
url = self.url('GET_USER_PRIVILEGES')
return self.dispatch('GET', url, auth=self.auth) | python | def get_privileges(self):
""" Get privledges for this user. """
url = self.url('GET_USER_PRIVILEGES')
return self.dispatch('GET', url, auth=self.auth) | [
"def",
"get_privileges",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"url",
"(",
"'GET_USER_PRIVILEGES'",
")",
"return",
"self",
".",
"dispatch",
"(",
"'GET'",
",",
"url",
",",
"auth",
"=",
"self",
".",
"auth",
")"
] | Get privledges for this user. | [
"Get",
"privledges",
"for",
"this",
"user",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/bitbucket.py#L289-L292 | train | 39,198 |
Sheeprider/BitBucket-api | bitbucket/deploy_key.py | DeployKey.create | def create(self, repo_slug=None, key=None, label=None):
""" Associate an ssh key with your repo and return it.
"""
key = '%s' % key
repo_slug = repo_slug or self.bitbucket.repo_slug or ''
url = self.bitbucket.url('SET_DEPLOY_KEY',
username=self.bitbucket.username,
repo_slug=repo_slug)
return self.bitbucket.dispatch('POST',
url,
auth=self.bitbucket.auth,
key=key,
label=label) | python | def create(self, repo_slug=None, key=None, label=None):
""" Associate an ssh key with your repo and return it.
"""
key = '%s' % key
repo_slug = repo_slug or self.bitbucket.repo_slug or ''
url = self.bitbucket.url('SET_DEPLOY_KEY',
username=self.bitbucket.username,
repo_slug=repo_slug)
return self.bitbucket.dispatch('POST',
url,
auth=self.bitbucket.auth,
key=key,
label=label) | [
"def",
"create",
"(",
"self",
",",
"repo_slug",
"=",
"None",
",",
"key",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"key",
"=",
"'%s'",
"%",
"key",
"repo_slug",
"=",
"repo_slug",
"or",
"self",
".",
"bitbucket",
".",
"repo_slug",
"or",
"''",
... | Associate an ssh key with your repo and return it. | [
"Associate",
"an",
"ssh",
"key",
"with",
"your",
"repo",
"and",
"return",
"it",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/deploy_key.py#L37-L49 | train | 39,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.