_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q233800 | refresher | train | def refresher(name, refreshers=CompletionRefresher.refreshers):
"""Decorator to add the decorated function to the dictionary of
refreshers. Any function decorated with a @refresher will be executed as
part of the completion refresh routine."""
def wrapper(wrapped):
refreshers[name] = wrapped
... | python | {
"resource": ""
} |
q233801 | CompletionRefresher.refresh | train | def refresh(self, executor, callbacks, completer_options=None):
"""Creates a SQLCompleter object and populates it with the relevant
completion suggestions in a background thread.
executor - SQLExecute object, used to extract the credentials to connect
to the database.
... | python | {
"resource": ""
} |
q233802 | handle_cd_command | train | def handle_cd_command(arg):
"""Handles a `cd` shell command by calling python's os.chdir."""
CD_CMD = 'cd'
tokens = arg.split(CD_CMD + ' ')
directory = tokens[-1] if len(tokens) > 1 else None
if not directory:
return False, "No folder name was provided."
try:
os.chdir(directory)
... | python | {
"resource": ""
} |
q233803 | get_editor_query | train | def get_editor_query(sql):
"""Get the query part of an editor command."""
sql = sql.strip()
# The reason we can't simply do .strip('\e') is that it strips characters,
# not a substring. So it'll strip "e" in the end of the sql also!
# Ex: "select * from style\e" -> "select * from styl".
pattern... | python | {
"resource": ""
} |
q233804 | delete_favorite_query | train | def delete_favorite_query(arg, **_):
"""Delete an existing favorite query.
"""
usage = 'Syntax: \\fd name.\n\n' + favoritequeries.usage
if not arg:
return [(None, None, None, usage)]
status = favoritequeries.delete(arg)
return [(None, None, None, status)] | python | {
"resource": ""
} |
q233805 | execute_system_command | train | def execute_system_command(arg, **_):
"""Execute a system shell command."""
usage = "Syntax: system [command].\n"
if not arg:
return [(None, None, None, usage)]
try:
command = arg.strip()
if command.startswith('cd'):
ok, error_message = handle_cd_command(arg)
... | python | {
"resource": ""
} |
q233806 | need_completion_refresh | train | def need_completion_refresh(queries):
"""Determines if the completion needs a refresh by checking if the sql
statement is an alter, create, drop or change db."""
tokens = {
'use', '\\u',
'create',
'drop'
}
for query in sqlparse.split(queries):
try:
first_... | python | {
"resource": ""
} |
q233807 | is_mutating | train | def is_mutating(status):
"""Determines if the statement is mutating based on the status."""
if not status:
return False
mutating = set(['insert', 'update', 'delete', 'alter', 'create', 'drop',
'replace', 'truncate', 'load'])
return status.split(None, 1)[0].lower() in mutatin... | python | {
"resource": ""
} |
q233808 | AthenaCli.change_prompt_format | train | def change_prompt_format(self, arg, **_):
"""
Change the prompt format.
"""
if not arg:
message = 'Missing required argument, format.'
return [(None, None, None, message)]
self.prompt = self.get_prompt(arg)
return [(None, None, None, "Changed prom... | python | {
"resource": ""
} |
q233809 | AthenaCli.get_output_margin | train | def get_output_margin(self, status=None):
"""Get the output margin (number of rows for the prompt, footer and
timing message."""
margin = self.get_reserved_space() + self.get_prompt(self.prompt).count('\n') + 1
if special.is_timing_enabled():
margin += 1
if status:
... | python | {
"resource": ""
} |
q233810 | AthenaCli.output | train | def output(self, output, status=None):
"""Output text to stdout or a pager command.
The status text is not outputted to pager or files.
The message will be logged in the audit log, if enabled. The
message will be written to the tee file, if enabled. The
message will be written to... | python | {
"resource": ""
} |
q233811 | AthenaCli._on_completions_refreshed | train | def _on_completions_refreshed(self, new_completer):
"""Swap the completer object in cli with the newly created completer.
"""
with self._completer_lock:
self.completer = new_completer
# When cli is first launched we call refresh_completions before
# instantiat... | python | {
"resource": ""
} |
q233812 | AthenaCli.get_reserved_space | train | def get_reserved_space(self):
"""Get the number of lines to reserve for the completion menu."""
reserved_space_ratio = .45
max_reserved_space = 8
_, height = click.get_terminal_size()
return min(int(round(height * reserved_space_ratio)), max_reserved_space) | python | {
"resource": ""
} |
q233813 | AthenaCompleter.find_matches | train | def find_matches(text, collection, start_only=False, fuzzy=True, casing=None):
"""Find completion matches for the given text.
Given the user's input text and a collection of available
completions, find completions matching the last word of the
text.
If `start_only` is True, the t... | python | {
"resource": ""
} |
q233814 | log | train | def log(logger, level, message):
"""Logs message to stderr if logging isn't initialized."""
if logger.parent.name != 'root':
logger.log(level, message)
else:
print(message, file=sys.stderr) | python | {
"resource": ""
} |
q233815 | read_config_file | train | def read_config_file(f):
"""Read a config file."""
if isinstance(f, basestring):
f = os.path.expanduser(f)
try:
config = ConfigObj(f, interpolation=False, encoding='utf8')
except ConfigObjError as e:
log(LOGGER, logging.ERROR, "Unable to parse line {0} of config file "
... | python | {
"resource": ""
} |
q233816 | read_config_files | train | def read_config_files(files):
"""Read and merge a list of config files."""
config = ConfigObj()
for _file in files:
_config = read_config_file(_file)
if bool(_config) is True:
config.merge(_config)
config.filename = _config.filename
return config | python | {
"resource": ""
} |
q233817 | cli_bindings | train | def cli_bindings():
"""
Custom key bindings for cli.
"""
key_binding_manager = KeyBindingManager(
enable_open_in_editor=True,
enable_system_bindings=True,
enable_auto_suggest_bindings=True,
enable_search=True,
enable_abort_and_exit_bindings=True)
@key_binding... | python | {
"resource": ""
} |
q233818 | prompt | train | def prompt(*args, **kwargs):
"""Prompt the user for input and handle any abort exceptions."""
try:
return click.prompt(*args, **kwargs)
except click.Abort:
return False | python | {
"resource": ""
} |
q233819 | SQLExecute.run | train | def run(self, statement):
'''Execute the sql in the database and return the results.
The results are a list of tuples. Each tuple has 4 values
(title, rows, headers, status).
'''
# Remove spaces and EOL
statement = statement.strip()
if not statement: # Empty str... | python | {
"resource": ""
} |
q233820 | SQLExecute.get_result | train | def get_result(self, cursor):
'''Get the current result's data from the cursor.'''
title = headers = None
# cursor.description is not None for queries that return result sets,
# e.g. SELECT or SHOW.
if cursor.description is not None:
headers = [x[0] for x in cursor.d... | python | {
"resource": ""
} |
q233821 | SQLExecute.tables | train | def tables(self):
'''Yields table names.'''
with self.conn.cursor() as cur:
cur.execute(self.TABLES_QUERY)
for row in cur:
yield row | python | {
"resource": ""
} |
q233822 | SQLExecute.table_columns | train | def table_columns(self):
'''Yields column names.'''
with self.conn.cursor() as cur:
cur.execute(self.TABLE_COLUMNS_QUERY % self.database)
for row in cur:
yield row | python | {
"resource": ""
} |
q233823 | create_toolbar_tokens_func | train | def create_toolbar_tokens_func(get_is_refreshing, show_fish_help):
"""
Return a function that generates the toolbar tokens.
"""
token = Token.Toolbar
def get_toolbar_tokens(cli):
result = []
result.append((token, ' '))
if cli.buffers[DEFAULT_BUFFER].always_multiline:
... | python | {
"resource": ""
} |
q233824 | _get_vi_mode | train | def _get_vi_mode(cli):
"""Get the current vi mode for display."""
return {
InputMode.INSERT: 'I',
InputMode.NAVIGATION: 'N',
InputMode.REPLACE: 'R',
InputMode.INSERT_MULTIPLE: 'M'
}[cli.vi_state.input_mode] | python | {
"resource": ""
} |
q233825 | export | train | def export(defn):
"""Decorator to explicitly mark functions that are exposed in a lib."""
globals()[defn.__name__] = defn
__all__.append(defn.__name__)
return defn | python | {
"resource": ""
} |
q233826 | execute | train | def execute(cur, sql):
"""Execute a special command and return the results. If the special command
is not supported a KeyError will be raised.
"""
command, verbose, arg = parse_special_command(sql)
if (command not in COMMANDS) and (command.lower() not in COMMANDS):
raise CommandNotFound
... | python | {
"resource": ""
} |
q233827 | find_prev_keyword | train | def find_prev_keyword(sql):
""" Find the last sql keyword in an SQL statement
Returns the value of the last keyword, and the text of the query with
everything after the last keyword stripped
"""
if not sql.strip():
return None, ''
parsed = sqlparse.parse(sql)[0]
flattened = list(par... | python | {
"resource": ""
} |
q233828 | FilerTeaserPlugin._get_thumbnail_options | train | def _get_thumbnail_options(self, context, instance):
"""
Return the size and options of the thumbnail that should be inserted
"""
width, height = None, None
subject_location = False
placeholder_width = context.get('width', None)
placeholder_height = context.get('h... | python | {
"resource": ""
} |
q233829 | create_image_plugin | train | def create_image_plugin(filename, image, parent_plugin, **kwargs):
"""
Used for drag-n-drop image insertion with djangocms-text-ckeditor.
Set TEXT_SAVE_IMAGE_FUNCTION='cmsplugin_filer_image.integrations.ckeditor.create_image_plugin' to enable.
"""
from cmsplugin_filer_image.models import FilerImage
... | python | {
"resource": ""
} |
q233830 | rename_tables | train | def rename_tables(db, table_mapping, reverse=False):
"""
renames tables from source to destination name, if the source exists and the destination does
not exist yet.
"""
from django.db import connection
if reverse:
table_mapping = [(dst, src) for src, dst in table_mapping]
table_name... | python | {
"resource": ""
} |
q233831 | group_and_sort_statements | train | def group_and_sort_statements(stmt_list, ev_totals=None):
"""Group statements by type and arguments, and sort by prevalence.
Parameters
----------
stmt_list : list[Statement]
A list of INDRA statements.
ev_totals : dict{int: int}
A dictionary, keyed by statement hash (shallow) with ... | python | {
"resource": ""
} |
q233832 | make_stmt_from_sort_key | train | def make_stmt_from_sort_key(key, verb):
"""Make a Statement from the sort key.
Specifically, the sort key used by `group_and_sort_statements`.
"""
def make_agent(name):
if name == 'None' or name is None:
return None
return Agent(name)
StmtClass = get_statement_by_name(v... | python | {
"resource": ""
} |
q233833 | get_ecs_cluster_for_queue | train | def get_ecs_cluster_for_queue(queue_name, batch_client=None):
"""Get the name of the ecs cluster using the batch client."""
if batch_client is None:
batch_client = boto3.client('batch')
queue_resp = batch_client.describe_job_queues(jobQueues=[queue_name])
if len(queue_resp['jobQueues']) == 1:
... | python | {
"resource": ""
} |
q233834 | tag_instances_on_cluster | train | def tag_instances_on_cluster(cluster_name, project='cwc'):
"""Adds project tag to untagged instances in a given cluster.
Parameters
----------
cluster_name : str
The name of the AWS ECS cluster in which running instances
should be tagged.
project : str
The name of the projec... | python | {
"resource": ""
} |
q233835 | submit_reading | train | def submit_reading(basename, pmid_list_filename, readers, start_ix=None,
end_ix=None, pmids_per_job=3000, num_tries=2,
force_read=False, force_fulltext=False, project_name=None):
"""Submit an old-style pmid-centered no-database s3 only reading job.
This function is provide... | python | {
"resource": ""
} |
q233836 | submit_combine | train | def submit_combine(basename, readers, job_ids=None, project_name=None):
"""Submit a batch job to combine the outputs of a reading job.
This function is provided for backwards compatibility. You should use the
PmidSubmitter and submit_combine methods.
"""
sub = PmidSubmitter(basename, readers, proje... | python | {
"resource": ""
} |
q233837 | Submitter.submit_reading | train | def submit_reading(self, input_fname, start_ix, end_ix, ids_per_job,
num_tries=1, stagger=0):
"""Submit a batch of reading jobs
Parameters
----------
input_fname : str
The name of the file containing the ids to be read.
start_ix : int
... | python | {
"resource": ""
} |
q233838 | Submitter.watch_and_wait | train | def watch_and_wait(self, poll_interval=10, idle_log_timeout=None,
kill_on_timeout=False, stash_log_method=None,
tag_instances=False, **kwargs):
"""This provides shortcut access to the wait_for_complete_function."""
return wait_for_complete(self._job_queue, j... | python | {
"resource": ""
} |
q233839 | Submitter.run | train | def run(self, input_fname, ids_per_job, stagger=0, **wait_params):
"""Run this submission all the way.
This method will run both `submit_reading` and `watch_and_wait`,
blocking on the latter.
"""
submit_thread = Thread(target=self.submit_reading,
a... | python | {
"resource": ""
} |
q233840 | PmidSubmitter.set_options | train | def set_options(self, force_read=False, force_fulltext=False):
"""Set the options for this run."""
self.options['force_read'] = force_read
self.options['force_fulltext'] = force_fulltext
return | python | {
"resource": ""
} |
q233841 | get_chebi_name_from_id | train | def get_chebi_name_from_id(chebi_id, offline=False):
"""Return a ChEBI name corresponding to the given ChEBI ID.
Parameters
----------
chebi_id : str
The ChEBI ID whose name is to be returned.
offline : Optional[bool]
Choose whether to allow an online lookup if the local lookup fail... | python | {
"resource": ""
} |
q233842 | get_chebi_name_from_id_web | train | def get_chebi_name_from_id_web(chebi_id):
"""Return a ChEBI mame corresponding to a given ChEBI ID using a REST API.
Parameters
----------
chebi_id : str
The ChEBI ID whose name is to be returned.
Returns
-------
chebi_name : str
The name corresponding to the given ChEBI ID... | python | {
"resource": ""
} |
q233843 | get_subnetwork | train | def get_subnetwork(statements, nodes, relevance_network=None,
relevance_node_lim=10):
"""Return a PySB model based on a subset of given INDRA Statements.
Statements are first filtered for nodes in the given list and other nodes
are optionally added based on relevance in a given network. ... | python | {
"resource": ""
} |
q233844 | _filter_statements | train | def _filter_statements(statements, agents):
"""Return INDRA Statements which have Agents in the given list.
Only statements are returned in which all appearing Agents as in the
agents list.
Parameters
----------
statements : list[indra.statements.Statement]
A list of INDRA Statements t... | python | {
"resource": ""
} |
q233845 | _find_relevant_nodes | train | def _find_relevant_nodes(query_nodes, relevance_network, relevance_node_lim):
"""Return a list of nodes that are relevant for the query.
Parameters
----------
query_nodes : list[str]
A list of node names to query for.
relevance_network : str
The UUID of the NDEx network to query rel... | python | {
"resource": ""
} |
q233846 | process_jsonld_file | train | def process_jsonld_file(fname):
"""Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a lis... | python | {
"resource": ""
} |
q233847 | tag_instance | train | def tag_instance(instance_id, **tags):
"""Tag a single ec2 instance."""
logger.debug("Got request to add tags %s to instance %s."
% (str(tags), instance_id))
ec2 = boto3.resource('ec2')
instance = ec2.Instance(instance_id)
# Remove None's from `tags`
filtered_tags = {k: v for k... | python | {
"resource": ""
} |
q233848 | tag_myself | train | def tag_myself(project='cwc', **other_tags):
"""Function run when indra is used in an EC2 instance to apply tags."""
base_url = "http://169.254.169.254"
try:
resp = requests.get(base_url + "/latest/meta-data/instance-id")
except requests.exceptions.ConnectionError:
logger.warning("Could ... | python | {
"resource": ""
} |
q233849 | get_batch_command | train | def get_batch_command(command_list, project=None, purpose=None):
"""Get the command appropriate for running something on batch."""
command_str = ' '.join(command_list)
ret = ['python', '-m', 'indra.util.aws', 'run_in_batch', command_str]
if not project and has_config('DEFAULT_AWS_PROJECT'):
proj... | python | {
"resource": ""
} |
q233850 | get_jobs | train | def get_jobs(job_queue='run_reach_queue', job_status='RUNNING'):
"""Returns a list of dicts with jobName and jobId for each job with the
given status."""
batch = boto3.client('batch')
jobs = batch.list_jobs(jobQueue=job_queue, jobStatus=job_status)
return jobs.get('jobSummaryList') | python | {
"resource": ""
} |
q233851 | get_job_log | train | def get_job_log(job_info, log_group_name='/aws/batch/job',
write_file=True, verbose=False):
"""Gets the Cloudwatch log associated with the given job.
Parameters
----------
job_info : dict
dict containing entries for 'jobName' and 'jobId', e.g., as returned
by get_jobs()
... | python | {
"resource": ""
} |
q233852 | get_log_by_name | train | def get_log_by_name(log_group_name, log_stream_name, out_file=None,
verbose=True):
"""Download a log given the log's group and stream name.
Parameters
----------
log_group_name : str
The name of the log group, e.g. /aws/batch/job.
log_stream_name : str
The name ... | python | {
"resource": ""
} |
q233853 | dump_logs | train | def dump_logs(job_queue='run_reach_queue', job_status='RUNNING'):
"""Write logs for all jobs with given the status to files."""
jobs = get_jobs(job_queue, job_status)
for job in jobs:
get_job_log(job, write_file=True) | python | {
"resource": ""
} |
q233854 | get_s3_file_tree | train | def get_s3_file_tree(s3, bucket, prefix):
"""Overcome s3 response limit and return NestedDict tree of paths.
The NestedDict object also allows the user to search by the ends of a path.
The tree mimics a file directory structure, with the leave nodes being the
full unbroken key. For example, 'path/to/f... | python | {
"resource": ""
} |
q233855 | SifAssembler.print_model | train | def print_model(self, include_unsigned_edges=False):
"""Return a SIF string of the assembled model.
Parameters
----------
include_unsigned_edges : bool
If True, includes edges with an unknown activating/inactivating
relationship (e.g., most PTMs). Default is Fals... | python | {
"resource": ""
} |
q233856 | SifAssembler.save_model | train | def save_model(self, fname, include_unsigned_edges=False):
"""Save the assembled model's SIF string into a file.
Parameters
----------
fname : str
The name of the file to save the SIF into.
include_unsigned_edges : bool
If True, includes edges with an unk... | python | {
"resource": ""
} |
q233857 | SifAssembler.print_boolean_net | train | def print_boolean_net(self, out_file=None):
"""Return a Boolean network from the assembled graph.
See https://github.com/ialbert/booleannet for details about
the format used to encode the Boolean rules.
Parameters
----------
out_file : Optional[str]
A file n... | python | {
"resource": ""
} |
q233858 | _ensure_api_keys | train | def _ensure_api_keys(task_desc, failure_ret=None):
"""Wrap Elsevier methods which directly use the API keys.
Ensure that the keys are retrieved from the environment or config file when
first called, and store global scope. Subsequently use globally stashed
results and check for required ids.
"""
... | python | {
"resource": ""
} |
q233859 | check_entitlement | train | def check_entitlement(doi):
"""Check whether IP and credentials enable access to content for a doi.
This function uses the entitlement endpoint of the Elsevier API to check
whether an article is available to a given institution. Note that this
feature of the API is itself not available for all institut... | python | {
"resource": ""
} |
q233860 | download_article | train | def download_article(id_val, id_type='doi', on_retry=False):
"""Low level function to get an XML article for a particular id.
Parameters
----------
id_val : str
The value of the id.
id_type : str
The type of id, such as pmid (a.k.a. pubmed_id), doi, or eid.
on_retry : bool
... | python | {
"resource": ""
} |
q233861 | download_article_from_ids | train | def download_article_from_ids(**id_dict):
"""Download an article in XML format from Elsevier matching the set of ids.
Parameters
----------
<id_type> : str
You can enter any combination of eid, doi, pmid, and/or pii. Ids will be
checked in that order, until either content has been found... | python | {
"resource": ""
} |
q233862 | get_abstract | train | def get_abstract(doi):
"""Get the abstract text of an article from Elsevier given a doi."""
xml_string = download_article(doi)
if xml_string is None:
return None
assert isinstance(xml_string, str)
xml_tree = ET.XML(xml_string.encode('utf-8'), parser=UTB())
if xml_tree is None:
re... | python | {
"resource": ""
} |
q233863 | get_article | train | def get_article(doi, output_format='txt'):
"""Get the full body of an article from Elsevier.
Parameters
----------
doi : str
The doi for the desired article.
output_format : 'txt' or 'xml'
The desired format for the output. Selecting 'txt' (default) strips all
xml tags and j... | python | {
"resource": ""
} |
q233864 | extract_paragraphs | train | def extract_paragraphs(xml_string):
"""Get paragraphs from the body of the given Elsevier xml."""
assert isinstance(xml_string, str)
xml_tree = ET.XML(xml_string.encode('utf-8'), parser=UTB())
full_text = xml_tree.find('article:originalText', elsevier_ns)
if full_text is None:
logger.info('C... | python | {
"resource": ""
} |
q233865 | get_dois | train | def get_dois(query_str, count=100):
"""Search ScienceDirect through the API for articles.
See http://api.elsevier.com/content/search/fields/scidir for constructing a
query string to pass here. Example: 'abstract(BRAF) AND all("colorectal
cancer")'
"""
url = '%s/%s' % (elsevier_search_url, quer... | python | {
"resource": ""
} |
q233866 | get_piis | train | def get_piis(query_str):
"""Search ScienceDirect through the API for articles and return PIIs.
Note that ScienceDirect has a limitation in which a maximum of 6,000
PIIs can be retrieved for a given search and therefore this call is
internally broken up into multiple queries by a range of years and the
... | python | {
"resource": ""
} |
q233867 | get_piis_for_date | train | def get_piis_for_date(query_str, date):
"""Search ScienceDirect with a query string constrained to a given year.
Parameters
----------
query_str : str
The query string to search with
date : str
The year to constrain the search to
Returns
-------
piis : list[str]
... | python | {
"resource": ""
} |
q233868 | download_from_search | train | def download_from_search(query_str, folder, do_extract_text=True,
max_results=None):
"""Save raw text files based on a search for papers on ScienceDirect.
This performs a search to get PIIs, downloads the XML corresponding to
the PII, extracts the raw text and then saves the text i... | python | {
"resource": ""
} |
q233869 | CWMSRDFProcessor.extract_statement_from_query_result | train | def extract_statement_from_query_result(self, res):
"""Adds a statement based on one element of a rdflib SPARQL query.
Parameters
----------
res: rdflib.query.ResultRow
Element of rdflib SPARQL query result
"""
agent_start, agent_end, affected_start, affected... | python | {
"resource": ""
} |
q233870 | CWMSRDFProcessor.extract_statements | train | def extract_statements(self):
"""Extracts INDRA statements from the RDF graph via SPARQL queries.
"""
# Look for events that have an AGENT and an AFFECTED, and get the
# start and ending text indices for each.
query = prefixes + """
SELECT
?agent_start
... | python | {
"resource": ""
} |
q233871 | SignorProcessor._recursively_lookup_complex | train | def _recursively_lookup_complex(self, complex_id):
"""Looks up the constitutents of a complex. If any constituent is
itself a complex, recursively expands until all constituents are
not complexes."""
assert complex_id in self.complex_map
expanded_agent_strings = []
expan... | python | {
"resource": ""
} |
q233872 | SignorProcessor._get_complex_agents | train | def _get_complex_agents(self, complex_id):
"""Returns a list of agents corresponding to each of the constituents
in a SIGNOR complex."""
agents = []
components = self._recursively_lookup_complex(complex_id)
for c in components:
db_refs = {}
name = uniprot... | python | {
"resource": ""
} |
q233873 | stmts_from_json | train | def stmts_from_json(json_in, on_missing_support='handle'):
"""Get a list of Statements from Statement jsons.
In the case of pre-assembled Statements which have `supports` and
`supported_by` lists, the uuids will be replaced with references to
Statement objects from the json, where possible. The method ... | python | {
"resource": ""
} |
q233874 | stmts_to_json_file | train | def stmts_to_json_file(stmts, fname):
"""Serialize a list of INDRA Statements into a JSON file.
Parameters
----------
stmts : list[indra.statement.Statements]
The list of INDRA Statements to serialize into the JSON file.
fname : str
Path to the JSON file to serialize Statements into... | python | {
"resource": ""
} |
q233875 | stmts_to_json | train | def stmts_to_json(stmts_in, use_sbo=False):
"""Return the JSON-serialized form of one or more INDRA Statements.
Parameters
----------
stmts_in : Statement or list[Statement]
A Statement or list of Statement objects to serialize into JSON.
use_sbo : Optional[bool]
If True, SBO annota... | python | {
"resource": ""
} |
q233876 | _promote_support | train | def _promote_support(sup_list, uuid_dict, on_missing='handle'):
"""Promote the list of support-related uuids to Statements, if possible."""
valid_handling_choices = ['handle', 'error', 'ignore']
if on_missing not in valid_handling_choices:
raise InputError('Invalid option for `on_missing_support`: \... | python | {
"resource": ""
} |
q233877 | draw_stmt_graph | train | def draw_stmt_graph(stmts):
"""Render the attributes of a list of Statements as directed graphs.
The layout works well for a single Statement or a few Statements at a time.
This function displays the plot of the graph using plt.show().
Parameters
----------
stmts : list[indra.statements.Statem... | python | {
"resource": ""
} |
q233878 | _fix_json_agents | train | def _fix_json_agents(ag_obj):
"""Fix the json representation of an agent."""
if isinstance(ag_obj, str):
logger.info("Fixing string agent: %s." % ag_obj)
ret = {'name': ag_obj, 'db_refs': {'TEXT': ag_obj}}
elif isinstance(ag_obj, list):
# Recursive for complexes and similar.
... | python | {
"resource": ""
} |
q233879 | SparserJSONProcessor.set_statements_pmid | train | def set_statements_pmid(self, pmid):
"""Set the evidence PMID of Statements that have been extracted.
Parameters
----------
pmid : str or None
The PMID to be used in the Evidence objects of the Statements
that were extracted by the processor.
"""
... | python | {
"resource": ""
} |
q233880 | get_args | train | def get_args(node):
"""Return the arguments of a node in the event graph."""
arg_roles = {}
args = node.findall('arg') + \
[node.find('arg1'), node.find('arg2'), node.find('arg3')]
for arg in args:
if arg is not None:
id = arg.attrib.get('id')
if id is not None:
... | python | {
"resource": ""
} |
q233881 | type_match | train | def type_match(a, b):
"""Return True of the types of a and b are compatible, False otherwise."""
# If the types are the same, return True
if a['type'] == b['type']:
return True
# Otherwise, look at some special cases
eq_groups = [
{'ONT::GENE-PROTEIN', 'ONT::GENE', 'ONT::PROTEIN'},
... | python | {
"resource": ""
} |
q233882 | add_graph | train | def add_graph(patterns, G):
"""Add a graph to a set of unique patterns."""
if not patterns:
patterns.append([G])
return
for i, graphs in enumerate(patterns):
if networkx.is_isomorphic(graphs[0], G, node_match=type_match,
edge_match=type_match):
... | python | {
"resource": ""
} |
q233883 | draw | train | def draw(graph, fname):
"""Draw a graph and save it into a file"""
ag = networkx.nx_agraph.to_agraph(graph)
ag.draw(fname, prog='dot') | python | {
"resource": ""
} |
q233884 | build_event_graph | train | def build_event_graph(graph, tree, node):
"""Return a DiGraph of a specific event structure, built recursively"""
# If we have already added this node then let's return
if node_key(node) in graph:
return
type = get_type(node)
text = get_text(node)
label = '%s (%s)' % (type, text)
gra... | python | {
"resource": ""
} |
q233885 | get_extracted_events | train | def get_extracted_events(fnames):
"""Get a full list of all extracted event IDs from a list of EKB files"""
event_list = []
for fn in fnames:
tp = trips.process_xml_file(fn)
ed = tp.extracted_events
for k, v in ed.items():
event_list += v
return event_list | python | {
"resource": ""
} |
q233886 | check_event_coverage | train | def check_event_coverage(patterns, event_list):
"""Calculate the ratio of patterns that were extracted."""
proportions = []
for pattern_list in patterns:
proportion = 0
for pattern in pattern_list:
for node in pattern.nodes():
if node in event_list:
... | python | {
"resource": ""
} |
q233887 | OntologyMapper.map_statements | train | def map_statements(self):
"""Run the ontology mapping on the statements."""
for stmt in self.statements:
for agent in stmt.agent_list():
if agent is None:
continue
all_mappings = []
for db_name, db_id in agent.db_refs.items(... | python | {
"resource": ""
} |
q233888 | load_grounding_map | train | def load_grounding_map(grounding_map_path, ignore_path=None,
lineterminator='\r\n'):
"""Return a grounding map dictionary loaded from a csv file.
In the file pointed to by grounding_map_path, the number of name_space ID
pairs can vary per row and commas are
used to pad out entrie... | python | {
"resource": ""
} |
q233889 | all_agents | train | def all_agents(stmts):
"""Return a list of all of the agents from a list of statements.
Only agents that are not None and have a TEXT entry are returned.
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
Returns
-------
agents : list of :py:class:`indra.stat... | python | {
"resource": ""
} |
q233890 | get_sentences_for_agent | train | def get_sentences_for_agent(text, stmts, max_sentences=None):
"""Returns evidence sentences with a given agent text from a list of statements
Parameters
----------
text : str
An agent text
stmts : list of :py:class:`indra.statements.Statement`
INDRA Statements to search in for evid... | python | {
"resource": ""
} |
q233891 | agent_texts_with_grounding | train | def agent_texts_with_grounding(stmts):
"""Return agent text groundings in a list of statements with their counts
Parameters
----------
stmts: list of :py:class:`indra.statements.Statement`
Returns
-------
list of tuple
List of tuples of the form
(text: str, ((name_space: st... | python | {
"resource": ""
} |
q233892 | ungrounded_texts | train | def ungrounded_texts(stmts):
"""Return a list of all ungrounded entities ordered by number of mentions
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
Returns
-------
ungroundc : list of tuple
list of tuples of the form (text: str, count: int) sorted in ... | python | {
"resource": ""
} |
q233893 | get_agents_with_name | train | def get_agents_with_name(name, stmts):
"""Return all agents within a list of statements with a particular name."""
return [ag for stmt in stmts for ag in stmt.agent_list()
if ag is not None and ag.name == name] | python | {
"resource": ""
} |
q233894 | save_base_map | train | def save_base_map(filename, grouped_by_text):
"""Dump a list of agents along with groundings and counts into a csv file
Parameters
----------
filename : str
Filepath for output file
grouped_by_text : list of tuple
List of tuples of the form output by agent_texts_with_grounding
"... | python | {
"resource": ""
} |
q233895 | protein_map_from_twg | train | def protein_map_from_twg(twg):
"""Build map of entity texts to validate protein grounding.
Looks at the grounding of the entity texts extracted from the statements
and finds proteins where there is grounding to a human protein that maps to
an HGNC name that is an exact match to the entity text. Return... | python | {
"resource": ""
} |
q233896 | save_sentences | train | def save_sentences(twg, stmts, filename, agent_limit=300):
"""Write evidence sentences for stmts with ungrounded agents to csv file.
Parameters
----------
twg: list of tuple
list of tuples of ungrounded agent_texts with counts of the
number of times they are mentioned in the list of sta... | python | {
"resource": ""
} |
q233897 | _get_text_for_grounding | train | def _get_text_for_grounding(stmt, agent_text):
"""Get text context for Deft disambiguation
If the INDRA database is available, attempts to get the fulltext from
which the statement was extracted. If the fulltext is not available, the
abstract is returned. If the indra database is not available, uses th... | python | {
"resource": ""
} |
q233898 | GroundingMapper.update_agent_db_refs | train | def update_agent_db_refs(self, agent, agent_text, do_rename=True):
"""Update db_refs of agent using the grounding map
If the grounding map is missing one of the HGNC symbol or Uniprot ID,
attempts to reconstruct one from the other.
Parameters
----------
agent : :py:clas... | python | {
"resource": ""
} |
q233899 | GroundingMapper.map_agents_for_stmt | train | def map_agents_for_stmt(self, stmt, do_rename=True):
"""Return a new Statement whose agents have been grounding mapped.
Parameters
----------
stmt : :py:class:`indra.statements.Statement`
The Statement whose agents need mapping.
do_rename: Optional[bool]
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.