Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def save_favorite_query(arg, **_): usage = 'Syntax: \\fs name query.\n\n' + favoritequeries.usage if not arg: return [(None, None, None, usage)] name, _, query = arg.partition(' ') # If either name or query is missing then print the usage and ...
[ "Save a new favorite query.\n Returns (title, rows, headers, status)" ]
Please provide a description of the function:def delete_favorite_query(arg, **_): 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)]
[ "Delete an existing favorite query.\n " ]
Please provide a description of the function:def execute_system_command(arg, **_): 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) ...
[ "Execute a system shell command." ]
Please provide a description of the function:def need_completion_refresh(queries): tokens = { 'use', '\\u', 'create', 'drop' } for query in sqlparse.split(queries): try: first_token = query.split()[0] if first_token.lower() in tokens: ...
[ "Determines if the completion needs a refresh by checking if the sql\n statement is an alter, create, drop or change db." ]
Please provide a description of the function:def is_mutating(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 mutating
[ "Determines if the statement is mutating based on the status." ]
Please provide a description of the function:def cli(execute, region, aws_access_key_id, aws_secret_access_key, s3_staging_dir, athenaclirc, profile, database): '''A Athena terminal client with auto-completion and syntax highlighting. \b Examples: - athenacli - athenacli my_database ...
[]
Please provide a description of the function:def change_prompt_format(self, arg, **_): if not arg: message = 'Missing required argument, format.' return [(None, None, None, message)] self.prompt = self.get_prompt(arg) return [(None, None, None, "Changed prompt f...
[ "\n Change the prompt format.\n " ]
Please provide a description of the function:def handle_editor_command(self, cli, document): # FIXME: using application.pre_run_callables like this here is not the best solution. # It's internal api of prompt_toolkit that may change. This was added to fix # https://github.com/dbcli/pgcl...
[ "\n Editor command is any query that is prefixed or suffixed\n by a '\\e'. The reason for a while loop is because a user\n might edit a query multiple times.\n For eg:\n \"select * from \\e\"<enter> to edit it in vim, then come\n back to the prompt with the edited query \"s...
Please provide a description of the function:def run_query(self, query, new_line=True): if (self.destructive_warning and confirm_destructive_query(query) is False): message = 'Wise choice. Command execution stopped.' click.echo(message) return ...
[ "Runs *query*." ]
Please provide a description of the function:def get_output_margin(self, status=None): margin = self.get_reserved_space() + self.get_prompt(self.prompt).count('\n') + 1 if special.is_timing_enabled(): margin += 1 if status: margin += 1 + status.count('\n') ...
[ "Get the output margin (number of rows for the prompt, footer and\n timing message." ]
Please provide a description of the function:def output(self, output, status=None): if output: size = self.cli.output.get_size() margin = self.get_output_margin(status) fits = True buf = [] output_via_pager = self.explicit_pager and special....
[ "Output text to stdout or a pager command.\n The status text is not outputted to pager or files.\n The message will be logged in the audit log, if enabled. The\n message will be written to the tee file, if enabled. The\n message will be written to the output file, if enabled.\n " ...
Please provide a description of the function:def _on_completions_refreshed(self, new_completer): with self._completer_lock: self.completer = new_completer # When cli is first launched we call refresh_completions before # instantiating the cli object. So it is necessa...
[ "Swap the completer object in cli with the newly created completer.\n " ]
Please provide a description of the function:def get_reserved_space(self): reserved_space_ratio = .45 max_reserved_space = 8 _, height = click.get_terminal_size() return min(int(round(height * reserved_space_ratio)), max_reserved_space)
[ "Get the number of lines to reserve for the completion menu." ]
Please provide a description of the function:def list_path(root_dir): res = [] if os.path.isdir(root_dir): for name in os.listdir(root_dir): res.append(name) return res
[ "List directory if exists.\n :param dir: str\n :return: list\n " ]
Please provide a description of the function:def complete_path(curr_dir, last_dir): if not last_dir or curr_dir.startswith(last_dir): return curr_dir elif last_dir == '~': return os.path.join(last_dir, curr_dir)
[ "Return the path to complete that matches the last entered component.\n If the last entered component is ~, expanded path would not\n match, so return all of the available paths.\n :param curr_dir: str\n :param last_dir: str\n :return: str\n " ]
Please provide a description of the function:def parse_path(root_dir): base_dir, last_dir, position = '', '', 0 if root_dir: base_dir, last_dir = os.path.split(root_dir) position = -len(last_dir) if last_dir else 0 return base_dir, last_dir, position
[ "Split path into head and last component for the completer.\n Also return position where last component starts.\n :param root_dir: str path\n :return: tuple of (string, string, int)\n " ]
Please provide a description of the function:def suggest_path(root_dir): if not root_dir: return [os.path.abspath(os.sep), '~', os.curdir, os.pardir] if '~' in root_dir: root_dir = os.path.expanduser(root_dir) if not os.path.exists(root_dir): root_dir, _ = os.path.split(root_d...
[ "List all files and subdirectories in a directory.\n If the directory is not specified, suggest root directory,\n user directory, current and parent directory.\n :param root_dir: string: directory to list\n :return: list\n " ]
Please provide a description of the function:def extend_relations(self, data, kind): # 'data' is a generator object. It can throw an exception while being # consumed. This could happen if the user has launched the app without # specifying a database name. This exception must be handled ...
[ "Extend metadata for tables or views\n :param data: list of (rel_name, ) tuples\n :param kind: either 'tables' or 'views'\n :return:\n " ]
Please provide a description of the function:def extend_columns(self, column_data, kind): # 'column_data' is a generator object. It can throw an exception while # being consumed. This could happen if the user has launched the app # without specifying a database name. This exception must...
[ "Extend column metadata\n :param column_data: list of (rel_name, column_name) tuples\n :param kind: either 'tables' or 'views'\n :return:\n " ]
Please provide a description of the function:def find_matches(text, collection, start_only=False, fuzzy=True, casing=None): last = last_word(text, include='most_punctuations') text = last.lower() completions = [] if fuzzy: regex = '.*?'.join(map(escape, text)) ...
[ "Find completion matches for the given text.\n Given the user's input text and a collection of available\n completions, find completions matching the last word of the\n text.\n If `start_only` is True, the text will match an available\n completion only at the beginning. Otherwise,...
Please provide a description of the function:def find_files(self, word): base_path, last_path, position = parse_path(word) paths = suggest_path(word) for name in sorted(paths): suggestion = complete_path(name, last_path) if suggestion: yield Compl...
[ "Yield matching directory or file names.\n :param word:\n :return: iterable\n " ]
Please provide a description of the function:def populate_scoped_cols(self, scoped_tbls): columns = [] meta = self.dbmetadata for tbl in scoped_tbls: # A fully qualified schema.relname reference or default_schema # DO NOT escape schema names. schema ...
[ "Find all columns in a set of scoped_tables\n :param scoped_tbls: list of (schema, table, alias) tuples\n :return: list of column names\n " ]
Please provide a description of the function:def populate_schema_objects(self, schema, obj_type): metadata = self.dbmetadata[obj_type] schema = schema or self.dbname try: objects = metadata[schema].keys() except KeyError: # schema doesn't exist ...
[ "Returns list of tables or functions for a (optional) schema" ]
Please provide a description of the function:def log(logger, level, message): if logger.parent.name != 'root': logger.log(level, message) else: print(message, file=sys.stderr)
[ "Logs message to stderr if logging isn't initialized." ]
Please provide a description of the function:def read_config_file(f): 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 co...
[ "Read a config file." ]
Please provide a description of the function:def read_config_files(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
[ "Read and merge a list of config files." ]
Please provide a description of the function:def cli_bindings(): 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_bindin...
[ "\n Custom key bindings for cli.\n ", "\n Enable/Disable SmartCompletion Mode.\n ", "\n Enable/Disable Multiline Mode.\n ", "\n Toggle between Vi and Emacs mode.\n ", "\n Force autocompletion at cursor.\n ", "\n Initialize autocompletion...
Please provide a description of the function:def confirm_destructive_query(queries): prompt_text = ("You're about to run a destructive command.\n" "Do you want to proceed? (y/n)") if is_destructive(queries) and sys.stdin.isatty(): return prompt(prompt_text, type=bool)
[ "Check if the query is destructive and prompts the user to confirm.\n Returns:\n * None if the query is non-destructive or we can't prompt the user.\n * True if the query is destructive and the user wants to proceed.\n * False if the query is destructive and the user doesn't want to proceed.\n " ]
Please provide a description of the function:def confirm(*args, **kwargs): try: return click.confirm(*args, **kwargs) except click.Abort: return False
[ "Prompt for confirmation (yes/no) and handle any abort exceptions." ]
Please provide a description of the function:def prompt(*args, **kwargs): try: return click.prompt(*args, **kwargs) except click.Abort: return False
[ "Prompt the user for input and handle any abort exceptions." ]
Please provide a description of the function:def style_factory(name, cli_style): try: style = pygments.styles.get_style_by_name(name) except ClassNotFound: style = pygments.styles.get_style_by_name('native') style_tokens = {} style_tokens.update(style.styles) custom_styles = {s...
[ "Create a Pygments Style class based on the user's preferences.\n :param str name: The name of a built-in Pygments style.\n :param dict cli_style: The user's token-type style preferences.\n " ]
Please provide a description of the function: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.s...
[]
Please provide a description of the function: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: ...
[]
Please provide a description of the function:def tables(self): '''Yields table names.''' with self.conn.cursor() as cur: cur.execute(self.TABLES_QUERY) for row in cur: yield row
[]
Please provide a description of the function: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
[]
Please provide a description of the function:def create_toolbar_tokens_func(get_is_refreshing, show_fish_help): token = Token.Toolbar def get_toolbar_tokens(cli): result = [] result.append((token, ' ')) if cli.buffers[DEFAULT_BUFFER].always_multiline: result.append((to...
[ "\n Return a function that generates the toolbar tokens.\n " ]
Please provide a description of the function:def _get_vi_mode(cli): return { InputMode.INSERT: 'I', InputMode.NAVIGATION: 'N', InputMode.REPLACE: 'R', InputMode.INSERT_MULTIPLE: 'M' }[cli.vi_state.input_mode]
[ "Get the current vi mode for display." ]
Please provide a description of the function:def suggest_type(full_text, text_before_cursor): word_before_cursor = last_word(text_before_cursor, include='many_punctuations') identifier = None # here should be removed once sqlparse has been fixed try: # If we've partially type...
[ "Takes the full_text that is typed so far and also the text before the\n cursor to suggest completion type and scope.\n Returns a tuple with a type of entity ('table', 'column' etc) and a scope.\n A scope for a column category will be a list of tables.\n " ]
Please provide a description of the function:def export(defn): globals()[defn.__name__] = defn __all__.append(defn.__name__) return defn
[ "Decorator to explicitly mark functions that are exposed in a lib." ]
Please provide a description of the function:def run_step(*args, prompt=None): global DRY_RUN cmd = args print(' '.join(cmd)) if skip_step(): print('--- Skipping...') elif DRY_RUN: print('--- Pretending to run...') else: if prompt: print(prompt) ...
[ "\n Prints out the command and asks if it should be run.\n If yes (default), runs it.\n :param args: list of strings (command and args)\n " ]
Please provide a description of the function:def execute(cur, sql): command, verbose, arg = parse_special_command(sql) if (command not in COMMANDS) and (command.lower() not in COMMANDS): raise CommandNotFound try: special_cmd = COMMANDS[command] except KeyError: special_cm...
[ "Execute a special command and return the results. If the special command\n is not supported a KeyError will be raised.\n " ]
Please provide a description of the function:def show_keyword_help(cur, arg): keyword = arg.strip('"').strip("'") query = "help '{0}'".format(keyword) log.debug(query) cur.execute(query) if cur.description and cur.rowcount > 0: headers = [x[0] for x in cur.description] return [(...
[ "\n Call the built-in \"show <command>\", to display help for an SQL keyword.\n :param cur: cursor\n :param arg: string\n :return: list\n " ]
Please provide a description of the function:def last_word(text, include='alphanum_underscore'): if not text: # Empty string return '' if text[-1].isspace(): return '' else: regex = cleanup_regex[include] matches = regex.search(text) if matches: r...
[ "\n Find the last word in a sentence.\n >>> last_word('abc')\n 'abc'\n >>> last_word(' abc')\n 'abc'\n >>> last_word('')\n ''\n >>> last_word(' ')\n ''\n >>> last_word('abc ')\n ''\n >>> last_word('abc def')\n 'def'\n >>> last_word('abc def ')\n ''\n >>> last_word('ab...
Please provide a description of the function:def extract_table_identifiers(token_stream): for item in token_stream: if isinstance(item, IdentifierList): for identifier in item.get_identifiers(): # Sometimes Keywords (such as FROM ) are classified as # identi...
[ "yields tuples of (schema_name, table_name, table_alias)" ]
Please provide a description of the function:def extract_tables(sql): parsed = sqlparse.parse(sql) if not parsed: return [] # INSERT statements must stop looking for tables at the sign of first # Punctuation. eg: INSERT INTO abc (col1, col2) VALUES (1, 2) # abc is the table name, but i...
[ "Extract the table names from an SQL statment.\n Returns a list of (schema, table, alias) tuples\n " ]
Please provide a description of the function:def find_prev_keyword(sql): if not sql.strip(): return None, '' parsed = sqlparse.parse(sql)[0] flattened = list(parsed.flatten()) logical_operators = ('AND', 'OR', 'NOT', 'BETWEEN') for t in reversed(flattened): if t.value == '(' ...
[ " Find the last sql keyword in an SQL statement\n Returns the value of the last keyword, and the text of the query with\n everything after the last keyword stripped\n " ]
Please provide a description of the function:def query_starts_with(query, prefixes): prefixes = [prefix.lower() for prefix in prefixes] formatted_sql = sqlparse.format(query.lower(), strip_comments=True) return bool(formatted_sql) and formatted_sql.split()[0] in prefixes
[ "Check if the query starts with any item from *prefixes*." ]
Please provide a description of the function:def queries_start_with(queries, prefixes): for query in sqlparse.split(queries): if query and query_starts_with(query, prefixes) is True: return True return False
[ "Check if any queries start with any item from *prefixes*." ]
Please provide a description of the function:def _get_thumbnail_options(self, context, instance): width, height = None, None subject_location = False placeholder_width = context.get('width', None) placeholder_height = context.get('height', None) if instance.use_autoscale...
[ "\n Return the size and options of the thumbnail that should be inserted\n " ]
Please provide a description of the function:def create_image_plugin(filename, image, parent_plugin, **kwargs): from cmsplugin_filer_image.models import FilerImage from filer.models import Image image_plugin = FilerImage() image_plugin.placeholder = parent_plugin.placeholder image_plugin.parent...
[ "\n Used for drag-n-drop image insertion with djangocms-text-ckeditor.\n Set TEXT_SAVE_IMAGE_FUNCTION='cmsplugin_filer_image.integrations.ckeditor.create_image_plugin' to enable.\n " ]
Please provide a description of the function:def rename_tables(db, table_mapping, reverse=False): from django.db import connection if reverse: table_mapping = [(dst, src) for src, dst in table_mapping] table_names = connection.introspection.table_names() for source, destination in table_map...
[ "\n renames tables from source to destination name, if the source exists and the destination does\n not exist yet.\n " ]
Please provide a description of the function:def group_and_sort_statements(stmt_list, ev_totals=None): def _count(stmt): if ev_totals is None: return len(stmt.evidence) else: return ev_totals[stmt.get_hash()] stmt_rows = defaultdict(list) stmt_counts = defaultdi...
[ "Group statements by type and arguments, and sort by prevalence.\n\n Parameters\n ----------\n stmt_list : list[Statement]\n A list of INDRA statements.\n ev_totals : dict{int: int}\n A dictionary, keyed by statement hash (shallow) with counts of total\n evidence as the values. Incl...
Please provide a description of the function:def make_stmt_from_sort_key(key, verb): def make_agent(name): if name == 'None' or name is None: return None return Agent(name) StmtClass = get_statement_by_name(verb) inps = list(key[1]) if verb == 'Complex': stmt = ...
[ "Make a Statement from the sort key.\n\n Specifically, the sort key used by `group_and_sort_statements`.\n " ]
Please provide a description of the function:def wait_for_complete(queue_name, job_list=None, job_name_prefix=None, poll_interval=10, idle_log_timeout=None, kill_on_log_timeout=False, stash_log_method=None, tag_instances=False, result_record=None): ...
[ "Return when all jobs in the given list finished.\n\n If not job list is given, return when all jobs in queue finished.\n\n Parameters\n ----------\n queue_name : str\n The name of the queue to wait for completion.\n job_list : Optional[list(dict)]\n A list of jobID-s in a dict, as retu...
Please provide a description of the function:def get_ecs_cluster_for_queue(queue_name, batch_client=None): 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: queue = q...
[ "Get the name of the ecs cluster using the batch client." ]
Please provide a description of the function:def tag_instances_on_cluster(cluster_name, project='cwc'): # Get the relevant instance ids from the ecs cluster ecs = boto3.client('ecs') task_arns = ecs.list_tasks(cluster=cluster_name)['taskArns'] if not task_arns: return tasks = ecs.descri...
[ "Adds project tag to untagged instances in a given cluster.\n\n Parameters\n ----------\n cluster_name : str\n The name of the AWS ECS cluster in which running instances\n should be tagged.\n project : str\n The name of the project to tag instances with.\n " ]
Please provide a description of the function: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): sub = PmidSubmitter(basename, readers, project_na...
[ "Submit an old-style pmid-centered no-database s3 only reading job.\n\n This function is provided for the sake of backward compatibility. It is\n preferred that you use the object-oriented PmidSubmitter and the\n submit_reading job going forward.\n " ]
Please provide a description of the function:def submit_combine(basename, readers, job_ids=None, project_name=None): sub = PmidSubmitter(basename, readers, project_name) sub.job_list = job_ids sub.submit_combine() return sub
[ "Submit a batch job to combine the outputs of a reading job.\n\n This function is provided for backwards compatibility. You should use the\n PmidSubmitter and submit_combine methods.\n " ]
Please provide a description of the function:def create_read_parser(): import argparse parent_read_parser = argparse.ArgumentParser(add_help=False) parent_read_parser.add_argument( 'input_file', help=('Path to file containing input ids of content to read. For the ' 'no-db optio...
[]
Please provide a description of the function:def submit_reading(self, input_fname, start_ix, end_ix, ids_per_job, num_tries=1, stagger=0): # stash this for later. self.ids_per_job = ids_per_job # Upload the pmid_list to Amazon S3 id_list_key = 'reading_re...
[ "Submit a batch of reading jobs\n\n Parameters\n ----------\n input_fname : str\n The name of the file containing the ids to be read.\n start_ix : int\n The line index of the first item in the list to read.\n end_ix : int\n The line index of the la...
Please provide a description of the function:def watch_and_wait(self, poll_interval=10, idle_log_timeout=None, kill_on_timeout=False, stash_log_method=None, tag_instances=False, **kwargs): return wait_for_complete(self._job_queue, job_list=self.job_list, ...
[ "This provides shortcut access to the wait_for_complete_function." ]
Please provide a description of the function:def run(self, input_fname, ids_per_job, stagger=0, **wait_params): submit_thread = Thread(target=self.submit_reading, args=(input_fname, 0, None, ids_per_job), kwargs={'stagger': stagger}, ...
[ "Run this submission all the way.\n\n This method will run both `submit_reading` and `watch_and_wait`,\n blocking on the latter.\n " ]
Please provide a description of the function:def set_options(self, force_read=False, force_fulltext=False): self.options['force_read'] = force_read self.options['force_fulltext'] = force_fulltext return
[ "Set the options for this run." ]
Please provide a description of the function:def get_chebi_name_from_id(chebi_id, offline=False): chebi_name = chebi_id_to_name.get(chebi_id) if chebi_name is None and not offline: chebi_name = get_chebi_name_from_id_web(chebi_id) return chebi_name
[ "Return a ChEBI name corresponding to the given ChEBI ID.\n\n Parameters\n ----------\n chebi_id : str\n The ChEBI ID whose name is to be returned.\n offline : Optional[bool]\n Choose whether to allow an online lookup if the local lookup fails. If\n True, the online lookup is not at...
Please provide a description of the function:def get_chebi_name_from_id_web(chebi_id): url_base = 'http://www.ebi.ac.uk/webservices/chebi/2.0/test/' url_fmt = url_base + 'getCompleteEntity?chebiId=%s' resp = requests.get(url_fmt % chebi_id) if resp.status_code != 200: logger.warning("Got ba...
[ "Return a ChEBI mame corresponding to a given ChEBI ID using a REST API.\n\n Parameters\n ----------\n chebi_id : str\n The ChEBI ID whose name is to be returned.\n\n Returns\n -------\n chebi_name : str\n The name corresponding to the given ChEBI ID. If the lookup\n fails, No...
Please provide a description of the function:def get_subnetwork(statements, nodes, relevance_network=None, relevance_node_lim=10): if relevance_network is not None: relevant_nodes = _find_relevant_nodes(nodes, relevance_network, relevance...
[ "Return a PySB model based on a subset of given INDRA Statements.\n\n Statements are first filtered for nodes in the given list and other nodes\n are optionally added based on relevance in a given network. The filtered\n statements are then assembled into an executable model using INDRA's\n PySB Assembl...
Please provide a description of the function:def _filter_statements(statements, agents): filtered_statements = [] for s in stmts: if all([a is not None for a in s.agent_list()]) and \ all([a.name in agents for a in s.agent_list()]): filtered_statements.append(s) return f...
[ "Return INDRA Statements which have Agents in the given list.\n\n Only statements are returned in which all appearing Agents as in the\n agents list.\n\n Parameters\n ----------\n statements : list[indra.statements.Statement]\n A list of INDRA Statements to filter.\n agents : list[str]\n ...
Please provide a description of the function:def _find_relevant_nodes(query_nodes, relevance_network, relevance_node_lim): all_nodes = relevance_client.get_relevant_nodes(relevance_network, query_nodes) nodes = [n[0] for n in all_nodes[:relevance_node_lim...
[ "Return a list of nodes that are relevant for the query.\n\n Parameters\n ----------\n query_nodes : list[str]\n A list of node names to query for.\n relevance_network : str\n The UUID of the NDEx network to query relevance in.\n relevance_node_lim : int\n The number of top relev...
Please provide a description of the function:def process_jsonld_file(fname): with open(fname, 'r') as fh: json_dict = json.load(fh) return process_jsonld(json_dict)
[ "Process a JSON-LD file in the new format to extract Statements.\n\n Parameters\n ----------\n fname : str\n The path to the JSON-LD file to be processed.\n\n Returns\n -------\n indra.sources.hume.HumeProcessor\n A HumeProcessor instance, which contains a list of INDRA Statements\n ...
Please provide a description of the function:def kill_all(job_queue, reason='None given', states=None): if states is None: states = ['STARTING', 'RUNNABLE', 'RUNNING'] batch = boto3.client('batch') runnable = batch.list_jobs(jobQueue=job_queue, jobStatus='RUNNABLE') job_info = runnable.get(...
[ "Terminates/cancels all RUNNING, RUNNABLE, and STARTING jobs." ]
Please provide a description of the function:def tag_instance(instance_id, **tags): 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 ...
[ "Tag a single ec2 instance." ]
Please provide a description of the function:def tag_myself(project='cwc', **other_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 not connect to service. No...
[ "Function run when indra is used in an EC2 instance to apply tags." ]
Please provide a description of the function:def get_batch_command(command_list, project=None, purpose=None): 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'): project = get_config('DE...
[ "Get the command appropriate for running something on batch." ]
Please provide a description of the function:def get_jobs(job_queue='run_reach_queue', job_status='RUNNING'): batch = boto3.client('batch') jobs = batch.list_jobs(jobQueue=job_queue, jobStatus=job_status) return jobs.get('jobSummaryList')
[ "Returns a list of dicts with jobName and jobId for each job with the\n given status." ]
Please provide a description of the function:def get_job_log(job_info, log_group_name='/aws/batch/job', write_file=True, verbose=False): job_name = job_info['jobName'] job_id = job_info['jobId'] logs = boto3.client('logs') batch = boto3.client('batch') resp = batch.describe_jobs...
[ "Gets the Cloudwatch log associated with the given job.\n\n Parameters\n ----------\n job_info : dict\n dict containing entries for 'jobName' and 'jobId', e.g., as returned\n by get_jobs()\n log_group_name : string\n Name of the log group; defaults to '/aws/batch/job'\n write_fil...
Please provide a description of the function:def get_log_by_name(log_group_name, log_stream_name, out_file=None, verbose=True): logs = boto3.client('logs') kwargs = {'logGroupName': log_group_name, 'logStreamName': log_stream_name, 'startFromHead': True} ...
[ "Download a log given the log's group and stream name.\n\n Parameters\n ----------\n log_group_name : str\n The name of the log group, e.g. /aws/batch/job.\n\n log_stream_name : str\n The name of the log stream, e.g. run_reach_jobdef/default/<UUID>\n\n Returns\n -------\n lines : ...
Please provide a description of the function:def dump_logs(job_queue='run_reach_queue', job_status='RUNNING'): jobs = get_jobs(job_queue, job_status) for job in jobs: get_job_log(job, write_file=True)
[ "Write logs for all jobs with given the status to files." ]
Please provide a description of the function:def get_s3_file_tree(s3, bucket, prefix): def get_some_keys(keys, marker=None): if marker: relevant_files = s3.list_objects(Bucket=bucket, Prefix=prefix, Marker=marker) else: releva...
[ "Overcome s3 response limit and return NestedDict tree of paths.\n\n The NestedDict object also allows the user to search by the ends of a path.\n\n The tree mimics a file directory structure, with the leave nodes being the\n full unbroken key. For example, 'path/to/file.txt' would be retrieved by\n\n ...
Please provide a description of the function:def make_model(self, use_name_as_key=False, include_mods=False, include_complexes=False): self.graph = nx.DiGraph() self._use_name_as_key = use_name_as_key for st in self.stmts: support_all = len(st.evidence) ...
[ "Assemble the graph from the assembler's list of INDRA Statements.\n\n Parameters\n ----------\n use_name_as_key : boolean\n If True, uses the name of the agent as the key to the nodes in\n the network. If False (default) uses the matches_key() of the\n agent.\n...
Please provide a description of the function:def print_model(self, include_unsigned_edges=False): sif_str = '' for edge in self.graph.edges(data=True): n1 = edge[0] n2 = edge[1] data = edge[2] polarity = data.get('polarity') if polarit...
[ "Return a SIF string of the assembled model.\n\n Parameters\n ----------\n include_unsigned_edges : bool\n If True, includes edges with an unknown activating/inactivating\n relationship (e.g., most PTMs). Default is False.\n " ]
Please provide a description of the function:def save_model(self, fname, include_unsigned_edges=False): sif_str = self.print_model(include_unsigned_edges) with open(fname, 'wb') as fh: fh.write(sif_str.encode('utf-8'))
[ "Save the assembled model's SIF string into a file.\n\n Parameters\n ----------\n fname : str\n The name of the file to save the SIF into.\n include_unsigned_edges : bool\n If True, includes edges with an unknown activating/inactivating\n relationship (e....
Please provide a description of the function:def print_loopy(self, as_url=True): init_str = '' node_id = 1 node_list = {} for node, data in self.graph.nodes(data=True): node_name = data['name'] nodex = int(500*numpy.random.rand()) nodey = int(...
[ "Return \n\n Parameters\n ----------\n out_file : Optional[str]\n A file name in which the Loopy network is saved.\n\n Returns\n -------\n full_str : str\n The string representing the Loopy network.\n " ]
Please provide a description of the function:def print_boolean_net(self, out_file=None): init_str = '' for node_key in self.graph.nodes(): node_name = self.graph.node[node_key]['name'] init_str += '%s = False\n' % node_name rule_str = '' for node_key in s...
[ "Return a Boolean network from the assembled graph.\n\n See https://github.com/ialbert/booleannet for details about\n the format used to encode the Boolean rules.\n\n Parameters\n ----------\n out_file : Optional[str]\n A file name in which the Boolean network is saved....
Please provide a description of the function:def _ensure_api_keys(task_desc, failure_ret=None): def check_func_wrapper(func): @wraps(func) def check_api_keys(*args, **kwargs): global ELSEVIER_KEYS if ELSEVIER_KEYS is None: ELSEVIER_KEYS = {} ...
[ "Wrap Elsevier methods which directly use the API keys.\n\n Ensure that the keys are retrieved from the environment or config file when\n first called, and store global scope. Subsequently use globally stashed\n results and check for required ids.\n " ]
Please provide a description of the function:def check_entitlement(doi): if doi.lower().startswith('doi:'): doi = doi[4:] url = '%s/%s' % (elsevier_entitlement_url, doi) params = {'httpAccept': 'text/xml'} res = requests.get(url, params, headers=ELSEVIER_KEYS) if not res.status_code == ...
[ "Check whether IP and credentials enable access to content for a doi.\n\n This function uses the entitlement endpoint of the Elsevier API to check\n whether an article is available to a given institution. Note that this\n feature of the API is itself not available for all institution keys.\n " ]
Please provide a description of the function:def download_article(id_val, id_type='doi', on_retry=False): if id_type == 'pmid': id_type = 'pubmed_id' url = '%s/%s' % (elsevier_article_url_fmt % id_type, id_val) params = {'httpAccept': 'text/xml'} res = requests.get(url, params, headers=ELSE...
[ "Low level function to get an XML article for a particular id.\n\n Parameters\n ----------\n id_val : str\n The value of the id.\n id_type : str\n The type of id, such as pmid (a.k.a. pubmed_id), doi, or eid.\n on_retry : bool\n This function has a recursive retry feature, and th...
Please provide a description of the function:def download_article_from_ids(**id_dict): valid_id_types = ['eid', 'doi', 'pmid', 'pii'] assert all([k in valid_id_types for k in id_dict.keys()]),\ ("One of these id keys is invalid: %s Valid keys are: %s." % (list(id_dict.keys()), valid_id_typ...
[ "Download an article in XML format from Elsevier matching the set of ids.\n\n Parameters\n ----------\n <id_type> : str\n You can enter any combination of eid, doi, pmid, and/or pii. Ids will be\n checked in that order, until either content has been found or all ids\n have been checked...
Please provide a description of the function:def get_abstract(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: return None coredata ...
[ "Get the abstract text of an article from Elsevier given a doi." ]
Please provide a description of the function:def get_article(doi, output_format='txt'): xml_string = download_article(doi) if output_format == 'txt' and xml_string is not None: text = extract_text(xml_string) return text return xml_string
[ "Get the full body of an article from Elsevier.\n\n Parameters\n ----------\n doi : str\n The doi for the desired article.\n output_format : 'txt' or 'xml'\n The desired format for the output. Selecting 'txt' (default) strips all\n xml tags and joins the pieces of text in the main t...
Please provide a description of the function:def extract_paragraphs(xml_string): 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('Could not find fu...
[ "Get paragraphs from the body of the given Elsevier xml." ]
Please provide a description of the function:def get_dois(query_str, count=100): url = '%s/%s' % (elsevier_search_url, query_str) params = {'query': query_str, 'count': count, 'httpAccept': 'application/xml', 'sort': '-coverdate', 'field': 'doi'} ...
[ "Search ScienceDirect through the API for articles.\n\n See http://api.elsevier.com/content/search/fields/scidir for constructing a\n query string to pass here. Example: 'abstract(BRAF) AND all(\"colorectal\n cancer\")'\n " ]
Please provide a description of the function:def get_piis(query_str): dates = range(1960, datetime.datetime.now().year) all_piis = flatten([get_piis_for_date(query_str, date) for date in dates]) return all_piis
[ "Search ScienceDirect through the API for articles and return PIIs.\n\n Note that ScienceDirect has a limitation in which a maximum of 6,000\n PIIs can be retrieved for a given search and therefore this call is\n internally broken up into multiple queries by a range of years and the\n results are combin...
Please provide a description of the function:def get_piis_for_date(query_str, date): count = 200 params = {'query': query_str, 'count': count, 'start': 0, 'sort': '-coverdate', 'date': date, 'field': 'pii'} all_piis = [] while Tr...
[ "Search ScienceDirect with a query string constrained to a given year.\n\n Parameters\n ----------\n query_str : str\n The query string to search with\n date : str\n The year to constrain the search to\n\n Returns\n -------\n piis : list[str]\n The list of PIIs identifying ...
Please provide a description of the function:def download_from_search(query_str, folder, do_extract_text=True, max_results=None): piis = get_piis(query_str) for pii in piis[:max_results]: if os.path.exists(os.path.join(folder, '%s.txt' % pii)): continue ...
[ "Save raw text files based on a search for papers on ScienceDirect.\n\n This performs a search to get PIIs, downloads the XML corresponding to\n the PII, extracts the raw text and then saves the text into a file\n in the designated folder.\n\n Parameters\n ----------\n query_str : str\n The...
Please provide a description of the function:def extract_statement_from_query_result(self, res): agent_start, agent_end, affected_start, affected_end = res # Convert from rdflib literals to python integers so we can use # them to index strings agent_start = int(agent_start) ...
[ "Adds a statement based on one element of a rdflib SPARQL query.\n\n Parameters\n ----------\n res: rdflib.query.ResultRow\n Element of rdflib SPARQL query result\n " ]
Please provide a description of the function:def extract_statements(self): # Look for events that have an AGENT and an AFFECTED, and get the # start and ending text indices for each. query = prefixes + results = self.graph.query(query) for res in results: #...
[ "Extracts INDRA statements from the RDF graph via SPARQL queries.\n ", "\n SELECT\n ?agent_start\n ?agent_end\n ?affected_start\n ?affected_end\n WHERE {\n ?rel role:AGENT ?agent .\n ?rel role:AFFECTED ?affected .\n ...
Please provide a description of the function:def _recursively_lookup_complex(self, complex_id): assert complex_id in self.complex_map expanded_agent_strings = [] expand_these_next = [complex_id] while len(expand_these_next) > 0: # Pop next element c = ex...
[ "Looks up the constitutents of a complex. If any constituent is\n itself a complex, recursively expands until all constituents are\n not complexes." ]
Please provide a description of the function:def _get_complex_agents(self, complex_id): agents = [] components = self._recursively_lookup_complex(complex_id) for c in components: db_refs = {} name = uniprot_client.get_gene_name(c) if name is None: ...
[ "Returns a list of agents corresponding to each of the constituents\n in a SIGNOR complex." ]
Please provide a description of the function:def stmts_from_json(json_in, on_missing_support='handle'): stmts = [] uuid_dict = {} for json_stmt in json_in: try: st = Statement._from_json(json_stmt) except Exception as e: logger.warning("Error creating statement:...
[ "Get a list of Statements from Statement jsons.\n\n In the case of pre-assembled Statements which have `supports` and\n `supported_by` lists, the uuids will be replaced with references to\n Statement objects from the json, where possible. The method of handling\n missing support is controled by the `on_...
Please provide a description of the function:def stmts_to_json_file(stmts, fname): with open(fname, 'w') as fh: json.dump(stmts_to_json(stmts), fh, indent=1)
[ "Serialize a list of INDRA Statements into a JSON file.\n\n Parameters\n ----------\n stmts : list[indra.statement.Statements]\n The list of INDRA Statements to serialize into the JSON file.\n fname : str\n Path to the JSON file to serialize Statements into.\n " ]