seed
stringlengths
1
14k
source
stringclasses
2 values
def _bbox(pts): """Find the AABB bounding box for a set of points""" x, y = pts[0] ax, ay, bx, by = x, y, x, y for i in range(1, len(pts)): x, y = pts[i] ax = x if x < ax else ax ay = y if y < ay else ay bx = x if x > bx else bx by = y if y > by else by return...
bigcode/self-oss-instruct-sc2-concepts
import math def rnd(x): """ Round a number so that the output SVG doesn't have unneeded precision """ digits = 6 if x == 0 or not math.isfinite(x): return x digits -= math.ceil(math.log10(abs(x))) return round(x, digits)
bigcode/self-oss-instruct-sc2-concepts
import requests def store_document(url, document): """ Stores a document in the database :param url: the base url of the REST server :param document: document string :returns response.text: document_id is returned if successful """ url += "/documents" headers = {"Content-Type": "appli...
bigcode/self-oss-instruct-sc2-concepts
def is_positive(example): """ Check if the example is positive. :param example: the example :type example: Atom :return: `True` if the example is positive; otherwise, `False` :rtype: bool """ return example.weight > 0.0
bigcode/self-oss-instruct-sc2-concepts
import random def odds(poweroftwo): """ Return True with odds 2**-poweroftwo , else False For example, odds(2) will be True roughly 1/4 of the time, odds(3) will be True about 1/8 of the time, and so on. """ # # To test this look at for example this count of the errors # >> (a,b)...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Any import ipaddress def check_ip(val: Union[str, Any]) -> Any: """ Function to check whether a value is valid ip address """ try: return bool(ipaddress.ip_address(val)) except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
import math def entropy(probabilities): """ Calcola entropia della distribuzione di probabilità :param probabilities: lista contenente una distribuzione di probabilità :return: valore dell'entropia relativa alla distribuzione in input """ entropy = 0.0 for i in range(len(probabilities)): entropy += probabil...
bigcode/self-oss-instruct-sc2-concepts
def TENSOR_AXIS_IN_RANGE_APPLY_FILTER(arg_values): """Ensures the axis is less than the rank of the tensor.""" tensor, axis = arg_values return axis.value < len(tensor.shape)
bigcode/self-oss-instruct-sc2-concepts
import re def has_ancillary_files(source_type: str) -> bool: """Check source type for indication of ancillary files.""" if not source_type: return False return re.search('A', source_type, re.IGNORECASE) is not None
bigcode/self-oss-instruct-sc2-concepts
def safefloat(value): """safely converts value to float or none""" try: return float(value) except ValueError: return None
bigcode/self-oss-instruct-sc2-concepts
def get_bit(number, position): """Returns the bit at the given position of the given number. The position is counted starting from the left in the binary representation (from the most significant to the least significant bit). """ if position < 0 or position > 31: return 0 return (number...
bigcode/self-oss-instruct-sc2-concepts
def reverse(t): """Return a tuple with reversed order""" return tuple([t[i] for i in range(len(t)-1, 0, -1)])
bigcode/self-oss-instruct-sc2-concepts
import glob def number_of_netcdf_files(source_dir): """ Counts the number of netcdf files in the given directory :param source_dir: :return: """ netcdf_pattern = source_dir + "/*.nc" netcdf_list=sorted(glob.glob(netcdf_pattern)) return len(netcdf_list)
bigcode/self-oss-instruct-sc2-concepts
def parse_access_variable(v): """ Parses the accessibility arguments from a variable anme. Should be structued as <variable_name>_<dir>_within<travel_time>_mode. For example: `sb_jobs_sector92_to_within20_OpAuto`: - variable: sb_jobs_sector92 - direction: travel towards the zone ...
bigcode/self-oss-instruct-sc2-concepts
import struct def _encode_int64(value: int) -> bytes: """Encodes an int64 in big-endian stripping leading zeros.""" return struct.pack(">Q", value).lstrip(b"\x00")
bigcode/self-oss-instruct-sc2-concepts
def intersect(a, b): """Find intersection of two lists, sequences, etc. Returns a list that includes repetitions if they occur in the inputs.""" return [e for e in a if e in b]
bigcode/self-oss-instruct-sc2-concepts
def mask_deltar_first(backend, objs1, mask1, objs2, mask2, drcut): """Masks objects in the first collection that are closer than drcut to objects in the second collection according to dR=sqrt(dEta^2 + dPhi^2) Args: backend (library): either hepaccelerate.backend_cpu or hepaccelerate.backend_cud...
bigcode/self-oss-instruct-sc2-concepts
def running_paren_sums(program): """ Map the lines in the list *program* to a list whose entries contain a running sum of the per-line difference between the number of '(' and the number of ')'. """ count_open_parens = lambda line: line.count('(') - line.count(')') paren_counts = map(count_o...
bigcode/self-oss-instruct-sc2-concepts
def pretty_str_time(dt): """Get a pretty string for the given datetime object. Parameters ---------- dt : :obj:`datetime` A datetime object to format. Returns ------- :obj:`str` The `datetime` formatted as {year}_{month}_{day}_{hour}_{minute}. """ return "{0...
bigcode/self-oss-instruct-sc2-concepts
import json def getNodeGroups(session, url, details=False): """ Return a list of node group objects (by the index endpoint). Passing details=True will get all information for each node group. """ groups = [] page = 1 per_page = 100 done = False while not done: new_node_gr...
bigcode/self-oss-instruct-sc2-concepts
import threading def synchronized(func): """synchronized decorator function This method allows the ability to add @synchronized decorator to any method. This method will wrap the decorated function around a call to threading.Lock ensuring only a single execution of the decorated method/line of co...
bigcode/self-oss-instruct-sc2-concepts
def strip_definition_from_video(vid_id): """Strip any sort of HD tag from the video""" hd = ['[HD]', '[FHD]', '[SD]', '(SD)', '(HD)', '(FHD)'] for item in hd: vid_id = vid_id.replace(item, '') return vid_id
bigcode/self-oss-instruct-sc2-concepts
def skipHeader(infile): """ skip the lines beginning with a '!' """ ## find where the header ends counter = 0 while infile.readline().startswith("!"): counter += 1 ## reposition the file iterator infile.seek(0) for i in range(0, counter): infile.readline() return infile
bigcode/self-oss-instruct-sc2-concepts
def sexpr_print_sexpr(sexpr): """Prints a python S-expression as a string S-expression.""" if isinstance(sexpr, str): return sexpr elif isinstance(sexpr, int): return str(sexpr) elif isinstance(sexpr, tuple): assert len(sexpr) > 1, sexpr parts = map(sexpr_print_sexpr, sex...
bigcode/self-oss-instruct-sc2-concepts
def find_pivot(input_list): """Find the pivot point of the sorted yet "shifted" list. A simple divide and conquer strategy to find the pivot point of the list. Time complexity O(log n) :param input_list: a sorted and pivoted list (i.e. "shifted") :type input_list: list :return: an index of th...
bigcode/self-oss-instruct-sc2-concepts
import sympy def jacobian(expr, symbols): """ Derive a symbolic expr w.r.t. each symbol in symbols. This returns a symbolic jacobian vector. :param expr: A sympy Expr. :param symbols: The symbols w.r.t. which to derive. """ jac = [] for symbol in symbols: # Differentiate to every ...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_track_info(url): """ Get the track info of the passed URL. """ _client_ID = "LvWovRaJZlWCHql0bISuum8Bd2KX79mb" api = "http://api.soundcloud.com/resolve.json?url={}&client_id={}" URL = api.format(url, _client_ID) r = requests.get(URL).json() title = r["title"] ...
bigcode/self-oss-instruct-sc2-concepts
def bmi(W, H): """ Body Mass Index Calculator Calculates the BMI Algorithm: https://www.cdc.gov/healthyweight/assessing/bmi/childrens_bmi/childrens_bmi_formula.html :return: The BMI in kg/m^2 :rtype: float """ res = 703.0*W/(H*H) return res
bigcode/self-oss-instruct-sc2-concepts
def append_s(value): """ Adds the possessive s after a string. value = 'Hans' becomes Hans' and value = 'Susi' becomes Susi's """ if value.endswith('s'): return u"{0}'".format(value) else: return u"{0}'s".format(value)
bigcode/self-oss-instruct-sc2-concepts
def _zone(index): """Chooses a GCP zone based on the index.""" if index < 6: return 'us-central1-a' elif index < 12: return 'us-east1-b' elif index < 18: return 'us-east4-c' elif index < 24: return 'us-west2-a' else: raise ValueError('Unhandled zone index')
bigcode/self-oss-instruct-sc2-concepts
import torch def change_box_order(boxes, order, dim=-1): """Change box order between (x_min, y_min, x_max, y_max) and (x_center, y_center, width, height). Args: boxes: (tensor) bounding boxes, sized [N, 4]. order: (str) either 'xyxy2xywh' or 'xywh2xyxy'. Returns: (tensor) converted bou...
bigcode/self-oss-instruct-sc2-concepts
def clip(text, max_len=80): """Return max_len characters clipped at space if possible""" text = text.rstrip() if len(text) <= max_len or ' ' not in text: return text end = len(text) space_at = text.rfind(' ', 0, max_len + 1) if space_at >= 0: end = space_at else: spac...
bigcode/self-oss-instruct-sc2-concepts
def gq_add_vertex_collection(coll): """Create the gremlin query that creates a Vertex for a collection in the Tree Entry table """ name = coll.entry.container.split('/')[-1] if not name: # root name = '/' query = "graph.addVertex(T.label, 'collection', " query += "'name', '{}', ...
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_clifford_table(picklefile='cliffords2.pickle'): """ Load pickled files of the tables of 1 and 2 qubit Clifford tables. Args: picklefile - pickle file name. Returns: A table of 1 and 2 qubit Clifford gates. """ with open(picklefile, "rb") as ...
bigcode/self-oss-instruct-sc2-concepts
import ast def format_nasdaq(companies): """ Convert the parsed companies list to format that is interpretable by dash_core_components.dropdown """ companies_list = ast.literal_eval(companies) options=[] # Get the company name and symbol. for i in range(len(companies_list)): new_co...
bigcode/self-oss-instruct-sc2-concepts
def make_coordinates(df, index_col='index'): """ Formats a geopandas.GeoDataFrame (from a shapefile that contains junction information) to a coordinate table. Parameters ---------- catchments : geopandas.GeoDataFrame Must contain a geometry field with points. index_col : str ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import List def lst_inc(inc: Sequence, seq: Sequence) -> List: """ Returns the intersection of two sequences. Similar to the built-in method ``set.intersection``, but duplicate (non-unique) items are not discarded. Args: inc: Sequence E...
bigcode/self-oss-instruct-sc2-concepts
def _strip_or_pad_version(version, num_components): """Strips or pads a version string to the given number of components. If the version string contains fewer than the requested number of components, it will be padded with zeros. Args: version: The version string. num_components: The d...
bigcode/self-oss-instruct-sc2-concepts
def _block_format_index(index): """ Convert a list of indices ``[0, 1, 2]`` into ``"arrays[0][1][2]"``. """ idx_str = ''.join('[{}]'.format(i) for i in index if i is not None) return 'arrays' + idx_str
bigcode/self-oss-instruct-sc2-concepts
def urljoin(*path): """Joins the passed string parts into a one string url""" return '/'.join((part.strip('/') for part in path))
bigcode/self-oss-instruct-sc2-concepts
def euler14(lim=1000000): """Solution for problem 14.""" collatz = {1: 1} for i in range(2, lim): if i not in collatz: chain = [] while i not in collatz: chain.append(i) i = (3 * i + 1) if i % 2 else (i // 2) stop = collatz[i] + 1 ...
bigcode/self-oss-instruct-sc2-concepts
def check_rule(m, number, board, row, col): """ 如果遵循每一行,每一列,每一区域都包含1-9数字,且不重复的规则,返回真 number: 被校验的数字 board: 当前九宫格所有的元素(9x9的二维列表) row, col: 当前行数,当前列数 """ flag = True # 检查行 if number in board[row]: flag = False # 检查列 if not all([row[col] != number for row in board])...
bigcode/self-oss-instruct-sc2-concepts
import six def dtype(spec): """ Allow Python 2/3 compatibility with Numpy's dtype argument. Relevant issue: https://github.com/numpy/numpy/issues/2407 """ if six.PY2: return [(str(n), str(t) if type(t)==type else t) for n, t in spec] else: return spec
bigcode/self-oss-instruct-sc2-concepts
def get_collection_keys(cleaned_zot_files): """ Gets the collection (folder) id keys for each entry in the cleaned Zotero files """ col_keys = [] if 'collections' in cleaned_zot_files['data'].keys(): if len(cleaned_zot_files['data']['collections']) > 1: for i in cleaned_zot_files...
bigcode/self-oss-instruct-sc2-concepts
def find_all_stacktraces(data): """Given a data dictionary from an event this returns all relevant stacktraces in a list. If a frame contains a raw_stacktrace property it's preferred over the processed one. """ rv = [] def _probe_for_stacktrace(container): raw = container.get('raw_stac...
bigcode/self-oss-instruct-sc2-concepts
def ensure_dtype(data): """ To ensure that input file and output file are comparable, data types should be the same in all files. #Input: @data: pandas DataFrame #Output: @data_trans: transformed pandas DataFrame with corrected dtype """ # dtypes taken from Hestia website data_tr...
bigcode/self-oss-instruct-sc2-concepts
def is_equal_strings_ignore_case(first, second): """The function compares strings ignoring case""" if first and second: return first.upper() == second.upper() else: return not (first or second)
bigcode/self-oss-instruct-sc2-concepts
def is_interval_subset(interval1, interval2): """Checks whether interval1 is subset of interval2.""" # Check the upper bound. if (interval1[1] == "inf" and interval2[1] != "inf") or \ (interval1[1] != "inf" and interval2[1] != "inf" and interval1[1] > interval2[1]): return False # C...
bigcode/self-oss-instruct-sc2-concepts
def find_nested_attr(config, attr): """ Takes a config dictionary and an attribute string as input and tries to find the attribute in the dictionary. The attribute may use dots to indicate levels of depth within the dictionary. Example: find_nested_attr({'one': {'two': {'three': 3}}}, 'one.two....
bigcode/self-oss-instruct-sc2-concepts
def insertion_sort(array): """ Insertion sort implementation Arguments: - array : (int[]) array of int to sort Returns: - array : (int[]) sorted numbers """ for i in range(len(array)): j = i while j > 0 and array[j] < array[j-1]: array[j], array[j-1] = a...
bigcode/self-oss-instruct-sc2-concepts
def decimal_to_binary(num): """Convert a Decimal Number to a Binary Number.""" binary = [] while num > 0: binary.insert(0, num % 2) num >>= 1 return "".join(str(e) for e in binary)
bigcode/self-oss-instruct-sc2-concepts
def simple_fill(text:str, width:int=60) -> str: """ Split `text` into equal-sized chunks of length `width` This is a simplified version of `textwrap.fill`. The code is adapted from: http://stackoverflow.com/questions/11781261 Parameters ---------- text : string The text to split ...
bigcode/self-oss-instruct-sc2-concepts
def prod(a, b): """ Example operator function. Takes in two integers, returns their product. """ return a * b
bigcode/self-oss-instruct-sc2-concepts
def get_decrypted_file_path(enc_file, config): """ returns the path to the decrypted copy of the file """ result = enc_file.replace('.gpg','').replace(config.enc_mainfolder + '/', '').replace('_HOME', '$HOME') return result
bigcode/self-oss-instruct-sc2-concepts
def assertWrapperExceptionTypes(self, deferred, mainType, reasonTypes): """ Assert that the given L{Deferred} fails with the exception given by C{mainType} and that the exceptions wrapped by the instance of C{mainType} it fails with match the list of exception types given by C{reasonTypes}. This is...
bigcode/self-oss-instruct-sc2-concepts
def extract_pairs(data_list, tag='mean_trajectory_return'): """Extract data from positive and negative alpha evaluations. Args: data_list: A list of dictionaries with data. Dictionary should contain 'pos' and 'neg' keys which represent going forward and backward in the parameter space. Each key sho...
bigcode/self-oss-instruct-sc2-concepts
import copy def calibrate_mp(pixel): """ This is a helper function in order to use multiprocessing to invoke the calibrate() method for an array of Pilatus_Pixel objects. """ pixel.calibrate() return copy.copy(pixel)
bigcode/self-oss-instruct-sc2-concepts
import torch def symsqrt(matrix): """ Compute the square root of a positive definite matrix. Retrieved from https://github.com/pytorch/pytorch/issues/25481#issuecomment-544465798. """ _, s, v = matrix.svd() # truncate small components above_cutoff = s > s.max() * s.size(-1) * torch.finfo(s...
bigcode/self-oss-instruct-sc2-concepts
from typing import Collection def A000120(start: int = 0, limit: int = 20) -> Collection[int]: """1's-counting sequence: number of 1's in binary expansion of n (or the binary weight of n). """ return ["{:b}".format(n).count("1") for n in range(start, start + limit)]
bigcode/self-oss-instruct-sc2-concepts
def _telegram_escaped_string(s): """Replaces characters in a string for Markdown V2.""" for c in "_*[]()~>#+-=|{}.!": s = s.replace(c, "\\" + c) return s
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def get_anterior_datetime(offset = 300): """ Returns an anterior date given an offset time in seconds :param offset: offset interval in seconds (default: 300s) :return datetime: the anterior datetime :raises Exception: Invalid time offset """ if off...
bigcode/self-oss-instruct-sc2-concepts
def is_palindromic(input_string): """Return True if input string is a palindromic""" return input_string == input_string[::-1]
bigcode/self-oss-instruct-sc2-concepts
def gmx_bonds_func_1(x, a, b, c): """ Gromacs potential function 1 for bonds. """ return a / 2 * (x - b) ** 2 + c
bigcode/self-oss-instruct-sc2-concepts
import math def gammanu_to_tthphi(gamma, nu): """Transfer gamma-nu to ttheta-phi. gamma is the angle in the equatorial plane nu is the angle between equatorial plane and scattering neutron [-pi/2, pi/2] return ttheta is diffraction angle phi is polar angle ...
bigcode/self-oss-instruct-sc2-concepts
import struct def SetVersionBit(protocol=1): """Generate the Version bit""" return struct.pack("<B", protocol)
bigcode/self-oss-instruct-sc2-concepts
def build_pathnet_graph(p_inputs, p_labels, p_task_id, pathnet, training): """Builds a PathNet graph, returns input placeholders and output tensors. Args: p_inputs: (tf.placeholder) placeholder for the input image. p_labels: (tf.placeholder) placeholder for the target labels. p_task_id: (tf.placeholder...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def store_secret(tmp_path: Path, name: str, secret: bytes) -> Path: """Store a secret in a temporary path. Parameters ---------- tmp_path : `pathlib.Path` The root of the temporary area. name : `str` The name of the secret to construct nice file names. ...
bigcode/self-oss-instruct-sc2-concepts
import textwrap def wrap_summary(summary, initial_indent, subsequent_indent, wrap_length): """Return line-wrapped summary text.""" if wrap_length > 0: return '\n'.join( textwrap.wrap(summary, width=wrap_length, initial_indent=initial_inde...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Union def wipe_empty_fields(card: List[Union[str, int, float, None]]) -> List[Union[str, int, float, None]]: """ Removes any trailing Nones from the card. Also converts empty strings to None. Allows floats & ints, but that's not the intended value, though...
bigcode/self-oss-instruct-sc2-concepts
def reuss_avg(M1, M2, f1, f2): """ Reuss average for a 2 mineral mixture Usage: M = reuss_avg(M1, M2, f1, f2) Inputs: M1 & M2 = Elastic moduli for each phase (float) f1 & f1 = Volume fraction of each phase (float) Output: M = Reuss average of elastic moduli (float)...
bigcode/self-oss-instruct-sc2-concepts
import six import re def keys_by_pattern_dict(in_dict, patterns, matchs=None): """ Recursive dictionary lookup by regex pattern. Args: in_dict (dict): Input dict. patterns (list): Lookup regex pattern list. matchs (list): Match accumulator (recursive call only). ...
bigcode/self-oss-instruct-sc2-concepts
def add_cushions(table): """ Add space to start and end of each string in a list of lists Parameters ---------- table : list of lists of str A table of rows of strings. For example:: [ ['dog', 'cat', 'bicycle'], ['mouse', trumpet', ''] ...
bigcode/self-oss-instruct-sc2-concepts
def WmiBaseClasses(connWmi, className): """ This returns the base classes of a WMI class. """ # Adds the qualifiers of this class. klassObj = getattr( connWmi, className ) # It always work even if there is no object. return klassObj.derivation()
bigcode/self-oss-instruct-sc2-concepts
import re def validate_rdm_string(ops: str) -> str: """Check that a string for rdms are valid. Args: ops (str): String expression to be computed. Returns (str): Either 'element' or 'tensor'. """ qftops = ops.split() nops = len(qftops) assert (nops % 2) == 0 if any(...
bigcode/self-oss-instruct-sc2-concepts
def ete_dendrogram(corpus, tree, outputfile=None, fontsize=5, save_newick=True, mode='c', show=False, color_leafs=False, save=False, return_svg=True): """ Draw a dendrogram of the texts in the corpus using ETE. Parameters ---------- corpus : `Corpus` instan...
bigcode/self-oss-instruct-sc2-concepts
def is_loc_free(loc, tile_grid): """ Checks whether a location in the given tilegrid is free. """ if loc not in tile_grid: return True if tile_grid[loc] is None: return True return False
bigcode/self-oss-instruct-sc2-concepts
import string def _default_devour(text): """ The default devour function (strips out whitespace). """ i = 0 while i < len(text) and text[i] in string.whitespace: i += 1 return text[i:]
bigcode/self-oss-instruct-sc2-concepts
def heading(text, level): """ Return a ReST heading at a given level. Follows the style in the Python documentation guide, see <https://devguide.python.org/documenting/#sections>. """ assert 1 <= level <= 6 chars = ("#", "*", "=", "-", "^", '"') line = chars[level] * len(text) re...
bigcode/self-oss-instruct-sc2-concepts
import json def _str_to_tiptap_markup(text): """Convert a plain text string into a TipTap-compatible markup structure""" return json.dumps( { 'type': 'doc', 'content': [ {'type': 'paragraph', 'content': [{'type': 'text', 'text': paragraph}]} for ...
bigcode/self-oss-instruct-sc2-concepts
import re def remove_from_text(raw_text: str, symbols: list) -> str: """ Removes every symbol/character in the given symbols list from a given string, raw_text. """ return re.sub("|".join(symbols), "", raw_text)
bigcode/self-oss-instruct-sc2-concepts
def get_factors(x): """Returns a list of factors of given number x.""" factors = [] #iterate over range from 1 to number x for i in range(1, x+1): #check if i divide by number x evenly if (x % i == 0): factors.append(i) return factors
bigcode/self-oss-instruct-sc2-concepts
def root_node_only_token_stream(request): """ Fixture that yields strings that will generate a token stream that creates a single root node. """ return request.param
bigcode/self-oss-instruct-sc2-concepts
def _read_config(filename): """ Read config file into `c`. Variables in config file are formatted as `KEY=VALUE`. """ c = {} with open(filename, "r") as f: for line in f: key, val = line.split("=") key = key.strip() val = val.strip() c[key...
bigcode/self-oss-instruct-sc2-concepts
def is_business_type(business_type_choice, on_default_path=False): """Returns a function to assert whether the wizard step should be shown based on the business type selected. The `on_default_path` allows the returned function to return a default value if the business type hasn't been filled in yet. Th...
bigcode/self-oss-instruct-sc2-concepts
import re def natural_sort_key(sort_key, _nsre=re.compile('([0-9]+)')): """ Pass to ``key`` for ``str.sort`` to achieve natural sorting. For example, ``["2", "11", "1"]`` will be sorted to ``["1", "2", "11"]`` instead of ``["1", "11", "2"]`` :param sort_key: Original key to be processed :retur...
bigcode/self-oss-instruct-sc2-concepts
def contains_digit(text): """Returns true if any digits exist in the text""" return any(c.isdigit() for c in text)
bigcode/self-oss-instruct-sc2-concepts
def many_any(lst, k): """ Returns True if at least k elements of lst are True; otherwise False. Do this in one line for extra credit. Hint: use a list comprehension. Example: >>> many_any([True, True, False, True], 3) True >>> many_any([True, True, False, False], 3) False """ re...
bigcode/self-oss-instruct-sc2-concepts
import math def largest_numeric_increase_infant_mortality(data_by_country): """ Which country had the largest increase in Infant mortality for both sexes from 2005 to 2015? Parameters: data_by_country: dictionary with different data for countries. Returns: Tuple(String, String) - (Qu...
bigcode/self-oss-instruct-sc2-concepts
def collect_reducer_count(values): """Return the number of values >>> collect_reducer_count(['Sheep', 'Elephant', 'Wolf', 'Dog']) 4 """ return len(values)
bigcode/self-oss-instruct-sc2-concepts
import secrets def generate_token(length : int=32) -> str: """ Uses the secrets.token_hex() method to generate a a hexidecimal token Parameters ---------- length : int The desired length of token Returns ------- str The hexidecimal string generated by Pyth...
bigcode/self-oss-instruct-sc2-concepts
def B(value): """Returns 1 if value is truthy, 0 otherwise.""" return 1 if value else 0
bigcode/self-oss-instruct-sc2-concepts
def leading(value): """ Strip all leading whitespaces. :param value: The value :type value: str :return: The value with all leading whitespaces removed :rtype: str """ return value.lstrip()
bigcode/self-oss-instruct-sc2-concepts
def box_text(text, width, offset=0): """ Return text inside an ascii textbox """ box = " " * offset + "-" * (width + 2) + "\n" box += " " * offset + "|" + text.center(width) + "|" + "\n" box += " " * offset + "-" * (width + 2) return box
bigcode/self-oss-instruct-sc2-concepts
def add_class(form_widget, css_class): """ Adds a css class to a django form widget """ return form_widget.as_widget(attrs={'class': css_class})
bigcode/self-oss-instruct-sc2-concepts
def get_thresholds(threshs_d: dict) -> tuple: """ Parameters ---------- threshs_d : dict Thresholds configs Returns ------- names : list Name for the threshold thresh_sam : int Samples threshold thresh_feat : int Features threshold """ names ...
bigcode/self-oss-instruct-sc2-concepts
def _field_name_grib1_to_grib2(field_name_grib1): """Converts field name from grib1 to grib2. :param field_name_grib1: Field name in grib1 format. :return: field_name_grib2: Field name in grib2 format. """ return field_name_grib1.replace('gnd', 'ground').replace('sfc', 'surface')
bigcode/self-oss-instruct-sc2-concepts
def get_descriptors(image, filtered_coords, wid=5): """ For each point return, pixel values around the point using a neighbourhood of width 2*wid+1. (Assume points are extracted with min_distance > wid). """ desc = [] for coords in filtered_coords: patch = image[coords[0]-wid:coords[0]+wid+...
bigcode/self-oss-instruct-sc2-concepts
def write_to_file(filepath, data_to_write): """ TO DO: This function takes any <data_to_write>, converts it into a string via the str() function (if possible), and then writes it to a file located at <filepath>. Note that this function is a general writing function. It should not use the .csv mo...
bigcode/self-oss-instruct-sc2-concepts
def callback_ResetDropdown(window): """ Updates the dropdown after newVal is selected and applied Parameters ------------- window = GUI object Returns None ------------- """ # set values and value to empty to get rid of previously specified answers window['changeMod'].update('C...
bigcode/self-oss-instruct-sc2-concepts
def dice_jaccard(y_true, y_pred, smooth=1, thr=None): """ Computes Dice and Jaccard coefficients. Args: y_true (ndarray): (H,W)-shaped groundtruth map with binary values (0, 1) y_pred (ndarray): (H,W)-shaped predicted map with values in [0, 1] smooth (int, optional): Smoothing facto...
bigcode/self-oss-instruct-sc2-concepts