seed
stringlengths
1
14k
source
stringclasses
2 values
def overlap(a1, a2, b1, b2): """ Check if ranges a1-a2 and b1-b2 overlap. """ a_min = min(a1, a2) a_max = max(a1, a2) b_min = min(b1, b2) b_max = max(b1, b2) return a_min <= b_min <= a_max or b_min <= a_min <= b_max or \ a_min <= b_max <= a_max or b_min <= a_max <= b_max
bigcode/self-oss-instruct-sc2-concepts
def _combine_regex(*regexes: str) -> str: """Combine a number of regexes in to a single regex. Returns: str: New regex with all regexes ORed together. """ return "|".join(regexes)
bigcode/self-oss-instruct-sc2-concepts
def ofp_instruction_from_jsondict(dp, jsonlist, encap=True): """ This function is intended to be used with fluxory.lib.ofctl_string.ofp_instruction_from_str. It is very similar to ofp_msg_from_jsondict, but works on a list of OFPInstructions/OFPActions. It also encapsulates OFPAction into OFPIns...
bigcode/self-oss-instruct-sc2-concepts
def parse_return(data): """ Returns the data portion of a string that is colon separated. :param str data: The string that contains the data to be parsed. Usually the standard out from a command For example: ``Time Zone: America/Denver`` will return: ``America/Denver`` """ if ...
bigcode/self-oss-instruct-sc2-concepts
def _find_version_line_in_file(file_path): """ Find and return the line in the given file containing `VERSION`. :param file_path: Path to file to search. :return: Line in file containing `VERSION`. """ with open(str(file_path), "r") as fileh: version_lines = [ line for line ...
bigcode/self-oss-instruct-sc2-concepts
def all_but_last(items): """Return a tuple of all but the last item in items. >>> all_but_last([1, 2, 3, 4]) (1, 2, 3) """ return tuple(items[0:-1])
bigcode/self-oss-instruct-sc2-concepts
def pudl_etl_parameters(etl_settings): """Read PUDL ETL parameters out of test settings dictionary.""" return etl_settings.datasets
bigcode/self-oss-instruct-sc2-concepts
import getpass def get_user(lower=True): """ Returns the current user :param lower: bool :return: str """ username = getpass.getuser() return username.lower() if lower else username
bigcode/self-oss-instruct-sc2-concepts
def get_img_height() -> int: """ Auxiliary method that sets the height, which is fixed for the Neural Network. """ return 32
bigcode/self-oss-instruct-sc2-concepts
def moveRowDimension(obj, i, j, numrows, numcols, section, more, custom): """Move a row in front of another row. Note that this will change the nesting hierarchy parameters: from: row number to move from to: row number to move to Default action interchanges the first two columns of the row label...
bigcode/self-oss-instruct-sc2-concepts
def pad_to_two_digits(n): """ Add leading zeros to format a number as at least two digits :param n: any number :return: The number as a string with at least two digits """ return str(n).zfill(2)
bigcode/self-oss-instruct-sc2-concepts
def _SplitLabels(labels): """Parse the 'labels' key from a PerfKitBenchmarker record. Labels are recorded in '|key:value|,|key:value|' form. This function transforms them to a dict. Args: labels: string. labels to parse. Returns: dict. Parsed 'labels'. """ result = {} for item in labels.strip...
bigcode/self-oss-instruct-sc2-concepts
import re def small_titles(markdown): """Make titles smaller, eg replace '# ' with '### ' at the start of a line.""" markdown = re.sub(r'\n# |^# ', '\n### ', markdown) markdown = re.sub(r'\n## |^##', '\n#### ', markdown) return markdown
bigcode/self-oss-instruct-sc2-concepts
def vector_subtract(u, v): """returns the difference (vector) of vectors u and v""" return (u[0]-v[0], u[1]-v[1], u[2]-v[2])
bigcode/self-oss-instruct-sc2-concepts
def _uniq(lst): """ Return the unique elements from a list. Retrieved from https://www.peterbe.com/plog/uniqifiers-benchmark """ seen = set() seen_add = seen.add return [i for i in lst if not (i in seen or seen_add(i))]
bigcode/self-oss-instruct-sc2-concepts
def get_single_message(sqs_queue, wait_time_seconds=5): """Get a maximum of one message from the provided sqs queue.""" messages = sqs_queue.receive_messages( MaxNumberOfMessages=1, WaitTimeSeconds=wait_time_seconds) if messages: return messages[0] else: return None
bigcode/self-oss-instruct-sc2-concepts
def resource_filter(value, resource, field='displayName'): """ Given a mapping (resource), gets the data at resource[field] and checks for equality for the argument value. When field is 'name', it is expected to look like 'organization/1234567890', and returns only the number after the slash. ...
bigcode/self-oss-instruct-sc2-concepts
def timeify(time): """Format a time in seconds to a minutes/seconds timestamp.""" time = float(time) mins, secs = time // 60, time % 60 return f"{mins:.0f}:{secs:05.2f}"
bigcode/self-oss-instruct-sc2-concepts
def _verify_limits(limits): """ Helper function to verify that the row/column limits are sensible. Parameters ---------- limits : None|tuple|list Returns ------- None|tuple """ if limits is None: return limits temp_limits = [int(entry) for entry in limits] if ...
bigcode/self-oss-instruct-sc2-concepts
def timestamp_format_to_redex(time_format): """ convert time stamp format to redex Parameters ---------- time_format : str datetime timestamp format Returns ------- redex : str redex format for timestamp """ time_keys = {'%Y': r'\d{4}', '%m': r...
bigcode/self-oss-instruct-sc2-concepts
import itertools def held_karp(dists): """ Implementation of Held-Karp, an algorithm that solves the Traveling Salesman Problem using dynamic programming with memoization. Parameters: dists: distance matrix Returns: A tuple, (cost, path). """ n = len(dists) # Maps ea...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_format(string): """ Parses an AMBER style format string. Example: >>> string = "%FORMAT(10I8)" >>> _parse_format(string) [10, int, 8] """ if "FORMAT" not in string: raise ValueError("AMBER: Did not understand format line '%s'." % string) pstring = str...
bigcode/self-oss-instruct-sc2-concepts
def bb_area(bbox): """ returns area: bbox in format xs, ys, xe, ye if bbox is empty returns 0 """ if bbox.size == 0: area = 0 else: width = bbox[2] - bbox[0] height = bbox[3] - bbox[1] area = width*height return area
bigcode/self-oss-instruct-sc2-concepts
def F1(p, r): """ Calculate F1 score from precision and recall. Returns zero if one of p, r is zero. """ return (2*p*r/(p+r)) if p != 0 and r != 0 else 0
bigcode/self-oss-instruct-sc2-concepts
import torch def rot_z(gamma): """ Rotation around Z axis """ if not torch.is_tensor(gamma): gamma = torch.tensor(gamma, dtype=torch.get_default_dtype()) return gamma.new_tensor([ [gamma.cos(), -gamma.sin(), 0], [gamma.sin(), gamma.cos(), 0], [0, 0, 1] ])
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict def describe_topics(mlModel) -> List[Dict[str, float]]: """Obtain topic words and weights from the LDA model. Returns: topics -> List[Dict[str, float]] A list of mappings between the top 15 topic words (str) and their weights (float) for each to...
bigcode/self-oss-instruct-sc2-concepts
def percent(v): """ Transform probability into percentage. """ return v * 100
bigcode/self-oss-instruct-sc2-concepts
import re def is_custom(text, regex): """ Checks if the given text matches with a given regex Args: text (str): The text to match regex (str): A regular expression that you wanna match (recomended a raw string: r'') Returns: A boolean value, True if the text matches the string...
bigcode/self-oss-instruct-sc2-concepts
import re def split_auth_header(header): """Split comma-separate key=value fields from a WWW-Authenticate header""" fields = {} remaining = header.strip() while remaining: matches = re.match(r'^([0-9a-zA-Z]+)="([^"]+)"(?:,\s*(.+))?$', remaining) if not matches: # Without qu...
bigcode/self-oss-instruct-sc2-concepts
import calendar def get_month_button(month, text=None): """ Get the button corresponding to the given month. If no `text` is given, the name of the month in English will be used. """ if month < 1: month += 12 elif month > 12: month -= 12 return { 'text': text or c...
bigcode/self-oss-instruct-sc2-concepts
import requests def _request(url: str, token: str) -> requests.Response: """ Creates a request for the IUCN API and handles HTTP exceptions. Parameters ---------- url : str IUCN API endpoint. token : str IUCN API authentication token. Returns ------- Response ...
bigcode/self-oss-instruct-sc2-concepts
def parse_topology_str(s) -> list: """Parses node-topology string and returns list of dicts""" topology = [] if s: for a in s.split(','): (ip_port, valency) = a.split('/') (ip, port) = ip_port.split(':') #if resolve_hostname: ip = resolve_hostname(ip) ...
bigcode/self-oss-instruct-sc2-concepts
def numestate_incolour(colour:str) -> int: """Return the number of fields in given colour.""" if colour in {'brown','blue'}: return 2 return 3
bigcode/self-oss-instruct-sc2-concepts
def strike_through(text: str) -> str: """Returns a strike-through version of the input text""" result = '' for c in text: result = result + c + '\u0336' return result
bigcode/self-oss-instruct-sc2-concepts
def frohner_cor(sig1,sig2,n1,n2): """ Takes cross-sections [barns] and atom densities [atoms/barn] for two thicknesses of the same sample, and returns extrapolated cross section according to Frohner. Parameters ---------- sig1 : array_like Cross section of the thinner of the two sa...
bigcode/self-oss-instruct-sc2-concepts
def unblockshaped(arr, h, w): """ Return an array of shape (h, w) where h * w = arr.size If arr is of shape (n, nrows, ncols), n sublocks of shape (nrows, ncols), then the returned array preserves the "physical" layout of the sublocks. """ n, nrows, ncols = arr.shape return (arr.reshape...
bigcode/self-oss-instruct-sc2-concepts
def filename_ext(filename): """ Function that returns filename extension """ # Taken from http://flask.pocoo.org/docs/1.0/patterns/fileuploads/ return '.' in filename and filename.rsplit('.', 1)[1].lower()
bigcode/self-oss-instruct-sc2-concepts
import torch def load_saved_model(model : torch.nn.Module, path : str) -> torch.nn.Module: """ Loads a pre-saved neural net model. Args: ---- model (torch.nn.Module) : Existing but bare-bones model variable. path (str) : Path to the saved model. Returns: ------- ...
bigcode/self-oss-instruct-sc2-concepts
def item_based_predict(movie_data, u, m1, nn_list): """Returns a prediction from parameters for a movie. Parameters ---------- movie_data : dict Dictionary of the data set. u : str Id of user to be used for prediction. m1 : str Id of mov...
bigcode/self-oss-instruct-sc2-concepts
def _mu(df, formula, temp, cas, full): """ Helper for the `mu_gas` function to determine gas viscosity. Parameters ---------- df : dataframe Dataframe from inorganic or organic data formula : str Molecular formula for the gas temp : float Gas temperature cas : st...
bigcode/self-oss-instruct-sc2-concepts
import click def validate_section(ctx, param, value): """ Validate that a given section exists. """ config = ctx.obj.config if value and config.has_section(value): raise click.BadParameter( 'Missing or unknown section: {}'.format(value)) return value
bigcode/self-oss-instruct-sc2-concepts
def extract_local_dets(data): """Extracts the local detectors from the TOD objects Some detectors could only appear in some observations, so we need to loop through all observations and accumulate all detectors in a set """ local_dets = set() for obs in data.obs: tod = obs["tod"] ...
bigcode/self-oss-instruct-sc2-concepts
import random def randomize_capitalization(data): """ Randomize the capitalization of a string. """ return "".join(random.choice([k.upper(), k]) for k in data)
bigcode/self-oss-instruct-sc2-concepts
def nvmf_subsystem_get_controllers(client, nqn, tgt_name=None): """Get list of controllers of an NVMe-oF subsystem. Args: nqn: Subsystem NQN. tgt_name: name of the parent NVMe-oF target (optional). Returns: List of controller objects of an NVMe-oF subsystem. """ params = {'...
bigcode/self-oss-instruct-sc2-concepts
def escape_variables(environ): """ Escape environment variables so that they can be interpreted correctly by python configparser. """ return {key: environ[key].replace('%', '%%') for key in environ}
bigcode/self-oss-instruct-sc2-concepts
def subscription_name(project, name): """Get subscription name.""" return 'projects/{project}/subscriptions/{name}'.format( project=project, name=name)
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict from typing import Any import random def conflict_resolution_function(productions: List[Dict[str, Any]]) -> Dict[str, Any]: """ACT-R conflict resolution function. Currently selects a production at random from the already matched productions, since utility values...
bigcode/self-oss-instruct-sc2-concepts
def blurb(bio): """ Returns champion blurb which cuts off around 250 characters """ if " " not in bio: return bio bio = bio[0:254] bio = ' '.join(bio.split(' ')[:-1]) try: if bio[-1] == ",": bio = bio[:-1] except Exception: print(bio) return bio + ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def is_design(obj): """ Check if an object is a Metal Design, i.e., an instance of `QDesign`. The problem is that the `isinstance` built-in method fails when this module is reloaded. Args: obj (object): Test this object Returns: bool (bool): True if i...
bigcode/self-oss-instruct-sc2-concepts
def fix_angle(ang): """ Normalizes an angle between -180 and 180 degree. """ while ang > 360: ang -= 360 while ang < 0: ang += 360 return ang
bigcode/self-oss-instruct-sc2-concepts
def ranks_already_set(args) -> bool: """Return True is both local and global ranks have been set.""" is_local_rank_set = args.local_rank > -1 is_global_rank_set = args.global_rank > -1 return is_local_rank_set and is_global_rank_set
bigcode/self-oss-instruct-sc2-concepts
def match_all_attrs(token, attrs_to_match): """ Return true if all the values in the given dict match the morphology attributes of the token. So attrs_to_match is a way of filtering out which tokens will be matched. Returns true for an empty dict. :param token: :param attrs_to_match: :retur...
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def getResultsURLs(URL: str) -> list: """Finds appropriate result page link in the rounds section Args: URL (str): the URL of the division results page breaks (bool, optional): Return the link of the Returns: list: the URL of the requ...
bigcode/self-oss-instruct-sc2-concepts
def IS(attribute, val): """ Check if two values are equal """ return attribute == val
bigcode/self-oss-instruct-sc2-concepts
import statistics def get_password_lengths(creds: list): """ Determine how many passwords have what lengths """ lengths = {} s = 0 for p in creds: if len(p) not in lengths.keys(): lengths[len(p)] = 1 else: lengths[len(p)] += 1 s += len(p) # The reason I didn't make this an orderdict or use Collec...
bigcode/self-oss-instruct-sc2-concepts
def normalize_str(x): """ Given a value from an Excel cell, attempt to convert it to a string. Returns that normalized string if possible, or `None` otherwise. """ if not isinstance(x, str): return None return x.strip()
bigcode/self-oss-instruct-sc2-concepts
def cast_op_support(X, bXs, tXs): # Type: (XLayer, List[XLayer], List[XLayer]) -> boolean """ Check whether we can execute the provided Cast operator on the dpuv2-ultra96 target """ dtype = X.attrs['dtype'] return dtype == 'float32'
bigcode/self-oss-instruct-sc2-concepts
def solution2(values, expected): """ determines if exists two elements in values whose sum is exactly expected """ dic = {} for index, value in enumerate(values): diff = expected - value if diff not in dic: dic[value] = index continue return True ...
bigcode/self-oss-instruct-sc2-concepts
import json def parse_json(s, **kwargs): """Parse a string into a (nbformat, dict) tuple.""" d = json.loads(s, **kwargs) nbformat = d.get('nbformat',1) return nbformat, d
bigcode/self-oss-instruct-sc2-concepts
import base64 def _bytes_to_url64(bytes_data): """Convert bytes to custom-url-base64 encoded string""" return base64.urlsafe_b64encode(bytes_data).decode().replace('=', '~')
bigcode/self-oss-instruct-sc2-concepts
def find_missing_number(arr: list[int]) -> int: """ Complexity: Time: O(n) Space: O(1) Args: arr: array containing n-1 distinct numbers taken from the range [1,n] (n possible numbers) Returns: the single missing number in the range [1,n] missing fro...
bigcode/self-oss-instruct-sc2-concepts
def scrap_signature(consensus, fix=b'SIGNATURE'): """ Consume a signature field if there is one to consume. :param bytes consensus: input which may start with a signature. :returns: a tuple (updated-consensus, signature-or-None) """ if not consensus.startswith(b'-----BEGIN ' + fix ...
bigcode/self-oss-instruct-sc2-concepts
def _is_sass_file(filename): """Checks whether the specified filename resolves to a file supported by Sass.""" if filename.endswith(".scss"): return True elif filename.endswith(".sass"): return True elif filename.endswith(".css"): return True return False
bigcode/self-oss-instruct-sc2-concepts
def create_city_and_api_groups(data): """ Creates a list of groups based on city name and issue source used in scaling the final predictions. Args: data - a pandas dataframe that contains city and source columns Returns: a list of strings, each string contains the city na...
bigcode/self-oss-instruct-sc2-concepts
def provides_dep(package, other_package): """ Check if a package provides a dependency of another package. """ for dep in other_package.alldepends(): if package.providesName(dep.name): return True return False
bigcode/self-oss-instruct-sc2-concepts
import math def euclidean(vec1, vec2): """ 距离函数: 欧几里得距离. :param vec1: :type vec1: list[numbers.Real] :param vec2: :type vec2: list[numbers.Real] :return: """ d = 0.0 for i in range(len(vec1)): d += (vec1[i] - vec2[i]) ** 2 return math.sqrt(d)
bigcode/self-oss-instruct-sc2-concepts
def generate_question_id(example_id, assignment_id, question_per_example_index): """ Identifier assigned to a collected question question_per_example_index: 0-based (if a worker can write multiple questions for a single passage) """ if isinstance(question_per_example_index, int): question_pe...
bigcode/self-oss-instruct-sc2-concepts
def get_raise(data, key, expect_type=None): """Helper function to retrieve an element from a JSON data structure. The *key* must be a string and may contain periods to indicate nesting. Parts of the key may be a string or integer used for indexing on lists. If *expect_type* is not None and the retrieved...
bigcode/self-oss-instruct-sc2-concepts
def regions_intersect_ogr_p(region_a, region_b): """check if two regions intersect using ogr region_a_ogr_geom.Intersects(region_b_ogr_geom) Args: region_a (region): a region region_b (region): a region Returns: bool: True if `region_a` and `region_b` intersect else False. ...
bigcode/self-oss-instruct-sc2-concepts
def dim0(s): """Dimension of the slice list for dimension 0.""" return s[0].stop-s[0].start
bigcode/self-oss-instruct-sc2-concepts
def get_aa_counts(table): """ A function that takes a Code and finds the counts of each AA. Returns a dictionary mapping AA to their respective counts. Parameters ---------- dict table: a python dict representing the codon table Returns ------- dict AA_count: a python dict mapping amin...
bigcode/self-oss-instruct-sc2-concepts
def extract_sql_param_from_http_param(separator: str, http_param: str): """ Extracts sql params from an http param with given separator, returning tuple of db_query_label and query_name """ try: db_query_label, query_name = http_param.split(separator) except ValueError: raise Exc...
bigcode/self-oss-instruct-sc2-concepts
import re def isfloat(value): """ Return whether or not given value is a float. This does not give the same answer as:: isinstance(num_value,float) Because isfloat('1') returns true. More strict typing requirements may want to use is_instance. If the value is a float, this function...
bigcode/self-oss-instruct-sc2-concepts
def is_method_topic(topic): """ Topics for methods are of the following format: "$iothub/methods/POST/{method name}/?$rid={request id}" :param str topic: The topic string. """ if "$iothub/methods/POST" in topic: return True return False
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import Union import click def parse_profit_input(expected_profit: str) -> Optional[Union[str, float]]: """Parses user input expected profit and ensures the input is either a float or the string 'YOLO'.""" if expected_profit == "YOLO": return expected_profit ...
bigcode/self-oss-instruct-sc2-concepts
def select_supporting_facts(scored_sfs, min_thresholds): """ select supporting facts according to the provided thresholds :param scored_sfs: a list of (sentence_id, score) :param min_thresholds: a list of minimum scores for top ranked supporting facts: [min_score_for_top_ranked, min_score_for...
bigcode/self-oss-instruct-sc2-concepts
def strip_quotes(s): """ Remove surrounding single or double quotes >>> print strip_quotes('hello') hello >>> print strip_quotes('"hello"') hello >>> print strip_quotes("'hello'") hello >>> print strip_quotes("'hello") 'hello """ single_quote = "'" double_quote = '"' ...
bigcode/self-oss-instruct-sc2-concepts
def project_bucket(project_id, bucket_name): """Return a project-specific bucket name.""" return '{name}.{project_id}.appspot.com'.format( name=bucket_name, project_id=project_id)
bigcode/self-oss-instruct-sc2-concepts
def create_buffer(gdf,buffer_distance): """ This function is used to create buffer around given geodataframe with a specified distance Input: - gdf: input geo dataframe Output: - buffer_poly: a buffer around the input gdf with the specified distance """ buffer_po...
bigcode/self-oss-instruct-sc2-concepts
def categorical_encoding(item, categories): """ Numerical encoding items for specified categories. If there are no appropriate category, returns -1. :param object item: item to encode. :param list categories: categories to encode by. :return: digit. :rtype: int """ for num, cat in e...
bigcode/self-oss-instruct-sc2-concepts
def to_lower(text): """Convert uppercase text into lowercase.""" return text.lower()
bigcode/self-oss-instruct-sc2-concepts
def yes_no_binarize(df, columns = None, case_sensitive = True, inplace = False): """Replaces ``"Yes"`` and ``"No"`` with ``1`` and ``0``, respectively. Can specify a subset of columns to perform the replacement on using the ``columns`` parameter. :param df: :type df: :class:`~pandas.DataF...
bigcode/self-oss-instruct-sc2-concepts
def energy_value(h, J, sol): """ Obtain energy of an Ising solution for a given Ising problem (h,J). :param h: External magnectic term of the Ising problem. List. :param J: Interaction term of the Ising problem. Dictionary. :param sol: Ising solution. List. :return: Energy of the Ising string. ...
bigcode/self-oss-instruct-sc2-concepts
def trint(inthing): """ Turn something input into an integer if that is possible, otherwise return None :param inthing: :return: integer or None """ try: outhing = int(inthing) except: outhing = None return outhing
bigcode/self-oss-instruct-sc2-concepts
import dill def load_fn(path: str): """Load a function from a file produced by ``encode_fn``.""" with open(path, "rb") as file: return dill.load(file)
bigcode/self-oss-instruct-sc2-concepts
def aggregate_values(values_list, values_keys): """ Returns a string with concatenated values based on a dictionary values and a list of keys :param dict values_list: The dictionary to get values from :param str[] values_keys: A list of strings to be used as keys :return str: """ output = ""...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union import torch def int2precision(precision: Union[int, torch.dtype]): """ Get torch floating point precision from integer. If an instance of torch.dtype is passed, it is returned automatically. Args: precision (int, torch.dtype): Target precision. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def get_parent(tree, child_clade): """ Get the parent of a node in a Bio.Phylo Tree. """ if child_clade == tree.root: return None node_path = tree.root.get_path(child_clade) if len(node_path) < 2: return tree.root return node_path[-2]
bigcode/self-oss-instruct-sc2-concepts
def geojson_driver_args(distribution): """ Construct driver args for a GeoJSON distribution. """ url = distribution.get("downloadURL") or distribution.get("accessURL") if not url: raise KeyError(f"A download URL was not found for {str(distribution)}") return {"urlpath": url}
bigcode/self-oss-instruct-sc2-concepts
import json def maybe_dumps(s): """ If the given value is a json structure, encode it as a json string. Otherwise leave it as is. """ if isinstance(s, (dict, list)): return json.dumps(s) return s
bigcode/self-oss-instruct-sc2-concepts
import html def escape(s, quotes=True): """ Converts html syntax characters to character entities. """ return html.escape(s, quotes)
bigcode/self-oss-instruct-sc2-concepts
def quad2cubic(q0x, q0y, q1x, q1y, q2x, q2y): """ Converts a quadratic Bezier curve to a cubic approximation. The inputs are the *x* and *y* coordinates of the three control points of a quadratic curve, and the output is a tuple of *x* and *y* coordinates of the four control points of the cubic cur...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Optional def parse_xlets(xlet: List[dict]) -> Optional[List[str]]: """ Parse airflow xlets for V1 :param xlet: airflow v2 xlet dict :return: table list or None """ if len(xlet) and isinstance(xlet[0], dict): tables = xlet[0].get("tables") ...
bigcode/self-oss-instruct-sc2-concepts
def let_user_pick(options: list) -> int: """ Present a list of options to the user for selection. Parameters ---------- options : list A list of options to be printed and user to choose from. Returns ------- int The index of the users selection. """ print("Plea...
bigcode/self-oss-instruct-sc2-concepts
import string def filter_term(term, vocabulary): """If a word is not present in a vocabulary, check whether its lowercased or capitalized versions are present. If not and word is not a punctuation sign, then it is OOV. Otherwise, it is replaced by different case. Punctuation signs are omitted completely. ...
bigcode/self-oss-instruct-sc2-concepts
def boost_nmhc(group, nmhc, med_max_mhc): """ Return a fraction of boost based on total number of MHCs stimulated by peptides from the IAR. :param group::param pandas.core.frame.DataFrame group: The IAR under review. :param float nmhc: The total boost amount allotted to this criterion. :param tuple...
bigcode/self-oss-instruct-sc2-concepts
def load_sentences(filepath): """ Given a file of raw sentences, return the list of these sentences. """ with open(filepath, 'r') as myfile: sentences = [line for line in myfile if line != '\n'] return sentences
bigcode/self-oss-instruct-sc2-concepts
def get_ssl_subject_alt_names(ssl_info): """ Return the Subject Alt Names """ altNames = '' subjectAltNames = ssl_info['subjectAltName'] index = 0 for item in subjectAltNames: altNames += item[1] index += 1 if index < len(subjectAltNames): altNames += ', ' ret...
bigcode/self-oss-instruct-sc2-concepts
def propose(prop, seq): """wrapper to access a dictionary even for non-present keys""" if seq in prop: return prop[seq] else: return None
bigcode/self-oss-instruct-sc2-concepts
def piece_length(size): """ Calculate the ideal piece length for bittorrent data. Piece Length is required to be a power of 2, and must be larger than 16KiB. Not all clients support the same max length so to be safe it is set at 8MiB. Args ----------- size: int - total bits of all ...
bigcode/self-oss-instruct-sc2-concepts