seed
stringlengths
1
14k
source
stringclasses
2 values
def get_value(specs, name): """ Unpack metric specification Parameters ---------- specs: dict a dict with keys value and name name: str the spec name Return ------ value: float or None value of the spec if exists, None otherwise """ value = None for ...
bigcode/self-oss-instruct-sc2-concepts
def get_default_arrow(scale=1): """Get the default arrow """ return { 'cylinder_radius': scale*0.05, 'cylinder_height': scale*0.75, 'cone_radius': scale*0.125, 'cone_height': scale*0.25 }
bigcode/self-oss-instruct-sc2-concepts
def query_templater( table_name, columns=None, conds=None, db_name="darpa_data" ): """ Generates an appropriate SQL query for db_name Params: table_name : str Some darpa_data table columns : [str] or None A list of column names to fetch...
bigcode/self-oss-instruct-sc2-concepts
import string def sanitize_channel_name(name: str) -> str: """Filter out characters that aren't allowed by Discord for guild channels. Args: name: Channel name. Returns: Sanitized channel name. """ whitelist = string.ascii_lowercase + string.digits + "-_" name = name.lower()....
bigcode/self-oss-instruct-sc2-concepts
from operator import mul def multiplyLists(lst1, lst2): """Return the elementwise product of lst1 and lst2.""" assert len(lst1) == len(lst2), "The lists have to be the same length." return list(map(mul, lst1, lst2))
bigcode/self-oss-instruct-sc2-concepts
def serialize_uint256(n: int) -> bytes: """ Serialize an unsigned integer ``n`` as 32 bytes (256 bits) in big-endian order. Corresponds directly to the "ser_256(p)" function in BIP32 (https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#conventions). :param n: The integer to be seria...
bigcode/self-oss-instruct-sc2-concepts
def add_mask_to_image(img, mask, x, y): """Paste a mask at specific position on image""" if y + mask.shape[0] > img.shape[0]: max_height = img.shape[0] - y mask = mask[: max_height, :] if x + mask.shape[1] > img.shape[1]: max_width = img.shape[1] - x mask = mask[: , :max_wid...
bigcode/self-oss-instruct-sc2-concepts
def dSquaredLoss(a, y): """ :param a: vector of activations output from the network :param y: the corresponding correct label :return: the vector of partial derivatives of the squared loss with respect to the output activations """ # assuming that we measure the L(a, y) by sum(1/2*square(y_i - a...
bigcode/self-oss-instruct-sc2-concepts
def get_cmd_arg(arg, cmd_tree): """ Return the indicated command argument from command parse tree. If arg is a str it is a keyword. If arg is an int it is a positional index. If the argument is not found, return None. Args: arg: Command argument to look up cmd_tree: Parsed command t...
bigcode/self-oss-instruct-sc2-concepts
def get_notes_by_song(song, notes_map): """ Iterate over all labels for a given song. Same note have different midi codes in different octaves. For example the note C has the following codes: 12, 24, 36, 48, 60, 72, 84, 96, 108, 120 For this representation, we transform all these code only t...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_bert_embeddings(tokens_tensor, segments_tensors, model): """Get embeddings from an embedding model Args: tokens_tensor (obj): Torch tensor size [n_tokens] with token ids for each token in text segments_tensors (obj): Torch tensor size [n_tokens] ...
bigcode/self-oss-instruct-sc2-concepts
def parse_dependencies_windows(data): """ Parses the given output from dumpbin /dependents to determine the list of dll's this executable file depends on. """ lines = data.splitlines() li = 0 while li < len(lines): line = lines[li] li += 1 if line.find(' has the following de...
bigcode/self-oss-instruct-sc2-concepts
def get_datetime_str(dt): """ >>> dt = datetime.datetime.now() >>> def get_datetime_str(dt): ... return dt.strftime("%Y-%m-%d %H:%M:%S") >>> get_datetime_str(dt) '2021-04-11 17:19:10' """ return dt.strftime("%Y-%m-%d %H:%M:%S")
bigcode/self-oss-instruct-sc2-concepts
import gc import time def measure(func, inner_iterations=1, repeats=5): """ Runs func ``repeats`` times and returns the fastest speed (inner loop iterations per second). Use ``inner_iterations`` to specify the number of inner loop iterations. Use this function for long-running functions. """ ...
bigcode/self-oss-instruct-sc2-concepts
def calculateBoxInertia(mass, size): """Returns upper diagonal of inertia tensor of a box as tuple. Args: mass(float): The box' mass. size(iterable): The box' size. Returns: : tuple(6) """ i = mass / 12 ixx = i * (size[1] ** 2 + size[2] ** 2) ixy = 0 ixz = 0 iyy ...
bigcode/self-oss-instruct-sc2-concepts
def get_suspecious_items(_items): """Items with libraryCatalog==Zotero These items are suspecious, cause they were imported from pdf files and maybe Zotero did not import the metadata properly. :param _items: Zotero library items :type _items: list containing dicts :returns: list containing di...
bigcode/self-oss-instruct-sc2-concepts
def validate_change_dict_for_blog_post(change_dict): """Validates change_dict required for updating values of blog post. Args: change_dict: dict. Data that needs to be validated. Returns: dict. Returns the change_dict after validation. """ if 'title' in change_dict: blog_do...
bigcode/self-oss-instruct-sc2-concepts
def covxy(x, y): """ Covariance => average of pair products. """ N = x.shape[0] psum = 0 for i in range(N): psum = psum + x[i] * y[i] return psum / N
bigcode/self-oss-instruct-sc2-concepts
def overlaps(low1: int, high1: int, low2: int, high2: int) -> bool: """ Returns true if the two regions [low1, high1] and [low2, high2] overlap. """ return high1 >= low2 and high2 >= low1
bigcode/self-oss-instruct-sc2-concepts
def uniq(seq): """return uniq elements of a list, preserving order :param seq: an iterable to be analyzed """ seen = set() return [x for x in seq if not (x in seen or seen.add(x))]
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def import_class(name: str) -> Any: """Import from a module specified by a string""" components = name.split(".") mod = __import__(components[0]) for comp in components[1:]: mod = getattr(mod, comp) return mod
bigcode/self-oss-instruct-sc2-concepts
def pos_mask(row: int, col: int) -> int: """Return the bit mask for (row, col) on a bitboard.""" assert 0 <= row < 8 assert 0 <= col < 8 return 0x8000000000000000 >> col >> row * 8
bigcode/self-oss-instruct-sc2-concepts
def find_vswitch_uri_for_id(k2_id, vswitch_map): """ Returns the vSwitch href URI for a given K2 id. :param k2_id: The K2 vSwitch ID :param vswitch_map: The vSwitch map from the HMC Topo :returns: vSwitch URI """ k2_obj = vswitch_map.get(k2_id) if not k2_obj: return None retu...
bigcode/self-oss-instruct-sc2-concepts
def get_leftmost_end_point(linestring): """ extracts leftmost end point of linestring :param linestring: shapely.geometry.LineString :return: shapely.geometry.Point """ point_0_x = linestring.xy[0][0] point_1_x = linestring.xy[0][-1] if point_0_x <= point_1_x: return point_0_x ...
bigcode/self-oss-instruct-sc2-concepts
def getKey(myDict, value): """ Finds key associated with a value in dictionary """ for key, val in myDict.items(): if val == value: return key return -1
bigcode/self-oss-instruct-sc2-concepts
def _worker_fn(url, dataset_fn, sampler_fn): """Function to generate the dataset and sampler for each worker.""" dataset = dataset_fn(url) sampler = sampler_fn(dataset) return (dataset, sampler)
bigcode/self-oss-instruct-sc2-concepts
def summary_global_quantities(ods, update=True): """ Calculates global quantities for each time slice and stores them in the summary ods: - Greenwald Fraction - Energy confinement time estimated from the IPB98(y,2) scaling - Integrate power densities to the totals - Generate summary.global_q...
bigcode/self-oss-instruct-sc2-concepts
def get_resume_name(stage_name): """return a new name with resume and an increasing index""" split_stage_name = stage_name.split("_") if len(split_stage_name) > 2 and split_stage_name[-2] == "resume": resume_index = int(split_stage_name[-1]) + 1 return "_".join(split_stage_name[:-2] + ["resu...
bigcode/self-oss-instruct-sc2-concepts
import yaml def extract(mdtext): """ Extract a yaml text blob from markdown text and parse the blob. Returns a tuple (yaml_obj, markdown_text) """ lines = mdtext.split("\n") n = 0 ylines = [] mlines = [] for line in lines: if (line == "---"): n = n + 1 else: if n == 1: y...
bigcode/self-oss-instruct-sc2-concepts
import torch def binary_accuracy(prediction, target): """Calculates accuracy between two classes using probabilities Parameters ---------- prediction : torch.Tensor or torch.autograd.Variable Vector of probabilities of class 1 target : torch.Tensor Vector containing the class indices 0 or 1 """ ...
bigcode/self-oss-instruct-sc2-concepts
import inspect def listens_to(name): # noqa: D401 """Decorator to register a method of a :class:`Handler` as a listener. The method must be a coroutine. Arguments --------- name: :class:`str` The name of the event to listen to. Raises ------ TypeError The name was n...
bigcode/self-oss-instruct-sc2-concepts
def correlate_dicts(dicts, key): """Correlate several dicts under one superdict. If you have several dicts each with a 'name' key, this puts them in a container dict keyed by name. Example:: >>> d1 = {"name": "Fred", "age": 41} >>> d2 = {"name": "Barney", "age": 31} >>> flint...
bigcode/self-oss-instruct-sc2-concepts
import functools def as_list(f): """Decorator that changes a generator into a function that returns a list.""" @functools.wraps(f) def wrapper(*args, **kwargs): return list(f(*args, **kwargs)) return wrapper
bigcode/self-oss-instruct-sc2-concepts
def is_overlapped(end1, start2): """Returns True if the two segments overlap Arguments --------- end1 : float End time of the first segment. start2 : float Start time of the second segment. """ if start2 > end1: return False else: return True
bigcode/self-oss-instruct-sc2-concepts
def _delta(x,y): """ Returns 1 if x and y differ, 0 otherwise. """ return x != y
bigcode/self-oss-instruct-sc2-concepts
def matrix_relative_rotation(r0, r1): """ Find the relative rotation to go from r0 to r1. """ return r1 @ r0.T
bigcode/self-oss-instruct-sc2-concepts
import tempfile def makeTempDir() -> str: """Make a temporary directory. :rtype: str :return: The path to the temporary directory. """ return tempfile.mkdtemp()
bigcode/self-oss-instruct-sc2-concepts
def parse_header(line): """Returns dict {'field': (start, length), ...}""" fields = [f.strip() for f in line.split(' ') if f.strip()] return {field: (line.index(field), len(field) + 1) for field in fields}
bigcode/self-oss-instruct-sc2-concepts
import warnings def deprecate_arg(old_arg, new_arg, old_value, new_value): """Helper to raise warnings when a deprecated arg is used. Args: old_arg (str): Name of old/deprecated argument. new_arg (str): Name of new argument. old_value (Any): Value the user passed in for the old argume...
bigcode/self-oss-instruct-sc2-concepts
def readfile(filename): """ Reads and returns file contents """ with open(filename) as docfile: return docfile.read()
bigcode/self-oss-instruct-sc2-concepts
def topic_ref_transform(ref_string, topic): """ Converts a topic string with forward-slashes into a JSON reference-friendly format ("/" becomes "~1"), then places the new string into the provided base reference path. :param ref_string: The base reference path :param topic: The DXL topic string to c...
bigcode/self-oss-instruct-sc2-concepts
import re def check_date_format(date_str): """ Check the date to ensure that it's in the proper format """ pattern = re.compile("^\d{4}-+\d{2}-+\d{2}T+\d{2}:+\d{2}:+\d{2}.+\d{1,}Z+$") matched = pattern.match(date_str) return matched
bigcode/self-oss-instruct-sc2-concepts
def compute_standard_walking_time(length_m: float, elevation_gain_m: float, elevation_loss_m: float) -> float: """Estimate the hiking time in seconds Parameters ---------- :param: length_m: Length of the hike in meters :param: elevation_gain_m: Elevation gain of the hike in meters :...
bigcode/self-oss-instruct-sc2-concepts
def sort_dict(data: dict, key_type=None, reverse=False): """ Returns a sorted dictionary by keys :param data: the input dictionary :param key_type: type of key (if keys are not str for example) :param reverse: sort in reverse order :return: sorted dictionary """ res = {} if len(data)...
bigcode/self-oss-instruct-sc2-concepts
def bounds_to_geojson(bounds): """ Convert a rio BoundingBox to geojson with optional buffer :param bounds: BoundingBox :return: geojson with applied buffer """ return { "type": "Polygon", "coordinates": [ [ [bounds.left, bounds.top], [...
bigcode/self-oss-instruct-sc2-concepts
def _get_dataset_length(dset, default=1): """Return the dataset's training data length and in case the dataset is uncountable return a defalt value.""" try: return len(dset.train_data) except RuntimeError: return default
bigcode/self-oss-instruct-sc2-concepts
def attribution() -> str: """Returns data attribution string""" return '\u0026copy; <a href="https://usafacts.org">USAFacts</a>. '
bigcode/self-oss-instruct-sc2-concepts
def _filter_core_state_space(df, options): """Applies filters to the core state space. Sometimes, we want to apply filters to a group of choices. Thus, use the following shortcuts. - ``i`` is replaced with every choice with experience. - ``j`` is replaced with every choice without experience. ...
bigcode/self-oss-instruct-sc2-concepts
def get_output_file(dataset, output_dir): """ Compute the output metadata file name for the given dataset. """ out_file_name = str(dataset.id) + '-metadata.yaml' return output_dir / out_file_name
bigcode/self-oss-instruct-sc2-concepts
import warnings def _split_sections(lines): """ Split rigaku file into sections Returns a list of sections [(name, body, index)] where name is the section type, body is the list of lines between *RAS_name_START and *RAS_name_END and index is the 1-origin index of *RAS_name_START (or the 0-origin ...
bigcode/self-oss-instruct-sc2-concepts
import zipfile def list_files_in_zip(filename, endswith=None): """ List files in zip archive :param filename: path of the zip :param endswith: optional, end of filename to be matched :return: list of the filepaths """ with zipfile.ZipFile(filename) as zip_file: filelist = zip_file.name...
bigcode/self-oss-instruct-sc2-concepts
def producer_config(config): """Filter the producer config""" for field in ["group.id", "partition.assignment.strategy", "session.timeout.ms", "default.topic.config"]: if field in config: del config[field] return config
bigcode/self-oss-instruct-sc2-concepts
def label_filter(label_key, label_value): """Return a valid label filter for operations.list().""" return 'labels."{}" = "{}"'.format(label_key, label_value)
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def utc_folder(x): """ Convert a UTC timestamp to a folder string """ return datetime.utcfromtimestamp(x).strftime('%Y/%j/%H')
bigcode/self-oss-instruct-sc2-concepts
def short_state(state: str) -> str: """Return a short version of query state. >>> short_state("active") 'active' >>> short_state("idle in transaction") 'idle in trans' >>> short_state("idle in transaction (aborted)") 'idle in trans (a)' """ return { "idle in transaction": "i...
bigcode/self-oss-instruct-sc2-concepts
import re def _extract_sentence_tags(tagged_sentence): """Given a tagged sentence, extracts a dictionary mapping tags to the words or phrases that they tag. Parameters ---------- tagged_sentence : str The sentence with Medscan annotations and tags Returns ------- tags : dict ...
bigcode/self-oss-instruct-sc2-concepts
def find_median(a: int, b: int, c: int) -> int: """Find median of three elements""" x = a - b y = b - c z = a - c if x * y > 0: return b if x * z > 0: return c return a
bigcode/self-oss-instruct-sc2-concepts
def get_updater(api, resource_type): """Returns the method to update a given resource type """ updaters = { "source": api.update_source, "dataset": api.update_dataset, "model": api.update_model, "ensemble": api.update_ensemble, "batchprediction": api.update_batch_pre...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_complete_dataset(dataloaders, key="train", region="region1"): """ Load complete dataset to memory. Args: dataloaders (OrderedDict): dictionary of dictionaries where the first level keys are 'train', 'validation', and 'test', and second level keys are r...
bigcode/self-oss-instruct-sc2-concepts
def converter_tuple(obj) -> tuple: """ Convert input to a tuple. ``None`` will be converted to an empty tuple. Parameters ---------- obj: Any Object to convert. Returns ------- obj: Tuple[Any] Tuple. """ if obj is None: return () elif hasattr(obj, "_...
bigcode/self-oss-instruct-sc2-concepts
def tupilate(source, val): """Broadcasts val to be a tuple of same size as source""" if isinstance(val, tuple): assert(len(val) == len(source)) return val else: return (val,)*len(source)
bigcode/self-oss-instruct-sc2-concepts
def convert_eq(list_of_eq): """ Convert equality constraints in the right format to be used by unification library. """ lhs = [] rhs = [] for eq in list_of_eq: lhs.append(eq.lhs) rhs.append(eq.rhs) return tuple(lhs), tuple(rhs)
bigcode/self-oss-instruct-sc2-concepts
def split_filtStr(filtStr): """ ...doctest: >>> split_filtStr('a>b;c<=d; e == f; bc=[0,1]') ['a>b', 'c<=d', 'e == f', 'bc=[0,1]'] >>> split_filtStr('a>b AND c<=d AND e == f') ['a>b', 'c<=d', 'e == f'] >>> split_filtStr('bc=[0,1]') ['bc=[0,1]'] >>> split_f...
bigcode/self-oss-instruct-sc2-concepts
def coord2pix(cx, cy, cdim, imgdim, origin="upper"): """Converts coordinate x/y to image pixel locations. Parameters ---------- cx : float or ndarray Coordinate x. cy : float or ndarray Coordinate y. cdim : list-like Coordinate limits (x_min, x_max, y_min, y_max) of imag...
bigcode/self-oss-instruct-sc2-concepts
def multiply(a,b): """ multiply two numbers """ return a*b
bigcode/self-oss-instruct-sc2-concepts
def get_public_key(remote, realm_url): """Get the realm's public key with the ID kid from Keycloak.""" certs_resp = remote.get(realm_url).data return certs_resp["public_key"]
bigcode/self-oss-instruct-sc2-concepts
def triple(n): """ (number) -> number Returns triple a given number. >>> triple(9) 27 >>> triple(-5) -15 >>> triple(1.1) 3.3 """ one = n * 3 return (one)
bigcode/self-oss-instruct-sc2-concepts
import hashlib def md5_bytes(data: bytes): """ generate md5 hash of binary. """ return hashlib.md5(data).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
import shlex def expand_file_arguments(argv): """ Any argument starting with "@" gets replaced with all values read from a text file. Text file arguments can be split by newline or by space. Values are added "as-is", as if they were specified in this order on the command line. """ new_args = [] ...
bigcode/self-oss-instruct-sc2-concepts
def hosts_loader(filename: str) -> dict: """ Loads host mapping file :param str filename: path to file :return: mapping as dictionary """ return_dict = {} with open(filename) as mapfile: lines = [ line.strip() for line in mapfile if not line.startswith('#') and l...
bigcode/self-oss-instruct-sc2-concepts
from zlib import crc32 def safe_crc(string): """64 bit safe crc computation. See http://docs.python.org/library/zlib.html#zlib.crc32: To generate the same numeric value across all Python versions and platforms use crc32(data) & 0xffffffff. """ return crc32(string) & 0xffffffff
bigcode/self-oss-instruct-sc2-concepts
def iterator_strategy(cube, axis=None): """ Guess the most efficient iteration strategy for iterating over a cube, given its size and layout Parameters ---------- cube : SpectralCube instance The cube to iterate over axis : [0, 1, 2] For reduction methods, the axis that is ...
bigcode/self-oss-instruct-sc2-concepts
def format_number(num): """Return a number representation with comma separators.""" snum = str(num) parts = [] while snum: snum, part = snum[:-3], snum[-3:] parts.append(part) parts.reverse() return ",".join(parts)
bigcode/self-oss-instruct-sc2-concepts
def invert_dict(dct: dict) -> dict: """Invert dictionary, i.e. reverse keys and values. Args: dct: Dictionary Returns: Dictionary with reversed keys and values. Raises: :class:`ValueError` if values are not unique. """ if not len(set(dct.values())) == len(dct.values())...
bigcode/self-oss-instruct-sc2-concepts
def sort_list(coord_list): """ Return a sorted list of coordinates, by y, then x """ return sorted(coord_list, key=lambda k: [k[1], k[0]])
bigcode/self-oss-instruct-sc2-concepts
def space_list(line: str) -> list: """"Given a string, return a list of index positions where a blank space occurs. >>> space_list(" abc ") [0, 1, 2, 3, 7] """ spaces = [] for idx, car in enumerate(list(line)): if car == " ": spaces.append(idx) return spaces
bigcode/self-oss-instruct-sc2-concepts
import itertools def _get_coord_mapping( dims, output, out_indices, numblocks, argpairs, concatenate, ): """Calculate coordinate mapping for graph construction. This function handles the high-level logic behind Blockwise graph construction. The output is a tuple containing: The ma...
bigcode/self-oss-instruct-sc2-concepts
def xr_average_across_days_of_year(da): """ Collapses an array across days of each year. Parameters ---------- da: xr.DataArray with 'time' dimension Returns ------- xr.DataArray with a 'year' dimension instead of 'time' """ return da.groupby("time.year").mean()
bigcode/self-oss-instruct-sc2-concepts
def prompt_for_yes_no(msg): """returns a bool based on whether the user presses y/n.""" choice = None while not choice or choice.lower() not in ['y', 'n', 'yes', 'no']: choice = input('%s (y/n) ' % msg).lower() return choice.lower() in ['y', 'yes']
bigcode/self-oss-instruct-sc2-concepts
def divide(x, y): """ Idiomatic / Pythonic recursive division with remainder """ if x == 0: return (0,0) q, r = divide(x / 2, y) q *= 2 r *= 2 if x & 1: r += 1 if r >= y: r -= y q += 1 return (q,r)
bigcode/self-oss-instruct-sc2-concepts
def evaluate_mva(df, mva): """ Evaluate the response of a trained classifier. Parameters ---------- df : DataFrame, shape= [n_training_samples, n_features] DataFrame containing features. mva Trained classifier. Returns ------- Series or array Classifier resp...
bigcode/self-oss-instruct-sc2-concepts
def add_50(x): """ Adds 50 to the input value x. """ return x + 50
bigcode/self-oss-instruct-sc2-concepts
def is_descriptor_schema(data): """Return ``True`` if passed object is DescriptorSchema and ``False`` otherwise.""" return type(data).__name__ == 'DescriptorSchema'
bigcode/self-oss-instruct-sc2-concepts
def serialize_curve(fcurve): """Returns a list of dictionaries representing each of the keys in the given FCurve.""" key_data_list = [] for key in fcurve.Keys: key_data = { 'time': key.Time.Get(), 'value': key.Value, 'interpolation': int(key.Interpolation), ...
bigcode/self-oss-instruct-sc2-concepts
def valid_year(year): """Check if number is a valid year""" return 1920 <= year < 2030
bigcode/self-oss-instruct-sc2-concepts
def add_reprompt(response): """ Adds a response message to tell the user to ask their question again. """ response['response']['reprompt'] = { "outputSpeech": { "type": "PlainText", "text": "Please ask your crypto price question" } } return response
bigcode/self-oss-instruct-sc2-concepts
import math def rotation_matrix_to_euler_angle(R): """ Converts a rotation matrix to [yaw, pitch, roll] """ yaw = math.atan2(R[1, 0], R[0, 0]) pitch = math.atan2(-R[2, 0], math.sqrt(R[2, 1] ** 2 + R[2, 2] ** 2)) roll = math.atan2(R[2, 1], R[2, 2]) return yaw, pitch, roll
bigcode/self-oss-instruct-sc2-concepts
def arc(equity_array, scale=252): """ Annualized Return Ratio :param equity_array: equity line :param scale: number of days required for normalization. By default in a year there are 252 trading days. :return: ARC as percentage """ return (equity_array[-1] / equity_array[0]) ** (scale / len(...
bigcode/self-oss-instruct-sc2-concepts
import re def normalize_directors(s: str) -> str: """Restore proper first-last name order and use a uniform separator between multiple names.""" flip = lambda name: ' '.join(reversed(name.split(', '))) return ' & '.join(map(flip, re.split(' & |/', s)))
bigcode/self-oss-instruct-sc2-concepts
def string_to_number(s): """Input stringified number and return integer.""" return int(s)
bigcode/self-oss-instruct-sc2-concepts
def sparrow_url_helper(*, build_url, config, **_): """ This helper function uses the "build_url" input from flowbyactivity.py, which is a base url for data imports that requires parts of the url text string to be replaced with info specific to the data year. This function does not parse the data, on...
bigcode/self-oss-instruct-sc2-concepts
def translated_geometry(assets): """Returns the translated geometry assets folder.""" return assets / "translated_geometry"
bigcode/self-oss-instruct-sc2-concepts
def valida_input(msg, respostas_validas, erro): """ Cria um laço de repetição "while True" que só é encerrado quando o usuário fornece uma resposta válida. enquanto isso não acontece, uma mensagem de "erro" é mostrada na tela. param msg(str): mensagem mostrada ao úsuario no input param respostas_va...
bigcode/self-oss-instruct-sc2-concepts
def _str_to_str(value: str) -> str: """Convert ``str`` to ``str``""" return value
bigcode/self-oss-instruct-sc2-concepts
import string def sanitise_string_for_stream_id(unsafe_string): """ Removes any unhelpful characters (e.g. #,/,<space>,%) from a string. We pass: -Letters ([A-Za-z]) -digits ([0-9]), -hyphens ("-"),underscores ("_"), colons (":"), and periods (".") -Plus symbol ('+') ...
bigcode/self-oss-instruct-sc2-concepts
import unicodedata def normalize_string(string): """Normalize string for tokenization and matching. Characters can come in composed or decomposed varieties. We normalize to decomposed characters in order to allow fine-grained control of accent patterns. The string is converted to lowercase. ...
bigcode/self-oss-instruct-sc2-concepts
def add_if_not_none(a, b): """Returns a/b is one of them is None, or their sum if both are not None.""" if a is None: return b if b is None: return a return a + b
bigcode/self-oss-instruct-sc2-concepts
def _database_delete_all_data_function_name(dataset): """Returns the name of the function to delete all data from the dataset's database""" return '{}_database_delete_all_data'.format(dataset.name)
bigcode/self-oss-instruct-sc2-concepts
def removeLocations(lmA, prefix): """Removes locations with a given prefix Keyword arguments: lmA -- Location map to delete location from prefix -- Key or part of key in location map dictionary Creates a copy of provided location map lmA Copy contains all key-value pairs from l...
bigcode/self-oss-instruct-sc2-concepts
def create_list_tuples_span_tag(list_span, tag): """ takes a list of span and returns a list of tuples of the form [((start_index, end_index), tag), ..., (start_index, end_index), tag)]""" list_tuples = [(x, tag) for x in list_span] return list_tuples
bigcode/self-oss-instruct-sc2-concepts