seed
stringlengths
1
14k
source
stringclasses
2 values
def get_frame_durations(sentences, timestamps): """Given a list of sentences and timestamps of all words, return timestamps of each sentence Args: sentences (list): List of sentences timestamps (list): [ [<word_string>, <start_time_float>, <end_time_float>], ... ...
bigcode/self-oss-instruct-sc2-concepts
def _token_addresses( token_amount, number_of_tokens, deploy_service, participants, register): """ Deploy `number_of_tokens` ERC20 token instances with `token_amount` minted and distributed among `blockchain_services`. Optionally the instances will be registered with ...
bigcode/self-oss-instruct-sc2-concepts
def get_attack_rate(df, location): """ Get the attack rate for the location. Args: df (pd.DataFrame) : pandas DataFrame with attack rates for this scenario location (str) : name of the location Returns: float: Attack rate as a fraction from SIR model, values between 0 and 1....
bigcode/self-oss-instruct-sc2-concepts
import tarfile def extract_tarfile(file_path): """Extract a .tar archive into an appropriately named folder, return the path of the folder, avoid extracting if folder exists.""" new_path = None with tarfile.open(str(file_path)) as archive: new_dir = file_path.name.split('.tar')[0] new_path...
bigcode/self-oss-instruct-sc2-concepts
import math def get_epsilon_of_fedmd_nfdp(n, k, replacement=True): """Return epsilon of FedMD-NFDP Args: n (int): training set size k (int): sampling size replacement (bool, optional): sampling w/o replacement. Defaults to True. Returns: float: epsilon of FedMD-NFDP "...
bigcode/self-oss-instruct-sc2-concepts
def compute_line_intersection_point(x1, y1, x2, y2, x3, y3, x4, y4): """ Compute the intersection point of two lines. Taken from https://stackoverflow.com/a/20679579 . Parameters ---------- x1 : number x coordinate of the first point on line 1. (The lines extends beyond this point.) ...
bigcode/self-oss-instruct-sc2-concepts
def padded_concat(*values: str, strip: bool = True, sep: str = " ") -> str: """ >>> padded_concat(" hello", " yolo", "", " ", "yo", strip=True) 'hello yolo yo' >>> padded_concat(" hello", " yolo", "", " ", "yo", strip=False) ' hello yolo yo' >>> padded_concat(" hello", " yolo", "yo"...
bigcode/self-oss-instruct-sc2-concepts
def income1(households): """ Dummy for for income group 1 """ return (households['income_category'] == 'income group 1').astype(int)
bigcode/self-oss-instruct-sc2-concepts
def get_android_data_path(language: str, word_type: str): """ Returns the path to the data json of the Android app given a language and word type. Parameters ---------- language : str The language the path should be returned for. word_type : str The type of word...
bigcode/self-oss-instruct-sc2-concepts
def build_company_name(name_dict, _emptyString=u''): """Given a dictionary that represents a "long" IMDb company name, return a string. """ name = name_dict.get('name') if not name: return _emptyString country = name_dict.get('country') if country is not None: name += ' %s' %...
bigcode/self-oss-instruct-sc2-concepts
def remove_namespaces_whitespaces(type_str): """ Clear type name from namespaces and whitespaces """ return type_str.replace('sycl::', '').replace( ' ', '_').replace('std::', '')
bigcode/self-oss-instruct-sc2-concepts
def listSum(SumList): """ 递归求和函数 :param SumList: 求和列表 :return:求和之后的值 """ if len(SumList) == 1: return SumList[0] else: return SumList[0] + listSum(SumList[1:])
bigcode/self-oss-instruct-sc2-concepts
def get_to_folder_name(folder_name, date_stamp): """ From the date_stamp return the S3 folder name to save published files into """ return folder_name + date_stamp + "/"
bigcode/self-oss-instruct-sc2-concepts
from typing import List def parse_combined_columns(eval_data: List[List[str]], index_a: int, index_b: int, delimiter: str = ' - ') -> str: """ Combines two columns worth of data into a single list of comments, separated by a delimiter """ if len(eval_data) <= 1: return '' return_val = "\\b...
bigcode/self-oss-instruct-sc2-concepts
import math def get_prime_factors(n): """Return prime decomposition of an int n """ prime_factors = [] while n % 2 == 0: prime_factors.append(2) n = n / 2 for i in range(3, int(math.sqrt(n))+1,2): while n % i== 0: prime_factors.append(i) n = n / i...
bigcode/self-oss-instruct-sc2-concepts
def load_figer_set_present_in_conll(file_path): """ Load the freebase types that were present in conll dataset. """ types_covered_local = set() with open(file_path) as file_i: for row in file_i: fb_type, _ = row.split('\t') types_covered_local.add(fb_type) return ...
bigcode/self-oss-instruct-sc2-concepts
def get_percentile_dict(yhat_name, valid, id_): """ Returns the percentiles of a column, yhat_name, as the indices based on another column id_. :param yhat_name: Name of column in valid in which to find percentiles. :param valid: Pandas validation frame. :param id_: Validation Pandas frame con...
bigcode/self-oss-instruct-sc2-concepts
def get_container_indicators(item_json): """Returns container indicator(s) for an archival object. Args: item_json (dict): ArchivesSpace archival object information that has resolved top containers and digital objects. Returns: string or None: A concatenated string containing t...
bigcode/self-oss-instruct-sc2-concepts
def filter_traceback(tb_list): """Given a traceback as a list of strings, looks for common boilerplate and removes it.""" # List of boiler plate pattern to look for, with example before each # The match pattern is just some string that the line needs to contain """ File "asynq/async_task.py", l...
bigcode/self-oss-instruct-sc2-concepts
import json def read_json(file_path: str) -> dict: """ Function that reads JSON configuration file and returns data. >>> from snakypy import helpers >>> file = '/tmp/file.json' >>> helpers.files.read_json(file) Args: file_path (str): You must receive the full/absolute file path ...
bigcode/self-oss-instruct-sc2-concepts
import math def floor(x): """Round x to the nearest whole number smaller than or equal to x.""" return math.floor(x)
bigcode/self-oss-instruct-sc2-concepts
import re def words(text): """Get all words from the text.""" return re.findall("[a-z]+", text.lower())
bigcode/self-oss-instruct-sc2-concepts
import re def parse_signature(signature): """ Parses one signature :param signature: stanc3 function signature :return: return type, fucntion name and list of function argument types """ rest, return_type = signature.rsplit("=>", 1) function_name, rest = rest.split("(", 1) args = re.fi...
bigcode/self-oss-instruct-sc2-concepts
def rgb(rgb_colors): """ Return a tuple of integers, as used in AWT/Java plots. Parameters ---------- rgb_colors : list Represents a list with three positions that correspond to the percentage red, green and blue colors. Returns ------- tuple Represents a tuple ...
bigcode/self-oss-instruct-sc2-concepts
def _triangulate(g, comb_emb): """ Helper function to schnyder method for computing coordinates in the plane to plot a planar graph with no edge crossings. Given a connected graph g with at least 3 vertices and a planar combinatorial embedding comb_emb of g, modify g in place to form a graph whose ...
bigcode/self-oss-instruct-sc2-concepts
def enabled_disabled(b): """Convert boolean value to 'enabled' or 'disabled'.""" return "enabled" if b else "disabled"
bigcode/self-oss-instruct-sc2-concepts
def match_update_from_regex(re_parsing_rules, stmt): """Parse an update statement using regexes. Args: re_parsing_rules (dict): Dictionary containing the rules for parsing statements as values and their effects as keys. stmt (str): String representing a statement Returns: ...
bigcode/self-oss-instruct-sc2-concepts
import requests import json def custom_ws_perm_maker(user_id: str, ws_perms: dict): """ Returns an Adapter for requests_mock that deals with mocking workspace permissions. :param user_id: str - the user id :param ws_perms: dict of permissions, keys are ws ids, values are permission. Example: {...
bigcode/self-oss-instruct-sc2-concepts
def heuristic(point_1, point_2): """Calculates the manhattan distance between points and returns an integer""" x1, y1 = point_1 x2, y2 = point_2 man_dist = abs(x1 - x2) + abs(y1 - y2) return man_dist
bigcode/self-oss-instruct-sc2-concepts
def read_whitelist(whitelist_file): """This function reads the white list file and returns the list""" # create an empty dictionary to store the white lists whitelistdict = {} with open(whitelist_file, 'r') as fp: for line in fp: whitelistdict[line.strip()] = True # return the ...
bigcode/self-oss-instruct-sc2-concepts
def create_count_neighbors_ca1d(width): """ Returns a list with the weights for 'neighbors' and 'center_idx' parameters of evodynamic.connection.cellular_automata.create_conn_matrix_ca1d(...). The weights are responsible to count the number of alive neighbors. Parameters ---------- width : int Neig...
bigcode/self-oss-instruct-sc2-concepts
import re def isHour(time): """renvoit 1 si l'heure est au bon format pour etre transformé en heure, 0 sinon""" try: assert isinstance(time, str) regex = re.compile(r"[0-9]*:[0-9]*") assert regex.match(time) args = time.split(":") assert len(args) == 2 and isinstance(...
bigcode/self-oss-instruct-sc2-concepts
import base64 def base642str(s: str): """ Convert a base64 to string. :param s: the base64 string :return: a string """ return base64.b64decode(s).decode()
bigcode/self-oss-instruct-sc2-concepts
import struct def u32(x): """Unpacks a 4-byte string into an integer (little endian)""" return struct.unpack('<I', x)[0]
bigcode/self-oss-instruct-sc2-concepts
import http def auth_reject(realm=None): """ Returns a HTTP 401 UNAUTHORIZED response to a user that is being rejected from requesting a resource. Use the realm param to control which realm is provided in the rejection """ auth_header_value = 'Basic' if realm is not None: auth_header_...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def sha1(text_: str) -> str: """Get SHA1 hash from string in hex form.""" return hashlib.sha1(str(text_).encode("UTF-8")).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def get_current_account_id(context): """ Get current account id. @param context: the context of the event @return: current account id """ return context.invoked_function_arn.split(":")[4]
bigcode/self-oss-instruct-sc2-concepts
def getShortVersion(version: str) -> str: """ :param version: A Python version. :return: The major and minor part of 'version'. """ return '.'.join(version.split('.')[:2])
bigcode/self-oss-instruct-sc2-concepts
import math def dip(x0, z0, x1, z1): """ Compute dip between two points: (x0, z0) (x1, z1) Parameters ---------- x0 : float X-coordinate of point 0 x1 : float X-coordinate of point 1 z0 : float Z-coordinate of point 0 z1 : float Z-coordinate of point 1 ...
bigcode/self-oss-instruct-sc2-concepts
def get_n_grams(text, n): """ Computes the n-grams of a given text :rtype : list :param text: The text provided :param n: The n of n-grams :return: List of all the word's n-grams """ # returning the list of n-grams return [text[i:i+n] for i in range(len(text) - n + 1)]
bigcode/self-oss-instruct-sc2-concepts
def normalize(z): """ Normalize an array. :param z: The array to normalize :type z: array """ return (z - min(z)) / (max(z) - min(z))
bigcode/self-oss-instruct-sc2-concepts
import string def str_to_python_id(val): """Convert a string to a valid python id in a reversible way Arguments: val (str): The value to convert Returns: str: The valid python id """ result = '' for c in val: if c in string.ascii_letters or c == '_': resul...
bigcode/self-oss-instruct-sc2-concepts
def set_generator(filename, index): """ Given a file, returns a set with all the values from the column[index] """ results = set() with open(filename, 'r') as fi: for line in fi: line = line.strip().split() results.add(line[index]) return results
bigcode/self-oss-instruct-sc2-concepts
def fetch_pipe_elements(pipesystem, ignore_inlets=False, ignore_outlets=False): """Iterates through the PipeSystem and returns a list of all PipeElements Arguments ------------------ pipesystem : PipeSystem The PipeSystem for which the elements should be gathered for ignore_inlets : bool ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_requirements(reqs_filename: str) -> List[str]: """Get a package's requirements based on its requirements file.""" try: with open(reqs_filename, "r", encoding="utf-8") as reqs_file: reqs = reqs_file.read().strip().split() return reqs except FileN...
bigcode/self-oss-instruct-sc2-concepts
def adjust_to_1(row): """If total sum larger than 1, remove the differnce from largest value.""" total = sum(row) if total > 1: largest = max(row) replace = row.index(largest) row[replace] = largest - (total-1) return row
bigcode/self-oss-instruct-sc2-concepts
def _set_default_duty_cycle(duty_cycle: float, type_id: int) -> float: """Set the default max rated temperature for mechanical relays. :param duty_cycle: the current duty cycle. :param type_id: the type ID of the relay with missing defaults. :return: _duty_cycle :rtype: float """ if duty_cy...
bigcode/self-oss-instruct-sc2-concepts
def _R(T, Cr, n): """ Basic function for calculating relaxation time due to the Raman mechanism. For canonical definition, see fx. DOI: 10.1039/c9cc02421b Input T: temperature for the calculation Cr: Raman pre-factor n: Raman exponent Output tau: relaxation time due to ...
bigcode/self-oss-instruct-sc2-concepts
def partially_tracked(df, track_ratios): """Number of objects tracked between 20 and 80 percent of lifespan.""" del df # unused return track_ratios[(track_ratios >= 0.2) & (track_ratios < 0.8)].count()
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def trim_microseconds(dt: datetime) -> datetime: """Trim microseconds from a datetime as per ECMA-262.""" return dt.replace(microsecond=((dt.microsecond // 1000) * 1000))
bigcode/self-oss-instruct-sc2-concepts
import torch def temporal_separation_loss(cfg: dict, coords: torch.Tensor) -> torch.Tensor: """ Encourages key-point to have different temporal trajectories. :param cfg: Configuration dictionary :param coords: Key-point coordinates tensor in (N, T, C, 3) :return: The separation loss """ # Tr...
bigcode/self-oss-instruct-sc2-concepts
def rank2int(rank): """Convert a rank/placing string into an integer.""" ret = None try: ret = int(rank.replace(u'.',u'')) except Exception: pass return ret
bigcode/self-oss-instruct-sc2-concepts
def write(path, content): """Write to file.""" with open(path, 'a') as _file: return _file.write(content)
bigcode/self-oss-instruct-sc2-concepts
def slice_up_range(n, num_slices, start=0): """ Divides up `range(start,start+n)` into `num_slices` slices. Parameters ---------- n : int The number of (consecutive) indices in the range to be divided. num_slices : int The number of slices to divide the range into. start :...
bigcode/self-oss-instruct-sc2-concepts
def normalize_image(x): """ Normalize an image so its values are between 0.0 and 1.0. This is useful for plotting the gradient. """ # Get the min and max values for all pixels in the input. x_min = x.min() x_max = x.max() # Normalize so all values are between 0.0 and 1.0 x_norm = (x...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_docket(auth_token, docket_number, court_name, client_matter="", cached=True, normalize=True): """ Takes in an authentication token as a string, a docket number as a string, and the court name as a string, and returns the docket data as a dictionary. Optional parameters are...
bigcode/self-oss-instruct-sc2-concepts
def format_phone_number(phone): """ Given a phone number as a string of digits (only), format for presentation. Local Libya numbers will look like '+218 (0)xx-xxx-xxxx', and Thuraya numbers will look like '+88216xxxxxxx' (per Elliott, Hipchat, Dec. 30, 2014). You can also use this from a template: ...
bigcode/self-oss-instruct-sc2-concepts
def maxim(numar1, numar2): """Funcție ce determină maximul dintre două numere.""" if numar1 > numar2: return numar1 elif numar2 > numar1: return numar2 else: # Numerele sunt egale return numar1
bigcode/self-oss-instruct-sc2-concepts
def df_retrieve(data,cols_vals): """ Retrieves a subset of a dataframe based on equivalence matches Parameters: data (pandas.DataFrame): the dataframe from which a subset is to be created from cols_vals (dict): a dict with the key as the column name and the val as the equivalence val ...
bigcode/self-oss-instruct-sc2-concepts
def process_nlp_response(get_response): """ This function takes as input an NLP GET response and returns a list of concept codes. Input: get_response - A list of GET responses Output: codes - A list of concept Codes """ keep = ["ICD9CM", "ICD10CM", "RXNORM", "SNOMEDCT_US", "SNOMED", "NCI"]...
bigcode/self-oss-instruct-sc2-concepts
def mclag_domain_id_valid(domain_id): """Check if the domain id is in acceptable range (between 1 and 4095) """ if domain_id<1 or domain_id>4095: return False return True
bigcode/self-oss-instruct-sc2-concepts
def package_name_from_url(url): """Parse out Package name from a repo git url""" url_repo_part = url.split('/')[-1] if url_repo_part.endswith('.git'): return url_repo_part[:-4] return url_repo_part
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def is_empty_directory(path: Path) -> bool: """ Returns if path is a directory with no content. """ sentinel = object() return path.is_dir() and next(path.iterdir().__iter__(), sentinel) == sentinel
bigcode/self-oss-instruct-sc2-concepts
def _StopOps(from_ops, stop_gradient_ops, pending_count): """The set of ops that terminate the gradient computation. This computes the frontier of the forward graph *before* which backprop should stop. Operations in the returned set will not be differentiated. This set is defined as the subset of `from_ops` co...
bigcode/self-oss-instruct-sc2-concepts
def merge_dict(a: dict, b: dict) -> dict: """ Merge 2 dictionaries. If the parent and child shares a similar key and the value of that key is a dictionary, the key will be recursively merged. Otherwise, the child value will override the parent value. Parameters ---------- a dict: P...
bigcode/self-oss-instruct-sc2-concepts
def spammer_cmd_header(username): """Return formatted text for spammer command header. Args: username (str): DeviantArt username. Returns: str: Formatted text for spammer command header. """ return '\n'.join([ 'REPORT LINK: https://contact.deviantartsupport.com/en?subOption...
bigcode/self-oss-instruct-sc2-concepts
def placeholder(_: str): """ Return False. Using this as a command argument annotation will always fail the command. Useful for groups. """ return False
bigcode/self-oss-instruct-sc2-concepts
def sbs_annotation_converter(x: str) -> str: """ Eithers swaps from word -> arrow format for SBS or vice versa. word: (REF)(ALT)(LEFT)(RIGHT) arrow: (LEFT)[(REF)>(ALT)](RIGHT) """ if '>' in x: return x[2]+x[4]+x[0]+x[6] else: return x[2]+'['+x[0]+'>'+x[1]+']'+x[3]
bigcode/self-oss-instruct-sc2-concepts
def _check_consistency_sizes(list_arrays) : """Check if all arrays in list have the same size Parameters: ----------- list_arrays: list of numpy arrays Return ------ bool: True if all arrays are consistent, False otherwise. """ if len(list_arrays) == 0 : return True re...
bigcode/self-oss-instruct-sc2-concepts
def validate_probability(p: float, p_str: str) -> float: """Validates that a probability is between 0 and 1 inclusively. Args: p: The value to validate. p_str: What to call the probability in error messages. Returns: The probability p if the probability if valid. Raises: ...
bigcode/self-oss-instruct-sc2-concepts
def remove_newlines(text): # type: (str) -> str """ Remove newlines. The `name` field serves as a displayable title. We remove newlines and leading and trailing whitespace. We also collapse consecutive spaces to single spaces. :param text: Text for newline removal :return: Single line of t...
bigcode/self-oss-instruct-sc2-concepts
def get_layer_parents(adjList,lidx): """ Returns parent layer indices for a given layer index. """ return [e[0] for e in adjList if e[1]==lidx]
bigcode/self-oss-instruct-sc2-concepts
def extract_bmpstp(filename): """ Extracts Bmpstp from filename. Filenames are often of the form: fort.Bmpstp or: fort.(Bmpstp+myid) """ ii = int(filename.split('fort.')[1].split('+myid')[0]) # Extract from filename # Not true? #if ii >= 100: # print(...
bigcode/self-oss-instruct-sc2-concepts
def intersect_2d(x1, x2): """ Given two arrays [m1, n], [m2,n], returns a [m1, m2] array where each entry is True if those rows match. :param x1: [m1, n] numpy array :param x2: [m2, n] numpy array :return: [m1, m2] bool array of the intersections """ if x1.shape[1] != x2.shape[1]: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def flags_to_args(flags: dict[str, Any]) -> dict[str, Any]: """ Turn flags dict from docopt into **kwargs-usable dict. '--'-prefix is removed, dashes are turned into underscores and keys are lowercased. When conflicts arise (ie --repo: None vs REPO: "ideaseed"), do a 'or', ...
bigcode/self-oss-instruct-sc2-concepts
def createFile(name, paramToValue, numberOfCycles=1): """Creates a dictionary storing file information""" File = {'name': name, 'paramToValue': paramToValue, 'numberOfCycles': numberOfCycles} return File
bigcode/self-oss-instruct-sc2-concepts
def rol(x, i): """Rotate the bottom 32 bits of x left by i bits.""" return ((x << i) | ((x & 0xffffffff) >> (32 - i))) & 0xffffffff
bigcode/self-oss-instruct-sc2-concepts
import traceback def _formatException(_, ei): """ Format and return the specified exception information as a string. This implementation builds the complete stack trace, combining traceback.format_exception and traceback.format_stack. """ lines = traceback.format_exception(*ei) if ei[2]: ...
bigcode/self-oss-instruct-sc2-concepts
def virial_temp_HB(mass, z): """Virial temperature from halo mass according to Haiman & Bryan (2006ApJ...650....7). z is the redshift. Units are Msun and kelvin. """ return 1800. * (mass/1e6)**(2./3.) * (1.+z)/21
bigcode/self-oss-instruct-sc2-concepts
import json def GetDataFromFile(filename): """ Retrives JSON formatted data from a file and loads as a Python object. Returns False if the requested file is unreadable. """ try: fileObj = open(filename, 'r') except IOError: return False data = json.load(fileObj) fileObj.close() return data
bigcode/self-oss-instruct-sc2-concepts
def is_not_outstanding(invoice): """ Return `True` if the given invoice is paid """ return invoice.status == 'Paid'
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def resolve_path(path: Path, database_yml: Path) -> Path: """Resolve path Parameters ---------- path : `Path` Path. Can be either absolute, relative to current working directory, or relative to `config.yml`. database_yml : `Path` Path to pyannote.d...
bigcode/self-oss-instruct-sc2-concepts
def get_revision_ids_for_credential(credential): """ For the given credential, return a list of archive credential IDs. """ _range = range(1, credential.revision + 1) ids = [] for i in _range: ids.append("{0}-{1}".format(credential.id, i)) return ids
bigcode/self-oss-instruct-sc2-concepts
def inverse_mvr(mean, var): """ Inverse function of the negative binomial fixed-dispersion mean-variance relationship. Vectorized. Parameters ---------- mean, var : float The mean and variance of a NB distribution, respectively. Returns ------- float The dispersion ...
bigcode/self-oss-instruct-sc2-concepts
def state_from_scratch(args: tuple, kwargs: dict) -> dict: """Create pipeline state from (args, kwargs).""" state = {i: v for i, v in enumerate(args)} state.update(kwargs) return state
bigcode/self-oss-instruct-sc2-concepts
def timestr(seconds): """Return time as string M:SS.""" minutes = seconds // 60 seconds = seconds - (minutes * 60) return f"{minutes}:{seconds:02}"
bigcode/self-oss-instruct-sc2-concepts
import torch def zeros_like(input, *args, **kwargs): """ In ``treetensor``, you can use ``zeros_like`` to create a tree of tensors with all zeros like another tree. Example:: >>> import torch >>> import treetensor.torch as ttorch >>> ttorch.zeros_like(torch.randn(2, 3)) # the sa...
bigcode/self-oss-instruct-sc2-concepts
def resolve_mro(model, name, predicate): """ Return the list of successively overridden values of attribute ``name`` in mro order on ``model`` that satisfy ``predicate``. Model classes (the ones that appear in the registry) are ignored. """ result = [] for cls in type(model).__mro__: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import List def _listify(chars: str) -> Optional[List]: """ Converts a string into a list of characters. :param chars: String containing the characters you wish to turn into a list. :return: List of characters. """ return list(chars)
bigcode/self-oss-instruct-sc2-concepts
def islower(text): """ Checks if all cased characters in ``text`` are lowercase and there is at least one cased character. Cased characters are defined by the Unicode standard. All alphabetic characters in the ASCII character set are cased. :param text: The string to check :type text...
bigcode/self-oss-instruct-sc2-concepts
def startswith(s, prefix): """ True if the string starts with the specified prefix. """ return s.startswith(prefix)
bigcode/self-oss-instruct-sc2-concepts
def _section(section_name, section_data): """Add opening/closing section_name tags to data.""" opening_tag = ['<' + section_name + '>'] closing_tag = ['</' + section_name + '>'] section = None if isinstance(section_data, list): section = opening_tag + section_data + closing_tag elif isi...
bigcode/self-oss-instruct-sc2-concepts
def sanitize(name): """ Sanitize the specified ``name`` for use with breathe directives. **Parameters** ``name`` (:class:`python:str`) The name to be sanitized. **Return** :class:`python:str` The input ``name`` sanitized to use with breathe directives (primarily for use ...
bigcode/self-oss-instruct-sc2-concepts
def obj_get_name(obj): """get_name(obj) return object name.""" return obj.__name__
bigcode/self-oss-instruct-sc2-concepts
def clock_emoji(time): """ Accepts an hour (in 12 or 24 hour format) and returns the correct clock emoji. Args: time: 12 or 24 hour format time (:00 or :30) Returns: clock: corresponding clock emoji. """ hour_emojis = { "0": "🕛", "1": "🕐", "2": "🕑", ...
bigcode/self-oss-instruct-sc2-concepts
import itertools def count_alive_neighbors(alive_cells: set, coords: tuple) -> int: """return the number of alive neighbors of a given cell""" alive = 0 ranges = ((c-1, c, c+1) for c in coords) for cell in itertools.product(*ranges): if cell in alive_cells: alive += 1 if coords...
bigcode/self-oss-instruct-sc2-concepts
def minor(matrix: list[list], row: int, column: int) -> list[list]: """ >>> minor([[1, 2], [3, 4]], 1, 1) [[1]] """ minor = matrix[:row] + matrix[row + 1 :] return [row[:column] + row[column + 1 :] for row in minor]
bigcode/self-oss-instruct-sc2-concepts
def maxpitchamp(amparray): """ Max Pitch Amplitude audio feature: High Predictability rate (86%) :param amparray: array of pitch period amplitudes (floats) :return maxamp: Max pitch period amplitude """ maxamp = 0 if len(amparray) > 0: maxamp = max(amparray) return maxamp
bigcode/self-oss-instruct-sc2-concepts
def get_overlap(a, b): """ Computes the amount of overlap between two intervals. Returns 0 if there is no overlap. The function treats the start and ends of each interval as inclusive, meaning that if a = b = [10, 20], the overlap reported would be 11, not 10. Args: a: Fi...
bigcode/self-oss-instruct-sc2-concepts
def _GetResourceMessageClassName(singular_name): """Returns the properly capitalized resource class name.""" resource_name = singular_name.strip() if len(resource_name) > 1: return resource_name[0].upper() + resource_name[1:] return resource_name.capitalize()
bigcode/self-oss-instruct-sc2-concepts