seed
stringlengths
1
14k
source
stringclasses
2 values
def scope_contains_scope(sdict, node, other_node): """ Returns true iff scope of `node` contains the scope of `other_node`. """ curnode = other_node nodescope = sdict[node] while curnode is not None: curnode = sdict[curnode] if curnode == nodescope: return True retur...
bigcode/self-oss-instruct-sc2-concepts
def radio_text(route): """Returns a short representation of a Route Args: route: a Route object Returns: str: a string containing the route summary and duration """ text = " ".join([ "via " + route.summary, f"({max(1, round(route.duration / 60))} minutes)" ]) ...
bigcode/self-oss-instruct-sc2-concepts
def snitch_last_contained(metadata): """Return the frame when snitch was last contained.""" last_contain = 0 for _, movements in metadata['movements'].items(): contain_start = False for movement in movements: if movement[0] == '_contain' and movement[1] == 'Spl_0': ...
bigcode/self-oss-instruct-sc2-concepts
def dict_factory(cursor, row): """Returns a sqlite row factory that returns a dictionary""" d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d
bigcode/self-oss-instruct-sc2-concepts
import torch def gram_matrix(tensor): """ Calculate the Gram Matrix of a given tensor Gram Matrix: https://en.wikipedia.org/wiki/Gramian_matrix """ # get the batch_size, depth, height, and width of the Tensor _, d, h, w = tensor.size() # reshape so we're multiplying the features...
bigcode/self-oss-instruct-sc2-concepts
def isOnCorner(x, y): """Returns True if the position is in one of the four corners.""" return ((x == 0 and y == 0) or (x == 7 and y == 0) or (x == 0 and y == 7) or (x == 7 and y == 7))
bigcode/self-oss-instruct-sc2-concepts
def is_paired(cursor, imei_norm): """ Method to check if an IMEI is paired. :param cursor: db cursor :param imei_norm: normalized imei :return: bool """ cursor.execute("""SELECT EXISTS(SELECT 1 FROM pairing_list WHER...
bigcode/self-oss-instruct-sc2-concepts
def get_P_v(X_ex): """外気の水蒸気圧 式(2) Args: X_ex(ndarray): 絶湿[g/kg'] Returns: ndarray: 外気の水蒸気圧 """ return 101325 * (X_ex / (622 + X_ex))
bigcode/self-oss-instruct-sc2-concepts
import re def remove_digits(string): """Removes digits from a string""" return re.sub(r"\d+", "", string)
bigcode/self-oss-instruct-sc2-concepts
def _trim_css_to_bounds(css, image_shape): """ Make sure a tuple in (top, right, bottom, left) order is within the bounds of the image. :param css: plain tuple representation of the rect in (top, right, bottom, left) order :param image_shape: numpy shape of the image array :return: a trimmed plain ...
bigcode/self-oss-instruct-sc2-concepts
import math def log(*args): """ Evaluate a logarithm Args: *args (:obj:`list` of :obj:`float`): value optional proceeded by a base; otherwise the logarithm is calculated in base 10 Returns: :obj:`float` """ value = args[-1] if len(args) > 1: base = args[0]...
bigcode/self-oss-instruct-sc2-concepts
import socket import contextlib def has_dual_stack(sock=None): """Return True if kernel allows creating a socket which is able to listen for both IPv4 and IPv6 connections. If *sock* is provided the check is made against it. """ try: socket.AF_INET6; socket.IPPROTO_IPV6; socket.IPV6_V6ONLY...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any from typing import List from functools import reduce def traverse_dict(obj: Dict[Any, Any], properties: List[str]) -> Any: """ Traverse a dictionary for a given list of properties. This is useful for traversing a deeply nested dictionary. Instead of recu...
bigcode/self-oss-instruct-sc2-concepts
def _BuildRestrictionChoices(freq_restrictions, actions, custom_permissions): """Return a list of autocompletion choices for restriction labels. Args: freq_restrictions: list of (action, perm, doc) tuples for restrictions that are frequently used. actions: list of strings for actions that are relev...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_sha_digest(s, strip=True): """Generate digest for s. Convert to byte string. Produce digest. """ if strip: s = s.rstrip() s = s.encode("utf-8") return hashlib.sha256(s).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
import hashlib def hash_(list_): """Generate sha1 hash from the given list.""" return hashlib.sha1(str(tuple(sorted(list_))).encode("utf-8")).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def get_by_name(ast, name): """ Returns an object from the AST by giving its name. """ for token in ast.declarations: if token.name == name: return token return None
bigcode/self-oss-instruct-sc2-concepts
def _ecdf_y(data, complementary=False): """Give y-values of an ECDF for an unsorted column in a data frame. Parameters ---------- data : Pandas Series Series (or column of a DataFrame) from which to generate ECDF values complementary : bool, default False If True, give the E...
bigcode/self-oss-instruct-sc2-concepts
def _calculate_bsize(stat): """ Calculate the actual disk allocation for a file. This works at least on OS X and Linux, but may not work on other systems with 1024-byte blocks (apparently HP-UX?) From pubs.opengroup.org: The unit for the st_blocks member of the stat structure is not defined wit...
bigcode/self-oss-instruct-sc2-concepts
def vcum(self, key="", **kwargs): """Allows array parameter results to add to existing results. APDL Command: *VCUM Parameters ---------- key Accumulation key: Overwrite results. - Add results to the current value of the results parameter. Notes ----- Allows results f...
bigcode/self-oss-instruct-sc2-concepts
def brightness_to_percentage(byt): """Convert brightness from absolute 0..255 to percentage.""" return round((byt * 100.0) / 255.0)
bigcode/self-oss-instruct-sc2-concepts
def ensure_bool(val): """ Converts query arguments to boolean value. If None is provided, it will be returned. Otherwise, value is lowered and compared to 'true'. If comparison is truthful, True is returned, otherwise False. :param val: Value to convert to boolean. :return: boolean value ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def get_word_from_cursor(s: str, pos: int) -> Tuple[str, int, int]: """ Return the word from a string on a given cursor. :param s: String :param pos: Position to check the string :return: Word, position start, position end """ assert 0 <= pos < len(s) pos += 1...
bigcode/self-oss-instruct-sc2-concepts
import math def geometric_progression(a, r, n): """Returns a list [a, ar, ar^2, ar^3, ... , ar^(n-1)]""" comp = [] for num in range(n): comp.append(a*math.pow(r, num)) return(comp)
bigcode/self-oss-instruct-sc2-concepts
def lifetime_high(m): """Compute the lifetime of a high mass star (M > 6.6 Msun) Args: m (array): stellar mass. Returns: array: stellar lifetimes. """ return (1.2 * m**(-1.85) + 0.003) * 1000.
bigcode/self-oss-instruct-sc2-concepts
def replace_subset(lo, hi, arr, new_values, unique_resort=False): """ Replace a subset of a sorted arr with new_values. Can also ensure the resulting outcome is unique and sorted with the unique_resort option. :param lo: :param hi: :param arr: :param new_values: :param unique_resort: ...
bigcode/self-oss-instruct-sc2-concepts
def remove_comment(command): """ Return the contents of *command* appearing before #. """ return command.split('#')[0].strip()
bigcode/self-oss-instruct-sc2-concepts
def getdefaultencoding(space): """Return the current default string encoding used by the Unicode implementation.""" return space.newtext(space.sys.defaultencoding)
bigcode/self-oss-instruct-sc2-concepts
def seconds_to_str(value): """Convert seconds to a simple simple string describing the amount of time.""" if value < 60: return "%s seconds" % round(value, 2) elif value < 3600: return "%s minutes" % round(value / 60, 2) else: return "%s hours and %s minutes" % (round(value / 360...
bigcode/self-oss-instruct-sc2-concepts
def get_mask(k: int, c: int) -> int: """Returns the mask value to copy bits inside a single byte. :param k: The start bit index in the byte. :param c: The number of bits to copy. Examples of returned mask: Returns Arguments 00001111 k=0, c=4 011111...
bigcode/self-oss-instruct-sc2-concepts
def _hoist_track_info(track): """Mutates track with artist and album info at top level.""" track['album_name'] = track['album']['name'] artist = track['artists'][0] track['artist_name'] = artist['name'] return track
bigcode/self-oss-instruct-sc2-concepts
import time def isDSTTime(timestamp): """Helper function for determining whether the local time currently uses daylight saving time.""" local_time = time.localtime(timestamp) return time.daylight > 0 and local_time.tm_isdst > 0
bigcode/self-oss-instruct-sc2-concepts
def get_endpoints(astute_config): """Returns services endpoints :returns: dict where key is the a name of endpoint value is dict with host, port and authentication information """ master_ip = astute_config['ADMIN_NETWORK']['ipaddress'] # Set default user/password becaus...
bigcode/self-oss-instruct-sc2-concepts
def single_child(node): """ The single child node or None. """ result = None if node.nodes is not None and len(node.nodes) == 1: result = node.nodes[0] return result
bigcode/self-oss-instruct-sc2-concepts
def count_paras(paras): """Count the trainable parameters of the model. """ return sum(p.numel() for p in paras if p.requires_grad)
bigcode/self-oss-instruct-sc2-concepts
import re def _has_no_hashtag(href): """ Remove sub chapters :Param href: tags with the `href` attribute :Return: True if `href` exists and does not contain a hashtag else return False """ return href and not re.compile("#").search(href)
bigcode/self-oss-instruct-sc2-concepts
def orm_query_keys(query): """Given a SQLAlchemy ORM query, extract the list of column keys expected in the result.""" return [c["name"] for c in query.column_descriptions]
bigcode/self-oss-instruct-sc2-concepts
def ParsePrimitiveArgs(args, arg_name, current_value_thunk): """Parse the modification to the given repeated field. To be used in combination with AddPrimitiveArgs; see module docstring. Args: args: argparse.Namespace of parsed arguments arg_name: string, the (plural) suffix of the argument (snake_case)...
bigcode/self-oss-instruct-sc2-concepts
def select_text_color(r, g, b): """ Choose a suitable color for the inverse text style. :param r: The amount of red (an integer between 0 and 255). :param g: The amount of green (an integer between 0 and 255). :param b: The amount of blue (an integer between 0 and 255). :returns: A CSS color in...
bigcode/self-oss-instruct-sc2-concepts
def point_to_geojson(lat, lng): """ Converts a single x-y point to a GeoJSON dictionary object of coordinates :param lat: latitude of point :param lng: longitude of point :return: dictionary appropriate for conversion to JSON """ feature = { 'type': 'Feature', 'geometry': { ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping def nop(string: str, _: Mapping[str, str]) -> str: """No operation parser, returns given string unchanged. This exists primarily as a default for when no parser is given as the use of `lift(str)` is recommended when the parsed value is supposed to be a string. :param s...
bigcode/self-oss-instruct-sc2-concepts
import socket def authenticate(port, password): """ Authentication function used in all testcases to authenticate with server """ s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) s.sendto(b"AUTH %s" % password, ("127.0.0.1", port)) msg, addr = s.recvfrom(1024) return (s, ms...
bigcode/self-oss-instruct-sc2-concepts
import grp def groupmembers(name): """Return the list of members of the group with the given name, KeyError if the group does not exist. """ return list(grp.getgrnam(name).gr_mem)
bigcode/self-oss-instruct-sc2-concepts
import math def rotate_point(angle, point, origin): """ Rotates a point about the origin. Used from http://stackoverflow.com/q/8948001/1817465 mramazingguy asked Jan 20 '12 at 21:20 :param angle: cw from E, in degrees :param point: [x, y] :param origin: [x0, y0] :return: The point, rotat...
bigcode/self-oss-instruct-sc2-concepts
def did_to_dirname(did: str): """ Takes a Rucio dataset DID and returns a dirname like used by strax.FileSystemBackend """ # make sure it's a DATASET did, not e.g. a FILE if len(did.split('-')) != 2: raise RuntimeError(f"The DID {did} does not seem to be a dataset DID. " ...
bigcode/self-oss-instruct-sc2-concepts
def parse_genome_size(txt_file): """Pull out the genome size used for analysis.""" with open(txt_file, 'rt') as txt_fh: return txt_fh.readline().rstrip()
bigcode/self-oss-instruct-sc2-concepts
async def present( hub, ctx, name, lock_level, resource_group=None, notes=None, owners=None, connection_auth=None, **kwargs, ): """ .. versionadded:: 2.0.0 .. versionchanged:: 4.0.0 Ensure a management lock exists. By default this module ensures that the management ...
bigcode/self-oss-instruct-sc2-concepts
def sort_set_by_list(s, l, keep_duplicates=True): """ Convert the set `s` into a list ordered by a list `l`. Elements in `s` which are not in `l` are omitted. If ``keep_duplicates==True``, keep duplicate occurrences in `l` in the result; otherwise, only keep the first occurrence. """ if kee...
bigcode/self-oss-instruct-sc2-concepts
import pytz def IsValidTimezone(timezone): """ Checks the validity of a timezone string value: - checks whether the timezone is in the pytz common_timezones list - assumes the timezone to be valid if the pytz module is not available """ try: return timezone in pytz.common_timezones ex...
bigcode/self-oss-instruct-sc2-concepts
def xp_to_level(level: int): """Returns the amount of EXP needed for a level. Parameters ---------- level: int The level to find the amount of EXP needed for. Returns ------- int: The amount of EXP required for the level. """ return (level ** 3) // 2
bigcode/self-oss-instruct-sc2-concepts
def gpu_size(wildcards, attempt): """Return model size in gb based on {prot} and {model}""" prot = wildcards.get('prot', 'V3') model = wildcards.get('model', 'protbert') if 'bert' not in model: return 0 if prot == 'V3': return 9*attempt return 12*attempt
bigcode/self-oss-instruct-sc2-concepts
def is_prime(P): """ Method to check if a number is prime or composite. Parameters: P (int): number to be checked, must be greater than 1 Returns: bool: True if prime, False if composite """ for i in range(2, P): j = P % i if j == 0: ...
bigcode/self-oss-instruct-sc2-concepts
def h(number): """ convert a number to a hex representation, with no leading '0x'. Example:: assert h(16) == '10' assert hex(16) == '0x10' """ return "%02x" % number
bigcode/self-oss-instruct-sc2-concepts
def add_feature_transaction_completed_ratio(profile_updated_df): """ Create feature transcation count to offer completed ratio to avoid np.inf as a result of division, a 0.1 number was added to the denominator """ profile_updated = profile_updated_df.copy() profile_updated['transaction_complet...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence def max_len( row: Sequence) \ -> int: """ Max `len` of 1d array. """ return max(len(str(x)) for x in row)
bigcode/self-oss-instruct-sc2-concepts
def calculate_air_density(pressure, temperature): """ Calculates air density from ideal gas law. :param pressure: Air pressure in Pascals :param temp: Air temperature in Kelvins :return density: Air density in kg/m^2 """ R = 286.9 # specific gas constant for air [J/(kg*K)] density...
bigcode/self-oss-instruct-sc2-concepts
import pprint def api_message_to_javadoc(api_message): """ Converts vpe.api message description to javadoc """ str = pprint.pformat(api_message, indent=4, width=120, depth=None) return " * " + str.replace("\n", "\n * ")
bigcode/self-oss-instruct-sc2-concepts
def set_ranks(taxonomy): """Set ranks for species/subspecies creation.""" default_ranks = [ "genus", "family", "order", "class", "subphylum", "phylum", ] taxon_rank = None if "subspecies" in taxonomy: ranks = ["species"] + default_ranks ...
bigcode/self-oss-instruct-sc2-concepts
def read_xyz(filepath): """ Reads coordinates from an xyz file. Parameters ---------- filepath : str The path to the xyz file to be processed. Returns ------- atomic_coordinates : list A two dimensional list containing atomic coordinates """ with ...
bigcode/self-oss-instruct-sc2-concepts
def get_adaptive_eval_interval(cur_dev_size, thres_dev_size, base_interval): """ Adjust the evaluation interval adaptively. If cur_dev_size <= thres_dev_size, return base_interval; else, linearly increase the interval (round to integer times of base interval). """ if cur_dev_size <= thres_dev_size: ...
bigcode/self-oss-instruct-sc2-concepts
def convert88to256(n): """ 88 (4x4x4) color cube to 256 (6x6x6) color cube values """ if n < 16: return n elif n > 79: return 234 + (3 * (n - 80)) else: def m(n): "0->0, 1->1, 2->3, 3->5" return n and n + n-1 or n b = n - 16 x = b % 4 ...
bigcode/self-oss-instruct-sc2-concepts
def standard(X): """ standard : This function makes data ragbe between 0 and 1. Arguments: X (numoy array) : input data. -------- Returns: standard data. """ xmin = X.min() X = X-xmin xmax = X.max() X = X/xmax return X
bigcode/self-oss-instruct-sc2-concepts
def list_to_sql_in_list(l): """Convert a python list into a string that can be used in an SQL query with operator "in" """ return '(' + ','.join(f"'{e}'" for e in l) + ')'
bigcode/self-oss-instruct-sc2-concepts
def any(seq, pred=None): """Returns True if pred(x) is true for at least one element in the iterable""" for elem in filter(pred, seq): return True return False
bigcode/self-oss-instruct-sc2-concepts
def vectorize(tokens, vocab): """ Covert array of tokens, to array of ids Args: tokens (list): list of tokens vocab (Vocab): Returns: list of ids """ ids = [] for token in tokens: if token in vocab.tok2id: ids.append(vocab.tok2id[token]) else: ...
bigcode/self-oss-instruct-sc2-concepts
def generate_symbol_definitions_direct(symbols, prefix): """Generate a listing of definitions to point to real symbols.""" ret = [] for ii in symbols: ret += [ii.generate_rename_direct(prefix)] return "\n".join(ret)
bigcode/self-oss-instruct-sc2-concepts
import re def cleanOfSpaces(myString): """Clean a string of trailing spaces""" myString = re.sub("^( )+", "", myString) myString = re.sub("( )+$", "", myString) return myString
bigcode/self-oss-instruct-sc2-concepts
def get_build_os_arch(conanfile): """ Returns the value for the 'os' and 'arch' settings for the build context """ if hasattr(conanfile, 'settings_build'): return conanfile.settings_build.get_safe('os'), conanfile.settings_build.get_safe('arch') else: return conanfile.settings.get_safe('os_b...
bigcode/self-oss-instruct-sc2-concepts
def observe_rate(rate, redshift): """Returns observable burst rate (per day) from given local rate """ return rate / redshift
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def find_occurrences(number_list): """Finds how many times every number in a list occurs.""" counter = Counter(number_list) occurrences = counter.most_common() return occurrences
bigcode/self-oss-instruct-sc2-concepts
def add_vectors(v1, v2): """ Adds 2 vector :param v1: vector 1 :param v2: vector 2 :return: v1 + v2 """ return tuple([v1[i] + v2[i] for i in range(0, len(v1))])
bigcode/self-oss-instruct-sc2-concepts
def _get_issue_tracker(obj): """Get issue_tracker dict from obj if dict is based on existing tracker""" if not obj: return None ret = obj.issue_tracker if not ret.get('_is_stub'): return ret return None
bigcode/self-oss-instruct-sc2-concepts
import random def ordered(parent1, parent2, point=None): """Return a new chromosome using ordered crossover (OX). This crossover method, also called order-based crossover, is suitable for permutation encoding. Ordered crossover respects the relative position of alleles. Args: parent1 (Li...
bigcode/self-oss-instruct-sc2-concepts
def _weighted_sum(*args): """Returns a weighted sum of [(weight, element), ...] for weights > 0.""" # Note: some losses might be ill-defined in some scenarios (e.g. they may # have inf/NaN gradients), in those cases we don't apply them on the total # auxiliary loss, by setting their weights to zero. return su...
bigcode/self-oss-instruct-sc2-concepts
def rh_from_avp_svp(avp, sat_vp): """ Calculate relative humidity as the ratio of actual vapour pressure to saturation vapour pressure at the same temperature. See Allen et al (1998), page 67 for details. :param avp: Actual vapour pressure [units do not matter so long as they are the same ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def str_to_timestamp(time_as_str, time_format) -> float: """转换时间字符串为unix时间戳 Args: time_as_str: 时间字符串, 比如: 2019-09-10 15:20:25 time_format: 时间格式, 比如: %Y-%m-%d %H:%M:%S Returns: unix时间戳, 类型: float """ datetime_ = datetime.strptime(time_as_str, ti...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def remove_signature_parameters(s, *param_names): """ Removes the provided parameters from the signature s (returns a new signature instance). :param s: :param param_names: a list of parameter names to remove :return: """ params = OrderedDict(s.parameters.it...
bigcode/self-oss-instruct-sc2-concepts
def frequencies_imp(word_list): """ Takes a list of words and returns a dictionary associating words with frequencies of occurrence """ word_freqs = {} for w in word_list: if w in word_freqs: word_freqs[w] += 1 else: word_freqs[w] = 1 return word_freqs
bigcode/self-oss-instruct-sc2-concepts
def transforms_are_applied(obj): """ Check that the object is at 0,0,0 and has scale 1,1,1 """ if ( obj.location.x != 0 or obj.location.y != 0 or obj.location.z != 0 ): return False if ( obj.rotation_euler.x != 0 or obj.rotation_euler.y != 0 or obj.rotation_euler.z != 0 ): retu...
bigcode/self-oss-instruct-sc2-concepts
def get_distinct_values(df, key): """Get the distinct values that are present in a given column.""" return sorted(list(df[key].value_counts().index.values))
bigcode/self-oss-instruct-sc2-concepts
def get_path_array(node): """ Takes an end node and gives you every node (in order) for the shortest path to it. PARAMS: node (node): end node RETURNS: array[nodes]: every note you need to visit (in order) """ if node.shortest_path_via == None: return [node] else: ...
bigcode/self-oss-instruct-sc2-concepts
def decode_prefix(byte): """Decode a byte according to the Field Prefix encoding scheme. Arguments: byte: the encoded representation of the prefix Return: fixedwidth: Is the field fixed width (bool) variablewidth: if not fixed width, the number of bytes needed to en...
bigcode/self-oss-instruct-sc2-concepts
import requests def ct_get_lists(api_token=""): """Retrieve the lists, saved searches and saved post lists of the dashboard associated with the token sent in Args: api_token (str, optional): you can locate your API token via your crowdtangle dashboard under Settings...
bigcode/self-oss-instruct-sc2-concepts
def build_endpoint_description_strings( host=None, port=None, unix_socket=None, file_descriptor=None ): """ Build a list of twisted endpoint description strings that the server will listen on. This is to streamline the generation of twisted endpoint description strings from easier to use command lin...
bigcode/self-oss-instruct-sc2-concepts
def force_charge_fit(mol, current_rule, match): """ Forces the formal charges of a rule to match the formal charges of a molecule. Parameters ---------- mol: rdkit.Chem.Mol RDKit molecule object. current_rule: rdkit.Chem.Mol RDKit molecule object of rule match: tuple ...
bigcode/self-oss-instruct-sc2-concepts
def dataframe_map_module_to_weight(row) -> int: """ Return the weight of a given module from a dataframe row based on the module level and the module name (since the final project is worth more). Args: row (dataframe row): A row from a dataframe containing at least two ...
bigcode/self-oss-instruct-sc2-concepts
def is_foreign_key(col): """Check if a column is a foreign key.""" if col.foreign_keys: return True return False
bigcode/self-oss-instruct-sc2-concepts
def _build_body(res): """ Build the body of the Exchange appointment for a given Reservation. :type res: resources.models.Reservation :return: str """ return res.event_description or ''
bigcode/self-oss-instruct-sc2-concepts
def mm_as_m(mm_value): """Turn a given mm value into a m value.""" if mm_value == 'None': return None return float(mm_value) / 1000
bigcode/self-oss-instruct-sc2-concepts
def verify_positive(value): """Throws exception if value is not positive""" if not value > 0: raise ValueError("expected positive integer") return value
bigcode/self-oss-instruct-sc2-concepts
def get_devices_dict(version, image=None, arch=None, feature=None): """Based on version and image, returns a dictionary containing the folder location and the patterns of the installation files for each device type :param version: build version, e.g. 6.2.3-623 :param image: optional, 'Autotes...
bigcode/self-oss-instruct-sc2-concepts
def close_enough(v1,v2): """ Helper function for testing if two values are "close enough" to be considered equal. """ return abs(v1-v2) <= 0.0001
bigcode/self-oss-instruct-sc2-concepts
def map_onto_scale(p1, p2, s1, s2, v): """Map value v from original scale [p1, p2] onto standard scale [s1, s2]. Parameters ---------- p1, p2 : number Minimum and maximum percentile scores. s1, s2 : number Minimum and maximum intensities on the standard scale. v : number ...
bigcode/self-oss-instruct-sc2-concepts
def _read_phone(text_path): """Read phone-level transcripts. Args: text_path (string): path to a transcript text file Returns: transcript (string): a text of transcript """ # Read ground truth labels phone_list = [] with open(text_path, 'r') as f: for line in f: ...
bigcode/self-oss-instruct-sc2-concepts
def pytorch_array_to_scalar(v): """Implementation of array_to_scalar for pytorch.""" if v.is_cuda: v = v.cpu() return v.detach().numpy()
bigcode/self-oss-instruct-sc2-concepts
def create_tagging_decorator(tag_name): """ Creates a new decorator which adds arbitrary tags to the decorated functions and methods, enabling these to be listed in a registry :param tag_name: :return: """ def tagging_decorator(*args, **kwargs): # here we can receive the parameters hand...
bigcode/self-oss-instruct-sc2-concepts
def incr(num): """ Increment its argument by 1. :param num: number :return: number """ return num + 1
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def convertDateToUnix(dstr): """ Convert a given string with MM/DD/YYYY format to millis since epoch """ d = datetime.strptime(dstr, '%m/%d/%Y') return int((d - datetime.utcfromtimestamp(0)).total_seconds() * 1000)
bigcode/self-oss-instruct-sc2-concepts
def split_text(txt, trunc=None): """Split text into sentences/words Args: txt(str): text, as a single str trunc(int): if not None, stop splitting text after `trunc` words and ignore sentence containing `trunc`-th word (i.e. each sentence has len <= trunc)...
bigcode/self-oss-instruct-sc2-concepts
def get_auth_dict(auth_string): """ Splits WWW-Authenticate and HTTP_AUTHORIZATION strings into a dictionaries, e.g. { nonce : "951abe58eddbb49c1ed77a3a5fb5fc2e"', opaque : "34de40e4f2e4f4eda2a3952fd2abab16"', realm : "realm1"', qop : "auth"' } """ amap =...
bigcode/self-oss-instruct-sc2-concepts