seed
stringlengths
1
14k
source
stringclasses
2 values
def get_padding(ks, s, hw): """ choose padding value to make sure: if s = 1, out_hw = in_hw; if s = 2, out_hw = in_hw // 2; if s = 4, out_hw = in_hw // 4; """ if hw % s == 0: pad = max(ks - s, 0) else: pad = max(ks - (hw % s), 0) if pad % 2 == 0: return pad // 2 ...
bigcode/self-oss-instruct-sc2-concepts
def generate_header_list(unsorted_keys): """Return a list of headers for the CSV file, ensuing that the order of the first four headers is fixed and the remainder are sorted.""" unsorted_keys.remove('identifier') sorted_remainder = sorted(unsorted_keys) header_list = ['identifier', 'label1', 'lab...
bigcode/self-oss-instruct-sc2-concepts
def hamming_distance(str1, str2): """Calculate the Hamming distance between two bit strings Args: str1 (str): First string. str2 (str): Second string. Returns: int: Distance between strings. Raises: ValueError: Strings not same length """ if len(str1) != len(str2...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List import pickle def parse_list(data: Union[str, List], indicator: int = 0, query=['MCF7']) -> List: """Filter the data based on compound, cell line, dose or time This function takes the directory of dataset, indicator that indicates w...
bigcode/self-oss-instruct-sc2-concepts
def extend_flight_distance(distance: float) -> float: """Add factor to shortest flight distance to account for indirect flight paths Following https://www.icao.int/environmental-protection/CarbonOffset/Documents/Methodology%20ICAO%20Carbon%20Calculator_v11-2018.pdf section 4.2 we add a correction factor to...
bigcode/self-oss-instruct-sc2-concepts
def triwhite(x, y): """ Convert x,y chromaticity coordinates to XYZ tristimulus values. """ X = x / y Y = 1.0 Z = (1-x-y)/y return [X, Y, Z]
bigcode/self-oss-instruct-sc2-concepts
def create_header(args): """Constructs the header row for the csv""" header = ["Propublica Number", "Org Name", "Tax Year", "Data Source", "PDF URL"] if args.totalrev: header.append("Total Revenue") if args.totalexp: header.append("Total Functional Expenses") if args.ne...
bigcode/self-oss-instruct-sc2-concepts
def predict_large_image(model, input_image): """Predict on an image larger than the one it was trained on All networks with U-net like architecture in this repo, use downsampling of 2, which is only conducive for images with shapes in powers of 2. If different, please crop / resize accordingly to avoid...
bigcode/self-oss-instruct-sc2-concepts
import logging def get_logger(*components) -> logging.Logger: """Get a logger under the app's hierarchy.""" name = '.'.join(['skipscale'] + list(components)) return logging.getLogger(name)
bigcode/self-oss-instruct-sc2-concepts
def convert_to_SimpleIndex(data, axis=0): """ Converts the index of a DataFrame to a simple, one-level index The target index uses standard SimCenter convention to identify different levels: a dash character ('-') is used to separate each level of the index. Parameters ---------- data: Dat...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def hr_bytes(data: Iterable[int], delimiter: str = ' ') -> str: # pragma: no cover """ Print bytes (or another int iterable) as hex and delimiters :param data: Bytes or iterable object :param delimiter: Delimiter (str value) :return: str valu...
bigcode/self-oss-instruct-sc2-concepts
def create_path(network, user_A, user_B, path=[]): """ Finds a connections path from user_A to user_B using recursion. It has to be an existing path but it DOES NOT have to be the shortest path. Circular loops returns None (for example, A is connected to B. B is connected to C. C is connected to B.)...
bigcode/self-oss-instruct-sc2-concepts
import math def chunk(iterable, n): """Splits a list into n equal parts""" iterable = [e for e in iterable] avg_length = int(math.ceil(len(iterable) / n)) return [iterable[i * avg_length:(i + 1) * avg_length] for i in range(n)]
bigcode/self-oss-instruct-sc2-concepts
def first_down(items): """Return True if the first item is down.""" return items[0] == '-'
bigcode/self-oss-instruct-sc2-concepts
def unsort(sorted_list, oidx): """ Unsort a sorted list, based on the original idx. """ assert len(sorted_list) == len(oidx), "Number of list elements must match with original indices." _, unsorted = [list(t) for t in zip(*sorted(zip(oidx, sorted_list)))] return unsorted
bigcode/self-oss-instruct-sc2-concepts
def figure_linguistic_type(labels): """ Gets linguistic type for labels Parameters ---------- labels : list of lists the labels of a tier Returns ------- the linguistic type """ if len(labels) == 0: return None elif len(labels) == 1: return lab...
bigcode/self-oss-instruct-sc2-concepts
def get_rank(cutoff: dict, coverage: float, quality: float, length: int, contigs: int, genome_size: int, is_paired: bool) -> list: """ Determine the rank (gold, silver, bronze, fail) based on user cutoffs. Args: cutoff (dict): Cutoffs set by users to determine rank coverage (float): Estimat...
bigcode/self-oss-instruct-sc2-concepts
def filter_empty_values(mapping_object: dict) -> dict: """Remove entries in the dict object where the value is `None`. >>> foobar = {'username': 'rafaelcaricio', 'team': None} >>> filter_empty_values(foobar) {'username': 'rafaelcaricio'} :param mapping_object: Dict object to be filtered """ ...
bigcode/self-oss-instruct-sc2-concepts
def axis_ticklabels_overlap(labels): """Return a boolean for whether the list of ticklabels have overlaps. Parameters ---------- labels : list of ticklabels Returns ------- overlap : boolean True if any of the labels overlap. """ if not labels: return False try:...
bigcode/self-oss-instruct-sc2-concepts
def logreg_classifier_to_dict(classifier, feature_names=None): """ Serialize sklearn logistic regression classifier Inspired by https://stackoverflow.com/questions/48328012/python-scikit-learn-to-json Parameters ---------- classifier : sklearn.linear_model.LogisticRegression Logistic r...
bigcode/self-oss-instruct-sc2-concepts
def add(x, y): """This is a doc string :param x: first value to add :param y: second value to add :returns: x + y """ return x + y
bigcode/self-oss-instruct-sc2-concepts
def remove_atom_maps(mol): """ Iterates through the atoms in a Mol object and removes atom maps Parameters: mol (rdkit.Mol): Rdkit Mol Object Returns: mol (rdkit.Mol): Rdkit Mol Object without atom maps or 'nan' if error """ try: for atom in mol.GetAtoms(): ...
bigcode/self-oss-instruct-sc2-concepts
import torch def stft_wrapper(x, fft_n, frame_shift, frame_length, window, pad_mode="constant"): """Due to the different signature of torch.stft, write a wrapper to handle this input ----- x: tensor, waveform, (batch, length) window: tensor, window coef, (frame_length, ...
bigcode/self-oss-instruct-sc2-concepts
import torch def one_hot_encoding(input, c): """ One-hot encoder: Converts NxHxW label image to NxCxHxW, where each label is stored in a separate channel :param input: input image (NxHxW) :param c: number of channels/labels :return: output image (NxCxHxW) """ assert input.dim() == 3 N...
bigcode/self-oss-instruct-sc2-concepts
def kv_array_to_dict(kv_pairs): """ Takes an array of key=value formatted Strings and returns a dict """ pairs = {} if kv_pairs: for kv_string in kv_pairs: kv = kv_string.split("=") if len(kv) == 2: pairs[kv[0]] = kv[1] return pairs
bigcode/self-oss-instruct-sc2-concepts
import inspect def call(method, **kwargs): """Calls method with only parameters it requires""" # Due to SelfManaged overriding __new__, inspect cannot infer the expected variables from __new__ inspected_method = method.__init__ if inspect.isclass(method) else method expected = inspect.signature(inspec...
bigcode/self-oss-instruct-sc2-concepts
def read_database(file_name): """ Read the method templates from a file. The first line contains the arguments for this method. All other lines contain the methods body. """ with open(file_name, 'r') as file_obj: lines = file_obj.readlines() methods = {} name = '' for line ...
bigcode/self-oss-instruct-sc2-concepts
def _derive_module_name(ctx): """Gets the `module_name` attribute if it's set in the ctx, otherwise derive a unique module name using the elements found in the label.""" module_name = getattr(ctx.attr, "module_name", "") if module_name == "": module_name = (ctx.label.package.lstrip("/").replace(...
bigcode/self-oss-instruct-sc2-concepts
def inr(value): """Formats value as INR.""" return f"₹{value:,.2f}"
bigcode/self-oss-instruct-sc2-concepts
import json def fetch_json_from_path(path): """Helper method to fetch json dict from file Args: path: Path to fetch json dict Returns: dict: JSON object stored in file at path """ if path is not None: with open(path, "r") as file: return json.load(file) else...
bigcode/self-oss-instruct-sc2-concepts
def back_num(num: int) -> bytes: """Set terminal background color to a numbered color (0-255).""" return b"\x1b[48;5;%dm" % (num)
bigcode/self-oss-instruct-sc2-concepts
def build_testset_surprise(dataset): """ Build a test set from a Surprise Dataset so that it can be used for making predictions and model evaluation. """ testset = dataset.build_full_trainset().build_testset() return testset
bigcode/self-oss-instruct-sc2-concepts
def add_alternative_source(transfer, alt_source): """ Adds an alternative source to a transfer Args: transfer: A dictionary created with new_transfer alt_source: Alternative source Returns: For convenience, transfer """ transfer['sources'].push_back(alt_source) re...
bigcode/self-oss-instruct-sc2-concepts
def ComputeQ(node_weights): """ Computes the value of Q (sum of node weights) given the node weights of a graph. """ return node_weights.sum()
bigcode/self-oss-instruct-sc2-concepts
def get_isbn(raw): """ Extract ISBN(s). @param raw: json object of a Libris edition @type raw: dictionary """ identified_by = raw["mainEntity"].get("identifiedBy") if identified_by: isbns = [x for x in identified_by if x["@type"].lower() == "isbn"] return [x...
bigcode/self-oss-instruct-sc2-concepts
def has_any_labels(revision, labels): """ Return true if any labels are present. """ for label in labels: if label in revision: return True return False
bigcode/self-oss-instruct-sc2-concepts
def parse_parent(docname): """ Given a docname path, pick apart and return name of parent """ lineage = docname.split('/') lineage_count = len(lineage) if docname == 'index': # This is the top of the Sphinx project parent = None elif lineage_count == 1: # This is a non-inde...
bigcode/self-oss-instruct-sc2-concepts
def _get_config_option(parser, section='stere', option='', default=''): """Get an option from a config section, if it exists. Arguments: section(str): The name of the section option(str): The name of the option Returns: str: The found value, or else the default value """ if...
bigcode/self-oss-instruct-sc2-concepts
def string_to_bool(arg): """Converts a string into a returned boolean.""" if arg.lower() == 'true': arg = True elif arg.lower() == 'false': arg = False else: raise ValueError('ValueError: Argument must be either "true" or "false".') return arg
bigcode/self-oss-instruct-sc2-concepts
def all_subsets(aset): """Solution to exercise C-4.15. Write a recursive function that will output all the subsets of a set of n elements (without repeating any subsets). -------------------------------------------------------------------------- Solution: --------------------------------------...
bigcode/self-oss-instruct-sc2-concepts
def is_space_free(board, move): """Return true if the passed move is free on the passed board.""" return board[move] == ' '
bigcode/self-oss-instruct-sc2-concepts
def check_module(nwbfile, name, description=None): """ Check if processing module exists. If not, create it. Then return module. Parameters ---------- nwbfile: pynwb.NWBFile name: str description: str | None (optional) Returns ------- pynwb.module """ if name in nwbfil...
bigcode/self-oss-instruct-sc2-concepts
def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return...
bigcode/self-oss-instruct-sc2-concepts
def toposort(tasks): """Simple topological sort routine for task lists. Not fast, but easy - especially leaves nodes in original order if already topologically sorted. Dependencies that are not in the tasks list are ignored for the purpose of the sort. """ tasks_set = set(tasks) tasks_out =...
bigcode/self-oss-instruct-sc2-concepts
def quiz_question_change(statement): """ Get link for a quiz question update. :param statement: the xAPI statement :return: The url location. """ return '/assistants/api/question_sync_agent/'
bigcode/self-oss-instruct-sc2-concepts
import random def get_uniform_mutation_function(minimum, maximum): """ Returns a function that returns a value drawn from a uniform distribution over the closed interval [minimum, maximum]; see :ref:`mutation-functions` :Valid For: any gene type :param minimum: the minimum allowed value ...
bigcode/self-oss-instruct-sc2-concepts
def is_bit_set(a, offset): """ Checks whether the offset bit in a is set or not. Returns bool, True if bit in position offset in a is 1 """ return a & (1 << offset) != 0
bigcode/self-oss-instruct-sc2-concepts
def avoid_hazards(future_head, data): """ Return True if the proposed future_head avoids the hazards, False if it means you will hit a hazard. """ result = True # Get the list of hazards hazards = data["hazards"] # If the future head is in a hazard, return False to mean you'll hit ...
bigcode/self-oss-instruct-sc2-concepts
def __io_addr_reg(op): """ Return the i/o port address 'A' and register Rr/Rd from a 2-byte IN or OUT opcode sequence """ AVR_IO_IN_ADDR_MASK = 0x060F # mask for 'A' address for opcode `IN Rd,A`. nb non-contiguous addr_part = op & AVR_IO_IN_ADDR_MASK addr = ((addr_part >> 5) & 0x0030) | (addr_p...
bigcode/self-oss-instruct-sc2-concepts
import string def remove_punctuation(text: str) -> str: """ Removes punctuation from text :param text: The string being searched and replaced on :return: Text without the punctuation characters """ punctuation = string.punctuation + '¿¡' table = str.maketrans('', '', punctuation) words = t...
bigcode/self-oss-instruct-sc2-concepts
import crypt def generate_mosquitto_user_line(username, password): """Generates a line for a mosquitto user with a crypt hashed password :username: username to use :password: password that will be hashed (SHA512) :returns: a line as expected by mosquitto """ password_hash = crypt.crypt(passw...
bigcode/self-oss-instruct-sc2-concepts
import torch def make_cuda(model): """Use CUDA if available.""" if torch.cuda.is_available(): model = model.cuda() return model
bigcode/self-oss-instruct-sc2-concepts
def isPower2(num): """ Check if num is power of two """ return ((num & (num - 1)) == 0) and num > 0
bigcode/self-oss-instruct-sc2-concepts
def is_indexable_but_not_string(obj): """Return True if ``obj`` is indexable but isn't a string.""" return not hasattr(obj, "strip") and hasattr(obj, "__getitem__")
bigcode/self-oss-instruct-sc2-concepts
def _process_keys(left, right): """ Helper function to compose cycler keys Parameters ---------- left, right : Cycler or None The cyclers to be composed Returns ------- keys : set The keys in the composition of the two cyclers """ l_key = left.keys if left is not...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import ipaddress def is_ip_allowed(ip: str, allowed_networks: List[str]) -> bool: """Return True if the ip is in the list of allowed networks Any IP is allowed if the list is empty """ if not allowed_networks: return True try: addr = ipaddress.ip_address(ip...
bigcode/self-oss-instruct-sc2-concepts
def calculate_boundaries(dist_args1, dist_args2, dist_type, shift): """ Calculate minimum and maximum reward possible for certain distribution types. For normal distribution take 3 times standard deviation. These minimum and maximum are used to determine the bin sizes. :param dist_args1: parameter o...
bigcode/self-oss-instruct-sc2-concepts
def device(portnum): """Turn a port number into a device name""" return 'COM%d' % (portnum+1)
bigcode/self-oss-instruct-sc2-concepts
def func(a): """This is a function that just returns `a`.""" return a
bigcode/self-oss-instruct-sc2-concepts
def T0_T(M, gamma): """Ratio of total to static temperature for adiabatic flow (eq. 3.28) :param <float> M: Mach # at area A :param <float> gamma: Specific heat ratio :return <float> Temperature ratio T0/T """ return 1.0 + 0.5 * (gamma - 1.0) * M ** 2
bigcode/self-oss-instruct-sc2-concepts
def flip_ctrlpts2d(ctrlpts2d, size_u=0, size_v=0): """ Flips a list of surface 2-D control points in *[u][v]* order. The resulting control points list will be in *[v][u]* order. :param ctrlpts2d: 2-D control points :type ctrlpts2d: list, tuple :param size_u: size in U-direction (row length) :t...
bigcode/self-oss-instruct-sc2-concepts
def lerp(x, from_, to): """Linear interpolates a value using the `x` given and ``(x,y)`` pairs `from_` and `to`. All x values must be numbers (have `-` and `/` defined). The y values can either be single numbers, or sequences of the same length. If the latter case, then each dimension is interpolated li...
bigcode/self-oss-instruct-sc2-concepts
import itertools def pairs(list1,list2): """ :param list1: list of elements :param list2: list of elements :return: pairs of elements with no repetition """ temp = list(itertools.product(list1, list2)) # output list initialization out = [] # iteration for elem in temp: ...
bigcode/self-oss-instruct-sc2-concepts
def make_goal(nb_columns: int = 3) -> str: """ Define the goal expressed in LDLf logic. E.g. for nb_columns = 3: <(!c0 & !c1 & !c2)*;c0;(!c0 & !c1 & !c2)*;c1;(!c0 & !c1 & !c2)*;c2>tt :param nb_columns: the number of column :return: the string associated with the goal. """ labels =...
bigcode/self-oss-instruct-sc2-concepts
def _get_from_f(word: dict, key: str): """HELPER: extracts the key from the word dictionary :param word: dictionary from the json word :type word: dict :param key: key that needed to be found in the f dictionary that in word :type key: str :return: value of key in the f key in word dictionary ...
bigcode/self-oss-instruct-sc2-concepts
import base64 def save_b64_image(base64_string): """Decodes a b64-encoded image and saves it locally to disk to be displayed in the Monitoring Station GUI Args: base64_string (str): encoded image string Returns: (str): filename for decoded image """ image_bytes = base64.b6...
bigcode/self-oss-instruct-sc2-concepts
def epc_calc_common_mode(reg_dict): """ Returns True if common mode is enabled, False otherwise Parameters ---------- reg_dict : dict The dictionary that contains all the register information Returns ---------- bool True if common mode enabled, false otherwise """ ...
bigcode/self-oss-instruct-sc2-concepts
def get_item(tbl:dict, key): """ Looks up an item in a dictionary by key first, assuming the key is in the dictionary. Otherwise, it checks if the key is an integer, and returns the item in that position. :param tbl: The dictionary to look in :param key: The key, or integer position to get th...
bigcode/self-oss-instruct-sc2-concepts
import collections def _list_to_dicts(list_of_values, keys): """Restores a list of dicts from a list created by `_dicts_to_list`. `keys` must be the same as what was used in `_dicts_to_list` to create the list. This is used to restore the original dicts inside `host_call_fn` and `metrics_fn`. Transforms a...
bigcode/self-oss-instruct-sc2-concepts
def rotate270_augment(aug=None, is_training=True, **kwargs): """Rotation by 270 degree augmentation.""" del kwargs if aug is None: aug = [] if is_training: return aug + [('rotate270', {})] return aug
bigcode/self-oss-instruct-sc2-concepts
def create_deets_message(time, size, image): """Creates message of image details for the GUI client Image details returned include the time the image was uploaded or processed and the image size in pixels. If the image was original, the upload time is returned. If the image was inverted, the process...
bigcode/self-oss-instruct-sc2-concepts
def _get_venue_storage(districts): """Initializes a dict for storing venues, organized by district. """ # This ensures districts are included even if they have no rated venues. res = {district['name']: [] for district in districts} res[None] = [] # Hack: avoids exception if venue has no district. ...
bigcode/self-oss-instruct-sc2-concepts
import re def create_form_data(data): """ Convert all keys in data dictionary from camelCaseFormat to underscore_format and return the new dict """ to_lower = lambda match: "_" + match.group(1).lower() to_under = lambda x: re.sub("([A-Z])", to_lower, x) return dict(map(lambda x: (to_under(...
bigcode/self-oss-instruct-sc2-concepts
def find_my_friend(queue: list, friend_name: str) -> int: """ :param queue: list - names in the queue. :param friend_name: str - name of friend to find. :return: int - index at which the friends name was found. """ for i, name in enumerate(queue): if friend_name == name: ret...
bigcode/self-oss-instruct-sc2-concepts
import networkx as nx def OeMolToGraph(oemol): """ Convert charged molecule to networkX graph and add WiberBondOrder as edge weight Parameters ---------- mol: charged OEMolGraph Returns ------- G: NetworkX Graph of molecule """ G = nx.Graph() for atom in oemol.GetAtoms()...
bigcode/self-oss-instruct-sc2-concepts
import pathlib def return_file_extension(_path): """Return string of file extension. Example: .txt; .py""" return pathlib.Path(_path).suffix
bigcode/self-oss-instruct-sc2-concepts
def read_csv(filepath): """ Simple CSV reader function required for blast function to output results as a dictionary Input ----- filepath = str, path to the CSV file containing blast results Output ------ dictionary = dict, keys = column names, values = columns. ...
bigcode/self-oss-instruct-sc2-concepts
def array_find(arr, obj) -> int: """A helpher function which finds the index of an object in an array. Instead of throwing an error when no index can be found it returns -1. Args: arr : the array to be searched obj : the object whose index is to be found. Returns: int: The i...
bigcode/self-oss-instruct-sc2-concepts
def __calculate_waterfootprint(wf_ing, quantity): """ Calculate the right water footprint of a ingredient from its (l/kg) water footprint and the quantity provided (in gr). :param wf_ing: the water footprint of the ingredient. :param quantity: the quantity of the ingredient. :return: the water ...
bigcode/self-oss-instruct-sc2-concepts
def _is_extended_mux_needed(messages): """Check for messages with more than one mux signal or signals with more than one multiplexer value.""" for message in messages: multiplexers = [ signal.name for signal in message.signals if signal.is_multiplexer ] ...
bigcode/self-oss-instruct-sc2-concepts
def parse_int(arg): """ Parse an integer of an unknown base. The supported bases are 2, 8, 10 and 16. """ arg = arg.lower() base = 10 if arg.startswith('0x'): base = 16 elif arg.startswith('0b'): base = 2 elif arg.startswith('0o'): base = 8 return int...
bigcode/self-oss-instruct-sc2-concepts
def _combine_external_inputs_with_precursor_nodes(node, external_inputs): """ User_provided_input_nodes. Args: node (OnnxGraphNode): Node instance. external_inputs (list[str]): Inputs in onnx ir. Returns: list[str], precursor nodes list. """ inputs = set(node.ir_node_in...
bigcode/self-oss-instruct-sc2-concepts
import random import string def generate_name(length=8): # type: (int) -> str """Generate and return a random name.""" return ''.join(random.choice(string.ascii_letters + string.digits) for _idx in range(length))
bigcode/self-oss-instruct-sc2-concepts
import re def check_mixed_digits(value): """ Checks if an string has mixed digits :param value: String to be checked :type value: String :returns: True if there are mixed digits in the string :rtype: Boolean Examples: >>> check_mixed_digits('Lorem ipsum dolor sit amet, consec...
bigcode/self-oss-instruct-sc2-concepts
def file_fzp_start(filename): """ finds the start of the fzp data :param filename: string of the fzp file name :return: number of lines to skip at top of file """ with open(filename) as in_f: c= 0 cols = [] #find start of VISSIM data line = in_f.readline() ...
bigcode/self-oss-instruct-sc2-concepts
def emphasis_sub(match): """Substitutes <strong>, <em>, and <strong><em> tags.""" level = len(match.group(1)) content = match.group(2) if level == 3: return '<strong><em>{0}</em></strong>'.format(content) elif level == 2: return '<strong>{0}</strong>'.format(content) elif level =...
bigcode/self-oss-instruct-sc2-concepts
import math def calculate_distance(coord1, coord2, box_length=None): """ Calculate the distance between two 3D coordinates. Parameters ---------- coord1, coord2: list The atomic coordinates Returns ------- distance: float The distance between the two points. ...
bigcode/self-oss-instruct-sc2-concepts
import re def isurl(value): """ Return whether or not given value is an URL. If the value is an URL, this function returns ``True``, otherwise ``False``. Examples:: >>> isurl('http://foo.bar#com') True >>> isurl('http://foobar.c_o_m') False :param value: string ...
bigcode/self-oss-instruct-sc2-concepts
def longest_common_subsequence(x, y): """longest common subsequence Dynamic programming :param x: :param y: x, y are lists or strings :returns: longest common subsequence in form of a string :complexity: `O(|x|*|y|)` """ n = len(x) m = len(y) # -- compute o...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_charges(node): """ Solve the function to get the absolute charges of atoms in a molecule from parameters. Parameters ---------- e : tf.Tensor, dtype = tf.float32, electronegativity. s : tf.Tensor, dtype = tf.float32, hardness. Q : tf.Tensor, dtype = tf....
bigcode/self-oss-instruct-sc2-concepts
import re def RemoveReportHeaderAndFooter(output): """Removes Google Test result report's header and footer from the output.""" output = re.sub(r'.*gtest_main.*\n', '', output) output = re.sub(r'\[.*\d+ tests.*\n', '', output) output = re.sub(r'\[.* test environment .*\n', '', output) output = re.sub(r'\[=...
bigcode/self-oss-instruct-sc2-concepts
def cgi_decode(s): """Decode the CGI-encoded string `s`: * replace "+" by " " * replace "%xx" by the character with hex number xx. Return the decoded string. Raise `ValueError` for invalid inputs.""" # Mapping of hex digits to their integer values hex_values = { '0': 0, '1': 1...
bigcode/self-oss-instruct-sc2-concepts
def should_apply_max_and_skip_env(hparams): """MaxAndSkipEnv doesn't make sense for some games, so omit it if needed.""" return hparams.game != "tictactoe"
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def norm_abs_path(path, ref_path): """\ Convert `path` to absolute assuming it's relative to ref_path (file or dir). """ path, ref_path = Path(path), Path(ref_path).absolute() ref_dir = ref_path if ref_path.is_dir() else ref_path.parent return ref_dir / path
bigcode/self-oss-instruct-sc2-concepts
def get_user_choice(choices, choice_type, default_value=""): """ A common method to take user choice from a list of choices Args: (list) choices - list of choices (str) choice_type - Type of choice (boolean) default_value - Return default value in case wrong input Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def partTypeNum(partType): """ Mapping between common names and numeric particle types. """ if str(partType).isdigit(): return int(partType) if str(partType).lower() in ['gas','cells']: return 0 if str(partType).lower() in ['dm','darkmatter']: return 1 if str(partType).l...
bigcode/self-oss-instruct-sc2-concepts
import itertools def _split_list(lst, delim): """ 리스트를 delimiter로 split하는 함수 >>> _split_list(['가/JKS', '_', '너/NP'], '_') [['가/JKS'], ['너/NP']] Args: lst: 리스트 delim: delimiter Returns: list of sublists """ sublists = [] while lst: prefix = [x for...
bigcode/self-oss-instruct-sc2-concepts
def lremove(s, prefix): """Remove prefix from string s""" return s[len(prefix):] if s.startswith(prefix) else s
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def prelimSeeds(URL: str) -> dict: """Parses the prelim seeds page of a tournament Args: URL (str): the URL of the prelim seeds page of a certain division Returns: dict: a dict containing the parsed prelim data RETURN SCHEMA: ...
bigcode/self-oss-instruct-sc2-concepts
def date_to_string(date, granularity=0): """ Convert a date to a string, with an appropriate level of granularity. :param date: A datetime object. :param granularity: Granularity for the desired textual representation. 0: precise (date and time are returned) ...
bigcode/self-oss-instruct-sc2-concepts