seed
string
source
string
import torch def compute_returns(rewards, masks, discount, returns4traj=True): """ Using rewards to compute returns. :param rewards: rewards agent obtains per step. Size: batch_size x 1 :param masks: indicate the final step of each trajectory. 0 for last step and 1 for others. Size: batch_size x 1 ...
bigcode/self-oss-instruct-sc2-concepts
def min_coins(coins, total): """ Computes the minimum number of coins which sum up to total. Params: coins: list of non-negative integers representing the values of the coins. total: int, in fact it has to be a non-negative integer. Returns tuple: (min_num_coins, picked_coins) ...
bigcode/self-oss-instruct-sc2-concepts
def offset(coordinates, offset_scales): """Apply offsets to box coordinates # Arguments coordinates: List of floats containing coordinates in point form. offset_scales: List of floats having x and y scales respectively. # Returns coordinates: List of floats containing coordinates i...
bigcode/self-oss-instruct-sc2-concepts
def getNumberOfMatches(segment): """ Get numnber of matches from alignment Do not consider insertion/deletion as mismatches """ parsed_MD = segment.get_aligned_pairs(with_seq=True) return len([ base for (read_pos, ref_pos, base) in parsed_MD if ((base is not None and base.isuppe...
bigcode/self-oss-instruct-sc2-concepts
def _cli_options(parameters): """Return command line options for parameters passed as AiiDA ArrayData """ arrayname = parameters.get_arraynames()[0] dVarray = parameters.get_array(arrayname) # array of volume change in %: -6, -2, ... ndV = 0 # number of non-zero volume changes options = '' ...
bigcode/self-oss-instruct-sc2-concepts
def get_action_by_name(client, cluster, name): """ Get action by name from some object Args: client: ADCM client API objects cluster: cluster object name: action name Returns: (action object): Action object by name Raises: :py:class:`ValueError` ...
bigcode/self-oss-instruct-sc2-concepts
def remove_title(text): """ Removes the title of a document :param text: text containing an article output from cleanhtml() :return: text of the article without title """ index = text.find("\n\n") if index != -1: return text[index+2:] else: return text
bigcode/self-oss-instruct-sc2-concepts
def _s(strs): """ Convert a byte array to string using UTF8 encoding. """ if strs is None: return None assert isinstance(strs, bytes) return strs.decode('utf8')
bigcode/self-oss-instruct-sc2-concepts
def format_traits(code, value): """Format traits as list of names. """ result = [] for trait in code: if value & code[trait]: result.append(trait) result.sort() return ','.join(result)
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def int_from_str(arg: Any) -> int: """Take in an argument and try to return its int equivalent. Args: arg (Any): This can be any type. However, in general use it should be either an int or str. Returns: int: The int equivalent of the passed in argument. I...
bigcode/self-oss-instruct-sc2-concepts
def parse_to( buffer, keyword ): """Continues through the buffer until a line with a first token that matches the specified keyword. """ while True: line = buffer.next() if line == '': return None values = line.split( None ) if values[ 0 ] == keyword: ...
bigcode/self-oss-instruct-sc2-concepts
def returnPreds(preds, threshold): """ Return predicted binary values from prediction probabilities based on a given threshold Inputs: - preds: prediction probabilities - threshold: threshold for positive prediction value Output: - predicted_labels list of binary predicted labe...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def hashtext(stringText): """Return a string with first 16 numeric chars from hashing a given string """ #hashlib md5 returns same hash for given string each time return hashlib.md5(str(stringText).encode('utf-8')).hexdigest()[:16]
bigcode/self-oss-instruct-sc2-concepts
def get_equipment_slot_string(equipment_item) -> str: """ This function is called specifically for the print_character_equipment function in information_printer.py Returns the string representation of an Equipment object or returns empty if there is no such item. """ if equipment_item: retur...
bigcode/self-oss-instruct-sc2-concepts
from time import strftime,localtime def datestring(seconds): """Format time in seconds since 1 Jan 1970 00:00 UST as local time string in the format '1-Jan-70 00:00:00'""" return strftime("%d-%b-%y %H:%M:%S",localtime(seconds))
bigcode/self-oss-instruct-sc2-concepts
def left_canonical_form_mps(orig_mps, chi=0, threshold=1e-14, normalise=False): """ Computes left canonical form of an MPS See also -------- Tensor.left_canonise() """ mps = orig_mps.copy() mps.left_canonise(chi=chi, threshold=threshold, normalise=normalise) ...
bigcode/self-oss-instruct-sc2-concepts
def as_dict(language_object): """ Get a dict representing a language """ # Previously we had a list of ISO_639_2b (bibliographic) languages in datasets.py represented e.g. # [u"wel", u"cym", u"cy", u"Welsh", u"gallois"] - now we have pycountry, so we favour the bibliographic name when # available. Frenc...
bigcode/self-oss-instruct-sc2-concepts
def has(name, o): """Returns whether or not an object has an own property with the specified name""" if hasattr(o, str(name)): return True try: o[name] return True except (TypeError, KeyError): return False
bigcode/self-oss-instruct-sc2-concepts
def all_equal(elements): """ :param elements: A collection of things :return: True if all things are equal, otherwise False. (Note that an empty list of elements returns true, just as all([]) is True """ element_iterator = iter(elements) try: first = next(element_iterator) # Will throw ...
bigcode/self-oss-instruct-sc2-concepts
def _get_physical_table(api, *, table_id: str) -> str: """ Returns the physical table name for a given GUID. """ r = api._metadata.detail(guid=table_id, type='LOGICAL_TABLE').json() return r['logicalTableContent']['physicalTableName']
bigcode/self-oss-instruct-sc2-concepts
def get_decipher_values(values, text_key): """ Converts a Decipher values collection into a Quantipy values collection. Parameters ---------- values : list The values object from a block of Decipher metadata Returns ------- values : list The Quantipy values object ...
bigcode/self-oss-instruct-sc2-concepts
def linear_search(lst, value): """ Searches for a specified value in a list. It performs linear search in an iterative way. @param lst: a list containing numbers @param value: value to search @return: True if value is found. Otherwise, False. """ for element in lst: if element ...
bigcode/self-oss-instruct-sc2-concepts
def harmonic_mean_reward_fn(env, top1, top5, vloss, total_macs): """This reward is based on the idea of weighted harmonic mean Balance compute and accuracy provided a beta value that weighs the two components. See: https://en.wikipedia.org/wiki/F1_score """ beta = 1 # beta = 0.75 # How much to...
bigcode/self-oss-instruct-sc2-concepts
import math def calculate_kl(p, q): """Calculate D_KL(P || Q) (the KL-divergence) in bits. D_KL(P || Q) is the `information gained when one revises one's beliefs from the prior probability distribution Q to the posterior probability distribution P`. (Wikipedia, Kullback–Leibler divergence) ...
bigcode/self-oss-instruct-sc2-concepts
import random import string def client_token_generator(challenge_pk): """ Returns a 32 characters long client token to ensure idempotency with create_service boto3 requests. Parameters: None Returns: str: string of size 32 composed of digits and letters """ remaining_chars = 32 - len(str...
bigcode/self-oss-instruct-sc2-concepts
def apply_units(v, units): """Apply unit to a dimensionless value. Return dimensional values unchanged. Args: v (numeric, unit): The value to which units will be applied. units (unit): Unit to apply to the value. Returns: unit: A value with a Pint unit applied to it. Example: ...
bigcode/self-oss-instruct-sc2-concepts
def mean_squared_error(a, initial=None): """Mean squared error (MSE). By default, assume the input array `a` is the residuals/deviations/error, so MSE is calculated from zero. Another reference point for calculating the error can be specified with `initial`. """ if initial is None: init...
bigcode/self-oss-instruct-sc2-concepts
def ListVersionTags(client, messages, package, version): """Lists tags associated with the given version.""" list_tags_req = messages.ArtifactregistryProjectsLocationsRepositoriesPackagesTagsListRequest( parent=package, filter="version=\"{}\"".format(version)) list_tags_res = client.projects_locations_repos...
bigcode/self-oss-instruct-sc2-concepts
import math import bisect def get_tile_coords_range(min_lat, min_long, max_lat, max_long, interval): """ Get the coordinates of the upper left corners of the list tiles containing the region. Args: min_lat: (float) The minimum latitude (farthest south). min_long: (float) The mini...
bigcode/self-oss-instruct-sc2-concepts
def get_file_target(content, output, dependencies=None): """ Get a target that creates a file Parameters ---------- content : str file content output : str copy destination during build dependencies : list of str, optional outputs of target's dependencies, by default...
bigcode/self-oss-instruct-sc2-concepts
def indent(text, prefix): """ Adds `prefix` to the beginning of non-empty lines in `text`. """ # Based on Python 3's textwrap.indent def prefixed_lines(): for line in text.splitlines(True): yield (prefix + line if line.strip() else line) return u"".join(prefixed_lines())
bigcode/self-oss-instruct-sc2-concepts
def _flatten_yocto_conf(conf): """ Flatten conf entries. While using YAML *entries syntax, we will get list of conf entries inside of other list. To overcome this, we need to move inner list 'up' """ # Problem is conf entries that it is list itself # But we can convert inner lists to tuples, wh...
bigcode/self-oss-instruct-sc2-concepts
def load_corrupted_test_info(dataset): """Loads information for CIFAR-10-C.""" if dataset == 'cifar10': corruption_types = [ 'gaussian_noise', 'shot_noise', 'impulse_noise', 'defocus_blur', 'frosted_glass_blur', 'motion_blur', 'zoom_blur', 'snow', ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from datetime import datetime from typing import Tuple def parse_date_range(date_range: str) -> Union[datetime, Tuple[datetime, datetime]]: """Parse either a date string or date tuple from a string. Args: date_range (str): This can either be a string with a single date or a t...
bigcode/self-oss-instruct-sc2-concepts
import itertools def flatten(iterable): """Concatenate several iterables.""" return itertools.chain.from_iterable(iterable)
bigcode/self-oss-instruct-sc2-concepts
def _has_annotation(var: str) -> bool: """Check if a variable has an annotation. 'self' and 'cls' can't have annotations. :param var: str String containing variable name, annotations, and default value :return: bool Returns whether or not the variable has an annotation """ if va...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple def _split_chunk_bounds( start: int, stop: int, multiple: int, ) -> List[Tuple[int, int]]: # pylint: disable=g-doc-args # pylint: disable=g-doc-return-or-yield """Calculate the size of divided chunks along a dimension. Example usage: >>> _split_chunk_...
bigcode/self-oss-instruct-sc2-concepts
def map_bound(value, in_low, in_high, out_low, out_high): """map with high and low bound handling.""" result = None if value <= in_low: result = out_low else: if value >= in_high: result = out_high else: # http://stackoverflow.com/a/5650012/574981 ...
bigcode/self-oss-instruct-sc2-concepts
def search_fid_mock(self, criterion_type, criteria_list): """ Mock of TemporalDataMgr.search_functional_identifiers method Same parameters and types as the original function """ return [{"tsuid": "00001", "funcId": "FuncId_0001"}, {"tsuid": "00002", "funcId": "FuncId_0002"}, ...
bigcode/self-oss-instruct-sc2-concepts
import inspect def build(klass, **kwargs): """Build instance of klass using matching kwargs""" known_param_names = list(inspect.signature(klass).parameters.keys()) known_params = {n: kwargs[n] for n in known_param_names if n in kwargs} return klass(**known_params)
bigcode/self-oss-instruct-sc2-concepts
def more_vowels(astring): """Solution to exercise C-4.18. Use recursion to write a Python function for determining if a string s has more vowels than consonants. """ string = astring.lower() vowels = 'aeiou' n = len(string) vowel_count = 0 def recurse(idx): nonlocal vowel_c...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def rgb_to_cmyk(r: int, g: int, b: int) -> Tuple[float, float, float, float]: """Convert RGB (Red Green Blue) to CMYK (Cyan Magenta Yellow Black). :param r: Red (0 to 255 inclusive). :param g: Green (0 to 255 inclusive). :param b: Blue (0 to 255 inclusive). :return: CMYK ...
bigcode/self-oss-instruct-sc2-concepts
def find_all(L, x): """Find indexes of all occurrences of *x* in list *L*, and return a list of them.""" out = [] prev = -1 while 1: try: prev = L.index(x,prev+1) out.append(prev) except: return out
bigcode/self-oss-instruct-sc2-concepts
def any_check(geom_test, gdf, how): """Improve speed for an 'any()' test on a list comprehension. Replace a statement like... .. code:: if any([geom_test.touches(g) for g in gdf.geometry]): ... with the following: .. code:: if any_check(geom_test, gdf, how='touches'): Inst...
bigcode/self-oss-instruct-sc2-concepts
def drop_duplicates_sorted(df, subset=None, sep='', inplace=True): """ Drop duplicate rows based on unique combination of values from given columns. Combinations will be sorted on row axis before dropping duplicates. Params ------ df : pandas DataFrame subset : list of str Subs...
bigcode/self-oss-instruct-sc2-concepts
def is_valid_energy(ext): """ Checks if energy format is compatible with GROMACS """ formats = ['edr'] return ext in formats
bigcode/self-oss-instruct-sc2-concepts
def trim_the_firsts_e(L, e): """Return the list L without the first sequence of element(s) e. Eg. trim_the_firsts_e([0, 0, 1, 0, 1, 0]) -> [1, 0, 1, 0] :param L: the list to trim :param e: the element to remove :type L: list(int) :type e: int :return: the list L without the first(s) e(s) ...
bigcode/self-oss-instruct-sc2-concepts
def combine_dict_in_list(d1_, d2_): """ Merges two dictionaries, non-destructively, combining values on duplicate keys in a list >>> d1 = {'a': 'test', 'b': 'btest', 'd': 'dreg'} >>> d2 = {'a': ['cool', 'test'], 'b': 'main', 'c': 'clear'} >>> combine_dict_in_list(d1,d2) {'c': ['clear'], 'a': ['...
bigcode/self-oss-instruct-sc2-concepts
def part2(allergens): """Part 2 wants the list of unsafe ingredients, sorted by their allergen alphabetically, joined together into one string by commas. """ return ",".join( ingredient for (allergen, ingredient) in sorted(allergens.items()) )
bigcode/self-oss-instruct-sc2-concepts
from typing import List from functools import reduce def mult_list(list_: List[int], modulus: int = 0) -> int: """ Utility function to multiply a list of numbers in a modular group :param list_: list of elements :param modulus: modulus to be applied, use 0 for no modulus :return: product of the e...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def get_j2k_parameters(codestream: bytes) -> Dict[str, object]: """Return a dict containing JPEG 2000 component parameters. .. versionadded:: 2.1 Parameters ---------- codestream : bytes The JPEG 2000 (ISO/IEC 15444-1) codestream to be parsed. Returns ---...
bigcode/self-oss-instruct-sc2-concepts
def _is_trivial_description(col_name, col_description): # type: (str, str) -> bool """ Heuristics to determine if the column has a trivial description (which we do not document). """ return col_description == col_name or \ col_description == "Property " + col_name or \ col_...
bigcode/self-oss-instruct-sc2-concepts
def _original_var_name(var_name): """ Return the original variable name. """ if var_name.endswith('.quantized.dequantized'): return var_name[:-len('.quantized.dequantized')] if var_name.endswith('.quantized'): return var_name[:-len('.quantized')] if var_name.endswith('.dequantize...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_input_paths(global_conf, local_conf): """Returns a 2-tuple: - Markdown Path or None - Input-file Paths or empty list """ del global_conf # Unused relative_markdown_path = None # Markdown is optional input_files = [] # Input file could be empty if "m...
bigcode/self-oss-instruct-sc2-concepts
import torch def compute_kld(mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor: """ Compute the expected/averaged kl-divergence from a batch of mu's and logvar's for a fully-factorized Gaussian distribution. Assume dim0 is the batch dimension, and all the rest are data dimension. .. note::...
bigcode/self-oss-instruct-sc2-concepts
def check_complete(board): """Checks the board. If all matches have been found, returns True.""" for card in board: if not card["cleared"]: return False return True
bigcode/self-oss-instruct-sc2-concepts
def elide_text(text: str, max_length: int) -> str: """Shorten a string to a max length and end it with an ellipsis.""" return text if len(text) < max_length else f"{text[:max_length]}..."
bigcode/self-oss-instruct-sc2-concepts
import json def get_workout_data_from_file(fNamePath): """ Parses passed files and loads that json data to a Dictionary. Returns the Dictionary storing the json data. """ data = '' with open(fNamePath) as data_file: data = json.load(data_file) return data
bigcode/self-oss-instruct-sc2-concepts
import json def load_json_schema(schema_file_name): """Load json schema from JSON file.""" with open(schema_file_name) as schema_file: return json.loads(schema_file.read())
bigcode/self-oss-instruct-sc2-concepts
def chen_celikovsky(XYZ, t, a=36, b=3, d=20): """ The Chen-Celikovsky Attractor. x0 = (0.1,0.1,0.1) """ x, y, z = XYZ x_dt = a * (y - x) y_dt = -x * z + d * y z_dt = x * y - b * z return x_dt, y_dt, z_dt
bigcode/self-oss-instruct-sc2-concepts
def capitalize_first(string): """Returns string with its first character capitalized (if any)""" return string[:1].capitalize() + string[1:]
bigcode/self-oss-instruct-sc2-concepts
def evaluate_old_grounding(grounding): """Return status of old grounding.""" if not grounding['db_refs']: return 'ungrounded' elif not grounding['correct']: return 'incorrect' else: return 'correct'
bigcode/self-oss-instruct-sc2-concepts
def rotate(string, n): """Rotate characters in a string. Expects string and n (int) for number of characters to move. """ return string[n:] + string[:n]
bigcode/self-oss-instruct-sc2-concepts
import logging def append_to_file(file_path: str, file_text: str) -> bool: """ Purpose: Append text to a file Args/Requests: file_path: file path file_text: Text of file Return: Status: True if appended, False if failed """ try: with open(file_path, "...
bigcode/self-oss-instruct-sc2-concepts
import re def explode(bus_str): """ Explode a bus into its separate lines. This function takes a bus expression like "ADDR[0:3]" and returns "ADDR0,ADDR1,ADDR2,ADDR3". It also works if the order is reversed, e.g. "ADDR[3:0]" returns "ADDR3,ADDR2,ADDR1,ADDR0". If the input string is not a vali...
bigcode/self-oss-instruct-sc2-concepts
def unique(mylist): """Finds unique elements of list""" return list(set(mylist))
bigcode/self-oss-instruct-sc2-concepts
def percent(val, val_max): """ Percentage calc :param val: value :param val_max: max value :return: ratio in percentage """ return float(val * 100) / val_max
bigcode/self-oss-instruct-sc2-concepts
from typing import Collection def mean(iterable: Collection[float]) -> float: """ Returns the average value of an iterable """ return sum(iterable) / len(iterable)
bigcode/self-oss-instruct-sc2-concepts
import re def contains_chinese(text): """Returns whether the given text contains any chinese characters.""" return re.search(u'[\u4e00-\u9fff]', text)
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Any def get_attr_path(data: dict, path: List[str]) -> Any: """ Used to get a value in a dict based on a path. Args: data (dict): A dict of data to be searched. path (list): An ordered list of string attrs to be used for searching through the obje...
bigcode/self-oss-instruct-sc2-concepts
def s2b(s): """ Converts a string to boolean value """ s = s.lower() return s == 'true' or s == 'yes' or s == 'y' or s == '1'
bigcode/self-oss-instruct-sc2-concepts
def parse_td(row_html): """ Return the td elements from a row element. Parameters ---------- obj : node-like A DOM <tr> node. Returns ------- list of node-like These are the elements of each row, i.e., the columns. """ return row_html.find_all(("td", "th"), recurs...
bigcode/self-oss-instruct-sc2-concepts
def configure_approle(client, name, cidr, policies): """Create/update a role within vault associating the supplied policies :param client: Vault client :ptype client: hvac.Client :param name: Name of role :ptype name: str :param cidr: Network address of remote unit :ptype cidr: str :par...
bigcode/self-oss-instruct-sc2-concepts
def _get_update_fields(queryset, to_update, exclude=None): """ Get the fields to be updated in an upsert. Always exclude auto_now_add, auto_created fields, and unique fields in an update """ exclude = exclude or [] model = queryset.model fields = { **{field.attname: field for fi...
bigcode/self-oss-instruct-sc2-concepts
def Metadata2dict(md): """ Converts a Metadata object to a Python dict. This is the inverse of dict2Metadata. It converts a Metadata object to a Python dict. Note that Metadata behavies like dict, so this conversion is usually not necessay. :param md: Metadata object to convert. :type md:...
bigcode/self-oss-instruct-sc2-concepts
def split_text(lines): """Split a text devided by newline into chunks of about 4000 characters.""" chunks = [] current_chunk = [] chars = 0 for line in lines: # Append the length of the line + a newline chars += len(line) + 1 if chars < 4000: current_chunk.append...
bigcode/self-oss-instruct-sc2-concepts
def sellmeier(lmbda, B1, B2, B3, C1, C2, C3): """ Estimate refractive index of glass with wavelength. Using the Sellmeier equation. Input: lmbda: the Wavelength B(1-3) : B coefficients of glass C(1-3) : C coefficients of glass Returns: n : Fitted refractive index """ n_squ...
bigcode/self-oss-instruct-sc2-concepts
def discrete_binary_search(func, lo, hi): """ Locate the first value x s.t. func(x) = True within [lo, hi] """ while lo < hi: mi = lo + (hi - lo) // 2 if func(mi): hi = mi else: lo = mi + 1 return lo
bigcode/self-oss-instruct-sc2-concepts
def dummy_import(monkeypatch): # (MonkeyPatch) -> Callable """ This fixture monkeypatches the import mechanism to fail. After raising an `ImportError`, the monkeypatch is immediately removed. """ def dummy_import(*args, **kwargs): try: raise ImportError("this is a monkeypatch"...
bigcode/self-oss-instruct-sc2-concepts
def clean_sample_data(samples): """Clean unnecessary information from sample data, reducing size for message passing. """ out = [] for data in (x[0] for x in samples): data["dirs"] = {"work": data["dirs"]["work"], "galaxy": data["dirs"]["galaxy"], "fastq": data["dirs"].ge...
bigcode/self-oss-instruct-sc2-concepts
def noop(*args, **kwargs): """No-Op function for when callable is required""" return None
bigcode/self-oss-instruct-sc2-concepts
def is_source(f): """Returns true iff the input file name is considered a source file.""" return not f.endswith('_test.go') and ( f.endswith('.go') or f.endswith('.s'))
bigcode/self-oss-instruct-sc2-concepts
def primo(n): """Verifica se número é primo. Considera que n sempre é maior que 1. Retorna True se n for primo ou False caso contrário. """ if n % 2 == 0 and n != 2: resultado = False elif n % 3 == 0 and n != 3: resultado = False else: resultado = True return...
bigcode/self-oss-instruct-sc2-concepts
def eiler_func(p, q): """ Computes Euler's totient function for the modulus 'n' computed as `p`*`q`. Args: p (long): First modulus factor. q (long): Second modulus factor. Returns: long: Euler's totient function value for the modulus n=`p`*`q`. """ phi = (p...
bigcode/self-oss-instruct-sc2-concepts
def _CountPositives(solution): """Counts number of test images with non-empty ground-truth in `solution`. Args: solution: Dict mapping test image ID to list of ground-truth IDs. Returns: count: Number of test images with non-empty ground-truth. """ count = 0 for v in solution.values(): if v: ...
bigcode/self-oss-instruct-sc2-concepts
def get_bounds(points): """ Given a list of n-dimensional points, returns a list of length n where each element is a tuple holding (min, max) for that dimension. points -- list of n-dimensional points """ bounds = [[None, None] for dimension_num in range(len(points[0]))] for point in poin...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import List def flatten_nested(input_iter: Iterable) -> List: """Flatten a nested Iterable with arbitrary levels of nesting. If the input is an iterator then this function will exhaust it. Args: input_iter: The input Iterable which may or may not be nested...
bigcode/self-oss-instruct-sc2-concepts
def mass_spring(x, u, dt=0.05, m=1, c=2, k=1): """Mass-spring-damper system x :: state variables (x1, x2) where x1 = position (m) x2 = velocity (m/s) u :: input force (N) dt :: timestep (s) m :: mass (kg) c :: damping coefficient (Ns/m) k :: spring constant (N/m) ...
bigcode/self-oss-instruct-sc2-concepts
def transform_init_state_cause(cause, message): """ Transforms the init failure cause to a user-friendly message. :param cause: cause of failure :param message: failure message :return: transformed message """ return { 'credentials': 'No or invalid credentials provided', 'to...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_optimizer(opt_config, model): """Creates an optimizer based on the opt_config and model parameters. Args: - opt_config: (dict) optimizer config. It should have the following fields: * name: (str) name of the optimizer. It should be one of SGD, Adam, or LBFGS * params: (dict) o...
bigcode/self-oss-instruct-sc2-concepts
def height(grid): """Gets the height of a rectangular grid (stored row-major).""" return len(grid)
bigcode/self-oss-instruct-sc2-concepts
def extras_msg(extras): """ Create an error message for extra items or properties. """ if len(extras) == 1: verb = "was" else: verb = "were" return ", ".join(repr(extra) for extra in sorted(extras)), verb
bigcode/self-oss-instruct-sc2-concepts
import decimal def ceiling(x): """Return the smallest integral value >= x.""" return x.to_integral(rounding=decimal.ROUND_CEILING)
bigcode/self-oss-instruct-sc2-concepts
def generalized_fibonacci_sequence(n, p): """Compute the generalized Fibonacci sequence. Args: n: An `int`. The number of terms to compute. Must be >= 2. p: An `int`. The number of the generalized sequence. Must be >= 1. If `p` is 1, the sequence is the standard Fibonacci sequence. Returns: A ...
bigcode/self-oss-instruct-sc2-concepts
def apply_selection_cuts(input_catalog, snap_tolerance=1e-3): """ Select only galaxies with petrotheta > 3 and not within 1e-3 of bad measurement snap value Args: catalog (astropy.Table): Galaxy catalog including NSA information snap_tolerance (float): Minimum deviation from bad measurement...
bigcode/self-oss-instruct-sc2-concepts
def list_to_dict(list_): """Transform a list to a dictionary with its indices as keys.""" dict_ = { str(i): element for i, element in enumerate(list_) } return dict_
bigcode/self-oss-instruct-sc2-concepts
def sanitise_text(text: str): """Sanitise input text. Args: text: input text. Returns: Sanitised text """ return ''.join(e for e in text if e.isalnum() or e.isspace())
bigcode/self-oss-instruct-sc2-concepts
def getAllSubclasses(cls): """ Searches all subclasses of given class. :param cls: The base class. :type cls: class """ stack = [cls] sub=[] while len(stack): base = stack.pop() for child in base.__subclasses__(): if child not in sub: ...
bigcode/self-oss-instruct-sc2-concepts
def kid_kernel(x, y): """KID kernel introduced in https://arxiv.org/pdf/1801.01401.pdf. k(x, y) = (1/ndim * x @ y + 1)^3 Args: x: `numpy.ndarray` or `torch.Tensor` with shape [num_samples, ndim]. y: `numpy.ndarray` or `torch.Tensor` with shape [num_samples, ndim]. Returns: `nu...
bigcode/self-oss-instruct-sc2-concepts
def str2bool(val): """ convert string to bool (used to pass arguments with argparse) """ dict = {'True': True, 'False': False, 'true': True, 'false': False, '1': True, '0': False} return dict[val]
bigcode/self-oss-instruct-sc2-concepts