seed
stringlengths
1
14k
source
stringclasses
2 values
from typing import Any from typing import Sequence def _get_value_str(value: Any, arguments: Sequence[str], index: int = 0) -> str: """Returns the `value_str` given parsed `arguments` and the desired `index`. Args: value: The input value to generate a string representation for. arguments: The input seque...
bigcode/self-oss-instruct-sc2-concepts
def has_snapshot(html): """Given a BeautifulSoup instance containing the HTML of a search result webpage from archive.org, this method will search the HTML for an id='error' tag. If there is such a tag, that means there is no snapshot of the URL searched for. If there is no error tag, that means there i...
bigcode/self-oss-instruct-sc2-concepts
def split_fields(fields): """ >>> from comma.csv.applications.csv_eval import split_fields >>> split_fields('') [] >>> split_fields('x') ['x'] >>> split_fields('x,y') ['x', 'y'] """ return fields.split(',') if fields else []
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import Optional def lower_vector_to_matrix( lower_flat: torch.Tensor, matrix_dim: Optional[int] = None ) -> torch.Tensor: """Convert a valid vector to a lower triangular matrix. Parameters ---------- vector : torch.Tensor vector matix_dim : Optional[int] ...
bigcode/self-oss-instruct-sc2-concepts
def sound_exposure(pressure, fs, axis=-1): """ Sound exposure :math:`E_{T}`. :param pressure: Instantaneous sound pressure :math:`p`. :param fs: Sample frequency :math:`f_s`. :param axis: Axis. .. math:: E_T = \\int_{t_1}^{t_2} p^2 (t) \\mathrm{d}t """ return (pressure**2.0/fs).sum(ax...
bigcode/self-oss-instruct-sc2-concepts
def get_default_nncf_compression_config(h, w): """ This function returns the default NNCF config for this repository. The config makes NNCF int8 quantization. """ nncf_config_data = { 'input_info': { 'sample_size': [1, 3, h, w] }, 'compression': [ { ...
bigcode/self-oss-instruct-sc2-concepts
def f2c(f): """Fahrenheit to Celsius""" return (f - 32)*5/9
bigcode/self-oss-instruct-sc2-concepts
def get_weighted_completion_scores(job_list): """ Gets the weighted completion score for a set of jobs by taking the sum of the total time elapsed at the end of each job * job weight. """ total_length, score = 0, 0 for job in job_list: total_length += job[1] score += (total_leng...
bigcode/self-oss-instruct-sc2-concepts
import pytz def validate_timezone(zone): """Return an IETF timezone from the given IETF zone or common abbreviation. :param str zone: in a strict or a human-friendly format :return: the valid IETF timezone properly formatted :raise ValueError: when ``zone`` is not a valid timezone Prior to check...
bigcode/self-oss-instruct-sc2-concepts
def is_git_diff_header(diff_header): """Returns True if the diff was generated with git.""" return any(l.startswith('diff --git') for l in diff_header.splitlines())
bigcode/self-oss-instruct-sc2-concepts
def str2bool(v): """ Converts a string to boolean Args: v (str) : string to be percieved as true or false Returns: (bool) : True or false based on string """ return v.lower() in ("yes", "True", "true", "t", "1")
bigcode/self-oss-instruct-sc2-concepts
def hamming_distance(input_bytes_1: bytes, input_bytes_2: bytes): """Takes in two byte strings. Outputs the hamming distance (https://www.tutorialspoint.com/what-is-hamming-distance) between those strings""" xor_result = ((a ^ b) for (a, b) in zip(input_bytes_1, input_bytes_2)) joined_binary_string = "".join([bin(nu...
bigcode/self-oss-instruct-sc2-concepts
def string_date_range(hr_data): """ Using the list of tuples from the `parse_heart_json` method, determines the date range of data present. Two outputs are possible: 1) Data for only one day: Will return the one day in month-day-year format: i.e. Dec16-2019 2) Data spanning multiple days: Will retu...
bigcode/self-oss-instruct-sc2-concepts
def line_to_coords(linestring): """ Converts (Multi)LineString to 2d-array of Point coordinates Parameters ---------- line : (Multi)LineString Returns ------- coords : list List of points representing the endpoints of the (Multi)LineStrings """ allowed_types = [ ...
bigcode/self-oss-instruct-sc2-concepts
def draw_line(x, y, x2, y2, stroke_width=0.5, color='black', stroke_dasharray='None'): """Draw a line for svg""" return f'<line x1="{x}" y1="{y}" x2="{x2}" y2="{y2}" stroke="{color}" \ stroke-width="{stroke_width}" stroke-dasharray="{stroke_dasharray}" />'
bigcode/self-oss-instruct-sc2-concepts
import torch def mean_jaccard_index(target, predictions): """ Semantic segmentation metric. Calculates mean intersection over union over all classes. Works for batches of data. """ intersection = torch.logical_and(target, predictions) union = torch.logical_or(target, predictions) interse...
bigcode/self-oss-instruct-sc2-concepts
def _bonds(mol, node_idx, use_order=True): """ Returns how many explicit bonds the specified node has. If use_order is False, treat all bonds as if they are order 1. Parameters ---------- mol : nx.Graph The molecule. node_idx : hashable The node to look at. Should be in mol. ...
bigcode/self-oss-instruct-sc2-concepts
import re def getCleanSpaces(inputText, minimumLength=0, lineCutTrigger="", keepSpaceSepators=False): """ Removes spaces and comments from the input expression. `minimumLength` of a line to not be ignored `lineCutTrigger` all lines after a line starting with this string will be ignored ...
bigcode/self-oss-instruct-sc2-concepts
def get_mean_param(params): """Return the parameter used to show reconstructions or generations. For example, the mean for Normal, or probs for Bernoulli. For Bernoulli, skip first parameter, as that's (scalar) temperature """ if params[0].dim() == 0: return params[1] elif len(params) ==...
bigcode/self-oss-instruct-sc2-concepts
def longest_common_subsequence(x: str, y: str): """ Finds the longest common subsequence between two strings. Also returns the The subsequence found Parameters ---------- x: str, one of the strings y: str, the other string Returns ------- L[m][n]: int, the length of the longes...
bigcode/self-oss-instruct-sc2-concepts
def multimax(k, key=None): """Returns an in-place list of the max values in the k. Args: k(lazy iteration, generator or list): contains the list of items key: a key by which to sort the items Returns: A list of the max values in the input. """ p = list(k)[:] if not p: r...
bigcode/self-oss-instruct-sc2-concepts
import json def get_json_bytes_for_sign_data(sign_data): """ Convert SignData object to JSON bytes for signing. Args: sign_data (SignData): The sign data object. Returns: bytes: The sign data in JSON bytes. """ return json.dumps(sign_data._asdict(), sor...
bigcode/self-oss-instruct-sc2-concepts
import torch def _to_complex(x: torch.Tensor) -> torch.Tensor: """View real tensor as complex.""" return torch.view_as_complex(x.view(*x.shape[:-1], -1, 2))
bigcode/self-oss-instruct-sc2-concepts
def calc_row_checksum(row_data): """ Method for calculating the checksum for a row. """ min_val = 0 max_val = 0 first = True for cell in row_data.split("\t"): if first: min_val = int(cell) max_val = int(cell) first = False else: ...
bigcode/self-oss-instruct-sc2-concepts
import re def binder_spec_from_github_url(github_url): """ Converts GitHub origin into a Binder spec. For example: git@github.com:SamLau95/nbinteract.git -> SamLau95/nbinteract/master https://github.com/Calebs97/riemann_book -> Calebs97/riemann_book/master """ if github_url.endswith('.git...
bigcode/self-oss-instruct-sc2-concepts
import torch def aggregate_accuracy(test_logits_sample, test_labels): """ Compute classification accuracy. """ return torch.mean(torch.eq(test_labels, torch.argmax(test_logits_sample, dim=-1)).float())
bigcode/self-oss-instruct-sc2-concepts
def _float(text): """Return text as a float (PRIVATE).""" if text is not None: try: return float(text) except Exception: return None
bigcode/self-oss-instruct-sc2-concepts
import glob import logging def get_all_waves(directory: str) -> list: """ Return all wave files (recursively) from the provided directory in sorted order :param directory: path to the directory :return: list of files (possibly empty) """ files = glob.glob(directory + '/**/*.wav') if not fi...
bigcode/self-oss-instruct-sc2-concepts
import math def _isnum(val) -> bool: """Returns true when the given value is a number.""" if isinstance(val, (float, int)): return not math.isnan(val) return False
bigcode/self-oss-instruct-sc2-concepts
def year_month_period(start_year, start_month, end_year, end_month): """ Generate all year,month tuple between given time period :param start_year: int, start from this year :param start_month: int, start from this month :param end_year: int, end to this year(inclusive) :param end_month: int, en...
bigcode/self-oss-instruct-sc2-concepts
def clean_whitespaces(text): """ Remove double whitespaces and trailing "." and "," from text. """ return ' '.join(text.strip().rstrip(".,").split())
bigcode/self-oss-instruct-sc2-concepts
from typing import List import random def ga_crossover(parents: List[List[str]], num_pop: int) -> List[List[str]]: """Create the next generation from parents A random index is chosen and genes up to that index from the first chromosome is used and genes from the index to the end is us...
bigcode/self-oss-instruct-sc2-concepts
import time def timestampToSeconds(timestamp): """ Given a timestamp in the form '2021-08-17:21:41:18', return the number of seconds since epoch. Returns 0 on invalid input. """ fmt = '%Y-%m-%d:%H:%M:%S' try: time_struct = time.strptime(timestamp, fmt) except ValueError: return 0 return int(...
bigcode/self-oss-instruct-sc2-concepts
def calculate_issn_checkdigit(s): """ Given a string of length 7, return the ISSN check digit. """ if len(s) != 7: raise ValueError('seven digits required') ss = sum([int(digit) * f for digit, f in zip(s, range(8, 1, -1))]) _, mod = divmod(ss, 11) checkdigit = 0 if mod == 0 else 11 -...
bigcode/self-oss-instruct-sc2-concepts
import copy def pop(x, k): """Returns copy of dict `x` without key `k`.""" x = copy.copy(x) del x[k] return x
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import Tuple def intersectionAndUnionGPU( output: torch.Tensor, target: torch.Tensor, K: int, ignore_index: int=255, cuda_available: bool=True ) -> Tuple[torch.Tensor,torch.Tensor,torch.Tensor]: """ Note output and target sizes are N or N * L or N * H * W ...
bigcode/self-oss-instruct-sc2-concepts
def create_switch_to_profile_payload(context: str, device: str, profile: str): """Create and return "switchToProfile" dictionary to send to the Plugin Manager. Args: context (str): An opaque value identifying the instance's action you want to modify. device (str): Unique device identifier. ...
bigcode/self-oss-instruct-sc2-concepts
import base64 import quopri def decode_payload(encoding, payload): """Decode the payload according to the given encoding Supported encodings: base64, quoted-printable. :param encoding: the encoding's name :param payload: the value to decode :return: a string """ encoding = encoding.lower...
bigcode/self-oss-instruct-sc2-concepts
def reverse_int(i): """ Given an integer, return an integer that is the reverse ordering of numbers. reverse_int(15) == 51 reverse_int(981) == 189 reverse_int(500) == 5 reverse_int(-15) == -51 reverse_int(-90) == -9 """ negative = i < 0 tmp = abs(i) tmp_str = str(tmp)[::-...
bigcode/self-oss-instruct-sc2-concepts
def delattr_call(obj, attr_name, *args, **vargs): """ Call the deleter for the attribute `attr_name` of `obj`. If the attribute is a property, pass ``*args`` and ``**kwargs`` to the deleter (`fdel`); otherwise, ignore them. """ try: return getattr(type(obj),attr_name).fdel(obj,*args,**vargs...
bigcode/self-oss-instruct-sc2-concepts
def get_smaller_and_greater(a, b): """compare two elements then return smaller and greater""" if a < b: return a, b return b, a
bigcode/self-oss-instruct-sc2-concepts
def det(tensor): """Detach a torch Tensor to a cpu numpy version Args: tensor (torch.Tensor): A tensor to be detached and turned into an ndarray Returns: (ndarray): The same data as an ndarray """ return tensor.cpu().detach().numpy()
bigcode/self-oss-instruct-sc2-concepts
def sext_8(value): """Sign-extended 8 bit number. """ if value & 0x80: return 0xffffff00 | value return value
bigcode/self-oss-instruct-sc2-concepts
def b2mb(num): """ convert Bs to MBs and round down """ return int(num/2**20)
bigcode/self-oss-instruct-sc2-concepts
def lower(value): """ Functor to return a lower-case string. """ return value.lower()
bigcode/self-oss-instruct-sc2-concepts
import torch def sample_z(batch_size, dim_z, device, distribution=None): """Sample random noises. Args: batch_size (int) dim_z (int) device (torch.device) distribution (str, optional): default is normal Returns: torch.FloatTensor or torch.cuda.FloatTensor """...
bigcode/self-oss-instruct-sc2-concepts
def is_short_term(date1,date2): """ Return True if it's a short term gain for buying at date1 and selling at date2 """ date1Months = date1.year*12+date1.month date2Months = date2.year*12+date2.month if date2Months - date1Months > 12: return False elif date2Months - date1Months == 12 ...
bigcode/self-oss-instruct-sc2-concepts
def get_pxe_address_x64(virtual_address, pte_base): """ The functions gives the PTE address for a virtual address Based on: https://www.coresecurity.com/system/files/publications/2016/05/Windows%20SMEP%20bypass%20U%3DS.pdf @param virtual_address: the virtual address to convert @param pte_base: the base address for...
bigcode/self-oss-instruct-sc2-concepts
def normalize_list(items, width, filler = None): #=============================================================================== """ Normalize list to a specified width, truncating or filling as needed. Filler data can be supplied by caller. The filler will be copied to each added item. None will be us...
bigcode/self-oss-instruct-sc2-concepts
def draw_sure(deck, n, exclusions): """Draw n cards from a deck but skip any cards listed in exclusions. Please note this func always returns a list, unlike native deuces draw function. """ drawn = [] while len(drawn) < n: c = deck.draw() if c in exclusions + drawn: c...
bigcode/self-oss-instruct-sc2-concepts
def getEntireFamilyTree(cls): """Returns a list of classes subclassing the input class One large caveat is it can only locate subclasses that had been imported somewhere Look to use importEntirePackage before searching for subclasses if not all children are being found as expected. """ return ...
bigcode/self-oss-instruct-sc2-concepts
def _supports_fileno(stream): """ Returns True if 'stream' supports the file descriptor and allows fileno(). """ if hasattr(stream, 'fileno'): try: stream.fileno() return True except IOError: return False else: return False
bigcode/self-oss-instruct-sc2-concepts
def base_count(seq): """ Count the number of A, C, G, T in a given sequence """ return seq.count('A'), seq.count('C'), seq.count('G'), seq.count('T')
bigcode/self-oss-instruct-sc2-concepts
import torch def get_r1_src_target(k_in=2, k_out=1): """ Returns the r1 experiment src and targets tensors """ # torch.set_default_dtype(torch.float64) # works best in float64 points_tens = torch.tensor( [[-k_in, 0, 0], [k_in, 0, 0]]).unsqueeze(0).float() target_points_tens = ( ...
bigcode/self-oss-instruct-sc2-concepts
import collections def duplicates(arr): """ Returns a list of Axis objects which have duplicate names in arr Arguments: arr: The iterable of Axis objects to check for duplicates in. Returns: list of Axis: duplicate Axis found in arr """ # group axes by name axes_by_name =...
bigcode/self-oss-instruct-sc2-concepts
def find_zone(domain, zones): """ Does the domain exist in a tracked zone? """ if domain is None: return "" for zone in zones: if domain.endswith("." + zone) or domain == zone: return zone return ""
bigcode/self-oss-instruct-sc2-concepts
def config(ctx): """show current cli configuration""" return """Base url: %(base_url)s username: %(username)s""" % { 'base_url': ctx.obj.connection.api_url, 'username': ctx.obj.connection.credentials.username }
bigcode/self-oss-instruct-sc2-concepts
def min_max_comparison(value, value_to_compare, condition): """ Translate the values and condition to comparison operator and get result. :param value: (numeric) original value :param value_to_compare: (numeric) value to compare with, the value to beat. :param condition: (str) min/max condition. If ...
bigcode/self-oss-instruct-sc2-concepts
def check_preconditions(key, value): """ Check if the filter applies to the current element in the syntax tree. :param key: The type of pandoc object. :type key: str :param value: The contents of the object. :type value: list | str :return: ``True`` if the filter applices to the current ele...
bigcode/self-oss-instruct-sc2-concepts
def as_dict(keys, values): """Take two iterables, one with keys and other with values and return a dict """ try: _ = iter(keys) except TypeError: return {keys: values} return dict(zip(keys, values))
bigcode/self-oss-instruct-sc2-concepts
def divide(a: int, b: int = 1) -> int: """Simple division function for testing run_hook Args: a (int): Dividend b (int, optional): Divisor. Defaults to 1. Returns: int: Quotient """ return int(a/b)
bigcode/self-oss-instruct-sc2-concepts
def parse_repeat(n, msg) -> tuple: """ Parse the argument for the repeat command. :param n: the number of times of repeat. :param msg: the message to be repeated. :return: (number of times of repeat, message to be repeated) :raises ValueError: if n is not an integre between 1 and 5, or m...
bigcode/self-oss-instruct-sc2-concepts
def delete_list_of_keys( d, *keys ): """ elimina las keys de un dicionario Parameters ========== d: dict dicionario del que se eliminaran las keys keys: tuple llaves a eliminar Examples ======== >>>origin = { 'a': 'a', 'b': 'b': 'c': 'c' } >>>delete_list_of_keys...
bigcode/self-oss-instruct-sc2-concepts
def zero_cross(data, zero=0): """ Calculate the number of times the data crosses the `zero` value. Parameters ---------- data : ndarray Time series of data values. zero : scalar, default=0 Crossing point to analyze. Returns ------- cross : float Number of times the data crosses `zero`. """ return (...
bigcode/self-oss-instruct-sc2-concepts
def remove_by_min_overlapping_users(keen_keen_graph, min_overlapping_user): """It only keeps the edges whose weight >= min_overlapping_user""" filtered = {} for ka, ints in keen_keen_graph.items(): new_ints = {kb: n_users for kb, n_users in ints.items() if n_users >= min_overlapping_user} if...
bigcode/self-oss-instruct-sc2-concepts
def _format_as_index(indices): """ Construct a single string containing indexing operations for the indices. For example, [1, 2, "foo"] -> [1][2]["foo"] :type indices: sequence """ if not indices: return "" return "[%s]" % "][".join(repr(index) for index in indices)
bigcode/self-oss-instruct-sc2-concepts
def get_dfg_graph(dset): """ return the dfg graph for a dataset """ # helpesk dfg graph graphs = {} graph = {} graph[0] = {1:3644, 3:108, 0:1} #end of process instance 1, start of instance 2 graph[3] = {1:105} graph[1] = {8:3483,1:394} graph[8] = {2:42, 9:851, 6:4150,4:9, 7:4} #...
bigcode/self-oss-instruct-sc2-concepts
def _ical_escape(text): """ Format value according to iCalendar TEXT escaping rules. from https://github.com/collective/icalendar/blob/4.0.2/src/icalendar/parser.py#L20 """ return ( text.replace(r'\N', '\n') .replace('\\', '\\\\') .replace(';', r'\;') .replace(',', r'...
bigcode/self-oss-instruct-sc2-concepts
def at_left_obstacle(Rover, safe_pixs=50): """ Check if obstacle is to the left of rover. Keyword arguments: safe_pixs -- minimum number of pixels to keep from left obstacles """ nav_pixs_left = len(Rover.nav_angles_left) return nav_pixs_left < safe_pixs
bigcode/self-oss-instruct-sc2-concepts
def get_llvm_type(context, type): """Returns the LLVM Value corresponsing to a Numba type. Args: context: The LLVM context or the execution state of the current IR generator. type: A Numba type object. Returns: An Python object wrapping an LLVM Value corresponding to the ...
bigcode/self-oss-instruct-sc2-concepts
def diagpq(p,q=0): """ Return string equivalent metric tensor for signature (p,q). """ n = p+q D = '' rn = list(range(n)) for i in rn: for j in rn: if i ==j: if i < p: D += '1 ' else: D += '-1 ' ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from pathlib import Path def find_base_index_path(alignment_index: Union[Path, str]) -> Path: """ When BWA indexes a reference genome, it produces five files: reference.fasta -> [ reference.fasta.amb reference.fasta.ann reference.fasta.bwt referen...
bigcode/self-oss-instruct-sc2-concepts
def _decode_text(text: list[int]) -> str: """ Converts the text from numerical values to literal values. Uses the inverse table conversion of that used in _encode_text. Args: text (list[int]): List with each position representing a character to be decoded. Returns: str:...
bigcode/self-oss-instruct-sc2-concepts
def is_key_value_exist(list_of_dict, key, value): """ Check if at least one value of a key is equal to the specified value. """ for d in list_of_dict: if d[key] == value: return True return False
bigcode/self-oss-instruct-sc2-concepts
def _create_ip_range(range_start, range_end): """ Given a start ip, eg 192.168.1.1, and an end ip, eg 192.168.1.254, generate a list of all of the ips within that range, including the start and end ips. """ ip_range = [] start = int(range_start[range_start.rfind('.')+1:]) end = int(range...
bigcode/self-oss-instruct-sc2-concepts
def get_backend(group): """Return the backend of given process group. Parameters ---------- group : ProcessGroup The process group to query backend. Returns ------- str The backend spec. """ return group.backend
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def create_mesa_dir_name(comb: Dict[str, Any]) -> str: """ Creates a MESA run dir name to use for the given combination of MESA parameter values. These prefixes should be unique for each MESA run. This also needs to be deterministic, reguardless of the f...
bigcode/self-oss-instruct-sc2-concepts
def json_as_python_set(dct): """Decode json {'_set_object': [1,2,3]} to set([1,2,3]) Example ------- decoded = json.loads(encoded, object_hook=json_as_python_set) Also see :class:`JSONSetEncoder` """ if '_set_object' in dct: return set(dct['_set_object']) return dct
bigcode/self-oss-instruct-sc2-concepts
def reverse_list_strings(lines): """ Reverse a list of strings: - First, reverse entries of the list. - Second, reverse each entry of the reversed list. """ return [line[::-1] for line in lines[::-1]]
bigcode/self-oss-instruct-sc2-concepts
import zipfile def _format_toc(filename): """Return a table of contents for the zip file as a string. Args: filename (str): Path to zip file Returns: directory listed in format matching zipfile.printdir() """ zf = zipfile.ZipFile(filename) lines = [] lines.append("%-46s %19s %12s...
bigcode/self-oss-instruct-sc2-concepts
import requests def validate_api(api): """ Validates the API key by sending a single request to Climacell API :param api: 32-char API ket :return: True if api is valid """ endpoint = "https://api.climacell.co/v3/weather/realtime" # Build sample params params = {'lat': '0', 'lon': '...
bigcode/self-oss-instruct-sc2-concepts
def prplus(number): """Prefix with "+" for positive values""" return '+' if number >= 0 else ''
bigcode/self-oss-instruct-sc2-concepts
def format_percent(d, t): """ Format a value as a percent of a total. """ return '{:.1%}'.format(float(d) / t)
bigcode/self-oss-instruct-sc2-concepts
def smart_zip(keys, values): """For handling the case where keys and values may be scalars""" if isinstance(values, float): return zip(keys, [values]) else: return zip(keys, values)
bigcode/self-oss-instruct-sc2-concepts
def format_frame(frame): """ Return a nice representation of frame.f_locals :param frame: frame object :returns: string representation """ buf = "" for key, value in frame.f_locals.items(): buf += "\t%s -> %s\n" % (key, value) return buf
bigcode/self-oss-instruct-sc2-concepts
def tmp_file(tmpdir): """Provide a temporary file in pytest-defined tmp dir Returns: A path to the tmp file """ return tmpdir.join('tmp_data.json').strpath
bigcode/self-oss-instruct-sc2-concepts
import secrets def arbitrary_string() -> str: """ :return: an arbitrary, URL-safe string. """ return secrets.token_urlsafe()
bigcode/self-oss-instruct-sc2-concepts
def simulate(dynamics,x0,ufunc,T=1,dt=1e-3): """Returns a simulation trace of dynamics using Euler integration over duration T and time step dt. Args: dynamics (Dynamics): the system. x0 (np.ndarray): the initial state. ufunc (callable): a policy u(t,x) returning a control vect...
bigcode/self-oss-instruct-sc2-concepts
def dup_scores(scores, num_winners): """Expand a list of scores by a factor of num_winners, yielding one per candidate >>> dup_scores([0, 5], 3) [0, 0, 0, 5, 5, 5] """ return [s for s in scores for n in range(num_winners)]
bigcode/self-oss-instruct-sc2-concepts
def dut_artifacts_dir(request): """Fixture for --dut-artifacts-dir.""" return request.config.getoption("--dut-artifacts-dir")
bigcode/self-oss-instruct-sc2-concepts
import base64 def generate_api_key(username, password): """ Generates a Base64-encoded api key, based on the WEkEO user credentials username:password. Parameters: username: WEkEO username password: WEkEO password Returns: Returns a string of the Base64-encoded a...
bigcode/self-oss-instruct-sc2-concepts
def lane_lines_directixes(lane_info): """ Computes the parabola directrix for both curves. """ def directrix(coefficients): a, b, c = coefficients return (b ** 2 - 4 * a * c + 1) / 4 * a return directrix(lane_info.left_fit), directrix(lane_info.right_fit)
bigcode/self-oss-instruct-sc2-concepts
def cross_list(sequences): """ Code taken from the Python cookbook v.2 (19.9 - Looping through the cross-product of multiple iterators) This is used to create all the variations associated with an product """ result =[[]] for seq in sequences: result = [sublist+[item] for sublist in resu...
bigcode/self-oss-instruct-sc2-concepts
def _l2_regularization(l2, model): """Computes the L2 regularization for the given model Args: l2 (float): L2 parameter model (:obj:`torch.nn.Module`): Model to use Returns: float: L2 loss (i.e. (l2 * l2_norm(params)) / 2) """ l2_loss = sum(param.norm(2) ** 2 for param in m...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def parse_path(input: str) -> Path: """Parse a string path from the config file. Args: input (str): Input list Returns: Path: Path """ return Path(input).expanduser()
bigcode/self-oss-instruct-sc2-concepts
import functools def preduce(func): """shorthand for functools.partial(functools.reduce, func), for use with pipelines. """ return functools.partial(functools.reduce, func)
bigcode/self-oss-instruct-sc2-concepts
import torch def alpha2rot_y(alpha, x, cx, fx): """ Get rotation_y by alpha + theta - 180 alpha : Observation angle of object, ranging [-pi..pi] x : Object center x to the camera center (x-W/2), in pixels rotation_y : Rotation ry around Y-axis in camera coordinates [-pi..pi] """ rot_y = al...
bigcode/self-oss-instruct-sc2-concepts
import re def filter_results(results, args): """Filters results for any the user didn't want processed. Arguments: results: list of dicts, with each dict containing status for a service. args: argparse.ArgumentParser, options passed to script. Returns: list: with any matc...
bigcode/self-oss-instruct-sc2-concepts
def preprocess(data): """ Function used to preprocess the input and output for the model. The input gets the special [SEP] token and the output gets a space added. """ return { "input": data['premise'] + '</s>' + data['hypothesis'], "output": str(data['label']) + ' ' + data['explanat...
bigcode/self-oss-instruct-sc2-concepts
def basic_obj_get(obj): """Return the value of attribute "value" of "obj".""" return obj.value
bigcode/self-oss-instruct-sc2-concepts