seed
stringlengths
1
14k
source
stringclasses
2 values
def env_config() -> dict: """ Configures a database connection using an environment variable (Oracle and PostgreSQL only). :return: A dictionary containing information about the newly-created database connection. """ env_var = input( "\nIdentify the name of the environment variable the conn...
bigcode/self-oss-instruct-sc2-concepts
def find_sub_list(sub_list, main_list): """Find starting and ending position of a sublist in a longer list. Args: sub_list (list): sublist main_list (list): main longer list Returns: (int, int): start and end index in the list l. Returns None if sublist is not found in the main lis...
bigcode/self-oss-instruct-sc2-concepts
def roman_event(date): """Return the event of Roman date 'date'.""" return date[2]
bigcode/self-oss-instruct-sc2-concepts
import copy def strip_revision_in_copy(doc_map): """ Strip the _rev field in a deep copy of doc_map and return it. :param dict doc_map: A dict representation of a JSON document. :return: doc_map itself without _rev """ new_doc = copy.deepcopy(doc_map) new_doc.pop("_rev", None) return new_doc
bigcode/self-oss-instruct-sc2-concepts
def checkpoint2epoch(_checkpoint_name: str) -> int: """ Args: _checkpoint_name: e.g. 'epoch=2.ckpt' or 'epoch=2_v0.ckpt' Returns: _epoch: e.g. 2 """ return int(_checkpoint_name.split("epoch=")[-1].split("_")[0].replace(".ckpt", ""))
bigcode/self-oss-instruct-sc2-concepts
import re def is_ssh_destination(string) -> bool: """Check if string is a (more or less) valid SSH address (user@host:...).""" return bool(re.match(r'([^\s]+)@([^\s]+):(.*)', string))
bigcode/self-oss-instruct-sc2-concepts
def manual(path, value): # pylint: disable=W0613 """ Dummy function that returns it's input For tools that cannot be read automatically use a value from the toolkit file Parameters ---------- path : str Ignored value : str The value to return Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
def uppercase(s: str) -> str: """ Convert a string to uppercase. Args: s (str): The string to be converted. Returns: str: The converted uppercase string. Example: >>> uppercase('completely different') == 'COMPLETELY DIFFERENT' True """ return s.upper()
bigcode/self-oss-instruct-sc2-concepts
def get_text_hv(angle): """Returns (ha, va) text horizontal and vertical alignment for line label. This makes the line label text inside its area, assuming areas closed CW. Args: angle (float): line normal vector in degrees, between 180 and -180 """ horiz, vert = ('', '') if abs(angle)...
bigcode/self-oss-instruct-sc2-concepts
def _incrementResourceVersion(version): """ Pyrsistent transformation function which can increment a ``v1.ObjectMeta.resourceVersion`` value (even if it was missing). :param version: The old version as a ``unicode`` string or ``None`` if there wasn't one. :return unicode: The new version, ...
bigcode/self-oss-instruct-sc2-concepts
def load_words(file_name): """ file_name (string): the name of the file containing the list of words to load Returns: a list of valid words. Words are strings of lowercase letters Depending on the size of the word list, this function may take a while """ print("Loading word list from file.....
bigcode/self-oss-instruct-sc2-concepts
import yaml def load_yaml(file_path): """ Load a yaml file. Handles doc separation by loading all and combining into common dict. """ docs = yaml.load_all(open(file_path,'r',encoding='utf-8'),Loader=yaml.SafeLoader) data = {} for doc in docs: for key in doc: if key not in data: data[key] = doc[key] e...
bigcode/self-oss-instruct-sc2-concepts
def calc_frip(bamfile, ftfile, frip_func, pipeline_manager, aligned_reads_key="Aligned_reads"): """ Calculate the fraction of reads in feature file. Use the given function and data from an aligned reads file and a features file, along with a PipelineManager, to calculate. :param str...
bigcode/self-oss-instruct-sc2-concepts
def binconv(fp, fp_len): """ Converts 0 to -1 in the tokens' hashes to facilitate merging of the tokens' hashes later on. input : 1001...1 output : [1,-1,-1, 1, ... , 1] """ vec = [1] * fp_len for indx, b in enumerate(fp): if b == '0': vec[indx] = -1 return vec
bigcode/self-oss-instruct-sc2-concepts
import re def remove_stop_words(stop_words, text): """ Description Parameters: ---------------- stop_words: list List of strings to remove text: string String to process Returns: ---------------- filtered: string String with stop words removed """ ...
bigcode/self-oss-instruct-sc2-concepts
def get_modified_fields(old_values, new_values): """ Return all fields that have been modified from original fields """ field_changes = {} for key, value in new_values.items(): try: original_value = old_values[key] except KeyError: """If there are addtional ...
bigcode/self-oss-instruct-sc2-concepts
def tokenize(text, nlp): """Word tokenize a single string. Parameters ---------- x: str A piece of text to tokenize. nlp: spacy tokenizer, e.g. spacy.lang.en.English By default, a spacy tokenizer with a small English vocabulary is used. NER, parsing, and tagging are disabled...
bigcode/self-oss-instruct-sc2-concepts
def load_dfa(path_to_dfa_file): """ This function reads the DFA in the specified file and returns a data structure representing it. It is up to you to choose an appropriate data structure. The returned DFA will be used by your accepts_word function. Consider using a tuple to hold the parts o...
bigcode/self-oss-instruct-sc2-concepts
def test_mask_none(dqarr, bitmask): """ Probes 'dqarr' to see whether NONE OF the bits in the specified mask are raised. :Parameters: dqarr: numpy array which represents a dq plane (or part of it). bitmask: integer A bit mask specifying any of the bits...
bigcode/self-oss-instruct-sc2-concepts
def get_layer_set(layer: str) -> str: """Layers in the same layer set share a config. Args: layer: Full name of the layer. This will be the PyTorch or Opacus name of the layer in lower case (e.g. linear, rnn, dprnn), prefixed with gsm_ (e.g. gsm_linear, gsm_dprnn) if DP is enabled. Mult...
bigcode/self-oss-instruct-sc2-concepts
def get_context(token_ids, target_position, sequence_length=128): """ Given a text containing a target word, return the sentence snippet which surrounds the target word (and the target word's position in the snippet). :param token_ids: list of token ids (for an entire line of text) :param target_po...
bigcode/self-oss-instruct-sc2-concepts
def get_optional_option(config, section, option): """Return an option from a ConfigParser, or None if it doesn't exist.""" if config.has_option(section, option): return config.get(section, option) return None
bigcode/self-oss-instruct-sc2-concepts
def collect_subset_scores(scorer_list, metric_name, tag_list, reset=False): """ Get the scorer measures of each tag. This function is only used by tasks that need evalute results on tags, and should be called in get_metrics. Parameters: scorer_list: a list of N_tag scorer object met...
bigcode/self-oss-instruct-sc2-concepts
def _blocks_changed(block1, block2): """ Compare two Block objects Args: block1: The first block to compare block2: The second block to compare Returns: True if the provided blocks are different, False otherwise """ if block1.name != block2.name: return True ...
bigcode/self-oss-instruct-sc2-concepts
import copy import collections def stringify_keys(dictionary: dict): """ This helper function will stringify all keys in the given dictionary. For example: > from apps.authentication.models.user import Jobs > data = { Jobs.PTA: True } > stringify_keys(data) { "PTA": Tr...
bigcode/self-oss-instruct-sc2-concepts
import torch def gaussian_discrete_erf(window_size, sigma): """ Discrete Gaussian by interpolating the error function. Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py """ device = sigma.device if isinstance(sigma, torch.Tensor) else None...
bigcode/self-oss-instruct-sc2-concepts
def get_id(vmfObject, idPropName='id'): """ Returns the ID of the given VMF object. """ return int(vmfObject[idPropName])
bigcode/self-oss-instruct-sc2-concepts
import collections def build_toc_item(title, path=None, sub_items=None): """Create an item in the TOC. Args: title (str) - Title for this item. path (str) - Path to the page for this item. sub_items (list) - Items to place in a collapsible subsection. """ item = collections.OrderedD...
bigcode/self-oss-instruct-sc2-concepts
import importlib def load_class(str_full_type): """ Load a python class given full qualified name. """ type_s = str_full_type.split('.') mod = importlib.import_module('.'.join(type_s[:-1])) cls = getattr(mod, type_s[-1]) return cls
bigcode/self-oss-instruct-sc2-concepts
def convert_hex_to_rgb_255(hex_str): """Convert hex color to rgb in range 0-255.""" hex_color = hex_str.lstrip("#") n = len(hex_color) rgb = list(int(hex_color[i : i + int(n / 3)], 16) for i in range(0, int(n), int(n / 3))) return rgb
bigcode/self-oss-instruct-sc2-concepts
from typing import List def nd_slice(d: int, dim: int = 0, start: int = 0, end: int = 1) -> List[slice]: """Create a multi-dimensional slice. Args: d (int): number of dimensions dim (int, optional): target dimension that will be sliced. Defaults to 0. start (int, optional): start inde...
bigcode/self-oss-instruct-sc2-concepts
def filter_interface_conf(c): """Determine if an interface configuration string is relevant.""" c = c.strip() if c.startswith("!"): return False if c.startswith("version "): return False if c.startswith("interface"): return False if not c: return False return ...
bigcode/self-oss-instruct-sc2-concepts
import torch def assemble_recon_data(heldin, heldin_forward, heldout, heldout_forward): """Combines heldin/heldout and observed/forward data into a single tensor. Parameters ---------- heldin : torch.Tensor A BxTxN tensor. heldin_forward : torch.Tensor A BxT_FWDxN tensor. ...
bigcode/self-oss-instruct-sc2-concepts
def _quote(filename, protect = "="): """Quote the filename, by escaping = by \\= and \\ by \\\\""" return filename.replace("\\", "\\\\").replace(protect, "\\" + protect)
bigcode/self-oss-instruct-sc2-concepts
def fully_qualified_name(type_: type) -> str: """Construct the fully qualified name of a type.""" return getattr(type_, '__module__', '') + '.' + getattr(type_, '__qualname__', '')
bigcode/self-oss-instruct-sc2-concepts
def is_passed_counting_roi(current_point, first_point, roi_polygon, roi_outside, is_enter): """ will check if the point passed the counting roi. if the current location in the roi and the first location not in the roi - it passed if the current location not in the roi and the first location in the roi - it ...
bigcode/self-oss-instruct-sc2-concepts
def _capped_double_heads(num_heads, cap=16): """Calculate the number of heads for the attention layers with more heads. The number of heads will be twice the normal amount (num_heads), until it reaches |cap| heads. Args: num_heads: the num_heads hparam for the model. cap: the maximum number of heads |...
bigcode/self-oss-instruct-sc2-concepts
def is_only_preceded_by(string: str, to_find: str, preceded: str) -> bool: """ check if an element in a string is only preceded by the indicated character, even multiple times. Raise an ValueError if to_find is not found :param string: the string to search in :param to_find: the string to searc...
bigcode/self-oss-instruct-sc2-concepts
def sub_block_values(config, key): """Extract set of values associated with a sub block key Parameters ---------- config : str Path of the config file. key : str Sub block key (e.g. "SubCategory") Returns ------- set(str) Unique values of the given key """ ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def _get_file_sha256_hash(file_path): """ Takes a file and returns the SHA 256 hash of its data Args: file_path (str): path of file to hash Returns: (str) """ sha256hash = hashlib.sha256() chunk_size = 8192 with open(file_path, "rb") as f: while True: ...
bigcode/self-oss-instruct-sc2-concepts
def chrome_options(chrome_options, create_tmp_dir): """Set configuration to run Chrome with specific options.""" prefs = {"download.default_directory": create_tmp_dir, "download.prompt_for_download": False} chrome_options.add_experimental_option("prefs", prefs) return chrome_options
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def solve_part2(identified: Dict[str, str]) -> str: """ identified: 'eggs': 'hn', 'fish': 'dgsdtj', 'nuts': 'kpksf', 'peanuts': 'sjcvsr', 'sesame': 'bstzgn', 'shellfish': 'kmmqmv', 'soy': 'vkdxfj', 'wheat': 'bsfqgb' Solution: hn,dgsdtj,kpksf,s...
bigcode/self-oss-instruct-sc2-concepts
def _list_info(candidate_element): """Log element id, title or placeholder """ outer_html = candidate_element.get_attribute('outerHTML') if outer_html != '' or outer_html is not None: return "OuterHTML: {}".format(outer_html) return candidate_element
bigcode/self-oss-instruct-sc2-concepts
def parse_cdk_file(file): """ Function to parse CDK output Parameters ---------- file : str file to parse the chemical descriptors from Returns ------- dict dictionary containing the chemical descriptor name and the chemical descriptor value """ cdk_file...
bigcode/self-oss-instruct-sc2-concepts
def _normalise(s): """ Normalise the supplied string in the following ways: 1. String excess whitespace 2. cast to lower case 3. Normalise all internal spacing :param s: string to be normalised :return: normalised string """ if s is None: return "" s = s.strip().lower()...
bigcode/self-oss-instruct-sc2-concepts
import six def inclusion_only_unlimited_args_from_template(*args): """Expected inclusion_only_unlimited_args_from_template __doc__""" return { "result": "inclusion_only_unlimited_args_from_template - Expected result: %s" % ( ', '.join(six.text_type(arg) for arg in args) ) }
bigcode/self-oss-instruct-sc2-concepts
import warnings def no_of_events(tweet_file, t_observation, t_prediction, time_factor=1): """ calculate the number of retweets at the observation time (=t_observation) and at the final time of prediction (=t_prediction) :param tweet_file: data file :param t_observation: observation time :param t_p...
bigcode/self-oss-instruct-sc2-concepts
def option_str_list(argument): """ An option validator for parsing a comma-separated option argument. Similar to the validators found in `docutils.parsers.rst.directives`. """ if argument is None: raise ValueError("argument required but none supplied") else: return [s.strip() fo...
bigcode/self-oss-instruct-sc2-concepts
def discard_empty(s: str) -> bool: """Return true if the provided string is non-empty.""" if s: return True return False
bigcode/self-oss-instruct-sc2-concepts
def calcDistance(ent1, ent2): """ Calculate the distance between two entities """ dimensionDelta = (ent1.dimension-ent2.dimension) * 1000 deltaPos = [ent1.pos[a]-ent2.pos[a] for a in (0, 1)] return (deltaPos[0]**2 + deltaPos[1]**2)**0.5 + dimensionDelta
bigcode/self-oss-instruct-sc2-concepts
import torch def create_batch_from_data_list(data_list): """Given a list of datapoints, create a batch. Args: data_list (list): List of items returned by SceneRenderDataset. """ imgs = [] azimuths = [] elevations = [] for data_item in data_list: img, render_params = data_i...
bigcode/self-oss-instruct-sc2-concepts
import io def _encode_image(image_array, fmt): """encodes an (numpy) image array to string. Args: image_array: (numpy) image array fmt: image format to use Returns: encoded image string """ from PIL import Image # pylint: disable=g-import-not-at-top pil_image = Image.fromarray(image_array) ...
bigcode/self-oss-instruct-sc2-concepts
from typing import AnyStr def detect_space_after(txt: AnyStr, end: int): """Given text and an end index returns True if there is a space after the end index, false otherwise. Parameters ---------- txt : str the text itself. end : int the end index of the token. Returns ...
bigcode/self-oss-instruct-sc2-concepts
def split_file_name(file_absolute_name): """ Splits a file name into: [directory, name, extension] :param full_name_template: :return: """ split_template = file_absolute_name.split('/') [name, extension] = split_template[-1].split('.') directory = "/".join(split_template[0: len(split_te...
bigcode/self-oss-instruct-sc2-concepts
import json import hashlib def get_hash(block): """ Creates a SHA-256 hash of a Block :param block: Block """ # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes block_string = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(block_string)...
bigcode/self-oss-instruct-sc2-concepts
def return_ttl(name: str) -> int: """ **return_ttl** returns ttl for cache depending on long, short, and medium :param name: string -> period = short, medium, long :return: int -> time to live """ cache_ttl_short: int = 1800 # (60*60 * 0.5) 30 minutes cache_ttl_medium: int ...
bigcode/self-oss-instruct-sc2-concepts
import json def get_filtered_keys_from_map(key_map, payload): """ Filter the payload for the given keylist and return the filtered dict :param key_list: a json old_key:new_key map in string format :param payload: dict payload which needs to be filtered :return: dict with new_key, value pair based ...
bigcode/self-oss-instruct-sc2-concepts
def chunk_string(input_str, length): """ Splits a string in to smaller chunks. NOTE: http://stackoverflow.com/questions/18854620/ :param input_str: str the input string to chunk. :param length: int the length of each chunk. :return: list of input str chunks. """ return list((input_str[...
bigcode/self-oss-instruct-sc2-concepts
def transform_table(table): """ Unsqueeze keys aligning with values Args: table: table defining key-value pairs Returns: - unsqueezed key-value dict """ keys, values = [], [] for sample in table: ks, vs = [], [] for k, vals in sample.items(): ks....
bigcode/self-oss-instruct-sc2-concepts
def line_from_2_points(x1, y1, x2, y2): """ Gets the coefficients of a line, given 2 points :param x1: :param y1: :param x2: :param y2: :return: """ a = y1 - y2 b = x2 - x1 c = x1 * y2 - x2 * y1 return a, b, c
bigcode/self-oss-instruct-sc2-concepts
def is_pandigital(n): """Tests if n is a 1-9 pandigital""" if len(str(n)) != 9: return False if "0" in str(n): return False return len(str(n)) == len(set(str(n)))
bigcode/self-oss-instruct-sc2-concepts
def mulrowcol(row, col, K): """ Multiplies two lists representing row and column element-wise. Gotcha: Here the column is represented as a list contrary to the norm where it is represented as a list of one element lists. The reason is that the theoretically correct approach is too expensive. This p...
bigcode/self-oss-instruct-sc2-concepts
def bool_to_bin(bool_value): """ Helper function to map a boolean value to a binary value. :param bool_value: boolean boolean value [bool] :return: binary value [int] """ if bool_value: return 1 else: return 0
bigcode/self-oss-instruct-sc2-concepts
def _has_tag(Estimator, tag): """Check whether an Estimator has the given tag or not. Parameters ---------- Estimator : Estimator class tag : str An Estimator tag like "skip-inverse-transform" Returns ------- bool """ # Check if tag is in all tags return Estimator._...
bigcode/self-oss-instruct-sc2-concepts
import logging def get_lower_level(l0, l1): """Compare logging levels and return the lower level.""" if isinstance(l0, (str)): l0 = logging.getLevelName(l0) if isinstance(l1, (str)): l1 = logging.getLevelName(l1) return l0 if l0 < l1 else l1
bigcode/self-oss-instruct-sc2-concepts
import string import re def clean_text_round3(text): """ Clean up text data. Do what clean_text_round1 does, adding: Remove pontuations, except accents. Remove words if less than 3 letters Remove some special chars commom in papers """ remove = string.punctuation remove = remove.r...
bigcode/self-oss-instruct-sc2-concepts
def model_snowdepthtrans(Sdepth = 0.0, Pns = 100.0): """ - Name: SnowDepthTrans -Version: 1.0, -Time step: 1 - Description: * Title: snow cover depth conversion * Author: STICS * Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002 ...
bigcode/self-oss-instruct-sc2-concepts
def match_path(path, partial_paths): """Does the given path contain any of the stubs in partial_paths?""" return any(partial_path in str(path) for partial_path in partial_paths)
bigcode/self-oss-instruct-sc2-concepts
import click def atomic_to_global_desc_options(f): """Create common options for global descriptors constructed based on atomic fingerprints """ f = click.option('--reducer_type', '-r', help='type of operations to get global descriptors from the atomic soap vectors, e.g. \ ...
bigcode/self-oss-instruct-sc2-concepts
def get_aa_at_gene_pos(row, ref_aa_seq_dict): """ Helper function to apply on every row of a data frame to find the reference amino acid at given a gene and amino acid position. Parameters: ============== - row: dict Row of dataframe in dict form. Should have fields aa_pos (1-based aa po...
bigcode/self-oss-instruct-sc2-concepts
def lower_text(text: str) -> str: """ Given ``text`` str, transform it into lowercase Parameters ---------- text : string Returns ------- string """ return text.lower()
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def get_current_datetime() -> datetime: """ Generate datetime in UTC timezone. Returns: datetime: datetime. """ return datetime.utcnow()
bigcode/self-oss-instruct-sc2-concepts
def _extract_match_id(match_json): """ Extract the match_id from json response. { "matches": [ { "id": "0000...", "match_id": 1313, "similarity": "001000" } ] } """ matches = match_json.get('matches', []) ...
bigcode/self-oss-instruct-sc2-concepts
def ascii_encodable(text): """ Return True if the given TEXT can be losslessly encoded in ASCII. Otherwise, return False. """ return all(ord(char) < 128 for char in text)
bigcode/self-oss-instruct-sc2-concepts
import time def allow_retries(retry_on=[], wait=time.sleep, retries=3, delay=2): """ A general purpose decorator that allows a given function to be retried after certain failures. **Example** Suppose we have a function that occasionally throws errors if it doesn't get its way. In that case we ca...
bigcode/self-oss-instruct-sc2-concepts
import socket def ping_command(ping_binary, address, version=socket.AF_INET, count=1, payload_size=None): """Generate a ping shell command for Popen""" args = [ping_binary] if version == socket.AF_INET6: args.append('-6') else: args.append('-4') # ping interval args.append('-i...
bigcode/self-oss-instruct-sc2-concepts
def df2geojson(df, lat='latitude', long='longitude', remove_coords_properties=True): """ Convert um dataframe, com colunas de latitude e longitude, em um objeto geojson de pontos https://notebook.community/gnestor/jupyter-renderers/notebooks/nteract/pandas-to-geojson # Usage feature_collection = da...
bigcode/self-oss-instruct-sc2-concepts
def google_map(context): """ Dependencies for google_map gizmo. """ return ('tethys_gizmos/js/tethys_map.js',)
bigcode/self-oss-instruct-sc2-concepts
def pipe_Do(Di, WT): """Calculate pipe outer diameter, given the pipe inner diamater and wall thickness. """ Do = Di + 2 * WT return Do
bigcode/self-oss-instruct-sc2-concepts
def compute_asdp_size(manifest): """ Computes the total size of the ASDP from the manifest entires Parameters ---------- manifest: list list of dicts containing the manifest entries Returns ------- asdp_size: int the total size in bytes associated with "asdp," "validate...
bigcode/self-oss-instruct-sc2-concepts
def general_acquisition_info(metadata): """General sentence on data acquisition. This should be the first sentence in the MRI data acquisition section. Parameters ---------- metadata : :obj:`dict` The metadata for the dataset. Returns ------- out_str : :obj:`str` Outpu...
bigcode/self-oss-instruct-sc2-concepts
def get_bulb(zid, bulbs): """Retrieve a bulb by its zid from a list of Bulb objects.""" for bulb in bulbs: if bulb.zid == zid: return bulb return None
bigcode/self-oss-instruct-sc2-concepts
def _get_proto_name(proto): """Get the value of a proto's name field or return the proto type name. Args: proto: Proto to query. Returns: Human readable name of the proto. """ if 'name' in proto.DESCRIPTOR.fields_by_name: return proto.name return proto .DESCRIPTOR.name
bigcode/self-oss-instruct-sc2-concepts
import torch def gpu_mem_allocate_mbs(n, fatal=False): """ Try to allocate n MBs on the current device. Return the variable holding it on success, None on failure. fatal=True will throw an exception on failure to allocate (default is False). """ # don't try to allocate less than 6MB as it'd...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence def wrap_with_any_of(schemas: Sequence): """Take multiple JSON schemas and combine them using the `anyOf` JSON schema notation""" if len(schemas) == 1: return schemas[0] else: return {"anyOf": schemas}
bigcode/self-oss-instruct-sc2-concepts
def get_neighbours(x, y): """Get neighbours for an x, y location Args: x (int): x coord y (int): y coord Returns: List: list of tuples with x,y coords """ neighbours = [] neighbours += [(x-1, y)] neighbours += [(x, y-1)] neighbours += [(x, y+1)] neighbours += ...
bigcode/self-oss-instruct-sc2-concepts
def get_roots(pred_calls, sort_key = str): """Returns list of all roots of the given predicate calls. >>> aststs = functools.partial(ast, sts) >>> preds = list(map(aststs, [sl.tree("x"), sl.list("h"), sl.tree("a"), sl.list.seg("h", "t")])) >>> get_roots(preds) [a, h, x] >>> get_roots(preds, str...
bigcode/self-oss-instruct-sc2-concepts
def get_index_dictionary(filepath, delimiter='\n'): """Generates a dictionary of words to their respective indices. Args: filepath (str): File path. delimiter (str, optional): Delimiter separating words. Defaults to '\n'. Returns: Dictionary mapping words to their indices. """ ...
bigcode/self-oss-instruct-sc2-concepts
def qname_and_mate(qname): """ Removes mate sequence from qname. qname: original qname Return value: tuple (qname, mate sequence, which could be empty) """ split_name = qname.split('\x1d') mate = split_name[1].rpartition(':') split_name[1] = mate[0] + ':' return ('\x1d'.join(sp...
bigcode/self-oss-instruct-sc2-concepts
def flow_number_poly(cappa): """Calculate flow number for a given pump's typical number. The polynomial has been calculated applaying the curve fitting at nodes cappa .2 .3 .4 .5 .6 .7 .8 .9 1.0 1.1 1.2 phi .080 .093 .100 .110 .120 .130 .140 .150 .160 .165 .170 weights ones(cappa)...
bigcode/self-oss-instruct-sc2-concepts
def is_missing_atom_map(molecule): """ Checks if any atom in molecule is missing a map index. If even only one atom is missing a map index will return True Parameters ---------- molecule: oechem.OEMOl Returns ------- bool """ MISSING_ATOM_MAP = False for atom in molecule.Ge...
bigcode/self-oss-instruct-sc2-concepts
def stringify(hitObject): """Turns a TaikoObject into a string that TITaiko understands""" ret = str(int(hitObject.offset)) + ':' + str(hitObject.objType.value) # Add a third parameter if the object is a long note if (hitObject.length != None): ret += ':' + str(int(hitObject.length)) return ret
bigcode/self-oss-instruct-sc2-concepts
import torch def encode(matched, priors, variances): """Encode the variances from the priorbox layers into the ground truth boxes we have matched (based on jaccard overlap) with the prior boxes. Args: matched: (tensor) Coords of ground truth for each prior in point-form Shape: [num_pri...
bigcode/self-oss-instruct-sc2-concepts
def product(l): """Multiply together the elements of a list.""" prod = 1 for x in l: prod *= x return prod
bigcode/self-oss-instruct-sc2-concepts
def expected_errors(snippets): """Get and normalize expected errors from snippet.""" out = snippets.pop(0) assert out.startswith("[GraphQLError(") return " ".join(out.split()).replace("( ", "(").replace('" "', "")
bigcode/self-oss-instruct-sc2-concepts
def avoids(w, s): """ Check if the word contains any of the characters specified in a string. Return True if it does not """ for l in w: if l in s: return False return True
bigcode/self-oss-instruct-sc2-concepts
import time def dateToDBFmt(strVal, fromFmt="%m/%d/%Y"): """Convert a date from the specified fromFmt (a string accepted by time.strptime) to "yyyy-mm-dd", the format used by databases. """ try: dateTuple = time.strptime(strVal, fromFmt) except ValueError: raise ValueError("%s not ...
bigcode/self-oss-instruct-sc2-concepts
def has_test(args): """Returns if some kind of test data is given in args. """ return (args.test_set or args.test_source or args.test_dataset or args.test_stdin or args.test_datasets)
bigcode/self-oss-instruct-sc2-concepts
def is_tachycardic(age, heart_rate): """Determines if a given heart rate indicates tachycardia Every time a new heart rate is added to the server, it is necessary to ensure that the given heart rate does not indicate tachycardia in that given patient. This function reads in an age and a heart rate,...
bigcode/self-oss-instruct-sc2-concepts
def suppress_value(valuein: int, rc: str = "*", upper: int = 100000000) -> str: """ Suppress values less than or equal to 7, round all non-national values. This function suppresses value if it is less than or equal to 7. If value is 0 then it will remain as 0. If value is at national level it will ...
bigcode/self-oss-instruct-sc2-concepts