seed
stringlengths
1
14k
source
stringclasses
2 values
def reorder_coefficients(occupations, coefficients): """ Reorder the coefficients according to occupations. Occupated orbitals will be grouped at the beginning non occupied will be attached at the end :param occupations: list on integers (0 or 1) or list of Boolean :param coefficients: dictionary ...
bigcode/self-oss-instruct-sc2-concepts
import io def _load_vectors(filename, head_n=None, open_encoding='utf-8'): """ 装载前N个词向量 :param filename: :param head_n: head n word vectors will be loaded :return: dict, {word: str => vector: float list} """ line_count = 0 data = {} try: fin = io.open(filename, 'r', encodin...
bigcode/self-oss-instruct-sc2-concepts
def profit(initial_capital, multiplier): """Calculate the profit based on multiplier factor. :param initial_capital: Initial amount of capital :type initial_capital: float :param multiplier: Multiplying factor :type multiplier: float :return: Profit :rtype: float """ return initi...
bigcode/self-oss-instruct-sc2-concepts
def colors_objects() -> dict: """ Age of Empires II object colors for minimap. Credit for a list of objects goes to: https://github.com/happyleavesaoc/aoc-mgz. :rtype: dict """ food = (150, 200, 150) return { # FOOD 48: food, # BOAR 59: food, # BERRY BU...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def get_restore_path(restore_path: Optional[str] = None) -> Optional[str]: """Gets the path containing checkpoints from a previous calculation. Args: restore_path: path to checkpoints. Returns: The path or None if restore_path is falsy. """ if restore_path: ckpt_res...
bigcode/self-oss-instruct-sc2-concepts
def get_manual_flags(level="all"): """Returns a list of content flags from the qualitative coding manual available at http://www2.psych.ubc.ca/~psuedfeld/MANUAL.pdf. Valid `level` inputs are: ["all", 1, 2, 3, 4, 5]. Other inputs will return an empty list.""" flags_for_1 = ["absolutely", "all",...
bigcode/self-oss-instruct-sc2-concepts
import math def bin_width_of_dec(num): """ >>> bin_width_of_dec(255) 8 >>> bin_width_of_dec(256) 9 """ return int(math.ceil(math.log(num + 1, 2)))
bigcode/self-oss-instruct-sc2-concepts
def in_range(x: int, minimum: int, maximum: int) -> bool: """ Return True if x is >= minimum and <= maximum. """ return (x >= minimum and x <= maximum)
bigcode/self-oss-instruct-sc2-concepts
def pop(trace, instructions, reg): """Pop one item off the stack into reg""" instructions.append({"trace": trace, "op": "pop", "reg": reg}) return instructions
bigcode/self-oss-instruct-sc2-concepts
def modify_extra_section(yaml_content): """Modifies extra's section of the yaml_content. Args: yaml_content (str): Text representing yaml content Returns: [str]: yaml_content with extra's section modified """ yaml_content["extra"]["recipe-maintainers"] = ["prabhakk-mw", "diningPhil...
bigcode/self-oss-instruct-sc2-concepts
def model_cs_id_list(cursor, model_name): """Get a list of ``cs_id``'s for a model in a NEPC database. Parameters ---------- cursor : cursor.MySQLCursor A MySQLCursor object. See return value ``cursor`` of :func:`.connect`. model_name : str Name of a model in the NEPC MySQL database...
bigcode/self-oss-instruct-sc2-concepts
def reject_none(dict_obj: 'dict') -> 'dict': """Remove the item whose value is `None`""" return {k: v for k, v in dict_obj.items() if v is not None}
bigcode/self-oss-instruct-sc2-concepts
def mention_channel_by_id(channel_id): """ Mentions the channel by it's identifier. Parameters ---------- channel_id : `int` The channel's identifier. Returns ------- channel_mention : `str` """ return f'<#{channel_id}>'
bigcode/self-oss-instruct-sc2-concepts
def to_sg(plato): """ Convert from plato to specific gravity """ return 1 + (plato / (258.6 - ((plato / 258.2) * 227.1)))
bigcode/self-oss-instruct-sc2-concepts
def parse_version(version_string): """ Parse the version from a string The format handled is "<major>.<minor>.<patch>-<date> <commit>" Args: version_string: the version string to parse Returns: A 3-tuple of numbers: (<major>, <minor>, <patch>) """ # Remove commit from version...
bigcode/self-oss-instruct-sc2-concepts
def _format_pval(p_value): """Helper function for formatting p-value.""" if p_value < 0.0001: return 'p < 0.0001' else: return 'p = {:5.4f}'.format(p_value)
bigcode/self-oss-instruct-sc2-concepts
import torch def covariance_diff_biased(X, Xk, SigmaHat, Mask, scale=1.0): """ Second-order loss function, as described in deep knockoffs manuscript :param X: input data :param Xk: generated knockoffs :param SigmaHat: target covariance matrix :param Mask: masking the diagonal of Cov(X,Xk) :par...
bigcode/self-oss-instruct-sc2-concepts
import torch import math def cal_GauProb(mu, sigma, x): """ Return the probability of "data" given MoG parameters "mu" and "sigma". Arguments: mu (BxGxC) - The means of the Gaussians. sigma (BxGxC) - The standard deviation of the Gaussians. x (BxC) - A batch of data ...
bigcode/self-oss-instruct-sc2-concepts
def _lowercase_kind(value): """Ensure kind is lowercase with a default of "metric" """ if isinstance(value, dict): kind = value.get("kind", "metric").lower() # measure is a synonym for metric if kind == "measure": kind = "metric" value["kind"] = kind return value
bigcode/self-oss-instruct-sc2-concepts
import torch def zdot(x1, x2): """Finds the complex-valued dot product of two complex-valued vectors. Args: x1 (Tensor): The first input vector. x2 (Tensor): The second input vector. Returns: The dot product of x1 and x2, defined as sum(conj(x1) * x2) """ return torch.su...
bigcode/self-oss-instruct-sc2-concepts
def reswrite(self, fname="", cflag="", **kwargs): """Appends results data from the database to a results file. APDL Command: RESWRITE Parameters ---------- fname File name and directory path (248 characters maximum, including the characters needed for the directory path). A...
bigcode/self-oss-instruct-sc2-concepts
import socket def check_remote_port_whether_open(remote_addr, remote_port): """ Check the remote port whether open :param remote_addr: Remote host's ip address :param remote_port: Remote host's tcp port :type remote_addr: string :type remote_port: int :return: A boolean value to decide the po...
bigcode/self-oss-instruct-sc2-concepts
def stringListaksi(string, delim=",", poistaTyhjat=True): """ Paloittelee merkkijonon erottimen (delim) kohdalta listaksi, poistaa listasta tyhjät merkkijonot (jos poistaTyhjat=True), siivoaa ylimääräiset välilyönnit ja muuttaa tekstin kirjainkoon pieneksi. Oletuserotin on pilkku. """ lista = [s...
bigcode/self-oss-instruct-sc2-concepts
def are_blocking_checks(checks, ignore_warnings): """ Return True if checks are errors or unignored warnings. :arg dict checks: dictionary with a list of errors/warnings per library :arg bool ignore_warnings: ignores failed checks of type warning """ has_errors = any(p.endswith('Errors') for p ...
bigcode/self-oss-instruct-sc2-concepts
def _split_gradient(gradient: float, ratio: float) -> tuple[float, float]: """ (s+h)/2 = c s = 2c-h --- s-1 = r*(h-1) s-1 = rh-r s = rh-r+1 --- 2c-h = rh-r+1 h(r+1) = 2c+r-1 h = (2c+r-1)/(r+1) s = 2c-(2c+r-1)/(r+1) = (2cr+r-1)/(r+1) """ highlight = (2 * gradient +...
bigcode/self-oss-instruct-sc2-concepts
def parse_contrast(contrast, samples, check=True): """ Extract contrast batch and column, target and reference groups from a DE contrast design. Check for contrast validity if check = True. If "all" is in the contrast groups, it is always assumed to be the target (and expanded to mean all groups in...
bigcode/self-oss-instruct-sc2-concepts
def update_vehicle_profile(spawn_profile, new_vehicle): """ Updates the vehicle profile of the spawning profile :param new_vehicle: new vehicle profile :param spawn_profile: spawning profile :type spawn_profile: SpawningProfile :type new_vehicle: VehicleProfile :return: updated spawning prof...
bigcode/self-oss-instruct-sc2-concepts
import operator def _cross_platform_stable_fs_iter(dir): """ Provides a stable ordering across platforms over a directory Path. This allows iteration across filesystems in a consistent way such that case sensitivity of the underlying system does not affect how the files are iterated. Args: ...
bigcode/self-oss-instruct-sc2-concepts
def count(seq): """ Count the number of items in seq Like the builtin ``len`` but works on lazy sequencies. Not to be confused with ``itertools.count`` See also: len """ if hasattr(seq, '__len__'): return len(seq) return sum(1 for i in seq)
bigcode/self-oss-instruct-sc2-concepts
def range_corrector(g_range): """Swap start and end if start > end.""" chrom, start_end = g_range.split(":") start_end_split = start_end.split("-") start, end = int(start_end_split[0]), int(start_end_split[1]) if start < end: return g_range else: return f"{chrom}:{end}-{start}"
bigcode/self-oss-instruct-sc2-concepts
import re def combine_tops(top_text, itp_texts): """ Search through parent topology top_text and replace #include lines with the relevant child topologies from the dictionary itp_texts """ for itp in itp_texts: # split on include string, then rejoin around itp file spl = re.spl...
bigcode/self-oss-instruct-sc2-concepts
def residuals(constants, function, x, y): """ Function used to optimise the fit of the curve to the data. It calculates the distance between y-value from real data and y-value from the function (sigmoid/sine/etc). """ return y - function(constants, x)
bigcode/self-oss-instruct-sc2-concepts
def rgb_maximize(r, g, b, scale=255): """ Calculates full luminosity RGB values from rgb chromacity coordinates :param r: Red ratio :param g: Green ratio :param b: Blue ratio :param scale: Output R,G,B values scale :return: RGB tuple """ ratio = scale / max(r, g, b) return tuple(int(...
bigcode/self-oss-instruct-sc2-concepts
from operator import contains def project_contains_keywords(project, keywords): """Returns True if project contains at least one of the keywords.""" # Iterate over all sprites and backdrops, and the project itself. for child in project["children"] + [project]: # Perform a DFS on each script look...
bigcode/self-oss-instruct-sc2-concepts
def filter_lines(infile,outfile,wind,nskip=0) : """ Read from input linelist file, output comments and lines falling in windows of [w1,w2] to outfile Args : infile (str) : name of input file outfile (str) : name of output file wind (list of [w1,w2] pairs) : list of window ranges ...
bigcode/self-oss-instruct-sc2-concepts
def read_file_as_str(filepath): """ Reads the file content Args: filepath (str): File to read Returns: str : File contents in string """ with open(rf"{filepath}") as fd: content = fd.read() return content
bigcode/self-oss-instruct-sc2-concepts
def tile_key(layer, coord, format): """ Return a tile key string. """ name = layer.name() tile = '%(zoom)d/%(column)d/%(row)d' % coord.__dict__ ext = format.lower() return str('%(name)s/%(tile)s.%(ext)s' % locals())
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Any from typing import Tuple def index_2d(seqs: List[List[Any]], target: Any) -> Tuple[int, int]: """Finds the first index of a target item within a list of lists. Args: seqs: The list of lists to search. target: The item to find. Raises: ...
bigcode/self-oss-instruct-sc2-concepts
def get_count(results): """Creates a dictionary, word being the key, and word count being the value""" counts_dict = dict() for word in results: counts_dict[word] = counts_dict.get(word, 0) + 1 return counts_dict
bigcode/self-oss-instruct-sc2-concepts
import struct def memory_read(dev_file: str, address: int, length=1) -> tuple: """ reads bytes from a rc2f memory file @param dev_file: the memory to use @param address: where to read @param length: how many bytes to read @return: the read bytes as a tuple @rtype: tuple """ with op...
bigcode/self-oss-instruct-sc2-concepts
def length(database): """Computes the total number of tuning entries""" num_tuning_entries = 0 for section in database["sections"]: num_tuning_entries += len(section["results"]) return num_tuning_entries
bigcode/self-oss-instruct-sc2-concepts
def eval_e_x_polarized_using_e_x_unpolarized(e_x_unpolarized): """Decorator function for computing e_x for spin polarized case. The spin-scaling relation for exchange energy is used: e_x(rhoa, rhob) = 0.5 * (e_x(2*rhoa) + e_x(2*rhob)) Args: e_x_unpolarized: function to evaluate exchange energy density ...
bigcode/self-oss-instruct-sc2-concepts
def minRefuelStops_DP( target_distance: int, start_fuel: int, stations: list[list[int]] ) -> int: """1-D Dynamic Programming DP_table[num_stops] the furthest distance (== max gas) that we can get with num_stops times of refueling. So for every station, stations[i], if the curre...
bigcode/self-oss-instruct-sc2-concepts
import torch def generate_grids(fh: int, fw: int) -> torch.Tensor: """generates grids using given feature map dimension Args: fh (int): height of the feature map fw (int): width of the feature map Returns: torch.Tensor: fh x fw x 2 as x1,y1 """ # y: fh x fw # x: fh x ...
bigcode/self-oss-instruct-sc2-concepts
def normalize(position): """ Accepts the 'position' of random precision, and returns the block which contains that position Params ------- position: tuple of the len(3) then Returns: ------- block_position: tuple of ints of len(3) """ x, y, z = position x, y, z = (int(round(x))...
bigcode/self-oss-instruct-sc2-concepts
def even_chars(st): """ Finds all the even characters in a string. :param st: string value. :return: a sequence (index begins with 1) of all the even characters from a string. If the string is smaller than two characters or longer than 100 characters, the function should return "invalid str...
bigcode/self-oss-instruct-sc2-concepts
def not_yet_found(input_site, d_tracker): """if site has not yet been found, return True, else False""" if input_site not in set(d_tracker.keys()): return True # not yet else: return False
bigcode/self-oss-instruct-sc2-concepts
def get_num_shards(path): """Get number of shards in sharded dataset.""" return int(path.split('@')[-1])
bigcode/self-oss-instruct-sc2-concepts
def _get_value_indices(names1, names2, lookups): """ >>> _get_value_indices(['foo', 'bar', 'baz'], ['foo', 'bar', 'baz'], ... ['bar', 'foo']) [1, 0] >>> _get_value_indices(['foo', 'bar', 'baz'], ['FOO', 'bar', 'baz'], ... ['bar', 'FOO']) [1, 0] >>> _...
bigcode/self-oss-instruct-sc2-concepts
def byte_to_human(size): """Transform the size in bytes into the appropriate unit of measurement. :param int size: Size in bytes. :return: Actual size in B/KB/MB/GB. :rtype: str """ try: size = int(size) except ValueError: return (0, "B") um = "B" if size < pow(2, 2...
bigcode/self-oss-instruct-sc2-concepts
import random def sort_by_lenght(words): """ (basic DSU example) 1. Build a list of tuples with word lenght and a random number as sort keys 2. (reverse) sort the list 3. Extract the (now sorted) elements of the original sequence """ l = [] for w in words: l.append((len(w), ran...
bigcode/self-oss-instruct-sc2-concepts
def half(x: float) -> float: """Half the value""" return x / 2.0
bigcode/self-oss-instruct-sc2-concepts
def get_valid_init_tree(trees): """Returns first NewickTree entry that is not NoTree""" for i in range(len(trees)): if trees[i] == "NoTree": continue else: return trees[i]
bigcode/self-oss-instruct-sc2-concepts
def dict_remove_none(_dict): """ Removes key-value pairs from a dictionary where the value is `None`. Does not handle nested dictionaries. :param _dict: `dict` :returns: `dict` """ return {k: v for k, v in _dict.items() if v is not None}
bigcode/self-oss-instruct-sc2-concepts
def lovibond_to_srm(lovibond: float) -> float: """ Convert from Degrees Lovibond color system to Standard Reference Method (SRM) color system. """ return 1.3546 * lovibond - 0.76
bigcode/self-oss-instruct-sc2-concepts
def parser_shortname(parser_argument): """Return short name of the parser with dashes and no -- prefix""" return parser_argument[2:]
bigcode/self-oss-instruct-sc2-concepts
def retrieve_actor(world, bp_regex, role_name): """ Retrieves the actor from the world with the given blueprint and the role_name. Args: world: The instance of the simulator to retrieve the actors from. bp_regex: The actor's blueprint to be retrieved from the simulator. role_name: T...
bigcode/self-oss-instruct-sc2-concepts
def part1(depths): """ Count the number of times a depth measurement increases from the previous measurement How many measurements are larger than the previous measurement? """ depth_increases = 0 previous_depth = depths[0] for depth in depths: if depth > previous_depth: ...
bigcode/self-oss-instruct-sc2-concepts
import torch def convert_to_one_hot(index, action_size): """ Converts a given input to a one hot vector Parameters ---------- index: int index of the one size: int size of tensor Returns ------- torch.tensor output tensor one hot """ one_hot_action = torch.zeros((1, action_size)) one_hot_action[0]...
bigcode/self-oss-instruct-sc2-concepts
import json import base64 def base64_to_dict(byte_string): """ :param byte_string: base64 encoded string :type byte_string: str :return: python dictionary decoding of byte_string :rtype dict """ return json.loads(base64.b64decode(byte_string).decode('utf-8'))
bigcode/self-oss-instruct-sc2-concepts
def get_placesWithMissingTokens(t, net, marking): """ Get places with missing tokens Parameters ---------- t Transition to enable net Petri net marking Current marking """ placesWithMissing = set() for a in t.in_arcs: if marking[a.source] < a.weig...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def create_task_name(path: Path, base_name: str): """Create the name of a task from a path and the task's base name. Examples -------- >>> from pathlib import Path >>> create_task_name(Path("module.py"), "task_dummy") 'module.py::task_dummy' """ return path.a...
bigcode/self-oss-instruct-sc2-concepts
def parse_latitude(value): """ Parse latitude in the form "S10" or "N10". """ latsign = {'N': 1, 'S': -1} if "N" in value or "S" in value: return latsign[value[0]] * float(value[1:3])
bigcode/self-oss-instruct-sc2-concepts
from typing import List def build_uri(scheme: str, loc: str, paths: List[str] = [], **kwargs) -> str: """ Used to build URIs :param scheme: scheme e.g. http in http://google.com/ :param loc: netloc e.g. google.com in http://google.com/ :param paths: a list of paths e.g. ["example", "path"] in http...
bigcode/self-oss-instruct-sc2-concepts
def series(*resistors): """Calculate an equivalent resistory value for series resistors. Given resistor values as input, assume they are put in series in a circuit, and return the equivalent resistor value as if they were a single resistor. """ return sum(resistors)
bigcode/self-oss-instruct-sc2-concepts
def _get_mins_and_secs_str_from_secs(delta): """ Returns minutes and seconds from a seconds number """ mins = round(delta / 60) secs = round(delta-mins*60) if (secs == 60): mins += 1 secs -= 60 time_text = (f"{mins} minute" if mins > 0 else "") + ("s" if mins > 1 else "") + \ ...
bigcode/self-oss-instruct-sc2-concepts
def catch_error(list_like): """ if none of the options are true, something has gone wrong :param list_like: a list_like of bools :return: true if at least one is true, else returns false """ for b in list_like: if b: return True return False
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def plurality_value(examples: list): """ Returns the most common classification in a list of examples. :param examples: list of dictionaries with examples as entries, must contain the key "classification" :return: str, most common classification """ return C...
bigcode/self-oss-instruct-sc2-concepts
import json def pack_message(routing_id, message): """ Pack a routing id and Message into a mutlipart zmq message. Parameters ---------- routing_id : str The zmq socket identity to place first in the message. message : Message The Message object to serialized into the multipart m...
bigcode/self-oss-instruct-sc2-concepts
def retry(value, multiplier=1.5, max_value=100000): """Creates callable that increases resource value on retries. This function is intended for use with resources, especially memory (mem_mb). Parameters ---------- value : int The value that will be multiplied on retries. This v...
bigcode/self-oss-instruct-sc2-concepts
def check_distance_residue(AA, H): """ Parameters ---------- AA : amino acid from a protein structure object made with PDBParser(). H : hetero residue from a protein structure object made with PDBParser(). Returns ------- distance : the smallest distance between the two residues (i...
bigcode/self-oss-instruct-sc2-concepts
import pytz from datetime import datetime def float_to_datetime(timestamp, tzinfo=None): """ Convert a timestamp to a datetime instance. If tzinfo is passed, interpret the timestamp in the given timezone. If tzinfo isn't passed, interpret the timestamp as UTC. For example, epoch starts at 1am CET...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import time def measure_time(func: Any) -> Any: """ Measures and prints execution time for function. Args: func: Function to monitor. Returns: inner function. """ def inner(*args, **kwargs): start = time.time() try: return fun...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def md5_for_file(f, block_size=2**20): """ Reads in a file, f, using a configurable block size, block_size. Returns an md5 hash of the content of the file """ m = hashlib.md5() with open(f , "rb" ) as f: while True: buf = f.read(block_size) if no...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def calculateVoltageDifference(adapters: List[int]) -> int: """ Given a list of adapters, calculate product of 1-volt and 3-volt diffs """ oneDiff: int = 0 threeDiff: int = 1 # your phone adapter's diff prev: int = 0 for i in range(len(adapters)): diff: int = abs(pr...
bigcode/self-oss-instruct-sc2-concepts
def search(misp, **kwargs): """ Search the MISP server and return records that match misp: The MISP server connection object kwargs: The specification of the search (e.g. controller="attributes", org="CIRCL") """ res = {} try: r = misp.search(**kwargs) if r.get('errors'): ...
bigcode/self-oss-instruct-sc2-concepts
def str_timedelta(dt, max_num_fields=3, short=False, negative_to_zero = False): """ Given a dt in seconds, return it in a HH:MM:SS format. :param dt: a TimeDelta object :param max_num_fields: maximum number of non-zero fields to show (for instance if the number of days is non-zero, shows only ...
bigcode/self-oss-instruct-sc2-concepts
import math def areaToDiameter(area): """Returns the diameter of a circle based on a given area Args: area (int): The area in pixels. Returns: diameter (int): The diameter of the corresponding circle. """ return (2 * math.sqrt((area / math.pi)))
bigcode/self-oss-instruct-sc2-concepts
def escape(s): """Escape characters forbidden by Telegram API""" # to_escape = '_*~[]()`#+-|{}.!' # for c in to_escape: # s = s.replace(c, '\\' + c) return s
bigcode/self-oss-instruct-sc2-concepts
def proxify(scraped_urls,prefix): """ This method takes a list of scraped urls and turns them into urls that go through the UW Library proxy so that all of them are full access. """ proxy_urls = [] for url in scraped_urls: sd_id = url[32:] newlink = prefix + sd_id proxy_...
bigcode/self-oss-instruct-sc2-concepts
def get_intent_by_name(intent_list: list, intent_name: str): """Get an intent by name from an intent list.""" for intent in intent_list: if intent.display_name == intent_name: return intent return None
bigcode/self-oss-instruct-sc2-concepts
def read_file(fname): """ Get a file into a list of strings (one entry=one line) """ with open(fname) as f: lines = f.readlines() return lines
bigcode/self-oss-instruct-sc2-concepts
def sort_dict_desc(dictionary): """Sorts dictionary in descending order by values.""" return sorted(dictionary.items(), key=lambda item: item[1], reverse=True)
bigcode/self-oss-instruct-sc2-concepts
def modular_geometric_sum(x, n, mod): """ Compute a_n = (1 + a^1 + ... + a^{n-1}) % mod using that a_{2n} = ((x_n + 1) * a_n) % mod a_{2n+1} = (x^{2n} + a_{2n}) % mod """ if n == 1: return 1 % mod elif n % 2 == 0: return ((pow(x, n // 2, mod) + 1) * modular_geometri...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def join(value: Union[tuple, list, str], separator: str = ':') -> str: """Uses ``.join`` to squash a list or tuple using a separator. Args: value: Value to be squashed. separator: Separator to be used to squash. Returns: str: A squashed string. ...
bigcode/self-oss-instruct-sc2-concepts
def from_sdss_albd_to_megacam_albd(sdss): """Return A(lbd) for the 6 Megecam filters: u, g, r, i_old, i_new, z.""" megacam = {} megacam['u'] = sdss['u'] - 0.241 * (sdss['u'] - sdss['g']) megacam['g'] = sdss['g'] - 0.153 * (sdss['g'] - sdss['r']) megacam['r'] = sdss['r'] - 0.024 * (sdss['g'] - sdss['...
bigcode/self-oss-instruct-sc2-concepts
def get_cameras_with_filter(cameras, filter_name): """ Get a dict of cameras wit the required filter. Args: cameras (dict): Dict of cam_name: camera pairs. filter_name (str): The filter name. """ cameras_with_filter = {} for cam_name, cam in cameras.items(): if cam.filterwhe...
bigcode/self-oss-instruct-sc2-concepts
import operator def eval_RPN(tokens: list[str]) -> int: """Returns the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is gua...
bigcode/self-oss-instruct-sc2-concepts
def _replace_characters(s: str) -> str: """Replace characters that are not suitable to present in Labber. Returns: Labber compatible string. """ if not s: return "" chars = [ ("\n", " "), ("\r", ""), ('"', "`"), ("'", "`"), (";", ":"), ...
bigcode/self-oss-instruct-sc2-concepts
def to_classname(filename: str) -> str: """ maps divided mock class file name to class names inverse function of headersplit.to_filename e.g. map "test/mocks/server/admin_stream.h" to "MockAdminStream" Args: filename: string, mock class header file name (might be the whole path instead of t...
bigcode/self-oss-instruct-sc2-concepts
from io import StringIO def render_pil(image, fmt="jpg"): """ Render PIL Image to base64. :param image: given image. :param fmt: image format. :return: rendered image. """ if not callable(getattr(image, "save", None)): return None output = StringIO() image.save...
bigcode/self-oss-instruct-sc2-concepts
def tuplefy(value): """Returns the value in or as a tuple if not already a tuple.""" return value if isinstance(value, tuple) \ else tuple(value) if isinstance(value, list) else (value, )
bigcode/self-oss-instruct-sc2-concepts
def _sh_cmd(system, *args): """ Helper function to build a local shell command """ if len(args) == 0: return None return args
bigcode/self-oss-instruct-sc2-concepts
def split_alpha_mask(RGBA_mask): """Splits alpha mask and RGB image. # Arguments RGBA_mask: Tensor [batch, H, W, 4] # Returns Color tensor [batch, H, W, 3] and alpha tensor [batch, H, W, 1] """ color_mask = RGBA_mask[:, :, :, 0:3] alpha_mask = RGBA_mask[:, :, :, 3:4] return...
bigcode/self-oss-instruct-sc2-concepts
def change_elements(items, old_index, new_index): """Switch places of two elements in list collection.""" new_items = items[:] new_items[old_index], new_items[new_index] = new_items[new_index], new_items[old_index] return new_items
bigcode/self-oss-instruct-sc2-concepts
def event_wrapper(function): """ Useful to wrap callbacks for calling in a different context. """ def f(event): function() return f
bigcode/self-oss-instruct-sc2-concepts
import random def _apply_randomness(value, random_factor): """ Applies a random factor to the value :param value: Input value :param random_factor: Random factor, must be between 0 (no random) and 1 (output is between 0 and 2* value) :return: Value with random factor applied """ if random_...
bigcode/self-oss-instruct-sc2-concepts
def has_solution(cell): """Return True if cell is marked as containing an exercise solution.""" cell_text = cell["source"].replace(" ", "").lower() first_line = cell_text.split("\n")[0] return ( cell_text.startswith("#@titlesolution") or "to_remove" in first_line and "explanation...
bigcode/self-oss-instruct-sc2-concepts
def af_subtraction(ch1, ch2, m, c): """ Subtract ch2 from ch1 ch2 is first adjusted to m * ch2 + c :param ch1: :param ch2: :param m: :param c: :return: """ af = m * ch2 + c signal = ch1 - af return signal
bigcode/self-oss-instruct-sc2-concepts
def title2list(news_title): """ 将一个新闻标题分字并转换成列表 :param news_title: 一个新闻标题字符串 E.g.:'2019年校领导寒假会商会召开' :return: 一个新闻标题按字切分的列表 ['2','0','1','9','年','校','领','导','寒','假','会','商','会','召','开'] """ title = [] for i in news_title: title.append(i) # print("================title============\...
bigcode/self-oss-instruct-sc2-concepts