seed
stringlengths
1
14k
source
stringclasses
2 values
def get_raw_field_descr_from_header(file_handler): """ Get the raw field descriptors of the GNSS Logger log. These field descriptors will be later used to identify the data. This method advances the file pointer past the line where the raw fields are described """ for line in file_handler:...
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def bitList32ToList4(lst): """Convert a 32-bit list into a 4-byte list""" def bitListToInt(lst): return reduce(lambda x,y:(x<<1)+y,lst) lst2 = [] for i in range(0,len(lst),8): lst2.append(bitListToInt(lst[i:i+8])) return list([0]*(4-len(lst2))...
bigcode/self-oss-instruct-sc2-concepts
import torch def tensor_normalize(tensor, mean, std): """ Normalize a given tensor by subtracting the mean and dividing the std. Args: tensor (tensor): tensor to normalize. mean (tensor or list): mean value to subtract. std (tensor or list): std to divide. """ if tensor.dty...
bigcode/self-oss-instruct-sc2-concepts
def parse_filename(fname): """ Parse an SAO .hf5 filename for date and source """ parts = fname[7:-8].split('.') UNIXtime = float('.'.join(parts[:2])) sourcename = '.'.join(parts[2:]) return UNIXtime, sourcename
bigcode/self-oss-instruct-sc2-concepts
def secant_method(tol, f, x0): """ Solve for x where f(x)=0, given starting x0 and tolerance. Arguments ---------- tol: tolerance as percentage of final result. If two subsequent x values are with tol percent, the function will return. f: a function of a single variable x0: a starting value...
bigcode/self-oss-instruct-sc2-concepts
def checkOperatorPrecedence(a,b): """ 0 if a's precedence is more than b operator 1 otherwise """ check={} check['(']=1 check['*']=2 check['/']=2 check['-']=3 check['+']=3 if check[a] <= check[b]: return 1 else: return 0
bigcode/self-oss-instruct-sc2-concepts
def get_unique_attribute_objects(graph, uniq_attrs): """Fetches objects from given scene graph with unique attributes. Args: graph: Scene graph constructed from the dialog generated so far uniq_attrs: List of unique attributes to get attributes Returns: obj_ids: List of object ids with the unique at...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Optional def cast_to_num(value: Union[float, int, str]) -> Optional[Union[float, int]]: """Casts a value to an int/float >>> cast_to_num('5') 5 >>> cast_to_num('5.2') 5.2 >>> cast_to_num(10) 10 >>> cast_to_num(10.1) 10.1 >>> cast_to_...
bigcode/self-oss-instruct-sc2-concepts
def deltaT_boil(t_boil, t_cond): """ Calculates the temperature difference of boiler. Parameters ---------- t_boil : float The boiling temperature of liquid, [С] t_cond : float The condensation temperature of steam, [C] Returns ------- deltaT_boil : float The ...
bigcode/self-oss-instruct-sc2-concepts
def full_classname(cls): """Return full class name with modules""" return cls.__module__ + "." + cls.__name__
bigcode/self-oss-instruct-sc2-concepts
async def read_status(): """Check if server is running.""" return {'message': 'Server is running'}
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def versionToInt(version): """ Converts a WebODM version string (major.minor.build) to a integer value for comparison >>> versionToInt("1.2.3") 100203 >>> versionToInt("1") 100000 >>> versionToInt("1.2.3.4") 100203 >>> versionToInt("wrong") -1 ...
bigcode/self-oss-instruct-sc2-concepts
def _aggregates_associated_with_providers(a, b, prov_aggs): """quickly check if the two rps are in the same aggregates :param a: resource provider ID for first provider :param b: resource provider ID for second provider :param prov_aggs: a dict keyed by resource provider IDs, of sets ...
bigcode/self-oss-instruct-sc2-concepts
def get_closest_waveform(x, y, t, response): """ This function, given a point on the pixel pad and a time, returns the closest tabulated waveformm from the response array. Args: x (float): x coordinate of the point y (float): y coordinate of the point t (float): time of the wave...
bigcode/self-oss-instruct-sc2-concepts
def test_name(msg_name): """Generate the name of a serialization unit test given a message name""" return "test_{}_serialization".format(msg_name)
bigcode/self-oss-instruct-sc2-concepts
import re def natural_key(string): """ Key to use with sort() in order to sort string lists in natural order. Example: [1_1, 1_2, 1_5, 1_10, 1_13]. """ return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string)]
bigcode/self-oss-instruct-sc2-concepts
def flipra(coordinate): """Flips RA coordinates by 180 degrees""" coordinate = coordinate + 180 if coordinate > 360: coordinate = coordinate - 360 return coordinate
bigcode/self-oss-instruct-sc2-concepts
def get_location_from_object(loc_obj): """Return geo-location from a RefContext location object.""" if loc_obj.db_refs.get('GEOID'): return loc_obj.db_refs['GEOID'] elif loc_obj.name: return loc_obj.name else: return None
bigcode/self-oss-instruct-sc2-concepts
def ExtractImageTag(obj): """ Function to extract and return all image tags present in a BeautifulSoup object """ taglist = obj.findAll("img") return taglist
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from pathlib import Path from typing import Tuple from typing import List from typing import Dict def parse_synset_mapping( synset_mapping_filename: Union[Path, str] ) -> Tuple[List[str], Dict[str, str]]: """Parses the synset mapping file. Args: synset_mapping_filename: a...
bigcode/self-oss-instruct-sc2-concepts
def clear_all(client): """Delete all keys in configured memcached :param client: memcached client object """ client.flush_all() return True
bigcode/self-oss-instruct-sc2-concepts
import json def convert_response_to_json(response): """Converts the response to a json type""" json_response = json.loads(response.data.decode('utf-8')) return json_response
bigcode/self-oss-instruct-sc2-concepts
import re def extract_points_from(result): """ Expected line: "Unlocked 31/50 Git Achievements for 248 points" """ pattern = re.compile(r'[^0-9]*Unlocked[^0-9]+(\d+)[^0-9]+(\d+)[^0-9]+(\d+)') for line in result.readlines(): match = pattern.search(line) if match: return [int(n) for n in match.g...
bigcode/self-oss-instruct-sc2-concepts
def write_gif(clip, path, sub_start, sub_end): """Write subclip of clip as gif.""" subclip = clip.subclip(sub_start, sub_end) subclip.write_gif(path) return subclip
bigcode/self-oss-instruct-sc2-concepts
def decompose_chrstr(peak_str): """ Take peak name as input and return splitted strs. Args: peak_str (str): peak name. Returns: tuple: splitted peak name. Examples: >>> decompose_chrstr("chr1_111111_222222") "chr1", "111111", "222222" """ *chr_, start, end = ...
bigcode/self-oss-instruct-sc2-concepts
def are_keys_binary_strings(input_dict): """Check if the input dictionary keys are binary strings. Args: input_dict (dict): dictionary. Returns: bool: boolean variable indicating whether dict keys are binary strings or not. """ return all(not any(char not in '10' for char in key) f...
bigcode/self-oss-instruct-sc2-concepts
def flatten_nparray(np_arr): """ Returns a 1D numpy array retulting from the flatten of the input """ return np_arr.reshape((len(np_arr)))
bigcode/self-oss-instruct-sc2-concepts
def height(I): """returns the height of image""" return I.shape[0]
bigcode/self-oss-instruct-sc2-concepts
def read_names(filename): """File with name "filename" assumed to contain one leafname per line. Read and return set of names""" names = set() with open(filename, "r") as infile: for line in infile: leaf = line.strip() if leaf: names.add(leaf) return name...
bigcode/self-oss-instruct-sc2-concepts
def learning_rate_decay(alpha, decay_rate, global_step, decay_step): """ Updates the learning rate using inverse time decay in numpy alpha is the original learning rate decay_rate is the weight used to determine the rate at which alpha will decay global_step is the number of passes of gradien...
bigcode/self-oss-instruct-sc2-concepts
def tanimoto(e1, e2): """ Tanimoto coefficient measures the similarity of two bit patterns. Also referred to as the Jaccard similarity :return: real 0-1 similarity measure """ return (e1 & e2).count() / float((e1 | e2).count())
bigcode/self-oss-instruct-sc2-concepts
def scaleValues(values): """Scale a numpy array of values so that (min, max) = (0,1).""" values = values - values.min() return values/values.max()
bigcode/self-oss-instruct-sc2-concepts
import time def ValueOfDate() -> int: """ Return current unix time in milisecond (Rounded to nearest number) """ return round(time.time() * 1000)
bigcode/self-oss-instruct-sc2-concepts
def register_versions(role, versions=None): """Decorator for connecting methods in the views to api versions. Example: class MyView(BaseView): @register_versions('fetch', ['v4', 'v5']) def _get_data(self, param1, param2): ... @register_versions('re...
bigcode/self-oss-instruct-sc2-concepts
def latex_safe(s): """ Produce laTeX safe text """ s = s.replace('_','\_') return s
bigcode/self-oss-instruct-sc2-concepts
def open_wordlist(path): """ open a wordlist Note: a wordlist should be a text document with one word per line Args: path(str): full path to the wordlist Returns: passwordlist(list): list of all the words (as strings) in the wordlist """ with open(path, 'r', errors...
bigcode/self-oss-instruct-sc2-concepts
def fahrenheit_to_celsius(temp): """Convert temperature in fahrenheit to celsius. Parameters ---------- temp : float or array_like Temperature(s) in fahrenheit. Returns ------- float or array_like Temperatures in celsius. bubbles """ try: ...
bigcode/self-oss-instruct-sc2-concepts
import functools def replace_all(text, replacements): """ Replace in `text` all strings specified in `replacements` Example: replacements = ('hello', 'goodbye'), ('world', 'earth') """ return functools.reduce(lambda a, kv: a.replace(*kv), replacements, text)
bigcode/self-oss-instruct-sc2-concepts
import glob def get_files(data_dir_list, data_ext): """ Given a list of directories containing data with extention 'date_ext', generate a list of paths for all files within these directories """ data_files = [] for sub_dir in data_dir_list: files = glob.glob(sub_dir + "/*" + data_ext)...
bigcode/self-oss-instruct-sc2-concepts
def supertype(tcon): """ Return the supertype of the given type constructor. """ return tcon.supertype
bigcode/self-oss-instruct-sc2-concepts
def pfx_path(path : str) -> str: """ Prefix a path with the OS path separator if it is not already """ if path[0] != '/': return '/' + path else: return path
bigcode/self-oss-instruct-sc2-concepts
def check_entity_schema( sg, logger, entity_type, field_name, field_types, required_values ): """ Verifies that field_name of field_type exists in entity_type's schema. :param sg: An authenticated Shotgun Python API instance. :param entity_type: str, a Shotgun entity type. :param field_name: st...
bigcode/self-oss-instruct-sc2-concepts
def split_into_sets(array, tindx, eindx): """ Split data into train and validation (or evaluation) set with indices. Args: array (ndarray): processed without nans tindx (array): train data indices eindx (array): validation/evaluation data indices """ array_t = array...
bigcode/self-oss-instruct-sc2-concepts
import re def get_module_runtime(yaml_path): """Finds 'runtime: ...' property in module YAML (or None if missing).""" # 'yaml' module is not available yet at this point (it is loaded from SDK). with open(yaml_path, 'rt') as f: m = re.search(r'^runtime\:\s+(.*)$', f.read(), re.MULTILINE) return m.group(1) ...
bigcode/self-oss-instruct-sc2-concepts
def pixels_to_figsize(opt_dim, opt_dpi): """Converts pixel dimension to inches figsize """ w, h = opt_dim return (w / opt_dpi, h / opt_dpi)
bigcode/self-oss-instruct-sc2-concepts
def get_line_slope_intercept(x1, y1, x2, y2): """Returns slope and intercept of lines defined by given coordinates""" m = (y2 - y1) / (x2 - x1) b = y1 - m*x1 return m, b
bigcode/self-oss-instruct-sc2-concepts
def compare(n, p1, p2): """Compares two bits in an integer. Takes integers n, p1, p2. If the bit of n at positions p1 and p2 are the same, true is returned to the caller. Otherwise returns false. Bit positions start at 1 and go from low order to high. For example: n = 5, p1 = 1, p2 = 2 ...
bigcode/self-oss-instruct-sc2-concepts
def getDisabled(self, pos): """Get a boolean representing whether or not cell (i,j) is disabled.""" self.__checkIndices__(pos) return self.__isdisabled__[pos[0]][pos[1]]
bigcode/self-oss-instruct-sc2-concepts
def Diff(li1, li2): """ get the difference between two lists """ list_dif = [i for i in li1 + li2 if i not in li1 or i not in li2] return list_dif
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict import codecs def load_dict(dict_path: str, required: List[str] = ["<sos>", "<eos>"], reverse: bool = False) -> Dict: """ Load the dictionary object Args: dict_path: path of the vocabulary dictionary required: requ...
bigcode/self-oss-instruct-sc2-concepts
def vander_det(x): """Vandermonde determinant for the points x""" prod = 1 num = x.shape[0] for j in range(1, num): for i in range(0, j): prod *= x[j] - x[i] return prod
bigcode/self-oss-instruct-sc2-concepts
def argmax(pairs): """ Given an iterable of pairs (key, value), return the key corresponding to the greatest value. Raises `ValueError` on empty sequence. >>> argmax(zip(range(20), range(20, 0, -1))) 0 """ return max(pairs, key=lambda x: x[1])[0]
bigcode/self-oss-instruct-sc2-concepts
def _calc_detlam(xx, yy, zz, yx, zx, zy): """ Calculate determinant of symmetric 3x3 matrix [[xx,yx,xz], [yx,yy,zy], [zx,zy,zz]] """ return zz * (yy*xx - yx**2) - \ zy * (zy*xx - zx*yx) + \ zx * (zy*yx - zx*yy)
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_sha512_sums(file_bytes): """ Hashes bytes with the SHA-512 algorithm """ return hashlib.sha512(file_bytes).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def _colorize(text, color): """Applies ANSI color codes around the given text.""" return "\033[1;{color}m{text}{reset}".format( color = color, reset = "\033[0m", text = text, )
bigcode/self-oss-instruct-sc2-concepts
def factory_name(obj): """ Returns a string describing a DisCoPy object. """ return '{}.{}'.format(type(obj).__module__, type(obj).__name__)
bigcode/self-oss-instruct-sc2-concepts
def get_marker(func_item, mark): """ Getting mark which works in various pytest versions """ pytetstmark = [m for m in (getattr(func_item, 'pytestmark', None) or []) if m.name == mark] if pytetstmark: return pytetstmark[0]
bigcode/self-oss-instruct-sc2-concepts
def _approx_equal(a, b, tolerance): """Check if difference between two numbers is inside tolerance range.""" if abs(a - b) <= tolerance * a: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def _field_name(name, prefix=None): """ Util for quick prefixes >>> _field_name(1) '1' >>> _field_name("henk") 'henk' >>> _field_name("henk", 1) '1henk' """ if prefix is None: return str(name) return "%s%s" % (prefix, name)
bigcode/self-oss-instruct-sc2-concepts
import re def title(value): """Converts a string into titlecase.""" t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title()) return re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t)
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def sort_dictionary(dictionary): """ This function will turn a dictionary with sortable keys into an OrderedDict with keys in the ordering of the keys. This dictionary will have two levels of nesting as it will be a mapping of the sort {State -> {State -> value}} ...
bigcode/self-oss-instruct-sc2-concepts
def square(n): """Square a Number.""" return n ** 2
bigcode/self-oss-instruct-sc2-concepts
def parse_json_data(data,sep='\t'): """ Extract the data from json into a dictionary and a string """ # Set up the dictionary keys = ['date','rower','meters','duration','split','spm', 'watts','calories','resistance','instructor','workout'] workout = {} # Pointers to portions of the data...
bigcode/self-oss-instruct-sc2-concepts
def merge(L1: list, L2: list) -> list: """Merge sorted lists L1 and L2 into a new list and return that new list. >>> >>> merge([1, 3, 4, 6], [1, 2, 5, 7]) 1, 1, 2, 3, 4, 5, 6, 7] """ newL = [] i1 = 0 i2 = 0 # For each pair of items L1[i1] and L2[i2], copy the smaller into newL. whi...
bigcode/self-oss-instruct-sc2-concepts
def filter_entity(org_name, app_name, collection_name, entity_data, source_client, target_client, attempts=0): """ This is an example handler function which can filter entities. Multiple handler functions can be used to process a entity. The response is an entity which will get passed to the next handler i...
bigcode/self-oss-instruct-sc2-concepts
def get_host_id(session, hostname): """ Get host_id from the hostname. """ query = """ SELECT host_id FROM monitoring.hosts WHERE hostname = :hostname """ result = session.execute(query, {"hostname": hostname}) try: return result.fetchone()[0] except Exception: ...
bigcode/self-oss-instruct-sc2-concepts
def find_smallest_bin(b): """ Take boundary non-uniform vector and find smallest bin assuming they are multiple of each other Parameters ---------- b: array of floats boundaries, in mm returns: float minimal bin size """ minb = 10000000.0 prev = b[0] ll ...
bigcode/self-oss-instruct-sc2-concepts
def _func_star(args): """ A function and argument expanding helper function. The first item in args is callable, and the remainder of the items are used as expanded arguments. This is to make the function header for reduce the same for the normal and parallel versions. Otherwise, the functions ...
bigcode/self-oss-instruct-sc2-concepts
def always_none(x): """Returns None""" return None
bigcode/self-oss-instruct-sc2-concepts
def run_algo(op_list): """Execute all operations in a given list (multiply all matrices to each other).""" ops = op_list[::-1] # reverse the list; after all, it's matrix mult. result = ops[0] for op in ops[1:]: result = result * op return result
bigcode/self-oss-instruct-sc2-concepts
def get_docomo_post_data(number, hidden_param): """Returns a mapping for POST data to Docomo's url to inquire for messages for the given number. Args: number: a normalized mobile number. Returns: a mapping for the POST data. """ return {'es': 1, 'si': 1, '...
bigcode/self-oss-instruct-sc2-concepts
def AioNodeNameFromLightNickname(light): """Returns AIO node name for the specified light node.""" if light == 'BaseStation': return 'kAioNodeGpsBaseStation' else: return 'kAioNodeLight' + light
bigcode/self-oss-instruct-sc2-concepts
from typing import List def encode_message(message_string: str) -> List[int]: """Build a message to send in a sysex command.""" return [ord(char) for char in message_string]
bigcode/self-oss-instruct-sc2-concepts
def parse_performance_data(response): """Parse metrics response to a map :param response: response from unispshere REST API :returns: map with key as metric name and value as dictionary containing {timestamp: value} for a the timestamps available """ metrics_map = {} for metrics in respo...
bigcode/self-oss-instruct-sc2-concepts
def flat_node_list(graph): """ returns list of all non-compund nodes in a graph, inculding all the nodes that are inside compound nodes. """ node_ids = [] for node in graph: node_data = graph.node[node] #print(node_data) if 'components' in node_data: internal_...
bigcode/self-oss-instruct-sc2-concepts
def calc_total_fuel_for_mass(mass:int) -> int: """Calculates the total amount of fuel needed for a given mass, including its needed fuel mass.""" fuel = (mass // 3) - 2 if fuel <= 0: return 0 return fuel + calc_total_fuel_for_mass(fuel)
bigcode/self-oss-instruct-sc2-concepts
def _plugin_url(name, version): """ Given a name and an optional version, return the jenkins plugin url. If there is no version, grab the latest version of the plugin. >>> _plugin_url("git", None) 'https://updates.jenkins-ci.org/latest/git.hpi' >>> _plugin_url("git", "2.3.5") 'https://updat...
bigcode/self-oss-instruct-sc2-concepts
import functools import builtins import logging def requires_ipython(fn): """Decorator for methods that can only be run in IPython.""" @functools.wraps(fn) def run_if_ipython(*args, **kwargs): """Invokes `fn` if called from IPython, otherwise just emits a warning.""" if getattr(builtins, '__IPYTHON__',...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def get_linking_log_headers() -> list: """ Get linking log headers for creating project master linking log :return: list of headers for linking log """ linking_headers = OrderedDict() linking_headers['SubjectID'] = 'subject_id' linking_headers['MedicalRecordN...
bigcode/self-oss-instruct-sc2-concepts
def ErrorMessage(text): """Format an error output message """ return "\n\n" \ "********************************************************************\n" \ "{}\n" \ "********************************************************************" \ "\n\n".format(text)
bigcode/self-oss-instruct-sc2-concepts
import textwrap def wrap_text(text, width=90, indent=''): """Wrap each line of text to width characters wide with indent. Args: text (str): The text to wrap. width (str): width to wrap to. indent (str): the indent to prepend to each line. Returns: str: A wrapped block of ...
bigcode/self-oss-instruct-sc2-concepts
import re def expand_refs(comment_line): """Adds hrefs to markdown links that do not already have them; e.g. expands [Foo] to [Foo](#Foo) but leaves [Foo](https://foo) alone. """ result = comment_line result = re.sub(r"\[(\S+)\]([^(])", r"[\1](#\1)\2", result) result = re.sub(r"\[(\S+)\]$", r"...
bigcode/self-oss-instruct-sc2-concepts
def get_control_variation(campaign): """Returns control variation from a given campaign Args: campaign (dict): Running campaign Returns: variation (dict): Control variation from the campaign, ie having id = 1 """ for variation in campaign.get("variations"): if int(variation...
bigcode/self-oss-instruct-sc2-concepts
def get_all_ngrams(words): """ Get all n-grams of words :param words: list of str :return: ngrams, list of (list of str) """ ngrams = [] N = len(words) for n in range(1, N + 1): for i in range(0, N - n + 1): ngrams.append([words[j] for j in range(i, i + n)]) retu...
bigcode/self-oss-instruct-sc2-concepts
def total_hours(hours, days, weeks): """Total hours in w weeks + d days + h hours.""" return hours + 24 * (days + 7 * weeks)
bigcode/self-oss-instruct-sc2-concepts
def to_port_num(str_in): """ Tries to coerce provided argument `str_in` to a port number integer value. Args: str_in (string): String to coerce to port number. Returns: (int) or (None): Integer port number if provided `str_in` is a valid port number string,...
bigcode/self-oss-instruct-sc2-concepts
def contains_ingredients(ing, check_ing): """ IMPORTANT: You should NOT use loops or list comprehensions for this question. Instead, use lambda functions, map, and/or filter. Take a 2D list of ingredients you have and a list of pancake ingredients. Return a 2D list where each list only contains ing...
bigcode/self-oss-instruct-sc2-concepts
def match_emoji(emoji: str, text: str) -> bool: """ True if the emoji matches with `text` (case insensitive), False otherwise. """ return emoji.lower().startswith(text.lower())
bigcode/self-oss-instruct-sc2-concepts
import math def _find_utm_crs(lat, lon): """Find the UTM CRS based on lat/lon coordinates. Parameters ---------- lat : float Decimal latitude. lon : float Decimal longitude. Returns ------- crs : dict Corresponding UTM CRS. """ utm_zone = (math.floor((...
bigcode/self-oss-instruct-sc2-concepts
def format_states(states): """ Format logging states to prettify logging information Args: states: logging states Returns: - formated logging states """ formated_states = {} for key, val in states.items(): if isinstance(val, float): if val < 1e-3: ...
bigcode/self-oss-instruct-sc2-concepts
def set_gte(left, right): """:yaql:operator >= Returns true if right set is subset of left set. :signature: left >= right :arg left: left set :argType left: set :arg right: right set :argType right: set :returnType: boolean .. code:: yaql> set(0, 1) >= set(0, 1) t...
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup def extract_data_by_class(raw_content, elem, class_name, is_all=False): """extract html tags by element and class name""" parser = "html.parser" soup = BeautifulSoup(str(raw_content), parser) if is_all: return soup.find_all(elem, class_=class_name) else: ...
bigcode/self-oss-instruct-sc2-concepts
def str2bool(s): """ Turn a string s, holding some boolean value ('on', 'off', 'True', 'False', 'yes', 'no' - case insensitive) into boolean variable. s can also be a boolean. Example: >>> str2bool('OFF') False >>> str2bool('yes') True """ if isinstance(s, str): true_val...
bigcode/self-oss-instruct-sc2-concepts
def runtime_sync_hook_is_client_running(client): """ Runtime sync hook to check whether a slash command should be registered and synced instantly when added or removed. Parameters ---------- client : ``Client`` The respective client of the ``Slasher``. """ return client.running
bigcode/self-oss-instruct-sc2-concepts
import math def root_ttr(n_terms, n_words): """ Root TTR (RTTR) computed as t/sqrt(w), where t is the number of unique terms/vocab, and w is the total number of words. Also known as Guiraud's R and Guiraud's index. (Guiraud 1954, 1960) """ if n_words == 0: return 0 retu...
bigcode/self-oss-instruct-sc2-concepts
def read_file(path): """ reads lines of a file and joins them into a single string """ try: with open(path, 'r') as text_file: return "".join(text_file.readlines()).strip() except IOError: exit("Error: file '%s' is not readable!" % path)
bigcode/self-oss-instruct-sc2-concepts
import re import uuid def _replace_re_pattern(code, pattern): """Replace the given re pattern with a unique id. Return the replaced string and a list of replacement tuples: (unique_id, original_substring) """ replacements = [] matches = re.findall(pattern, code) code_ = code for m in m...
bigcode/self-oss-instruct-sc2-concepts
import torch def cr_matrix_vector_product(m: torch.Tensor, x: torch.Tensor) -> torch.Tensor: """Returns the product of a complex matrix and a real vector. :param m: Matrix as ``(*, m, n, 2)`` tensor. :param x: Vector as ``(*, n)`` tensor. :return: Result as ``(*, m, 2)`` tensor. """ xr = x.un...
bigcode/self-oss-instruct-sc2-concepts
def _CheckNoInterfacesInBase(input_api, output_api): """Checks to make sure no files in libbase.a have |@interface|.""" pattern = input_api.re.compile(r'@interface') files = [] for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile): if (f.LocalPath().find('base/') != -1 and f.LocalPath()...
bigcode/self-oss-instruct-sc2-concepts
def _get_view_name(task_name: str, window_size: int) -> str: """Returns the view name for a given task name.""" return f"{task_name}_{window_size}_view"
bigcode/self-oss-instruct-sc2-concepts