sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def update(self, client):
"""Execute update command on instance."""
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:
... | Execute update command on instance. | entailment |
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
... | 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... | entailment |
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 ... | 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
... | entailment |
def ordered(start, edges, predicate=None, inverse=False):
""" Depth first edges from a SciGraph response. """
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!')
... | Depth first edges from a SciGraph response. | entailment |
def tcsort(item): # FIXME SUCH WOW SO INEFFICIENT O_O
""" get len of transitive closure assume type items is tree... """
return len(item[1]) + sum(tcsort(kv) for kv in item[1].items()) | get len of transitive closure assume type items is tree... | entailment |
def get_node(start, tree, pnames):
""" for each parent find a single branch to root """
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):
... | for each parent find a single branch to root | entailment |
def dematerialize(parent_name, parent_node): # FIXME we need to demat more than just leaves!
#FIXME still an issue: Fornix, Striatum, Diagonal Band
""" 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 ... | 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! | entailment |
def inv_edges(json):
"""Switch obj/sub for a set of edges (makes fixing known inverse edges MUCH easier)"""
for edge in json['edges']:
sub, obj = edge['sub'], edge['obj']
edge['sub'] = obj
edge['obj'] = sub
edge['pred'] += 'INVERTED' | Switch obj/sub for a set of edges (makes fixing known inverse edges MUCH easier) | entailment |
def collect_results(results_file):
"""Return the result (pass/fail) for json file."""
with open(results_file, 'r') as results:
data = json.load(results)
return data | Return the result (pass/fail) for json file. | entailment |
def get_terms(self):
''' 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(se... | GROUP BY is a shortcut to only getting the first in every list of group | entailment |
def get_terms_complete(self) -> pd.DataFrame:
''' 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_com... | Gets complete entity data like term/view | entailment |
def get_ilx2superclass(self, clean:bool=True):
''' 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 enumer... | clean: for list of literals only | entailment |
def get_tid2annotations(self, clean:bool=True):
''' 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 enumer... | clean: for list of literals only | entailment |
def get_tid2synonyms(self, clean:bool=True):
''' 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 cl... | clean: for list of literals only | entailment |
def get_ilx2synonyms(self, clean:bool=True):
''' 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)}
... | clean: for list of literals only | entailment |
def superclasses_bug_fix(data):
''' 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 | PHP returns "id" in superclass but only accepts superclass_tid | entailment |
def log_info(self, data):
''' 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'],... | Logs successful responses | entailment |
def get(self, url):
''' Requests data from database '''
req = r.get(url,
headers = self.headers,
auth = self.auth)
return self.process_request(req) | Requests data from database | entailment |
def post(self, url, data):
''' 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) | Gives data to database | entailment |
def process_request(self, req):
''' 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.jso... | Checks to see if data returned from database is useable | entailment |
def is_equal(self, string1, string2):
''' Simple string comparator '''
return string1.lower().strip() == string2.lower().strip() | Simple string comparator | entailment |
def get_data_from_ilx(self, ilx_id):
''' 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.AP... | Gets full meta data (expect their annotations and relationships) from is ILX ID | entailment |
def search_by_label(self, label):
''' 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) | Server returns anything that is simlar in any catagory | entailment |
def are_ilx(self, ilx_ids):
''' 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:... | Checks list of objects to see if they are usable ILX IDs | entailment |
def add_triple(self, subj, pred, obj):
''' 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'] !=... | Adds an entity property to an existing entity | entailment |
def add_relationship(self, term1, relationship, term2):
''' 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'],
... | Creates a relationship between 3 entities in database | entailment |
def add_annotation(self, entity, annotation, value):
''' 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':... | Adds an annotation proprty to existing entity | entailment |
def custom_update(self, data, pred, obj):
''' 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
... | Updates existing entity proprty based on the predicate input | entailment |
def add_entity(self, rdf_type, superclass, label, definition=None):
''' Adds entity as long as it doesn't exist and has a usable
superclass ILX ID and rdf:type
'''
# Checks if you inputed the right type
rdf_type = rdf_type.lower().strip().replace('owl:Class', 'term')
... | Adds entity as long as it doesn't exist and has a usable
superclass ILX ID and rdf:type | entailment |
def sortProperties(self, properties): # modified to sort objects using their global rank
"""Take a hash from predicate uris to lists of values.
Sort the lists of values. Return a sorted list of properties."""
# Sort object lists
for prop, objects in properties.items():
o... | Take a hash from predicate uris to lists of values.
Sort the lists of values. Return a sorted list of properties. | entailment |
def _buildPredicateHash(self, subject): # XXX unmodified
"""
Build a hash key by predicate to a list of objects for the given
subject
"""
properties = {}
for s, p, o in self.store.triples((subject, None, None)):
oList = properties.get(p, [])
oList... | Build a hash key by predicate to a list of objects for the given
subject | entailment |
def isValidList(self, l): # modified to flatten lists specified using [ a rdf:List; ] syntax
"""
Checks if l is a valid RDF list, i.e. no nodes have other properties.
"""
try:
if self.store.value(l, RDF.first) is None:
return False
except:
... | Checks if l is a valid RDF list, i.e. no nodes have other properties. | entailment |
def _write(self, value):
""" rename to write and import inspect to debut the callstack """
if ' ' in value:
s = inspect.stack()
fn = s[1].function
super().write('%%DEBUG {} %%'.format(fn))
super().write(value) | rename to write and import inspect to debut the callstack | entailment |
def serialize(self, *args, **kwargs):
""" Modified to allow additional labels to be passed in. """
if 'labels' in kwargs:
# populate labels from outside the local graph
self._labels.update(kwargs['labels'])
super(HtmlTurtleSerializer, self).serialize(*args, **kwargs) | Modified to allow additional labels to be passed in. | entailment |
def checkCalledInside(classname, stack):
""" Fantastically inefficient! """
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 i... | Fantastically inefficient! | entailment |
def addLNT(LocalName, phenoId, predicate, g=None): # XXX deprecated
""" Add a local name for a phenotype from a pair of identifiers """
if g is None:
s = inspect.stack(0) # horribly inefficient
checkCalledInside('LocalNameManager', s)
g = s[1][0].f_locals # get globals of calling scop... | Add a local name for a phenotype from a pair of identifiers | entailment |
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. """
if g is None:
g = inspect.stack(0)[1][0].f_locals # get globals of calling scope
for k in list(graphBase.LocalNa... | WARNING: Only call from top level! THIS DOES NOT RESET NAMES in an embeded IPython!!!
Remove any local names that have already been defined. | entailment |
def load_existing(self):
""" advanced usage allows loading multiple sets of neurons and using a config
object to keep track of the different graphs """
from pyontutils.closed_namespaces import rdfs
# bag existing
try:
next(iter(self.neurons()))
raise ... | advanced usage allows loading multiple sets of neurons and using a config
object to keep track of the different graphs | entailment |
def configGraphIO(remote_base,
local_base= None,
branch= 'master',
core_graph_paths= tuple(),
core_graph= None,
in_graph_paths= tuple(),
out_graph_path= Non... | We set this up to work this way because we can't
instantiate graphBase, it is a super class that needs
to be configurable and it needs to do so globally.
All the default values here are examples and not real.
You should write a local `def config` function as part
... | entailment |
def python_header(cls):
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()... | }} | entailment |
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 sta... | 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... | entailment |
def label_maker(self):
""" needed to defer loading of local conventions to avoid circular dependency issue """
if (not hasattr(graphBase, '_label_maker') or
graphBase._label_maker.local_conventions != graphBase.local_conventions):
graphBase._label_maker = LabelMaker(graphBase.loc... | needed to defer loading of local conventions to avoid circular dependency issue | entailment |
def _graphify(self, *args, graph=None): # defined
""" Lift phenotypeEdges to Restrictions """
if graph is None:
graph = self.out_graph
################## LABELS ARE DEFINED HERE ##################
gl = self.genLabel
ll = self.localLabel
ol = self.origLabel
... | Lift phenotypeEdges to Restrictions | entailment |
def run(args):
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 fe... | localhost:~/files/ontology-packages/scigraph/ | entailment |
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). """
return self.makeOutput(EXE, command... | 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). | entailment |
def build(self, mode=None, check=False):
""" Just shuffle the current call off to the build server with --local attached """
kwargs = {}
if not self.build_only: # don't try to deploy twice
kwargs[' --build-only'] = True
if not self.local:
kwargs['--local'] = True... | Just shuffle the current call off to the build server with --local attached | entailment |
def swanson():
""" not really a parcellation scheme
NOTE: the defining information up here is now deprecated
it is kept around to keep the code further down happy """
source = Path(devconfig.resources, 'swanson_aligned.txt').as_posix()
ONT_PATH = 'http://ontology.neuinfo.org/NIF/ttl/generat... | not really a parcellation scheme
NOTE: the defining information up here is now deprecated
it is kept around to keep the code further down happy | entailment |
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) """
if working_dir is None:
return Path(failover, pathstring).resolve()
els... | relative paths to resources in this repository
`failover` matches the location relative to the
github location (usually for prov purposes) | entailment |
def build(*onts, fail=False, n_jobs=9, write=True):
""" Set n_jobs=1 for debug or embed() will crash. """
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=... | Set n_jobs=1 for debug or embed() will crash. | entailment |
def qname(uri, warning=False):
""" compute qname from defaults """
if warning:
print(tc.red('WARNING:'), tc.yellow(f'qname({uri}) is deprecated! please use OntId({uri}).curie'))
return __helper_graph.qname(uri) | compute qname from defaults | entailment |
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. """
prefs = ['']
if keep:
prefixes.update({p:str(n) for p, n in graph.namespaces()}... | Remove unused curie prefixes and normalize to a standard set. | entailment |
def displayTriples(triples, qname=qname):
""" triples can also be an rdflib Graph instance """
[print(*(e[:5]
if isinstance(e, rdflib.BNode) else
qname(e)
for e in t), '.')
for t in sorted(triples)] | triples can also be an rdflib Graph instance | entailment |
def write(self, cull=False):
""" Serialize self.g and write to self.filename, set cull to true to remove unwanted prefixes """
if cull:
cull_prefixes(self).write()
else:
ser = self.g.serialize(format='nifttl')
with open(self.filename, 'wb') as f:
... | Serialize self.g and write to self.filename, set cull to true to remove unwanted prefixes | entailment |
def add_ap(self, id_, label=None, addPrefix=True):
""" Add id_ as an owl:AnnotationProperty"""
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 labe... | Add id_ as an owl:AnnotationProperty | entailment |
def add_op(self, id_, label=None, subPropertyOf=None, inverse=None, transitive=False, addPrefix=True):
""" Add id_ as an owl:ObjectProperty"""
self.add_trip(id_, rdf.type, owl.ObjectProperty)
if inverse:
self.add_trip(id_, owl.inverseOf, inverse)
if subPropertyOf:
... | Add id_ as an owl:ObjectProperty | entailment |
def add_hierarchy(self, parent, edge, child): # XXX DEPRECATED
""" Helper function to simplify the addition of part_of style
objectProperties to graphs. FIXME make a method of makeGraph?
"""
if type(parent) != rdflib.URIRef:
parent = self.check_thing(parent)
if ... | Helper function to simplify the addition of part_of style
objectProperties to graphs. FIXME make a method of makeGraph? | entailment |
def add_restriction(self, subject, predicate, object_):
""" Lift normal triples into restrictions using someValuesFrom. """
if type(object_) != rdflib.URIRef:
object_ = self.check_thing(object_)
if type(predicate) != rdflib.URIRef:
predicate = self.check_thing(predicate)... | Lift normal triples into restrictions using someValuesFrom. | entailment |
def get_equiv_inter(self, curie):
""" get equivelant classes where curie is in an intersection """
start = self.qname(self.expand(curie)) # in case something is misaligned
qstring = """
SELECT DISTINCT ?match WHERE {
?match owl:equivalentClass/owl:intersectionOf/rdf:rest*/rdf:fi... | get equivelant classes where curie is in an intersection | entailment |
def qname(self, uri, generate=False):
""" Given a uri return the qname if it exists, otherwise return the uri. """
try:
prefix, namespace, name = self.g.namespace_manager.compute_qname(uri, generate=generate)
qname = ':'.join((prefix, name))
return qname
excep... | Given a uri return the qname if it exists, otherwise return the uri. | entailment |
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.
"""
log_src, description = split_history_item(item.strip())
# Get relative path for log:
# {provider}... | Archive the log and results file for the given history item.
Copy the files and update the results file in destination directory. | entailment |
def echo_results(data, no_color, verbose=False):
"""Print test results in nagios style format."""
try:
summary = data['summary']
except KeyError as error:
click.secho(
'The results json is missing key: %s' % error,
fg='red'
)
sys.exit(1)
if 'faile... | Print test results in nagios style format. | entailment |
def echo_results_file(results_file, no_color, verbose=False):
"""Print test results in nagios style format."""
try:
data = collect_results(results_file)
except ValueError:
echo_style(
'The results file is not the proper json format.',
no_color,
fg='red'
... | Print test results in nagios style format. | entailment |
def echo_verbose_results(data, no_color):
"""Print list of tests and result of each test."""
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'] == 'p... | Print list of tests and result of each test. | entailment |
def get_log_file_from_item(history):
"""
Return the log file based on provided history item.
Description is optional.
"""
try:
log_file, description = shlex.split(history)
except ValueError:
log_file = history.strip()
return log_file | Return the log file based on provided history item.
Description is optional. | entailment |
def results_history(history_log, no_color):
"""Display a list of ipa test results history."""
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,... | Display a list of ipa test results history. | entailment |
def split_history_item(history):
"""
Return the log file and optional description for item.
"""
try:
log_file, description = shlex.split(history)
except ValueError:
log_file = history.strip()
description = None
return log_file, description | Return the log file and optional description for item. | entailment |
def get_working_dir(script__file__):
""" hardcoded sets the 'equivalent' working directory if not in git """
start = Path(script__file__).resolve()
_root = Path(start.root)
working_dir = start
while not list(working_dir.glob('.git')):
if working_dir == _root:
return
work... | hardcoded sets the 'equivalent' working directory if not in git | entailment |
def sysidpath(ignore_options=False):
""" get a unique identifier for the machine running this function """
# 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... | get a unique identifier for the machine running this function | entailment |
def chunk_list(list_, size):
""" Split a list list_ into sublists of length size.
NOTE: len(chunks[-1]) <= size. """
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:
c... | Split a list list_ into sublists of length size.
NOTE: len(chunks[-1]) <= size. | entailment |
def NICKNAME(selfPARAMSDEFAULT_OUTPUT):
""" DOCSTRING
"""
{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}
... | DOCSTRING | entailment |
def gencode(self):
""" Run this to generate the code """
ledict = requests.get(self.api_url).json()
ledict = self.dotopdict(ledict)
out = self.dodict(ledict)
self._code = out | Run this to generate the code | entailment |
def dotopdict(self, dict_):
""" Rewrite the 2.0 json to match what we feed the code for 1.2 """
mlookup = {'get':'GET', 'post':'POST'}
def rearrange(path, method_dict, method):
oid = method_dict['operationId']
self._paths[oid] = path
method_dict['nickname'] = ... | Rewrite the 2.0 json to match what we feed the code for 1.2 | entailment |
def local_imports(remote_base, local_base, ontologies, local_versions=tuple(), readonly=False, dobig=False, revert=False):
""" Read the import closure and use the local versions of the files. """
done = []
triples = set()
imported_iri_vs_ontology_iri = {}
p = owl.imports
oi = b'owl:imports'
... | Read the import closure and use the local versions of the files. | entailment |
def id_fix(value):
""" fix @prefix values for ttl """
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 = ... | fix @prefix values for ttl | entailment |
def write(self, filename, type_='obo'): #FIXME this is bugged
""" 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.
"""
if os.path.exists(filename):
name, ext = file... | 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. | entailment |
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 m... | 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... | entailment |
def main():
from IPython import embed
""" 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
"""
""" Python 3.5.3 ... | 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 | entailment |
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.
... | 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... | entailment |
def serialize(self, subject, *objects_or_combinators):
""" object_combinators may also be URIRefs or Literals """
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)
... | object_combinators may also be URIRefs or Literals | entailment |
def update_with(self, **query):
"""
secure update, mass assignment protected
"""
for k, v in self._filter_attrs(query).items():
setattr(self, k, v)
return self.save() | secure update, mass assignment protected | entailment |
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__
... | 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 | entailment |
def _validate(self):
"""Validate model data and save errors
"""
errors = {}
for name, validator in self._validators.items():
value = getattr(self, name)
try:
validator(self, value)
except ValidationError as e:
errors[n... | Validate model data and save errors | entailment |
def penn_to_wn(tag):
""" Convert between a Penn Treebank tag to a simplified Wordnet tag """
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 | Convert between a Penn Treebank tag to a simplified Wordnet tag | entailment |
def sentence_similarity(sentence1, sentence2):
""" compute the sentence similarity using Wordnet """
# 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) f... | compute the sentence similarity using Wordnet | entailment |
def command_line():
''' 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 = ... | If you want to use the command line | entailment |
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 '''
self.create_pickle((self.g.namespaces, ))
self.df.to_pickle(output) | Saves entities into multiple files within the same folder because of pickle-recursive
errors that would happen if squeezed into one | entailment |
def qname(self, uri: str) -> str:
''' 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:', pref... | Returns qname of uri in rdflib graph while also saving it | entailment |
def Graph2Pandas_converter(self):
'''Updates self.g or self.path bc you could only choose 1'''
if isinstance(self.path, str) or isinstance(self.path, p):
self.path = str(self.path)
filetype = p(self.path).suffix
if filetype == '.pickle':
self.g = pick... | Updates self.g or self.path bc you could only choose 1 | entailment |
def get_sparql_dataframe( self ):
''' 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
... | Iterates through the sparql table and condenses it into a Pandas DataFrame | entailment |
def df(self, qname_predicates:bool=False, keep_variable_type:bool=True) -> pd.DataFrame:
''' 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 k... | Multi funcitonal DataFrame with settings | entailment |
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 m... | 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... | entailment |
def qname(self, iri: str) -> str:
""" Get qualified name of uri in rdflib graph while also saving it
Args: iri: The iri that you want to replace the uri with a known prefix with
Returns: qualified name of the iri to be used as the new predicate
"""
prefix, namespace, name = sel... | Get qualified name of uri in rdflib graph while also saving it
Args: iri: The iri that you want to replace the uri with a known prefix with
Returns: qualified name of the iri to be used as the new predicate | entailment |
def add_namespace(self, prefix: str, uri: str) -> Namespace:
""" Adds a prefix to uri mapping (namespace)
Adds a namespace to replace any uris in iris with shortened prefixes
in order to make the file more readable. Not techniqually necessary.
Args:
prefix: prefix that will... | Adds a prefix to uri mapping (namespace)
Adds a namespace to replace any uris in iris with shortened prefixes
in order to make the file more readable. Not techniqually necessary.
Args:
prefix: prefix that will substitute the uri in the iri
uri: the uri in the iri to be ... | entailment |
def find_prefix(self, iri: Union[URIRef, Literal, str]) -> Union[None, str]:
""" Finds if uri is in common_namespaces
Auto adds prefix if incoming iri has a uri in common_namespaces. If its not in the local
library, then it will just be spit out as the iri and not saved/condensed into qualified... | Finds if uri is in common_namespaces
Auto adds prefix if incoming iri has a uri in common_namespaces. If its not in the local
library, then it will just be spit out as the iri and not saved/condensed into qualified
names.
The reason for the maxes is find the longest string match. This ... | entailment |
def add_annotation(
self,
subj: URIRef,
pred: URIRef,
obj: Union[Literal, URIRef],
a_p: URIRef ,
a_o: Union[Literal, URIRef],
) -> BNode:
""" Adds annotation to rdflib graph.
The annotation axiom will filled in if this is a... | Adds annotation to rdflib graph.
The annotation axiom will filled in if this is a new annotation for the triple.
Args:
subj: Entity subject to be annotated
pref: Entities Predicate Anchor to be annotated
obj: Entities Object Anchor to be annotated
a_p: A... | entailment |
def add_triple(
self,
subj: Union[URIRef, str],
pred: Union[URIRef, str],
obj: Union[URIRef, Literal, str]
) -> None:
""" Adds triple to rdflib Graph
Triple can be of any subject, predicate, and object of the entity without a need for order.
... | Adds triple to rdflib Graph
Triple can be of any subject, predicate, and object of the entity without a need for order.
Args:
subj: Entity subject
pred: Entity predicate
obj: Entity object
Example:
In [1]: add_triple(
...: 'h... | entailment |
def process_prefix(self, prefix: str) -> Union[Namespace, None]:
""" Add namespace to graph if it has a local match
This allows qnames to be used without adding their respected namespaces if they are in
the common_namespaces local dict. This is is to save a butt-ton of time trying to see what
... | Add namespace to graph if it has a local match
This allows qnames to be used without adding their respected namespaces if they are in
the common_namespaces local dict. This is is to save a butt-ton of time trying to see what
the ontology has as far as uris go.
Args: prefix: prefix of t... | entailment |
def process_subj_or_pred(self, component: Union[URIRef, str]) -> URIRef:
""" Adds viable uri from iri or expands viable qname to iri to be triple ready
Need to have a viable qualified name (qname) in order to use a qname. You can make it
viable by either add the namespace beforehand with add_na... | Adds viable uri from iri or expands viable qname to iri to be triple ready
Need to have a viable qualified name (qname) in order to use a qname. You can make it
viable by either add the namespace beforehand with add_namespace(s) or if its already
in the local common_namespaces preloaded.
... | entailment |
def process_obj(self, obj: Union[URIRef, Literal, str]) -> Union[URIRef, Literal]:
""" Gives component the proper node type
Args:
obj: Entity object to be converted to its appropriate node type
Returns:
URIRef or Literal type of the object provided.
Raises:
... | Gives component the proper node type
Args:
obj: Entity object to be converted to its appropriate node type
Returns:
URIRef or Literal type of the object provided.
Raises:
SystemExit: If object is a dict or list it becomes str with broken data. Needs to
... | entailment |
def serialize(self, **kwargs) -> str:
""" rdflib.Graph().serialize wrapper
Original serialize cannot handle PosixPath from pathlib. You should ignore everything, but
destination and format. format is a must, but if you don't include a destination, it will
just return the formated graph ... | rdflib.Graph().serialize wrapper
Original serialize cannot handle PosixPath from pathlib. You should ignore everything, but
destination and format. format is a must, but if you don't include a destination, it will
just return the formated graph as an str output.
Args:
desti... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.