seed
stringlengths
1
14k
source
stringclasses
2 values
def outliers_z_score(serie, window, treshold): """ Find outliers on a serie based on z-scores. Parameters ---------- :serie: array_like Input array or object that can be converted to an array. :windows: int :treshold: number of standard deviations to filter Retu...
bigcode/self-oss-instruct-sc2-concepts
def check_bw_unit(bw_unit: str) -> str: """Check if the bandwidth unit is one of "gbit" and "mbit". Parameters ---------- bw_unit : str The bandwidth unit. Returns ------- str The bandwidth unit changing to lowercase letters and removing extra spaces. Raises ------...
bigcode/self-oss-instruct-sc2-concepts
import re def to_snake_case(name): """Convert the name from camel-style to snake-style.""" intermediate = re.sub('(.)([A-Z][a-z0-9]+)', r'\1_\2', name) insecure = re.sub('([a-z])([A-Z])', r'\1_\2', intermediate).lower() if insecure[0] != '_': return insecure return insecure[2:]
bigcode/self-oss-instruct-sc2-concepts
def field(name, transform=None): """ Convenience function to explicitly return a "field" specification for a Bokeh :class:`~bokeh.core.properties.DataSpec` property. Args: name (str) : name of a data source field to reference for a ``DataSpec`` property. transform (Transform, o...
bigcode/self-oss-instruct-sc2-concepts
def regulate_column_names(df, test_type): """ Regulate column names for flu_ag test data since Quidel changed their column names multiple times. We want to finalize the column name list to be: ['SofiaSerNum', 'TestDate', 'Facility', 'Zip', 'FluA', 'FluB', 'StorageDate'] """ # No reg...
bigcode/self-oss-instruct-sc2-concepts
def chunk(lines): """Return groups of lines separated by whitespace or comments [(int, str)] -> [[(int, str)]] """ chunks = [] chunk = [] for lineno, line in lines: stripped = line.strip() if not stripped or stripped[0] == '#': if chunk: chunks.append...
bigcode/self-oss-instruct-sc2-concepts
def _user_lookup(key, users): """Given a user id and a list of users, search list for user with matching id. If found, return user name, else return string 'Not Found' Args: key (str): User id to match on users (list of obj): List of users objects (students) Return: (str): U...
bigcode/self-oss-instruct-sc2-concepts
def post_process_response(token_ids, reader, merge=True): """Post-process the decoded sequence. Truncate from the first <eos> and remove the <bos> and <eos> tokens. Convert token_ids to words(merge=True) or tokens(merge=False) Args: token_ids: Token id sequence. merge: If true, merge s...
bigcode/self-oss-instruct-sc2-concepts
def retreive_details(input_dict,keys_to_extract): """ Retreive specific keys from a dictionary object This function searches through a dictionary, and retreives keys that match keys from a list. This function will find matching keys in every level of the dictionary heirarchy. Inputs: ...
bigcode/self-oss-instruct-sc2-concepts
def _get_bbox_feature(image_size, feature_map, x_min, x_max, y_min, y_max): """Get bounding box features. The feature is the center pixel of a bounding box. Args: image_size (tuple): Size of an image in [x, y]. feature_map (numpy.ndarray(numpy.float)): Feature map of size [x, y, n_features...
bigcode/self-oss-instruct-sc2-concepts
def _sane_version_list(version): """Ensure the major and minor are int. Parameters ---------- version : list Version components Returns ------- version : list List of components where first two components has been sanitised """ v0 = str(version[0]) if v0: ...
bigcode/self-oss-instruct-sc2-concepts
def transpose_table(table): """ Transpose any table of values stored as list of lists. Table must be rectangular. Returns: Transposed list of lists. """ n_table = [] while len(n_table) != len(table[0]): n_table += [[]] for col_ind in range(0, len(table[0])): for row_in...
bigcode/self-oss-instruct-sc2-concepts
def _matches2str(matches): """ Get matches into a multi-line string :param matches: matches to convert :return: multi-line string containing matches """ output_text = '' for match in matches: output_text += f"{match[0]} - {match[1]}\n" return output_text
bigcode/self-oss-instruct-sc2-concepts
def parse_list(value): """ Parse a string to extract a simple list of string values. """ if value.startswith('[') and value.endswith(']'): value = value[1:len(value)-1].strip() elif not value.strip(): return [] return list(value.split(','))
bigcode/self-oss-instruct-sc2-concepts
def mk_int(s): """Convert to a int, if it can't, return 0""" s = s.strip().replace(",", "") return int(s) if s else 0
bigcode/self-oss-instruct-sc2-concepts
def load_metaparameters(param_dict=None): """ Parameters for bayesian optimizer. Default dictionary listed and updated by param_dict. The default contains some redundancy dependent on the architecture. If the generic architecture is used, the 'dense_X' values are ignored. If not, the values of 'den...
bigcode/self-oss-instruct-sc2-concepts
def _apply_filters(filters, fn): """ Parameters ---------- filters: a filter bank fn: a function to apply on the parameters Returns ------- filters: the filters modified """ for k in range(len(filters)): filters[k] = fn(filters[k]) return ...
bigcode/self-oss-instruct-sc2-concepts
def bytes_to_int(d): """Convert a list of bytes to an int Bytes are in LSB first. >>> hex(bytes_to_int([0, 1])) '0x100' >>> hex(bytes_to_int([1, 2])) '0x201' """ v = 0 for i,d in enumerate(d): v |= d << (i*8) return v
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources def _check_presence(dependencies): """Check if all dependencies are present. Return missing dependencies.""" missing = [] for dependency in dependencies: requirement = dependency.name + dependency.constraint try: pkg_resources.require(requirement) e...
bigcode/self-oss-instruct-sc2-concepts
import secrets def spoiler(help_text: str, button_text="🕵️ Show Hint") -> str: """ HTML boilerplate for spoiler element in challenge descriptions. """ div_id = secrets.token_hex(5) return f""" <div> <div id="{div_id}-help" class="d-none"> <hr/> ...
bigcode/self-oss-instruct-sc2-concepts
def arrays_as_dataset(states, actions, rewards, next_states, absorbings, lasts): """ Creates a dataset of transitions from the provided arrays. Args: states (np.ndarray): array of states; actions (np.ndarray): array of actions; rewards (np.ndarray): array of rewards; next_st...
bigcode/self-oss-instruct-sc2-concepts
def is_utf8_encoded(bstring): """ Return ``True`` if the given byte string can be decoded into a Unicode string using the UTF-8 decoder. :param bytes bstring: the string to test :rtype: bool """ try: bstring.decode("utf-8") return True except UnicodeDecodeError: ...
bigcode/self-oss-instruct-sc2-concepts
def find_val_or_next_smaller_iter(bst, x, d=None): """Get the greatest value <= x in a binary search tree. Returns None if no such value can be found. """ while True: if bst is None: return d elif bst.val == x: return x elif bst.val > x: (bst, ...
bigcode/self-oss-instruct-sc2-concepts
def _validate_name(name): """ Validates the given name. Parameters ---------- name : `None` or `str` A command's respective name. Returns ------- name : `None` or `str` The validated name. Raises ------ TypeError If `name` is not given a...
bigcode/self-oss-instruct-sc2-concepts
def get_accuracy(Y, Y_pred): """ Calcualtes accuracy. :param Y: int(N, ) Correct labels. :param Y_pred: int(N, ) | double(N, C) Predicted labels of shape(N, ) or (N, C) in case of one-hot vector. :return: double Accuracy. """ return (Y == Y_pred).mean() # return ...
bigcode/self-oss-instruct-sc2-concepts
def fib(n): """ Compute the n'th Fibonacci number. :param n: target Fibonacci number :return: the appropriate number """ if n <=2: return 1 else: return fib(n-1) + fib(n-2)
bigcode/self-oss-instruct-sc2-concepts
def parse_results(results): """ parses the results file into a dictionary of names and tuples """ # hold the results in a dictionary results_dict = {} # loop over each line (result) for result in results: # split the string based on spaces parts = result.split() # there shoul...
bigcode/self-oss-instruct-sc2-concepts
from typing import Type from typing import Any def typed_property(name: str, expected_type: Type[Any]) -> property: """Avoids definition of repetitive property class methods. Simplifies type assertions on class attributes values. Illustrates an important feature of inner functions or closures. Args:...
bigcode/self-oss-instruct-sc2-concepts
def _src_lines(start_line, end_line): """ Test lines to write to the source file (Line 1, Line 2, ...). """ return "\n".join( [f"Line {line_num}" for line_num in range(start_line, end_line + 1)] )
bigcode/self-oss-instruct-sc2-concepts
def _grad_nll(p, gp, y): """ Given parameters and data, compute the gradient of the negative log likelihood of the data under the george Gaussian process. Parameters ---------- p : array GP hyperparameters gp : george.GP y : array data to condition GP on Returns ...
bigcode/self-oss-instruct-sc2-concepts
def mutation_type(alleles): """ Is this mutation a transition (A <-> G and C <-> T) or a transversion (everything else). """ alleles = set([a.upper() for a in alleles]) assert len(alleles) == 2 and alleles.issubset({"A", "C", "G", "T", "N"}) return "ts" if alleles in [{"A", "G"}, {"C", "T"}] els...
bigcode/self-oss-instruct-sc2-concepts
import torch def gaussian_noise(x, std=1, **kwargs): """Add Gaussian noise and clips the output.""" return torch.clamp(x + torch.randn_like(x) * std, **kwargs)
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def human_number(number: Union[int, float]) -> str: """human-readable number format. It is a general-purpose number formatter, which separates every three digits to make it human-readable. Args: number (int or float): Accepts only one element (i.e., scalar). Ret...
bigcode/self-oss-instruct-sc2-concepts
def contains(func, iterable): """ Return true if one element of iterable for which function returns true. """ if func is None: func = bool for x in iterable: if func(x): return True return False
bigcode/self-oss-instruct-sc2-concepts
def isiterable(variable): """ Check whether the given variable is iterable. Lists, tuples, NumPy arrays, but strings as well are iterable. Integers, however, are not. Parameters ---------- variable : variable to check for being iterable Returns ------- answer : :class:...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def star(f: Callable) -> Callable: """ Converts a function of multiple arguments, to a function taking a tuple. Useful for e.g. min(list_of_tuples, key=star(lambda a,b: ....)). """ return lambda args: f(*args)
bigcode/self-oss-instruct-sc2-concepts
def get_row_column(play, board): """ prompt for user input until its correct catch any letters or incomplete values in user input :param play - string, user command: :param board - object, board: :return row, column - int, locations on board in 2-D: """ # loop until there is valid user i...
bigcode/self-oss-instruct-sc2-concepts
import math def continued_fraction_expansion(target, terms): """ Return continued fraction expansion of a real number. >>> continued_fraction_expansion(1.4142, 2) [1, 2, 2] The first component is the integer part, and rest is fractional part, whose number of terms is specified by the second ...
bigcode/self-oss-instruct-sc2-concepts
def compute_prob(eng: float, beta: float, num_spin: int) -> float: """Boltzmann probability distribution Args: eng (float): Energy of the sample. beta (float): Inverse temperature num_spin (int): Number of spins in the sample. Returns: float: Log-Boltzmann probability. ...
bigcode/self-oss-instruct-sc2-concepts
import opcode def _opcode(name): """Return the opcode by name from the opcode module.""" return opcode.opmap[name]
bigcode/self-oss-instruct-sc2-concepts
def augment_lab_config(lab_config): """augment the configuration by - adding a "connected_to" attribute to each port which has a cable plugged in Args: lab_config (dict): [description] Returns: dict: lab_config """ for cable in lab_config["cables"]: lab_config["devices"][cable["sour...
bigcode/self-oss-instruct-sc2-concepts
def format_link(link): """ Append site url """ return "https://old.reddit.com" + link if link[:3] == "/r/" else link
bigcode/self-oss-instruct-sc2-concepts
def purity(label_pred, label_true, Ia_flag=0): """Calculate purity. input: label_pred, predicted labels label_true, true labels Ia_flag, Ia flag (optional, default is 0) output: purity """ cc_Ia = sum([label_pred[i] == label_true[i] and label_true[i] == Ia_flag f...
bigcode/self-oss-instruct-sc2-concepts
import json import time def serialize_spool_file_contents(reason, expiration=None, creation=None): """Serialize the contents of the spool file (as JSON). :param reason: a string representing the reason why the downtime exists. :param expiration: The unix time when this downtime should be considered valid...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import click def validate_json_yaml_filename(ctx, param, value): """Validate the name of the file has the proper extension and add the extension to the file object""" if value is None: return value if not hasattr(value, "name") or value.name == "<stdout>": # stdin...
bigcode/self-oss-instruct-sc2-concepts
def get_middle_point(xx, yy): """ Roughly get the middle point of line of x, y coordinates :param xx: np.array , x array coordinates :param yy: np.array , y array coordinates :return: (x_center, y_center) """ half = int(len(xx) / 2) return xx[half], yy[half]
bigcode/self-oss-instruct-sc2-concepts
def GetRegionFromZone(zone): """Returns the GCP region that the input zone is in.""" return '-'.join(zone.split('-')[:-1]).lower()
bigcode/self-oss-instruct-sc2-concepts
def take_keys(keys, data_dict): """Take keys from dict Arguments: keys {List[str]} -- Keys it include in output dict data_dict {Dict} Returns: [Dict] """ return {k: v for k, v in data_dict.items() if k in keys}
bigcode/self-oss-instruct-sc2-concepts
def locationGenerator(r,t,c,data='data', contextMgr=False): """ Given R, T, C, this funtion will generate a path to data in an imaris file default data == 'data' the path will reference with array of data if data == 'attrib' the bath will reference the channel location where attributes are stored ""...
bigcode/self-oss-instruct-sc2-concepts
def drop_substring_from_str(item: str, substring: str) -> str: """Drops 'substring' from 'item'. Args: item (str): item to be modified. substring (str): substring to be added to 'item'. Returns: str: modified str. """ if substring in item: return item.replace(s...
bigcode/self-oss-instruct-sc2-concepts
import re def format_species(name, mhchem=False, mathrm=False): """ Format the name of a chemical species. Usage: formatted_name = format_species(name, mhchem=False) Takes a string which represents an atomic or molecular species and returns a string with LaTeX-style sub- and superscripts...
bigcode/self-oss-instruct-sc2-concepts
def is_decorated(func): """Return True if |func| is decorated by @public or @require decorators.""" return hasattr(func, '__auth_public') or hasattr(func, '__auth_require')
bigcode/self-oss-instruct-sc2-concepts
def decode_bytes(s, encoding='utf-8', errors='replace'): """Decodes bytes to str, str to unicode.""" return s.decode(encoding, errors=errors) if isinstance(s, bytes) else s
bigcode/self-oss-instruct-sc2-concepts
def metaslice(alen, nmeta, trim=0, thickness=False): """ Return *[imin,imax,istp]* so that `range(imin,imax+1,istp)` are the boundary indices for *nmeta* (centered) metaslices. Note: *imax* is the end boundary index of last metaslice, therefore element *imax* is *not* included in last ...
bigcode/self-oss-instruct-sc2-concepts
import json def import_json(path): """Decodes and returns the JSON object in the file at the specified path. Args: path (str): The path of the file to read. """ with open(path) as data_file: return json.load(data_file)
bigcode/self-oss-instruct-sc2-concepts
import torch def get_distorted_x(x, prob, corrupt=True): """ Distorts the node feature matrix (X) either through corruption or through blanking out - Corruption: Add uniform random noise in [0,1] to the node feature matrix - Blanking out: Replace entries in the node feature matrix with zer...
bigcode/self-oss-instruct-sc2-concepts
def _select_entries_param(list, param): """Takes a list of logfile_entry objects and returns a sub set of it. The sub set includes a entries that have a source attribute that occurs in the param argument. Positional arguments: list -- a list of logfile_entry objects param -- a list of strings, representing source...
bigcode/self-oss-instruct-sc2-concepts
def choose_robots(exclude_bimanual=False): """ Prints out robot options, and returns the requested robot. Restricts options to single-armed robots if @exclude_bimanual is set to True (False by default) Args: exclude_bimanual (bool): If set, excludes bimanual robots from the robot options R...
bigcode/self-oss-instruct-sc2-concepts
def simd_loop_filter(loops, tuning): """ Filter out the SIMD candidate loops based on the tuning information. We select the legal simd loop with the highest score. If there is no such loop, we will set "loops" to all "1"s. AutoSA will not tile loops with the tiling factor as one for latency hiding or ...
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup def scrape_target_elements(html, target, target_type, specific_tag=''): """Scrape target from the html document Positional Arguments: html (str): standard html document target (str): name of tag, id or class target_type (str): tag (html element such as <l...
bigcode/self-oss-instruct-sc2-concepts
import itertools def _MakeBytes(bits, toks): """Creates a multi-byte string from ASCII strings and/or ASCII codes. Args: bits: Number of bits per character, must be in {8, 16, 32}. toks: A list of tokens, each of which is a ASCII strings or an integer representing a character's ASCII value (e.g., 0...
bigcode/self-oss-instruct-sc2-concepts
def limit(string, print_length=58): """Limit the length of a string to print_length characters Replaces the middle with ... """ if len(string) > print_length: trim = int((print_length-3)/2) return string[:trim] + '...' + string[-trim:] else: return string
bigcode/self-oss-instruct-sc2-concepts
def reduce_subjects(doc): """Iterates and sort all topic and subject related fields and returns a set of unique subjects. :param doc: Dictionary of subject values from the Solr document query :rtype: Set of subject terms """ subjects = [] if doc.has_key('subject'): f...
bigcode/self-oss-instruct-sc2-concepts
import random def get_otp_code() -> str: """Get random 6-digit OTP code""" return "".join([random.choice("0123456789") for i in range(6)])
bigcode/self-oss-instruct-sc2-concepts
import requests def download_json(url, args={}): """ Downloads a JSON :param url: The URL of the JSON :type url: string :param args: Optional keyword arguments for requests :type args: dict :return: The downloaded JSON :rtype: dict """ r = requests.get(url, **args) return r.json()
bigcode/self-oss-instruct-sc2-concepts
def load_all_vectors(embd, wikiWordsPath): """Loads all word vectors for all words in the list of words as a matrix Arguments embd : Dictonary of word-to-embedding for all words wikiWordsPath : URL to the path where all embeddings are stored Returns all_words_index : Dictonary of w...
bigcode/self-oss-instruct-sc2-concepts
import uuid def get_guid() -> str: """ Returns a new guid """ return uuid.uuid4().hex
bigcode/self-oss-instruct-sc2-concepts
def gen_team(name): """Generate a dict to represent a soccer team """ return {'name': name, 'avg_height': 0, 'players': []}
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import Tuple from typing import Mapping import inspect def get_function_parameters( f: Callable, ) -> Tuple[Mapping[str, inspect.Parameter], type]: """ Returns function's signature as parameters and the output type. :param f: the function :return: the param...
bigcode/self-oss-instruct-sc2-concepts
import time def timefunc(func): """ decorator to measure the execution time of the decorated function. """ def profiled_func(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(func.__name__, 'took', end - start, 'time') ...
bigcode/self-oss-instruct-sc2-concepts
def remove_whitespace(word): """Removes whitespace from word""" return word.strip()
bigcode/self-oss-instruct-sc2-concepts
def key_for_path(p): """ Representation of the path, ID for a path :param p: a JSON path dictionary :return: a unique string for the path """ # key for a path is made of starting user id and ending business id in the path return '%s_%s' % (p[0]['props']['id'], p[-1]['props']['id'])
bigcode/self-oss-instruct-sc2-concepts
def fix_ts(timestamp): """ Remove milliseconds from timestamps """ s, ms = divmod(int(timestamp), 1000) # import time # s = int(time.time()) # Uncomment for testing return s
bigcode/self-oss-instruct-sc2-concepts
import math def get_point_from_angle(point, angle, lenght): """ Return a point given a starting point, the angle that it has to form with respect to X-axis and how far from that point it has to be. :param point: Initial point :param angle: angle with respect to X-axis :param lenght: How far fr...
bigcode/self-oss-instruct-sc2-concepts
def class_identifier(typ): """Return a string that identifies this type.""" return "{}.{}".format(typ.__module__, typ.__name__)
bigcode/self-oss-instruct-sc2-concepts
def save_df_as_csv(d, output_file, fields_order=None, csv_order_by=None, keep_index=False, encoding='utf-8-sig', blankna=False, excel=False, verbose=False, **kwargs): """Save a dataframe in a csv fields_order allows to precise what columns to put first (you don't need to specify all columns, only the ones you w...
bigcode/self-oss-instruct-sc2-concepts
import inspect def get_instance_user_attributes(cls): """ Returns user attributes defined in a class or instance of a class :param cls: :return: list """ _def_attrs = dir(type('dummy', (object,), {})) _def_attrs.extend(['staticMetaObject']) attributes = inspect.getmembers(cls, lambda...
bigcode/self-oss-instruct-sc2-concepts
def get_class_name(o, lower=False): """ Returns the class name of an object o. """ if not isinstance(o, type): o = o.__class__ if lower: return o.__name__.lower() else: return o.__name__
bigcode/self-oss-instruct-sc2-concepts
def _namespace_data(data: dict, namespace: str) -> dict: """Prefix configuration key with a namespace. Namespace is ConfigSource wide, and is resolved at source build time. It should be one of: - "target" - "app" - library name (where "mbed_lib.json" comes from) If given key is already na...
bigcode/self-oss-instruct-sc2-concepts
import time def format_time(ts): """Converts UNIX timestamp to local timestring with human-readable format""" return time.strftime("%d %B %Y, %I:%M %p", time.localtime(int(ts)))
bigcode/self-oss-instruct-sc2-concepts
def _sanitize(hex_str, comment_strings=None, ignore_strings=None): """ Sanitize string input before attempting to write to file. :param hex_str: the string input to sanitize :param comment_strings: a tuple of strings identifying comment characters :param ignore_strings: a tuple of strings to igno...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import pathlib def find_all_coreref_files(directory: str) -> List[pathlib.Path]: """Searches for all the COREREF files in a directory and all its subdirectories. Parameters ---------- directory: str A string containing the path to directory where we want to search the ...
bigcode/self-oss-instruct-sc2-concepts
def find_max_recursively(S, n): """Find the maximum element in a sequence S, of n elements.""" if n == 1: # reached the left most item return S[n-1] else: previous = find_max_recursively(S, n-1) current = S[n-1] if previous > current: return previous else...
bigcode/self-oss-instruct-sc2-concepts
def is_child_node(node): """ Return `True` if the given node is a "child" node, `False` otherwise. """ if not node: return False return node.is_child is True and node.is_root is False
bigcode/self-oss-instruct-sc2-concepts
def xor_string(string: str, xor_int_value=42): """Takes a given string and does an XOR operation on the converted ord() value of each character with the "xor_int_value", which by default is 42 Examples: >>> string2encode = 'Now is better than never.'\n >>> xor_string(string2encode)\n 'd...
bigcode/self-oss-instruct-sc2-concepts
def voxel_to_world_coordinates(voxel_index, bbox, grid_shape): """Given a voxel, the bbox that encloses the scene and the shape of the grid, it computes the center of the voxel in world coordinates. Arguments: ---------- voxel_index: array(shape=(3, ), dtype=int32) The voxel indice...
bigcode/self-oss-instruct-sc2-concepts
def compute_veer(wind_a, height_a, wind_b, height_b): """ Compute veer between wind direction measurements Args: wind_a, wind_b(:obj:`array`): arrays containing the wind direction mean data; units of deg height_a, height_b(:obj:`array`): sensor heights (m) Returns: veer(:obj:`a...
bigcode/self-oss-instruct-sc2-concepts
import re def _ReplaceIndices(language, expression): """Replaces array access with underscored variable. For matrices: `variable[3,7]` becomes `variable_3_7` For vectors: `variable[3]` becomes `variable_3` The accessor for matrices is chosen according to the language (`[]` vs. `()`) """ #Ma...
bigcode/self-oss-instruct-sc2-concepts
def bdf_width(width: int) -> int: """Calculates the width in bits of each row in the BDF from the actual witdth of a character in pixels.""" # NOTE: Lines in BDF BITMAPs are always stored in multiples of 8 bits # (https://stackoverflow.com/a/37944252) return -((-width) // 8) * 8
bigcode/self-oss-instruct-sc2-concepts
def EVI(red, nir, blue): """ Return the Enhanced Vegetation Index for a set of np.ndarrays EVI is calculated as: .. math:: 2.5 * \\frac{(NIR - RED)}{(NIR + C_1 * RED - C_2 * BLUE + L)} where: - :math:`RED` is the red band - :math:`NIR` is the near infrared band - :math...
bigcode/self-oss-instruct-sc2-concepts
import re def is_valid_hash(value, algo): """Returns if the value is a valid hash for the corresponding algorithm.""" size = 2 * algo().digest_size return bool(re.match(r'^[a-fA-F0-9]{%d}$' % size, value))
bigcode/self-oss-instruct-sc2-concepts
def zbar_bch15_5_encode(x): """ZBar's implementation of bch15_5_encode""" return ( (-(x & 1) & 0x0537) ^ (-(x >> 1 & 1) & 0x0A6E) ^ (-(x >> 2 & 1) & 0x11EB) ^ (-(x >> 3 & 1) & 0x23D6) ^ (-(x >> 4 & 1) & 0x429B) )
bigcode/self-oss-instruct-sc2-concepts
import math def flux_ratio(meas_x, meas_y): """ Calculate the flux ratio between two `heuslertools.mbe.flux_ratio.FluxMeasurement`s. The ratio is calculate with $$\\frac{J_X}{J_Y}=\\frac{BEP_X}{BEP_Y}\\cdot\\frac{\\eta_Y}{\\eta_X}\\cdot\\sqrt{\\frac{T_X M_Y}{T_Y M_X}}$$ """ return (meas_x.bep/...
bigcode/self-oss-instruct-sc2-concepts
def getFileLocations(years, filings): """ Returns a list with the folder names where the data will be found """ fileLocations = list() for year in years: if filings == ['10-K']: fileLocations.append(year + 'q1/') # only valid if the user wants solely 10-K's as they are filed in Q1 ...
bigcode/self-oss-instruct-sc2-concepts
def stripquotes(s): """ Enforce to be a string and strip matching quotes """ return str(s).lstrip('"').rstrip('"')
bigcode/self-oss-instruct-sc2-concepts
def tuple_to_bool(value): """ Converts a value triplet to boolean2 values From a triplet: concentration, decay, threshold Truth value = conc > threshold/decay """ return value[0] > value[2] / value[1]
bigcode/self-oss-instruct-sc2-concepts
def normalize_module(module): """ Normalize a module name """ return module.lower()
bigcode/self-oss-instruct-sc2-concepts
def split_list_into_chunks(list_to_split, max_entries_per_list): """ Takes a list and splits it up into smaller lists """ chunks = [] for i in range(0, len(list_to_split), max_entries_per_list): chunk = list_to_split[i:i + max_entries_per_list] chunks.append(chunk) return chunk...
bigcode/self-oss-instruct-sc2-concepts
def set_show_hit_test_borders(show: bool) -> dict: """Requests that backend shows hit-test borders on layers Parameters ---------- show: bool True for showing hit-test borders """ return {"method": "Overlay.setShowHitTestBorders", "params": {"show": show}}
bigcode/self-oss-instruct-sc2-concepts
def groupify(data): """ Takes a dict with groups identified by ./ and turns it into a nested dict """ new = {} for key in data.keys(): if "./" in key: group, field = key.split("./") if group not in new: new[group] = {} new[group][field] = d...
bigcode/self-oss-instruct-sc2-concepts