seed
stringlengths
1
14k
source
stringclasses
2 values
def get_address_type(ip_type): """ Return the address type to reserve. """ if ip_type in ['GLOBAL', 'REGIONAL']: return 'EXTERNAL' return 'INTERNAL'
bigcode/self-oss-instruct-sc2-concepts
def ss_to_index(ss): """Secondary structure symbol to index. H=0 E=1 C=2 """ if ss == "H": return 0 if ss == "E": return 1 if ss == "C": return 2 assert 0
bigcode/self-oss-instruct-sc2-concepts
import random import string def random_alphanumeric(length=5, upper_case=False): """Generate a random alphanumeric string of given length :param length: the size of the string :param upper_case: whether to return the upper case string """ if upper_case: return ''.join(random.choice( ...
bigcode/self-oss-instruct-sc2-concepts
def multi1(vals): """ This will either return the common value from a list of identical values or the single character '?' """ uniq_vals = list(set(vals)) num_vals = len(uniq_vals) if num_vals == 0: return None if num_vals == 1: return uniq_vals[0] if num_vals > 1: ...
bigcode/self-oss-instruct-sc2-concepts
def ternary(value, result_true, result_false): """ Implements a ternary if/else conditional. """ return result_true if value else result_false
bigcode/self-oss-instruct-sc2-concepts
def square(x): """ Squares given number """ return x ** 2
bigcode/self-oss-instruct-sc2-concepts
def flatten_dict(tree, parent_key='', sep=' '): """ Recursively flatten a nested dictionary into a single level whose keys are phrases. For example, given the following dict: ..code-block:: python { 'my': { 'git': { 'branch': 'master' ...
bigcode/self-oss-instruct-sc2-concepts
import re def detect_timestamp_format(timestamp): """ Given an input timestamp string, determine what format is it likely in. :param string timestamp: the timestamp string for which we need to determine format :return: best guess timestamp format """ time_formats = { 'epoch': re.compile(r'^[0-9]{10...
bigcode/self-oss-instruct-sc2-concepts
import io def read_img_bin(img_fn): """Get image binary from an image file. Args: img_fn: image file path. Returns: image binary data as bytes. """ with io.open(img_fn, "rb") as f: img_bin_bytes = f.read() return img_bin_bytes
bigcode/self-oss-instruct-sc2-concepts
def calculate_common_period(a_times, b_times): """ Calculate the common period between two time series. Parameters ---------- a_times, b_times: numpy arrays of numpy datetime64s Arrays of datetimes. Returns ------- start_time: the latest of the two series start times. finis...
bigcode/self-oss-instruct-sc2-concepts
def operation_1(request): """ This will be in description """ return {"docstrings": True}
bigcode/self-oss-instruct-sc2-concepts
def isWithinUnitedStates(latitude, longitude): """Returns true if the latitude longitude pair is roughly within the boundaries of the United States. Returns false otherwise""" return (25 < latitude and latitude < 50) and (-127 < longitude and longitude < -65)
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def _get_optional_type(type_): """Check if a type is an ``Union`` permitting ``None``. For ``Optional``-like unions permitting only ``None`` and another type, returns the other type. For other ``None``-permitting unions, returns ``True``. For everything else, returns ``False``. ...
bigcode/self-oss-instruct-sc2-concepts
def timestamp2date(ts): """ Converts Timestamp object to str containing date """ date = ts.date().strftime("%Y-%m-%d") return date
bigcode/self-oss-instruct-sc2-concepts
import time def time_delta_now(t_start: float) -> str: """ Convert the difference of the given timestamp and now into a human readable timestring. Args: t_start (float): Start timestamp. Returns: Human readable timestring of time passed between `t_start` and now. """ a = t_sta...
bigcode/self-oss-instruct-sc2-concepts
import math def convert_kelvins_to_rgb_bartlett(color_temperature: float) -> tuple: """ Convert Kelvin temperature to black body emission RGB color using approximation by Neil Bartlett Author used the ideas of Tanner Helland and came up with a slightly better approximation Source: http://www.zombiepro...
bigcode/self-oss-instruct-sc2-concepts
def reverse(s: str) -> str: """ For a string s return the reversed string s[::-1]. """ return s[::-1]
bigcode/self-oss-instruct-sc2-concepts
def get_db_connection_tz(cursor): """ Return time zone of the Django database connection with which the specified cursor is associated. """ cursor.execute("SHOW timezone;") return cursor.fetchall()[0][0]
bigcode/self-oss-instruct-sc2-concepts
import math def probability_to_bayeselo(probability): """ Takes a probability: P['win'], P['loss'] Returns elo, draw_elo """ assert (0 < probability['win'] < 1 and 0 < probability['loss'] < 1) elo = 200 * math.log10( probability['win'] / probability['loss'] * (1 - probability['...
bigcode/self-oss-instruct-sc2-concepts
def hex_to_bin(hex_value) -> str: """ Convert all hex digits to binary representation, with leading zeroes """ bin_len = 4*len(hex_value) # 4 bits per hex return "{0:0{width}b}".format(int(hex_value, 16), width=bin_len)
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any from typing import List def handle_price_rows( card_data: Dict[str, Any], card_uuid: str ) -> List[Dict[str, Any]]: """ This method will take the card data and convert it, preparing for SQLite insertion :param card_data: Data to process :param car...
bigcode/self-oss-instruct-sc2-concepts
def zif_bank_code(zif_pinout: list): """ Return a list encoding even/odd ZIF pins in the data acquisition order. Empirically, this has been useful for finding differential offsets in array maps (although the ZIF even-/odd-ness tends to overlap with other pin breakouts). >>> print(zif_pintout(zif_by...
bigcode/self-oss-instruct-sc2-concepts
import pathlib def gef_makedirs(path: str, mode: int = 0o755) -> pathlib.Path: """Recursive mkdir() creation. If successful, return the absolute path of the directory created.""" fpath = pathlib.Path(path) if not fpath.is_dir(): fpath.mkdir(mode=mode, exist_ok=True, parents=True) return fpath....
bigcode/self-oss-instruct-sc2-concepts
def convert_line_graph_path(path: list) -> list: """ Converts the given shortest path for the line graph into the min cost path in the original path. In principle, this means extracting the nodes in the right order from the given line graph path. The given line-graph path looks like: (n1, n2), (n3, n4) ...
bigcode/self-oss-instruct-sc2-concepts
def replace_first(base, old, new): """Replace the first substring with new string""" return base.replace(old, new, 1)
bigcode/self-oss-instruct-sc2-concepts
def parse_nuclide(nuclide: str) -> str: """ Parses a nuclide string from e.g. '241Pu' or 'Pu241' format to 'Pu-241' format. Not this function works for both radioactive and stable nuclides. Parameters ---------- nuclide : str Nuclide string. Returns ------- str Nucl...
bigcode/self-oss-instruct-sc2-concepts
import torch def bbox_cxcywh_to_xyxy(bbox): """Convert bbox coordinates from (cx, cy, w, h) to (x1, y1, x2, y2). Args: bbox (Tensor): Shape (n, 4) for bboxes. Returns: Tensor: Converted bboxes. """ cx, cy, w, h = bbox.split((1, 1, 1, 1), dim=-1) bbox_new = [(cx - 0.5 * w), (c...
bigcode/self-oss-instruct-sc2-concepts
def factorial(num): """ This function calculates factorial of a number recursively. n! = n*(n-1)*(n-2)*...*2*1 Parameters ---------- num : uint64 Input positive integer to calcuate factorial. Returns ------- uint64 Factorial of input positive integer. """ ...
bigcode/self-oss-instruct-sc2-concepts
def _encode_string(s: str) -> bytes: """ Encode a python string into a bencoded string. """ return f"{len(s)}:{s}".encode("utf-8")
bigcode/self-oss-instruct-sc2-concepts
def _get_downcast_field(class_reference): """Get the downcast field name if set, None otherwise.""" return getattr(class_reference, "__deserialize_downcast_field__", None)
bigcode/self-oss-instruct-sc2-concepts
def prefixes(s: str): """ Returns the prefixes of the string given in parameter """ return (s[:i] for i in range(len(s) + 1))
bigcode/self-oss-instruct-sc2-concepts
def get_dim_inds(generalized_tensor): """ Returns a tuple 0..length, where length is the number of dimensions of the tensors""" return tuple(range(len(generalized_tensor.shape)))
bigcode/self-oss-instruct-sc2-concepts
def request_method_predicate(self, obj, request): """match request method. Predicate for :meth:`morepath.App.view`. """ return request.method
bigcode/self-oss-instruct-sc2-concepts
import requests def create_http_reader(url): """ Simple reader for an HTTP resource. """ def http_reader(): return requests.get(url).content return http_reader
bigcode/self-oss-instruct-sc2-concepts
import io def generate_generic_error_message(exception: Exception, lineno: int) -> str: """ Generate a generic error message in the following format: { exception.__class__.__name } in line { lineno }: { str(exception) } """ buffer = io.StringIO() buffer.write('\n') buffer.write(excep...
bigcode/self-oss-instruct-sc2-concepts
import textwrap def format_ordinary_line(source_line, line_offset): """Format a single C++ line with a diagnostic indicator""" return textwrap.dedent( f"""\ ```cpp {source_line} {line_offset * " " + "^"} ``` """ )
bigcode/self-oss-instruct-sc2-concepts
def _flatten_list_of_lists(_2d_list): """Input a list of lists and output one single list""" flat_list = [] # Iterate through the outer list for element in _2d_list: if type(element) is list: # If the element is of type list, iterate through the sublist for item in ele...
bigcode/self-oss-instruct-sc2-concepts
def has_core_metadata(response, file_type): """ Return True if a query response contains core metadata, False otherwise. """ try: # try to access the core_metadata response["data"][file_type][0]["core_metadata_collections"][0] except: return False return True
bigcode/self-oss-instruct-sc2-concepts
import platform def get_system_type() -> str: """Attempts to determine what type of system we're on, limited to systems this addon can usefully do things with""" system = platform.uname()[0].lower() if system in ["windows"]: return system return "unknown"
bigcode/self-oss-instruct-sc2-concepts
import string def filter_unicode(data): """ Function to remove all non-printable characters from a string :param data: str: String to be analysed :return: String with all non-printable characters removed """ return "".join(c for c in str(data) if c in string.printable)
bigcode/self-oss-instruct-sc2-concepts
def quantile(xs, q=(0.25, 0.5, 0.75), sort=True): """Returns the qth quantile of an unsorted or sorted numeric vector. There are a number of different ways to calculate the sample quantile. The method implemented by igraph is the one recommended by NIST. First we calculate a rank n as q(N+1), where N i...
bigcode/self-oss-instruct-sc2-concepts
import asyncio def create_checked_task(coro_or_future): """ Wrapper for `asyncio.ensure_future` that always propagates exceptions. """ def raise_any_exc(task): return task.result() task = asyncio.ensure_future(coro_or_future) task.add_done_callback(raise_any_exc) return task
bigcode/self-oss-instruct-sc2-concepts
def scalar_function(x, y): """ Returns the f(x,y) defined in the problem statement. """ if x <= y: return x * y return x / y
bigcode/self-oss-instruct-sc2-concepts
def _clean_accounting_column(x: str) -> float: """ Perform the logic for the `cleaning_style == "accounting"` attribute. This is a private function, not intended to be used outside of `currency_column_to_numeric``. It is intended to be used in a pandas `apply` method. :returns: An object with...
bigcode/self-oss-instruct-sc2-concepts
def bytes_to_int(b: bytes): """ Convert a byte array to an integer. :param b: the byte array :return: the integer """ neg = False # Have we determined the value to be negative? We'll see. i=0 # This is the variable in which we'll store the value. # Now we need to do some tap dancing ...
bigcode/self-oss-instruct-sc2-concepts
import pickle import hashlib def generate_hash(data_in): """ Generate a hash from the data_in that can be used to uniquely identify equivalent data_in. Args: data_in (any): The data from which a hash is to be generated. This can be of any type that can be pickled. ...
bigcode/self-oss-instruct-sc2-concepts
def eat_ghost(power_pellet_active: bool, touching_ghost: bool) -> bool: """ Args: power_pellet_active (bool): does the player have an active power pellet? touching_ghost (bool): is the player touching a ghost? Returns: bool """ return power_pellet_active and touching_ghost
bigcode/self-oss-instruct-sc2-concepts
def fastaRecordSizer(recordLines): """ Returns the number of charcters in every line excluding: the first (header) line whitespace at the start and end of lines """ size=0 for i in range(1,len(recordLines)): size+=len(recordLines[i].strip()) return size
bigcode/self-oss-instruct-sc2-concepts
def argmin(list_obj): """Returns the index of the min value in the list.""" min = None best_idx = None for idx, val in enumerate(list_obj): if min is None or val < min: min = val best_idx = idx return best_idx
bigcode/self-oss-instruct-sc2-concepts
def remove_prefix(text, prefix): """ Remove the prefix from the text if it exists. >>> remove_prefix('underwhelming performance', 'underwhelming ') 'performance' >>> remove_prefix('something special', 'sample') 'something special' """ null, prefix, rest = text.rpartition(prefix) re...
bigcode/self-oss-instruct-sc2-concepts
def flip_v(grid): """Flip grid vertically.""" return '\n'.join(reversed(grid.split('\n')))
bigcode/self-oss-instruct-sc2-concepts
import ipaddress def parse_ip(ip_bytes): """ Convert an IPv4/IPv6 address in bytes to a valid IP address in string format, if it is indeed valid. :param bytes ip_bytes: bytes of IPv4/IPv6 address. :returns: IP address in string format, None if input invalid. """ try: retu...
bigcode/self-oss-instruct-sc2-concepts
import struct import socket import fcntl def get_interface_IP(interface_name): """Retrieve IP address of the specified network interface. Args: interface_name (str): Name of the interace. Returns: str: Standard dotted-quad string representation of the IP address. """ IFNAMSIZ = 1...
bigcode/self-oss-instruct-sc2-concepts
def mlo(i, j): # pragma: no cover """Auxiliary function for La Budde's algorithm. See `arXiv:1104.3769 <https://arxiv.org/abs/1104.3769v1>`_. .. note:: The La Budde paper uses indices that start counting at 1 so this function lowers them to start counting at 0. Args: matrix (...
bigcode/self-oss-instruct-sc2-concepts
import textwrap def format_tooltip(text, *args, **kwargs): """ Wrapper around textwrap.fill that preserves newline characters """ return '\n'.join(textwrap.fill(t, *args, **kwargs) \ for t in text.splitlines())
bigcode/self-oss-instruct-sc2-concepts
def months_interval(start_date, end_date): """ Generate the monthly intervals between a start date and an end date """ months_num = [str(i+1).zfill(2) for i in range(12)] start_year = int(start_date[0:4]) start_month = int(start_date[4:6]) end_year = int(end_date[0:4]) end_month = int(en...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import Tuple def named_range(name, stop: int) -> Sequence[Tuple[str, int]]: """Equivalent to `range()` but suitable for use with ``named_parameters``.""" return tuple(((f"{name}_{i}", i) for i in range(stop)))
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import Iterable def stringify(value: Any) -> Any: """Creates an equivalent data structure representing data values as string Parameters ---------- value Value to be stringified Returns ------- stringified_value """ if value is None or is...
bigcode/self-oss-instruct-sc2-concepts
def elementwise_list_addition(increment, list_to_increment): """ Simple method to element-wise increment a list by the values in another list of the same length. """ if not list_to_increment: return increment assert len(increment) == len(list_to_increment), 'Attempted to add two lists of di...
bigcode/self-oss-instruct-sc2-concepts
def utc_iso8601(datetime): """Convert a UTC datetime into an ISO8601 timestamp string.""" return datetime.strftime("%Y-%m-%dT%H:%M:%S.%f+00:00")
bigcode/self-oss-instruct-sc2-concepts
import torch def proj(x, epsilon=0.00001): """ Projects a matrix of vectors in hyperbolic geometry back into the unit ball Parameters ---------- x the matrix with each row representing a vector epsilon the small difference to subtract to ensure that vectors remain in the unit b...
bigcode/self-oss-instruct-sc2-concepts
import socket def get_host_name() -> str: # pragma: no cover - we're just proxying """Get hostname of the machine Returns: str: host name """ return socket.gethostname()
bigcode/self-oss-instruct-sc2-concepts
def reverse_complement(dna, reverse=True, complement=True): """ Make the reverse complement of a DNA sequence. You can also just make the complement or the reverse strand (see options). Input: A DNA sequence containing 'ATGC' base pairs and wild card letters Output: DNA sequence as a string. ...
bigcode/self-oss-instruct-sc2-concepts
def predict(x_tst, model): """ The method predicts labels for testing data samples by using trained learning model. Parameters ---------- x_tst: features of testing data model: trained learning model """ predictions = model.predict(x_tst) return predictions
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import re def __is_condition_met(condition_type: str, condition_value: Any, value: Any) -> bool: """ Checks if given value meets the given condition Args: condition_type: condition type, could be "equal" or "regex" condition_value: the value of the condition, in case...
bigcode/self-oss-instruct-sc2-concepts
def y_coordinate(block): """Returns the y-coordinate component in block as a string.""" start = block.find(',')+1 # Skip the first space end = block.find(' ', block.find(' ')+1) return block[start:end]
bigcode/self-oss-instruct-sc2-concepts
def write_coord(coord): """ Adjusts whitespace for coordinates """ return "{:06.8f}".format(coord) if coord < 0.0 else " " + "{:06.8f}".format(coord)
bigcode/self-oss-instruct-sc2-concepts
import torch def compute_batch_accuracy(output, target): """Computes the accuracy for a batch""" with torch.no_grad(): batch_size = target.size(0) _, pred = output.max(1) correct = pred.eq(target).sum() return correct * 100.0 / batch_size
bigcode/self-oss-instruct-sc2-concepts
def twitter_auth_required(view_func): """ Decorator for views that requires the authenicated user to have authorized the site on Twitter. If no credentials are on record, user will be directed to a page to authorize the site. """ view_func.twitter_auth_required = True return view_func
bigcode/self-oss-instruct-sc2-concepts
def lsum (inlist): """ Returns the sum of the items in the passed list. Usage: lsum(inlist) """ s = 0 for item in inlist: s = s + item return s
bigcode/self-oss-instruct-sc2-concepts
def TETChromaticScale(frequency, octaveDivider): """creates an even tempered scale with a given starting frequency and a number for how many divisions you want the octave to be divided into. Returns an Array""" i = 0 scale = [] while i < octaveDivider: i += 1 note = round(frequency *...
bigcode/self-oss-instruct-sc2-concepts
def GetParentNodeWhereTrue(node_id, tree, stop_function): """walk up in gene tree and stop where stop_function is true. The walk finishes at the root. returns tuple of node and distance. """ node = tree.node(node_id) distance = 0 while node.prev is not None: if stop_function(node...
bigcode/self-oss-instruct-sc2-concepts
def setBit(num, n): """ Return num with the nth bit set to 1. """ # Make a mask of all 0s with the nth bit set to 1. mask = 1 << n return num | mask
bigcode/self-oss-instruct-sc2-concepts
import time def display_timestamp(t): """Takes a Unix timestamp as a an arg, returns a text string with '<unix timestamp> (<equivalent time>)'.""" return '%s (%s)' % (t, time.strftime('%d/%m/%Y %H:%M', time.gmtime(t)))
bigcode/self-oss-instruct-sc2-concepts
def create_valid_bigquery_field_name(field_name): """ Clean up / prettify field names, make sure they match BigQuery naming conventions. Fields must: • contain only -letters, -numbers, and -underscores, • start with a -letter or ...
bigcode/self-oss-instruct-sc2-concepts
def uniq(iterable, key=lambda x: x): """ Remove duplicates from an iterable. Preserves order. :type iterable: Iterable[Ord => A] :param iterable: an iterable of objects of any orderable type :type key: Callable[A] -> (Ord => B) :param key: optional argument; by default an item (A) is discarded ...
bigcode/self-oss-instruct-sc2-concepts
def make_cached_ssd_store_options( cache_budget_mb, persistent_path, capacity=None, size_factor=1, physical_block_size=512, host_cache_budget_mb=0, ): """make SSD use GPU and host as cache store_options param of MultiTableEmbedding. If cache_budget_mb > 0 and host_cache_budget_mb > 0, use GP...
bigcode/self-oss-instruct-sc2-concepts
import re def is_match(regex, string, ignore_case=False): """Check if regex matches string.""" regex_flags = re.DOTALL if ignore_case: regex_flags = re.DOTALL | re.IGNORECASE return re.match(regex, string, regex_flags) is not None
bigcode/self-oss-instruct-sc2-concepts
def classify_token(w): """ Function for feature augmentation. Improves the network's results by generating the information that will be fed into the feature-augmentend embedding layer Parameters ---------- w : str Word Returns ------- str Class to which a token ...
bigcode/self-oss-instruct-sc2-concepts
def _get_global_variable_names(name, tuple_path): """Get the global variables names for ground truth. Args: name: Python `str`. Name of the sample transformation. tuple_path: Tuple path of the part of the ground truth we're saving. See `nest.flatten_with_tuple_paths`. Returns: mean_name: Varia...
bigcode/self-oss-instruct-sc2-concepts
def _parse_file_move(file_move): """Return the (old_filename, new_filename) tuple for a file move.""" _, old_filename, new_filename = file_move.split() return (old_filename, new_filename)
bigcode/self-oss-instruct-sc2-concepts
import hashlib def getETag(data): """Gets the ETag for the specified data. Args: data: The data for which the ETag should be generated. """ md5 = hashlib.md5() md5.update(data) return md5.hexdigest()[-16:]
bigcode/self-oss-instruct-sc2-concepts
def njoiner(inbox, n=None, join=""): """ String joins and returns the first "n" inputs. Arguments: - n(``int``) [default: ``None``] All elements in the inbox smaller then this number will be joined. - join(``str``) [default: ``""``] String which will join the elements of the ...
bigcode/self-oss-instruct-sc2-concepts
import traceback def format_exception(e): """ Format the traceback of the exception ``e`` in a string. """ elements = traceback.format_exception(type(e), e, e.__traceback__) return ''.join(elements)
bigcode/self-oss-instruct-sc2-concepts
def est_majeure(nom: str, prenom : str, age: int) -> bool: """ Renvoie True si la personne est majeure, ou False sinon. Précondition : nom != "" and prenom != "" and age > 0 """ return age >= 18
bigcode/self-oss-instruct-sc2-concepts
def optimizerModel2wts(model): """Convert an optimizer model file into a flat weight vector.""" wts = [] with open(model) as f: for line in f: wts.append(float(line.partition(' ')[2])) return wts
bigcode/self-oss-instruct-sc2-concepts
def convert_wavelength_vacuum2air(wavelength_vacuum): """ Convert vacuum wavelength to air wavelength Parameters ----------- wavelength_vacuum: float Vacuum wavelength in Angstroms Returns -------- float Air wavelength in Angstroms """ sigma2 = (1e4/wavelength_va...
bigcode/self-oss-instruct-sc2-concepts
def is_sorted( s, strict = True ): """Test if a sequence is sorted""" prev_elem = None for x in s: if prev_elem != None and x < prev_elem or ( x == prev_elem and strict ): return False prev_elem = x return True
bigcode/self-oss-instruct-sc2-concepts
from PIL import Image def _to_pil_rgb_image(image): """Returns an PIL Image converted to the RGB color space. If the image has an alpha channel (transparency), it will be overlaid on a black background. :param image: the PIL image to convert :returns: The input image if it was already in RGB mode, o...
bigcode/self-oss-instruct-sc2-concepts
def get_bfield_name(name): """Sanitize the name of bitfields.""" return name.replace(' ', '') + 'Bits'
bigcode/self-oss-instruct-sc2-concepts
def get_refdes(anno_record): """ Build and return a reference designator from the subsite, node and sensor fields in record supplied. """ subsite = anno_record.get('subsite', None) node = anno_record.get('node', None) sensor = anno_record.get('sensor', None) if node is None: return subsi...
bigcode/self-oss-instruct-sc2-concepts
def _is_comment(line): """ Assert if line is a comment or a line to ignore. Expects striped lines. """ is_comment = \ line.startswith('#') \ or not bool(line) return is_comment
bigcode/self-oss-instruct-sc2-concepts
def calc_3d_bbox(xs, ys, zs): """Calculates 3D bounding box of the given set of 3D points. :param xs: 1D ndarray with x-coordinates of 3D points. :param ys: 1D ndarray with y-coordinates of 3D points. :param zs: 1D ndarray with z-coordinates of 3D points. :return: 3D bounding box (x, y, z, w, h, d)...
bigcode/self-oss-instruct-sc2-concepts
def add_mask_if_none(f, clip, *a, **k): """ Add a mask to the clip if there is none. """ if clip.mask is None: clip = clip.add_mask() return f(clip, *a, **k)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def add_stem_suffix(p: Path, s: str) -> Path: """ eg. ("/path/to/file.ext","-suffix") -> ("/path/to/file-suffix.ext")""" return p.parent / Path(p.stem + s + p.suffix)
bigcode/self-oss-instruct-sc2-concepts
def compare_version(lhs, rhs): """Compare two versions. Parameters ---------- lhs : tuple tuple of three integers (major, minor, patch) rhs : tuple tuple of three integers (major, minor, patch) Returns ------- int Returns 0 if lhs and rhs are equal, 1 if lhs is bigger than rhs, otherwise...
bigcode/self-oss-instruct-sc2-concepts
def default_to_list(value): """ Ensures non-list objects are add to a list for easy parsing. Args: value(object): value to be returned as is if it is a list or encapsulated in a list if not. """ if not isinstance(value, list) and value is not None: value = [value] el...
bigcode/self-oss-instruct-sc2-concepts
def _to_list(obj): """Make object into a list""" return [obj] if not isinstance(obj, list) else obj
bigcode/self-oss-instruct-sc2-concepts
import functools import time def timed(func): """ Time the execution of a wrapped function and print the output :param func: Function to be wrapped :return: function to be wrapped """ @functools.wraps(func) def wrap(*args, **kwargs): start = time.perf_counter() func(*args,...
bigcode/self-oss-instruct-sc2-concepts
def shorten_task_names(configs, common_task_prefix): """ Shorten the task names of the configs by remove the common task prefix. """ new_configs = [] for config in configs: config.task_name = config.task_name.replace(common_task_prefix, "") new_configs += [config] return new_conf...
bigcode/self-oss-instruct-sc2-concepts