seed
stringlengths
1
14k
source
stringclasses
2 values
def splitOut(aa): """Splits out into x,y,z, Used to simplify code Args: aa - dictionary spit out by Returns: outkx, outky, outkz (numpy arrays) - arrays of the x, y, and values of the points """ outkx = aa['x'][::3] outky = aa['x'][1::3] outkz = aa['x'][2::3] return out...
bigcode/self-oss-instruct-sc2-concepts
def unwrap_cdata(value): """Remove CDATA wrapping from `value` if present""" if value.startswith("<![CDATA[") and value.endswith("]]>"): return value[9:-3] else: return value
bigcode/self-oss-instruct-sc2-concepts
import pkgutil def get_all_modules(package_path): """Load all modules in a package""" return [name for _, name, _ in pkgutil.iter_modules([package_path])]
bigcode/self-oss-instruct-sc2-concepts
def GetDeviceNamesFromStatefulPolicy(stateful_policy): """Returns a list of device names from given StatefulPolicy message.""" if not stateful_policy or not stateful_policy.preservedState \ or not stateful_policy.preservedState.disks: return [] return [disk.key for disk in stateful_policy.pres...
bigcode/self-oss-instruct-sc2-concepts
def replace_tabs(string: str, tab_width: int = 4) -> str: """Takes an input string and a desired tab width and replaces each \\t in the string with ' '*tab_width.""" return string.replace('\t', ' '*tab_width)
bigcode/self-oss-instruct-sc2-concepts
def closestsites(struct_blk, struct_def, pos): """ Returns closest site to the input position for both bulk and defect structures Args: struct_blk: Bulk structure struct_def: Defect structure pos: Position Return: (site object, dist, index) """ blk_close_sites = stru...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import inspect def compare_attributes(obj1: Any, obj2: Any, *, ignore_simple_underscore: bool = False) -> bool: """Compares all attributes of two objects, except for methods, __dunderattrs__, and, optionally, _private_attrs. Args: obj1 (Any): First object to compare. ob...
bigcode/self-oss-instruct-sc2-concepts
def _updated_or_published(mf): """ get the updated date or the published date Args: mf: python dictionary of some microformats object Return: string containing the updated date if it exists, or the published date if it exists or None """ props = mf['properties'] # construct updated/published date of mf ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def is_file(path: Path) -> bool: """ Return true if the given path is a file, false otherwise. :param path: a Path :return: a bool """ return path.is_file()
bigcode/self-oss-instruct-sc2-concepts
def dict2str(d): """Pretty formatter of a dictionary for one-line logging.""" return str(sorted(d.items()))
bigcode/self-oss-instruct-sc2-concepts
def retrieve_min_max_from_path(path): """looks for min and max float in path Args: path (str): folder path Returns: (float, float) retrieved min and max values """ path = path.replace("\\", "") path = path.replace("/", "") return float(path.split("_")[-2]), float(path.split...
bigcode/self-oss-instruct-sc2-concepts
def type_unpack(type): """ return the struct and the len of a particular type """ type = type.lower() s = None l = None if type == 'short': s = 'h' l = 2 elif type == 'bool': s = 'c' l = 1 elif type == 'ushort': s = 'H' l = 2 elif type == '...
bigcode/self-oss-instruct-sc2-concepts
def get_unicode_code_points(string): """Returns a string of comma-delimited unicode code points corresponding to the characters in the input string. """ return ', '.join(['U+%04X' % ord(c) for c in string])
bigcode/self-oss-instruct-sc2-concepts
def as_markdown(args): """ Return args configs as markdown format """ text = "|name|value| \n|-|-| \n" for attr, value in sorted(vars(args).items()): text += "|{}|{}| \n".format(attr, value) return text
bigcode/self-oss-instruct-sc2-concepts
def ndbi(swir, red, nir, blue): """ Converts the swir, red, nir and blue band of Landsat scene to a normalized difference bareness index. Source: Zao and Chen, "Use of Normalized Difference Bareness Index in Quickly Mapping Bare from TM/ETM+", IEEE Conference Paper, 2005 DOI: 10.1109/IGARSS.200...
bigcode/self-oss-instruct-sc2-concepts
import torch def reg_binary_entropy_loss(out): """ Mean binary entropy loss to drive values toward 0 and 1. Args: out (torch.float): Values for the binary entropy loss. The values have to be within (0, 1). Return: torch.float for the loss value. """ return torch.mean...
bigcode/self-oss-instruct-sc2-concepts
def get_hyperion_unique_id(server_id: str, instance: int, name: str) -> str: """Get a unique_id for a Hyperion instance.""" return f"{server_id}_{instance}_{name}"
bigcode/self-oss-instruct-sc2-concepts
def getModel(tsinput): """ This is the wrapper function for all profile models implemented in the runInput package. Parameters ---------- tsinput : :class:`.tsinput` A TurbSim input object. Returns ------- profModel : A subclass of :class:`.profModelBase` ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Collection from typing import Set def split_csp_str(val: Union[Collection[str], str]) -> Set[str]: """Split comma separated string into unique values, keeping their order.""" if isinstance(val, str): val = val.strip().split(",") return set(x for x in val...
bigcode/self-oss-instruct-sc2-concepts
def identity(*args): """ Always returns the same value that was used as its argument. Example: >>> identity(1) 1 >>> identity(1, 2) (1, 2) """ if len(args) == 1: return args[0] return args
bigcode/self-oss-instruct-sc2-concepts
import pathlib from typing import Optional def latest_checkpoint_update(target: pathlib.Path, link_name: str) -> Optional[pathlib.Path]: """ This function finds the file that the symlink currently points to, sets it to the new target, and returns the previous target if it exis...
bigcode/self-oss-instruct-sc2-concepts
def isTIFF(filename: str) -> bool: """Check if file name signifies a TIFF image.""" if filename is not None: if(filename.casefold().endswith('.tif') or filename.casefold().endswith('.tiff')): return True return False
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def dataset_is_authoritative(dataset: Dict) -> bool: """Check if dataset is tagged as authoritative.""" is_authoritative = dataset.get("isAuthoritative") if is_authoritative: return is_authoritative["value"] == "true" return False
bigcode/self-oss-instruct-sc2-concepts
def max_farmers(collection): # pragma: no cover """Returns the maximum number of farmers recorded in the collection""" max_farmers = 0 for doc in collection.find({}).sort([('total_farmers',-1)]).limit(1): max_farmers = doc['total_farmers'] return max_farmers
bigcode/self-oss-instruct-sc2-concepts
import hashlib import pathlib def calculate_file_hash(file_path): """ Calculate the hash of a file on disk. We store a hash of the file in the database, so that we can keep track of files if they are ever moved to new drives. :param file_path: :return: """ block_size = 65536 has...
bigcode/self-oss-instruct-sc2-concepts
def word_fits_in_line(pagewidth, x_pos, wordsize_w): """ Return True if a word can fit into a line. """ return (pagewidth - x_pos - wordsize_w) > 0
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def create_gyre_prefix(gyre_comb: Dict[str, Any]) -> str: """ Creates a GYRE run prefix to use for the given combination of GYRE parameter values. These prefixes should be unique within one MESA run, but can be repeated across multiple, separate, MESA run...
bigcode/self-oss-instruct-sc2-concepts
def findAllInfectedRelationships(tx): """ Method that finds all INFECTED relationships in the data base :param tx: is the transaction :return: a list of relationships """ query = ( "MATCH (n1:Person)-[r:COVID_EXPOSURE]->(n2:Person) " "RETURN ID(n1) , r , r.date , r.name , ID(n2);...
bigcode/self-oss-instruct-sc2-concepts
import typing def is_same_classmethod( cls1: typing.Type, cls2: typing.Type, name: str, ) -> bool: """Check if two class methods are not the same instance.""" clsmeth1 = getattr(cls1, name) clsmeth2 = getattr(cls2, name) return clsmeth1.__func__ is clsmeth2.__func__
bigcode/self-oss-instruct-sc2-concepts
import socket import pickle def send_packet(sock, pack): """ Send a packet to remote socket. We first send the size of packet in bytes followed by the actual packet. Packet is serialized using cPickle module. Arguments --------- sock : Destination socket pack : Instance of class...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_all_indcs(batch_size, n_possible_points): """ Return all possible indices. """ return torch.arange(n_possible_points).expand(batch_size, n_possible_points)
bigcode/self-oss-instruct-sc2-concepts
def N_STS_from_N_SS(N_SS, STBC): """ Number of space-time streams (N_{STS}) from number of spatial streams (N_{SS}), and the space-time block coding (STBC) used. The standard gives this a table (20-12), but it's just addition! """ return N_SS + STBC
bigcode/self-oss-instruct-sc2-concepts
def num_grid_points(d, mu): """ Checks the number of grid points for a given d, mu combination. Parameters ---------- d, mu : int The parameters d and mu that specify the grid Returns ------- num : int The number of points that would be in a grid with params d, mu ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime import time def get_end_date_of_schedule(schedule): """Return the end date of the provided schedule in ISO 8601 format""" currenttime = datetime.today() endtime = datetime( currenttime.year, currenttime.month, currenttime.day, schedule['end-hour'], schedule['end-minut...
bigcode/self-oss-instruct-sc2-concepts
def get_uncert_dict(res): """ Gets the row and column of missing values as a dict Args: res(np.array): missing mask Returns: uncertain_dict (dict): dictionary with row and col of missingness """ uncertain_dict = {} for mytuple in res: row = mytuple[0] col = mytuple[...
bigcode/self-oss-instruct-sc2-concepts
def _and(*args): """Helper function to return its parameters and-ed together and bracketed, ready for a SQL statement. eg, _and("x=1", "y=2") => "(x=1 AND y=2)" """ return " AND ".join(args)
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def load_lookup_from_csv(csv_source: str, count: int) -> Dict[str, int]: """ From Dino, feature extraction utils Load a lookup dictionary, mapping string to rank, from a CSV file. Assumes the CSV to be pre-sorted. :param csv_source: Source data filepath :param count: nu...
bigcode/self-oss-instruct-sc2-concepts
def get_edges(mapping): """ Returns the sorted edge list for topology. :param mapping: Process-to-node mapping :return: Topology edge list """ proc_map = mapping.mapping edges = mapping.process_graph.edges(data=True) return sorted([(min(proc_map[u], proc_map[v]), max(...
bigcode/self-oss-instruct-sc2-concepts
import random import string def get_shipping_details_response(order_id, address_id): """ Creates a json response for a shipping details request. :param order_id: ID for the transaction. :param address_id: Address ID received from Vipps. :return: A json response for a shipping details request. ...
bigcode/self-oss-instruct-sc2-concepts
def fillgaps_time(ds, method='cubic', max_gap=None): """ Fill gaps (nan values) across time using the specified method Parameters ---------- ds : xarray.Dataset The adcp dataset to clean method : string Interpolation method to use max_gap : numeric Max number of consective...
bigcode/self-oss-instruct-sc2-concepts
def predict1(payload): """ Define a hosted function that echos out the input. When creating a predict image, this is the function that is hosted on the invocations endpoint. Arguments: payload (dict[str, object]): This is the payload that will eventually be sent to the server us...
bigcode/self-oss-instruct-sc2-concepts
def signtest_data(RNG,n,trend=0): """ Creates a dataset of `n` pairs of normally distributed numbers with a trend towards the first half of a pair containing smaller values. If `trend` is zero, this conforms with the null hypothesis. """ return [( RNG.normal(size=size)-trend, RNG.normal(size=size) ) for ...
bigcode/self-oss-instruct-sc2-concepts
import re def finditer_with_line_numbers(pattern, input_string, flags=0): """ A version of 're.finditer' that returns '(match, line_number)' pairs. """ matches = list(re.finditer(pattern, input_string, flags)) if not matches: return [] end = matches[-1].start() # -1 so a failed '...
bigcode/self-oss-instruct-sc2-concepts
import csv def read_employees(csv_file_location): """ Convert csv file to dictionary. Receives a CSV file as a parameter and returns a list of dictionaries from that file. """ csv.register_dialect("empDialect", skipinitialspace=True, strict=True) employee_file = csv.DictReader( op...
bigcode/self-oss-instruct-sc2-concepts
def drop_irrelevant_practices(df, practice_col): """Drops irrelevant practices from the given measure table. An irrelevant practice has zero events during the study period. Args: df: A measure table. practice_col: column name of practice column Returns: A copy of the given measur...
bigcode/self-oss-instruct-sc2-concepts
import codecs def encode_endian(text, encoding, errors="strict", le=True): """Like text.encode(encoding) but always returns little endian/big endian BOMs instead of the system one. Args: text (text) encoding (str) errors (str) le (boolean): if little endian Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def features_axis_is_np(is_np, is_seq=False): """ B - batch S - sequence F - features :param d: torch.Tensor or np.ndarray of shape specified below :param is_seq: True if d has sequence dim :return: axis of features """ if is_np: # in case of sequence (is_seq == True): (S, F)...
bigcode/self-oss-instruct-sc2-concepts
def parse_args(args): """Parses and validates command line arguments Args: args (argparse.Namespace): Pre-paresed command line arguments Returns: bool: verbose flag, indicates whether tag frequency dictionary should be printed bool: sandbox flag, indicates whether Evernote API call...
bigcode/self-oss-instruct-sc2-concepts
def _extract_prop_set(line): """ Extract the (key, value)-tuple from a string like: >>> 'set foo = "bar"' :param line: :return: tuple (key, value) """ token = ' = "' line = line[4:] pos = line.find(token) return line[:pos], line[pos + 4:-1]
bigcode/self-oss-instruct-sc2-concepts
import torch def depth_map_to_locations(depth, invK, invRt): """ Create a point cloud from a depth map Inputs: depth HxW torch.tensor with the depth values invK 3x4 torch.tensor with the inverse intrinsics matrix invRt 3x4 torch.tensor with the inver...
bigcode/self-oss-instruct-sc2-concepts
def list_to_quoted_delimited(input_list: list, delimiter: str = ',') -> str: """ Returns a string which is quoted + delimited from a list :param input_list: eg: ['a', 'b', 'c'] :param delimiter: '|' :return: eg: 'a'|'b'|'c' """ return f'{delimiter} '.join("'{0}'".format(str_item) for str_ite...
bigcode/self-oss-instruct-sc2-concepts
def plugin(plugin_without_server): """ Construct mock plugin with NotebookClient with server registered. Use `plugin.client` to access the client. """ server_info = {'notebook_dir': '/path/notebooks', 'url': 'fake_url', 'token': 'fake_token'} plugin_without...
bigcode/self-oss-instruct-sc2-concepts
import typing import pathlib import glob def _get_paths(patterns: typing.Set[pathlib.Path]) -> typing.Set[pathlib.Path]: """Convert a set of file/directory patterns into a list of matching files.""" raw = [ pathlib.Path(item) for pattern in patterns for item in glob.iglob(str(pattern),...
bigcode/self-oss-instruct-sc2-concepts
def _attr2obj(element, attribute, convert): """ Reads text from attribute in element :param element: etree element :param attribute: name of attribute to be read :param convert: intrinsic function (e.g. int, str, float) """ try: if element.get(attribute) is None: return ...
bigcode/self-oss-instruct-sc2-concepts
def create_cercauniversita(conn, cercauni): """ Create a new person into the cercauniversita table :param conn: :param cercauni: :return: cercauni id """ sql = ''' INSERT INTO cercauniversita(id,authorId,anno,settore,ssd,fascia,orcid,cognome,nome,genere,ateneo,facolta,strutturaAfferenza) VALUES(?,?,?,?,?,?,...
bigcode/self-oss-instruct-sc2-concepts
def get_item_from_user(message, lst): """ Gets a valid index from a user to get an item from lst. The user is shown `message` and the range of valid indices, in the form of "Valid indices inclusive between 0 and max_index". The user is asked until a valid item was chosen. Args: messag...
bigcode/self-oss-instruct-sc2-concepts
def cauchy_cooling_sequence(initial_t, it): """ Calculates the new temperature per iteration using a cauchy progression. Parameters ---------- initial_t : float initial temperature it: int actual iteration Returns -------- tt: float new temperature """ tt = initial_t/(1+it) return tt
bigcode/self-oss-instruct-sc2-concepts
def is_end(word, separator): """Return true if the subword can appear at the end of a word (i.e., the subword does not end with separator). Return false otherwise.""" return not word.endswith(separator)
bigcode/self-oss-instruct-sc2-concepts
def _reconstruct_path(target_candidate, scanned): """ Reconstruct a path from the scanned table, and return the path sequence. """ path = [] candidate = target_candidate while candidate is not None: path.append(candidate) candidate = scanned[candidate.id] return path
bigcode/self-oss-instruct-sc2-concepts
import string def query_to_url(query, search_type, size): """convert query to usuable url Args: query (str): search query by user search_type (str): Search type (choice) size (int): number of items to query Returns: (str) the url for search """ # remove bad string & convert txt ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def read_polymer(filename: Path) -> tuple[dict, str]: """Read polymer structure information from a file The polymer is represented by a dict of rules and a polymer structer. Args: filename (Path): path to the input file. Returns: dict: rules str: ...
bigcode/self-oss-instruct-sc2-concepts
def query_phantoms(view, pids): """Query phantoms.""" return view.query_phantoms(pids)
bigcode/self-oss-instruct-sc2-concepts
def get_positive_passages(positive_pids, doc_scores, passage_map): """ Get positive passages for a given grounding using BM25 scores from the positive passage pool Parameters: positive_pids: list Positive passage indices doc_scores: list BM25 scores against the query'...
bigcode/self-oss-instruct-sc2-concepts
def lire_mots(nom_fichier): """fonction qui récupère la liste des mots dans un fichier paramètre - nom_fichier, de type chaine de caractère : nom du fichier contenant les mots (un par ligne) retour : liste de chaine de caractères """ liste_mots = [] # le t...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _hyphens_exists_next_line( line_splitted_list: List[str], next_line_idx: int) -> bool: """ Get the boolean value of whether there are multiple hyphen characters on the next line. Parameters ---------- line_splitted_list : list of str A list containi...
bigcode/self-oss-instruct-sc2-concepts
def get_data(dataset): """Get features and targets from a specific dataset. Parameters ---------- dataset : Dataset object dataset that can provide features and targets Returns ------- features : arrary features in the dataset targets : array 1-d targets in the ...
bigcode/self-oss-instruct-sc2-concepts
def _gen_perm_Numpy(order, mode): """ Generate the specified permutation by the given mode. Parameters ---------- order : int the length of permutation mode : int the mode of specific permutation Returns ------- list the axis order, according to Kolda's unfo...
bigcode/self-oss-instruct-sc2-concepts
def contains_duplicate(nums: list[int]) -> bool: """Returns True if any value appears at least twice in the array, otherwise False Complexity: n = len(nums) Time: O(n) Space: O(n) Args: nums: array of possibly non-distinct values Examples: >>> contains_duplicat...
bigcode/self-oss-instruct-sc2-concepts
def depth_bonacci_rule(depth): """rule for generating tribonacci or other arbitrary depth words Args: depth (int): number of consecutive previous words to concatenate Returns: lambda w: w[-1] + w[-2] + ... + w[-(depth+1)] For example, if depth is 3, you get the tribonacci words. ...
bigcode/self-oss-instruct-sc2-concepts
import re def compile_patterns(patterns): """Compile a list of patterns into one big option regex. Note that all of them will match whole words only.""" # pad intent patterns with \b (word boundary), unless they contain '^'/'$' (start/end) return re.compile('|'.join([((r'\b' if not pat.startswith('^') els...
bigcode/self-oss-instruct-sc2-concepts
def cli(ctx): """Get the list of all data tables. Output: A list of dicts with details on individual data tables. For example:: [{"model_class": "TabularToolDataTable", "name": "fasta_indexes"}, {"model_class": "TabularToolDataTable", "name": "bwa_indexes"}] "...
bigcode/self-oss-instruct-sc2-concepts
def _function_iterator(graph): """Iterate over the functions in a graph. :rtype: iter[str] """ return ( node.function for node in graph )
bigcode/self-oss-instruct-sc2-concepts
def ms_energy_stat(microstates): """ Given a list of microstates, find the lowest energy, average energy, and highest energy """ ms = next(iter(microstates)) lowerst_E = highest_E = ms.E N_ms = 0 total_E = 0.0 for ms in microstates: if lowerst_E > ms.E: lowerst_E = ms...
bigcode/self-oss-instruct-sc2-concepts
import json def check_role_in_retrieved_nym(retrieved_nym, role): """ Check if the role in the GET NYM response is what we want. :param retrieved_nym: :param role: the role we want to check. :return: True if the role is what we want. False if the role is not what we want. """ ...
bigcode/self-oss-instruct-sc2-concepts
def _do_get_features_list(featurestore_metadata): """ Gets a list of all features in a featurestore Args: :featurestore_metadata: metadata of the featurestore Returns: A list of names of the features in this featurestore """ features = [] for fg in featurestore_metadata.fea...
bigcode/self-oss-instruct-sc2-concepts
def vector_dot(xyz, vector): """ Take a dot product between an array of vectors, xyz and a vector [x, y, z] **Required** :param numpy.ndarray xyz: grid (npoints x 3) :param numpy.ndarray vector: vector (1 x 3) **Returns** :returns: dot product between the grid and the (1 x 3) vector, ret...
bigcode/self-oss-instruct-sc2-concepts
def filter_leetify(a, **kw): """Leetify text ('a' becomes '4', 'e' becomes '3', etc.)""" return a.replace('a','4').replace('e','3').replace('i','1').replace('o','0').replace('u','^')
bigcode/self-oss-instruct-sc2-concepts
import ast def eval_string(string): """automatically evaluate string to corresponding types. For example: not a string -> return the original input '0' -> 0 '0.2' -> 0.2 '[0, 1, 2]' -> [0,1,2] 'eval(1+2)' -> 3 'eval(range(5))' -> [0,1,2,3,4] Args: ...
bigcode/self-oss-instruct-sc2-concepts
def convolution(image, kernel, row, column): """ Apply convolution to given image with the kernel and indices. :param image: image that will be convolved. :param kernel: kernel that will be used with convolution. :param row: row index of the central pixel. :param column: row index of the central...
bigcode/self-oss-instruct-sc2-concepts
def token_to_char_position(tokens, start_token, end_token): """Converts a token positions to char positions within the tokens.""" start_char = 0 end_char = 0 for i in range(end_token): tok = tokens[i] end_char += len(tok) + 1 if i == start_token: start_char = end_char return start_char, end_...
bigcode/self-oss-instruct-sc2-concepts
def flatten_image(image): """ Flat the input 2D image into an 1D image while preserve the channels of the input image with shape==[height x width, channels] :param image: Input 2D image (either multi-channel color image or greyscale image) :type image: numpy.ndarray :return: The flatten 1D imag...
bigcode/self-oss-instruct-sc2-concepts
def split_fqdn(fqdn): """ Unpack fully qualified domain name parts. """ if not fqdn: return [None] * 3 parts = fqdn.split(".") return [None] * (3 - len(parts)) + parts[0:3]
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from pathlib import Path import json def read_json(path: Union[str, Path]): """ Read a json file from a string path """ with open(path) as f: return json.load(f)
bigcode/self-oss-instruct-sc2-concepts
def add_arrays(arr1, arr2): """ Function to adds two arrays element-wise Returns the a new array with the result """ if len(arr1) == len(arr2): return [arr1[i] + arr2[i] for i in range(len(arr1))] return None
bigcode/self-oss-instruct-sc2-concepts
def strip_commands(commands): """ Strips a sequence of commands. Strips down the sequence of commands by removing comments and surrounding whitespace around each individual command and then removing blank commands. Parameters ---------- commands : iterable of strings Iterable of co...
bigcode/self-oss-instruct-sc2-concepts
def __merge2sorted__(arr1, arr2): """ Takes two sorted subarrays and returns a sorted array """ m, n = len(arr1), len(arr2) aux_arr = [None] * (m + n) p1 = 0 p2 = 0 c = 0 while p1 < m and p2 < n: if arr1[p1] < arr2[p2]: aux_arr[c] = arr1[p1] p1 += 1 ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def userinfo_token( token_subject: str, token_idp: str, token_ssn: str, ) -> Dict[str, Any]: """ Mocked userinfo-token from Identity Provider (unencoded). """ return { 'iss': 'https://pp.netseidbroker.dk/op', 'nbf':...
bigcode/self-oss-instruct-sc2-concepts
def homo_line(a, b): """ Return the homogenous equation of a line passing through a and b, i.e. [ax, ay, 1] cross [bx, by, 1] """ return (a[1] - b[1], b[0] - a[0], a[0] * b[1] - a[1] * b[0])
bigcode/self-oss-instruct-sc2-concepts
from unittest.mock import call def get_local_jitter(sound, min_time=0., max_time=0., pitch_floor=75., pitch_ceiling=600., period_floor=0.0001, period_ceiling=0.02, max_period_factor=1.3): """ Function to calculate (local) jitter from a periodic PointProcess. :param (parselmouth.Sound...
bigcode/self-oss-instruct-sc2-concepts
def anchor_ctr_inside_region_flags(anchors, stride, region): """Get the flag indicate whether anchor centers are inside regions.""" x1, y1, x2, y2 = region f_anchors = anchors / stride x = (f_anchors[:, 0] + f_anchors[:, 2]) * 0.5 y = (f_anchors[:, 1] + f_anchors[:, 3]) * 0.5 flags = (x >= x1) &...
bigcode/self-oss-instruct-sc2-concepts
def position_is_escaped(string, position=None): """ Checks whether a char at a specific position of the string is preceded by an odd number of backslashes. :param string: Arbitrary string :param position: Position of character in string that should be checked :return: True if the char...
bigcode/self-oss-instruct-sc2-concepts
def select_column_values(df, col_name="totale_casi", groupby=["data"], group_by_criterion="sum"): """ :param df: pandas dataFrame :param col_name: column of interest :param groupby: column to group by (optional) data. :param group_by_criterion: how to merge the values of grouped elements in col_nam...
bigcode/self-oss-instruct-sc2-concepts
def normalize_min_max(x, x_min, x_max): """Normalized data using it's maximum and minimum values # Arguments x: array x_min: minimum value of x x_max: maximum value of x # Returns min-max normalized data """ return (x - x_min) / (x_max - x_min)
bigcode/self-oss-instruct-sc2-concepts
def get_orientation_from(pose): """ Extract and convert the pose's orientation into a list. Args: pose (PoseStamped): the pose to extract the position from Returns: the orientation quaternion list [x, y, z, w] """ return [pose.pose.orientation.x, pose.pose.orientation.y...
bigcode/self-oss-instruct-sc2-concepts
import string def index_to_column(index): """ 0ベース序数をカラムを示すアルファベットに変換する。 Params: index(int): 0ベース座標 Returns: str: A, B, C, ... Z, AA, AB, ... """ m = index + 1 # 1ベースにする k = 26 digits = [] while True: q = (m-1) // k d = m - q * k digit = stri...
bigcode/self-oss-instruct-sc2-concepts
def _listen_count(opp): """Return number of event listeners.""" return sum(opp.bus.async_listeners().values())
bigcode/self-oss-instruct-sc2-concepts
import math def distance(point1, point2): """ Calculates distance between two points. :param point1: tuple (x, y) with coordinates of the first point :param point2: tuple (x, y) with coordinates of the second point :return: distance between two points in pixels """ return math.sqrt(math.pow(po...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Set def scan_polarimeter_names(group_names: List[str]) -> Set[str]: """Scan a list of group names and return the set of polarimeters in it. Example:: >>> group_names(["BOARD_G", "COMMANDS", "LOG", "POL_G0", "POL_G6"]) set("G0", "G6") """ res...
bigcode/self-oss-instruct-sc2-concepts
def get_project_folders(window): """Get project folder.""" data = window.project_data() if data is None: data = {'folders': [{'path': f} for f in window.folders()]} return data.get('folders', [])
bigcode/self-oss-instruct-sc2-concepts
import textwrap def dedented_lines(description): """ Each line of the provided string with leading whitespace stripped. """ if not description: return [] return textwrap.dedent(description).split('\n')
bigcode/self-oss-instruct-sc2-concepts