seed
stringlengths
1
14k
source
stringclasses
2 values
def _label_group(key, pattern): """ Build the right pattern for matching with named entities. >>> _label_group('key', '[0-9]{4}') '(?P<key>[0-9]{4})' """ return '(?P<%s>%s)' % (key, pattern)
bigcode/self-oss-instruct-sc2-concepts
def _to_set(loc): """Convert an array of locations into a set of tuple locations.""" return set(map(tuple, loc))
bigcode/self-oss-instruct-sc2-concepts
def is_valid_port(entry, allow_zero = False): """ Checks if a string or int is a valid port number. :param list,str,int entry: string, integer or list to be checked :param bool allow_zero: accept port number of zero (reserved by definition) :returns: **True** if input is an integer and within the valid port...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def hide_if_not_none(secret: Any): """ Hide a secret unless it is None, which means that the user didn't set it. :param secret: the secret. :return: None or 'hidden' """ value = None if secret is not None: value = 'hidden' return value
bigcode/self-oss-instruct-sc2-concepts
def percentIncrease(old, new): """ Calculates the percent increase between two numbers. Parameters ---------- old : numeric The old number. new : numeric The new number. Returns ------- numeric The percent increase (as a decimal). """ return (new - ...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def create_model(api, name, fields): """Helper for creating api models with ordered fields :param flask_restx.Api api: Flask-RESTX Api object :param str name: Model name :param list fields: List of tuples containing ['field name', <type>] """ d = OrderedDict() ...
bigcode/self-oss-instruct-sc2-concepts
import torch def rgb_to_srgb(image): """Applies gamma correction to rgb to get sRGB. Assumes input is in range [0,1] Works for batched images too. :param image: A pytorch tensor of shape (3, n_pixels_x, n_pixels_y) in which the channels are linearized R, G, B :return: A pytorch tensor of shape (3, n_...
bigcode/self-oss-instruct-sc2-concepts
def confirmed_password_valid(password, confirmation): """ Tell if a password was confirmed properly Args: password the password to check. confirmation the confirmation of the password. Returns: True if the password and confirmation are the same (no typos) """ return password == confirmation
bigcode/self-oss-instruct-sc2-concepts
def contains(element): """ Check to see if an argument contains a specified element. :param element: The element to check against. :return: A predicate to check if the argument is equal to the element. """ def predicate(argument): try: return element in argument exce...
bigcode/self-oss-instruct-sc2-concepts
def split_bbox(bbox): """Split a bounding box into its parts. :param bbox: String describing a bbox e.g. '106.78674459457397, -6.141301491467023,106.80691480636597,-6.133834354201348' :type bbox: str :returns: A dict with keys: 'southwest_lng, southwest_lat, northeast_lng, northeas...
bigcode/self-oss-instruct-sc2-concepts
def compare_rgb_colors_tolerance(first_rgb_color, second_rgb_color, tolerance): """ Compares to RGB colors taking into account the given tolerance (margin for error) :param first_rgb_color: tuple(float, float, float), first color to compare :param second_rgb_color: tuple(float, float, float), second col...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def GetRendererLabelFromFilename(file_path: str) -> str: """Gets the renderer label from the given file name by removing the '_renderer.py' suffix.""" file_name = Path(file_path).stem return file_name.rstrip("_renderer.py")
bigcode/self-oss-instruct-sc2-concepts
def _sample_generator(*data_buffers): """ Takes a list of many mono audio data buffers and makes a sample generator of interleaved audio samples, one sample from each channel. The resulting generator can be used to build a multichannel audio buffer. >>> gen = _sample_generator("abcd", "ABCD") >>...
bigcode/self-oss-instruct-sc2-concepts
def get_novel_smiles(new_unique_smiles, reference_unique_smiles): """Get novel smiles which do not appear in the reference set. Parameters ---------- new_unique_smiles : list of str List of SMILES from which we want to identify novel ones reference_unique_smiles : list of str List o...
bigcode/self-oss-instruct-sc2-concepts
def error(message, code=400): """Generate an error message. """ return {"error": message}, code
bigcode/self-oss-instruct-sc2-concepts
import warnings def _validate_buckets(categorical, k, scheme): """ This method validates that the hue parameter is correctly specified. Valid inputs are: 1. Both k and scheme are specified. In that case the user wants us to handle binning the data into k buckets ourselves, using the stated...
bigcode/self-oss-instruct-sc2-concepts
import json def save_json(f, cfg): """ Save JSON-formatted file """ try: with open(f, 'w') as configfile: json.dump(cfg, configfile) except: return False return True
bigcode/self-oss-instruct-sc2-concepts
import math def parallelepiped_magnet( length=0.01, width=0.006, thickness=0.001, density=7500 ): """ Function to get the masse, volume and inertial moment of a parallelepiped magnet. International system units. The hole for the axis is ignored. """ V = length * width * thickness m = V...
bigcode/self-oss-instruct-sc2-concepts
def max_cw(l): """Return max value of a list.""" a = sorted(l) return a[-1]
bigcode/self-oss-instruct-sc2-concepts
def eia_mer_url_helper(build_url, config, args): """Build URL's for EIA_MER dataset. Critical parameter is 'tbl', representing a table from the dataset.""" urls = [] for tbl in config['tbls']: url = build_url.replace("__tbl__", tbl) urls.append(url) return urls
bigcode/self-oss-instruct-sc2-concepts
def safe_index(l, e): """Gets the index of e in l, providing an index of len(l) if not found""" try: return l.index(e) except: return len(l)
bigcode/self-oss-instruct-sc2-concepts
import codecs import json def load_json(path_to_json: str) -> dict: """Load json with information about train and test sets.""" with codecs.open(path_to_json, encoding='utf-8') as train_test_info: return json.loads(train_test_info.read())
bigcode/self-oss-instruct-sc2-concepts
def _and(arg1, arg2): """Boolean and""" return arg1 and arg2
bigcode/self-oss-instruct-sc2-concepts
def get_repositories(reviewboard): """Return list of registered mercurial repositories""" repos = reviewboard.repositories() return [r for r in repos if r.tool == 'Mercurial']
bigcode/self-oss-instruct-sc2-concepts
import grp def check_gid(gid): """ Get numerical GID of a group. Raises: KeyError: Unknown group name. """ try: return 0 + gid # already numerical? except TypeError: if gid.isdigit(): return int(gid) else: return grp.getgrnam(gid).g...
bigcode/self-oss-instruct-sc2-concepts
def bin_to_str(val): """ Converts binary integer to string of 1s and 0s """ return str(bin(val))[2:]
bigcode/self-oss-instruct-sc2-concepts
import signal def register_signal_handler(sig, handler): """Registers a signal handler.""" return signal.signal(sig, handler)
bigcode/self-oss-instruct-sc2-concepts
def AfterTaxIncome(combined, expanded_income, aftertax_income, Business_tax_expinc, corp_taxliab): """ Calculates after-tax expanded income. Parameters ---------- combined: combined tax liability expanded_income: expanded income corp_taxliab: imputed corporate tax liabili...
bigcode/self-oss-instruct-sc2-concepts
def _find_tbl_starts(section_index, lines): """ next three tables are the hill, channel, outlet find the table header lines :param section_index: integer starting index of section e.g. "ANNUAL SUMMARY FOR WATERSHED IN YEAR" :param lines: loss_pw0.txt as a list of strings ...
bigcode/self-oss-instruct-sc2-concepts
def decode_list_index(list_index: bytes) -> int: """Decode an index for lists in a key path from bytes.""" return int.from_bytes(list_index, byteorder='big')
bigcode/self-oss-instruct-sc2-concepts
def mode_decomposition(plant): """Returns a list of single mode transfer functions Parameters ---------- plant : TransferFunction The transfer function with at list one pair of complex poles. Returns ------- wn : array Frequencies (rad/s). q : array Q factors. ...
bigcode/self-oss-instruct-sc2-concepts
def assign_province_road_conditions(x): """Assign road conditions as paved or unpaved to Province roads Parameters x - Pandas DataFrame of values - code - Numeric code for type of asset - level - Numeric code for level of asset Returns String value as paved or unpav...
bigcode/self-oss-instruct-sc2-concepts
import ast def guess_type(string): """ Guess the type of a value given as string and return it accordingly. Parameters ---------- string : str given string containing the value """ string = str(string) try: value = ast.literal_eval(string) except Exception: # Synt...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def split_high_level(s: str, c: str, open_chars: List[str], close_chars: List[str] ) -> List[str]: """Splits input string by delimiter c. Splits input string by delimiter c excluding occurences of ...
bigcode/self-oss-instruct-sc2-concepts
def tonumpy(img): """ Convert torch image map to numpy image map Note the range is not change :param img: tensor, shape (C, H, W), (H, W) :return: numpy, shape (H, W, C), (H, W) """ if len(img.size()) == 2: return img.cpu().detach().numpy() return img.permute(1, 2, 0).c...
bigcode/self-oss-instruct-sc2-concepts
import re def substitute_query_params(query, params): """ Substitutes the placeholders of the format ${n} (where n is a non-negative integer) in the query. Example, ${0}. ${n} is substituted with params[n] to generate the final query. """ placeholders = re.findall("((\${)(\d+)(}))", query) for...
bigcode/self-oss-instruct-sc2-concepts
def group_text(text, n=5): """Groups the given text into n-letter groups separated by spaces.""" return ' '.join(''.join(text[i:i+n]) for i in range(0, len(text), n))
bigcode/self-oss-instruct-sc2-concepts
def p_length_unit(units): """Returns length units string as expected by pagoda weights and measures module.""" # NB: other length units are supported by resqml if units.lower() in ['m', 'metre', 'metres']: return 'metres' if units.lower() in ['ft', 'foot', 'feet', 'ft[us]']: return 'feet' assert(False)
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def fname(func: Callable) -> str: """Return fully-qualified function name.""" return "{}.{}".format(func.__module__, func.__name__)
bigcode/self-oss-instruct-sc2-concepts
def getNrOfDictElements(thisdict): """ Will get the total number of entries in a given dictionary Argument: the source dictionary Output : an integer """ total = 0 for dicttype in thisdict: for dictval in thisdict[dicttype]: total += 1 return total
bigcode/self-oss-instruct-sc2-concepts
import random def mutate_agent(agent_genome, max_mutations=3): """ Applies 1 - `max_mutations` point mutations to the given road trip. A point mutation swaps the order of two waypoints in the road trip. """ agent_genome = list(agent_genome) num_mutations = random.randint(...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence def strictly_increasing(s: Sequence): """Returns true if sequence s is monotonically increasing""" return all(x < y for x, y in zip(s, s[1:]))
bigcode/self-oss-instruct-sc2-concepts
import random def generate_number(digits): """Generate an integer with the given number of digits.""" low = 10**(digits-1) high = 10**digits - 1 return random.randint(low, high)
bigcode/self-oss-instruct-sc2-concepts
def _applescriptify_str(text): """Replace double quotes in text for Applescript string""" text = text.replace('"', '" & quote & "') text = text.replace('\\', '\\\\') return text
bigcode/self-oss-instruct-sc2-concepts
def unpack_spectrum(HDU_list): """ Unpacks and extracts the relevant parts of an SDSS HDU list object. Parameters ---------- HDU_list : astropy HDUlist object Returns ------- wavelengths : ndarray Wavelength array flux : ndarray Flux array z : float Reds...
bigcode/self-oss-instruct-sc2-concepts
import re def is_stable_version(version): """ Return true if version is stable, i.e. with letters in the final component. Stable version examples: ``1.2``, ``1.3.4``, ``1.0.5``. Non-stable version examples: ``1.3.4beta``, ``0.1.0rc1``, ``3.0.0dev0``. """ if not isinstance(version, tuple): ...
bigcode/self-oss-instruct-sc2-concepts
def read_symfile(path='baserom.sym'): """ Return a list of dicts of label data from an rgbds .sym file. """ symbols = [] for line in open(path): line = line.strip().split(';')[0] if line: bank_address, label = line.split(' ')[:2] bank, address = bank_address.split(':') symbols += [{ 'label': label...
bigcode/self-oss-instruct-sc2-concepts
def cert_bytes(cert_file_name): """ Parses a pem certificate file into raw bytes and appends null character. """ with open(cert_file_name, "rb") as pem: chars = [] for c in pem.read(): if c: chars.append(c) else: break # nul...
bigcode/self-oss-instruct-sc2-concepts
def cupy_cuda_MemoryPointer(cp_arr): """Return cupy.cuda.MemoryPointer view of cupy.ndarray. """ return cp_arr.data
bigcode/self-oss-instruct-sc2-concepts
def extend(*dicts): """Create a new dictionary from multiple existing dictionaries without overwriting.""" new_dict = {} for each in dicts: new_dict.update(each) return new_dict
bigcode/self-oss-instruct-sc2-concepts
def mult (x, y): """ multiply : 2 values """ return x * y
bigcode/self-oss-instruct-sc2-concepts
def combine_on_sep(items, separator): """ Combine each item with each other item on a `separator`. Args: items (list): A list or iterable that remembers order. separator (str): The SEPARATOR the items will be combined on. Returns: list: A list with all the combined item...
bigcode/self-oss-instruct-sc2-concepts
def swapPos(list:list, pos1:int, pos2:int): """ Swap two elements in list. Return modified list """ list[pos1], list[pos2] = list[pos2], list[pos1] return list
bigcode/self-oss-instruct-sc2-concepts
import csv def team2machine(cur_round): """Compute the map from teams to machines.""" # Get the config with the teamname-source mappings. config_name = f"configs/config_round_{cur_round}.csv" team_machine = {} with open(config_name, 'r') as infile: reader = csv.reader(infile) for r...
bigcode/self-oss-instruct-sc2-concepts
import torch def systematic_sampling(weights: torch.Tensor) -> torch.Tensor: """Sample ancestral index using systematic resampling. Get from https://docs.pyro.ai/en/stable/_modules/pyro/infer/smcfilter.html#SMCFilter Args: log_weight: log of unnormalized weights, tensor [batch_shape, ...
bigcode/self-oss-instruct-sc2-concepts
def get_column_as_list(matrix, column_no): """ Retrieves a column from a matrix as a list """ column = [] num_rows = len(matrix) for row in range(num_rows): column.append(matrix[row][column_no]) return column
bigcode/self-oss-instruct-sc2-concepts
def _GetDefault(t): """Returns a string containing the default value of the given type.""" if t.element_type or t.nullable: return None # Arrays and optional<T> are default-initialized type_map = { 'boolean': 'false', 'double': '0', 'DOMString': None, # std::string are default-initialized....
bigcode/self-oss-instruct-sc2-concepts
import configparser def get_downstream_distgit_branch(dlrn_projects_ini): """Get downstream distgit branch info from DLRN projects.ini""" config = configparser.ConfigParser() config.read(dlrn_projects_ini) return config.get('downstream_driver', 'downstream_distro_branch')
bigcode/self-oss-instruct-sc2-concepts
def get_defined_enums(conn, schema): """ Return a dict mapping PostgreSQL enumeration types to the set of their defined values. :param conn: SQLAlchemy connection instance. :param str schema: Schema name (e.g. "public"). :returns dict: { "my_enum": frozense...
bigcode/self-oss-instruct-sc2-concepts
def find_valid_edges(components, valid_edges): """Find all edges between two components in a complete undirected graph. Args: components: A [V]-shaped array of boolean component ids. This assumes there are exactly two nonemtpy components. valid_edges: An uninitialized array where ou...
bigcode/self-oss-instruct-sc2-concepts
def find_column_by_utype(table, utype): """ Given an astropy table derived from a VOTABLE, this function returns the first Column object that has the given utype. The name field of the returned value contains the column name and can be used for accessing the values in the column. Parameters ...
bigcode/self-oss-instruct-sc2-concepts
def calc_node_attr(node, edge): """ Returns a tuple of (cltv_delta, min_htlc, fee_proportional) values of the node in the channel. """ policy = None if node == edge['node1_pub']: policy = edge['node1_policy'] elif node == edge['node2_pub']: policy = edge['node2_policy'] else:...
bigcode/self-oss-instruct-sc2-concepts
def format_mac(mac: str) -> str: """ Format the mac address string. Helper function from homeassistant.helpers.device_registry.py """ to_test = mac if len(to_test) == 17 and to_test.count("-") == 5: return to_test.lower() if len(to_test) == 17 and to_test.count(":") == 5: t...
bigcode/self-oss-instruct-sc2-concepts
def present(element, act): """Return True if act[element] is valid and not None""" if not act: return False elif element not in act: return False return act[element]
bigcode/self-oss-instruct-sc2-concepts
def format_output(tosave, formatter): """ Applies the formatting function, formatter, on tosave. If the resulting string does not have a newline adds it. Otherwise returns the formatted string :param tosave: The item to be string serialized :param formatter: The formatter function applied to ite...
bigcode/self-oss-instruct-sc2-concepts
def _update_query(table: str, field: str, is_jsonb: bool, from_string: str, to_string: str) -> str: """Generates a single query to update a field in a PostgresSQL table. Args: table (str): The table to update. field (str): The field to update. is_jsonb (bool): Whether ...
bigcode/self-oss-instruct-sc2-concepts
def generateFilenameFromUrl(url): """ Transforms a card URL into a local filename in the format imageCache/setname_cardnumber.jpg. """ return 'imageCache/' + '_'.join(url.split('/')[1:])
bigcode/self-oss-instruct-sc2-concepts
import shutil def move(src_path, dest_path, raise_error=False): """ Moves a file or folder from ``src_path`` to ``dest_path``. If either the source or the destination path no longer exist, this function does nothing. Any other exceptions are either raised or returned if ``raise_error`` is False. "...
bigcode/self-oss-instruct-sc2-concepts
def unblock_list(blocked_ips_list, to_block_list): """ This function creates list of IPs that are present in the firewall block list, but not in the list of new blockings which will be sent to the firewall. :param blocked_ips_list: List of blocked IPs. :param to_block_list: List of new blockings. ...
bigcode/self-oss-instruct-sc2-concepts
import csv import re def get_keys_from_file(file): """ Reads a file and creates a list of dictionaries. :param file: Filename relative to project root. :return: lkeys - a list of dictionaries [{ Key: '00484545-2000-4111-9000-611111111111', Region: 'us-east-1' },...
bigcode/self-oss-instruct-sc2-concepts
def file_list(redis, task_id): """Returns the list of files attached to a task""" keyf = "files:" + task_id return redis.hkeys(keyf)
bigcode/self-oss-instruct-sc2-concepts
def _parse_quad_str(s): """Parse a string of the form xxx.x.xx.xxx to a 4-element tuple of integers""" return tuple(int(q) for q in s.split('.'))
bigcode/self-oss-instruct-sc2-concepts
def flatten_dict(dct, separator='-->', allowed_types=[int, float, bool]): """Returns a list of string identifiers for each element in dct. Recursively scans through dct and finds every element whose type is in allowed_types and adds a string indentifier for it. eg: dct = { 'a': 'a stri...
bigcode/self-oss-instruct-sc2-concepts
def _parse_tersoff_line(line): """ Internal Function. Parses the tag, parameter and final value of a function parameter from an atomicrex output line looking like: tersoff[Tersoff].lambda1[SiSiSi]: 2.4799 [0:] Returns: [(str, str, float): tag, param, value """ line = line.s...
bigcode/self-oss-instruct-sc2-concepts
def find_IPG_hits(group, hit_dict): """Finds all hits to query sequences in an identical protein group. Args: group (list): Entry namedtuples from an IPG from parse_IP_groups(). hit_dict (dict): All Hit objects found during cblaster search. Returns: List of all Hit objects correspon...
bigcode/self-oss-instruct-sc2-concepts
def get_mc_filepath(asm_path): """ Get the filepath for the machine code. This is the assembly filepath with .asm replaced with .mc Args: asm_path (str): Path to the assembly file. Returns: str: Path to the machine code file. """ return "{basepath}.mc".format(basepath=asm_...
bigcode/self-oss-instruct-sc2-concepts
import re def encode(name, system='NTFS'): """ Encode the name for a suitable name in the given filesystem >>> encode('Test :1') 'Test _1' """ assert system == 'NTFS', 'unsupported filesystem' special_characters = r'<>:"/\|?*' + ''.join(map(chr, range(32))) pattern = '|'.join(map(re.es...
bigcode/self-oss-instruct-sc2-concepts
from itertools import tee def pairs(iterable): """ Return a new iterable over sequential pairs in the given iterable. i.e. (0,1), (1,2), ..., (n-2,n-1) Args: iterable: the iterable to iterate over the pairs of Returns: a new iterator over the pairs of the given iterator """ # lazil...
bigcode/self-oss-instruct-sc2-concepts
import re def convert_spaces_and_special_characters_to_underscore(name): """ Converts spaces and special characters to underscore so 'Thi$ i# jun&' becomes 'thi__i__jun_' :param name: A string :return: An altered string Example use case: - A string might have special characters at the end when t...
bigcode/self-oss-instruct-sc2-concepts
def uid_already_processed(db, notification_uid): """Check if the notification UID has already been processed.""" uid = db.document(notification_uid).get() if uid.exists: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def count_matched_numbers(a:list, b:list): """ Write a function that takes two lists as parameters and returns a list containing the number of elements that occur in the same index in both lists. If there is not common elements in the same indices in both lists, return False Example: >>> count_matched_numbers([1,...
bigcode/self-oss-instruct-sc2-concepts
import binascii def from_bytes(bytes): """Reverse of to_bytes().""" # binascii works on all versions of Python, the hex encoding does not return int(binascii.hexlify(bytes), 16)
bigcode/self-oss-instruct-sc2-concepts
def runningMean(oldMean, newValue, numValues): # type: (float, float, int) -> float """ A running mean Parameters ---------- oldMean : float The old running average mean newValue : float The new value to be added to the mean numValues : int The number of values i...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Optional def validate_parse_directions(verb: str, direction: str) -> Tuple[Optional[str], Optional[str]]: """Parse north, south, east, west to n, s, e, w and if the user types trash insult them and return a tuple like, (None, some validation message)""" if len(d...
bigcode/self-oss-instruct-sc2-concepts
def read_file_lines(filename): """Reads the lines of a file as a list""" with open(filename, mode="r") as f_in: return f_in.readlines()
bigcode/self-oss-instruct-sc2-concepts
def get_list_hashes(lst): """ For LZ to be more effective, than worst case 'fresh' raw dump, you need to lz encode minimum 4 bytes length. Break into 4 bytes chunks and hash Parameters ---------- lst : list Input list to form hashes from (lz haystack). Returns ------- enume...
bigcode/self-oss-instruct-sc2-concepts
def remove_ext(filename: str, ext: str) -> str: """ Remove a file extension. No effect if provided extension is missing. """ if not ext.startswith('.'): ext = f'.{ext}' parts = filename.rsplit(ext, 1) if len(parts) == 2 and parts[1] == '': return parts[0] else: return...
bigcode/self-oss-instruct-sc2-concepts
def parse_to_dicts(lines, containers): """ Parses a list of lines into tuples places in the given containers. The lists of lines has the following format token1: tval1 key1: val11 key2: val12 token1: tval2 key1: val21 key2: val22 :param lines: :param containers: a dictio...
bigcode/self-oss-instruct-sc2-concepts
def is_number(s): """ Test if a string is an int or float. :param s: input string (word) :type s: str :return: bool """ try: float(s) if "." in s else int(s) return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
def get_locale_identifier(tup, sep='_'): """The reverse of :func:`parse_locale`. It creates a locale identifier out of a ``(language, territory, script, variant)`` tuple. Items can be set to ``None`` and trailing ``None``\s can also be left out of the tuple. >>> get_locale_identifier(('de', 'DE', Non...
bigcode/self-oss-instruct-sc2-concepts
def to_channel_last(tensor): """Move channel axis in last position.""" return tensor.permute(1, 2, 0)
bigcode/self-oss-instruct-sc2-concepts
def _is_file_a_directory(f): """Returns True is the given file is a directory.""" # Starting Bazel 3.3.0, the File type as a is_directory attribute. if getattr(f, "is_directory", None): return f.is_directory # If is_directory is not in the File type, fall back to the old method: # As of Oct....
bigcode/self-oss-instruct-sc2-concepts
def correct_bounding_box(x1, y1, x2, y2): """ Corrects the bounding box, so that the coordinates are small to big """ xmin = 0 ymin = 0 xmax = 0 ymax = 0 if x1 < x2: xmin = x1 xmax = x2 else: xmin = x2 xmax = x1 if y1 < y2: ymin = y1 ymax ...
bigcode/self-oss-instruct-sc2-concepts
def train_test_split_features(data_train, data_test, zone, features): """Returns a pd.DataFrame with the explanatory variables and a pd.Series with the target variable, for both train and test data. Args: data_train (pd.DataFrame): Train data set. data_tes (pd.DataFrame): Test data set. z...
bigcode/self-oss-instruct-sc2-concepts
import torch def create_random_binary_mask(features): """ Creates a random binary mask of a given dimension with half of its entries randomly set to 1s. :param features: Dimension of mask. :return: Binary mask with half of its entries set to 1s, of type torch.Tensor. """ mask = torch.zeros...
bigcode/self-oss-instruct-sc2-concepts
def pbar(val, maxval, empty='-', full='#', size=50): """ return a string that represents a nice progress bar Parameters ---------- val : float The fill value of the progress bar maxval : float The value at which the progress bar is full empty : str The character us...
bigcode/self-oss-instruct-sc2-concepts
def hasShapeType(items, sort): """ Detect whether the list has any items of type sort. Returns :attr:`True` or :attr:`False`. :param shape: :class:`list` :param sort: type of shape """ return any([getattr(item, sort) for item in items])
bigcode/self-oss-instruct-sc2-concepts
def reestructure_areas(config_dict): """Ensure that all [Area_0, Area_1, ...] are consecutive""" area_names = [x for x in config_dict.keys() if x.startswith("Area_")] area_names.sort() for index, area_name in enumerate(area_names): if f"Area_{index}" != area_name: config_dict[f"Area_...
bigcode/self-oss-instruct-sc2-concepts
def get_section_markups(document, sectionLabel): """ Given a ConTextDocument and sectionLabel, return an ordered list of the ConTextmarkup objects in that section""" tmp = [(e[1],e[2]['sentenceNumber']) for e in document.getDocument().out_edges(sectionLabel, data=True) if e[2].get('category') == 'mar...
bigcode/self-oss-instruct-sc2-concepts
def absolute_min(array): """ Returns absolute min value of a array. :param array: the array. :return: absolute min value >>> absolute_min([1, -2, 5, -8, 7]) 1 >>> absolute_min([1, -2, 3, -4, 5]) 1 """ return min(array, key=abs)
bigcode/self-oss-instruct-sc2-concepts