seed
stringlengths
1
14k
source
stringclasses
2 values
import math def normal(x1: float, y1: float, x2: float, y2: float) -> tuple[float, float]: """ Compute the normal vector given two points """ phi = math.atan2(y2 - y1, x2 - x1) + math.pi/2 return (math.cos(phi), math.sin(phi))
bigcode/self-oss-instruct-sc2-concepts
def test_banjo_player_name() -> str: """This function test banjo player name and format message.""" name = input('Are you playing banjo? Enter your name: ') if not name: exit("error: you doesn't entered name!") if name[0] == 'R' or name[0] == 'r': msg = ' plays banjo' else: msg = ' does not play banjo' return name + msg
bigcode/self-oss-instruct-sc2-concepts
def motifScoreCmp(motifOcc1, motifOcc2): """Compares two motif occurences according to their pval.""" if (motifOcc1.getPval() < motifOcc2.getPval()): return -1 elif (motifOcc1.getPval() == motifOcc2.getPval()): return 0 else: assert (motifOcc1.getPval() > motifOcc2.getPval()) return 1
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_requirements() -> List[str]: """Returns all requirements for this package.""" with open('requirements.txt') as f: requirements = f.read().splitlines() return requirements
bigcode/self-oss-instruct-sc2-concepts
def _proto_dataset_info(dataset): """Return information about proto dataset as a dict.""" # Analogous to dtool_info.inventory._dataset_info info = {} info['type'] = 'dtool-proto' info['uri'] = dataset.uri info['uuid'] = dataset.uuid info["size_int"] = None info["size_str"] = 'unknown' info['creator'] = dataset._admin_metadata['creator_username'] info['name'] = dataset._admin_metadata['name'] info["date"] = 'not yet frozen' info['readme_content'] = dataset.get_readme_content() return info
bigcode/self-oss-instruct-sc2-concepts
def escape_cell(cell): """ Escape table cell contents. :param cell: Table cell (as unicode string). :return: Escaped cell (as unicode string). """ cell = cell.replace(u'\\', u'\\\\') cell = cell.replace(u'\n', u'\\n') cell = cell.replace(u'|', u'\\|') return cell
bigcode/self-oss-instruct-sc2-concepts
def get_vm_ips(nm_client, resource_group, vm_name): """ Get the private and public IP addresses for a given virtual machine. If a virtual machine has the more than one IP address of each type, then only the first one (as determined by the Azure SDK) is returned. This function returns the following tuple: (private IP, public IP) If a given VM does not have a private or public IP address, its tuple entry will be None. """ for nif in nm_client.network_interfaces.list(resource_group): if vm_name in nif.name: ipc = nif.ip_configurations[0] pub_ip = ipc.public_ip_address if pub_ip: pub_ip = pub_ip.ip_address return (ipc.private_ip_address, pub_ip) return (None, None)
bigcode/self-oss-instruct-sc2-concepts
def interpolate_group(group, classes, params, group_names): """ In the dict returned by get_nm_group, replace class and parameter IDs, and other group IDs, with their appropriate string or dict representations. :param group: the Group dict returned by get_nm_group() :type group: dict :param classes: the dict of classes returned by get_nm_group_classes() :type classes: dict :param params: the dict of parameters returned by get_nm_group_params() :type params: dict :param group_names: the dict of group IDs to names returned by get_group_names() :type group_names: dict :returns: group dict, with classes and params interpolated :rtype: dict """ g_params = group.get('parameters', {}) params_text = {} for p in g_params: foo = params[p] params_text[foo['paramkey']] = foo['paramvalue'] group['parameters'] = params_text g_classes = group.get('classes', {}) classes_text = {} for c in g_classes: foo = classes[c] classes_text[foo['classname']] = foo['classparams'] group['classes'] = classes_text g_parents = group.get('parents', {}) parents_text = [] for p in g_parents: parents_text.append(group_names[p]) group['parents'] = parents_text g_groups = group.get('groups', {}) groups_text = [] for g in g_groups: groups_text.append(group_names[g]) group['groups'] = groups_text return group
bigcode/self-oss-instruct-sc2-concepts
def iterize(obj): """ Converts into or wraps in an iterator. If `obj` is an iterable object other than a `str`, returns an iterator. Otherwise, returns a one-element iterable of `obj`. >>> list(iterize((1, 2, 3))) [1, 2, 3] >>> list(iterize("Hello!")) ['Hello!'] >>> list(iterize(42)) [42] """ if isinstance(obj, str): return iter((obj, )) else: try: return iter(obj) except TypeError: return iter((obj, ))
bigcode/self-oss-instruct-sc2-concepts
import time def to_timestamp(time_val): """Generate a unix timestamp for the given datetime instance""" return time.mktime(time_val.timetuple())
bigcode/self-oss-instruct-sc2-concepts
def dump_feature(feature): """ Gets a single feature as a dictionary, and returns it rendered as a string """ s = "|f " for _key in sorted(feature.keys()): s += "{}:{} ".format(_key, feature[_key]) return s
bigcode/self-oss-instruct-sc2-concepts
def remove_padding(im, pad): """ Function for removing padding from an image. :param im: image to remove padding from :param pad: number of pixels of padding to remove :return: """ return im[pad:-pad, pad:-pad]
bigcode/self-oss-instruct-sc2-concepts
def about_view(request): """Return about page.""" return {}
bigcode/self-oss-instruct-sc2-concepts
import torch def split_with_shape(tensor_flatten, mask_flatten, tensor_shape): """ Params: :tensor_flatten: (B, L, C) :mask_flatten: (B, L) :tensor_shape: (N, 2) Return: :tensor_list: [(B, H1 * W1, C), ..., (B, HN * WN, C)] :mask_list: [(B, H1 * W1), ..., (B, HN * WN)] """ chunk_sizes = (tensor_shape[:, 0] * tensor_shape[:, 1]).tolist() if tensor_flatten is None and mask_flatten is None: raise ValueError("Both tensor and mask are None") if tensor_flatten is not None: tensor_list = torch.split(tensor_flatten, chunk_sizes, dim=1) else: tensor_list = None if mask_flatten is not None: mask_list = torch.split(mask_flatten, chunk_sizes, dim=1) else: mask_list = None return tensor_list, mask_list
bigcode/self-oss-instruct-sc2-concepts
def uniqueArrayName(dataset, name0): """ Generate a unique name for a DataArray in a dataset """ ii = 0 name = name0 while name in dataset.arrays: name = name0 + '_%d' % ii ii = ii + 1 if ii > 1000: raise Exception('too many arrays in DataSet') return name
bigcode/self-oss-instruct-sc2-concepts
import importlib def _import_module(mocker): """Fixture providing import_module mock.""" return mocker.Mock(spec_set=importlib.import_module)
bigcode/self-oss-instruct-sc2-concepts
def bin2int(bin): """convert the binary (as string) to integer""" #print('bin conversion', bin, int(bin, 2)) return int(bin, 2)
bigcode/self-oss-instruct-sc2-concepts
def _ci_to_hgvs_coord(s, e): """ Convert continuous interbase (right-open) coordinates (..,-2,-1,0,1,..) to discontinuous HGVS coordinates (..,-2,-1,1,2,..) """ def _ci_to_hgvs(c): return c + 1 if c >= 0 else c return (None if s is None else _ci_to_hgvs(s), None if e is None else _ci_to_hgvs(e) - 1)
bigcode/self-oss-instruct-sc2-concepts
def num_sevens(n): """Returns the number of times 7 appears as a digit of n. >>> num_sevens(3) 0 >>> num_sevens(7) 1 >>> num_sevens(7777777) 7 >>> num_sevens(2637) 1 >>> num_sevens(76370) 2 >>> num_sevens(12345) 0 >>> from construct_check import check >>> # ban all assignment statements >>> check(HW_SOURCE_FILE, 'num_sevens', ... ['Assign', 'AugAssign']) True """ if n == 0: return 0 if n % 10 == 7: return num_sevens(n // 10) + 1 else: return num_sevens(n // 10)
bigcode/self-oss-instruct-sc2-concepts
def _recurse_on_subclasses(klass): """Return as a set all subclasses in a classes' subclass hierarchy.""" return set(klass.__subclasses__()).union( [ sub for cls in klass.__subclasses__() for sub in _recurse_on_subclasses(cls) ] )
bigcode/self-oss-instruct-sc2-concepts
def average_word_length(tweet): """ Return the average length of the tweet :param tweet: raw text tweet :return: the float number of character count divided by the word count """ character_count = 0 word_count = 0 for c in tweet: character_count += 1 word_count = len(tweet.split()) return float(character_count)/float(word_count)
bigcode/self-oss-instruct-sc2-concepts
def flatten_dataframe_for_JSON(df): """Flatten a pandas dataframe to a plain list, suitable for JSON serialisation""" return df.values.flatten().tolist()
bigcode/self-oss-instruct-sc2-concepts
def _indent(text, amount): """Indent a multiline string by some number of spaces. Parameters ---------- text: str The text to be indented amount: int The number of spaces to indent the text Returns ------- indented_text """ indentation = amount * ' ' return indentation + ('\n' + indentation).join(text.split('\n'))
bigcode/self-oss-instruct-sc2-concepts
def normalize(x, xmin, xmax): """Normalize `x` given explicit min/max values. """ return (x - xmin) / (xmax - xmin)
bigcode/self-oss-instruct-sc2-concepts
def _translate_snapshot_summary_view(context, vol): """Maps keys for snapshots summary view.""" d = {} d['id'] = vol['id'] d['volumeId'] = vol['volume_id'] d['status'] = vol['status'] # NOTE(gagupta): We map volume_size as the snapshot size d['size'] = vol['volume_size'] d['createdAt'] = vol['created_at'] d['displayName'] = vol['display_name'] d['displayDescription'] = vol['display_description'] return d
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict import csv def read_csv(path: str) -> List[Dict[str, str]]: """Reads a csv file, and returns the content inside a list of dictionaries. Args: path: The path to the csv file. Returns: A list of dictionaries. Each row in the csv file will be a list entry. The dictionary is keyed by the column names. """ with open(path, 'r') as f: return list(csv.DictReader(f))
bigcode/self-oss-instruct-sc2-concepts
def correct_date(date): """ Converts the date format to one accepted by SWA SWA form cannot accept slashes for dates and is in the format YYYY-MM-DD :param date: Date string to correct :return: Corrected date string """ if date is None: return "" else: a, b, c = date.split("/") if len(a) == 4: # Assumed format is year, month, day return "%s-%s-%s"%(a, b, c) else: # Assumed format is month, day, year return "%s-%s-%s" % (c, a, b)
bigcode/self-oss-instruct-sc2-concepts
def dns_name_encode(name): """ DNS domain name encoder (string to bytes) name -- example: "www.example.com" return -- example: b'\x03www\x07example\x03com\x00' """ name_encoded = [b""] # "www" -> b"www" labels = [part.encode() for part in name.split(".") if len(part) != 0] for label in labels: # b"www" -> "\x03www" name_encoded.append(chr(len(label)).encode() + label) return b"".join(name_encoded) + b"\x00"
bigcode/self-oss-instruct-sc2-concepts
def TestingResources(network_ref, subnet_ref, region, zones): """Get the resources necessary to test an internal load balancer. This creates a test service, and a standalone client. Args: network_ref: A reference to a GCE network for resources to act in. subnet_ref: A reference to a GCE subnetwork for resources to act in. region: The region to deploy the load balancer. zones: A list of zones to deploy the service. Returns: A list of resource definitions. """ return [{ 'name': 'test-service', 'type': 'test_service.py', 'properties': { 'network': network_ref, 'subnet': subnet_ref, 'region': region, 'zones': zones } }, { 'name': 'standalone-client', 'type': 'standalone_test_instance.py', 'properties': { 'network': network_ref, 'subnet': subnet_ref, 'zone': zones[0] } }]
bigcode/self-oss-instruct-sc2-concepts
def compute_bigram(input, unigram_count, bigram_count): """ compute_bigram - function to compute bigram probability Inputs: input : tuple bigram unigram_count : defaultdict(int) Occurence hashmap of single words/tokens bigram_count : defaultdict(int) Occurence hasmap of bi-words/tokens Outputs: output : float Bigram probability """ return bigram_count[input] / unigram_count[input[0]]
bigcode/self-oss-instruct-sc2-concepts
def addQuotes(s): """wrap a strings with quotes""" return "\"" + s + "\""
bigcode/self-oss-instruct-sc2-concepts
def remove_matching_braces(latex): """ If `latex` is surrounded by matching braces, remove them. They are not necessary. Parameters ---------- latex : string Returns ------- string Examples -------- >>> remove_matching_braces('{2+2}') '2+2' >>> remove_matching_braces('{2+2') '{2+2' """ if latex.startswith("{") and latex.endswith("}"): opened = 1 matches = True for char in latex[1:-1]: if char == "{": opened += 1 elif char == "}": opened -= 1 if opened == 0: matches = False if matches: latex = latex[1:-1] return latex
bigcode/self-oss-instruct-sc2-concepts
def point_avg(points): """ Accepts a list of points, each with the same number of dimensions. NB. points can have more dimensions than 2 Returns a new point which is the center of all the points. """ dimensions = len(points[0]) new_center = [] for dimension in range(dimensions): dim_sum = 0 # dimension sum for p in points: dim_sum += p[dimension] # average of each dimension new_center.append(dim_sum / float(len(points))) return new_center
bigcode/self-oss-instruct-sc2-concepts
def _check_errors(results): """ <SEMI-PRIVATE> Checks whether the results from the Azure API contain errors or not. _check_errors(results) results: [str] The results from the Azure translation API call Returns: bool; True if the API results contain errors. """ errors = False for result in results: if 'translations' not in result: errors = True break return errors
bigcode/self-oss-instruct-sc2-concepts
from typing import List def join_sublist_element(input_list: List[List[str]]) -> List[str]: """Join each sublist of chars into string. This function joins all the element(chars) in each sub-lists together, and turns every sub-lists to one element in the overall list. The sublist will turned into a string with all the same elements as before. :param input_list: the returned list after cut :return: the list that contains all the segments as strings. """ return ["".join(chars) for chars in input_list]
bigcode/self-oss-instruct-sc2-concepts
import json def make_split_change_event(change_number): """Make a split change event.""" return { 'event': 'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type': 'SPLIT_UPDATE', 'changeNumber': change_number }) }) }
bigcode/self-oss-instruct-sc2-concepts
import logging def _get_logger(fp, enabled=True, log_level="INFO"): """Create a logger that outputs to supplied filepath Args: enabled (bool): Whether logging is enabled. This function is called in scripts that call it with suppied arguments, and allows the scripts this utility blindly. fp (str): filename of the log log_level (str): Python logging level to set Returns: (logging.logger) logging handle """ # no matter what a fangless logger is created (for cleaner code) logger = logging.getLogger(fp.split("/")[-1].split(".")[0]) logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s \n', datefmt="%Y-%m-%d %H:%M:%S") if enabled: # set filehandler fh = logging.FileHandler(fp, mode='w') fh.setFormatter(formatter) fh.setLevel(getattr(logging, log_level.upper())) logger.addHandler(fh) return logger
bigcode/self-oss-instruct-sc2-concepts
def assemble(current_lst): """ :param current_lst: list of index for the string list :return: str, assemble list as string """ string = '' for alphabet in current_lst: string += alphabet return string
bigcode/self-oss-instruct-sc2-concepts
import random def dataset_creation(labeled_data): """Split labeled data into train and test""" one_class = [] zero_class = [] for data_point in labeled_data: if data_point[2] == 0: zero_class.append(data_point) else: one_class.append(data_point) random.shuffle(zero_class) random.shuffle(one_class) training_data = one_class[:len(one_class) // 2] + zero_class[:len(one_class) // 2] test_data = one_class[len(one_class) // 2:] + zero_class[len(one_class) // 2:] return training_data, test_data
bigcode/self-oss-instruct-sc2-concepts
def is_power_of_two(value: int) -> bool: """ Determine if the given value is a power of 2. Negative numbers and 0 cannot be a power of 2 and will thus return `False`. :param value: The value to check. :return: `True` if the value is a power of two, 0 otherwise. """ if value <= 0: return False # If value is a power of two, its highest bit that is set to 1 will toggle to 0 when subtracting 1 because all # other bits are 0; all other bits will thus be flipped to 1. Therefore, value and (value - 1) don't have any bits # in common and the bitwise AND will return 0. # On the other hand, if value is not a power of two, the highest bit set to 1 will not be flipped when subtracting 1 # and thus, value and (value - 1) will have bits in common and the bitwise AND will not return 0. # Therefore, if the result is 0, value is a power of two. return (value & (value - 1)) == 0
bigcode/self-oss-instruct-sc2-concepts
def get_ctx_result(result): """ This function get's called for every result object. The result object represents every ActionResult object that you've added in the action handler. Usually this is one per action. This function converts the result object into a context dictionary. :param result: ActionResult object :param provides: action name :return: context dictionary """ ctx_result = {} # param = result.get_param() summary = result.get_summary() ctx_result['vault_id'] = summary.get('vault_id') ctx_result['vault_file_name'] = summary.get('name') ctx_result['vault_file_path'] = summary.get('vault_file_path') try: ctx_result[' '] = result.get_message() except: pass return ctx_result
bigcode/self-oss-instruct-sc2-concepts
def pintensity(policies, weights): """Get the total intensity of a given bin of policies""" total = 0 for p in policies: if p == "nan": continue if p not in weights.keys(): raise ValueError(f"Missing intensity group: {p}") else: total += weights[p] return total
bigcode/self-oss-instruct-sc2-concepts
def get(seq, ind, defVal=None): """Return seq[ind] if available, else defVal""" try: return seq[ind] except LookupError: return defVal
bigcode/self-oss-instruct-sc2-concepts
def get_bot_in_location(location, game): """Returns the bot in the given location.""" bots = game.get('robots') if location in bots.keys(): return bots[location] else: return None
bigcode/self-oss-instruct-sc2-concepts
def is_mutable_s(text: str) -> bool: """ Checks if the word starts with a mutable 's'. ('s' is mutable when followed by a vowel, n, r, or l) :param text: the string to check :return: true if the input starts with a mutable s """ lc = text.lower() return len(lc) >= 2 and lc[0] == 's' and lc[1] in "rnlaeiouáéíóú"
bigcode/self-oss-instruct-sc2-concepts
def NBR(ds): """ Computes the Normalized Burn Ratio for an `xarray.Dataset`. The formula is (NIR - SWIR2) / (NIR + SWIR2). Values should be in the range [-1,1] for valid LANDSAT data (nir and swir2 are positive). Parameters ---------- ds: xarray.Dataset An `xarray.Dataset` that must contain 'nir' and 'swir2' `DataArrays`. Returns ------- nbr: xarray.DataArray An `xarray.DataArray` with the same shape as `ds` - the same coordinates in the same order. """ return (ds.nir - ds.swir2) / (ds.nir + ds.swir2)
bigcode/self-oss-instruct-sc2-concepts
def epsIndicator(frontOld, frontNew): """ This function computes the epsilon indicator :param frontOld: Old Pareto front :type frontOld: list :param frontNew: New Pareto front :type frontNew: list :return: epsilon indicator between the old and new Pareto fronts :rtype: float """ epsInd = 0 firstValueAll = True for indNew in frontNew: tempEpsInd = 0 firstValue = True for indOld in frontOld: (aOld, bOld, cOld) = indOld.fitness.values (aNew, bNew, cNew) = indNew.fitness.values compare = max(aOld-aNew, bOld-bNew, cOld-cNew) if firstValue: tempEpsInd = compare firstValue = False if compare < tempEpsInd: tempEpsInd = compare if firstValueAll: epsInd = tempEpsInd firstValueAll = False if tempEpsInd > epsInd: epsInd = tempEpsInd return epsInd
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import Tuple import cgi def _parse_content_type(content_type: Optional[str]) -> Tuple[Optional[str], str]: """Tease out the content-type and character encoding. A default character encoding of UTF-8 is used, so the content-type must be used to determine if any decoding is necessary to begin with. """ if not content_type: return None, "utf-8" else: type_, parameters = cgi.parse_header(content_type) encoding = parameters.get("charset", "utf-8") return type_, encoding
bigcode/self-oss-instruct-sc2-concepts
def ranked_vaccine_peptides(variant_to_vaccine_peptides_dict): """ This function returns a sorted list whose first element is a Variant and whose second element is a list of VaccinePeptide objects. Parameters ---------- variant_to_vaccine_peptides_dict : dict Dictionary from varcode.Variant to list of VaccinePeptide Returns list of (varcode.Variant, VaccinePeptide list) tuples """ result_list = list(variant_to_vaccine_peptides_dict.items()) def sort_key(variant_and_vaccine_peptides_pair): vaccine_peptides = variant_and_vaccine_peptides_pair[1] if len(vaccine_peptides) == 0: return 0.0 else: top_vaccine_peptide = vaccine_peptides[0] return top_vaccine_peptide.combined_score # sort in descending order of combined (expression * mhc binding) scores result_list.sort(key=sort_key, reverse=True) return result_list
bigcode/self-oss-instruct-sc2-concepts
def get_coord_by_index(da, indx): """ Take an Xarray DataArray, return a coordinate by its index in the order of the data structure. E.g. if var is defined on: ('time', 'lat'), indx=0 will return the coordinate labelled as 'time'. """ coord_name = da.dims[indx] return da.coords[coord_name]
bigcode/self-oss-instruct-sc2-concepts
def variance(hist:dict): """Compute the variance of an histogram. :param hist: the histogram :type hist: dict :return: the variance of the histogram :rtype: float """ vl = list(hist.values()) m = sum(vl) / float(len(vl)) return sum([(m - v)**2 for v in vl]) / float(len(vl))
bigcode/self-oss-instruct-sc2-concepts
import base64 import io def mpl_png(fig) -> str: """Return the base64 encoded png string of a matplotlib figure. Parameters ---------- fig : Figure Matplotlib figure Returns ------- str Figure base64 encoding """ f = io.BytesIO() fig.savefig(f, format="png", bbox_inches="tight") f.seek(0) b = base64.b64encode(f.getvalue()).decode("utf-8").replace("\n", "") return '<img class="mpl-figure-png" align="center" src="data:image/png;base64,%s">' % b
bigcode/self-oss-instruct-sc2-concepts
import collections def compute_f1(hypothesis_list, reference_list, eps=1e-8): """ Computes token F1 given a hypothesis and reference. This is defined as F1 = 2 * ((P * R) / (P + R + eps)) where P = precision, R = recall, and eps = epsilon for smoothing zero denominators. By default, eps = 1e-8. """ hypothesis_set = collections.Counter(hypothesis_list) reference_set = collections.Counter(reference_list) overlapping_set = hypothesis_set & reference_set hypothesis_count = len(hypothesis_list) reference_count = len(reference_list) overlapping_count = sum(overlapping_set.values()) precision = overlapping_count / hypothesis_count if hypothesis_count > 0 else 0 recall = overlapping_count / reference_count if reference_count > 0 else 0 f1 = (2.0 * precision * recall) / (precision + recall + eps) return f1
bigcode/self-oss-instruct-sc2-concepts
def get_p_key(episode_info): """ create the primary key field by concatenating episode information :param episode_info: Dictionary of a single episode """ return f'{episode_info["show_stub"]}S{episode_info["season"]}E{episode_info["episode"]}'
bigcode/self-oss-instruct-sc2-concepts
from typing import List def maxCrossingSum(arr: List[int], start: int, mid: int, stop: int): """Helper Function - Find the max crossing sum w.r.t. middle index""" leftSum = arr[mid] # start point leftMaxSum = arr[mid] # Keep track of maximum sum # Traverse in reverse direction from (mid-1) to start for i in range(mid - 1, start - 1, -1): leftSum = leftSum + arr[i] if leftSum > leftMaxSum: leftMaxSum = leftSum rightSum = arr[mid + 1] # start point rightMaxSum = arr[mid + 1] # keep track of maximum sum # Traverse in forward direction from (mid+2) to stop for j in range(mid + 2, stop + 1): rightSum = rightSum + arr[j] if rightSum > rightMaxSum: rightMaxSum = rightSum return rightMaxSum + leftMaxSum
bigcode/self-oss-instruct-sc2-concepts
def get_attack_name(node): """Returns the first of the three '|'-delimited fields in the 'text' field of the child 'attack' node.""" for child in node.iterchildren(): if child.tag == 'attack': return child.text.split('|')[0]
bigcode/self-oss-instruct-sc2-concepts
def clean_html(html_text): """ Converts <1 to 1 in html text""" return html_text.replace("><1<", ">less than 1<")
bigcode/self-oss-instruct-sc2-concepts
def occupancy_accuracy(gt, pred): """Compute occupancy accuracy of numpy tensors.""" return (gt == pred).sum() / float(gt.size)
bigcode/self-oss-instruct-sc2-concepts
def _get_winsdk_full_version(repository_ctx): """Return the value of BAZEL_WINSDK_FULL_VERSION if defined, otherwise an empty string.""" return repository_ctx.os.environ.get("BAZEL_WINSDK_FULL_VERSION", default = "")
bigcode/self-oss-instruct-sc2-concepts
def asses_quality(spec, negative_threshold_percent=20): """ // default - 0 = default // good - 1: to be defined - 2: to be defined // bad - 3: Pointing Problem - 4: more than `negative_threshold_percent` of the flux is negative - 5: A science target with no WCS """ if "STD" not in spec.header.get("OBJECT") and spec.header.get("SRCPOS",None) =="auto": return 5 if not spec.header.get("POSOK",True): return 3 flagnegative = spec.data<0 if len(spec.data[flagnegative]) / len(spec.data) > negative_threshold_percent/100: return 4 return 0
bigcode/self-oss-instruct-sc2-concepts
def extendImages(center, left, right, steering, correction): """ Extend the image paths from `center`, `left` and `right` using the correction factor `correction` Returns ([imagePaths], [steerings]) """ imagePaths = [] imagePaths.extend(center) imagePaths.extend(left) imagePaths.extend(right) steerings = [] steerings.extend(steering) steerings.extend([x + correction for x in steering]) steerings.extend([x - correction for x in steering]) return (imagePaths, steerings)
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def linear_schedule( initial_value: float, final_value: float, end: float = 0 ) -> Callable[[float], float]: """ Linear learning rate schedule. :param initial_value: Initial learning rate. :param final_value: Final learning rate :param end: Progress remaining where final value will be reached. :return: schedule that computes current learning rate depending on remaining progress """ assert 0 < end < 1 def func(progress_remaining: float) -> float: """ Progress will decrease from 1 (beginning) to 0. :param progress_remaining: :return: current learning rate """ if progress_remaining < end: lr = final_value else: x0 = end x1 = 1 y0 = final_value y1 = initial_value a = (y1 - y0) / (x1 - x0) b = y1 - a * x1 lr = a * progress_remaining + b return lr return func
bigcode/self-oss-instruct-sc2-concepts
def is_target_platform(ctx, platform): """ Determine if the platform is a target platform or a configure/platform generator platform :param ctx: Context :param platform: Platform to check :return: True if it is a target platform, False if not """ return platform and platform not in ('project_generator', [])
bigcode/self-oss-instruct-sc2-concepts
def convert_station_group_to_dictionary(group): """ Takes station group in format: [[station, component, network, location, start, end], [..], ...] and returns its dictionary representation: { station: <station>, components: [component1, .., componentN], network: <network>, location: <location>, start: <start>, end: <end> } """ components = [x[1] for x in group] station = group[0] return { 'station': station[0], 'components': components, 'network': station[2], 'location': station[3], 'start': station[4], 'end': station[5] }
bigcode/self-oss-instruct-sc2-concepts
def get_max_lat(shape): """ It returns the maximum latitude given a shape :param shape: country shape :return: the max latitude """ return shape.bounds[3]
bigcode/self-oss-instruct-sc2-concepts
def get_card_group(card, idolized): """ Returns an identifier for a card's group, to help separate them by rarities :param card: card data from schoolido.lu api :param idolized: True if idolized version :return: card group name """ return "%s-%s%d" % (card['rarity'], card['attribute'], 1 if idolized else 0)
bigcode/self-oss-instruct-sc2-concepts
def parse(address): """Parses the given MAC address and transforms it into "xx:xx:xx:xx:xx:xx" form. This form of expressing MAC addresses is the most standard one. In general, the "address" parameter accepts three forms of MAC address i input: - '1234567890af', - '12-34-56-78-90-af' (windows-like) and - '12:34:56:78:90:af' (the most used form). The 'address' parameter must be string, of course. """ assert address is not None temp = address if "-" in temp: temp = temp.replace("-", ":") if ":" not in temp: lst = list(temp) for cnt in range(10, 0, -2): lst.insert(cnt, ":") temp = "" for c in lst: temp = temp + c return temp.lower()
bigcode/self-oss-instruct-sc2-concepts
def parse_mode(cipher_nme): """ Parse the cipher mode from cipher name e.g. aes-128-gcm, the mode is gcm :param cipher_nme: str cipher name, aes-128-cfb, aes-128-gcm ... :return: str/None The mode, cfb, gcm ... """ hyphen = cipher_nme.rfind('-') if hyphen > 0: return cipher_nme[hyphen:] return None
bigcode/self-oss-instruct-sc2-concepts
def get_coordinates(read): """ return external coordinates of aligned read bases """ fivep = read.aend if read.is_reverse else read.pos threep = read.pos if read.is_reverse else read.aend return fivep, threep
bigcode/self-oss-instruct-sc2-concepts
def add_drip_columns(cave_results_df): """ Calculates Drips per min Calculates Drip Rate Error Adds all as columns ad returns input df. Parameters ---------- cave_results_df : pandas dataframe Returns ------- cave_results_df : pandas dataframe """ # Data Conversions cave_results_df['DripsPerMin'] = 60.0/cave_results_df['DripInterval'] # Error Propagation cave_results_df['DripRate_Err'] = (60*cave_results_df['DripInterval_err'] / cave_results_df['DripInterval'].pow(2)) return cave_results_df
bigcode/self-oss-instruct-sc2-concepts
import calendar def datetime_to_ms(dt): """ Converts a datetime to a millisecond accuracy timestamp """ seconds = calendar.timegm(dt.utctimetuple()) return seconds * 1000 + dt.microsecond / 1000
bigcode/self-oss-instruct-sc2-concepts
def temp_gradient(x, y): """Calculate the temperature gradient for a point defined by its cartesian coordinates: x, y. """ # Could also use SymPy to calculate derivative tbh fx = -x / (x**2 + y**2) fy = -y / (x**2 + y**2) return fx, fy
bigcode/self-oss-instruct-sc2-concepts
import math def get_tile_size(num_pixels, tile_size=400): """ num_pixels is the number of pixels in a dimension of the image. tile_size is the desired tile-size. """ # How many times can we repeat a tile of the desired size. num_tiles = int(round(num_pixels / tile_size)) # Ensure that there is at least 1 tile. num_tiles = max(1, num_tiles) # The actual tile-size. actual_tile_size = math.ceil(num_pixels / num_tiles) return actual_tile_size
bigcode/self-oss-instruct-sc2-concepts
def b(b1, b2): """ Return the difference between b1 and b2. """ return b1 - b2
bigcode/self-oss-instruct-sc2-concepts
import csv def load_examples(input_file): """Load data that we'll learn from""" with open(input_file) as f: reader = csv.reader(f) header = next(reader) assert header == ["From", "To"] examples_to_learn_from = [l for l in reader] return examples_to_learn_from
bigcode/self-oss-instruct-sc2-concepts
def sublist(full_list, index): """ returns a sub-list of contiguous non-emtpy lines starting at index """ sub_list = [] while index < len(full_list): line = full_list[index].strip() if line != "": sub_list.append(line) index += 1 else: break return sub_list
bigcode/self-oss-instruct-sc2-concepts
import imp def load_model(model_name, X_train, y_train, optimization_parameters, sklearn_model=None): """ Loads the base model model with the specific parameters :param model_name: the name of the model :param X_train: training data (# of samples x # of features) :param y_train: labels for the training data (# of samples * 1) :return: model object """ model_source = imp.load_source(model_name, 'models/%s.py' % (model_name)) model = model_source.Model(X_train, y_train, optimization_parameters, sklearn_model) return model
bigcode/self-oss-instruct-sc2-concepts
def is_int(n): """Determines if a value is a valid integer""" try: int(n) return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
def _token_to_dict(name, prefix=None): """ Generates function that converts a token to a dict containing the token name as key. The length of prefix is stripped from the key. """ if prefix is not None: return lambda x: {name[len(prefix) :]: x[0]} return lambda x: {name: x[0]}
bigcode/self-oss-instruct-sc2-concepts
def keypoint_outside_bbox(kp, bb): """ Check if keypoint is outside box :param kp: co ordinates of keypoint(x, y) :param bb: bounding box details (x_top_left, y_top_left, x_bottom_right, y_bottom_right) :return: True if keypoint is outside of bounding box, else False """ x = kp.pt[0] y = kp.pt[1] x_top_left, y_top_left, x_bottom_right, y_bottom_right = bb return not ((x > x_top_left) and (x < x_bottom_right) and (y > y_top_left) and (y < y_bottom_right))
bigcode/self-oss-instruct-sc2-concepts
def isInt(string): """ Determine whether a string is an int @param string: the string to check @return True if the string is an int, False otherwise """ try: int(string) except: return False return True
bigcode/self-oss-instruct-sc2-concepts
def is_unlinked_account(user): """ Returns whether the provided user has authenticated via an InstitutionAccount not yet linked to a Uniauth profile. """ return user.username and user.username.startswith('cas-')
bigcode/self-oss-instruct-sc2-concepts
def add_prefix_safely(token, prefix): """Attaches the passed in prefix argument to the front of the token, unless the token is an empty string in which case nothing happens and the token is returned unchaged. This can be important for avoiding accidentally making a meaningless token meaningful by modifying it with an additional text component. Args: token (str): Any arbitrary string. prefix (str): Any arbitrary string. Returns: str: The token with the prefix added to the beginning of the string. """ if len(token) > 0: return("{}{}".format(prefix, token)) else: return("")
bigcode/self-oss-instruct-sc2-concepts
def in_bounds(lat, lon, corners): """ Return true if the lat lon is within the corners. """ return \ lat >= corners[0] and lat <= corners[2] and \ lon >= corners[1] and lon <= corners[3]
bigcode/self-oss-instruct-sc2-concepts
def hours2days(input_hours): """ Receive the hours and will return ow many days and hours there is in the input """ # Floor division to get the days but not the extra hours days = input_hours // 24 # Modulus to get the left hours after calculating the days hours = input_hours % 24 # Returns tuples return days, hours
bigcode/self-oss-instruct-sc2-concepts
def class_name(obj): """Fetch the class name of an object (class or instance). Another cosmetic shortcut. The builtin way of getting an instance's class name is pretty disgusting (and long), accessing two hidden attributes in a row just feels wrong. :param any obj: The object you want the class name of :returns str: The class name """ if isinstance(obj, type): # It's a class. return obj.__name__ else: # It's an instance of a class. return obj.__class__.__name__
bigcode/self-oss-instruct-sc2-concepts
import typing import re def extract_ints(raw: str) -> typing.List[int]: """Utility function to extract all integers from some string. Many inputs can be directly parsed with this function. """ return list(map(int, re.findall(r"((?:-|\+)?\d+)", raw)))
bigcode/self-oss-instruct-sc2-concepts
def tokenize_description(description, has_name): """ Splits comma-separated resource descriptions into tokens. :param description: String describing a resource, as described in the ion-hash-test-driver CLI help. :param has_name: If True, there may be three tokens, the first of which must be the resource's name. Otherwise, there may be a maximum of two tokens, which represent the location and optional revision. :return: If `has_name` is True, three components (name, location, revision). Otherwise, two components (name, location) """ components = description.split(',') max_components = 3 if not has_name: max_components = 2 if len(components) < max_components: revision = 'master' else: revision = components[max_components - 1] if len(components) < max_components - 1: raise ValueError("Invalid implementation description.") if has_name: return components[0], components[max_components - 2], revision else: return components[max_components - 2], revision
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def _get_object_count_by_type(objects): """Counts Python objects by type.""" return Counter(map(type, objects))
bigcode/self-oss-instruct-sc2-concepts
def Sqr_Chord_Len_C3V(vec1, vec2): """Computes the square length of the difference between the two arguments. The arguments are assumed to be 3d vectors (indexable items of length 3).""" diff0 = vec1[0] - vec2[0]; diff1 = vec1[1] - vec2[1]; diff2 = vec1[2] - vec2[2]; result = diff0 * diff0 + diff1 * diff1 + diff2 * diff2; return result
bigcode/self-oss-instruct-sc2-concepts
def set_binary_labels(input_examples, positive_label): """ Replaces the class labels with 1.0 or -1.0, depending on whether the class label matches 'positive_label'. Returns an array of tuples, where the first element is the label number and the second is a path to the image file. """ examples = [] for example in input_examples: if example[0] == positive_label: examples.append(("1.0", example[1])) else: examples.append(("-1.0", example[1])) return examples
bigcode/self-oss-instruct-sc2-concepts
def _ExtractCommentText(comment, users_by_id): """Return a string with all the searchable text of the given Comment PB.""" commenter_email = users_by_id[comment.user_id].email return '%s %s %s' % ( commenter_email, comment.content, ' '.join(attach.filename for attach in comment.attachments if not attach.deleted))
bigcode/self-oss-instruct-sc2-concepts
import torch def inv_quad_chol_lower(x,L,y): """ Computes x (L L^T) y x : (m x n) L : (n x n) y : (n x k) """ m = x.shape[0] if m == 1: xy = torch.cat([x.reshape(-1,1),y],dim=1) return torch.triangular_solve(xy,L,upper=False)[0].prod(dim=1).sum(dim=0).reshape(1,1) else: z1 = torch.triangular_solve(x.transpose(1,0),L,upper=False)[0].transpose(1,0) #m x n z2 = torch.triangular_solve(y,L,upper=False)[0] #n x k return torch.matmul(z1,z2)
bigcode/self-oss-instruct-sc2-concepts
import re def get_original_image_link(url): """ Parse the image URL to cut off the 150x150 from the RSS feed Args: url (str): The image URL Returns: str: The updated URL if it matches the regex, else the original URL """ match = re.match(r"^(?P<prefix>.+)-150x150\.(?P<suffix>.+)$", url) if match: return f"{match.group('prefix')}.{match.group('suffix')}" return url
bigcode/self-oss-instruct-sc2-concepts
def rgb_to_hex(rgb_color: tuple) -> str: """ Convert rgb color to hex example: (255, 255, 255) to #FFFFFF :param rgb_color: :return: """ r, g, b = rgb_color return '#%02x%02x%02x' % (r, g, b)
bigcode/self-oss-instruct-sc2-concepts
def _slugify(value: str) -> str: """ Converts the value to a slugified version reducing the str down to just alpha-numeric values and removing white-space :param value: value as a str :return: slugified version of the value """ return ''.join(s for s in value if s.isalnum()).lower()
bigcode/self-oss-instruct-sc2-concepts
def sort_nodes_by_priority(g): """ Sort node ids in ascending order of priority. :param g: a game graph. :return: the node ids sorted in ascending order of priority. """ # x is a key of the dictionary a value (1, 4) means player 1, priority 4 # we return the node id, sorted by priority incrementally return sorted(g.nodes.iterkeys(), key=lambda x: g.nodes[x][1])
bigcode/self-oss-instruct-sc2-concepts
def notcontains(value, arg): """ Test whether a value does not contain any of a given set of strings. `arg` should be a comma-separated list of strings. """ for s in arg.split(','): if s in value: return False return True
bigcode/self-oss-instruct-sc2-concepts
def power_time_series(series, scalar): """ Multiply a series by itself X times where X is a scalar """ s = str(series) return f"multiply([{','.join([s for _ in range(scalar)])}])"
bigcode/self-oss-instruct-sc2-concepts
def TraceAgent(agent): """Wrap the agent's program to print its input and output. This will let you see what the agent is doing in the environment.""" old_program = agent.program def new_program(percept): action = old_program(percept) print('{} perceives {} and does {}'.format(agent, percept, action)) return action agent.program = new_program return agent
bigcode/self-oss-instruct-sc2-concepts