seed
stringlengths
1
14k
source
stringclasses
2 values
import torch def redistribute_errors(power_deltaE_hyab, cmax, pc, pt): """ Redistributes exponentiated HyAB errors to the [0,1] range :param power_deltaE_hyab: float tensor (with Nx1xHxW layout) containing the exponentiated HyAb distance :param cmax: float containing the exponentiated, maximum HyAB difference be...
bigcode/self-oss-instruct-sc2-concepts
def decode_fit_par(fit_par, constraint_types): """ Translate the 1D array of fit parameters to individual lists. The fit paramters are sorted into the lists segment_borders, y_at_borders slope_at_borders based on the strings given in constraint_types. The three lists are used as arguments in piecew...
bigcode/self-oss-instruct-sc2-concepts
import itertools def get_room_locations(room_top_left, room_width, room_height): """ Returns the locations within a room, excluding walls. This is a helper function for adding objects to a room. It returns a list of all (x,y) coordinates that fall within the room excluding the walls. Parameters ...
bigcode/self-oss-instruct-sc2-concepts
import random def random_fill_sparse(table,K): """ brief : fills in a matrix randomly args : matrix : empty matrix K : number of cells to be filled in Return : the matrix (numpy array) filled in with "X" values (char) Raises : K must be smaller than...
bigcode/self-oss-instruct-sc2-concepts
def calcular_longitud_cadena(cadena): """ Calcula la longitud de una cadena de caracteres. """ contador = 0 for c in cadena: contador += 1 return contador
bigcode/self-oss-instruct-sc2-concepts
def process_text(response): """Returns the plaintext of the reponse.""" return response.text
bigcode/self-oss-instruct-sc2-concepts
def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new ha...
bigcode/self-oss-instruct-sc2-concepts
import torch def square_norm(x): """ Helper function returning square of the euclidean norm. Also here we clamp it since it really likes to die to zero. """ norm = torch.norm(x, dim=-1, p=2) ** 2 return torch.clamp(norm, min=1e-5)
bigcode/self-oss-instruct-sc2-concepts
def dt_tstamp(dt_obj): """ Args: dt_obj (dt.datetime): datetime.datetime object Returns: int: timestamp """ return int(dt_obj.strftime('%s'))
bigcode/self-oss-instruct-sc2-concepts
def other_bond_index(bond, index): """Return the atom index for the other atom in a bond.""" if bond[0] == index: return bond[1] elif bond[1] == index: return bond[0] else: raise ValueError("Index %s not found in bond %s" % (index, bond))
bigcode/self-oss-instruct-sc2-concepts
def pretty_print_time(time, message=None): """Pretty print the given time""" days = time.days hours, remainder = divmod(time.seconds, 3600) minutes, seconds = divmod(remainder, 60) if message is not None: print(message) print(f'\t {days} days, {hours} hours, {minutes} minutes, {secon...
bigcode/self-oss-instruct-sc2-concepts
import re def is_fc_uid(uid): """Validate the FC initiator format.""" return re.match(r"(\w{2}:){15}\w{2}", uid, re.I) is not None
bigcode/self-oss-instruct-sc2-concepts
def _make_url_args(url_args: dict): """ Make url parameters Args: url_args (Dict): Dict of url parametes Returns: str: The url parameters Example: input: {'test1': 1, 'test2': 2, 'test3': 3} output: "&test1=1&test2=2&test3=3" """ url = '' for key, v...
bigcode/self-oss-instruct-sc2-concepts
def package_time(date_dict): """Package a time/date statement in a standardised form.""" return {"time_value": date_dict}
bigcode/self-oss-instruct-sc2-concepts
def validate_container_command(output: str, name: str) -> tuple: """ Validates output from one of the *_container functions, eg start_container. :param output: output from the command line :param name: container name or ID :return: success boolean, message """ if "no such container" in outpu...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any from typing import Tuple from typing import List def get_category_counts(cookie_data: Dict[str, Dict[str, Any]]) -> Dict[Tuple[str,str], List[int]]: """ Retrieve category counts for each cookie, to then be able to compute the majority opinion. Cookies are ide...
bigcode/self-oss-instruct-sc2-concepts
def standardize_tabletype(tabletype): """ Given the user defined type of table it returns the proper 'tabletype' expected by the pipeline Args: tabletype, str. Allows for a flexible number of input options, but should refer to either the 'exposure', 'processing', or 'unproc...
bigcode/self-oss-instruct-sc2-concepts
def reorder_list_or_array(M, ordering): """ Reorders a list or array like object. """ if isinstance(M, list): return [M[i] for i in ordering] else: return M[ordering]
bigcode/self-oss-instruct-sc2-concepts
def standardise(x,l1,l2): """standardise data x to [0,1] Parameters x: original data l1: lower bound l2: upper bound ---------- Returns ------- standardised data """ return (x-l1)/float(l2-l1)
bigcode/self-oss-instruct-sc2-concepts
def full_product_to_l3_product(full_product: str): """Returns l3 product name.""" return full_product.split("-")[1]
bigcode/self-oss-instruct-sc2-concepts
def strip_string(value): """Remove all blank spaces from the ends of a given value.""" return value.strip()
bigcode/self-oss-instruct-sc2-concepts
import click def role_selection_is_valid(selection, account_roles): """Checks that the user input is a valid selection Args: selection: Value the user entered. account_roles: List of valid roles to check against. Returns: Boolean reflecting the validity of given choice. """ ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def largest_element(arr: List[int]) -> int: """ Find the largest element in the array >>> largest_element([1,2,3,4,5]) 5 """ mx = arr[0] for i in arr: mx = max(i, mx) return mx
bigcode/self-oss-instruct-sc2-concepts
import binascii def calc_crc32(memview): """ Calculate simple CRC-32 checksum over a memoryview of data """ crc = binascii.crc32(memview) & 0xffffffff return crc
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def calculate_large_sum(number_strings: Iterable[str]) -> str: """Calculate sum of large numbers. Args: number_strings: iterable of numbers as strings to sum up. Returns: The sum of the numbers as string. """ number_strings = list(number_strings) la...
bigcode/self-oss-instruct-sc2-concepts
import struct def i16(c, o = 0): """ Converts a 2-bytes (16 bits) string to an integer. :param c: string containing bytes to convert :param o: offset of bytes to convert in string """ return struct.unpack("<H", c[o:o+2])[0]
bigcode/self-oss-instruct-sc2-concepts
def mapl(function, array): """ Map a function to an array (equivalent to python2 map) :param function: Function to be mapped :param array: List of values :return: List of returns values f = function array = [x0, x1, x2, ... xn] [f(x0), f(x1), f(x2) ... f(xn)] = mapl(f, a...
bigcode/self-oss-instruct-sc2-concepts
def connect_(pairs, n=1): """connect_ Connects two adjacent clusters if their distance is <= n :param pairs: Clusters of iterateables e.g., [(1,5),(7,10)] :param n: distance between two clusters """ if len(pairs) == 0: return [] start_, end_ = pairs[0] new_pairs = [] for i, ...
bigcode/self-oss-instruct-sc2-concepts
def _distance(p1, p2): """ Returns distance between p1 point and p2 """ return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5
bigcode/self-oss-instruct-sc2-concepts
def read_text_file(file_path): """Read a txt file""" with open(file_path, 'r') as f: return f.readlines()
bigcode/self-oss-instruct-sc2-concepts
def created_by_external_idp_and_unconfirmed(user): """Check if the user is created by external IdP and unconfirmed. There are only three possible values that indicates the status of a user's external identity: 'LINK', 'CREATE' and 'VERIFIED'. Only 'CREATE' indicates that the user is newly created by an ...
bigcode/self-oss-instruct-sc2-concepts
def is_growth(name): """ Test if name is a growth rate-like variable""" return name in ["gam_leq_GB", "gam_great_GB"]
bigcode/self-oss-instruct-sc2-concepts
def getCouplesInteraction(couples:list, interaction_type:bool): """ | Get couples according to their interaction. :param couple: list of couples :param interaction: type of the interaction (True or False) :type couple: CoupleJson :type interaction_type: bool :return: list of couples :...
bigcode/self-oss-instruct-sc2-concepts
def _adjust_component(component: int) -> int: """Return the midpoint of the quadrant of the range 0-255 that the given component belongs to. Each quadrant spans 63 integers, and the midpoints are: 31, 95, 159, 223. >>> _adjust_component(25) 31 >>> _adjust_component(115) 95 """ if c...
bigcode/self-oss-instruct-sc2-concepts
import torch import math def perspective(aspect_ratio, fov_y, near_clip, far_clip): """Computes perspective transformation matrices. Functionality mimes gluPerspective (external/GL/glu/include/GLU/glu.h). See: https://unspecified.wordpress.com/2012/06/21/calculating-the-gluperspective-matrix-and-othe...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def timestamp_zip(string: str) -> str: """ Adds the current date and a .zip ending to the given string. Example: > timestamp("foo") "foo-1997-09-14-1253.zip" """ timestamp = datetime.today().strftime("%Y-%m-%d-%H%M") return f"{string}-{timestamp}.zip"
bigcode/self-oss-instruct-sc2-concepts
def _in_text(adict): """ Wrapper to add .* around matches so pattern can be found in words. Parameters ---------- adict : dict Dictonary with key = `pattern` Returns ------- wrapped_dict : dict Dictonary with key = `.*pattern.*` """ return dict((".*{}.*".forma...
bigcode/self-oss-instruct-sc2-concepts
def get_digit_c(number, digit): """ Given a number, returns the digit in the specified position, does not accept out of range digits """ return int(str(number)[-digit])
bigcode/self-oss-instruct-sc2-concepts
import mpmath def cdf(x, c, beta, scale): """ Cumulative distribution function of the Gamma-Gompertz distribution. """ with mpmath.extradps(5): if x < 0: return mpmath.mp.zero x = mpmath.mpf(x) beta = mpmath.mpf(beta) c = mpmath.mpf(c) scale = mpmath...
bigcode/self-oss-instruct-sc2-concepts
def calculate_temperature_rise_power_loss_weight( power_operating: float, weight: float, ) -> float: """Calculate the temperature rise based on the power loss and xfmr weight. :param power_operating: the power loss in W. :param weight: the weight of the device in lbf. :return: _temperature_rise...
bigcode/self-oss-instruct-sc2-concepts
def _cast(x): """ Auxiliary function used to cast strings read from the config file to more useful types. For example, it will convert any of the strings true, TRUE, True, etc, to True (bool). :param x: :return: """ # -- At the moment, it is guaranteed that x is a string, however we may wa...
bigcode/self-oss-instruct-sc2-concepts
def get_success_prob(n, pa): """ Calculate the probability of successful transmission input: n: number of nodes in the same communication range pa: the attempt probability (pa) return: the probability of successful transmission """ return (n - 1) * pa * (1 - pa) ** (n - 2)
bigcode/self-oss-instruct-sc2-concepts
def map_category_id(category_map): """ Assign an ID to each category """ category_id = {} id_category = {} counter = 0 for category in category_map: category_id[category['name']] = counter id_category[counter] = category['name'] counter += 1 return category_id, id_categor...
bigcode/self-oss-instruct-sc2-concepts
def lamson_setting(func, key): """Simple way to get the lamson setting off the function, or None.""" return func._lamson_settings.get(key)
bigcode/self-oss-instruct-sc2-concepts
def getSquareDistanceOriginal(p1, p2): """ Square distance between two points """ dx = p1['x'] - p2['x'] dy = p1['y'] - p2['y'] return dx * dx + dy * dy
bigcode/self-oss-instruct-sc2-concepts
def is_not_false_str(string): """ Returns true if the given string contains a non-falsey value. """ return string is not None and string != '' and string != 'false'
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import List import gzip def save_metadata_files(path: Path, contents: str) -> List[Path]: """Saves the metadata file and the corresponding compressed version of the file. :param path: The path to save the uncompressed metadata file at :param contents: The data to ...
bigcode/self-oss-instruct-sc2-concepts
def create_random_files(tmpdirname, num_of_files=10): """ Create random files in dir given """ _files_created = [] # Create random files for i in range(1, num_of_files + 1): _object_key = f"{i}{i}{i}.txt" _test_file = tmpdirname.join(_object_key) _test_file.write("XXXXXX...
bigcode/self-oss-instruct-sc2-concepts
def match_bag(context, bags): """Matches bag to the file for which an event is triggered and returns bag or list of all bags to run Fixity against. Args: context (obj): Object that contains event context information bags (set): List of bags to match against """ filename = context.res...
bigcode/self-oss-instruct-sc2-concepts
import torch def model_to(on_gpu, model): """Transfers model to cpu/gpu. Args: on_gpu (bool): Transfers model to gpu if True otherwise to cpu model (torch.nn.Module): PyTorch defined model. Returns: torch.nn.Module: The model after being moved to cpu/gpu. """ ...
bigcode/self-oss-instruct-sc2-concepts
def format_movie_year_min(pick_movie_year_min): """ Ensures that the minimum movie year is properly formatted (parameter is the minimum movie year) """ if bool(pick_movie_year_min) == True: movie_year_min = str(pick_movie_year_min) + "-01-01" else: movie_year_min = None retur...
bigcode/self-oss-instruct-sc2-concepts
def id_has_been_provided(entity_id): """ Simple function returning true or false if id has been provided. Created for readability purposes. """ return True if entity_id else False
bigcode/self-oss-instruct-sc2-concepts
def width0diameter(b, d): """Calculate rate width over diameter. :param b (float): impeller width [m] :param d (float): diameter [m] :return bd (float): width over diameter """ bd = b / d return bd
bigcode/self-oss-instruct-sc2-concepts
def remap_values(values, target_min=0.0, target_max=1.0, original_min=None, original_max=None): """ Maps a list of numbers from one domain to another. If you do not specify a target domain 0.0-1.0 will be used. Parameters ---------- val : list of int, list of long, list of float The val...
bigcode/self-oss-instruct-sc2-concepts
def match_gamma(value, gamma, gamma_mask): """Do a bitwise check of value with gamma using only the bits from gamma_mask""" return not (value & gamma_mask) ^ (gamma & gamma_mask)
bigcode/self-oss-instruct-sc2-concepts
def compare(song1, song2): """ Compares two songs and returns which is prefferec (1 or 2) or returns 0 if it's a tie. Numbers are returned as strings """ print("1:", song1.name, "by", song1.artist, "or,") print("2:", song2.name, "by", song2.artist, "?") # x is evaluated as a string and acts ...
bigcode/self-oss-instruct-sc2-concepts
import json def json_recursive_size(data, level=0, maxlevel=None): """Get size of a JSON object recursively.""" ### HELPERS # how many levels remaining? remaining_levels = maxlevel - level if maxlevel is not None else None def length_now(d): """Get length of a json string.""" re...
bigcode/self-oss-instruct-sc2-concepts
import math def rspace_sum(rs, qs, basis, kappa, rlim): """ Real space part of the sum Parameters: rs -- list of particle positions qs -- list of particle charges basis -- real space basis kappa -- splitting parameter rlim -- size of lattice (one side of a cube of points...
bigcode/self-oss-instruct-sc2-concepts
def findCompartment(rx, blocks, aR, aP, rR, metaboliteBlock): """ Derive information on compartment aspects of the reaction. Returns ------- 'type': String 'Transport','Exchange' or 'Normal' (kind of reaction). 'comp': compartment of SBML-model. arrow between compartments when reaction is 'Tran...
bigcode/self-oss-instruct-sc2-concepts
def revert_correct_V3SciYAngle(V3SciYAngle_deg): """Return corrected V3SciYAngle. Only correct if the original V3SciYAngle in [0,180) deg Parameters ---------- V3SciYAngle_deg : float angle in deg Returns ------- V3SciYAngle_deg : float Angle in deg """ if V3S...
bigcode/self-oss-instruct-sc2-concepts
def dynamic_range_compression(db, threshold, ratio, method='downward'): """ Execute dynamic range compression(https://en.wikipedia.org/wiki/Dynamic_range_compression) to dB. :param db: Decibel-scaled magnitudes :param threshold: Threshold dB :param ratio: Compression ratio. :param method: Downwa...
bigcode/self-oss-instruct-sc2-concepts
def fake_get_k8s_obj_always_successful(obj, _): """Mock of get_k8s_obj that always succeeds, returning the requested lightkube object""" return obj
bigcode/self-oss-instruct-sc2-concepts
def is_multiline(string: str) -> bool: """Check whether a string consists of multiple lines.""" return "\n" in string
bigcode/self-oss-instruct-sc2-concepts
import requests def download_dff(url, path): """Downloads a missing DFF from the specified URL to a given FS path.""" resp = requests.get(url, stream=True) if resp.status_code != 200: print('DFF %s not found' % url) return False with open(path, 'wb') as fp: for chunk in resp.it...
bigcode/self-oss-instruct-sc2-concepts
import re def replace_fullwidth_alpha_numeral_to_halfwidth(text: str): """ Replace full-width alpha-numeral characters to half-width characters. Args: text (str): Text to replace. Returns: str: Replaced text. """ return re.sub(r'[A-Za-z0-9]', lambda mathobj: chr(ord(mathobj.g...
bigcode/self-oss-instruct-sc2-concepts
import math def qsub_format_memory(n): """Format memory in bytes for use in qsub resources.""" if n >= 10 * (1024 ** 3): return "%dGB" % math.ceil(n / (1024 ** 3)) if n >= 10 * (1024 ** 2): return "%dMB" % math.ceil(n / (1024 ** 2)) if n >= 10 * 1024: return "%dkB" % math.ceil(...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def get_mode(mode: str, line: str) -> Tuple[str, bool]: """Get the mode of the map. Args: mode (str): the current mode line (str): the line to check Returns: str, bool: the new mode, if the mode has changed """ if line == "" or line[0] == "#": ...
bigcode/self-oss-instruct-sc2-concepts
def TAny(_): """Accepts any value. """ return True
bigcode/self-oss-instruct-sc2-concepts
def argwhere_to_tuples(argwhere_array): """ Converts the output locations array of np.argwhere(...) to a list of tuples. :param argwhere_array: Output of np.argwhere(...). :return: List of tuples, each tuple representing one argwhere position. """ return [tuple(x) for x in argwhere_array]
bigcode/self-oss-instruct-sc2-concepts
def get_future_suppression_from_r0(R0, scenario): """ Returns the future suppression level for a given R0 and a "future scenario". Parameters ---------- R0:float Reproduction number scenario: str 'no_intervention', 'flatten_the_curve', 'social_distancing'. Returns -----...
bigcode/self-oss-instruct-sc2-concepts
def split_by_comma(line): """ Converts the given line of text into comma-delimited tokens :param line: the line of text to process :return: an array of tokens contained in the line of text """ return line.split(",")
bigcode/self-oss-instruct-sc2-concepts
import ast def parse_migration(f): """ Parse migration file and return (frozen_models, complete_apps). The returned objects are full-fledged Python data structures, as if we actually imported the migration file. But because we use ast.literal_eval(), this is safe to run on untrusted code. """...
bigcode/self-oss-instruct-sc2-concepts
def set_conn_string(server, db_name, username, password): """ Sets connection string to SSAS database, in this case designed for Azure Analysis Services """ conn_string = ( "Provider=MSOLAP;Data Source={};Initial Catalog={};User ID={};" "Password={};Persist Security Info=True;Impers...
bigcode/self-oss-instruct-sc2-concepts
def _is_number(s: str) -> bool: # pylint: disable=invalid-name """Return True if string is a number.""" return s.replace(".", "", 1).isdigit()
bigcode/self-oss-instruct-sc2-concepts
def safe_int(string_, default=1): """Convert a string into a integer. If the conversion fails, return the default value. """ try: ret = int(float(string_)) except ValueError: return default else: return ret
bigcode/self-oss-instruct-sc2-concepts
def reverse_bits(x, n): """reverse n bits of x""" rev = 0 for i in range(n): rev = (rev << 1) + (x & 1) x >>= 1 return rev
bigcode/self-oss-instruct-sc2-concepts
def noop(sample, feat_idxs): """Don't expand.""" return []
bigcode/self-oss-instruct-sc2-concepts
def get_approvals_from_scrape(soup): """Take a BeautifulSouped page and return a clean list of all approval dates.""" table = soup.find('table', attrs={'class':'approvals'}) approvals = [] if table: for tr in table.find_all('tr'): country = tr.find('th') date = tr.find('t...
bigcode/self-oss-instruct-sc2-concepts
import csv def write_colocated_gates(coloc_gates, fname): """ Writes the position of gates colocated with two radars Parameters ---------- coloc_gates : dict dictionary containing the colocated gates parameters fname : str file name where to store the data Returns ---...
bigcode/self-oss-instruct-sc2-concepts
def winners(metrics, metric_name, point_values): """Awards points to the top scoring users in a particular metric point_values should be a list of point values like [1000, 500, 200]. In this example, 1000 points are awarded to the top scoring member, 500 to the second place, and 200 to the third. Any n...
bigcode/self-oss-instruct-sc2-concepts
def rgb2hex(colorin): """ Convert (r,g,b) to hex """ r = int(colorin.split('(')[1].split(')')[0].split(',')[0]) g = int(colorin.split('(')[1].split(')')[0].split(',')[1]) b = int(colorin.split('(')[1].split(')')[0].split(',')[2]) return "#{:02x}{:02x}{:02x}".format(r,g,b)
bigcode/self-oss-instruct-sc2-concepts
def count_groups(generator): """ Count the number of distinct elements in the stream, assuming that the elements come in groups. For example: >>> each(1, 2, 1, 10, 10, 5, 5) >> count_groups() 5 """ # Instead of using a sentinel value, just look at the first value output by # the...
bigcode/self-oss-instruct-sc2-concepts
def GetDetailedHelpForRemoveIamPolicyBinding(collection, example_id, role='roles/editor'): """Returns a detailed_help for a remove-iam-policy-binding command. Args: collection: Name of the command collection (ex: "project", "dataset") example_id: Collection iden...
bigcode/self-oss-instruct-sc2-concepts
def simple_function(x): """Docstring.""" return x # comment
bigcode/self-oss-instruct-sc2-concepts
import json def load_coupling(name): """ Loads the coupling map that is given as a json file from a subfolder named layouts Args: name (string): name of the coupling map that was used when saving (corresponds to the filename without the extension .json) Returns: ...
bigcode/self-oss-instruct-sc2-concepts
import functools def deep_merge(*args): """Deep merge multiple dictionaries. >>> value_1 = { 'a': [1, 2], 'b': {'c': 1, 'z': [5, 6]}, 'e': {'f': {'g': {}}}, 'm': 1, } >>> value_2 = { 'a': [3, 4], 'b': {'d': 2, 'z': [7]}, 'e': {'f': {'h': 1}}, 'm': [1],...
bigcode/self-oss-instruct-sc2-concepts
def str_to_bool(string): """Convert a string to a boolean value.""" if string.upper() in ["1", "ON", "TRUE", "YES"]: return True return False
bigcode/self-oss-instruct-sc2-concepts
def _get_QCheckTreeWidget(self): """ Get currently checked values in QCheckTreeWidget via re-mapping filter. Selected values are returned as a list. """ return [self._get_map(s) for s in self._checked_item_cache]
bigcode/self-oss-instruct-sc2-concepts
def transpose(xs): """ Transpose a matrix """ return map(list, zip(*xs))
bigcode/self-oss-instruct-sc2-concepts
def remove_prefix(text: str, prefix: str) -> str: """ Removes the prefix from the beginning of the text if the text starts with the prefix :param str text: text that potentially starts with a prefix :param str prefix: prefix that the text potentially starts with :return: the text with stripped pref...
bigcode/self-oss-instruct-sc2-concepts
def recognize_destination(line: str) -> bool: """ Recognizes .po file target string. """ if line.startswith("msgstr"): return True return False
bigcode/self-oss-instruct-sc2-concepts
def flatten_list_prime(l): """ Flattens a list so that all prime numbers in embedded lists are returned in a flat list Parameters: - l: a list of numbers; largest prime cannot be greater than 1000 Returns: - flat_l: a flat list that has all the prime numbers in l ...
bigcode/self-oss-instruct-sc2-concepts
def ignore_background(array, num_classes, ignore=0): """ :param array: [*],values in [0,num_classes) :param num_classes: C :param ignore: ignore value of background, here is 0 :return: [*] which ignore_index=num_classes """ array[array == ignore] = -1 array[array > ignore] -= 1 retur...
bigcode/self-oss-instruct-sc2-concepts
def apply_iam_bindings_patch(current_policy, bindings_patch, action): """ Patches the current policy with the supplied patch. action can be add or remove. """ for item in bindings_patch['bindings']: members = item['members'] roles = item['roles'] for role in roles: if role not in current_pol...
bigcode/self-oss-instruct-sc2-concepts
import inspect from typing import Callable import gc def func_in_frame_info(frame_info: inspect.FrameInfo) -> Callable: """Find callable corresponding to given frame_info.""" f_code = frame_info.frame.f_code for obj in gc.get_referrers(f_code): if hasattr(obj, '__code__') and obj.__code__ is f_cod...
bigcode/self-oss-instruct-sc2-concepts
def convertType(pair: tuple): """Convert items to the appropriate types Arguments: pair: A tuple containing 2 items Returns: pair: A tuple containing 2 items where the second item is converted to the appropriate types """ # If it is not a pair if len(pair) != 2: ...
bigcode/self-oss-instruct-sc2-concepts
def header(text, color='black'): """Create an HTML header""" raw_html = f'<h1 style="margin-top:12px;color: {color};font-size:54px"><center>' + str( text) + '</center></h1>' return raw_html
bigcode/self-oss-instruct-sc2-concepts
import json def load_json(location): """ Read JSON file at `location` and return a list of ordered dicts, one for each entry. """ with open(location) as json_file: results = json.load(json_file) if isinstance(results, list): results = sorted(results) else: results =...
bigcode/self-oss-instruct-sc2-concepts
def gateway_environment(gateway_environment): """Enables path routing on gateway""" gateway_environment.update({"APICAST_PATH_ROUTING": True}) return gateway_environment
bigcode/self-oss-instruct-sc2-concepts
def merge_words(current_words, new_words): """ Determine words to add and delete for words update. Parameters: list(dict). Currently existing words list(dict). Words after update Return: list(dict). Words to keep list(dict). Words to remove ...
bigcode/self-oss-instruct-sc2-concepts