output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Requests data from database
Given the following Python 3 function, write the documentation def get(self, url): ''' Requests data from database ''' req = r.get(url, headers = self.headers, auth = self.auth) return self.process_request(req)
As a Python code translator, you convert algorithms and pseudocode into Python.
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)
How would you implement a function in Python 3 that gives data to database
You are a Python code analyst, evaluating scripts for potential improvements.
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...
How would you code a function in Python 3 to check to see if data returned from database is useable '''
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Implement a function in Python 3 to get full meta data from an ILX ID
As a Python code analyst, you investigate and solve complex coding mysteries
Search for a single category by label
Make a summary of the following Python 3 code 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)
As a Python code composer, you craft elegant and concise scripts.
Checks list of objects to see if they are usable ILX IDs
Can you generate the documentation for the following Python 3 function 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('/', '') ...
As a python code expert, you are capable of creating scripts from specifications.
Adds an entity property to an existing entity
How would you explain what the following Python 3 function does 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('...
As a python code expert, you are capable of creating scripts from specifications.
Creates a relationship between 3 entities in database
Can you tell what is the following Python 3 function doing 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': rel...
You are a Python code generator, capable of creating scripts from specifications.
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':...
Can you implement a function in Python 3 that adds an annotation proprty to an existing entity
You are a Python code generator, capable of creating scripts from specifications.
Custom update of existing entity proprty based on the predicate input
Make a summary of the following Python 3 code 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, ...
You are a Python code analyst, evaluating scripts for potential improvements.
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') ...
Can you write a function in Python 3 where it adds an entity to the database.
As a Python code composer, you craft elegant and concise scripts.
Take a hash from predicate uris to lists of values.
Here you have a function in Python 3, explain what it does def sortProperties(self, properties): # modified to sort objects using their global rank # Sort object lists for prop, objects in properties.items(): objects.sort(key=self._globalSortKey) # Make sorted list of properties ...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
How would you code a function in Python 3 to build a hash key by predicate to a list of objects for the given subject.
As a Python code translator, you convert algorithms and pseudocode into Python.
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: ...
How would you code a function in Python 3 to check if a list is a valid RDF list.
As a Python code analyst, you investigate and solve complex coding mysteries
rename to write and import inspect to debut the callstack
Explain what the following Python 3 code does def _write(self, value): if ' ' in value: s = inspect.stack() fn = s[1].function super().write('%%DEBUG {} %%'.format(fn)) super().write(value)
As a Python code translator, you convert algorithms and pseudocode into Python.
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)
How would you implement a function in Python 3 that serializes the object to HTML.
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Implement a function in Python 3 to add a local name for a phenotype from a pair of identifiers
As a Python code translator, you convert algorithms and pseudocode into Python.
Reset all local names in the current scope.
Here you have a function in Python 3, explain what it does def resetLocalNames(g=None): 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...
You are a Python code generator, capable of creating scripts from specifications.
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 ...
Create a Python 3 function for advancing usage allows loading multiple sets of neurons and using a config object to keep track of the different graphs
You are a Python code architect, reviewing and designing scalable and efficient code
This function is a simple function that creates a graphIO class that can be used to configure a graphIO.
Can you generate a brief explanation for the following Python 3 code def configGraphIO(remote_base, local_base= None, branch= 'master', core_graph_paths= tuple(), core_graph= None, in_...
You are a Python code generator, capable of creating scripts from specifications.
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()...
Write a Python 3 script to return a python header for the class.
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Implement a Python 3 function for adding the equivalent class of this neuron with the set of other neurons
You are a Python code generator, capable of creating scripts from specifications.
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...
Write a Python 3 function for returning a labelMaker object for this graphBase
You are a Python code analyst, evaluating scripts for potential improvements.
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 ...
How would you implement a function in Python 3 that lifts phenotypeEdges to Restrictions
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Write a Python 3 function that can run the build server and returns the current version of the current node.
As a Python code composer, you craft elegant and concise scripts.
This method runs the given commands on the current executor.
Can you generate the documentation for the following Python 3 function def runOnExecutor(self, *commands, oper=ACCEPT, defer_shell_expansion=False): return self.makeOutput(EXE, commands, oper=oper, defer_shell_expansion=defer_shell_expansion)
You are a Python code generator, capable of creating scripts from specifications.
Shuffle the current call off to the build server with the specified mode.
Here you have a function in Python 3, explain what it does def build(self, mode=None, check=False): 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: kw...
You are a Python code generator, capable of creating scripts from specifications.
This function creates a graph that contains the swanson - aligned file and returns the NIFRID of the next page.
Explain what the following Python 3 code does def swanson(): source = Path(devconfig.resources, 'swanson_aligned.txt').as_posix() ONT_PATH = 'http://ontology.neuinfo.org/NIF/ttl/generated/' filename = 'swanson_hierarchies' ontid = ONT_PATH + filename + '.ttl' PREFIXES = SwansonLabels.prefixes n...
As a Python code analyst, you investigate and solve complex coding mysteries
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=...
Create a Python 3 function for building a list of all the tables in the ontology.
As a Python code translator, you convert algorithms and pseudocode into Python.
compute qname from defaults
Can you generate a brief explanation for the following Python 3 code def qname(uri, warning=False): if warning: print(tc.red('WARNING:'), tc.yellow(f'qname({uri}) is deprecated! please use OntId({uri}).curie')) return __helper_graph.qname(uri)
You are a Python code analyst, evaluating scripts for potential improvements.
Remove unused curie prefixes and normalize to a standard set.
Make a summary of the following Python 3 code 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.up...
As a python code expert, you are capable of creating scripts from specifications.
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)]
Implement a Python 3 function for displaying a list of triples in a nice way.
As a Python code translator, you convert algorithms and pseudocode into Python.
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: ...
Write a Python 3 function that can serialize self. g and write to self. filename
As a Python code analyst, you investigate and solve complex coding mysteries
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...
How would you code a function in Python 3 to add an annotation property to the resource.
You are a Python code generator, capable of creating scripts from specifications.
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: ...
Can you create a Python 3 function that adds an operation to the rdflib object.
As a Python code composer, you craft elegant and concise scripts.
Add a hierarchy of object properties to the graph.
Can you generate a brief explanation for the following Python 3 code def add_hierarchy(self, parent, edge, child): # XXX DEPRECATED if type(parent) != rdflib.URIRef: parent = self.check_thing(parent) if type(edge) != rdflib.URIRef: edge = self.check_thing(edge) if type...
As a Python code analyst, you investigate and solve complex coding mysteries
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)...
Write a Python 3 function that can add a restriction to the subject.
As a python code expert, you are capable of creating scripts from specifications.
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...
How would you code a function in Python 3 to get equivelant classes where curie is in an intersection
You are a Python code generator, capable of creating scripts from specifications.
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...
Can you create a Python 3 function that gives a uri return the qname if it exists otherwise return the uri.
As a Python code analyst, you investigate and solve complex coding mysteries
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}...
Implement a function in Python 3 to archive the log and results files for the given history item to the given destination directory.
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Write a Python 3 script to print test results in nagios style format.
You are a Python code analyst, evaluating scripts for potential improvements.
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' ...
Create a Python 3 function for printing test results in nagios style format.
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Can you create a Python 3 function that prints list of tests and result of each test.
As a Python code composer, you craft elegant and concise scripts.
Return the log file based on the provided history item.
Given the following Python 3 function, write the documentation def get_log_file_from_item(history): try: log_file, description = shlex.split(history) except ValueError: log_file = history.strip() return log_file
You are a Python code analyst, evaluating scripts for potential improvements.
Display a list of ipa test results history.
Can you tell what is the following Python 3 function doing def results_history(history_log, no_color): 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_c...
You are a Python code generator, capable of creating scripts from specifications.
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
Write a Python 3 script to split the history item into log file and optional description.
As a Python code composer, you craft elegant and concise scripts.
hardcoded sets the equivalent working directory if not in git
Make a summary of the following Python 3 code def get_working_dir(script__file__): 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 ...
You are a Python code architect, reviewing and designing scalable and efficient code
get a unique identifier for the machine running this function
How would you explain what the following Python 3 function does def sysidpath(ignore_options=False): # 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_op...
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Write a Python 3 function for splitting a list into size pieces.
As a Python code analyst, you investigate and solve complex coding mysteries
This method returns the NICKNAME of the current user.
Can you generate the documentation for the following Python 3 function def NICKNAME(selfPARAMSDEFAULT_OUTPUT): {params_conditional} kwargs = {param_rest} kwargs = {dict_comp} param_rest = self._make_rest({required}, **kwargs) url = self._basePath + ('{path}').format(**kwargs) ...
You are a Python code architect, reviewing and designing scalable and efficient code
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
Write a Python 3 script to run this to generate the code
You are a Python code generator, capable of creating scripts from specifications.
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'] = ...
Write a Python 3 function for rewriting the 2. 0 json to match what we feed the code for 1. 2
As a python code expert, you are capable of creating scripts from specifications.
Read the import closure and use the local versions of the files.
Explain what the following Python 3 code does def local_imports(remote_base, local_base, ontologies, local_versions=tuple(), readonly=False, dobig=False, revert=False): done = [] triples = set() imported_iri_vs_ontology_iri = {} p = owl.imports oi = b'owl:imports' oo = b'owl:Ontology' def in...
You are a Python code architect, reviewing and designing scalable and efficient code
fix values for ttl
Can you generate the documentation for the following Python 3 function def id_fix(value): 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.startsw...
As a Python code composer, you craft elegant and concise scripts.
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 a Python 3 script to write the current object to a file.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
How would you code a function in Python 3 to take a string and returns a list of strings.
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a predicate object combinator that can be used to defer production of a triple until the missing pieces are supplied and then is supplied.
Can you generate a brief explanation for the following Python 3 code def make_predicate_object_combinator(function, p, o): def predicate_object_combinator(subject): return function(subject, p, o) return predicate_object_combinator
You are a Python code architect, reviewing and designing scalable and efficient code
Yields RDF objects for the given subject and objects_or_combinators.
Explain what the following Python 3 code does def serialize(self, subject, *objects_or_combinators): 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._li...
You are a Python code architect, reviewing and designing scalable and efficient code
update with a query
Can you tell what is the following Python 3 function doing def update_with(self, **query): for k, v in self._filter_attrs(query).items(): setattr(self, k, v) return self.save()
As a Python code analyst, you investigate and solve complex coding mysteries
Filter the attrs dictionary to only include the attributes that are not in the whitelist or in the blacklist.
Explain what the following Python 3 code does def _filter_attrs(cls, attrs): 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__ - cl...
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 script to validate model data and save errors
You are a Python code analyst, evaluating scripts for potential improvements.
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
Implement a function in Python 3 to convert a Penn Treebank tag to a simplified Wordnet tag
You are a Python code architect, reviewing and designing scalable and efficient code
Compute the sentence similarity using Wordnet
Can you generate the documentation for the following Python 3 function def sentence_similarity(sentence1, sentence2): # 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(*t...
As a Python code composer, you craft elegant and concise scripts.
Saves the current state of the object into a pickle file.
Make a summary of the following Python 3 code 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, ...
As a python code expert, you are capable of creating scripts from specifications.
Returns qname of uri in rdflib graph while also saving it
Given the following Python 3 function, write the documentation 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 ...
You are a Python code generator, capable of creating scripts from specifications.
Updates self. g or self. path bc you could only choose 1
Can you generate the documentation for the following Python 3 function 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).suf...
As a Python code translator, you convert algorithms and pseudocode into Python.
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 ...
Write a Python 3 function for iterating through the sparql table and condenses it into a Pandas DataFrame
As a Python code analyst, you investigate and solve complex coding mysteries
Multi funcitonal DataFrame with settings
Can you generate a brief explanation for the following Python 3 code 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: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Adds a prefix to uri mapping in bulk
Can you generate a brief explanation for the following Python 3 code def add_namespaces(self, namespaces: Dict[str, str]) -> None: for prefix, uri in namespaces.items(): self.add_namespace(prefix=prefix, uri=uri)
As a python code expert, you are capable of creating scripts from specifications.
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...
Implement a function in Python 3 to get qualified name of uri in rdflib graph while also saving it
You are a Python code generator, capable of creating scripts from specifications.
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...
Implement a function in Python 3 to add a prefix to uri mapping
As a python code expert, you are capable of creating scripts from specifications.
Finds the prefix of a known uri in the localCOOKIE store.
Explain what the following Python 3 code does def find_prefix(self, iri: Union[URIRef, Literal, str]) -> Union[None, str]: iri = str(iri) max_iri_len = 0 max_prefix = None for prefix, uri in common_namespaces.items(): if uri in iri and max_iri_len < len(uri): # if matched uri...
As a Python code analyst, you investigate and solve complex coding mysteries
Adds an annotation to the graph.
Can you generate the documentation for the following Python 3 function def add_annotation( self, subj: URIRef, pred: URIRef, obj: Union[Literal, URIRef], a_p: URIRef , a_o: Union[Literal, URIRef], ) -> BNode: """ Adds annotation to ...
You are a Python code analyst, evaluating scripts for potential improvements.
Adds triple to Graph
Can you tell what is the following Python 3 function doing 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, predicat...
As a Python code analyst, you investigate and solve complex coding mysteries
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 ...
Write a Python 3 script for adding a namespace to the graph if it does not already exist
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Write a Python 3 function for adding viable uri from iri or expands viable qname to iri to be triple ready
As a Python code composer, you craft elegant and concise scripts.
Takes an entity object and returns the appropriate node type.
Can you generate a brief explanation for the following Python 3 code def process_obj(self, obj: Union[URIRef, Literal, str]) -> Union[URIRef, Literal]: if isinstance(obj, dict) or isinstance(obj, list): exit(str(obj) + ': should be str or intended to be a URIRef or Literal.') if isinstance(...
You are a Python code architect, reviewing and designing scalable and efficient code
Serialize the graph into a string.
How would you explain what the following Python 3 function does def serialize(self, **kwargs) -> str: kwargs = {key: str(value) for key, value in kwargs.items()} return self.g.serialize(**kwargs)
As a Python code translator, you convert algorithms and pseudocode into Python.
Removes a triple from the Graph.
Given the following Python 3 function, write the documentation def remove_triple( self, subj: URIRef, pred: URIRef, obj: Union[URIRef, Literal] ) -> None: """ Removes triple from rdflib Graph You must input the triple in its URIRef or Literal form...
You are a Python code architect, reviewing and designing scalable and efficient code
prints serialized RDFlib Graph
Given the following Python 3 function, write the documentation def print_graph(self, format: str = 'turtle') -> str: print(self.g.serialize(format=format).decode('utf-8'))
You are a Python code analyst, evaluating scripts for potential improvements.
def identifierSearches(self, ids=None, LIMIT=25, _print=True, crawl=False): """parameters( data = "list of term_ids" )""" url_base = self.base_url + '/api/1/term/view/{id}' + '?key=' + self.api_ke...
Can you create a Python 3 function that searches for a list of term ids
As a Python code composer, you craft elegant and concise scripts.
This method searches for ILX.
Can you tell what is the following Python 3 function doing def ilxSearches(self, ilx_ids=None, LIMIT=25, _print=True, crawl=False): """parameters( data = "list of ilx_ids" )""" url_base = self.base_url + "/api/1/ilx/search/i...
As a Python code analyst, you investigate and solve complex coding mysteries
Updates existing entities with new ones.
Here you have a function in Python 3, explain what it does def updateTerms(self, data:list, LIMIT:int=20, _print:bool=True, crawl:bool=False,) -> list: url_base = self.base_url + '/api/1/term/edit/{id}' merged_data = [] # PHP on the server is is LOADED with bugs. Best to just duplicate entity ...
You are a Python code generator, capable of creating scripts from specifications.
Adds terms to the internal state of the object.
Can you tell what is the following Python 3 function doing def addTerms(self, data, LIMIT=25, _print=True, crawl=False): needed = set([ 'label', 'type', ]) url_base = self.base_url + '/api/1/ilx/add' terms = [] for d in data: if (set(list(d)) ...
As a Python code composer, you craft elegant and concise scripts.
Get the list of annotations for a set of term ids
Can you generate the documentation for the following Python 3 function def getAnnotations_via_tid(self, tids, LIMIT=25, _print=True, crawl=False): """ tids = list of term ids that ...
As a Python code composer, you craft elegant and concise scripts.
Get the list of annotations via the ids of the annotations.
Given the following Python 3 function, write the documentation def getAnnotations_via_id(self, annotation_ids, LIMIT=25, _print=True, crawl=False): """tids = list of strings or ints that are t...
You are a Python code architect, reviewing and designing scalable and efficient code
Update the annotations of a specific term.
Can you generate the documentation for the following Python 3 function def updateAnnotations(self, data, LIMIT=25, _print=True, crawl=False,): """data = [{'id', 'tid', 'annotation_tid', 'value', 'comment', 'u...
You are a Python code architect, reviewing and designing scalable and efficient code
def deleteAnnotations(self, annotation_ids, LIMIT=25, _print=True, crawl=False,): """data = list of ids""" url_base = self.base_url + \ '/api/1/term/edit-annotation/{annotation_id}' # id ...
Create a Python 3 function for deleting the specified annotations.
As a Python code translator, you convert algorithms and pseudocode into Python.
def addRelationships( self, data: list, LIMIT: int = 20, _print: bool = True, crawl: bool = False, ) -> list: """ data = [{ "term1_id", "term2_id", "relationship_tid", "term1_version", "term2_version", "relationship_term...
How would you implement a function in Python 3 that adds relationships to the related terms.
You are a Python code generator, capable of creating scripts from specifications.
def deprecate_entity( self, ilx_id: str, note = None, ) -> None: """ Tagged term in interlex to warn this term is no longer used There isn't an proper way to delete a term and so we have to mark it so I can extrapolate that in mysql/ttl loads. Args: ...
How would you implement a function in Python 3 that deprecates an entity in interlex.
As a python code expert, you are capable of creating scripts from specifications.
Force an entity to add a term to InterLex
Can you generate the documentation for the following Python 3 function def force_add_term(self, entity: dict): needed = set([ 'label', 'type', ]) url_ilx_add = self.base_url + '/api/1/ilx/add' url_term_add = self.base_url + '/api/1/term/add' url_term_updat...
You are a Python code architect, reviewing and designing scalable and efficient code
Create a dataframe with query and save it to file.
Can you generate a brief explanation for the following Python 3 code def create_df_file_with_query(self, query, output): chunk_size = 100000 offset = 0 data = defaultdict(lambda : defaultdict(list)) with open(output, 'wb') as outfile: query = query.replace(';', '') ...
You are a Python code generator, capable of creating scripts from specifications.
Returns a list of the differences between two words.
Can you generate a brief explanation for the following Python 3 code def diff(s1, s2): ''' --word-diff=porcelain clone''' delta = difflib.Differ().compare(s1.split(), s2.split()) difflist = [] fullline = '' for line in delta: if line[0] == '?': continue elif line[0] == ' ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Colorize two words in a tree.
Can you generate the documentation for the following Python 3 function def diffcolor(s1, s2): ''' --word-diff=color clone ''' string = '' for line in diff(s1, s2): if line[0] == '-': string += ' ' + TermColors.red(line[2:]) elif line[0] == '+': string += ' ' + TermCol...
You are a Python code generator, capable of creating scripts from specifications.
def create_html(s1, s2, output='test.html'): ''' creates basic html based on the diff of 2 strings ''' html = difflib.HtmlDiff().make_file(s1.split(), s2.split()) with open(output, 'w') as f: f.write(html)
Can you implement a function in Python 3 that creates basic html based on the diff of two strings
You are a Python code analyst, evaluating scripts for potential improvements.
traverse nested list and dicts until key_target equals the current dict key
Can you generate a brief explanation for the following Python 3 code def traverse_data(obj, key_target): ''' will traverse nested list and dicts until key_target equals the current dict key ''' if isinstance(obj, str) and '.json' in str(obj): obj = json.load(open(obj, 'r')) if isinstance(obj, list):...
You are a Python code analyst, evaluating scripts for potential improvements.
returns a json object with the diff color of the two objects
Given the following Python 3 function, write the documentation def json_diff(json1, json2, key_target, get_just_diff=True, porcelain=False): ''' creates a (keyname + diff) key within the json of the same layer which key_target resides. Ex: json1={'definition':'data of key_target'}, json2={'definition':'data...
As a Python code composer, you craft elegant and concise scripts.
def memoryCheck(vms_max_kb): """ Lookup vms_max using getCurrentVMSKb """ safety_factor = 1.2 vms_max = vms_max_kb vms_gigs = vms_max / 1024 ** 2 buffer = safety_factor * vms_max buffer_gigs = buffer / 1024 ** 2 vm = psutil.virtual_memory() free_gigs = vm.available / 1024 ** 2 if vm....
Create a Python 3 function to check if there is enough memory for vms_max_kb
As a Python code composer, you craft elegant and concise scripts.
def _sequence_query(self): """ query all sequence rows """ klass = self.__class__ query = klass.select().where(klass.sequence.is_null(False)) seq_scope_field_names =\ (self.__seq_scope_field_name__ or '').split(',') for name in seq_scope_field_names: ...
Implement a Python 3 function for querying all sequence rows
As a python code expert, you are capable of creating scripts from specifications.
def update_sheet_values(spreadsheet_name, sheet_name, values, spreadsheet_service=None): SPREADSHEET_ID = devconfig.secrets(spreadsheet_name) if spreadsheet_service is None: service = get_oauth_service(readonly=False) ss = service.spreadsheets() else: ss = spreadsheet_service """...
Write a Python 3 script for updating the values of a single spreadsheet.
As a python code expert, you are capable of creating scripts from specifications.