seed
stringlengths
1
14k
source
stringclasses
2 values
def update_lifecycle_test_tags(lifecycle, test, tags): """Returns lifecycle object after creating or updating the tags for 'test'.""" if not lifecycle["selector"]["js_test"]: lifecycle["selector"]["js_test"] = {test: tags} else: lifecycle["selector"]["js_test"][test] = tags return lifecy...
bigcode/self-oss-instruct-sc2-concepts
def determine(userChoice, computerChoice): """ This function takes in two arguments userChoice and computerChoice, then determines and returns that who wins. """ if(userChoice == "Rock" and computerChoice == "Paper"): return "computer" elif(userChoice == "Rock" and computerChoice...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime import pytz def is_in_the_future(dt): """ Is this (UTC) date/time value in the future or not? """ if dt > datetime.now(pytz.utc): return True return False
bigcode/self-oss-instruct-sc2-concepts
def ensure_tuple(tuple_or_mixed, *, cls=tuple): """ If it's not a tuple, let's make a tuple of one item. Otherwise, not changed. :param tuple_or_mixed: :return: tuple """ if isinstance(tuple_or_mixed, cls): return tuple_or_mixed if tuple_or_mixed is None: return tuple...
bigcode/self-oss-instruct-sc2-concepts
def _interp_evaluate(coefficients, t0, t1, t): """Evaluate polynomial interpolation at the given time point. Args: coefficients: list of Tensor coefficients as created by `interp_fit`. t0: scalar float64 Tensor giving the start of the interval. t1: scalar float64 Tensor giving the end of...
bigcode/self-oss-instruct-sc2-concepts
import json def write_json(file_path, json_obj): """Write JSON string. # Arguments file_path: `str`<br/> the absolute path to the JSON string. json_obj: `dict`<br/> a dictionary # Returns flag : bool True if saved successfully False...
bigcode/self-oss-instruct-sc2-concepts
def broken_6(n): """ What comes in: A positive integer n. What goes out: Returns the sum: 1 + 1/2 + 1/3 + ... + 1/n. Side effects: None. """ total = 0 for k in range(1, n + 1): total = total + 1 / k return total
bigcode/self-oss-instruct-sc2-concepts
def fantasy_pros_column_reindex(df): """Adds columns that are missing from Fantasy Pros tables and reorders columns Some tables are missing stats (no passing stats for RBs) so this will fill in the gaps and have '0' as the value for any missing column :param df: cleaned dataframe object resul...
bigcode/self-oss-instruct-sc2-concepts
def no_comment_row(x_str): """ Tests if the row doesn't start as a comment line. """ return x_str[0] != "#"
bigcode/self-oss-instruct-sc2-concepts
def density(w, **kwargs): """Compute density of a sparse vector. Parameters ---------- w : array-like The sparse vector. Returns ------- float The density of w, between 0 and 1. """ if hasattr(w, "toarray"): d = float(w.nnz) / (w.shape[0] * w.shape[1]) e...
bigcode/self-oss-instruct-sc2-concepts
def id_from_uri(uri: str) -> str: """Get the item ID from URI address.""" return uri.rstrip("/").split("/")[-1]
bigcode/self-oss-instruct-sc2-concepts
def gen_model(model_name, image_tag, timeout, num_of_workers): """ Generates the Sagemaker model that will be loaded to the endpoint instances. """ model = { "SagemakerModel": { "Type": "AWS::SageMaker::Model", "Properties": { "ModelName": model_name, ...
bigcode/self-oss-instruct-sc2-concepts
import pickle def unpickle(file): """Unpickle something (in this case tf-id).""" with open(file, "rb") as source: return pickle.load(source)
bigcode/self-oss-instruct-sc2-concepts
def lammps_copy_files(job): """Check if the submission scripts have been copied over for the job.""" return job.isfile("submit.pbs")
bigcode/self-oss-instruct-sc2-concepts
def encode_count_header(count): """ Generate a header for a count HEAD response. """ return { "X-Total-Count": count, }
bigcode/self-oss-instruct-sc2-concepts
def round_up(n: int, div: int): """Round up to the nearest multiplier of div.""" return ((n + div - 1) // div) * div
bigcode/self-oss-instruct-sc2-concepts
import math def arc_chord_length(radius: float, sagitta: float) -> float: """Returns the chord length for an arc defined by `radius` and the `sagitta`_. Args: radius: arc radius sagitta: distance from the center of the arc to the center of its base """ return 2.0 * math.sqrt(2.0 ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import AnyStr from typing import Any def update_dictionary_keys_with_prefixes(input_dict: Dict[AnyStr, Any], prefix: AnyStr): """Adds a prefix to the keys of a dictionary.""" output_dict = dict((prefix + key, value) for (key, value) in input_dict.items()) return output_...
bigcode/self-oss-instruct-sc2-concepts
def div2D(v1,v2): """Elementwise division of vector v1 by v2""" return (v1[0] / v2[0], v1[1] / v2[1])
bigcode/self-oss-instruct-sc2-concepts
def get_visual_selection(lines, start, end): """Split an arbitrary selection of text between lines Args: lines (list): Lines of text to be processed start (tuple): Coordinates of the start of a selection in format (line, char) end (tuple): Coordinates of the en...
bigcode/self-oss-instruct-sc2-concepts
def default_collate(batch): """ Default collate function, used for ParlAIDataset and StreamDataset """ new_batch = [] for b in batch: idx = b[0] if type(b[1]) is list: ep = b[1][0] else: ep = b[1] new_batch.append((idx, ep)) return new_...
bigcode/self-oss-instruct-sc2-concepts
def user_says_yes(message=""): """Check if user input is either 'y' or 'n'. Returns a boolean.""" while True: choice = input(message).lower() if choice == "y": choice = True break elif choice == "n": choice = False break else: ...
bigcode/self-oss-instruct-sc2-concepts
def makespan(sol={}): """Returns the makespan of a solution (model 1's objective function).""" return sol["makespan"]
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def printable_field_location_split(location: str) -> Tuple[str, str]: """Return split field location. If top-level, location is returned as unquoted "top-level". If not top-level, location is returned as quoted location. Examples: (1) field1[idx].foo => 'foo', 'field1[id...
bigcode/self-oss-instruct-sc2-concepts
def replace_string_chars(s1, pos, s2): """ Replace characters in a string at the specified string position (index). @param s1: Input string for replacement. @param pos: Input string index of replace. @param s2: - Replacement string. @return: New resulting string. """ len2 = len(s2) i...
bigcode/self-oss-instruct-sc2-concepts
def path_as_0_moves(path): """ Takes the path which is a list of Position objects and outputs it as a string of rlud directions to match output desired by Rosetta Code task. """ strpath = "" for p in path: if p.directiontomoveto != None: strpath += p.directiontomove...
bigcode/self-oss-instruct-sc2-concepts
import ast def _to_dict(contents): """Parse |contents| as a dict, returning None on failure or if it's not a dict.""" try: result = ast.literal_eval(contents) if isinstance(result, dict): return result except (ValueError, TypeError): pass return None
bigcode/self-oss-instruct-sc2-concepts
import click from typing import Union from typing import Any from typing import List from typing import Tuple from pathlib import Path def validate_path_pair( ctx: click.core.Context, param: Union[click.core.Option, click.core.Parameter], value: Any, ) -> List[Tuple[Path, Path]]: """ Validate a pa...
bigcode/self-oss-instruct-sc2-concepts
def indent(*args) -> str: """Return joined string representations of objects with indented lines.""" text = '\n'.join(str(arg) for arg in args) return '\n'.join( (' ' + line if line else line) for line in text.splitlines() if line )[2:]
bigcode/self-oss-instruct-sc2-concepts
def get_f_min(f_max, cents_per_value, v_min, v_max): """ This function takes in a y value max and min, a maximum frequency and a y scale parameter in units of cents/y value, and returns the minimum frequency that fits to such a scale. Cents are a logarithmic unit of tone intervals (https://en.wikipedia.org/...
bigcode/self-oss-instruct-sc2-concepts
def dup_strip(f): """ Remove leading zeros from ``f`` in ``K[x]``. Examples ======== >>> from sympy.polys.densebasic import dup_strip >>> dup_strip([0, 0, 1, 2, 3, 0]) [1, 2, 3, 0] """ if not f or f[0]: return f i = 0 for cf in f: if cf: brea...
bigcode/self-oss-instruct-sc2-concepts
def column_to_list(data, index): """Return a list with values of a specific column from another list Args: data: The list from where the data will be extracted index: The index of the column to extract the values Returns: List with values of a specific column """ column_list = [] ...
bigcode/self-oss-instruct-sc2-concepts
import itertools import operator def group_versions(versions): """Group versions by `major.minor` releases. Example: >>> group_versions([ Version(1, 0, 0), Version(2, 0, 0, 'rc1'), Version(2, 0, 0), Version(2, 1, 0), ]) ...
bigcode/self-oss-instruct-sc2-concepts
def metacalibration_names(names): """ Generate the metacalibrated variants of the inputs names, that is, variants with _1p, _1m, _2p, and _2m on the end of each name. """ suffices = ['1p', '1m', '2p', '2m'] out = [] for name in names: out += [name + '_' + s for s in suffices] ...
bigcode/self-oss-instruct-sc2-concepts
def getNamespaceUnversioned(string: str): """getNamespaceUnversioned Gives namespace of a type string, version NOT included :param string: :type string: str """ if '#' in string: string = string.rsplit('#', 1)[1] return string.split('.', 1)[0]
bigcode/self-oss-instruct-sc2-concepts
def MultiplyTwoNumbers(a,b): """ multiplying two numbers input: a,b - two numbers output: returns multiplication """ c = a*b return c
bigcode/self-oss-instruct-sc2-concepts
def days_since(t1, t2): """ Returns the number of days between two timestamps. :param t1: Time one. :param t2: Time two. """ timedelta = t1 - t2 return timedelta.days
bigcode/self-oss-instruct-sc2-concepts
import re def substitute(line, regex, class_): """Generate a span and put it in the line per the regex.""" result = re.search(regex, line) if result: for match in result.groups(): line = line.replace( match, '<span class="{}">{}</span>'.format(class_, match), 1 ...
bigcode/self-oss-instruct-sc2-concepts
def ceildiv(a, b): """Divides with ceil. E.g., `5 / 2 = 2.5`, `ceildiv(5, 2) = 3`. Args: a (int): Dividend integer. b (int): Divisor integer. Returns: int: Ceil quotient. """ return -(-a // b)
bigcode/self-oss-instruct-sc2-concepts
def flatten(lst): """Flatten a 2D array.""" return [item for sublist in lst for item in sublist]
bigcode/self-oss-instruct-sc2-concepts
def lcfa_pattern(tmp_path): """Fixture to mock pattern for LCFA files.""" return str(tmp_path / "lcfa-fake" / "lcfa-fake-{year}{month}{day}{hour}{minute}{second}-" "{end_hour}{end_minute}{end_second}.nc")
bigcode/self-oss-instruct-sc2-concepts
def leverage(balance_df): """Checks if the leverage exposure was reduced since previous year Explanation of Leverage: https://www.investopedia.com/terms/l/leverage.asp balance_df = Balance Sheet of the specified company """ # current year assets_curr = balance_df.iloc[balance_df.index.get_l...
bigcode/self-oss-instruct-sc2-concepts
def get_progress(context, scope): """ Returns the number of calls to callbacks registered in the specified `scope`. """ return context.get("progress", {}).get(scope)
bigcode/self-oss-instruct-sc2-concepts
def fread(path): """Reads a file.""" with open(path, 'r') as file: return file.read()
bigcode/self-oss-instruct-sc2-concepts
def Multiply_by_number(matrix_1, number): # умножение матрицы на число """ Функция, которая умножает матрицу на число :params matrix_1: матрица :params matrix_2: число, на которое необходимо умножить матрицу :return matrix_out: матрица, как результат """ matrix_out = [] for...
bigcode/self-oss-instruct-sc2-concepts
def filter_products(queryset, user): """ Restrict the queryset to products the given user has access to. A staff user is allowed to access all Products. A non-staff user is only allowed access to a product if they are in at least one stock record's partner user list. """ if user.is_staff: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def arg_dict_creator(string: Any): """Creates a Dict from a CSV string. Args: string(str): CSV string - formatted as 'field1:value1,field2:value2'. Returns: Dict from string representation. """ if not string: return None split_string = string.s...
bigcode/self-oss-instruct-sc2-concepts
def create_dicts_by_chain(keys_chain: list): """ Create nested dicts by keys chain >>> create_dicts_by_chain(['some', 'keys']) {'some': {'keys': {}}} """ result = {} current_dict = result for key in keys_chain: current_dict[key] = {} current_dict = current_dict[key] r...
bigcode/self-oss-instruct-sc2-concepts
def load_collection(path): """Loads tsv collection into a dict of key: doc id, value: doc text.""" collection = {} with open(path) as f: for i, line in enumerate(f): doc_id, doc_text = line.rstrip().split('\t') collection[doc_id] = doc_text.replace('\n', ' ') if i % 1000000 == 0: pri...
bigcode/self-oss-instruct-sc2-concepts
def sampleIdsFromNode(node, cladeTops=()): """Return a list of IDs of all samples found under node.""" kids = node.get('children') if (kids): sampleIds = [] for kid in kids: if (kid not in cladeTops): sampleIds += sampleIdsFromNode(kid, cladeTops) else: ...
bigcode/self-oss-instruct-sc2-concepts
def dense_flops(in_neurons, out_neurons): """Compute the number of multiply-adds used by a Dense (Linear) layer""" return in_neurons * out_neurons
bigcode/self-oss-instruct-sc2-concepts
def calc_beats(data, rpeak_locs, metrics): """Returns the times when R-peaks occur Args: data (2D numpy array): contains two columns with time and ECG data rpeak_locs (1D numpy array): contains locations of R-peaks metrics (dict): dictionary containing the metrics calculated ...
bigcode/self-oss-instruct-sc2-concepts
def majority_vote(votes, minimum_count=3): """Determine the label voted for by the majority Given a list of binary votes we compute the preferred label based on a simple majority vote if there are atleast `minimum_count` votes. Returns the binary label or `None` if there are not enough votes "...
bigcode/self-oss-instruct-sc2-concepts
def pluralize(n, text, suffix='s'): # type: (int, str, str) -> str """Pluralize term when n is greater than one.""" if n != 1: return text + suffix return text
bigcode/self-oss-instruct-sc2-concepts
def shortest_path_tree(g, s, d): """Reconstruct shortest-path tree rooted at vertex s, given distance map d. Return tree as a map from each reachable vertex v (other than s) to the edge e=(u,v) that is used to reach v from its parent u in the tree. """ tree = {} for v in d: if v is not s: for e in...
bigcode/self-oss-instruct-sc2-concepts
def decodeImage(imageMatrix, bitPlane): """ Method to decode the text inside the image to a text string. Parameters ---------- imageMatrix : list A list of ints with the matrix of pixels of the image to be modified bitPlane : int The...
bigcode/self-oss-instruct-sc2-concepts
def set_blast_min_length(config): """Set minimum sequence length for running blast searches.""" return config["settings"].get("blast_min_length", 1000)
bigcode/self-oss-instruct-sc2-concepts
def local_name(url): """Generate a local filename from a remote URL.""" # We assume that the remote url is separated by / and that the file name # is the final part of the url return url.split('/')[-1]
bigcode/self-oss-instruct-sc2-concepts
def readlines(fil=None,raw=False): """ Read in all lines of a file. Parameters ---------- file : str The name of the file to load. raw : bool, optional, default is false Do not trim \n off the ends of the lines. Returns ------- lines : list The list ...
bigcode/self-oss-instruct-sc2-concepts
def normalize_commit_message(commit_message): """ Return a tuple of title and body from the commit message """ split_commit_message = commit_message.split("\n") title = split_commit_message[0] body = "\n".join(split_commit_message[1:]) return title, body.lstrip("\n")
bigcode/self-oss-instruct-sc2-concepts
import json def load_task(json_file): """Opens a task json file and returns its contents""" try: with open(json_file, 'r') as jinput: raw_input = json.load(jinput) except FileNotFoundError as e: print(f'\n\nError, file not found: {json_file}', end='\n\n') return re...
bigcode/self-oss-instruct-sc2-concepts
def FilterSet(df, annotSet="", annotSetArr=[], annotSetCompare="=", limit=0, negate=False): """Provide the ability to filter a Dataframe of AQAnnotations based on the value in the annotSet field. Args: df: Dataframe of AQAnnotations that will be filtered by the specified annotation set. annotSet: String to...
bigcode/self-oss-instruct-sc2-concepts
import json def load_dictionary_from_json_file(json_file_path): """ Loads a dictionary from file at json_file_path, returns the dictionary. """ with open(json_file_path, 'r') as json_file: return json.load(json_file)
bigcode/self-oss-instruct-sc2-concepts
def getBlockZone(p, aSearch, tBlock, blockSize): """ Retrieves the block searched in the anchor search area to be compared with the macroblock tBlock in the current frame :param p: x,y coordinates of macroblock center from current frame :param aSearch: anchor search area image :param tBlock: macrobl...
bigcode/self-oss-instruct-sc2-concepts
def find (possible): """Returns `(key, index)` such that `possible[key] = [ index ]`.""" for name, values in possible.items(): if len(values) == 1: return name, values[0]
bigcode/self-oss-instruct-sc2-concepts
def construct_raid_bdev(client, name, strip_size, raid_level, base_bdevs): """Construct pooled device Args: name: user defined raid bdev name strip_size: strip size of raid bdev in KB, supported values like 8, 16, 32, 64, 128, 256, 512, 1024 etc raid_level: raid level of raid bdev, supp...
bigcode/self-oss-instruct-sc2-concepts
def fit_pattern(pattern, word): """ Checks if given word fits to the pattern """ if len(pattern) != len(word): return False for i in range(len(pattern)): if pattern[i] != '.' and pattern[i] != word[i]: return False return True
bigcode/self-oss-instruct-sc2-concepts
import json def deserialize_json_response(byte_content): """Deserializes byte content that is a JSON encoding. Args: byte_content: The byte content of a response. Returns: The deserialized python object decoded from JSON. """ return json.loads(byte_content.decode("utf-8"))
bigcode/self-oss-instruct-sc2-concepts
def get_ttl(seconds=None, minutes=None, hours=None, days=None, weeks=None): """ Get ttl in seconds calculated from the arguments. Arguments: seconds (int | None): Number of seconds to include in the ttl. minutes (int | None): Number of minutes to include in the ttl. hours (int | Non...
bigcode/self-oss-instruct-sc2-concepts
def potential_cloud_shadow_layer(nir, swir1, water): """Find low NIR/SWIR1 that is not classified as water This differs from the Zhu Woodcock algorithm but produces decent results without requiring a flood-fill Parameters ---------- nir: ndarray swir1: ndarray water: ndarray Outpu...
bigcode/self-oss-instruct-sc2-concepts
import csv def readCSVIntoList(link): """ Reads CSV to list using 'csv.reader()' Params: link (String) - contains link to the file Returns: tweets_list (List) - containing the tweets in vector form (m x 1) """ tweets_file = csv...
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping def _turn_iterable_to_mapping_from_attribute(attribute, obj, optional=False): """ Given ``obj`` which is either something that is an instance of ``Mapping`` or an iterable, return something that implements ``Mapping`` from ``getattr(o, attribute)`` to the value of the items ...
bigcode/self-oss-instruct-sc2-concepts
import functools import warnings def deprecated(f): """Prints a deprecation warning when called.""" @functools.wraps(f) def wrapper(*args,**kw): warnings.warn_explicit("calling deprecated function %s"%f.__name__, category=DeprecationWarning, ...
bigcode/self-oss-instruct-sc2-concepts
def loan_principal(a: float, i: float, n: float) -> float: """ Calculates the loan principal given annuity payment, interest rate and number of payments :param a: annuity payment :param i: monthly nominal interest rate :param n: number of payments :return: loan principal """ numerator = ...
bigcode/self-oss-instruct-sc2-concepts
import string import random def id_generator(size=6, chars=string.ascii_uppercase + string.digits): """Random string generator. Original code from: http://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python Parameters ---------- size : i...
bigcode/self-oss-instruct-sc2-concepts
from typing import AsyncIterable from typing import AsyncIterator from typing import NoReturn def empty() -> AsyncIterable[None]: """ Returns an asynchronous iterable that yields zero values. """ class Empty(AsyncIterator[None]): def __aiter__(self) -> AsyncIterator[None]: return ...
bigcode/self-oss-instruct-sc2-concepts
def topHat(r,A0=0.2): """Top-hat beam profile as used in Ref. [1]. Args: r (numpy array, ndim=1): Equispaced 1D grid for radial coordinate. A0 (float): Top hat width (default: 0.2). Returns: f (numpy array, ndim=1): Top-hat beam profile. """...
bigcode/self-oss-instruct-sc2-concepts
def npv_converter(sensitivity, specificity, prevalence): """Generates the Negative Predictive Value from designated Sensitivity, Specificity, and Prevalence. Returns negative predictive value sensitivity: -sensitivity of the criteria specificity: -specificity of the criteria preval...
bigcode/self-oss-instruct-sc2-concepts
def convert_error_code(error_code): """Convert error code from the format returned by pywin32 to the format that Microsoft documents everything in.""" return error_code % 2 ** 32
bigcode/self-oss-instruct-sc2-concepts
def simplify_polyphen(polyphen_list): """ Takes list of polyphen score/label pairs (e.g. ['probably_damaging(0.968)', 'benign(0.402)']) Returns worst (worst label and highest score) - in this case, 'probably_damaging(0.968)' """ max_score = 0 max_label = 'unknown' for polyphen in polyphen_li...
bigcode/self-oss-instruct-sc2-concepts
def snake_to_camel(value: str, *, uppercase_first: bool = False) -> str: """ Convert a string from snake_case to camelCase """ result = "".join(x.capitalize() or "_" for x in value.split("_")) if uppercase_first: return result return result[0].lower() + result[1:]
bigcode/self-oss-instruct-sc2-concepts
def _expt__CMORvar(self): """Return set of CMORvar item identifiers for CMORvars requested for this experiment""" cmv = set() for u in self._get__requestItem(): ri = self._inx.uid[u] rl = self._inx.uid[ri.rlid] for i in rl._get__CMORvar(): cmv.add(i) return cmv
bigcode/self-oss-instruct-sc2-concepts
def extract_name_email (txt): """ Extracts the name and email from RFC-2822 encoded email address. For eg. "Jeff Jeff <jeff.jeff@gmail.com>" returns ("Jeff Jeff", "jeff.jeff@gmail.com") """ if "<" in txt and ">" in txt: name, email = txt.split("<") return name[:-1], email[:-...
bigcode/self-oss-instruct-sc2-concepts
def is_key_valid(key): """Returns True if a Cloud Datastore key is complete. A key is complete if its last element has either an id or a name. """ if not key.path: return False return key.path[-1].HasField('id') or key.path[-1].HasField('name')
bigcode/self-oss-instruct-sc2-concepts
def preprocess( text, min_token_len=2, irrelevant_pos=["ADV", "PRON", "CCONJ", "PUNCT", "PART", "DET", "ADP", "SPACE"], ): """ Given text, min_token_len, and irrelevant_pos carry out preprocessing of the text and return a preprocessed string. Parameters ------------- text : (str) ...
bigcode/self-oss-instruct-sc2-concepts
import datetime def convertto_iso_format(dt_obj: datetime.datetime): """Takes a given datetime object and returns the timestamp in ISO format as a string. Examples: >>> now = get_epoch_time()\n >>> now\n 1636559940.508071 >>> now_as_dt_obj = convertfrom_epoch_time( no...
bigcode/self-oss-instruct-sc2-concepts
def process_question(question): """Process the question to make it canonical.""" return question.strip(" ").strip("?").lower() + "?"
bigcode/self-oss-instruct-sc2-concepts
import functools import operator def solution(resources, args): """Problem 8 - Version 1 Go through the entire 1000-digit number and calculate the product of each digit in the specified numbers of digits, then find the maximum. Parameters: resources The 1000-digit number ar...
bigcode/self-oss-instruct-sc2-concepts
from typing import get_origin from typing import Union from typing import get_args def get_possible_types(t): """ Given a type or a Union of types, returns a list of the actual types """ if get_origin(t) == Union: return get_args(t) else: return [t]
bigcode/self-oss-instruct-sc2-concepts
import string import re def split(s): """Split string s by whitespace characters.""" whitespace_lst = [re.escape(ws) for ws in string.whitespace] pattern = re.compile('|'.join(whitespace_lst)) return pattern.split(s)
bigcode/self-oss-instruct-sc2-concepts
def sort_dict(d, reverse=True): """Return the dictionary sorted by value.""" return dict(sorted(d.items(), key=lambda item: item[1], reverse=reverse))
bigcode/self-oss-instruct-sc2-concepts
def reduceWith(reducer, seed, iterable): """ reduceWith takes reducer as first argument, computes a reduction over iterable. Think foldl from Haskell. reducer is (b -> a -> b) Seed is b iterable is [a] reduceWith is (b -> a -> b) -> b -> [a] -> b """ accumulation = seed for value...
bigcode/self-oss-instruct-sc2-concepts
import re def process_mac_ip_pairs(tshark_output): """ Process output from the tshark command with MAC-IP pairs and return parsed array of dictionaries. :param tshark_output: output obtained by running tshark command :return: array of dictionaries with parsed MAC-IP pairs """ # Remove white s...
bigcode/self-oss-instruct-sc2-concepts
def remove_duplicates_retain_order(seq): """Code credited to https://stackoverflow.com/a/480227. Args: seq (list): Any list of any datatype. Returns: list: The list in same order but only first occurence of all duplicates retained. """ seen = set() seen_add = seen.add return([x for x in seq if not (x in se...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import re def get_MD(tag_bytes: bytes, no_tag: Any = None) -> str: """Extract the MD tag from a raw BAM alignment bytestring Parameters ---------- tag_bytes : bytes a bytestring containing bam formatted tag elements no_tag : Any r...
bigcode/self-oss-instruct-sc2-concepts
def choose(n, k): """ Binomial coefficients Return the n!/((n-k)!k!) Arguments: n -- Integer k -- Integer Returns: The bionomial coefficient n choose k Example: >>> choose(6,2) 15 """ ntok = 1 for t in range(min(k, n - k)): ntok = ntok * (n...
bigcode/self-oss-instruct-sc2-concepts
def indices_of_nouns(tokens): """Return indices of tokens that are nouns""" return [i for i, (_, pos) in enumerate(tokens) if pos.startswith('N')]
bigcode/self-oss-instruct-sc2-concepts
import math def _lockfile_create_retries(timeout_sec): """Invert the lockfile-create --retry option. The --retry option specifies how many times to retry. Each retry takes an additional five seconds, starting at 0, so --retry 1 takes 5 seconds, --retry 2 takes 15 (5 + 10), and so on. So: timeout_sec =...
bigcode/self-oss-instruct-sc2-concepts
def AlignMatches(matches): """ Tallys up each dif's song id frequency and returns the song id with highest count diff Args: matches: list of tuples containing (song id, relative offset) matched from known song Returns: songId (int) """ diffMap = {} largestCount = 0 song...
bigcode/self-oss-instruct-sc2-concepts
import platform def is_os(*args): """Check if current OS is in args Returns: bool """ return platform.system() in args
bigcode/self-oss-instruct-sc2-concepts