seed
stringlengths
1
14k
source
stringclasses
2 values
def prepareFixed(query, ftypes, fixed): """Called by :meth:`.FileTreeManager.update`. Prepares a dictionary which contains all possible values for each fixed variable, and for each file type. :arg query: :class:`.FileTreeQuery` object :arg ftypes: List of file types to be displayed :arg fixe...
bigcode/self-oss-instruct-sc2-concepts
def manhattan(p1, p2): """Return manhattan distance between 2 points.""" return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
bigcode/self-oss-instruct-sc2-concepts
import re def _load_line(fh) -> str: """Loads a line from the file, skipping blank lines. Validates format, and removes whitespace. """ while True: line = fh.readline() line = line.rstrip() line = re.sub(" ", "", line) if line: # Not blank. ...
bigcode/self-oss-instruct-sc2-concepts
def find_all_lowest(l, f): """Find all elements x in l where f(x) is minimal""" if len(l) == 1: return l minvalue = min([f(x) for x in l]) return [x for x in l if f(x) == minvalue]
bigcode/self-oss-instruct-sc2-concepts
def get_num_attachments(connection): """Get the number of attachments that need to be migrated""" with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM form_processor_xformattachmentsql") return cursor.fetchone()[0]
bigcode/self-oss-instruct-sc2-concepts
def is_sorted(ls): """Returns true if the list is sorted""" return ls == sorted(ls)
bigcode/self-oss-instruct-sc2-concepts
import math def sin100( x ): """ A sin function that returns values between 0 and 100 and repeats after x == 100. """ return 50 + 50 * math.sin( x * math.pi / 50 )
bigcode/self-oss-instruct-sc2-concepts
def curve_between( coordinates, start_at, end_at, start_of_contour, end_of_contour): """Returns indices of a part of a contour between start and end of a curve. The contour is the cycle between start_of_contour and end_of_contour, and start_at and end_at are on-curve points, and the return value ...
bigcode/self-oss-instruct-sc2-concepts
def X_y_split(data: list): """ Split data in X and y for ML models. """ X = [row[0] for row in data] y = [row[1] for row in data] return X, y
bigcode/self-oss-instruct-sc2-concepts
def attr_str(ctrl_name, attr_name): """ join the two strings together to form the attribute name. :param ctrl_name: :param attr_name: :return: """ return '{}.{}'.format(ctrl_name, attr_name)
bigcode/self-oss-instruct-sc2-concepts
def percent_change(starting_point, current_point): """ Computes the percentage difference between two points :return: The percentage change between starting_point and current_point """ default_change = 0.00001 try: change = ((float(current_point) - starting_point) / abs(starting_point)) ...
bigcode/self-oss-instruct-sc2-concepts
def internal_header_to_external(internal_header: str) -> str: """ Within our app we access headers in this form HTTP_LMS_TYPE but they are supplied like LMS-TYPE. This converts the internal form to the external form for error reporting purposes. """ assert internal_header.startswith('HTTP_'...
bigcode/self-oss-instruct-sc2-concepts
def get_deps(project_config): """ Get the recipe engine deps of a project from its recipes.cfg file. """ # "[0]" Since parsing makes every field a list return [dep['project_id'][0] for dep in project_config.get('deps', [])]
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import base64 import gzip import json def compress(input: Any) -> str: """ Convenience function for compressing something before sending it to Cloud. Converts to string, encodes, compresses, encodes again using b64, and decodes. Args: - input (Any): the dictionary t...
bigcode/self-oss-instruct-sc2-concepts
def _parameterval(tsr,sol,coef): """ Creating polynomial surface based on given coefficients and calculating the point at a given TSR and solidity Parameters ---------- tsr : float specified tip-speed ratio sol : float specified solidity coef : array the polynomial s...
bigcode/self-oss-instruct-sc2-concepts
def get_callback(request, spider): """Get ``request.callback`` of a :class:`scrapy.Request`""" if request.callback is None: return getattr(spider, 'parse') return request.callback
bigcode/self-oss-instruct-sc2-concepts
import hashlib import binascii def verify_password(stored_password, provided_password): """Verify a stored password against one provided by user""" pwdhash = hashlib.pbkdf2_hmac( "sha256", provided_password.encode("utf-8"), stored_password["salt"].encode(), 10000, ) ret...
bigcode/self-oss-instruct-sc2-concepts
def get_lat_lon_alt(pandora_filepath): """Returns a dictionary of lat, lon, alt extracted from the pandora file :param pandora_filepath: The pandora file :type pandora_filepath: str :returns: A dict of {"lat":lat, "lon":lon, "alt":alt} :rtype: dict{str:int} """ lat = None lon = None ...
bigcode/self-oss-instruct-sc2-concepts
def is_user_message(message): """Check if the message is a message from the user""" return (message.get('message') and message['message'].get('text') and not message['message'].get("is_echo"))
bigcode/self-oss-instruct-sc2-concepts
def _ToString(rules): """Formats a sequence of Rule objects into a string.""" return '[\n%s\n]' % '\n'.join('%s' % rule for rule in rules)
bigcode/self-oss-instruct-sc2-concepts
import requests def gateway(self, IPFS_path: str, **kwargs): """ Retrieve an object from the IFPS gateway (useful if you do not want to rely on a public gateway, such as ipfs.blockfrost.dev). https://docs.blockfrost.io/#tag/IPFS-Gateway :param IPFS_path: Path to the IPFS object. :type IPFS_path:...
bigcode/self-oss-instruct-sc2-concepts
import json def ipynb2markdown(ipynb): """ Extract Markdown cells from iPython Notebook Args: ipynb (str): iPython notebook JSON file Returns: str: Markdown """ j = json.loads(ipynb) markdown = "" for cell in j["cells"]: if cell["cell_type"] == "ma...
bigcode/self-oss-instruct-sc2-concepts
def get_target_shape(shape, size_factor): """ Given an shape tuple and size_factor, return a new shape tuple such that each of its dimensions is a multiple of size_factor :param shape: tuple of integers :param size_factor: integer :return: tuple of integers """ target_shape = [] fo...
bigcode/self-oss-instruct-sc2-concepts
def format_row(row: list) -> list: """Format a row of scraped data into correct type All elements are scraped as strings and should be converted to the proper format to be used. This converts the following types: - Percentages become floats (Ex: '21.5%' --> 0.215) - Numbers become ints (Ex: '2020'...
bigcode/self-oss-instruct-sc2-concepts
def count_in_progress(state, event): """ Count in-progress actions. Returns current state as each new produced event, so we can see state change over time """ action = event['action'] phase = event['phase'] if phase == 'start': state[action] = state.get(action, 0) + 1 elif ...
bigcode/self-oss-instruct-sc2-concepts
def is_draft(record, ctx): """Shortcut for links to determine if record is a draft.""" return record.is_draft
bigcode/self-oss-instruct-sc2-concepts
def approx_equal(a_value: float, b_value: float, tolerance: float = 1e-4) -> float: """ Approximate equality. Checks if values are within a given tolerance of each other. @param a_value: a value @param b_value: b value @param tolerance: @return: boolean indicating values are with in gi...
bigcode/self-oss-instruct-sc2-concepts
def create_zero_matrix(rows: int, columns: int) -> list: """ Creates a matrix rows * columns where each element is zero :param rows: a number of rows :param columns: a number of columns :return: a matrix with 0s e.g. rows = 2, columns = 2 --> [[0, 0], [0, 0]] """ if not isinstance(ro...
bigcode/self-oss-instruct-sc2-concepts
def _fix_attribute_names(attrs, change_map): """ Change attribute names as per values in change_map dictionary. Parameters ---------- :param attrs : dict Dict of operator attributes :param change_map : dict Dict of onnx attribute name to mxnet attribute names. Returns ------- :retur...
bigcode/self-oss-instruct-sc2-concepts
def strip_token(token) -> str: """ Strip off suffix substring :param token: token string :return: stripped token if a suffix found, the same token otherwise """ if token.startswith(".") or token.startswith("["): return token pos = token.find("[") # If "." is not found if po...
bigcode/self-oss-instruct-sc2-concepts
def str_to_tile_index(s, index_of_a = 0xe6, index_of_zero = 0xdb, special_cases = None): """ Convert a string to a series of tile indexes. Params: s: the string to convert index_of_a: begining of alphabetical tiles index_of_zero: begining of numerical tiles special_cases: what to if a character is not alpha...
bigcode/self-oss-instruct-sc2-concepts
import csv def load_data(filename): """ Load shopping data from a CSV file `filename` and convert into a list of evidence lists and a list of labels. Return a tuple (evidence, labels). evidence should be a list of lists, where each list contains the following values, in order: - Administr...
bigcode/self-oss-instruct-sc2-concepts
def edges_from_matchings(matching): """ Identify all edges within a matching. Parameters ---------- matching : list of all matchings returned by matching api Returns ------- edges : list of all edge tuples """ edges = [] nodes = [] # only address highest...
bigcode/self-oss-instruct-sc2-concepts
def find_faces_with_vertex(index, faces): """ For a given vertex, find all faces containing this vertex. Note: faces do not have to be triangles. Parameters ---------- index : integer index to a vertex faces : list of lists of three integers the integers for each face are in...
bigcode/self-oss-instruct-sc2-concepts
def definitions_match(definition_objects, expected_descriptor): """ Return whether Definition objects have expected properties. The order of the definitions, and their sources, may appear in any order. expected_descriptor is a shorthand format, consisting of a list or tuple `(definition_string, so...
bigcode/self-oss-instruct-sc2-concepts
from typing import Pattern import re import fnmatch def _glob_to_re(glob: str) -> Pattern[str]: """Translate and compile glob string into pattern.""" return re.compile(fnmatch.translate(glob))
bigcode/self-oss-instruct-sc2-concepts
def run_dir_name(run_num): """ Returns the formatted directory name for a specific run number """ return "run{:03d}".format(run_num)
bigcode/self-oss-instruct-sc2-concepts
def _and(x,y): """Return: x and y (used for reduce)""" return x and y
bigcode/self-oss-instruct-sc2-concepts
def get_policy(observations, hparams): """Get a policy network. Args: observations: Tensor with observations hparams: parameters Returns: Tensor with policy and value function output """ policy_network_lambda = hparams.policy_network action_space = hparams.environment_spec.action_space retur...
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def column_checker(chat_df, message_df, attachment_df, handle_df): """ Checks the columns of the major tables for any conflicting column names :param chat_df: the chat table dataframe :param message_df: the message table dataframe :param attachment_df: the attachment tab...
bigcode/self-oss-instruct-sc2-concepts
def _IsMacro(command): """Checks whether a command is a macro.""" if len(command) >= 4 and command[0] == "MACRO" and command[2] == "=": return True return False
bigcode/self-oss-instruct-sc2-concepts
import json from collections import defaultdict def read_config_filters(file_config): """ Parse json file to build the filtering configuration Args: file_config (Path): absolute path of the configuration file Returns: combine (str): filter_param (dict): {key:list o...
bigcode/self-oss-instruct-sc2-concepts
def negate_conf(c): """Negate a line of configuration.""" return "no %s" % c
bigcode/self-oss-instruct-sc2-concepts
def input_s(prompt: str = "", interrupt: str = "", eof: str = "logout") -> str: """ Like Python's built-in ``input()``, but it will give a string instead of raising an error when a user cancel(^C) or an end-of-file(^D on Unix-like or Ctrl-Z+Return on Windows) is received. prompt The promp...
bigcode/self-oss-instruct-sc2-concepts
import re def instruction_decoder_name(instruction): """ Given an instruction with the format specified in ARMv7DecodingSpec.py output a unique name that represents that particular instruction decoder. """ # Replace all the bad chars. name = re.sub('[\s\(\)\-\,\/\#]', '_', instruction["name"])...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional import requests def get_def_tenant_id(sub_id: str) -> Optional[str]: """ Get the tenant ID for a subscription. Parameters ---------- sub_id : str Subscription ID Returns ------- Optional[str] TenantID or None if it could not be found. ...
bigcode/self-oss-instruct-sc2-concepts
import asyncio async def subprocess_run_async(*args, shell=False): """Runs a command asynchronously. If ``shell=True`` the command will be executed through the shell. In that case the argument must be a single string with the full command. Otherwise, must receive a list of program arguments. Returns ...
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def djb2(L): """ h = 5381 for c in L: h = ((h << 5) + h) + ord(c) # h * 33 + c return h """ return reduce(lambda h, c: ord(c) + ((h << 5) + h), L, 5381)
bigcode/self-oss-instruct-sc2-concepts
def create_user(ssh_fn, name): """Create a user on an instance using the ssh_fn and name. The ssh_fn is a function that takes a command and runs it on the remote system. It must be sudo capable so that a user can be created and the remote directory for the user be determined. The directory for the us...
bigcode/self-oss-instruct-sc2-concepts
from random import shuffle def randomize_ietimes(times, ids = []): """ Randomize the times of the point events of all the ids that are given. This randomization keeps the starting time of each individual and reshuffles its own interevent times. Parameters ---------- times : dictionary of l...
bigcode/self-oss-instruct-sc2-concepts
def write_csv_string(data): """ Takes a data object (created by one of the read_*_string functions). Returns a string in the CSV format. """ data_return = "" row_num = 0 #Building the string to return #print('data',data) for row in data: data_return += ','.join(str(v) for v in data[row_num].values()) data_...
bigcode/self-oss-instruct-sc2-concepts
def convert_list_to_string(input_list): """ Converts a list to a string with each value separated with a new paragraph Parameters ---------- input_list : list List of values Returns ------- output : str String output with each value in `input_list` recorded """ ...
bigcode/self-oss-instruct-sc2-concepts
import pathlib import hashlib def get_hash(file_path): """Return sha256 hash of file_path.""" text = b"" if (path := pathlib.Path(file_path)).is_file(): text = path.read_bytes() return hashlib.sha256(text).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def format_3(value): """Round a number to 3 digits after the dot.""" return "{:.3f}".format(value)
bigcode/self-oss-instruct-sc2-concepts
def get_only_first_stacktrace(lines): """Get the first stacktrace because multiple stacktraces would make stacktrace parsing wrong.""" new_lines = [] for line in lines: line = line.rstrip() if line.startswith('+----') and new_lines: break # We don't add the empty lines in the beginning. ...
bigcode/self-oss-instruct-sc2-concepts
def bande_est_noire(nv): """ Determine si une bande est noire ou blanche a partir de son numero """ return nv % 2 == 1
bigcode/self-oss-instruct-sc2-concepts
def fmt(obj): """Value formatter replaces numpy types with base python types.""" if isinstance(obj, (str, int, float, complex, tuple, list, dict, set)): out = obj else: # else, assume numpy try: out = obj.item() # try to get value except: ...
bigcode/self-oss-instruct-sc2-concepts
def get_first_aligned_bp_index(alignment_seq): """ Given an alignment string, return the index of the first aligned, i.e. non-gap position (0-indexed!). Args: alignment_seq (string): String of aligned sequence, consisting of gaps ('-') and non-gap characters, such as "HA-LO" or "---...
bigcode/self-oss-instruct-sc2-concepts
def risingfactorial(n, m): """ Return the rising factorial; n to the m rising, i.e. n(n+1)..(n+m-1). For example: >>> risingfactorial(7, 3) 504 """ r = 1 for i in range(n, n+m): r *= i return r
bigcode/self-oss-instruct-sc2-concepts
def get_adoc_title(title: str, level: int) -> str: """Returns a string to generate a ascidoc title with the given title, and level""" return " ".join(["="*level, title, '\n'])
bigcode/self-oss-instruct-sc2-concepts
def _normalize_typos(typos, replacement_rules): """ Applies all character replacement rules to the typos and returns a new dictionary of typos of all non-empty elements from normalized 'typos'. """ if len(replacement_rules) > 0: typos_new = dict() for key, values i...
bigcode/self-oss-instruct-sc2-concepts
import csv def create_idf_dict() -> dict: """Returns the idf_dict from tstar_idf.txt""" with open("climate_keywords/tstar_idf.txt", "r", encoding='utf-8', errors='ignore') as f: reader = csv.reader(f) idf_dict = {} for term, idf in reader: idf_dict[term] = float(idf) re...
bigcode/self-oss-instruct-sc2-concepts
import re def sanitize_json_string(string): """ Cleans up extraneous whitespace from the provided string so it may be written to a JSON file. Extraneous whitespace include any before or after the provided string, as well as between words. Parameters ---------- string : str The str...
bigcode/self-oss-instruct-sc2-concepts
def dict_slice(dict_input, start, end) -> dict: """ take slice for python dict :param dict_input: a dict for slicing :param start: start position for splicing :param end: end position for slicing :return: the sliced dict """ keys = dict_input.keys() dict_slice = {} for k in keys[...
bigcode/self-oss-instruct-sc2-concepts
def extract_barcode(read, plen): """ Extract barcode from Seq and Phred quality. :param read: A SeqIO object. :type read: object :param plen: The length of the barcode. :type plen: num :returns: A SeqIO object with barcode removed and a barcode string. """ barcode = str(read.seq[:pl...
bigcode/self-oss-instruct-sc2-concepts
def getGroupInputDataLength(hg): """ Return the length of a HDF5 group Parameters ---------- hg : `h5py.Group` or `h5py.File` The input data group Returns ------- length : `int` The length of the data Notes ----- For a multi-D array this return the length of th...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import re def get_current_zones(filename: str) -> Dict[str, str]: """Get dictionary of current zones and patterns""" res = {} try: for line in open(filename).readlines(): if line.startswith("#"): continue if match := re.match(r"^add (...
bigcode/self-oss-instruct-sc2-concepts
def std_ver_minor_uninst_valueerr_iativer(request): """Return a string that looks like it could be a valid IATIver minor version number, but is not.""" return request.param
bigcode/self-oss-instruct-sc2-concepts
def sec_url(period): """ Create url link to SEC Financial Statement Data Set """ url = "".join([ "https://www.sec.gov/files/dera/data/financial-statement-data-sets/", period, ".zip" ]) # handle weird path exception of SEC if period == "2020q1": url = "".join([ ...
bigcode/self-oss-instruct-sc2-concepts
def compute_sub(guard_str): """ Given a guard, return its sub-guards """ parens = [] sub = [] for i in range(len(guard_str)): if guard_str[i] == '(': parens.append(i) if guard_str[i] == ')': j = parens.pop() g = guard_str[j:i + 1].strip...
bigcode/self-oss-instruct-sc2-concepts
def clean_string(s): """ Get a string into a canonical form - no whitespace at either end, no newlines, no double-spaces. """ return s.strip().replace("\n", " ").replace(" ", " ")
bigcode/self-oss-instruct-sc2-concepts
import math def precision_digits(f, width): """Return number of digits after decimal point to print f in width chars. Examples -------- >>> precision_digits(-0.12345678, 5) 2 >>> precision_digits(1.23456789, 5) 3 >>> precision_digits(12.3456789, 5) 2 >>> precision_digits(12345...
bigcode/self-oss-instruct-sc2-concepts
def sorted_nodes_by_name(nodes): """Sorts a list of Nodes by their name.""" return sorted(nodes, key=lambda node: node.name)
bigcode/self-oss-instruct-sc2-concepts
def ai(vp,rho): """ Computes de acoustic impedance Parameters ---------- vp : array P-velocity. rho : array Density. Returns ------- ai : array Acoustic impedance. """ ai = vp*rho return (ai)
bigcode/self-oss-instruct-sc2-concepts
def get_bool(bytearray_: bytearray, byte_index: int, bool_index: int) -> bool: """Get the boolean value from location in bytearray Args: bytearray_: buffer data. byte_index: byte index to read from. bool_index: bit index to read from. Returns: True if the bit is 1, else 0. ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def evaluate(population: list, evaluation_fn: Callable) -> list: """Evaluates the given population using the given evaluation function. Params: - population (list<str>): The population of chromosomes to evaluate - evaluation_fn (Callable): The evaluation function to use ...
bigcode/self-oss-instruct-sc2-concepts
import copy def merge_to_panoptic(detection_dicts, sem_seg_dicts): """ Create dataset dicts for panoptic segmentation, by merging two dicts using "file_name" field to match their entries. Args: detection_dicts (list[dict]): lists of dicts for object detection or instance segmentation. ...
bigcode/self-oss-instruct-sc2-concepts
def intersection_pt(L1, L2): """Returns intersection point coordinates given two lines. """ D = L1[0] * L2[1] - L1[1] * L2[0] Dx = L1[2] * L2[1] - L1[1] * L2[2] Dy = L1[0] * L2[2] - L1[2] * L2[0] if D != 0: x = Dx / D y = Dy / D return x, y else: return False
bigcode/self-oss-instruct-sc2-concepts
def has_cli_method(script_path): """ Check if a script has a cli() method in order to add it to the main :param script_path: to a python script inside Cider packages :return: Boolean """ file_obj = open(script_path, 'r').read() return "cli()" in file_obj
bigcode/self-oss-instruct-sc2-concepts
def lobid_qs(row, q_field='surname', add_fields=[], base_url="https://lobid.org/gnd/search?q="): """ creates a lobid query string from the passed in fields""" search_url = base_url+row[q_field]+"&filter=type:Person" if add_fields: filters = [] for x in add_fields: if x: ...
bigcode/self-oss-instruct-sc2-concepts
def jaccard(ground, found): """Cardinality of set intersection / cardinality of set union.""" ground = set(ground) return len(ground.intersection(found))/float(len(ground.union(found)))
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import logging def collect_content_packs_to_install(id_set: Dict, integration_ids: set, playbook_names: set, script_names: set) -> set: """Iterates all content entities in the ID set and extract the pack names for the modified ones. Args: id_set (Dict): Structure which holds a...
bigcode/self-oss-instruct-sc2-concepts
def maximum_severity(*alarms): """ Get the alarm with maximum severity (or first if items have equal severity) Args: *alarms (Tuple[AlarmSeverity, AlarmStatus]): alarms to choose from Returns: (Optional[Tuple[AlarmSeverity, AlarmStatus]]) alarm with maximum severity; none for no argumen...
bigcode/self-oss-instruct-sc2-concepts
def extractRoi(frame, pos, dia): """ Extracts a region of interest with size dia x dia in the provided frame, at the specied position Input: frame: Numpy array containing the frame pos: 2D position of center of ROI dia: Integer used as width and height of the ROI Ou...
bigcode/self-oss-instruct-sc2-concepts
import secrets import click def generate_secret_key(num_bytes, show=True): """Generate and print a random string of SIZE bytes.""" rnd = secrets.token_urlsafe(num_bytes) if show: click.secho(rnd) return rnd
bigcode/self-oss-instruct-sc2-concepts
def npy_cdouble_from_double_complex(var): """Cast a Cython double complex to a NumPy cdouble.""" res = "_complexstuff.npy_cdouble_from_double_complex({})".format(var) return res
bigcode/self-oss-instruct-sc2-concepts
def find_highest_degree(graph): """ Find the highest degree in a graph """ degrees = graph.degree() max_degree = 0 for node in degrees: if degrees[node] > max_degree: max_degree = degrees[node] return max_degree
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable import functools from typing import Any import warnings def deprecated(func: Callable) -> Callable: """Decorator that can be used to mark functions as deprecated, emitting a warning when the function is used. Arguments: func: The function to be decorated. ...
bigcode/self-oss-instruct-sc2-concepts
def printtable(table, moe=False): """Pretty print information on a Census table (such as produced by `censustable`). Args: table (OrderedDict): Table information from censustable. moe (bool, optional): Display margins of error. Returns: None. Examples:: censusdata.printtable(censusdata.censustable('acs5...
bigcode/self-oss-instruct-sc2-concepts
def _juniper_vrf_default_mapping(vrf_name: str) -> str: """ This function will convert Juniper global/default/master routing instance => master => default :param vrf_name: :return str: "default" if vrf_name = "master" else vrf_name """ if vrf_name == "master": return "default" ...
bigcode/self-oss-instruct-sc2-concepts
def nz(df, y=0): """ Replaces NaN values with zeros (or given value) in a series. Same as the nz() function of Pinescript """ return df.fillna(y)
bigcode/self-oss-instruct-sc2-concepts
def placemark_name(lst): """Formats the placemark name to include its state if incomplete.""" if lst[1] == 'Complete': return lst[0] else: return ': '.join(lst)
bigcode/self-oss-instruct-sc2-concepts
def calc_suffix(_str, n): """ Return an n charaters suffix of the argument string of the form '...suffix'. """ if len(_str) <= n: return _str return '...' + _str[-(n - 3):]
bigcode/self-oss-instruct-sc2-concepts
from typing import List def datum_is_sum(datum: int, preamble: List[int]) -> bool: """Iterate the preamble numbers and determine whether datum is a sum. Args: datum (int): a number that should be a sum of any two numbers in preamble preamble (List[int]): a list of preceeding n num...
bigcode/self-oss-instruct-sc2-concepts
def filter_data(data, var_val_pairs): """ We use this to filter the data more easily than using pandas subsetting Args: data (df) is a dataframe var_val pairs (dict) is a dictionary where the keys are variables and the value are values """ d = data.copy() for k, v in var_val_pa...
bigcode/self-oss-instruct-sc2-concepts
def getFirstMatching(values, matches): """ Return the first element in :py:obj:`values` that is also in :py:obj:`matches`. Return None if values is None, empty or no element in values is also in matches. :type values: collections.abc.Iterable :param values: list of items to look through, c...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import List def compute_padding(kernel_size: Tuple[int, int]) -> List[int]: """Computes padding tuple.""" # 4 ints: (padding_left, padding_right,padding_top,padding_bottom) # https://pytorch.org/docs/stable/nn.html#torch.nn.functional.pad assert len(kernel_size) =...
bigcode/self-oss-instruct-sc2-concepts
def _calculate_temperature(c, h): """ Compute the temperature give a speed of sound ``c`` and humidity ``h`` """ return (c - 331.4 - 0.0124 * h) / 0.6
bigcode/self-oss-instruct-sc2-concepts
def get_region(df, region): """ Extract a single region from regional dataset. """ return df[df.denominazione_regione == region]
bigcode/self-oss-instruct-sc2-concepts
def get_installed_tool_shed_repository( trans, id ): """Get a tool shed repository record from the Galaxy database defined by the id.""" return trans.sa_session.query( trans.model.ToolShedRepository ).get( trans.security.decode_id( id ) )
bigcode/self-oss-instruct-sc2-concepts