seed
stringlengths
1
14k
source
stringclasses
2 values
import random from time import gmtime, strftime def generate_DOB(age=65): """Randomly generate a month & date for DOB """ birth_month = random.randint(1,12) if birth_month == "1" or "3" or "5" or "7" or "8" or "10" or "12": birth_day = random.randint(1,31) if birth_month == "2": birth_day = random.randint(1,28) else: birth_day = random.randint(1,30) """Can not use the age generator function here for some reason but this code worked on generate_data_english.py. For now, passing dummy age into the function to make it work for the time being. I did input reference to import generator in the beginning of the program but got stuck on 'unicode_encoding' age = generator.GenerateFreqAlt(attribute_name = 'agejy', freq_file_name = 'lookup_files/age_gender_ratio_female.csv', has_header_line = False, unicode_encoding = unicode_encoding_used) """ year_system = strftime ("%Y", gmtime()) year_from_age = int(year_system) - age DOB = str(birth_month) +'/' + str(birth_day) + '/' + str(year_from_age) return DOB
bigcode/self-oss-instruct-sc2-concepts
def nts(s): """Convert a null-terminated string field to a python string. """ # Use the string up to the first null char. p = s.find("\0") if p == -1: return s return s[:p]
bigcode/self-oss-instruct-sc2-concepts
def parse_csv_data(csv_filename: str) -> list: """Parses through a CSV file, reading and storing each line of the file. Opens a csv file, assigning covid_csv_file to a list of all lines in the file. For each line in the file, the newline character and the commas are removed from the file, with each line being appended to a local list that is then returned. Args: csv_filename (str): The name of the csv file to be parsed, given as a string. This allows for data to be extracted from the csv file. Returns: list: covid_csv_data. This is a list, where each index is a line from the csv file. This allows for the data to be accessed and modified much easier (specific values can be accessed much easier) than if it were in plain csv format. """ covid_csv_data = [] with open(csv_filename, 'r', encoding='utf8') as covid_csv_file: covid_csv_file = covid_csv_file.readlines() for index in covid_csv_file: # Removing the newline escape character from the line. index = index[:-1:] # Splits the line into each section, converts it to a tuple # And adds it to a list. covid_csv_data.append(tuple(index.split(","))) return covid_csv_data
bigcode/self-oss-instruct-sc2-concepts
def get_iscam_mws(intensities, mw_intensity_line_pars=None): """ Calculate the molecular weights of the intensities with the line parameters `mw_intensity_line_pars` Parameters ---------- intensities : np.ndarray inensities of an iscam measurements mw_intensity_line_pars : array like [slope, intercept] of the mw to intensities linear function. """ mw_intensity_line_pars = [1, 0] if mw_intensity_line_pars is None \ else mw_intensity_line_pars slope, intercept = mw_intensity_line_pars mws = (intensities - intercept) / slope return mws
bigcode/self-oss-instruct-sc2-concepts
import torch def torch_dot(x: torch.Tensor, y: torch.Tensor): """ Dot product of two tensors. """ return (x * y).sum(-1)
bigcode/self-oss-instruct-sc2-concepts
def _CheckTestDataReadmeUpdated(input_api, output_api): """ Checks to make sure the README.md file is updated when changing test files. """ test_data_dir = input_api.os_path.join('media', 'test', 'data') readme_path = input_api.os_path.join('media', 'test', 'data', 'README.md') test_files = [] readme_updated = False errors = [] for f in input_api.AffectedFiles(): local_path = f.LocalPath() if input_api.os_path.dirname(local_path) == test_data_dir: test_files.append(f) if local_path == readme_path: readme_updated = True break if test_files and not readme_updated: errors.append(output_api.PresubmitPromptWarning( 'When updating files in ' + test_data_dir + ', please also update ' + readme_path + ':', test_files)) return errors
bigcode/self-oss-instruct-sc2-concepts
def format_custom_attr(ddic): """ Format a dictionary of dictionaries in string format in the "custom attribute" syntax e.g. custom="readingOrder {index:1;} structure {type:heading;}" """ s = "" for k1, d2 in ddic.items(): if s: s += " " s += "%s" % k1 s2 = "" for k2, v2 in d2.items(): if s2: s2 += " " s2 += "%s:%s;" % (k2, v2) s += " {%s}" % s2 return s
bigcode/self-oss-instruct-sc2-concepts
import re def mark_quoted_strings(sql): """Mark all quoted strings in the SOQL by '@' and get them as params, with respect to all escaped backslashes and quotes. """ pm_pattern = re.compile(r"'[^\\']*(?:\\[\\'][^\\']*)*'") bs_pattern = re.compile(r"\\([\\'])") out_pattern = re.compile("^[-!()*+,.:<=>\w\s]*$") start = 0 out = [] params = [] for match in pm_pattern.finditer(sql): out.append(sql[start:match.start()]) assert out_pattern.match(sql[start:match.start()]) params.append(bs_pattern.sub('\\1', sql[match.start() + 1:match.end() -1])) start = match.end() out.append(sql[start:]) assert out_pattern.match(sql[start:]) return '@'.join(out), params
bigcode/self-oss-instruct-sc2-concepts
def eff_heat_pump(temp_diff, efficiency_intersect, m_slope=-.08, h_diff=10): """Calculate efficiency of heat pump Parameters ---------- temp_diff: array Temperature difference efficiency_intersect : float,default=-0.08 Extrapolated intersect at temp diff of 10 degree (which is treated as efficiency) m_slope : float, default=10 Temperature dependency of heat pumps (slope) derived from Staffell et al. (2012), h_diff : float Temperature difference Return ------ efficiency_hp : array Efficiency of heat pump Note ---- Because the efficieny of heat pumps is temperature dependent, the efficiency needs to be calculated based on slope and intersect which is provided as input for temp difference 10 and treated as efficiency The intersect at temp differenc 10 is for ASHP about 6, for GSHP about 9 """ #efficiency_hp = m_slope * h_diff + (intersect + (-1 * m_slope * 10)) #var_c = efficiency_intersect - (m_slope * h_diff) #var_c = efficiency_intersect - (m_slope * h_diff) #efficiency_hp = m_slope * temp_diff + var_c #SLOW efficiency_hp = m_slope * temp_diff + (efficiency_intersect - (m_slope * h_diff)) #FAST #efficiency_hp = -.08 * temp_diff + (efficiency_intersect - (-0.8)) return efficiency_hp
bigcode/self-oss-instruct-sc2-concepts
def equally_sized_accessor(elements, n_variadic, n_preceding_simple, n_preceding_variadic): """ Returns a starting position and a number of elements per variadic group assuming equally-sized groups and the given numbers of preceding groups. elements: a sequential container. n_variadic: the number of variadic groups in the container. n_preceding_simple: the number of non-variadic groups preceding the current group. n_preceding_variadic: the number of variadic groups preceding the current group. """ total_variadic_length = len(elements) - n_variadic + 1 # This should be enforced by the C++-side trait verifier. assert total_variadic_length % n_variadic == 0 elements_per_group = total_variadic_length // n_variadic start = n_preceding_simple + n_preceding_variadic * elements_per_group return start, elements_per_group
bigcode/self-oss-instruct-sc2-concepts
def _make_extra_string(s=''): """ Create an extra function that just returns a constant string. """ def extra(attr, die, section_offset): return s return extra
bigcode/self-oss-instruct-sc2-concepts
def previous(field): """Generates s-expression to access a `field` previous value. """ return ["f", field, -1]
bigcode/self-oss-instruct-sc2-concepts
def is_inside(x, y, window): """ Check if (x, y) is a valid coordinate in input window Args: x (int): x-coordinate y (int): y-coordinate window (face_spinner.Window): Window Returns: bool -> True if valid, False otherwise """ if window.x <= x < (window.x + window.w) and window.y <= y < (window.y + window.h): return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def is_source_directory(src_count, files_count): """ Return True is this resource is a source directory with at least over 90% of source code files at full depth. """ return src_count / files_count >= 0.9
bigcode/self-oss-instruct-sc2-concepts
def _prev_char(s: str, idx: int): """Returns the character from *s* at the position before *idx* or None, if *idx* is zero. """ if idx <= 0: return None else: return s[idx - 1]
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import Dict from typing import Union def get_instance_class_from_properties_seq( instance_idx: Sequence, map_dict: Dict[str, Union[str, int]]) -> Sequence: """ Extract instance classes form mapping dict Args: instance_idx: instance ids present in segmentaion map_dict: dict mapping instance ids (keys) to classes Returns: Sequence[int]: extracted instance classes """ instance_idx = sorted(instance_idx) classes = [int(map_dict[str(int(idx))]) for idx in instance_idx] return classes
bigcode/self-oss-instruct-sc2-concepts
def _item_to_value_identity(iterator, item): """An item to value transformer that returns the item un-changed.""" # pylint: disable=unused-argument # We are conforming to the interface defined by Iterator. return item
bigcode/self-oss-instruct-sc2-concepts
def get_first_line(filename, nlines=1): """return the first line of a file. Arguments --------- filename : string The name of the file to be opened. nlines : int Number of lines to return. Returns ------- string The first line(s) of the file. """ # U is to open it with Universal newline support with open(filename, 'rU') as f: line = "".join([f.readline() for x in range(nlines)]) return line
bigcode/self-oss-instruct-sc2-concepts
def _IsBuildRunning(build_data): """Checks whether the build is in progress on buildbot. Presence of currentStep element in build JSON indicates build is in progress. Args: build_data: A dictionary with build data, loaded from buildbot JSON API. Returns: True if build is in progress, otherwise False. """ current_step = build_data.get('currentStep') if (current_step and current_step.get('isStarted') and current_step.get('results') is None): return True return False
bigcode/self-oss-instruct-sc2-concepts
import ipaddress def search_prefix_list(ip, prefix_list): """ Check if IP address exists in some prefix which is part of `prefix_list` `prefix_list` must be a list of tuples Each tuple must be of form (ip_prefix_begin, ip_prefix_end) in int equivalent (check preparation step) 1. Convert IP to int equivalent 2. Binary search through list of tuples. Check if ip falls between (tuple[0], tuple[1]) 3. Return prefix if it does """ if isinstance(ip, str) and ("." in ip or ":" in ip): ip = int(ipaddress.ip_address(ip)) low = 0 high = len(prefix_list) - 1 while (low <= high): mid = (low + high) >> 1 # divide by 2 if ip >= prefix_list[mid][0] and ip <= prefix_list[mid][1]: return mid elif ip < prefix_list[mid][0]: high = mid - 1 else: low = mid + 1 return -1
bigcode/self-oss-instruct-sc2-concepts
def differ_in_at_most_one(first, second): """Check if two strings differ in at most one position.""" # Check if length differences make it possible if abs(len(first) - len(second)) > 1: return False if len(first) > len(second): longer, shorter = first, second else: longer, shorter = second, first one_found = False l, s = 0, 0 long_length = len(longer) short_length = len(shorter) while l < long_length and s < short_length: if longer[l] != shorter[s]: if one_found: # found second difference return False else: one_found = True # skip one, if we have different lengths # position in shorter string should stay in place in that case if long_length != short_length: l += 1 else: l += 1 s += 1 else: l += 1 s += 1 return True
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def is_within(parent, child) -> bool: """ Check that a path is within another. """ return Path(parent).resolve() in Path(child).resolve().parents
bigcode/self-oss-instruct-sc2-concepts
import torch def rankdata_pt(b, tie_method='ordinal', dim=0): """ pytorch equivalent of scipy.stats.rankdata, GPU compatible. :param b: torch.Tensor The 1-D or 2-D tensor of values to be ranked. The tensor is first flattened if tie_method is not 'ordinal'. :param tie_method: str, optional The method used to assign ranks to tied elements. The options are 'average', 'min', 'max', 'dense' and 'ordinal'. 'average': The average of the ranks that would have been assigned to all the tied values is assigned to each value. Supports 1-D tensors only. 'min': The minimum of the ranks that would have been assigned to all the tied values is assigned to each value. (This is also referred to as "competition" ranking.) Supports 1-D tensors only. 'max': The maximum of the ranks that would have been assigned to all the tied values is assigned to each value. Supports 1-D tensors only. 'dense': Like 'min', but the rank of the next highest element is assigned the rank immediately after those assigned to the tied elements. Supports 1-D tensors only. 'ordinal': All values are given a distinct rank, corresponding to the order that the values occur in `a`. The default is 'ordinal' to match argsort. :param dim: int, optional The axis of the observation in the data if the input is 2-D. The default is 0. :return: torch.Tensor An array of length equal to the size of `b`, containing rank scores. """ # b = torch.flatten(b) if b.dim() > 2: raise ValueError('input has more than 2 dimensions') if b.dim() < 1: raise ValueError('input has less than 1 dimension') order = torch.argsort(b, dim=dim) if tie_method == 'ordinal': ranks = order + 1 else: if b.dim() != 1: raise NotImplementedError('tie_method {} not supported for 2-D tensors'.format(tie_method)) else: n = b.size(0) ranks = torch.empty(n).to(b.device) dupcount = 0 total_tie_count = 0 for i in range(n): inext = i + 1 if i == n - 1 or b[order[i]] != b[order[inext]]: if tie_method == 'average': tie_rank = inext - 0.5 * dupcount elif tie_method == 'min': tie_rank = inext - dupcount elif tie_method == 'max': tie_rank = inext elif tie_method == 'dense': tie_rank = inext - dupcount - total_tie_count total_tie_count += dupcount else: raise ValueError('not a valid tie_method: {}'.format(tie_method)) for j in range(i - dupcount, inext): ranks[order[j]] = tie_rank dupcount = 0 else: dupcount += 1 return ranks
bigcode/self-oss-instruct-sc2-concepts
def get_temp_var(used_vars): """get a temp variable name """ for i in range(0, 1000): var_name = "t{}".format(i) if var_name not in used_vars: return var_name
bigcode/self-oss-instruct-sc2-concepts
def getCoinbaseAddr (node, blockHash): """ Extract the coinbase tx' payout address for the given block. """ blockData = node.getblock (blockHash) txn = blockData['tx'] assert len (txn) >= 1 txData = node.getrawtransaction (txn[0], True, blockHash) assert len (txData['vout']) >= 1 and len (txData['vin']) == 1 assert 'coinbase' in txData['vin'][0] return txData['vout'][0]['scriptPubKey']['address']
bigcode/self-oss-instruct-sc2-concepts
import time def format_ampm(time_24hour) -> str: """Convert 24 hour to 12 hour system""" t = time.strptime(time_24hour, "%H%M") # Create time object timevalue_12hour = time.strftime("%-I:%M %p", t) # e.g. From 08:14 to 8:14 AM or 15:24 to 3:24 PM return timevalue_12hour
bigcode/self-oss-instruct-sc2-concepts
def all_filled(board): """ Returns True if all board is filled, False otherwise. """ for i in range(len(board)): if board[i].count(None): return False return True
bigcode/self-oss-instruct-sc2-concepts
import struct def decode_ieee(val_int): """Decode Python int (32 bits integer) as an IEEE single precision format Support NaN. :param val_int: a 32 bit integer as an int Python value :type val_int: int :returns: float result :rtype: float """ return struct.unpack("f",struct.pack("I", val_int))[0]
bigcode/self-oss-instruct-sc2-concepts
import torch def log1p_exp(input_tensor): """ Computationally stable function for computing log(1+exp(x)). """ x = input_tensor * input_tensor.ge(0).to(torch.float32) res = x + torch.log1p(torch.exp(-torch.abs(input_tensor))) return res
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def tuples_as_dict(_list): """Translate a list of tuples to OrderedDict with key and val as strings. Parameters ---------- _list : list of tuples Returns ------- collections.OrderedDict Example ------- :: >>> tuples_as_dict([('cmd', 'val'), ('cmd2', 'val2')]) OrderedDict([('cmd', 'val'), ('cmd2', 'val2')]) """ _dict = OrderedDict() for key, val in _list: key = str(key) val = str(val) _dict[key] = val return _dict
bigcode/self-oss-instruct-sc2-concepts
def find_adjacent_segment_type(segments, time): """Find boundary type on left and right (NONSPEECH or SPEECH)""" # find previous segment type segments[0].append("NS") prev = segments[0] for i in range(1, len(segments)): if (segments[i][0] - time) > prev[2]: segments[i].append("NS") # nonspeech else: segments[i].append("SC") # speaker change prev = segments[i] # find following segment type for i in range(0, len(segments) - 1): if (segments[i][2] + time) < segments[i + 1][0]: segments[i].append("NS") # nonspeech else: segments[i].append("SC") # speaker change segments[len(segments) - 1].append("NS") return segments
bigcode/self-oss-instruct-sc2-concepts
import math def get_elapsed_time(start, end): """ Compute elapsed time. @param start: start time @param end: end time @return: elapsed time (string) """ diff = end - start days, hours, minutes = [0, 0, 0] s_time = [] if diff > 86400: # day days = math.floor(diff / 86400) diff = diff - days * 86400 if diff > 3600: # hour hours = math.floor(diff / 3600) diff = diff - hours * 3600 if diff > 60: # minute minutes = math.floor(diff / 60) diff = diff - minutes * 60 if days > 0: s_time = "{0} days {1} hrs {2} min {3:.4f} sec".format(days, hours, minutes, diff) # print(f"{days} days {hours} hrs {minutes} min {diff:.4f} sec") elif hours > 0: s_time = "{0} hrs {1} min {2:.4f} sec".format(hours, minutes, diff) # print(f"{hours} hrs {minutes} min {diff:.4f} sec") elif minutes > 0: s_time = "{0} min {1:.4f} sec".format(minutes, diff) # print(f"{minutes} min {diff:.4f} sec") else: s_time = "{0:.4f} sec".format(diff) # print(f"{diff: .4f} sec") return s_time
bigcode/self-oss-instruct-sc2-concepts
import asyncio def async_test(test): """ Decorator to run async test methods. """ def wrapper(*args, **kwargs): asyncio.run(test(*args, **kwargs)) return wrapper
bigcode/self-oss-instruct-sc2-concepts
import itertools def flatten(sequence_list, cls=list): """ Flatten one level of nesting :param sequence_list: list of sequence :param cls: create instance of cls by flatten_gen :return: cls instance or generator """ flatten_gen = itertools.chain.from_iterable(sequence_list) return cls(flatten_gen) if cls else flatten_gen
bigcode/self-oss-instruct-sc2-concepts
def calculate_precision_recall_f1score(y_pred, y_true, entity_label=None): """ Calculates precision recall and F1-score metrics. Args: y_pred (list(AnnotatedDocument)): The predictions of an NER model in the form of a list of annotated documents. y_true (list(AnnotatedDocument)): The ground truth set of annotated documents. entity_label (str, optional): The label of the entity for which the scores are calculated. It defaults to None, which means all annotated entities. Returns: (3-tuple(float)): (Precision, Recall, F1-score) """ # Flatten all annotations all_y_pred_ann = [] all_y_true_ann = [] if entity_label is None: for annotated_document in y_pred: all_y_pred_ann.extend(annotated_document.annotations) for annotated_document in y_true: all_y_true_ann.extend(annotated_document.annotations) else: for annotated_document in y_pred: all_y_pred_ann.extend([ annotation for annotation in annotated_document.annotations if annotation.label == entity_label ]) for annotated_document in y_true: all_y_true_ann.extend([ annotation for annotation in annotated_document.annotations if annotation.label == entity_label ]) tp = 0.0 fp = 0.0 fn = 0.0 # Convert true annotations to a set in O(n) for quick lookup all_y_true_ann_lookup = set(all_y_true_ann) # True positives are predicted annotations that are confirmed by # their existence in the ground truth dataset. False positives are # predicted annotations that are not in the ground truth dataset. for annotation in all_y_pred_ann: if annotation in all_y_true_ann_lookup: tp += 1.0 else: fp += 1.0 # Convert predictions to a set in O(n) for quick lookup all_y_pred_ann_lookup = set(all_y_pred_ann) # False negatives are annotations in the ground truth dataset that # were never predicted by the system. for annotation in all_y_true_ann: if annotation not in all_y_pred_ann_lookup: fn += 1.0 precision = tp / (tp + fp) if (tp + fp) > 0 else 0. recall = tp / (tp + fn) if (tp + fn) > 0 else 0. f1_score = (2 * precision * recall) / (precision + recall) if\ (precision + recall) > 0 else 0. return (precision, recall, f1_score)
bigcode/self-oss-instruct-sc2-concepts
def get_func_and_args_from_str(call_str): """Parse call string to get function and argument names. Args: call_str: Call string must be in the form: `tf.foo(arg1=val1, arg2=val2, ...)`. Returns: (function_name, list of arg names) tuple. """ open_paren_index = call_str.find("(") close_paren_index = call_str.rfind(")") function_name = call_str[:call_str.find("(")] args = call_str[open_paren_index+1:close_paren_index].split(",") args = [arg.split("=")[0].strip() for arg in args] args = [arg for arg in args if arg] # filter out empty strings return function_name, args
bigcode/self-oss-instruct-sc2-concepts
import json def read_from_json(full_path_with_name): """Read from an arbitrary JSON and return the structure""" with open(full_path_with_name, 'r') as mjson: return json.load(mjson)
bigcode/self-oss-instruct-sc2-concepts
def xml_tag_name(tag_name: str) -> str: """Cleans anonymous tag-names for serialization, so that the colon does not lead to invalid XML:: >>> xml_tag_name(':Series') 'ANONYMOUS_Series__' :param tag_name: the original tag name :returns: the XML-conform tag_name """ if tag_name[:1] == ':': return 'ANONYMOUS_%s__' % tag_name[1:] return tag_name
bigcode/self-oss-instruct-sc2-concepts
import uuid def default_test_msg(prefix='', suffix='', sep=' '): """Create a random test string""" return sep.join([prefix, uuid.uuid4().hex, suffix])
bigcode/self-oss-instruct-sc2-concepts
import re def polished(summary): """ Polish summary, e.g. by cutting and trimming it. Args: summary: summary text to polish Returns: (part of) polished summary """ first_sentence = re.search('.*\.', summary) if first_sentence: return first_sentence.group().strip() else: return summary.strip()
bigcode/self-oss-instruct-sc2-concepts
def sample_exposure(image, sample_indices): """ A helper function which samples the given image at the specified indices. :param image: a single RGB image to be sampled from :param sample_indices: an array of the length N with the indices to sample at. N is the number of pixels :return: sampled_red is an array of the length N with the sample from the red channel sampled_green is an array of the length N with the sample from the green channel sampled_blue is an array of the length N with the sample from the blue channel """ # Get the constituent channels. red_img = image[:, :, 0].flatten() green_img = image[:, :, 1].flatten() blue_img = image[:, :, 2].flatten() # Construct the samples. sampled_red = [red_img[indice] for indice in sample_indices] sampled_green = [green_img[indice] for indice in sample_indices] sampled_blue = [blue_img[indice] for indice in sample_indices] return sampled_red, sampled_green, sampled_blue
bigcode/self-oss-instruct-sc2-concepts
def triangular(n): """Gives the n-th triangle number.""" return n*(n+1)/2
bigcode/self-oss-instruct-sc2-concepts
def _get_command_prefix(properties): """ If multiple commands are registered with the same name, attempt to construct a unique prefix from other information in the command's properties dictionary to distinguish one command from another. Uses the properties' ``app`` and/or ``group`` keys to create the prefix. :param dict properties: Arbitrary key/value information related to a registered command. :returns: A unique identifier for the command as a str. """ prefix_parts = [] if properties.get("app"): # First, distinguish commands by app name. prefix_parts.append(properties["app"].instance_name) if properties.get("group"): # Second, distinguish commands by group name. prefix_parts.append(properties["group"]) return ":".join(prefix_parts)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def extract_words(input_file_name: str) -> List[str]: """ Extracts a list of words from a word list. Expects one word per line. :param input_file_name: the path of the file to extract the words from :return: a list of words """ input_tokens = [] with open(input_file_name, "r", encoding='utf-8') as input_file: for line in input_file.readlines(): token = line.strip() if len(token) > 0: input_tokens.append(token) return input_tokens
bigcode/self-oss-instruct-sc2-concepts
def checkbox_result_to_bool(res): """ Takes in a checkbox result from a form and converts it to a bool Params: res (str): the result string from a checkbox Returns: bool: the boolean value of res """ if res == "on": return True elif res == "off" or res is None: return False return None
bigcode/self-oss-instruct-sc2-concepts
def EQUAL(x, y): """checks if both given arguments are equal""" return x == y
bigcode/self-oss-instruct-sc2-concepts
def alphaB(T): """ Returns Case B recombination coefficient (Osterbrock 1989; Krumholz+07) 2.59e-13*(T/1e4)**(-0.7) """ return 2.59e-13*(T/1e4)**(-0.7)
bigcode/self-oss-instruct-sc2-concepts
def first_non_repeating_letter(the_string): """ Find first non-repeating letter in a string. Letters are to be treated case-insensitive, which means 't' = 'T'. However, one must return the first non-repeating letter as it appears in the string, either in uppercase or lowercase. 'sTress' -> 'T' :param the_string: str, letters of alphabet :return: str, single letter or '' """ single_letters = {} # if the left index and right index of the letter # are the same, we have a single letter. Here we # enumerate on the lowercase version of the string # so uppercase and lowercase letters are treated # identically. lowercase_string = the_string.lower() for index, letter in enumerate(lowercase_string): if lowercase_string.find(letter) == lowercase_string.rfind(letter): single_letters[letter] = index if len(single_letters) == 0: return '' # pick single letter with smallest index lowercase_first_letter, index =\ min(single_letters.items(), key=lambda l: l[1]) # display the letter from the original string # because it could be uppercase return the_string[index]
bigcode/self-oss-instruct-sc2-concepts
def weak_pareto_dominates(vec1, vec2): """ Returns whether vec1 weakly dominates vec2 """ for i in range(len(vec1)): if vec1[i] < vec2[i]: return False return True
bigcode/self-oss-instruct-sc2-concepts
def HtmlString_to_HtmlFile(html_string,file_name="test.html"): """Saves an html string as a file with the default name """ out_file=open(file_name,'w') out_file.write(html_string) out_file.close() return file_name
bigcode/self-oss-instruct-sc2-concepts
import requests import tempfile def download_file(url): """ Download and return temporary file """ print("url detected, downloading...") response = requests.get(url) # detect file type from MIME-TYPE of request content_type = response.headers['content-type'] if content_type == 'application/pdf': file_type = ".pdf" elif content_type == "application/vnd.ms-powerpoint": file_type = ".ppt" elif content_type == "application/vnd.openxmlformats-officedocument.presentationml.presentation": file_type = ".pptx" else: print("couldn't figure out type of downloaded file. aborting") raise print("downloaded {0}".format(file_type)) # write to temporary file temp = tempfile.NamedTemporaryFile(suffix=file_type) temp.write(response.content) return temp
bigcode/self-oss-instruct-sc2-concepts
def comma_list_to_shape(s): """Parse a string of comma-separated ints into a valid numpy shape. Trailing commas will raise an error. Parameters ---------- s : str A string of comma-separated positive integers. Returns ------- tuple """ if not isinstance(s, str): raise TypeError("s must be a string") if s == "": raise ValueError("s is empty") # split by comma into an array of strings and try to convert to int shape = tuple(map(int, s.split(","))) # check that each shape member is valid (positive int), return if valid for i in range(len(shape)): if shape[i] < 1: raise ValueError(f"axis {i} of shape {shape} must be positive") return shape
bigcode/self-oss-instruct-sc2-concepts
def has_juniper_error(s): """Test whether a string seems to contain an Juniper error.""" tests = ( 'unknown command.' in s, 'syntax error, ' in s, 'invalid value.' in s, 'missing argument.' in s, ) return any(tests)
bigcode/self-oss-instruct-sc2-concepts
def factorial(num): """ (int) -> int Calcula el factorial de un número entero >>> factorial(3) 6 >>> factorial(4) 24 :param num: int el numero a evaluar :return: int el resultado del factorial """ if num == 1 or num == 0: return 1 elif num < 0: raise ValueError(f'no existe el factorial ' f'para {num}') return num * factorial(num - 1)
bigcode/self-oss-instruct-sc2-concepts
def condition(cond, rule): """ Only apply rule if condition is true """ def conditioned_rl(expr): if cond(expr): return rule(expr) else: return expr return conditioned_rl
bigcode/self-oss-instruct-sc2-concepts
import json def to_json(obj): """ Converts the given object to a json string :param obj: The input object :type obj: object :return: object as json string :rtype: str """ return json.dumps(obj)
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def set_date_from_string(value: str, format_: str = "%Y-%m-%dT%H:%M:%S"): """Generic function to format a string to datetime Args: value: The value to be validated. format_: A regex pattern to validate if the string has a specific format Returns: A datetime object Raises: ValueError: If the value violates the format constraint. """ if value is None: return None if isinstance(value, datetime): return value if value[-1] == "Z": value = value[:-1] for fmt in (format_, "%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%S.%f"): try: return datetime.strptime(value, fmt) except ValueError: pass raise ValueError(f"Wrong date string format. The format {format_} " f"should be followed. {str(value)} passed")
bigcode/self-oss-instruct-sc2-concepts
def ChkCTStarOnly(cron_time_field): """Checks if a crontab field is only a *. Args: cron_time_field: Parsed cron time field to check. Returns: True if there's only a * in this field. """ if not cron_time_field: return True if len(cron_time_field) == 1 and cron_time_field[0].Kind == 'star': return True return False
bigcode/self-oss-instruct-sc2-concepts
def _stripBold(s): """Returns the string s, with bold removed.""" return s.replace('\x02', '')
bigcode/self-oss-instruct-sc2-concepts
def capitalize_title(title): """Convert the first letter of each word in the title to uppercase if needed. :param title: str - title string that needs title casing. :return: str - title string in title case (first letters capitalized). """ return title.title()
bigcode/self-oss-instruct-sc2-concepts
def perspectiveTransform(x, y, M): """ Implementation of the perspective transform (homography) in 2D. **Parameters**\n x, y: numeric, numeric Pixel coordinates of the original point. M: 2d array Perspective transform matrix. **Return**\n xtrans, ytrans: numeric, numeric Pixel coordinates after projective/perspective transform. """ denom = M[2, 0]*x + M[2, 1]*y + M[2, 2] xtrans = (M[0, 0]*x + M[0, 1]*y + M[0, 2]) / denom ytrans = (M[1, 0]*x + M[1, 1]*y + M[1, 2]) / denom return xtrans, ytrans
bigcode/self-oss-instruct-sc2-concepts
def decode_time(value): """time decoder Used for fields such as: duration=1234.123s """ if value == "never": return value time_str = value.rstrip("s") return float(time_str)
bigcode/self-oss-instruct-sc2-concepts
def InstanceOverlap_OLD(instance1,instance2): """Returns True if given instances share a vertex.""" for vertex1 in instance1.vertices: if vertex1 in instance2.vertices: return True return False
bigcode/self-oss-instruct-sc2-concepts
import numbers import string def build_coder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. The empty space counts as the 27th letter of the alphabet, so spaces should be mapped to a lowercase letter as appropriate. shift: 0 <= int < 27 returns: dict Example: >>> build_coder(3) {' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J', 'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O', 'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X', 'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd', 'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l', 'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q', 'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z', 'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'} (The order of the key-value pairs may be different.) """ assert shift >= 0 and shift < 27, 'shift %s is not between 0 and 27' % shift #numbers.Integral used in case of long integers assert isinstance(shift, numbers.Integral), 'shift is not an integer' coder = {} lowercase_and_space = string.ascii_lowercase + ' ' uppercase_and_space = string.ascii_uppercase + ' ' # Shift letters over shift places shifted_lowercase_and_space = lowercase_and_space[shift:] + lowercase_and_space[:shift] shifted_uppercase_and_space = uppercase_and_space[shift:] + uppercase_and_space[:shift] # Construct Caesar cipher dictionary # Add uppercase letters first so ' ' will be overwritten to point to lowercase letter for i in range(len(uppercase_and_space)): coder[uppercase_and_space[i]] = shifted_uppercase_and_space[i] for i in range(len(lowercase_and_space)): coder[lowercase_and_space[i]] = shifted_lowercase_and_space[i] return coder
bigcode/self-oss-instruct-sc2-concepts
def apply_ucrow_aggregation(X): """ Given a tensor of activations, aggregate by sum-pooling without weighting. :param ndarray X: 3d tensor of activations with dimensions (channels, height, width) :returns ndarray: unweighted global image feature """ return X.sum(axis=(1, 2))
bigcode/self-oss-instruct-sc2-concepts
def create_groupings_columns(groupings_params): """ Strips all other parameters from groupings except name and columns """ new_groupings={} for grouping_name, grouping_values in groupings_params.items(): for values_name, values in grouping_values.items(): if values_name is 'columns': new_groupings[grouping_name]=values return new_groupings
bigcode/self-oss-instruct-sc2-concepts
def _container_exists(blob_service_client, container): """Check if container exists""" return next(blob_service_client.list_containers(container), None) is not None
bigcode/self-oss-instruct-sc2-concepts
import re def parse_doi(doi: str) -> str: """Parses a DOI from e.g. a URL. Args: doi: DOI string. Returns: The (possibly trimmed) DOI. Raises: ValueError: if the DOI cannot be parsed. """ # See https://www.doi.org/doi_handbook/2_Numbering.html#2.2. match = re.search(r'(10\.[\d.]+\/[a-zA-Z\d.]+)', doi) if not match: raise ValueError(f'could not parse DOI: {doi}') return match.group(1)
bigcode/self-oss-instruct-sc2-concepts
import itertools def four_body_sum(spins): """Calculate four body term in the periodic lattice Input: spins: spins configuration matrix. Output: sum of four body terms. """ size = len(spins) Sum = 0 for i,j in itertools.product(range(size), repeat=2): Sum += spins[i,j] * spins[i,(j+1)%size] * spins[(i+1)%size,j] \ * spins[(i+1)%size, (j+1)%size] # only consider the right and top part for each site return Sum
bigcode/self-oss-instruct-sc2-concepts
from hashlib import md5 def part2_adventcoin_miner(secret_key, match='000000'): """ --- Part Two --- Now find one that starts with six zeroes. """ for x in range(99999999): newkey = md5(secret_key + str(x)).hexdigest() if newkey[:len(match)] == match: return (x)
bigcode/self-oss-instruct-sc2-concepts
def duration(duration_ms: float) -> str: """ Formats duration into a string logged in stats :param duration_ms: Duration in milliseconds :return: formatted duration """ return "{:.2f}ms".format(duration_ms)
bigcode/self-oss-instruct-sc2-concepts
def compare_probs(post_a, post_b): """Compute P(A > B) probability.""" return (post_a > post_b).sum() / post_a.size
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def getCosponsors(fileDict: Dict, includeFields = []) -> list: """ Gets Cosponsors from data.json Dict. `includeFields` is a list of keys to keep. The most useful are probably 'name' and 'bioguide_id'. Args: fileDict (Dict): the Dict created from data.json includeFields (list): the fields in the cosponsor object to keep. If no 'includeFields' list is provided, all fields are preserved. Returns: list: a list of cosponsors, with selected fields determined by includeFields """ cosponsors = fileDict.get('cosponsors', []) if includeFields: cosponsors = list(map(lambda cosponsor: { field: cosponsor.get(field) for field in includeFields }, cosponsors)) # for sponsor in cosponsors: # if not sponsor.get('bioguide_id'): # continue # Sponsor.objects.create(**sponsor) return cosponsors
bigcode/self-oss-instruct-sc2-concepts
def ternary_search(f, xmin, xmax, epsilon=1e-6): """Ternary search. Args: f: An objective function. Must be convex downward. xmin: The lower bound of the range to search. xmax: The upper bound of the range to search. epsilon: The epsilon value for judging convergence. """ l, r = xmin, xmax while r - l > epsilon: d = (r - l) / 3.0 m1 = l + d m2 = l + 2.0 * d if f(m1) < f(m2): r = m2 else: l = m1 return r
bigcode/self-oss-instruct-sc2-concepts
def build_response_body(sentiment_prediction, confidence): """ Returns a formatted dict containing sentiment prediction. :param sentiment_prediction: :param confidence: :return: """ return dict(sentiment='{}'.format(sentiment_prediction), confidence=confidence)
bigcode/self-oss-instruct-sc2-concepts
def is_mapping_table(table_id): """ Return True if specified table is a mapping table :param table_id: identifies the table :return: True if specified table is an mapping table, False otherwise """ return table_id.startswith('_mapping_')
bigcode/self-oss-instruct-sc2-concepts
def fsplit(pred, objs): """Split a list into two classes according to the predicate.""" t = [] f = [] for obj in objs: if pred(obj): t.append(obj) else: f.append(obj) return (t, f)
bigcode/self-oss-instruct-sc2-concepts
def _attr_key(attr): """Return an appropriate key for an attribute for sorting Attributes have a namespace that can be either ``None`` or a string. We can't compare the two because they're different types, so we convert ``None`` to an empty string first. """ return (attr[0][0] or ''), attr[0][1]
bigcode/self-oss-instruct-sc2-concepts
import bz2 def unpack(requests): """Unpack a list of requests compressed in bz2""" return [bz2.decompress(request) for request in requests]
bigcode/self-oss-instruct-sc2-concepts
import torch def my_l1(x, x_recon): """Calculate l1 loss Parameters ---------- x : torch.cuda.FloatTensor or torch.FloatTensor Input data x_recon : torch.cuda.FloatTensor or torch.FloatTensor Reconstructed input Returns ------- torch.cuda.FloatTensor or torch.FloatTensor """ return torch.mean(torch.abs(x-x_recon))
bigcode/self-oss-instruct-sc2-concepts
def step_lstm(lstm, input_, h_0_c_0=None): """LSTMCell-like API for LSTM. Args: lstm: nn.LSTM input_: [batch_size, input_size] h_0_c_0: None or h_0: [num_layers, batch_size, hidden_size] c_0: [num_layers, batch_size, hidden_size] Returns: output: [batch_size, hidden_size] h_1_c_1: h_1: [num_layers, batch_size, hidden_size] c_1: [num_layers, batch_size, hidden_size] """ output, h_1_c_1 = lstm(input_[None], h_0_c_0) return output[0], h_1_c_1
bigcode/self-oss-instruct-sc2-concepts
import string def title_to_url(title): """ Converts a title string to a valid string for a url. White space will be replaced by dash, case will be set to lower and all punctuation marks will be removed. :param title: the title string. :type title: str :return: a valid url string. :rtype: str """ new = title.lower() new = new.translate(str.maketrans('', '', string.punctuation)) new = new.replace(' ', '-') return new
bigcode/self-oss-instruct-sc2-concepts
def create_prediction_series(lis, predictor): """ this function returns a list, lets call it p, of the length of the given lis such that p[i] = the prediction of the i'th element in lis given the first i-1 elements to make things nice, p[0] would be equal to lis[0] :param lis: :param predictor: :return: the prediction list created """ p = [lis[0]] for i in range(1, len(lis)): p.append(predictor.predict(lis[: i])) return p
bigcode/self-oss-instruct-sc2-concepts
def usable_class_name(node): """Make a reasonable class name for a class node.""" name = node.qname() for prefix in ["__builtin__.", "builtins.", "."]: if name.startswith(prefix): name = name[len(prefix) :] return name
bigcode/self-oss-instruct-sc2-concepts
def is_pass_transistor(pip_json): """ Returns boolean if pip JSON indicates pip is a pass transistor. Always returns False if database lacks this information. """ if 'is_pass_transistor' in pip_json: return bool(int(pip_json['is_pass_transistor'])) else: return False
bigcode/self-oss-instruct-sc2-concepts
def task10(number: int) -> None: """ Function that take an integer number as string and print the "It is an even number" if the number is even, otherwise print "It is an odd number". Input: number Output: None """ if number % 2 == 0: print("It is an even number") else: print("It is an odd number") return None
bigcode/self-oss-instruct-sc2-concepts
def has_method(obj, method_name: str) -> bool: """ Returns True if the provided object (`obj`) has the named method (`method_name`). """ return callable(getattr(obj, method_name, None))
bigcode/self-oss-instruct-sc2-concepts
def make_naive(value, timezone): """ Makes an aware datetime.datetime naive in a given time zone. """ # If `value` is naive, astimezone() will raise a ValueError, # so we don't need to perform a redundant check. value = value.astimezone(timezone) if hasattr(timezone, 'normalize'): # This method is available for pytz time zones. value = timezone.normalize(value) return value.replace(tzinfo=None)
bigcode/self-oss-instruct-sc2-concepts
def ensure_other_is_scalar(matrix_method): """Simple decorator to check if second argument to a matrix method is a scalar.""" def wrapper(self, other, *args, **kwargs): if not isinstance(other, (int, float, complex)): raise ValueError(f"Cannot use {matrix_method} with 'other' of type {type(other)}.") return matrix_method(self, other, *args, **kwargs) return wrapper
bigcode/self-oss-instruct-sc2-concepts
def get_extension(local_file: str) -> str: """Extract the file extension of a file.""" return local_file.rsplit(".", 1)[1].lower()
bigcode/self-oss-instruct-sc2-concepts
def normalize(vector, size): """ Normalizes a vector given the vector and the corresponding document length """ for word in vector: vector[word]=vector[word]/float(size) return vector
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_pkl(path: str, load_mode: str = 'rb'): """ Read a pickle file. :param path: str, filepath to read :param load_mode: str, read mode :return: contents of the pickle file """ return pickle.load(open(path, load_mode))
bigcode/self-oss-instruct-sc2-concepts
def first_neighbours_last(batches, current_batch_idx, nb_left, nb_right): """Build a sublist from a large batch list. This is used to display batch links for a large table. arguments: * :param batches: a large sequence (may be a batches as well) * :param current_batch_idx: index of the current batch or item * :param nb_left: number of neighbours before the current batch * :param nb_right: number of neighbours after the current batch The returned list gives: * the first batch * a None separator if necessary * left neighbours of the current batch * the current batch * right neighbours of the current batch * a None separator if necessary * the last batch Example: >>> from pyams_batching.batch import first_neighbours_last as f_n_l >>> batches = range(100) # it works with real batches as well We try to get subsets at different levels: >>> for i in range(0,6): ... f_n_l(batches, i, 2, 2) [0, 1, 2, None, 99] [0, 1, 2, 3, None, 99] [0, 1, 2, 3, 4, None, 99] [0, 1, 2, 3, 4, 5, None, 99] [0, None, 2, 3, 4, 5, 6, None, 99] [0, None, 3, 4, 5, 6, 7, None, 99] >>> for i in range(93, 99): ... f_n_l(batches, i, 2, 2) [0, None, 91, 92, 93, 94, 95, None, 99] [0, None, 92, 93, 94, 95, 96, None, 99] [0, None, 93, 94, 95, 96, 97, None, 99] [0, None, 94, 95, 96, 97, 98, 99] [0, None, 95, 96, 97, 98, 99] [0, None, 96, 97, 98, 99] Try with no previous and no next batch: >>> f_n_l(batches, 0, 0, 0) [0, None, 99] >>> f_n_l(batches, 1, 0, 0) [0, 1, None, 99] >>> f_n_l(batches, 2, 0, 0) [0, None, 2, None, 99] Try with only 1 previous and 1 next batch: >>> f_n_l(batches, 0, 1, 1) [0, 1, None, 99] >>> f_n_l(batches, 1, 1, 1) [0, 1, 2, None, 99] >>> f_n_l(batches, 2, 1, 1) [0, 1, 2, 3, None, 99] >>> f_n_l(batches, 3, 1, 1) [0, None, 2, 3, 4, None, 99] Try with incoherent values: >>> f_n_l(batches, 0, -4, -10) Traceback (most recent call last): ... AssertionError >>> f_n_l(batches, 2000, 3, 3) Traceback (most recent call last): ... AssertionError """ sublist = [] # setup some batches and indexes first_idx = 0 last_idx = len(batches) - 1 assert 0 <= current_batch_idx <= last_idx assert nb_left >= 0 and nb_right >= 0 prev_idx = current_batch_idx - nb_left next_idx = current_batch_idx + 1 first_batch = batches[0] last_batch = batches[last_idx] # add first batch if first_idx < current_batch_idx: sublist.append(first_batch) # there must probably be space if first_idx + 1 < prev_idx: # we skip batches between first batch and first previous batch sublist.append(None) # add previous batches for i in range(prev_idx, prev_idx + nb_left): if first_idx < i: # append previous batches sublist.append(batches[i]) # add current batch sublist.append(batches[current_batch_idx]) # add next batches for i in range(next_idx, next_idx + nb_right): if i < last_idx: # append previous batch sublist.append(batches[i]) # there must probably be space if next_idx + nb_right < last_idx: # we skip batches between last batch and last next batch sublist.append(None) # add last batch if current_batch_idx < last_idx: sublist.append(last_batch) return sublist
bigcode/self-oss-instruct-sc2-concepts
import csv def fetch_education_urls(input_file): """ Given a local input file, parse it and return a list of GOV.UK URLs. """ documents = [] with open(input_file, 'r') as f: reader = csv.reader(f) # skip headers next(reader, None) documents = list(reader) return [document[0] for document in documents]
bigcode/self-oss-instruct-sc2-concepts
def createPointWkt(coords): """Create WKT POINT string. Args: coords (list): Two item list representing single point coordinate. Returns: str: WKT POINT string. """ return 'POINT(' + str(coords[0]) + ' ' + str(coords[1]) + ')'
bigcode/self-oss-instruct-sc2-concepts
def mu_lambda(E=None, nu=None, lam=None, mu=None): """Get lame's parameters. Build the lame constants of a material using the elastic constants for isotropic materials. You must specify exactly two of the four available constants. For example, you can provide E and mu as arguments. Args: E (float): Young's modulus or elastic modulus. nu (float): Poisson's ratio. mu (float): lame's second parameter or shear modulus G. lam (flaot): lame's first parameter lambda. Returns: (float, float): mu and lambda """ number_of_inputs = sum(p is not None for p in (E, nu, lam, mu)) if number_of_inputs != 2: raise ValueError( "Two elastic constants are expected and received" + f" {number_of_inputs} instead." ) if E is not None and nu is not None: lam = E * nu / (1 + nu) / (1 - 2 * nu) mu = E / 2 / (1 + nu) elif E is not None: if mu is not None: lam = mu * (E - 2 * mu) / (3 * mu - E) elif lam is not None: R = (E ** 2 + 9 * lam ** 2 + 2 * E * lam) ** 0.5 mu = (E - 3 * lam + R) / 4 elif nu is not None: if mu is not None: lam = 2 * mu * nu / (1 - 2 * nu) elif lam is not None: mu = lam * (1 - 2 * nu) / (2 * nu) return mu, lam
bigcode/self-oss-instruct-sc2-concepts
import re def _match_regex(pattern: str, path: str) -> bool: """True if `path` matches `pattern`.""" return re.match(pattern, path) is not None
bigcode/self-oss-instruct-sc2-concepts
def clean_path(source): """ Replace backslashes from source.file_name with a slash """ source.file_name = source.file_name.replace('\\', '/') return source
bigcode/self-oss-instruct-sc2-concepts
import re def remove_non_alphanumeric_symbols(s): """Make text usable for attribute name""" return re.sub(r"\W", "_", s)
bigcode/self-oss-instruct-sc2-concepts
def build_falloff(parameters, falloff_function): """Creates falloff reaction Troe parameter string Parameters ---------- parameters : numpy.ndarray Array of falloff parameters; length varies based on ``falloff_function`` falloff_function : {'Troe', 'SRI'} Type of falloff function Returns ------- falloff_string : str String of falloff parameters """ if falloff_function == 'Troe': falloff_string = ('TROE / ' + f'{parameters[0]} {parameters[1]} ' f'{parameters[2]} {parameters[3]} /\n' ) elif falloff_function == 'SRI': falloff_string = ('SRI / ' + f'{parameters[0]} {parameters[1]} ' + f'{parameters[2]} {parameters[3]} {parameters[4]} /\n' ) else: raise NotImplementedError(f'Falloff function not supported: {falloff_function}') return falloff_string
bigcode/self-oss-instruct-sc2-concepts