code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
resource = None
try:
resource = boto3.resource(
'ec2',
aws_access_key_id=self.access_key_id,
aws_secret_access_key=self.secret_access_key,
region_name=self.region
)
# boto3 resource is lazy so attempt method to test connection
resource.meta.client.describe_account_attributes()
except Exception:
raise EC2CloudException(
'Could not connect to region: %s' % self.region
)
return resource | def _connect(self) | Connect to ec2 resource. | 3.304883 | 2.748324 | 1.202509 |
resource = self._connect()
try:
instance = resource.Instance(self.running_instance_id)
except Exception:
raise EC2CloudException(
'Instance with ID: {instance_id} not found.'.format(
instance_id=self.running_instance_id
)
)
return instance | def _get_instance(self) | Retrieve instance matching instance_id. | 4.427064 | 3.916251 | 1.130434 |
instance = self._get_instance()
state = None
try:
state = instance.state['Name']
except Exception:
raise EC2CloudException(
'Instance with id: {instance_id}, '
'cannot be found.'.format(
instance_id=self.running_instance_id
)
)
return state | def _get_instance_state(self) | Attempt to retrieve the state of the instance.
Raises:
EC2CloudException: If the instance cannot be found. | 4.302626 | 3.417498 | 1.258999 |
key = ipa_utils.generate_public_ssh_key(
self.ssh_private_key_file
).decode()
script = BASH_SSH_SCRIPT.format(user=self.ssh_user, key=key)
return script | def _get_user_data(self) | Return formatted bash script string.
The public ssh key is added by cloud init to the instance based on
the ssh user and private key file. | 7.505578 | 5.155507 | 1.455837 |
resource = self._connect()
instance_name = ipa_utils.generate_instance_name('ec2-ipa-test')
kwargs = {
'InstanceType': self.instance_type or EC2_DEFAULT_TYPE,
'ImageId': self.image_id,
'MaxCount': 1,
'MinCount': 1,
'TagSpecifications': [
{
'ResourceType': 'instance',
'Tags': [
{
'Key': 'Name',
'Value': instance_name
}
]
}
]
}
if self.zone:
kwargs['Placement'] = {'AvailabilityZone': self.zone}
if self.ssh_key_name:
kwargs['KeyName'] = self.ssh_key_name
else:
kwargs['UserData'] = self._get_user_data()
if self.subnet_id:
kwargs['SubnetId'] = self.subnet_id
if self.security_group_id:
kwargs['SecurityGroupIds'] = [self.security_group_id]
try:
instances = resource.create_instances(**kwargs)
except Exception as error:
raise EC2CloudException(
'Unable to create instance: {0}.'.format(error)
)
self.running_instance_id = instances[0].instance_id
self.logger.debug('ID of instance: %s' % self.running_instance_id)
self._wait_on_instance('running', self.timeout) | def _launch_instance(self) | Launch an instance of the given image. | 2.313399 | 2.246588 | 1.029739 |
instance = self._get_instance()
# ipv6
try:
ipv6 = instance.network_interfaces[0].ipv6_addresses[0]
except (IndexError, TypeError):
ipv6 = None
self.instance_ip = instance.public_ip_address or \
ipv6 or instance.private_ip_address
if not self.instance_ip:
raise EC2CloudException(
'IP address for instance cannot be found.'
) | def _set_instance_ip(self) | Retrieve instance ip and cache it.
Current preference is for public ipv4, ipv6 and private. | 3.472907 | 3.261425 | 1.064843 |
instance = self._get_instance()
instance.start()
self._wait_on_instance('running', self.timeout) | def _start_instance(self) | Start the instance. | 5.942444 | 4.991683 | 1.190469 |
instance = self._get_instance()
instance.stop()
self._wait_on_instance('stopped', self.timeout) | def _stop_instance(self) | Stop the instance. | 5.64002 | 5.136477 | 1.098033 |
signal.signal(signal.SIGINT, signal.SIG_IGN) #block ctrl-c
return _process_worker_base(call_queue, result_queue) | def _process_worker(call_queue, result_queue) | This worker is wrapped to block KeyboardInterrupt | 4.079707 | 3.746077 | 1.089061 |
if not self.init_system:
try:
out = ipa_utils.execute_ssh_command(
client,
'ps -p 1 -o comm='
)
except Exception as e:
raise IpaDistroException(
'An error occurred while retrieving'
' the distro init system: %s' % e
)
if out:
self.init_system = out.strip() | def _set_init_system(self, client) | Determine the init system of distribution. | 4.889578 | 4.308651 | 1.134828 |
out = ''
self._set_init_system(client)
if self.init_system == 'systemd':
try:
out += 'systemd-analyze:\n\n'
out += ipa_utils.execute_ssh_command(
client,
'systemd-analyze'
)
out += 'systemd-analyze blame:\n\n'
out += ipa_utils.execute_ssh_command(
client,
'systemd-analyze blame'
)
out += 'journalctl -b:\n\n'
out += ipa_utils.execute_ssh_command(
client,
'sudo journalctl -b'
)
except Exception as error:
out = 'Failed to collect VM info: {0}.'.format(error)
return out | def get_vm_info(self, client) | Return vm info. | 3.731211 | 3.617104 | 1.031547 |
install_cmd = "{sudo} '{install} {package}'".format(
sudo=self.get_sudo_exec_wrapper(),
install=self.get_install_cmd(),
package=package
)
try:
out = ipa_utils.execute_ssh_command(
client,
install_cmd
)
except Exception as error:
raise IpaDistroException(
'An error occurred installing package {package} '
'on instance: {error}'.format(
package=package,
error=error
)
)
else:
return out | def install_package(self, client, package) | Install package on instance. | 3.74966 | 3.517889 | 1.065884 |
self._set_init_system(client)
reboot_cmd = "{sudo} '{stop_ssh};{reboot}'".format(
sudo=self.get_sudo_exec_wrapper(),
stop_ssh=self.get_stop_ssh_service_cmd(),
reboot=self.get_reboot_cmd()
)
try:
ipa_utils.execute_ssh_command(
client,
reboot_cmd
)
except Exception as error:
raise IpaDistroException(
'An error occurred rebooting instance: %s' % error
)
ipa_utils.clear_cache() | def reboot(self, client) | Execute reboot command on instance. | 5.307778 | 4.906727 | 1.081735 |
update_cmd = "{sudo} '{refresh};{update}'".format(
sudo=self.get_sudo_exec_wrapper(),
refresh=self.get_refresh_repo_cmd(),
update=self.get_update_cmd()
)
out = ''
try:
out = ipa_utils.execute_ssh_command(
client,
update_cmd
)
except Exception as error:
raise IpaDistroException(
'An error occurred updating instance: %s' % error
)
return out | def update(self, client) | Execute update command on instance. | 5.235241 | 4.583457 | 1.142203 |
kwargs = {'content':content, 'includeCat':includeCat, 'excludeCat':excludeCat, 'minLength':minLength, 'longestOnly':longestOnly, 'includeAbbrev':includeAbbrev, 'includeAcronym':includeAcronym, 'includeNumbers':includeNumbers}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/annotations').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None | def annotate(self, content, includeCat=None, excludeCat=None, minLength=None, longestOnly=None, includeAbbrev=None, includeAcronym=None, includeNumbers=None, output='text/plain; charset=utf-8') | Annotate text from: /annotations
Arguments:
content: The content to annotate
includeCat: A set of categories to include
excludeCat: A set of categories to exclude
minLength: The minimum number of characters in annotated entities
longestOnly: Should only the longest entity be returned for an overlapping group
includeAbbrev: Should abbreviations be included
includeAcronym: Should acronyms be included
includeNumbers: Should numbers be included
outputs:
text/plain; charset=utf-8 | 3.132526 | 3.126155 | 1.002038 |
if id and id.startswith('http:'):
id = parse.quote(id, safe='')
kwargs = {'id':id, 'hint':hint, 'relationships':relationships, 'lbls':lbls, 'callback':callback}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('id', **kwargs)
url = self._basePath + ('/graph/reachablefrom/{id}').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'id'}
output = self._get('GET', url, requests_params, output)
return output if output else [] | def reachableFrom(self, id, hint=None, relationships=None, lbls=None, callback=None, output='application/json') | Get all the nodes reachable from a starting point, traversing the provided edges. from: /graph/reachablefrom/{id}
Arguments:
id: The type of the edge
hint: A label hint to find the start node.
relationships: A list of relationships to traverse, in order. Supports cypher
operations such as relA|relB or relA*.
lbls: A list of node labels to filter.
callback: Name of the JSONP callback ('fn' by default). Supplying this
parameter or requesting a javascript media type will cause a
JSONP response to be rendered.
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png | 3.493872 | 3.521107 | 0.992265 |
s, o = 'sub', 'obj'
if inverse:
s, o = o, s
for edge in edges:
if predicate is not None and edge['pred'] != predicate:
print('scoop!')
continue
if edge[s] == start:
yield edge
yield from Graph.ordered(edge[o], edges, predicate=predicate) | def ordered(start, edges, predicate=None, inverse=False) | Depth first edges from a SciGraph response. | 4.909447 | 4.825065 | 1.017488 |
def tcsort(item): # FIXME SUCH WOW SO INEFFICIENT O_O
return len(item[1]) + sum(tcsort(kv) for kv in item[1].items()) | get len of transitive closure assume type items is tree... | null | null | null | |
def get_first_branch(node):
if node not in pnames: # one way to hit a root
return []
if pnames[node]: # mmmm names
fp = pnames[node][0]
if cycle_check(node, fp, pnames):
fp = pnames[node][1] # if there are double cycles I WILL KILL FOR THE PLEASURE IF IT
print(fp)
return [fp] + get_first_branch(fp)
else:
return []
branch = get_first_branch(start)
for n in branch[::-1]:
tree = tree[n]
assert start in tree, "our start wasnt in the tree! OH NO!"
branch = [start] + branch
print('branch', branch)
return tree, branch | def get_node(start, tree, pnames) | for each parent find a single branch to root | 6.788252 | 6.341139 | 1.07051 |
# if it is a leaf or all childs are leaves as well
if child_name in lleaves: # if it has previously been identified as a leaf!
#print('MATERIALIZATION DETECTED! LOWER PARENT:',
#lleaves[child_name],'ZAPPING!:', child_name,
#'OF PARENT:', parent_name)
children.pop(child_name)
#print('cn', child_name, 'pn', parent_name, 'BOTTOM')
#else: # if it has NOT previously been identified as a leaf, add the parent!
#new_lleaves[child_name] = parent_name # pass it back up to nodes above
#print('cn', child_name, 'pn', parent_name)
#else: # it is a node but we want to dematerizlize them too!
lleaves[child_name] = parent_name
lleaves.update(new_lleaves)
return lleaves | def dematerialize(parent_name, parent_node): # FIXME we need to demat more than just leaves!
#FIXME still an issue: Fornix, Striatum, Diagonal Band
lleaves = {}
children = parent_node[parent_name]
if not children: # children could be empty ? i think this only happens @ root?
#print('at bottom', parent_name)
lleaves[parent_name] = None
return lleaves
children_ord = reversed(sorted(sorted(((k, v)
for k, v in children.items()),
key=alphasortkey),
#key=lambda a: f'{a[0]}'.split('>')[1] if '>' in f'{a[0]}' else f'a[0]'),
#key=lambda a: a[0].split('>') if '>' in a[0] else a[0]),
key=tcsort)) # make sure we hit deepest first
for child_name, _ in children_ord: # get list so we can go ahead and pop
#print(child_name)
new_lleaves = dematerialize(child_name, children)
if child_name == 'magnetic resonance imaging': # debugging failing demat
pass
#embed()
if child_name in new_lleaves or all(l in lleaves for l in new_lleaves) | Remove nodes higher in the tree that occur further down the
SAME branch. If they occur down OTHER branchs leave them alone.
NOTE: modifies in place! | 5.692432 | 5.947926 | 0.957045 |
for edge in json['edges']:
sub, obj = edge['sub'], edge['obj']
edge['sub'] = obj
edge['obj'] = sub
edge['pred'] += 'INVERTED' | def inv_edges(json) | Switch obj/sub for a set of edges (makes fixing known inverse edges MUCH easier) | 4.770781 | 4.611562 | 1.034526 |
with open(results_file, 'r') as results:
data = json.load(results)
return data | def collect_results(results_file) | Return the result (pass/fail) for json file. | 2.836802 | 2.523225 | 1.124276 |
''' GROUP BY is a shortcut to only getting the first in every list of group '''
if not self.terms.empty:
return self.terms
if self.from_backup:
self.terms = open_pickle(TERMS_BACKUP_PATH)
return self.terms
engine = create_engine(self.db_url)
data =
self.terms = pd.read_sql(data, engine)
create_pickle(self.terms, TERMS_BACKUP_PATH)
return self.terms | def get_terms(self) | GROUP BY is a shortcut to only getting the first in every list of group | 6.434583 | 3.991084 | 1.612239 |
''' Gets complete entity data like term/view '''
if not self.terms_complete.empty:
return self.terms_complete
if self.from_backup:
self.terms_complete = open_pickle(TERMS_COMPLETE_BACKUP_PATH)
return self.terms_complete
ilx2synonyms = self.get_ilx2synonyms()
ilx2existing_ids = self.get_ilx2existing_ids()
ilx2annotations = self.get_ilx2annotations()
ilx2superclass = self.get_ilx2superclass()
ilx_complete = []
header = ['Index'] + list(self.fetch_terms().columns)
for row in self.fetch_terms().itertuples():
row = {header[i]:val for i, val in enumerate(row)}
row['synonyms'] = ilx2synonyms.get(row['ilx'])
row['existing_ids'] = ilx2existing_ids[row['ilx']] # if breaks we have worse problems
row['annotations'] = ilx2annotations.get(row['ilx'])
row['superclass'] = ilx2superclass.get(row['ilx'])
ilx_complete.append(row)
terms_complete = pd.DataFrame(ilx_complete)
create_pickle(terms_complete, TERMS_COMPLETE_BACKUP_PATH)
return terms_complete | def get_terms_complete(self) -> pd.DataFrame | Gets complete entity data like term/view | 3.241587 | 2.923553 | 1.108784 |
''' clean: for list of literals only '''
ilx2superclass = defaultdict(list)
header = ['Index'] + list(self.fetch_superclasses().columns)
for row in self.fetch_superclasses().itertuples():
row = {header[i]:val for i, val in enumerate(row)}
if clean:
superclass = {
'tid': row['superclass_tid'],
'ilx': row['superclass_ilx'],
}
ilx2superclass[row['term_ilx']].append(superclass)
elif not clean:
ilx2superclass[row['term_ilx']].append(row)
return ilx2superclass | def get_ilx2superclass(self, clean:bool=True) | clean: for list of literals only | 3.629938 | 3.179181 | 1.141784 |
''' clean: for list of literals only '''
tid2annotations = defaultdict(list)
header = ['Index'] + list(self.fetch_annotations().columns)
for row in self.fetch_annotations().itertuples():
row = {header[i]:val for i, val in enumerate(row)}
if clean:
annotation = {
'tid': row['tid'],
'annotation_type_tid': row['annotation_type_tid'],
'value': row['value'],
'annotation_type_label': row['annotation_type_label'],
}
tid2annotations[row['tid']].append(annotation)
elif not clean:
tid2annotations[row['tid']].append(row)
return tid2annotations | def get_tid2annotations(self, clean:bool=True) | clean: for list of literals only | 3.238105 | 2.750432 | 1.177308 |
''' clean: for list of literals only '''
tid2synonyms = {}
header = ['Index'] + list(self.fetch_synonyms().columns)
for row in self.fetch_synonyms().itertuples():
row = {header[i]:val for i, val in enumerate(row)}
if clean:
synonym = {'literal':row['literal'], 'type':row['type']}
tid2synonyms[row['tid']].append(synonym)
elif not clean:
tid2synonyms[row['tid']].append(row)
return tid2synonyms | def get_tid2synonyms(self, clean:bool=True) | clean: for list of literals only | 3.841475 | 3.132792 | 1.226215 |
''' clean: for list of literals only '''
ilx2synonyms = defaultdict(list)
header = ['Index'] + list(self.fetch_synonyms().columns)
for row in self.fetch_synonyms().itertuples():
row = {header[i]:val for i, val in enumerate(row)}
if clean:
synonym = {'literal':row['literal'], 'type':row['type']}
ilx2synonyms[row['ilx']].append(synonym)
elif not clean:
ilx2synonyms[row['ilx']].append(row)
return ilx2synonyms | def get_ilx2synonyms(self, clean:bool=True) | clean: for list of literals only | 3.558276 | 3.036106 | 1.171987 |
''' PHP returns "id" in superclass but only accepts superclass_tid '''
for i, value in enumerate(data['superclasses']):
data['superclasses'][i]['superclass_tid'] = data['superclasses'][i].pop('id')
return data | def superclasses_bug_fix(data) | PHP returns "id" in superclass but only accepts superclass_tid | 8.02541 | 3.289733 | 2.439532 |
''' Logs successful responses '''
info = 'label={label}, id={id}, ilx={ilx}, superclass_tid={super_id}'
info_filled = info.format(label = data['label'],
id = data['id'],
ilx = data['ilx'],
super_id = data['superclasses'][0]['id'])
logging.info(info_filled)
return info_filled | def log_info(self, data) | Logs successful responses | 5.475176 | 5.433524 | 1.007666 |
''' Requests data from database '''
req = r.get(url,
headers = self.headers,
auth = self.auth)
return self.process_request(req) | def get(self, url) | Requests data from database | 6.76339 | 6.812026 | 0.99286 |
''' Gives data to database '''
data.update({'key': self.APIKEY})
req = r.post(url,
data = json.dumps(data),
headers = self.headers,
auth = self.auth)
return self.process_request(req) | def post(self, url, data) | Gives data to database | 5.449893 | 4.872972 | 1.118392 |
''' Checks to see if data returned from database is useable '''
# Check status code of request
req.raise_for_status() # if codes not in 200s; error raise
# Proper status code, but check if server returned a warning
try:
output = req.json()
except:
exit(req.text) # server returned html error
# Try to find an error msg in the server response
try:
error = output['data'].get('errormsg')
except:
error = output.get('errormsg') # server has 2 variations of errormsg
finally:
if error:
exit(error)
return output | def process_request(self, req) | Checks to see if data returned from database is useable | 9.120104 | 7.366402 | 1.238068 |
''' Simple string comparator '''
return string1.lower().strip() == string2.lower().strip() | def is_equal(self, string1, string2) | Simple string comparator | 6.734673 | 6.093557 | 1.105212 |
''' Gets full meta data (expect their annotations and relationships) from is ILX ID '''
ilx_id = self.fix_ilx(ilx_id)
url_base = self.base_path + "ilx/search/identifier/{identifier}?key={APIKEY}"
url = url_base.format(identifier=ilx_id, APIKEY=self.APIKEY)
output = self.get(url)
# Can be a successful request, but not a successful response
success = self.check_success(output)
return output, success | def get_data_from_ilx(self, ilx_id) | Gets full meta data (expect their annotations and relationships) from is ILX ID | 7.371988 | 4.299017 | 1.714808 |
''' Server returns anything that is simlar in any catagory '''
url_base = self.base_path + 'term/search/{term}?key={api_key}'
url = url_base.format(term=label, api_key=self.APIKEY)
return self.get(url) | def search_by_label(self, label) | Server returns anything that is simlar in any catagory | 8.673206 | 4.267039 | 2.032605 |
''' Checks list of objects to see if they are usable ILX IDs '''
total_data = []
for ilx_id in ilx_ids:
ilx_id = ilx_id.replace('http', '').replace('.', '').replace('/', '')
data, success = self.get_data_from_ilx(ilx_id)
if success:
total_data.append(data['data'])
else:
total_data.append({})
return total_data | def are_ilx(self, ilx_ids) | Checks list of objects to see if they are usable ILX IDs | 3.66878 | 2.892338 | 1.268448 |
''' Adds an entity property to an existing entity '''
subj_data, pred_data, obj_data = self.are_ilx([subj, pred, obj])
# RELATIONSHIP PROPERTY
if subj_data.get('id') and pred_data.get('id') and obj_data.get('id'):
if pred_data['type'] != 'relationship':
return self.test_check('Adding a relationship as formate \
"term1_ilx relationship_ilx term2_ilx"')
return self.add_relationship(term1=subj_data,
relationship=pred_data,
term2=obj_data)
# ANNOTATION PROPERTY
elif subj_data.get('id') and pred_data.get('id'):
if pred_data['type'] != 'annotation':
return self.test_check('Adding a relationship as formate \
"term_ilx annotation_ilx value"')
return self.add_annotation(entity=subj_data,
annotation=pred_data,
value=obj)
# UPDATE ENTITY
elif subj_data.get('id'):
data = subj_data
_pred = self.ttl2sci_map.get(pred)
if not _pred:
error = pred + " doesnt not have correct RDF format or It is not an option"
return self.test_check(error)
data = self.custom_update(data, _pred, obj)
if data == 'failed': # for debugging custom_update
return data
data = superclasses_bug_fix(data)
url_base = self.base_path + 'term/edit/{id}'
url = url_base.format(id=data['id'])
return self.post(url, data)
else:
return self.test_check('The ILX ID(s) provided do not exist') | def add_triple(self, subj, pred, obj) | Adds an entity property to an existing entity | 4.643761 | 4.535991 | 1.023759 |
''' Creates a relationship between 3 entities in database '''
url = self.base_path + 'term/add-relationship'
data = {'term1_id': term1['id'],
'relationship_tid': relationship['id'],
'term2_id': term2['id'],
'term1_version': term1['version'],
'relationship_term_version': relationship['version'],
'term2_version': term2['version']}
return self.post(url, data) | def add_relationship(self, term1, relationship, term2) | Creates a relationship between 3 entities in database | 3.280523 | 2.864052 | 1.145413 |
''' Adds an annotation proprty to existing entity '''
url = self.base_path + 'term/add-annotation'
data = {'tid': entity['id'],
'annotation_tid': annotation['id'],
'value': value,
'term_version': entity['version'],
'annotation_term_version': annotation['version']}
return self.post(url, data) | def add_annotation(self, entity, annotation, value) | Adds an annotation proprty to existing entity | 5.263398 | 4.507786 | 1.167624 |
''' Updates existing entity proprty based on the predicate input '''
if isinstance(data[pred], str): # for all simple properties of str value
data[pred] = str(obj)
else: # synonyms, superclasses, and existing_ids have special requirements
if pred == 'synonyms':
literals = [d['literal'] for d in data[pred]]
if obj not in literals:
data[pred].append({'literal': obj}) # synonyms req for post
elif pred == 'superclasses':
ilx_ids = [d['ilx'] for d in data[pred]]
if obj not in ilx_ids:
_obj = obj.replace('ILX:', 'ilx_')
super_data, success = self.get_data_from_ilx(ilx_id=_obj)
super_data = super_data['data']
if success:
# superclass req post
data[pred].append({'id': super_data['id'], 'ilx': _obj})
else:
return self.test_check('Your superclass ILX ID '
+ _obj + ' does not exist.')
elif pred == 'existing_ids': # FIXME need to autogenerate curies from a map
iris = [d['iri'] for d in data[pred]]
if obj not in iris:
if 'http' not in obj:
return self.test_check('exisiting id value must \
be a uri containing "http"')
data[pred].append({
'curie': self.qname(obj),
'iri': obj,
'preferred': '0' # preferred is auto generated by preferred_change
})
#data[pred] = []
data = self.preferred_change(data) # One ex id is determined to be preferred
else:
# Somehow broke this code
return self.test_check(pred + ' Has slipped through the cracks')
return data | def custom_update(self, data, pred, obj) | Updates existing entity proprty based on the predicate input | 6.573155 | 6.12357 | 1.073419 |
objects.sort(key=self._globalSortKey)
# Make sorted list of properties
return sorted(properties, key=lambda p: self.predicate_rank[p]) | def sortProperties(self, properties): # modified to sort objects using their global rank
# Sort object lists
for prop, objects in properties.items() | Take a hash from predicate uris to lists of values.
Sort the lists of values. Return a sorted list of properties. | 9.996967 | 7.078915 | 1.412217 |
oList = properties.get(p, [])
oList.append(o)
properties[p] = oList
return properties | def _buildPredicateHash(self, subject): # XXX unmodified
properties = {}
for s, p, o in self.store.triples((subject, None, None)) | Build a hash key by predicate to a list of objects for the given
subject | 5.885761 | 4.171824 | 1.410836 |
if self.store.value(l, RDF.first) is None:
return False
except:
return False
while l:
if l != RDF.nil:
po = list(self.store.predicate_objects(l))
if (RDF.type, RDF.List) in po and len(po) == 3:
pass
elif len(po) != 2:
return False
l = self.store.value(l, RDF.rest)
return True | def isValidList(self, l): # modified to flatten lists specified using [ a rdf:List; ] syntax
try | Checks if l is a valid RDF list, i.e. no nodes have other properties. | 3.224603 | 3.1053 | 1.038419 |
if ' ' in value:
s = inspect.stack()
fn = s[1].function
super().write('%%DEBUG {} %%'.format(fn))
super().write(value) | def _write(self, value) | rename to write and import inspect to debut the callstack | 10.782966 | 8.279716 | 1.302335 |
if 'labels' in kwargs:
# populate labels from outside the local graph
self._labels.update(kwargs['labels'])
super(HtmlTurtleSerializer, self).serialize(*args, **kwargs) | def serialize(self, *args, **kwargs) | Modified to allow additional labels to be passed in. | 10.916751 | 8.075219 | 1.351883 |
ok = False
for s in stack[1:]:
cc = s.code_context[0]
if 'class' in cc:
if '(' in cc:
bases = [b.strip() for b in cc.split('(')[1].split(')')[0].split(',')]
for base_name in bases:
if base_name in s.frame.f_globals:
base = s.frame.f_globals[base_name]
for cls in base.__class__.mro(base):
if cls.__name__ == classname:
ok = True
break
if ok:
break
if ok:
break
if not ok:
name = stack[0].function
raise SyntaxError('%s not called inside a class inheriting from LocalNameManager' % name) | def checkCalledInside(classname, stack) | Fantastically inefficient! | 3.11501 | 3.079175 | 1.011638 |
s = inspect.stack(0) # horribly inefficient
checkCalledInside('LocalNameManager', s)
g = s[1][0].f_locals # get globals of calling scope
addLN(LocalName, Phenotype(phenoId, predicate), g) | def addLNT(LocalName, phenoId, predicate, g=None): # XXX deprecated
if g is None | Add a local name for a phenotype from a pair of identifiers | 15.674533 | 13.244658 | 1.183461 |
if g is None:
g = inspect.stack(0)[1][0].f_locals # get globals of calling scope
for k in list(graphBase.LocalNames.keys()):
try:
g.pop(k)
except KeyError:
raise KeyError('%s not in globals, are you calling resetLocalNames from a local scope?' % k)
graphBase.LocalNames.pop(k) | def resetLocalNames(g=None) | WARNING: Only call from top level! THIS DOES NOT RESET NAMES in an embeded IPython!!!
Remove any local names that have already been defined. | 4.888671 | 4.880222 | 1.001731 |
from pyontutils.closed_namespaces import rdfs
# bag existing
try:
next(iter(self.neurons()))
raise self.ExistingNeuronsError('Existing neurons detected. Please '
'load from file before creating neurons!')
except StopIteration:
pass
def getClassType(s):
graph = self.load_graph
Class = infixowl.Class(s, graph=graph)
for ec in Class.equivalentClass:
if isinstance(ec.identifier, rdflib.BNode):
bc = infixowl.CastClass(ec, graph=graph)
if isinstance(bc, infixowl.BooleanClass):
for id_ in bc._rdfList:
if isinstance(id_, rdflib.URIRef):
yield id_ # its one of our types
# bug is that I am not wiping graphBase.knownClasses and swapping it for each config
# OR the bug is that self.load_graph is persisting, either way the call to type()
# below seems to be the primary suspect for the issue
if not graphBase.ignore_existing:
ogp = Path(graphBase.ng.filename) # FIXME ng.filename <-> out_graph_path property ...
if ogp.exists():
from itertools import chain
from rdflib import Graph # FIXME
self.load_graph = Graph().parse(graphBase.ng.filename, format='turtle')
graphBase.load_graph = self.load_graph
# FIXME memory inefficiency here ...
_ = [graphBase.in_graph.add(t) for t in graphBase.load_graph] # FIXME use conjuctive ...
if len(graphBase.python_subclasses) == 2: # FIXME magic number for Neuron and NeuronCUT
ebms = [type(OntId(s).suffix, (NeuronCUT,), dict(owlClass=s))
for s in self.load_graph[:rdfs.subClassOf:NeuronEBM.owlClass]
if not graphBase.knownClasses.append(s)]
else:
ebms = []
class_types = [(type, s) for s in self.load_graph[:rdf.type:owl.Class]
for type in getClassType(s) if type]
sc = None
for sc in chain(graphBase.python_subclasses, ebms):
sc.owlClass
iris = [s for type, s in class_types if type == sc.owlClass]
if iris:
sc._load_existing(iris)
if sc is None:
raise ImportError(f'Failed to find any neurons to load in {graphBase.ng.filename}') | def load_existing(self) | advanced usage allows loading multiple sets of neurons and using a config
object to keep track of the different graphs | 7.690889 | 7.673561 | 1.002258 |
out = '#!/usr/bin/env python3.6\n'
out += f'from {cls.__import_name__} import *\n\n'
all_types = set(type(n) for n in cls.neurons())
_subs = [inspect.getsource(c) for c in subclasses(Neuron)
if c in all_types and Path(inspect.getfile(c)).exists()]
subs = '\n' + '\n\n'.join(_subs) + '\n\n' if _subs else ''
#log.debug(str(all_types))
#log.debug(f'python header for {cls.filename_python()}:\n{subs}')
out += subs
ind = '\n' + ' ' * len('config = Config(')
_prefixes = {k:str(v) for k, v in cls.ng.namespaces.items()
if k not in uPREFIXES and k != 'xml' and k != 'xsd'} # FIXME don't hardcode xml xsd
len_thing = len(f'config = Config({cls.ng.name!r}, prefixes={{')
'}}'
prefixes = (f',{ind}prefixes={pformat(_prefixes, 0)}'.replace('\n', '\n' + ' ' * len_thing)
if _prefixes
else '')
tel = ttl_export_dir = Path(cls.ng.filename).parent.as_posix()
ttlexp = f',{ind}ttl_export_dir={tel!r}'
# FIXME prefixes should be separate so they are accessible in the namespace
# FIXME ilxtr needs to be detected as well
# FIXME this doesn't trigger when run as an import?
out += f'config = Config({cls.ng.name!r},{ind}file=__file__{ttlexp}{prefixes})\n\n' # FIXME this is from neurons.lang
return out | def python_header(cls) | }} | 7.130882 | 7.1444 | 0.998108 |
# FIXME this makes the data model mutable!
# TODO symmetry here
# serious modelling issue
# If you make two bags equivalent to eachother
# then in the set theory model it becomes impossible
# to have a set that is _just_ one or the other of the bags
# which I do not think that we want
for other in others:
if isinstance(other, self.__class__):
#if isinstance(other, NegPhenotype): # FIXME maybe this is the issue with neg equivs?
otherid = other.id_
else:
otherid = other
self.out_graph.add((self.id_, owl.equivalentClass, otherid))
self._equivalent_bags_ids.add(otherid)
return self | def equivalentClass(self, *others) | as implemented this acts as a permenant bag union operator
and therefore should be used with extreme caution since
in any given context the computed label/identifier will
no longer reflect the entailed/reasoned bag
In a static context this means that we might want to have
an ilxtr:assertedAlwaysImplies -> bag union neuron | 11.616308 | 10.365663 | 1.120653 |
if (not hasattr(graphBase, '_label_maker') or
graphBase._label_maker.local_conventions != graphBase.local_conventions):
graphBase._label_maker = LabelMaker(graphBase.local_conventions)
return graphBase._label_maker | def label_maker(self) | needed to defer loading of local conventions to avoid circular dependency issue | 4.61028 | 3.376698 | 1.365322 |
graph = self.out_graph
################## LABELS ARE DEFINED HERE ##################
gl = self.genLabel
ll = self.localLabel
ol = self.origLabel
graph.add((self.id_, ilxtr.genLabel, rdflib.Literal(gl)))
if ll != gl:
graph.add((self.id_, ilxtr.localLabel, rdflib.Literal(ll)))
if ol and ol != gl:
graph.add((self.id_, ilxtr.origLabel, rdflib.Literal(ol)))
members = [self.expand(self.owlClass)]
for pe in self.pes:
target = pe._graphify(graph=graph)
if isinstance(pe, NegPhenotype): # isinstance will match NegPhenotype -> Phenotype
#self.Class.disjointWith = [target] # FIXME for defined neurons this is what we need and I think it is strong than the complementOf version
djc = infixowl.Class(graph=graph) # TODO for generic neurons this is what we need
djc.complementOf = target
members.append(djc)
else:
members.append(target) # FIXME negative logical phenotypes :/
intersection = infixowl.BooleanClass(members=members, graph=graph) # FIXME dupes
#existing = list(self.Class.equivalentClass)
#if existing or str(pe.pLabel) == 'Htr3a':
#embed()
ec = [intersection]
self.Class.equivalentClass = ec
return self.Class | def _graphify(self, *args, graph=None): # defined
if graph is None | Lift phenotypeEdges to Restrictions | 8.303135 | 7.777975 | 1.067519 |
if args['--debug']:
print(args)
# ignoring bamboo sequecing for the moment...
# check the build server to see if we have built the latest (or the specified commit)
# if yes just scp those to services
# if no check the web endpoint to see if latest matches build
# if yes fetch
# else build (push to web endpoint)
'localhost:~/files/ontology-packages/scigraph/'
'tom@orpheus:~/files/ontology-packages/graph/'
#b = Builder(build_host, services_host, build_user, services_user,
#graph_latest_url, scigraph_latest_url,
#scp, sscp, git_local, repo_name,
#services_folder, graph_folder, services_config_folder
#)
kwargs = {k.strip('--').strip('<').rstrip('>').replace('-','_'):v for k, v in args.items()}
b = Builder(args, **kwargs)
if b.mode is not None:
code = b.run()
else:
if args['--view-defaults']:
for k, v in combined_defaults.items():
print(f'{k:<22} {v}')
return
if b.debug:
FILE = '/tmp/test.sh'
with open(FILE, 'wt') as f:
f.write('#!/usr/bin/env bash\n' + code)
os.system(f"emacs -batch {FILE} --eval '(indent-region (point-min) (point-max) nil)' -f save-buffer")
print()
with open(FILE, 'rt') as f:
print(f.read())
#embed()
if b.local:
return
#if b.check_built:
#return
else:
print(code) | def run(args) | localhost:~/files/ontology-packages/scigraph/ | 9.728036 | 8.935961 | 1.088639 |
return self.makeOutput(EXE, commands, oper=oper, defer_shell_expansion=defer_shell_expansion) | def runOnExecutor(self, *commands, oper=ACCEPT, defer_shell_expansion=False) | This runs in the executor of the current scope.
You cannot magically back out since there are no
gurantees that ssh keys will be in place (they shouldn't be). | 6.097249 | 6.253122 | 0.975073 |
kwargs = {}
if not self.build_only: # don't try to deploy twice
kwargs[' --build-only'] = True
if not self.local:
kwargs['--local'] = True
if check:
kwargs['--check-built'] = True
remote_args = self.formatted_args(self.args, mode, **kwargs)
cmds = tuple() if self.check_built or self._updated else self.cmds_pyontutils()
if not self._updated:
self._updated = True
return self.runOnBuild(*cmds,
f'scigraph-deploy {remote_args}',
defer_shell_expansion=True,
oper=AND) | def build(self, mode=None, check=False) | Just shuffle the current call off to the build server with --local attached | 10.638346 | 9.639223 | 1.103652 |
if working_dir is None:
return Path(failover, pathstring).resolve()
else:
return Path(devconfig.resources, pathstring).resolve().relative_to(working_dir.resolve()) | def relative_resources(pathstring, failover='nifstd/resources') | relative paths to resources in this repository
`failover` matches the location relative to the
github location (usually for prov purposes) | 5.70736 | 6.513079 | 0.876292 |
tail = lambda:tuple()
lonts = len(onts)
if lonts > 1:
for i, ont in enumerate(onts):
if ont.__name__ == 'parcBridge':
onts = onts[:-1]
def tail(o=ont):
return o.setup(),
if i != lonts - 1:
raise ValueError('parcBridge should be built last to avoid weird errors!')
# ont_setup must be run first on all ontologies
# or we will get weird import errors
if n_jobs == 1 or True:
return tuple(ont.make(fail=fail, write=write) for ont in
tuple(ont.setup() for ont in onts) + tail())
# have to use a listcomp so that all calls to setup()
# finish before parallel goes to work
return Parallel(n_jobs=n_jobs)(delayed(o.make)(fail=fail, write=write)
for o in
#[ont_setup(ont) for ont in onts])
(tuple(Async()(deferred(ont.setup)()
for ont in onts)) + tail()
if n_jobs > 1
else [ont.setup()
for ont in onts])) | def build(*onts, fail=False, n_jobs=9, write=True) | Set n_jobs=1 for debug or embed() will crash. | 6.770279 | 6.675644 | 1.014176 |
if warning:
print(tc.red('WARNING:'), tc.yellow(f'qname({uri}) is deprecated! please use OntId({uri}).curie'))
return __helper_graph.qname(uri) | def qname(uri, warning=False) | compute qname from defaults | 11.458641 | 10.856349 | 1.055478 |
prefs = ['']
if keep:
prefixes.update({p:str(n) for p, n in graph.namespaces()})
if '' not in prefixes:
prefixes[''] = null_prefix # null prefix
pi = {v:k for k, v in prefixes.items()}
asdf = {} #{v:k for k, v in ps.items()}
asdf.update(pi)
# determine which prefixes we need
for uri in set((e for t in graph for e in t)):
if uri.endswith('.owl') or uri.endswith('.ttl') or uri.endswith('$$ID$$'):
continue # don't prefix imports or templates
for rn, rp in sorted(asdf.items(), key=lambda a: -len(a[0])): # make sure we get longest first
lrn = len(rn)
if type(uri) == rdflib.BNode:
continue
elif uri.startswith(rn) and '#' not in uri[lrn:] and '/' not in uri[lrn:]: # prevent prefixing when there is another sep
prefs.append(rp)
break
ps = {p:prefixes[p] for p in prefs}
cleanup(ps, graph)
ng = makeGraph('', prefixes=ps)
[ng.g.add(t) for t in graph]
return ng | def cull_prefixes(graph, prefixes={k:v for k, v in uPREFIXES.items() if k != 'NIFTTL'},
cleanup=lambda ps, graph: None, keep=False) | Remove unused curie prefixes and normalize to a standard set. | 5.401805 | 5.40943 | 0.99859 |
[print(*(e[:5]
if isinstance(e, rdflib.BNode) else
qname(e)
for e in t), '.')
for t in sorted(triples)] | def displayTriples(triples, qname=qname) | triples can also be an rdflib Graph instance | 9.841827 | 9.578059 | 1.027539 |
if cull:
cull_prefixes(self).write()
else:
ser = self.g.serialize(format='nifttl')
with open(self.filename, 'wb') as f:
f.write(ser) | def write(self, cull=False) | Serialize self.g and write to self.filename, set cull to true to remove unwanted prefixes | 7.457857 | 4.653522 | 1.602626 |
self.add_trip(id_, rdf.type, owl.AnnotationProperty)
if label:
self.add_trip(id_, rdfs.label, label)
if addPrefix:
prefix = ''.join([s.capitalize() for s in label.split()])
namespace = self.expand(id_)
self.add_namespace(prefix, namespace) | def add_ap(self, id_, label=None, addPrefix=True) | Add id_ as an owl:AnnotationProperty | 3.506239 | 2.899676 | 1.209183 |
self.add_trip(id_, rdf.type, owl.ObjectProperty)
if inverse:
self.add_trip(id_, owl.inverseOf, inverse)
if subPropertyOf:
self.add_trip(id_, rdfs.subPropertyOf, subPropertyOf)
if label:
self.add_trip(id_, rdfs.label, label)
if addPrefix:
prefix = ''.join([s.capitalize() for s in label.split()])
namespace = self.expand(id_)
self.add_namespace(prefix, namespace)
if transitive:
self.add_trip(id_, rdf.type, owl.TransitiveProperty) | def add_op(self, id_, label=None, subPropertyOf=None, inverse=None, transitive=False, addPrefix=True) | Add id_ as an owl:ObjectProperty | 2.005208 | 1.952195 | 1.027156 |
parent = self.check_thing(parent)
if type(edge) != rdflib.URIRef:
edge = self.check_thing(edge)
if type(child) != infixowl.Class:
if type(child) != rdflib.URIRef:
child = self.check_thing(child)
child = infixowl.Class(child, graph=self.g)
restriction = infixowl.Restriction(edge, graph=self.g, someValuesFrom=parent)
child.subClassOf = [restriction] + [c for c in child.subClassOf] | def add_hierarchy(self, parent, edge, child): # XXX DEPRECATED
if type(parent) != rdflib.URIRef | Helper function to simplify the addition of part_of style
objectProperties to graphs. FIXME make a method of makeGraph? | 3.558619 | 3.106188 | 1.145655 |
if type(object_) != rdflib.URIRef:
object_ = self.check_thing(object_)
if type(predicate) != rdflib.URIRef:
predicate = self.check_thing(predicate)
if type(subject) != infixowl.Class:
if type(subject) != rdflib.URIRef:
subject = self.check_thing(subject)
subject = infixowl.Class(subject, graph=self.g)
restriction = infixowl.Restriction(predicate, graph=self.g, someValuesFrom=object_)
subject.subClassOf = [restriction] + [c for c in subject.subClassOf] | def add_restriction(self, subject, predicate, object_) | Lift normal triples into restrictions using someValuesFrom. | 2.853389 | 2.65795 | 1.07353 |
start = self.qname(self.expand(curie)) # in case something is misaligned
qstring = % start
return [_ for (_,) in self.g.query(qstring)] | def get_equiv_inter(self, curie) | get equivelant classes where curie is in an intersection | 25.434183 | 22.524042 | 1.129202 |
try:
prefix, namespace, name = self.g.namespace_manager.compute_qname(uri, generate=generate)
qname = ':'.join((prefix, name))
return qname
except (KeyError, ValueError) as e:
return uri.toPython() if isinstance(uri, rdflib.URIRef) else uri | def qname(self, uri, generate=False) | Given a uri return the qname if it exists, otherwise return the uri. | 3.241003 | 3.007357 | 1.077691 |
log_src, description = split_history_item(item.strip())
# Get relative path for log:
# {provider}/{image}/{instance}/{timestamp}.log
log_dest = os.path.sep.join(log_src.rsplit(os.path.sep, 4)[1:])
# Get results src and destination based on log paths.
results_src = log_src.rsplit('.', 1)[0] + '.results'
results_dest = log_dest.rsplit('.', 1)[0] + '.results'
destination_path = os.path.join(destination, log_dest)
log_dir = os.path.dirname(destination_path)
try:
if not os.path.isdir(log_dir):
os.makedirs(log_dir)
# Copy results and log files to archive directory.
shutil.copyfile(log_src, destination_path)
shutil.copyfile(results_src, os.path.join(destination, results_dest))
except Exception as error:
echo_style(
'Unable to archive history item: %s' % error,
no_color,
fg='red'
)
sys.exit(1)
else:
# Only update the archive results log if no error occur.
update_history_log(
os.path.join(destination, '.history'),
description=description,
test_log=log_dest
) | def archive_history_item(item, destination, no_color) | Archive the log and results file for the given history item.
Copy the files and update the results file in destination directory. | 3.501055 | 3.328767 | 1.051757 |
try:
summary = data['summary']
except KeyError as error:
click.secho(
'The results json is missing key: %s' % error,
fg='red'
)
sys.exit(1)
if 'failed' in summary or 'error' in summary:
fg = 'red'
status = 'FAILED'
else:
fg = 'green'
status = 'PASSED'
results = '{} tests={}|pass={}|skip={}|fail={}|error={}'.format(
status,
str(summary.get('num_tests', 0)),
str(summary.get('passed', 0)),
str(summary.get('skipped', 0)),
str(summary.get('failed', 0)),
str(summary.get('error', 0))
)
echo_style(results, no_color, fg=fg)
if verbose:
echo_verbose_results(data, no_color) | def echo_results(data, no_color, verbose=False) | Print test results in nagios style format. | 2.610059 | 2.684929 | 0.972115 |
try:
data = collect_results(results_file)
except ValueError:
echo_style(
'The results file is not the proper json format.',
no_color,
fg='red'
)
sys.exit(1)
except Exception as error:
echo_style(
'Unable to process results file: %s' % error,
no_color,
fg='red'
)
sys.exit(1)
echo_results(data, no_color, verbose) | def echo_results_file(results_file, no_color, verbose=False) | Print test results in nagios style format. | 2.860325 | 2.980286 | 0.959748 |
click.echo()
click.echo(
'\n'.join(
'{}: {}'.format(key, val) for key, val in data['info'].items()
)
)
click.echo()
for test in data['tests']:
if test['outcome'] == 'passed':
fg = 'green'
elif test['outcome'] == 'skipped':
fg = 'yellow'
else:
fg = 'red'
name = parse_test_name(test['name'])
echo_style(
'{} {}'.format(name, test['outcome'].upper()),
no_color,
fg=fg
) | def echo_verbose_results(data, no_color) | Print list of tests and result of each test. | 2.671283 | 2.61565 | 1.021269 |
try:
log_file, description = shlex.split(history)
except ValueError:
log_file = history.strip()
return log_file | def get_log_file_from_item(history) | Return the log file based on provided history item.
Description is optional. | 5.474071 | 4.862839 | 1.125694 |
try:
with open(history_log, 'r') as f:
lines = f.readlines()
except Exception as error:
echo_style(
'Unable to process results history log: %s' % error,
no_color,
fg='red'
)
sys.exit(1)
index = len(lines)
for item in lines:
click.echo('{} {}'.format(index, item), nl=False)
index -= 1 | def results_history(history_log, no_color) | Display a list of ipa test results history. | 3.355162 | 3.395725 | 0.988055 |
try:
log_file, description = shlex.split(history)
except ValueError:
log_file = history.strip()
description = None
return log_file, description | def split_history_item(history) | Return the log file and optional description for item. | 5.004245 | 2.9829 | 1.677644 |
start = Path(script__file__).resolve()
_root = Path(start.root)
working_dir = start
while not list(working_dir.glob('.git')):
if working_dir == _root:
return
working_dir = working_dir.parent
return working_dir | def get_working_dir(script__file__) | hardcoded sets the 'equivalent' working directory if not in git | 4.087988 | 4.044193 | 1.010829 |
# in the event we have to make our own
# this should not be passed in a as a parameter
# since we need these definitions to be more or less static
failover = Path('/tmp/machine-id')
if not ignore_options:
options = (
Path('/etc/machine-id'),
failover, # always read to see if we somehow managed to persist this
)
for option in options:
if (option.exists() and
os.access(option, os.R_OK) and
option.stat().st_size > 0):
return option
uuid = uuid4()
with open(failover, 'wt') as f:
f.write(uuid.hex)
return failover | def sysidpath(ignore_options=False) | get a unique identifier for the machine running this function | 6.755379 | 6.531277 | 1.034312 |
ll = len(list_)
if ll <= size:
return [list_]
elif size == 0:
return list_ # or None ??
elif size == 1:
return [[l] for l in list_]
else:
chunks = []
for start, stop in zip(range(0, ll, size), range(size, ll, size)):
chunks.append(list_[start:stop])
chunks.append(list_[stop:]) # snag unaligned chunks from last stop
return chunks | def chunk_list(list_, size) | Split a list list_ into sublists of length size.
NOTE: len(chunks[-1]) <= size. | 3.592469 | 3.60301 | 0.997074 |
{params_conditional}
kwargs = {param_rest}
kwargs = {dict_comp}
param_rest = self._make_rest({required}, **kwargs)
url = self._basePath + ('{path}').format(**kwargs)
requests_params = {dict_comp2}
output = self._get('{method}', url, requests_params, {output})
return output if output else {empty_return_type} | def NICKNAME(selfPARAMSDEFAULT_OUTPUT) | DOCSTRING | 13.099373 | 11.956133 | 1.09562 |
ledict = requests.get(self.api_url).json()
ledict = self.dotopdict(ledict)
out = self.dodict(ledict)
self._code = out | def gencode(self) | Run this to generate the code | 12.144098 | 10.898442 | 1.114297 |
mlookup = {'get':'GET', 'post':'POST'}
def rearrange(path, method_dict, method):
oid = method_dict['operationId']
self._paths[oid] = path
method_dict['nickname'] = oid
method_dict['method'] = mlookup[method]
paths = dict_['paths']
for path, path_dict in paths.items():
if self.path_prefix and self.path_prefix not in path:
continue
path_dict['operations'] = []
for method, method_dict in sorted(path_dict.items()):
if method == 'operations':
continue
rearrange(path, method_dict, method)
#print(self.operation(method_dict))
path_dict['operations'].append(method_dict)
path_dict['path'] = path
def setp(v, lenp=len(self.path_prefix)):
v['path'] = v['path'][lenp:]
return v
dict_['apis'] = []
for tag_dict in dict_['tags']:
path = '/' + tag_dict['name']
d = {'path':path,
'description':tag_dict['description'],
'class_json':{
'docstring':tag_dict['description'],
'resourcePath':path,
'apis':[setp(v) for k, v in paths.items()
if k.startswith(self.path_prefix + path)]},
}
dict_['apis'].append(d)
# make sure this is run first so we don't get key errors
self._swagger(dict_['swagger'])
self._info(dict_['info'])
self._definitions(dict_['definitions'])
return dict_ | def dotopdict(self, dict_) | Rewrite the 2.0 json to match what we feed the code for 1.2 | 3.858882 | 3.802974 | 1.014701 |
if value.startswith('KSC_M'):
pass
else:
value = value.replace(':','_')
if value.startswith('ERO') or value.startswith('OBI') or value.startswith('GO') or value.startswith('UBERON') or value.startswith('IAO'):
value = 'obo:' + value
elif value.startswith('birnlex') or value.startswith('nlx'):
value = 'NIFSTD:' + value
elif value.startswith('MESH'):
value = ':'.join(value.split('_'))
else:
value = ':' + value
return OntId(value).URIRef | def id_fix(value) | fix @prefix values for ttl | 5.134443 | 5.210344 | 0.985433 |
name, ext = filename.rsplit('.',1)
try:
prefix, num = name.rsplit('_',1)
n = int(num)
n += 1
filename = prefix + '_' + str(n) + '.' + ext
except ValueError:
filename = name + '_1.' + ext
print('file exists, renaming to %s' % filename)
self.write(filename, type_)
else:
with open(filename, 'wt', encoding='utf-8') as f:
if type_ == 'obo':
f.write(str(self)) # FIXME this is incredibly slow for big files :/
elif type_ == 'ttl':
f.write(self.__ttl__())
else:
raise TypeError('No exporter for file type %s!' % type_) | def write(self, filename, type_='obo'): #FIXME this is bugged
if os.path.exists(filename) | Write file, will not overwrite files with the same name
outputs to obo by default but can also output to ttl if
passed type_='ttl' when called. | 3.575058 | 3.220526 | 1.110085 |
'''
long = '(life is is good) love world "(blah) blah" "here I am" once again "yes" blah '
print(string_profiler(long))
null = ''
print(string_profiler(null))
short = '(life love) yes(and much more)'
print(string_profiler(short))
short = 'yes "life love"'
print(string_profiler(short))
'''
mark = 0
string_list = []
tmp_string = ''
for i in range(len(string)):
curr_index = i + mark
if curr_index == len(string):
break
if string[curr_index] == start_delimiter:
flag = True
else:
flag = False
if flag:
if tmp_string:
string_list.extend(tmp_string.strip().split())
tmp_string = ''
quoted_string = ''
for j in range(curr_index+1, len(string)):
mark += 1
if string[j] == end_delimiter:
break
quoted_string += string[j]
if not remove:
string_list.append(quoted_string)
else:
tmp_string += string[curr_index]
if tmp_string:
string_list.extend(tmp_string.strip().split())
return string_list | def string_profiler(string, start_delimiter='(', end_delimiter=')', remove=True) | long = '(life is is good) love world "(blah) blah" "here I am" once again "yes" blah '
print(string_profiler(long))
null = ''
print(string_profiler(null))
short = '(life love) yes(and much more)'
print(string_profiler(short))
short = 'yes "life love"'
print(string_profiler(short)) | 3.652616 | 1.837768 | 1.987528 |
from IPython import embed
# well I guess that answers that question ...
# librdf much faster for cpython, not for pypy3
from time import time
rdflib.plugin.register('librdfxml', rdflib.parser.Parser,
'librdflib', 'libRdfxmlParser')
rdflib.plugin.register('libttl', rdflib.parser.Parser,
'librdflib', 'libTurtleParser')
p1 = Path('~/git/NIF-Ontology/ttl/NIF-Molecule.ttl').expanduser()
start = time()
graph = rdflib.Graph().parse(p1.as_posix(), format='libttl')
stop = time()
lttime = stop - start
print('libttl', lttime)
#serialize(graph)
start = time()
graph = rdflib.Graph().parse(p1.as_posix(), format='turtle')
stop = time()
ttltime = stop - start
print('ttl', ttltime)
print('diff lt - ttl', lttime - ttltime)
p2 = Path('~/git/NIF-Ontology/ttl/external/uberon.owl').expanduser()
start = time()
graph2 = rdflib.Graph().parse(p2.as_posix(), format='librdfxml')
stop = time()
lrtime = stop - start
print('librdfxml', lrtime)
if True:
start = time()
graph2 = rdflib.Graph().parse(p2.as_posix(), format='xml')
stop = time()
rltime = stop - start
print('rdfxml', rltime)
print('diff lr - rl', lrtime - rltime)
if True:
file_uri = p2.as_uri()
parser = RDF.Parser(name='rdfxml')
stream = parser.parse_as_stream(file_uri)
start = time()
# t = list(stream)
t = tuple(statement_to_tuple(statement) for statement in stream)
stop = time()
stime = stop - start
print('simple time', stime)
embed() | def main() | Python 3.6.6
ibttl 2.605194091796875
ttl 3.8316309452056885
diff lt - ttl -1.2264368534088135
librdfxml 31.267616748809814
rdfxml 58.25124502182007
diff lr - rl -26.983628273010254
simple time 17.405116319656372 | 4.051247 | 3.655963 | 1.10812 |
def predicate_object_combinator(subject):
return function(subject, p, o)
return predicate_object_combinator | def make_predicate_object_combinator(function, p, o) | Combinator to hold predicate object pairs until a subject is supplied and then
call a function that accepts a subject, predicate, and object.
Create a combinator to defer production of a triple until the missing pieces are supplied.
Note that the naming here tells you what is stored IN the combinator. The argument to the
combinator is the piece that is missing. | 2.901167 | 4.221731 | 0.687199 |
ec_s = rdflib.BNode()
if self.operator is not None:
if subject is not None:
yield subject, self.predicate, ec_s
yield from oc(ec_s)
yield from self._list.serialize(ec_s, self.operator, *objects_or_combinators)
else:
for thing in objects_or_combinators:
if isinstance(thing, Combinator):
object = rdflib.BNode()
#anything = list(thing(object))
#if anything:
#[print(_) for _ in anything]
hasType = False
for t in thing(object):
if t[1] == rdf.type:
hasType = True
yield t
if not hasType:
yield object, rdf.type, owl.Class
else:
object = thing
yield subject, self.predicate, object | def serialize(self, subject, *objects_or_combinators) | object_combinators may also be URIRefs or Literals | 4.634766 | 4.474565 | 1.035803 |
for k, v in self._filter_attrs(query).items():
setattr(self, k, v)
return self.save() | def update_with(self, **query) | secure update, mass assignment protected | 4.467675 | 3.921042 | 1.13941 |
if cls.__attr_whitelist__:
whitelist = cls.__attr_accessible__ - cls.__attr_protected__
return {k: v for k, v in attrs.items() if k in whitelist}
else:
blacklist = cls.__attr_protected__ - cls.__attr_accessible__
return {k: v for k, v in attrs.items() if k not in blacklist} | def _filter_attrs(cls, attrs) | attrs: { attr_name: attr_value }
if __attr_whitelist__ is True:
only attr in __attr_accessible__ AND not in __attr_protected__
will pass
else:
only attr not in __attr_protected__ OR in __attr_accessible__
will pass | 2.770712 | 1.990309 | 1.392101 |
errors = {}
for name, validator in self._validators.items():
value = getattr(self, name)
try:
validator(self, value)
except ValidationError as e:
errors[name] = str(e)
self._validate_errors = errors | def _validate(self) | Validate model data and save errors | 3.010695 | 2.610095 | 1.153481 |
if tag.startswith('N'):
return 'n'
if tag.startswith('V'):
return 'v'
if tag.startswith('J'):
return 'a'
if tag.startswith('R'):
return 'r'
return None | def penn_to_wn(tag) | Convert between a Penn Treebank tag to a simplified Wordnet tag | 1.746254 | 1.719266 | 1.015698 |
# Tokenize and tag
sentence1 = pos_tag(word_tokenize(sentence1))
sentence2 = pos_tag(word_tokenize(sentence2))
# Get the synsets for the tagged words
synsets1 = [tagged_to_synset(*tagged_word) for tagged_word in sentence1]
synsets2 = [tagged_to_synset(*tagged_word) for tagged_word in sentence2]
# Filter out the Nones
synsets1 = [ss for ss in synsets1 if ss]
synsets2 = [ss for ss in synsets2 if ss]
#print(synsets1)
#print(synsets2)
score, count = 0.0, 0.0
# For each word in the first sentence
for synset in synsets1:
# Get the similarity value of the most similar word in the other sentence
best_score=[synset.path_similarity(ss) for ss in synsets2 if synset.path_similarity(ss)]
# Check that the similarity could have been computed
if best_score:
score += max(best_score)
count += 1
# Average the values
if count > 0:
score /= count
else:
score = 0
return score | def sentence_similarity(sentence1, sentence2) | compute the sentence similarity using Wordnet | 2.368207 | 2.36746 | 1.000316 |
''' If you want to use the command line '''
from docopt import docopt
doc = docopt( __doc__, version=VERSION )
args = pd.Series({k.replace('--', ''): v for k, v in doc.items()})
if args.all:
graph = Graph2Pandas(args.file, _type='all')
elif args.type:
graph = Graph2Pandas(args.file, _type=args.type)
else:
graph = Graph2Pandas(args.file)
graph.save(args.output) | def command_line() | If you want to use the command line | 3.684587 | 3.603832 | 1.022408 |
''' Saves entities into multiple files within the same folder because of pickle-recursive
errors that would happen if squeezed into one '''
self.create_pickle((self.g.namespaces, ))
self.df.to_pickle(output) | def save(self, foldername: str, path_to_folder: str=None) -> None | Saves entities into multiple files within the same folder because of pickle-recursive
errors that would happen if squeezed into one | 50.428104 | 7.309755 | 6.89874 |
''' Returns qname of uri in rdflib graph while also saving it '''
try:
prefix, namespace, name = self.g.compute_qname(uri)
qname = prefix + ':' + name
return qname
except:
try:
print('prefix:', prefix)
print('namespace:', namespace)
print('name:', name)
except:
print('Could not print from compute_qname')
exit('No qname for ' + uri) | def qname(self, uri: str) -> str | Returns qname of uri in rdflib graph while also saving it | 5.19407 | 3.585257 | 1.44873 |
'''Updates self.g or self.path bc you could only choose 1'''
if isinstance(self.path, str) or isinstance(self.path, p):
self.path = str(self.path)
filetype = p(self.path).suffix
if filetype == '.pickle':
self.g = pickle.load(open(self.path, 'rb'))
if isinstance(self.g, rdflib.graph.Graph):
return self.get_sparql_dataframe()
else:
print('WARNING:: function df() wont work unless an ontology source is loaded')
return self.g
elif filetype == '.ttl' or filetype == '.rdf':
self.g = rdflib.Graph()
self.g.parse(self.path, format='turtle')
return self.get_sparql_dataframe()
elif filetype == '.nt':
self.g = rdflib.Graph()
self.g.parse(self.path, format='nt')
return self.get_sparql_dataframe()
elif filetype == '.owl' or filetype == '.xrdf':
self.g = rdflib.Graph()
try:
self.g.parse(self.path, format='xml')
except:
# some owl formats are more rdf than owl
self.g.parse(self.path, format='turtle')
return self.get_sparql_dataframe()
else:
exit('Format options: owl, ttl, df_pickle, rdflib.Graph()')
try:
return self.get_sparql_dataframe()
self.path = None
except:
exit('Format options: owl, ttl, df_pickle, rdflib.Graph()')
elif isinstance(self.g, rdflib.graph.Graph):
self.path = None
return self.get_sparql_dataframe()
else:
exit('Obj given is not str, pathlib obj, or an rdflib.Graph()') | def Graph2Pandas_converter(self) | Updates self.g or self.path bc you could only choose 1 | 3.196728 | 2.805721 | 1.13936 |
''' Iterates through the sparql table and condenses it into a Pandas DataFrame '''
self.result = self.g.query(self.query)
cols = set() # set(['qname'])
indx = set()
data = {}
curr_subj = None # place marker for first subj to be processed
bindings = []
for i, binding in enumerate(self.result.bindings):
subj_binding = binding[rdflib.term.Variable('subj')]
pred_binding = binding[rdflib.term.Variable('pred')]
obj_binding = binding[rdflib.term.Variable('obj')]
subj = subj_binding
pred = pred_binding # self.qname(pred_binding) if self.predicate_as_qname else pred_binding
obj = obj_binding
# stops at BNodes; could be exanded here
if isinstance(subj, BNode):
continue
elif isinstance(pred, BNode):
continue
elif isinstance(obj, BNode) and obj:
continue
# else:
# subj = str(subj)
# pred = str(pred)
# obj = str(obj)
cols.add(pred)
indx.add(subj)
bindings.append(binding)
bindings = sorted(bindings, key=lambda k: k[rdflib.term.Variable('subj')])
df = pd.DataFrame(columns=cols, index=indx)
for i, binding in enumerate(bindings):
subj_binding = binding[rdflib.term.Variable('subj')]
pred_binding = binding[rdflib.term.Variable('pred')]
obj_binding = binding[rdflib.term.Variable('obj')]
subj = subj_binding
pred = pred_binding # self.qname(pred_binding) if self.qname_predicates else pred_binding
obj = obj_binding
# stops at BNodes; could be exanded here
if isinstance(subj, BNode):
continue
elif isinstance(pred, BNode):
continue
elif isinstance(obj, BNode) and obj:
continue
# elif self.value_type:
# subj = str(subj)
# pred = str(pred)
# obj = str(obj)
if curr_subj == None:
curr_subj = subj
if not data.get(subj): # Prepare defaultdict home if it doesn't exist
data[subj] = defaultdict(list)
data[subj][pred].append(obj)
elif curr_subj != subj:
curr_subj = subj
for data_subj, data_pred_objs in data.items():
for data_pred, data_objs in data_pred_objs.items():
if len(data_objs) == 1: # clean lists of just 1 value
data_pred_objs[data_pred] = data_objs[0]
df.loc[data_subj] = pd.Series(data_pred_objs)
data = {}
if not data.get(subj): # Prepare defaultdict home if it doesn't exist
data[subj] = defaultdict(list)
data[subj][pred].append(obj)
else:
if not data.get(subj): # Prepare defaultdict home if it doesn't exist
data[subj] = defaultdict(list)
data[subj][pred].append(obj)
for data_subj, data_pred_objs in data.items():
for data_pred, data_objs in data_pred_objs.items():
if len(data_objs) == 1: # clean lists of just 1 value
data_pred_objs[data_pred] = data_objs[0]
df.loc[data_subj] = pd.Series(data_pred_objs)
df = df.where((pd.notnull(df)), None) # default Null is fricken Float NaN
return df | def get_sparql_dataframe( self ) | Iterates through the sparql table and condenses it into a Pandas DataFrame | 2.345787 | 2.269693 | 1.033526 |
''' Multi funcitonal DataFrame with settings '''
local_df = self.df.copy()
if qname_predicates:
for col in self.columns:
local_df.rename({col: self.g.qname(col)})
if not keep_variable_type:
pass
# convert all to strings, watch out for lists
return local_df | def df(self, qname_predicates:bool=False, keep_variable_type:bool=True) -> pd.DataFrame | Multi funcitonal DataFrame with settings | 9.04008 | 6.217069 | 1.454074 |
for prefix, uri in namespaces.items():
self.add_namespace(prefix=prefix, uri=uri) | def add_namespaces(self, namespaces: Dict[str, str]) -> None | Adds a prefix to uri mapping (namespace) in bulk
Adds a namespace to replace any uris in iris with shortened prefixes
in order to make the file more readable. Not techniqually necessary.
Args: namespaces: prefix to uri mappings
Example:
add_namespaces(
namespaces = {
'my_prefix': 'http://myurl.org/',
'memo': 'http://memolibrary.org/memo#',
}
) | 3.976367 | 3.992369 | 0.995992 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.