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 at...
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 ...
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=sel...
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, 'TagSpecifi...
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 ...
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 r...
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' ) ...
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 ...
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( ...
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, ...
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 ...
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: Shoul...
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._ma...
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 ...
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...
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 ...
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:...
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 b...
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) da...
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_ilx2syno...
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: ...
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: ...
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...
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 =...
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'], ...
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: ...
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) ...
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....
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...
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'], ...
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_...
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': ...
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 ...
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: ...
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) ...
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!') excep...
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' + ...
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 # wh...
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 hav...
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.loca...
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 ...
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, **k...
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 ...
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 ...
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(pr...
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 addP...
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)...
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...
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...
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: ...
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 ...
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 =...
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 l...
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 ...
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:...
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, {outp...
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'] ...
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...
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...
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"' ...
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...
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('lib...
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 comb...
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 thi...
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.ite...
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 sente...
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.fi...
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('namespa...
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')) ...
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...
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 l...
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( name...
3.976367
3.992369
0.995992