seed
stringlengths
1
14k
source
stringclasses
2 values
def trim_description(desc: str, n_words: int) -> str: """Return the first `n_words` words of description `desc`/""" return " ".join(str(desc).split(" ")[0:n_words])
bigcode/self-oss-instruct-sc2-concepts
def ahs_url_helper(build_url, config, args): """Based on the configured year, get the version arg and replace it into the URL.""" version = config["years"][args["year"]] url = build_url url = url.replace("__ver__", version) return [url]
bigcode/self-oss-instruct-sc2-concepts
import uuid import json def create_event(_action, _data): """ Create an event. :param _action: The event action. :param _data: A dict with the event data. :return: A dict with the event information. """ return { 'event_id': str(uuid.uuid4()), 'event_action': _action, ...
bigcode/self-oss-instruct-sc2-concepts
def level_up_reward(level, new_level): """ Coins rewarded when upgrading to new_level. """ coins = 0 while level < new_level: coins += 5 + level // 15 level += 1 return coins
bigcode/self-oss-instruct-sc2-concepts
def substitute_str_idx(s: str, r: str, i: int) -> str: """Substitute char at position Arguments: s: The str in which to substitute r: The char to substitute i: index of the substitution Returns: The string `s` with the i'th char substitute with `r` """ z = ''.join([(lambda: r,...
bigcode/self-oss-instruct-sc2-concepts
def rotate_address(level, address, rotate_num): """Rotates the address with respect to rotational symmetries of SG Args: level: A nonnegative integer representing the level of SG we're working with. address: np.array of size (level+1) representing the address vector of...
bigcode/self-oss-instruct-sc2-concepts
def get_key(file_name): """ Get id from file name """ return file_name.split('-')[0]
bigcode/self-oss-instruct-sc2-concepts
from tabulate import tabulate from typing import List def convert_cross_package_dependencies_to_table( cross_package_dependencies: List[str], markdown: bool = True, ) -> str: """ Converts cross-package dependencies to a markdown table :param cross_package_dependencies: list of cross-package depend...
bigcode/self-oss-instruct-sc2-concepts
def calc_league_points(pos_map, dsq_list): """ A function to work out the league points for each zone, given the rankings within that game. @param pos_map: a dict of position to array of zone numbers. @param dsq_list: a list of zones that shouldn't be awarded league points. @returns: a dict of zone number to leagu...
bigcode/self-oss-instruct-sc2-concepts
def getEnd(timefile, end_ind): """ Parameter ---------- timefile : array-like 1d the timefile. end_ind : integer the end index. Returns ------- the end of the condition. """ return timefile['ConditionTime'][end_ind]
bigcode/self-oss-instruct-sc2-concepts
from typing import List def split_module_names(mod_name: str) -> List[str]: """Return the module and all parent module names. So, if `mod_name` is 'a.b.c', this function will return ['a.b.c', 'a.b', and 'a']. """ out = [mod_name] while '.' in mod_name: mod_name = mod_name.rsplit('.', ...
bigcode/self-oss-instruct-sc2-concepts
def import_class(name): """Import class from string. Args: name (str): class path Example: >>> model_cls = import_class("tfchat.models.PreLNDecoder") """ components = name.split(".") mod = __import__(".".join(components[:-1]), fromlist=[components[-1]]) return getattr(mod, co...
bigcode/self-oss-instruct-sc2-concepts
def is_fractional_es(input_str, short_scale=True): """ This function takes the given text and checks if it is a fraction. Args: text (str): the string to check if fractional short_scale (bool): use short scale if True, long scale if False Returns: (bool) or (float): False if no...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Any from typing import List from typing import Set from typing import Type def _get_overloaded_args(relevant_args: Iterable[Any]) -> List[Any]: """Returns a list of arguments on which to call __torch_function__. Checks arguments in relevant_args for __torch_func...
bigcode/self-oss-instruct-sc2-concepts
def get_view_setting(view, sname, default=None): """Check if a setting is view-specific and only then return its value. Otherwise return `default`. """ s = view.settings() value = s.get(sname) s.erase(sname) value2 = s.get(sname) if value2 == value: return default else: ...
bigcode/self-oss-instruct-sc2-concepts
def strip_comments(lines): """ Returns the lines from a list of a lines with comments and trailing whitespace removed. >>> strip_comments(['abc', ' ', '# def', 'egh ']) ['abc', '', '', 'egh'] It should not remove leading whitespace >>> strip_comments([' bar # baz']) [' bar'] It...
bigcode/self-oss-instruct-sc2-concepts
def find_between(s, first, last): """ Find sting between two sub-strings Args: s: Main string first: first sub-string last: second sub-string Example find_between('[Hello]', '[', ']') -> returns 'Hello' Returns: String between the first and second sub-strings, if any...
bigcode/self-oss-instruct-sc2-concepts
def makeAdder(amount): """Make a function that adds the given amount to a number.""" def addAmount(x): return x + amount return addAmount
bigcode/self-oss-instruct-sc2-concepts
import types import enum def skip_non_methods(app, what, name, obj, skip, options): """ Skip all class members, that are not methods, enum values or inner classes, since other attributes are already documented in the class docstring. """ if skip: return True if what == "class": ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def _answer_types_row(row: Dict[str, str]): """ Transform the keys of each answer-type CSV row. If the CSV headers change, this will make a single place to fix it. """ return { 'k': row['Key'], 'c': row['Choices'], }
bigcode/self-oss-instruct-sc2-concepts
def twos_complement_to_int(val, length=4): """ Two's complement representation to integer. We assume that the number is always negative. 1. Invert all the bits through the number 2. Add one """ invertor = int('1' * length, 2) return -((int(val, 2) ^ invertor) + 1)
bigcode/self-oss-instruct-sc2-concepts
import re import time def wait_for_logs(container, predicate, timeout=None, interval=1): """ Wait for the container to emit logs satisfying the predicate. Parameters ---------- container : DockerContainer Container whose logs to wait for. predicate : callable or str Predicate ...
bigcode/self-oss-instruct-sc2-concepts
import shutil def prepare_empty_dirs(dirs: list): """ 建立空目录。若已经存在,则删除后创建。 parents=True Args: dirs: Path list Returns: dirs 中各个目录的句柄 """ result = [] for d in dirs: if d.exists(): shutil.rmtree(d.as_posix()) d.mkdir(parents=True, exist_ok=Fal...
bigcode/self-oss-instruct-sc2-concepts
def update_header(login_response, call_header): """Function to process and update the header after login""" token = str(login_response).split()[2] + " " + str(login_response).split()[3] call_header['Authorization'] = token return call_header
bigcode/self-oss-instruct-sc2-concepts
import torch def log2(input, *args, **kwargs): """ Returns a new tensor with the logarithm to the base 2 of the elements of ``input``. Examples:: >>> import torch >>> import treetensor.torch as ttorch >>> ttorch.log2(ttorch.tensor([-4.0, -1.0, 0, 2.0, 4.8, 8.0])) tensor([...
bigcode/self-oss-instruct-sc2-concepts
def binary_search(array, x): """ Binary search :param array: array: Must be sorted :param x: value to search :return: position where it is found, -1 if not found """ lower = 0 upper = len(array) while lower < upper: # use < instead of <= mid = lower + (upper - lower) // 2 ...
bigcode/self-oss-instruct-sc2-concepts
def insert_position(player, ship, starting): """Insert a valid position (e.g. B2).""" while True: if starting: position = input(player.name + ", where do you want to place your " + ship[0] + "(" + str(ship[1]) + ")? ").upper() else: position = input(player.name + ", whe...
bigcode/self-oss-instruct-sc2-concepts
def select_longest_utr3_exonic_content(transcripts): """Select transcript(s) with longest UTR3 exonic content""" ret = [transcripts[0]] longest = transcripts[0].utr3_exonic_content_length for i in range(1, len(transcripts)): t = transcripts[i] exonic_content_length = t.utr3_exonic_conte...
bigcode/self-oss-instruct-sc2-concepts
import torch def _moments(a, b, n): """ Computes nth moment of Kumaraswamy using using torch.lgamma """ arg1 = 1 + n / a log_value = torch.lgamma(arg1) + torch.lgamma(b) - torch.lgamma(arg1 + b) return b * torch.exp(log_value)
bigcode/self-oss-instruct-sc2-concepts
def single_byte_xor(byte_array, key_byte): """XOR every byte in 'byte_array' with the 'key_byte'""" result = bytearray() for i in range(0, len(byte_array)): result.append(byte_array[i] ^ key_byte) return result
bigcode/self-oss-instruct-sc2-concepts
def get_region_for_chip(x, y, level=3): """Get the region word for the given chip co-ordinates. Parameters ---------- x : int x co-ordinate y : int y co-ordinate level : int Level of region to build. 0 is the most coarse and 3 is the finest. When 3 is used the sp...
bigcode/self-oss-instruct-sc2-concepts
def get_calendar_event_id(user, block_key, date_type, hostname): """ Creates a unique event id based on a user and a course block key Parameters: user (User): The user requesting a calendar event block_key (str): The block key containing the date for the calendar event date_type (st...
bigcode/self-oss-instruct-sc2-concepts
def dnn_activation(data, model, layer_loc, channels=None): """ Extract DNN activation from the specified layer Parameters: ---------- data[tensor]: input stimuli of the model with shape as (n_stim, n_chn, height, width) model[model]: DNN model layer_loc[sequence]: a sequence of keys to find...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def expected(request) -> Any: """Expected test case result.""" return request.param
bigcode/self-oss-instruct-sc2-concepts
def clean_path(path): """ Add ws:///@user/ prefix if necessary """ if path[0:3] != "ws:": while path and path[0] == "/": path = path[1:] path = "ws:///@user/" + path return path
bigcode/self-oss-instruct-sc2-concepts
def strip_comments(s): """Strips the comments from a multi-line string. >>> strip_comments('hello ;comment\\nworld') 'hello \\nworld' """ COMMENT_CHAR = ';' lines = [] for line in s.split('\n'): if COMMENT_CHAR in line: lines.append(line[:line.index(COMMENT_CHAR)]) ...
bigcode/self-oss-instruct-sc2-concepts
def translate_p_vals(pval, as_emoji=True): """ Translates ambiguous p-values into more meaningful emoji. Parameters ---------- pval : float as_emoji : bool (default = True) Represent the p-vals as emoji. Otherwise, words will be used. Returns ------- interpreted : string "...
bigcode/self-oss-instruct-sc2-concepts
def str2LaTeX(python_string): """ Function that solves the underscore problem in a python string to :math:`\LaTeX` string. Parameters ---------- python_string : `str` String that needs to be changed. Returns ------- LaTeX_string : `str` String with the new underscor...
bigcode/self-oss-instruct-sc2-concepts
def ip_range(network): """Return tuple of low, high IP address for given network""" num_addresses = network.num_addresses if num_addresses == 1: host = network[0] return host, host elif num_addresses == 2: return network[0], network[-1] else: return network[1], networ...
bigcode/self-oss-instruct-sc2-concepts
def none_split(val): """Handles calling split on a None value by returning the empty list.""" return val.split(', ') if val else ()
bigcode/self-oss-instruct-sc2-concepts
def distinct_terms(n): """Finds number of distinct terms a^b for 2<=a<=n, 2<=b<=n""" return len(set([a**b for a in range(2, n+1) for b in range(2, n+1)]))
bigcode/self-oss-instruct-sc2-concepts
def t01_SimpleGetPut(C, pks, crypto, server): """Uploads a single file and checks the downloaded version is correct.""" alice = C("alice") alice.upload("a", "b") return float(alice.download("a") == "b")
bigcode/self-oss-instruct-sc2-concepts
def get_as_list(base: dict, target): """Helper function that returns the target as a list. :param base: dictionary to query. :param target: target key. :return: base[target] as a list (if it isn't already). """ if target not in base: return list() if not isinstance(base[target], l...
bigcode/self-oss-instruct-sc2-concepts
def intget(integer, default=None): """Returns `integer` as an int or `default` if it can't.""" try: return int(integer) except (TypeError, ValueError): return default
bigcode/self-oss-instruct-sc2-concepts
def hexagonal(n): """Returns the n-th hexagonal number""" return n*(2*n-1)
bigcode/self-oss-instruct-sc2-concepts
def isSubListInListWithIndex(sublist, alist): """ Predicates that checks if a list is included in another one Args: sublist (list): a (sub)-list of elements. alist (list): a list in which to look if the sublist is included in. Result: (True, Index) if the sublist is included in the l...
bigcode/self-oss-instruct-sc2-concepts
def gcd(x: int, y: int) -> int: """ Euclidean GCD algorithm (Greatest Common Divisor) >>> gcd(0, 0) 0 >>> gcd(23, 42) 1 >>> gcd(15, 33) 3 >>> gcd(12345, 67890) 15 """ return x if y == 0 else gcd(y, x % y)
bigcode/self-oss-instruct-sc2-concepts
from glob import glob def list_files_local(path): """ Get file list form local folder. """ return glob(path)
bigcode/self-oss-instruct-sc2-concepts
def combine(background_img, figure_img): """ :param background_img: SimpleImage, the background image :param figure_img: SimpleImage, the green screen figure image :return: SimpleImage, the green screen pixels are replaced with pixels of background image """ # (x, y) represent every pixel in the...
bigcode/self-oss-instruct-sc2-concepts
import socket import struct def ip2long(ip): """ Convert IPv4 address in string format into an integer :param str ip: ipv4 address :return: ipv4 address :rtype: integer """ packed_ip = socket.inet_aton(ip) return struct.unpack("!L", packed_ip)[0]
bigcode/self-oss-instruct-sc2-concepts
def invert(record): """ Invert (ID, tokens) to a list of (token, ID) Args: record: a pair, (ID, token vector) Returns: pairs: a list of pairs of token to ID """ return [(k,record[0]) for k,v in record[1].iteritems()]
bigcode/self-oss-instruct-sc2-concepts
def inv_map(dictionary: dict): """ creates a inverse mapped dictionary of the provided dict :param dictionary: dictionary to be reverse mapped :return: inverse mapped dict """ return {v: k for k, v in dictionary.items()}
bigcode/self-oss-instruct-sc2-concepts
import re def IsValidFolderForType(path, component_type): """Checks a folder is named correctly and in a valid tree for component type. Args: path: a relative path from ontology root with no leading or trailing slashes. Path should be the top level for the component. component_type: the base_lib.Co...
bigcode/self-oss-instruct-sc2-concepts
def convert_021_to_022(cfg): """Convert rev 0.21 to 0.22 The rev 0.22 only affected the fuzzy logic methods. The membership shape is now explicit so that the user has the freedom to choose alternatives. """ assert ("revision" in cfg) and (cfg["revision"] == "0.21") cfg["revision"] = 0.22 f...
bigcode/self-oss-instruct-sc2-concepts
import fnmatch def filter_tests(tests, filters): """Returns a filtered list of tests to run. The test-filtering semantics are documented in https://bit.ly/chromium-test-runner-api and https://bit.ly/chromium-test-list-format, but are as follows: Each filter is a list of glob expressions, with ea...
bigcode/self-oss-instruct-sc2-concepts
def get_all_descendants(root, children_map): """ Returns all descendants in the tree of a given root node, recursively visiting them based on the map from parents to children. """ return {root}.union( *[get_all_descendants(child, children_map) for child in children_map.get(root, ...
bigcode/self-oss-instruct-sc2-concepts
import time def curr_time() -> int: """Return the current time in ms.""" return int(time.perf_counter() * 1000)
bigcode/self-oss-instruct-sc2-concepts
def team_game_result(team, game): """Return the final result of the game as it relates to the team""" if game.winner == team: return "Win" elif game.winner and game.winner != team: return "Lose" elif game.home_team_score > 0: return "Tie" else: return "Scoreless Tie"
bigcode/self-oss-instruct-sc2-concepts
def get_assay_collections(assays, irods_backend): """Return a list of all assay collection names.""" return [irods_backend.get_path(a) for a in assays]
bigcode/self-oss-instruct-sc2-concepts
def fact(n): """ Factorial function :arg n: Number :returns: factorial of n """ if n == 0: return 1 return n * fact(n - 1)
bigcode/self-oss-instruct-sc2-concepts
def has_no_overlap(r1, r2): """Returns True if the two reads overlap. """ r1_start, r1_end = r1.reference_start, r1.reference_end r2_start, r2_end = r2.reference_start, r2.reference_end return (r2_end <= r1_start) or (r1_end <= r2_start)
bigcode/self-oss-instruct-sc2-concepts
def pick(*args): """ Returns the first non None value of the passed in values :param args: :return: """ for item in args: if item is not None: return item return None
bigcode/self-oss-instruct-sc2-concepts
def get_dataframe_name(s): """ Split dataframe and variable name from dataframe form field names (e.g. "___<var_name>___<dataframe_name>__"). Args: s (str): The string Returns: 2-tuple<str>: The name of the variable and name of the dataframe. False if not a properly formatted string. ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Any def count_bool(blist: Iterable[Any]) -> int: """ Counts the number of "truthy" members of the input list. Args: blist: list of booleans or other truthy/falsy things Returns: number of truthy items """ return sum([1 if x else...
bigcode/self-oss-instruct-sc2-concepts
import re def WrapWords(textlist, size, joiner='\n'): """Insert breaks into the listed strings at specified width. Args: textlist: a list of text strings size: width of reformated strings joiner: text to insert at break. eg. '\n ' to add an indent. Returns: list of strings """ # \S*? is a...
bigcode/self-oss-instruct-sc2-concepts
def _format_param_value(key, value): """Wraps string values in quotes, and returns as 'key=value'. """ if isinstance(value, str): value = "'{}'".format(value) return "{}={}".format(key, value)
bigcode/self-oss-instruct-sc2-concepts
def echo_args(*args, **kwargs): """Returns a dict containng all positional and keyword arguments. The dict has keys ``"args"`` and ``"kwargs"``, corresponding to positional and keyword arguments respectively. :param *args: Positional arguments :param **kwargs: Keyword arguments :rtype:...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def resolve_import(import_: str, location: str, file: Path) -> str: """Resolve potentially relative import inside a package.""" if not import_.startswith('.'): return import_ import_parts = import_.split('.') up_levels = len([p for p in import_parts if p == '']) i...
bigcode/self-oss-instruct-sc2-concepts
def time2int(float_time): """ Convert time from float (seconds) to int (nanoseconds). """ int_time = int(float_time * 10000000) return int_time
bigcode/self-oss-instruct-sc2-concepts
def fp_rate(FP, neg): """ Gets false positive rate. :param: FP: Number of false positives :type FP: `int` :param: neg: Number of negative labels :type neg: `int` :return: false positive rate :rtype: `float` """ if neg == 0: return 0 else: return FP / neg
bigcode/self-oss-instruct-sc2-concepts
def cmd_automation_event_lost(msg): """ (From protocol docs) Panel's automation buffer has overflowed. Automation modules should respond to this with request for Dynamic Data Refresh and Full Equipment List Request. """ return { }
bigcode/self-oss-instruct-sc2-concepts
def columns_to_nd(array2reshape, layers, rows, columns): """ Reshapes an array from columns layout to [n layers x rows x columns] """ if layers == 1: return array2reshape.reshape(columns, rows).T else: return array2reshape.T.reshape(layers, rows, columns)
bigcode/self-oss-instruct-sc2-concepts
def convert_none_type_object_to_empty_string(my_object): """ replace noneType objects with an empty string. Else return the object. """ return ('' if my_object is None else my_object)
bigcode/self-oss-instruct-sc2-concepts
import re def is_weight(word): """ is_weight() Purpose: Checks if word is a weight. @param word. A string. @return the matched object if it is a weight, otherwise None. >>> is_weight('1mg') is not None True >>> is_weight('10 g') is not None True >>> is_weight('78 mcg') ...
bigcode/self-oss-instruct-sc2-concepts
import re def get_locus_info(locus): """ Returns chrom, start and stop from locus string. Enforces standardization of how locus is represented. chrom:start_stop (start and stop should be ints or 'None') """ chrom, start_stop = locus.split(':') if chrom == 'None': chrom = None star...
bigcode/self-oss-instruct-sc2-concepts
def gameboard(level): """ This function will generate a gameboard, determined by the level size parameter. To keep the rows equivalent for both the user and the player, the board_size is guarenteed to be a multiple of two. Parameters: ----------- level: required parameter. Level determin...
bigcode/self-oss-instruct-sc2-concepts
import time def convert_time(longTime): """ Ignore time of day to help with grouping contributions by day. 2018-01-03 00:00:00 --> 2018-01-03 """ try: t = time.strptime(longTime, "%Y-%m-%d %H:%M:%S") except ValueError: return longTime ret = time.strftime( "%Y-%m-%d", t) ...
bigcode/self-oss-instruct-sc2-concepts
def computeRR(self): """ Compute the rectangularity ratio (RR) of the max-tree nodes. RR is defined as the area (volume) of a connected component divided by the area (volume) of its bounding-box. """ xmin,xmax = self.node_array[6,:], self.node_array[7,:] + 1 ymin,ymax = self.node_array[9,:], s...
bigcode/self-oss-instruct-sc2-concepts
def shape3d_to_size2d(shape, axis): """Turn a 3d shape (z, y, x) into a local (x', y', z'), where z' represents the dimension indicated by axis. """ shape = list(shape) axis_value = shape.pop(axis) size = list(reversed(shape)) size.append(axis_value) return tuple(size)
bigcode/self-oss-instruct-sc2-concepts
def orsample(df): """ Return the bitwise-OR of every value in the data frame. >>> orsample(empty) 0 >>> result = 1 | 3 | 5 | 6 | 8 >>> assert result == orsample(sample) """ if len(df) == 0: return 0 result = 0 for val in df.iloc[::, 0]: if val > 0: re...
bigcode/self-oss-instruct-sc2-concepts
def camels_to_move(camel_dict, space, height): """Getting information about camels that need to move Parameters ---------- camel_dict : nested dict Dictionary with current camel positions space : int Space the camel is on height : int Height of the camel Returns ...
bigcode/self-oss-instruct-sc2-concepts
def make_feasible(x_0, c): """ Returns a feasible x with respect to the constraints g_3, g_4, g_5, and g_6. :param np.array x_0: (n,) Initial, infeasible point. :param dict c: Constants defining the constraints. :return np.array: (n,) Initial, feasible point. Notes: - x_0 should follow: x0...
bigcode/self-oss-instruct-sc2-concepts
def binary_sum(S, start, stop): """Return the sum of the numbers in implicit slice S[start:stop].""" if start >= stop: # zero elemetns in slice return 0 elif start == stop - 1: return S[start] # one element in slice else: # two or more ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def gen_string(i: int, base: int, digits: List[str]): """Returns a string representation of an integer given the list of digits. Args: i (int): The integer to generate base (int): The base representation of the number. (based on the length of the list) digits (...
bigcode/self-oss-instruct-sc2-concepts
import math def round_up_to_multiple(x: int, base: int) -> int: """ Round a positive integer up to the nearest multiple of given base number For example: 12 -> 15, with base = 5 """ return base * math.ceil(x / base)
bigcode/self-oss-instruct-sc2-concepts
def module_name_join(names): """Joins names with '.' Args: names (iterable): list of strings to join Returns: str: module name """ return '.'.join(names)
bigcode/self-oss-instruct-sc2-concepts
def _calculate_texture_sim(ri, rj): """ Calculate texture similarity using histogram intersection """ return sum([min(a, b) for a, b in zip(ri["texture_hist"], rj["texture_hist"])])
bigcode/self-oss-instruct-sc2-concepts
def pp_value(TP, FP): """ Gets positive predictive value, or precision. :param: TP: Number of true positives :type TP: `int` :param: FP: Number of false positives :type FP: `int` :return: positive predictive value :rtype: `float` """ if TP == 0 and FP == 0: return 0 ...
bigcode/self-oss-instruct-sc2-concepts
def _no_pending_images(images): """If there are any images not in a steady state, don't cache""" for image in images: if image.status not in ('active', 'deleted', 'killed'): return False return True
bigcode/self-oss-instruct-sc2-concepts
def get_data(fname: str) -> list: """ Read the data file into a list. """ with open(fname) as f: return [int(line) for line in f]
bigcode/self-oss-instruct-sc2-concepts
def format_skills(text: str, ents: list) -> list: """ Get the list of skills according to the HrFlow.ai Job format @param text: text description of the job @param ents: list of entities in the text @return: list of skills """ skills = [{ "name": text[ent["start"]:ent["end"]].lower(), "value"...
bigcode/self-oss-instruct-sc2-concepts
import csv def write_csv(f, extract, fields=None): """ Writers extract to file handle Parameters __________ f : file handle (string mode) extract: list of dicts fields: list of str Field names to include in CSV. Returns _______ f : file handle (string mode) """ key...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _replace_with(items: List[int], value: int) -> List[int]: """Replaces all values in items with value (in-place).""" length = len(items) del items[:] items.extend(length * [value]) return items
bigcode/self-oss-instruct-sc2-concepts
import requests def token(code, redirect_uri, client_id, client_secret): """Generates access token used to call Spotify API Args: code (str): Authorization code used to generate token redirect_uri (str): Allowed redirect URL set in Spotify's developer dashboard client_id (str): Appli...
bigcode/self-oss-instruct-sc2-concepts
import torch def broadcast_backward(input, shape): """Sum a tensor across dimensions that have been broadcasted. Parameters ---------- input : tensor Tensor with broadcasted shape. shape : tuple[int] Original shape. Returns ------- output : tensor with shape `shape` ...
bigcode/self-oss-instruct-sc2-concepts
def _getrawimagelist(glance_client): """Helper function that returns objects as dictionary. We need this function because we use Pool to implement a timeout and the original results is not pickable. :param glance_client: the glance client :return: a list of images (every image is a dictionary) ...
bigcode/self-oss-instruct-sc2-concepts
import uuid def prefixUUID(pre: str = "PREFIX", max_length: int = 30) -> str: """ Create a unique name with a prefix and a UUID string :param pre: prefix to use :param max_length: max length of the unique name :return: unique name with the given prefix """ if len(pre) > max_length: ...
bigcode/self-oss-instruct-sc2-concepts
import re def _make_safe_id_component(idstring): """Make a string safe for including in an id attribute. The HTML spec says that id attributes 'must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), ...
bigcode/self-oss-instruct-sc2-concepts
def is_pickup(df): """Return if vehicle is a pickup truck, per NHTSA convention.""" yr = df['YEAR'] body = df['BODY_TYP'] return ((yr.between(1975, 1981) & (body == 50)) | (yr.between(1982, 1990) & body.isin([50, 51])) | ((1991 <= yr) & body.between(30, 39)))
bigcode/self-oss-instruct-sc2-concepts
def _num_items_2_heatmap_one_day_figsize(n): """ uses linear regression model to infer adequate figsize from the number of items Data used for training: X = [2,4,6,10,15,20,30,40,50,60] y = [[10,1],[10,2],[10,3],[10,4],[10,6],[10,8],[10,10],[10,12],[10,15],[10,17]] Parameters --...
bigcode/self-oss-instruct-sc2-concepts