seed
stringlengths
1
14k
source
stringclasses
2 values
def listAxes(axd): """ make a list of the axes from the dictionary of axes Parameters ---------- axd : dict a dict of axes, whose values are returned in a list Returns ------- list : a list of the axes """ if type(axd) is not dict: if type(axd) is l...
bigcode/self-oss-instruct-sc2-concepts
def pagetitle(string, remove_first=False, divider=' > '): """Convert a string of characters to page-title format. Args: string (str): The string to conert. remove_first (bool, optional): Remove the first instance of the delimiter of the newly formed title. Returns: str:...
bigcode/self-oss-instruct-sc2-concepts
def create_business_hours_schedule(api, configuration, api_version, api_exception): """ Creates a schedule for an activity that occurs during normal business hours. :param api: The Deep Security API modules. :param configuration: Configuration object to pass to the api client. :param api_version: The v...
bigcode/self-oss-instruct-sc2-concepts
def gen_post_id(reddit_obj_id): """ Generates the Elasticsearch document id for a post Args: reddit_obj_id (int|str): The id of a reddit object as reported by PRAW Returns: str: The Elasticsearch document id for this object """ return "p_{}".format(reddit_obj_id)
bigcode/self-oss-instruct-sc2-concepts
def collection_to_dict(collection): """Utility function to construct collection dict with names.""" return {v.name[:v.name.rfind(':')]: v for v in collection}
bigcode/self-oss-instruct-sc2-concepts
def _ofc(id): """OFC ID converter.""" return "ofc-%s" % id
bigcode/self-oss-instruct-sc2-concepts
def snake2pascal(target: str) -> str: """Convert snake case to pascal case Args: target (str) Returns: str """ return ''.join(map(lambda x: x.title(), target.split('_')))
bigcode/self-oss-instruct-sc2-concepts
import stat def calc_mode( sticky=False, isuid=True, isgid=True, type=stat.S_IFREG, owner_read=True, owner_write=True, owner_exec=True, group_read=True, group_write=True, group_exec=True, other_read=True, other_write=True, other_exec=True, ): """helper function to calculate the mode bits of a file.""" ...
bigcode/self-oss-instruct-sc2-concepts
def get_limit_spec(limit): """ Based on an input *limit* string of the form: <system>.<type>.<direction>.<qualifier> (where the "qualifier" element is optional) return the various pieces into a dictionary for convenience. Parameters ---------- limit : str The input limit s...
bigcode/self-oss-instruct-sc2-concepts
def unpack_quantity(row, concept, value): """Unpack row like {"variable": [{"concept":<concept>, <value>:_i_want_this_}]} Args: row (dict): Row of Worldbank API data. concept (str): The name of the dataset containing the variable. value (str): The name of the variable to unpack. Ret...
bigcode/self-oss-instruct-sc2-concepts
def serializeEdge(edge): """Return the Edge as native Python datatypes, fit for json. Edges only reference Knobs, so we have to store their Node id here to be able to correctly associate it once reconstructed. """ return { "source_nodeId": edge.source.node().uuid, "source_name": edg...
bigcode/self-oss-instruct-sc2-concepts
def no_preproc(x, **kwargs): """Identity function that can be passed used as feature_preproc_fn in Dataset, since lambda is not pickleable and doesn't take an arbitrary number of params.""" return x
bigcode/self-oss-instruct-sc2-concepts
import math def quaternion_from_matrix(M): """Returns the 4 quaternion coefficients from a rotation matrix. Parameters ---------- M : list[list[float]] The coefficients of the rotation matrix, row per row. Returns ------- [float, float, float, float] The quaternion coeffi...
bigcode/self-oss-instruct-sc2-concepts
from unittest.mock import patch def patch_bond_device(return_value=None): """Patch Bond API device endpoint.""" return patch( "homeassistant.components.bond.Bond.device", return_value=return_value, )
bigcode/self-oss-instruct-sc2-concepts
def is_local_ressource(path): """ Check if given path is a local ressource. Arguments: path (string): Ressource path. Returns: bool: True if file path, else False. """ if not path.startswith("http://") and not path.startswith("https://"): return True return False
bigcode/self-oss-instruct-sc2-concepts
def strip_signature_from_subject(content): """Assume --\n is marker for email signature and return everything before. """ return content.split('--')[0]
bigcode/self-oss-instruct-sc2-concepts
import itertools def compress(string: str) -> str: """Return string represented as tuples of characters and their count.""" return " ".join([ "({})".format(", ".join((str(len(list(grp))), char))) for char, grp in itertools.groupby(string, lambda c: c) ])
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def from_datetime(value: datetime) -> str: """Convert from datetime to ISO8601-formatted string. Parameters ---------- value : datetime The datetime to be converted. Expected in UTC. Returns ------- str ISO8601-formatted string Examples ...
bigcode/self-oss-instruct-sc2-concepts
def session_status(space): """Returns the current session status""" return space.wrap(space.ec.interpreter.session.status)
bigcode/self-oss-instruct-sc2-concepts
def get_attack_details(ipal_entry): """ Parse the attack-details IPAL field. The field is expected to have the format "<attack category>;<attack type>". Example: "2;12". """ split = ipal_entry["attack-details"].split(";") assert ( len(split) == 2 ), "'attack-details' field in IP...
bigcode/self-oss-instruct-sc2-concepts
def little_endian_data() -> bytes: """Little endian data fixture.""" return b"\x00\x00\x00\x05\x00\x00\x00\x06"
bigcode/self-oss-instruct-sc2-concepts
import time def get_current_time(time_form: str="%Y%m%d%H%M%S"): """ get_current_time from time Args: time_form: str, string form of return time Returns: time_current: str """ time_now = int(time.time()) time_local = time.localtime(time_now) time_current = time.strftime...
bigcode/self-oss-instruct-sc2-concepts
def get_marc_as_list(raw_marc): """Method takes Solr MARC format and splits into a list of field dictionarys :param raw_marc: Raw MARC string :rtype: List of field dictionary """ output = [] marc_listing = raw_marc.split("=") for row in marc_listing: output.append({'tag':row[0:3], ...
bigcode/self-oss-instruct-sc2-concepts
import math def calculate(point1, point2): """ Calculate the distance between two points (point1 and point2) on the Earth's surface using the 'spherical law of cosines' formula. Input: point1 : two floating point numbers between -180 and 180, where positive indicates North/East ...
bigcode/self-oss-instruct-sc2-concepts
def request_input(message, choices): """ Request user input. Parameters ---------- message : str Message to display choices : list of str List of recognized inputs """ while True: choice = input(message).strip().lower() if choice in choices: ...
bigcode/self-oss-instruct-sc2-concepts
def _append_norm(ktl0, norm_types): """Generate human-readable labels for multiple norms.""" ktl = {} for norm_type in norm_types: for key, val in ktl0.items(): ktl['%s/%s' % (key, norm_type)] = '%s(%s)' % (val, norm_type) return ktl
bigcode/self-oss-instruct-sc2-concepts
def get_rules_with_scope(rules, scope): """ from the given collection of rules, select those with the given scope. args: rules (List[capa.rules.Rule]): scope (str): one of the capa.rules.*_SCOPE constants. returns: List[capa.rules.Rule]: """ return list(rule for rule in rules...
bigcode/self-oss-instruct-sc2-concepts
def _SharedPrefix(pattern1, pattern2): """Returns the shared prefix of two patterns. Args: pattern1: A handler's pattern string pattern2: A handler's pattern string Returns: The shared prefix of the two patterns, up to the index of the first wildcard of either pattern. For example, the shared pre...
bigcode/self-oss-instruct-sc2-concepts
def get_enum_strings(enum_strings, enum_dict): """Get enum strings from either `enum_strings` or `enum_dict`.""" if enum_dict: max_value = max(enum_dict) return [enum_dict.get(idx, '') for idx in range(max_value + 1)] return enum_strings
bigcode/self-oss-instruct-sc2-concepts
from typing import List def sauvegarde_fichier(nom_fichier : str, Contenu : List[str]) -> None: """Précondition : nom_fichier est un nom correct de fichier Sauvegarde le Contenu comme lignes de texte dans le fichier identifié par nom_fichier Attention : si le fichier existe déjà son contenu sera e...
bigcode/self-oss-instruct-sc2-concepts
def make_columns(repetitions, n_splits): """Provides column names for the tables of all predictions (from each split of each rep). Parameters ---------- repetitions : int Repetitions of the n-fold validation n_splits : int number of splits in KFold Returns ------- l...
bigcode/self-oss-instruct-sc2-concepts
def id_is_generic(inid, inyear): """ Test to see if an ID is one of the generic IDs :param inid: ID from marine report :param inyear: year we are checking for :type inid: string :type inyear: integer :return: True if the ID is generic and False otherwise :rtype: logical Cer...
bigcode/self-oss-instruct-sc2-concepts
def reduce_broadcast(grad, var_shape): """ Sum-reduce axes of `grad` so its shape matches `var_shape. This the appropriate mechanism for backpropagating a gradient through an operation in which broadcasting occurred for the given variable. Parameters ---------- grad...
bigcode/self-oss-instruct-sc2-concepts
def merge_dicts(dict1, dict2): """ Merge two dictionaries. Parameters ---------- dict1, dict2 : dict Returns ------- dict_merged : dict Merged dictionaries. """ dict_merged = dict1.copy() dict_merged.update(dict2) return dict_merged
bigcode/self-oss-instruct-sc2-concepts
def select_all_columns_except_some(df, column_names): """Select all columns in the dataframe except those specified in ``column_list``. Args: df (pd.DataFrame): Dataframe. column_names (list): List of column names. Returns: pd.DataFrame: Dataframe with the columns removed. ...
bigcode/self-oss-instruct-sc2-concepts
import json def reject(status_code, **kwargs): """ Bad request. :param int status_code: Rejection status code :param dict kwargs: Rejection body JSON :return dict: Rejection response """ body = json.dumps(kwargs) if kwargs else '' headers = { 'content-length': len(body), ...
bigcode/self-oss-instruct-sc2-concepts
import torch def to_torchaudio(tensor, dim: int = -2): """Converts complex-like torch tensor to torchaudio style complex tensor. Args: tensor (torch.tensor): asteroid-style complex-like torch tensor. dim(int, optional): the frequency (or equivalent) dimension along which real and ...
bigcode/self-oss-instruct-sc2-concepts
def parse_stream(stream): """This function parses the contents of a stream to generate a list of lines. This function removes comments delimited by '#', ingores empty lines, and leading and trailing whitespace. Args: stream : A file that has been open()'d Returns: A list of lines. """ lines = ...
bigcode/self-oss-instruct-sc2-concepts
def user_id(msg): """ Use the userid from the msg as the user search criteria Args: msg (errbot.backends.base.Message): The message from the bot that triggered the LDAP lookup Returns: str: The user ID that will be used to search LDAP """ if hasattr(msg.frm, "userid"): ...
bigcode/self-oss-instruct-sc2-concepts
def CreateEmptyHubDictionary(input_map): """hub_map_tools.CreateEmptyHubDictionary() INPUTS: - input_map -- a hub map dictionary with teacher or grade name keys, and hub IDs for values OUTPUTS: - output_map -- a new dictionary keyed by unique hub IDs, and having ...
bigcode/self-oss-instruct-sc2-concepts
def getMBR(ploygon): """ get the Minimum Bounding Rectangle of the given ploygon :param ploygon: the given polygon :return: the given ploygon's MBR """ left_bottom_x = float('inf') left_bottom_y = float('inf') right_up_x = float('-inf') right_up_y = float('-inf') for plg in ployg...
bigcode/self-oss-instruct-sc2-concepts
def convert_qa_input_dict(infer_dict): """ Input dictionaries in QA can either have ["context", "qas"] (internal format) as keys or ["text", "questions"] (api format). This function converts the latter into the former. It also converts the is_impossible field to answer_type so that NQ and SQuAD dicts have t...
bigcode/self-oss-instruct-sc2-concepts
def max_val(t): """ t, tuple or list Each element of t is either an int, a tuple, or a list No tuple or list is empty Returns the maximum int in t or (recursively) in an element of t """ def find_all_int(data): int_list = [] for item in data: if isinstance(item, l...
bigcode/self-oss-instruct-sc2-concepts
def spin_energy(J = -2, mu = 1.1, k = 1, state = [1,-1,1,-1]): """Computes the energy of some spin configuration. Note, all lists should be in the format of a sequential list where 1 is spin up and -1 is spin down :param J: Ferromagnetic constant, defaults to -2 :type J: int or float :p...
bigcode/self-oss-instruct-sc2-concepts
def parse_reference(reference): """ Helper function, parses a 'reference' to document name and anchor """ if "#" in reference: docname, anchor = reference.split("#", 1) else: docname = reference anchor = None return docname, anchor
bigcode/self-oss-instruct-sc2-concepts
import torch def torch_cat_dicts(L): """Concatenates a list of dictionary of torch tensors L = [{k: v1}, {k: v2}, ...] to {k: [v1; v2]} """ d = {} if L: K = L[0].keys() cat_fns = [torch.hstack if L[0][k].ndim == 0 else torch.cat for k in K] for cat_fn...
bigcode/self-oss-instruct-sc2-concepts
def partition_games(df, frac=0.7): """ Returns a 2-tuple of arrays containing the indices. The first are the indices in the dataframe that correspond to the first <frac> games of each season. The second are the indices that correspond to the last <1-frac> games of each season. Assumes that the g...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import Any def safe_ith(arr: Optional[list], ind: int, default: Any = None) -> Optional[Any]: """Performs safe index access. If array is None, returns default.""" if arr is not None: return arr[ind] return default
bigcode/self-oss-instruct-sc2-concepts
def decode_report_item_id(report_id): """Provided with a DOM report item id return the report_item id in the database""" return int(report_id.replace("reportItem", "").split("-")[1])
bigcode/self-oss-instruct-sc2-concepts
def count_refs_in_mapping( references, mapping ): """Count the number of references in the mapping""" count = 0 for r in references: if r in mapping: count += 1 return count
bigcode/self-oss-instruct-sc2-concepts
def to_list(val): """ Method for casting an object into a list if it isn't already a list """ return val if type(val) is list else [val]
bigcode/self-oss-instruct-sc2-concepts
import random def random_seq(size, nucleotides="ACTG"): """Generate a random nucleotide sequence of length `size` and composition `nucleotides` Parameters ---------- size : int length of desired sequence nucleotides : str, optional string of nucleotides to use in sequ...
bigcode/self-oss-instruct-sc2-concepts
def convert(seconds): """ Convert seconds to (seconds, minutes, hours, remainder_seconds) """ r = seconds s = r % 60 m = (r - s) % (60*60) h = (r - s - m) % (60*60*60) return s, int(m/60), int(h/(60*60)), r - (s + m + h)
bigcode/self-oss-instruct-sc2-concepts
def dup_mul_term(f, c, i, K): """ Multiply ``f`` by ``c*x**i`` in ``K[x]``. Examples ======== >>> R, x = ring("x", ZZ) >>> R.dmp_mul_term(x**2 - 1, ZZ(3), 2) 3*x**4 - 3*x**2 """ if not c or not f: return [] else: return [cf * c for cf in f] + [K.zero]*i
bigcode/self-oss-instruct-sc2-concepts
def pull_pairs(flat): """Return a Iterable of pairs of adjacent items in another Iterable `flat` should be of even size: `len(list(flat)) % 2 == 0` >>> list(pull_pairs([1, 2, 3, 4])) [(1, 2), (3, 4)] """ it = iter(flat) return zip(it, it)
bigcode/self-oss-instruct-sc2-concepts
def sizes_execpt(inp, dim): """return all except the specified dimension indices""" return [s for d, s in enumerate(inp.shape) if d != dim]
bigcode/self-oss-instruct-sc2-concepts
def _find_neighborhoods_ids(input_list, neighborhoods_df): """ Read in a list of names of neighborhood names. Returns a list of neighbhorhood ids Args: input_list: a list containing the names of the neighborhoods in the treatment group. neighborhoods_df: a dataframe containi...
bigcode/self-oss-instruct-sc2-concepts
def slowest_speed(speed_list): """ Compute the derived speed by finding the slowest object in the speed_list. :param speed_list: A list of objects with a speed_mb attribute. :returns: Speed as an integer. """ speed_mb = 0 if speed_list: for obj in speed_list: if not spee...
bigcode/self-oss-instruct-sc2-concepts
def world2pixel(x,y,w,h,bbox): """Converts world coordinates to image pixel coordinates""" # Bounding box of the map minx,miny,maxx,maxy=bbox # world x distance xdist=maxx-minx # world y distance ydist=maxy-miny # scaling factors for x,y xratio = w/xdist yratio = h/ydist # Calculate x,y pixel co...
bigcode/self-oss-instruct-sc2-concepts
def dominating_set(G): """ Finds a greedy approximation for a minimal vertex cover of a specified graph. At each iteration, the algorithm picks the vertex with the highest degree and adds it to the cover, until all edges are covered. :param G: networkx graph :return: vertex cover as a list of ...
bigcode/self-oss-instruct-sc2-concepts
def convert_iob_to_iobes(iob_tags): """Converts a sequence of IOB tags into IOBES tags.""" iobes_tags = [] # check each tag and its following one. A None object is appended # to the end of the list for tag, next_tag in zip(iob_tags, iob_tags[1:] + [None]): if tag == 'O': io...
bigcode/self-oss-instruct-sc2-concepts
def getTitlePerks() -> list: """ Get the list of perks to look for in the job description :return: list - list of perks """ perkList = ["Why you'll like working here", 'Benefits', "The top five reasons our team members joined us (according to them)", "What’s in it fo...
bigcode/self-oss-instruct-sc2-concepts
import operator def max_element (elements, ordered = None): """ Returns the maximum number in 'elements'. Uses 'ordered' for comparisons, or '<' is none is provided. """ if not ordered: ordered = operator.lt max = elements [0] for e in elements [1:]: if ordered (max, e): ...
bigcode/self-oss-instruct-sc2-concepts
def prid(obj, show_cls=False): """Get the id of an object as a hex string, optionally with its class/type.""" if obj is None: s = 'None' else: s = hex(id(obj)) if show_cls: s += str(type(obj)) return s
bigcode/self-oss-instruct-sc2-concepts
def extract_seq_pseudo_label_from_submission(submission_df, rna_seq_id, pred_cols=None): """ Each Kaggle's OpenVaccine submission csv file can be used to make a pseudo label. OpenVaccine submission format is explained here: https://www.kaggle.com/c/stanford-covid-vaccine/overview/evaluation Exampl...
bigcode/self-oss-instruct-sc2-concepts
def calculate_point_triplet_orientation(coordinate_1, coordinate_2, coordinate_3): """ Returns a value that represents the negative sine of the angle created by connecting coordinate_1 to coordinate_2 to coordinate_3. If this connection occurs in a clockwise fashion the value will be negative, counterc...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List def create_column_statement(name: str, data_type: str, nullable: bool, constraints: Union[List, None] = None, **kwargs) -> str: """Function for generatin...
bigcode/self-oss-instruct-sc2-concepts
def _MergeProguardConfigs(proguard_configs): """Merging the given proguard config files and returns them as a string.""" ret = [] for config in proguard_configs: ret.append('# FROM: {}'.format(config)) with open(config) as f: ret.append(f.read()) return '\n'.join(ret)
bigcode/self-oss-instruct-sc2-concepts
def scoped_logger_name(module_name: str, config_name: str = "maestral") -> str: """ Returns a logger name for the module ``module_name``, scoped to the given config. :param module_name: Module name. :param config_name: Config name. :returns: Scoped logger name. """ if config_name == "maest...
bigcode/self-oss-instruct-sc2-concepts
def op_help(oper, left_op, right_op): """Helper method does math on operands and returns them""" if oper == '+': return left_op + right_op elif oper == '-': return left_op - right_op elif oper == '*': return left_op * right_op else: return left_op / right_op
bigcode/self-oss-instruct-sc2-concepts
import pickle def serialize(x): """Return a pickled object.""" return pickle.dumps(x)
bigcode/self-oss-instruct-sc2-concepts
def preload(pytac_lat): """Load the elements onto an 'elems' object's attributes by family so that groups of elements of the same family can be more easily accessed, e.g. 'elems.bpm' will return a list of all the BPMs in the lattice. As a special case 'elems.all' will return all the elements in the latt...
bigcode/self-oss-instruct-sc2-concepts
def list_to_csv(parlist, sep=", "): """Returns a csv string with elements from a list.""" result_str = "" for par in parlist: result_str += str(par) + sep return result_str[:-len(sep)]
bigcode/self-oss-instruct-sc2-concepts
import importlib def load_command_class(name): """ Given a command name, returns the Command class instance. All errors raised by the import process (ImportError, AttributeError) are allowed to propagate. """ module = importlib.import_module(f's2e_env.commands.{name}') return module.Comman...
bigcode/self-oss-instruct-sc2-concepts
def build_datasets_by_publisher_query() -> str: """Build query to count datasets grouped by publisher.""" return """ PREFIX dct: <http://purl.org/dc/terms/> PREFIX dcat: <http://www.w3.org/ns/dcat#> SELECT ?organizationNumber (COUNT(DISTINCT ?dataset) AS ?count) FROM <https://datasets.fellesdatakatalog.digdir.n...
bigcode/self-oss-instruct-sc2-concepts
def update_list(content, new_values): """Update a list with additional or new values.""" new_content = content[:] if content else [] new_values = [x.strip() for x in new_values.split(",")] if isinstance(new_values, str) else new_values or [] for value in new_values: if value == "-": ...
bigcode/self-oss-instruct-sc2-concepts
def checkColumns(board: list) -> bool: """ Returns True if there is no repeating numbers in the columns. """ for i in range(len(board[0])): column = [] for line in board: if line[i].isnumeric(): column.append(line[i]) if len(column) != len(set(column))...
bigcode/self-oss-instruct-sc2-concepts
def f(z): """ A function of metallicity Z, which we will set as the yield of Sr from core-collapse supernovae. """ return 3.5e-8 * (z / 0.014)
bigcode/self-oss-instruct-sc2-concepts
def GetMessageFromQueue(session, queueurl, delete_after_receive=False): """Get message from the queue to process :param session: Session to use for AWS access :type session: boto3.session.Session :param queueurl: URL of the queue from which to receive messages :type queueurl: str :param delete_after_receiv...
bigcode/self-oss-instruct-sc2-concepts
def offset_api_limit(sp, sp_call): """ Get all (non-limited) artists/tracks from a Spotify API call. :param sp: Spotify OAuth :param sp_call: API function all :return: list of artists/tracks """ results = sp_call if 'items' not in results.keys(): results = results['artists'] ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def make_normalization_function(min_value: float, max_value: float, scope=(0, 1)) -> Callable: """ Minimax normalization :param min_value: Min value in data :param max_value: Max value in data :param scope: Normalization range :return: normalization function ""...
bigcode/self-oss-instruct-sc2-concepts
import requests def request(url, input_file, token, include_words=False): """ :param input_file: Input object :param url: Endpoint url :param token: X-Inferuser-Token :param include_words: Include Mindee vision words in http_response :return: requests response """ input_file.file_objec...
bigcode/self-oss-instruct-sc2-concepts
def xml_get_attrs(xml_element, attrs): """Returns the list of necessary attributes Parameters: element: xml element attrs: tuple of attributes Returns: a dictionary of elements """ result = {} for attr in attrs: result[attr] = xml_element.getAttribute(attr) ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def _get_api_headers(token: str) -> Dict: """ Return authorization header with current token. Parameters ---------- token : str Azure auth token. Returns ------- Dict A dictionary of headers to be used in API calls. """ return { ...
bigcode/self-oss-instruct-sc2-concepts
def arg_cond_req_or(args_array, opt_con_req_dict): """Function: arg_cond_req_or Description: Checks a dictionary list array for options that require one or more options to be included in the argument list. Arguments: (input) args_array -> Array of command line options and values. ...
bigcode/self-oss-instruct-sc2-concepts
def fanout(w): """ Get the number of places a wire is used as an argument. :param w: WireVector to check fanout for :return: integer fanout count """ _, dst_nets = w._block.net_connections() if w not in dst_nets: return 0 all_args = [arg for net in dst_nets[w] for arg in net.args] ...
bigcode/self-oss-instruct-sc2-concepts
def get_tree( graph, root, prop, mapper=lambda x: x, sortkey=None, done=None, dir="down" ): """ Return a nested list/tuple structure representing the tree built by the transitive property given, starting from the root given i.e. get_tree(graph, rdflib.URIRef("http://xmlns.com/foaf/0.1/P...
bigcode/self-oss-instruct-sc2-concepts
def get_file_contents(file_path): """ Get expected result from file. """ try: with open(file_path, 'r') as f: # remove string literals (needed in python2) and newlines return f.read().replace('\r', '').strip() except OSError as e: raise e
bigcode/self-oss-instruct-sc2-concepts
def endswith_xFFxD9(data): """ Checks whether the given data endswith `b'\xD9\xFF'` ignoring empty bytes at the end of it. Parameters ---------- data : `bytes-like` Returns ------- result : `bool` """ index = len(data) - 1 while index > 1: actual = data[index] ...
bigcode/self-oss-instruct-sc2-concepts
def infix(formula: str, arg: int): """ evaluation of infix expression :param formula: bytebeat formula :param arg: time argument :return: int: computation result """ characters = formula.replace("t", str(arg)).replace("/", "//") try: return eval(characters) except...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_list_nab() -> list: """ Get list of possible time series to retrieve from the Numenta Anomaly Benchmark: https://github.com/numenta/NAB. Returns ------- List with time series names. """ url_labels = 'https://raw.githubusercontent.com/numenta/NAB/master/labels/combi...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def first_subset_second(first: Dict, second: Dict) -> bool: """ Return true if first is a subset of second, false otherwise. :param first: first dict :param second: second dict :return: true if all elements in first are in second, and are mapped to same value,...
bigcode/self-oss-instruct-sc2-concepts
def mean(items): """ Calculates arithmetic mean. Returns zero for empty lists. """ return float(sum(items)) / len(items) if items else 0
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def _build_date(date, kwargs): """ Builds the date argument for event rules. """ if date is None: if not kwargs: raise ValueError('Must pass a date or kwargs') else: return datetime.date(**kwargs) elif kwargs: raise Val...
bigcode/self-oss-instruct-sc2-concepts
def parse(puzzle_input): """Parse input""" return [int(line) for line in puzzle_input.split()]
bigcode/self-oss-instruct-sc2-concepts
import six def to_utf8(string): """ Encode a string as a UTF8 bytestring. This function could be passed a bytestring or unicode string so must distinguish between the two. """ if isinstance(string, six.text_type): return string.encode('utf8') return string
bigcode/self-oss-instruct-sc2-concepts
import gzip def reader(fname): """Returns correct file object handler or reader for gzipped or non-gzipped FastQ files based on the file extension. Assumes gzipped files endwith the '.gz' extension. """ if fname.endswith('.gz'): # Opens up file with gzip handler return gzip.open ...
bigcode/self-oss-instruct-sc2-concepts
import torch def one_hot_encoding(input_tensor, num_labels): """ One-hot encode labels from input """ return torch.eye(num_labels, device=input_tensor.device)[input_tensor]
bigcode/self-oss-instruct-sc2-concepts
def check_type(lp): """ check the type of the launchpad :param lp: launchpad object :return: name of launchpad type """ if lp.Check(0, "pro"): print("Launchpad Pro") return "Pro" elif lp.Check(0, "mk2"): print("Launchpad Mk2") return "Mk2" else: ...
bigcode/self-oss-instruct-sc2-concepts
def edits0(word): """ Return all strings that are zero edits away from the input word (i.e., the word itself). """ return {word}
bigcode/self-oss-instruct-sc2-concepts