seed
stringlengths
1
14k
source
stringclasses
2 values
import math def translate_key(key): """ Translate from MIDI coordinates to x/y coordinates. """ vertical = math.floor(key / 16) horizontal = key - (vertical * 16) return horizontal, vertical
bigcode/self-oss-instruct-sc2-concepts
def naniži(vrijednost): """Pretvaranje vrijednosti koja nije n-torka u 1-torku.""" return vrijednost if isinstance(vrijednost, tuple) else (vrijednost,)
bigcode/self-oss-instruct-sc2-concepts
import math def calculate_fov(zoom, height=1.0): """Calculates the required FOV to set the view frustrum to have a view with the specified height at the specified distance. :param float zoom: The distance to calculate the FOV for. :param float height: The desired view height at the specified distance. The default is 1.0. :rtype: A float representing the FOV to use in degrees. """ # http://www.glprogramming.com/red/chapter03.html rad_theta = 2.0 * math.atan2(height / 2.0, zoom) return math.degrees(rad_theta)
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def avg_dicts(*args): """ Average all the values in the given dictionaries. Dictionaries must only have numerical values. If a key is not present in one of the dictionary, the value is 0. Parameters ---------- *args Dictionaries to average, as positional arguments. Returns ------- dict Dictionary with the average of all inputs. Raises ------ TypeError If a value is not a number. """ try: total = sum(map(Counter, args), Counter()) n_dict = len(args) return {k: v / n_dict for k, v in total.items()} except TypeError as e: raise TypeError('Some values of the dictionaries are not numbers.') from e
bigcode/self-oss-instruct-sc2-concepts
def first_ok(results): """Get the first Ok or the last Err Examples -------- >>> orz.first_ok([orz.Err('wrong value'), orz.Ok(42), orz.Ok(3)]) Ok(42) >>> @orz.first_ok.wrap >>> def get_value_rz(key): ... yield l1cache_rz(key) ... yield l2cache_rz(key) ... yield get_db_rz(key) Parameters ---------- results : Iterable[Result] Returns ------- Result first ok or last err in parameters """ result = None for result in results: if result.is_ok(): return result return result
bigcode/self-oss-instruct-sc2-concepts
def add1(num): """Add one to a number""" return num + 1
bigcode/self-oss-instruct-sc2-concepts
def chomp(string): """ Simple callable method to remove additional newline characters at the end of a given string. """ if string.endswith("\r\n"): return string[:-2] if string.endswith("\n"): return string[:-1] return string
bigcode/self-oss-instruct-sc2-concepts
def subtract(datae): """Subtracts two fields Parameters ---------- datae : list List of `np.ndarray` with the fields on which the function operates. Returns ------- numpy.ndarray Subtracts the second field to the first field in `datae`. Thought to process a list of two fields. """ return datae[0] - datae[1]
bigcode/self-oss-instruct-sc2-concepts
import itertools def flatten(list_of_lists): """ Takes an iterable of iterables, returns a single iterable containing all items """ return itertools.chain(*list_of_lists)
bigcode/self-oss-instruct-sc2-concepts
import time def timer(function): """Decorator for timer functions Usage: @timer def function(a): pass """ def wrapper(*args, **kwargs): start = time.time() result = function(*args, **kwargs) end = time.time() print(f"{function.__name__} took: {end - start:.5f} sec") return result return wrapper
bigcode/self-oss-instruct-sc2-concepts
def add_default_module_params(module_parameters): """ Adds default fields to the module_parameters dictionary. Parameters ---------- module_parameters : dict Examples -------- >> module = add_default_module_params(module) Returns ------- module_parameters : dict Same as input, except default values are added for the following fields: 'Mbvoc' : 0 'FD' : 1 'iv_model' : 'sapm' 'aoi_model' : 'no_loss' """ if not 'Mbvoc' in module_parameters: module_parameters['Mbvoc'] = 0 if not 'FD' in module_parameters: module_parameters['FD'] = 1 if not 'iv_model' in module_parameters: module_parameters['iv_model'] = 'sapm' if not 'aoi_model' in module_parameters: module_parameters['aoi_model'] = 'no_loss' return module_parameters
bigcode/self-oss-instruct-sc2-concepts
def yesno(value): """Converts logic value to 'yes' or 'no' string.""" return "yes" if value else "no"
bigcode/self-oss-instruct-sc2-concepts
def str2bool(val): """ converts a string to a boolean value if a non string value is passed then following types will just be converted to Bool: int, float, None other types will raise an exception inspired by https://stackoverflow.com/questions/15008758/ parsing-boolean-values-with-argparse """ if val is None: return None if isinstance(val, (bool, int, float)): return bool(val) if not hasattr(val, "lower"): pass elif val.lower() in ("yes", "oui", "ja", "true", "t", "y", "1"): return True elif val.lower() in ("no", "non", "nein", "false", "f", "n", "0", ""): return False raise ValueError("can't convert %r to bool" % val)
bigcode/self-oss-instruct-sc2-concepts
def _find_text_in_file(filename, start_prompt, end_prompt): """ Find the text in `filename` between a line beginning with `start_prompt` and before `end_prompt`, removing empty lines. """ with open(filename, "r", encoding="utf-8", newline="\n") as f: lines = f.readlines() # Find the start prompt. start_index = 0 while not lines[start_index].startswith(start_prompt): start_index += 1 start_index += 1 end_index = start_index while not lines[end_index].startswith(end_prompt): end_index += 1 end_index -= 1 while len(lines[start_index]) <= 1: start_index += 1 while len(lines[end_index]) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index]), start_index, end_index, lines
bigcode/self-oss-instruct-sc2-concepts
import math def refraction_angle( theta1, index2, index1=1.0): """ Determine the exit angle (theta2) of a beam arriving at angle theta1 at a boundary between two media of refractive indices index1 and index2. The angle of refraction is determined by Snell's law, sin theta1 / sin theta2 = n2 / n1 where n is the refractive index (named "index" in this function). :Parameters: theta1: float Arrival angle of incidence (radians) index2: float Refractive index of second medium. index1: float (optional) Refractive index of first medium. Defaults to a vacuum (1.0) :Returns: theta2: float Exit angle of incidence (radians) """ assert index2 > 0.0 sin_theta2 = math.sin(theta1) * index1 / index2 theta2 = math.asin(sin_theta2) return theta2
bigcode/self-oss-instruct-sc2-concepts
def region_key(r): """ Create writeable name for a region :param r: region :return: str """ return "{0}_{1}-{2}".format(r.chr, r.start, r.end)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def _read_lark_file() -> str: """Reads the contents of the XIR Lark grammar file.""" path = Path(__file__).parent / "xir.lark" with path.open("r") as file: return file.read()
bigcode/self-oss-instruct-sc2-concepts
def outliers_detect_iqr(s, factor=1.5): """ Detects outliers in a pandas series using inter-quantile ranges Parameters ---------- s : pandas.core.series.Series Pandas Series for which the outliers need to be found factor : int iqr factor used for outliers Returns ------- numpy.array Boolean array with same length as the input, indices of outlier marked. Examples -------- >>> from eazieda.outliers_detect import outliers_detect_iqr >>> s = pd.Series([1,2,1,2,1, 1000]) >>> outliers_detect_iqr(s) array([False, False, False, False, False, True]) """ q1 = s.quantile(0.25) q3 = s.quantile(0.75) inter_quantile_range = q3 - q1 return ( (s < (q1 - factor * inter_quantile_range)) | (s > (q3 + factor * inter_quantile_range)) ).values
bigcode/self-oss-instruct-sc2-concepts
import bisect def compute_previous_intervals(I): """ For every interval j, compute the rightmost mutually compatible interval i, where i < j I is a sorted list of Interval objects (sorted by finish time) """ # extract start and finish times start = [i.left for i in I] finish = [i.right for i in I] p = [] for j in range(len(I)): # rightmost interval f_i <= s_j i = bisect.bisect_right(finish, start[j]) - 1 p.append(i) return p
bigcode/self-oss-instruct-sc2-concepts
def read_bytes(filename, offset, number): """ Reads specific bytes of a binary file. :param filename: path to file :type filename: string :param offset: start reading at offset :type offset: integer :param number: number of bytes :type number: integer :return: byte string """ with open(filename, "rb") as f: f.seek(offset) byte_string = f.read(number) f.close() return byte_string
bigcode/self-oss-instruct-sc2-concepts
def combine_roi_and_cav_mask(roi_mask, cav_mask): """ Combine ROI mask and CAV mask Parameters ---------- roi_mask : torch.Tensor Mask for ROI region after considering the spatial transformation/correction. cav_mask : torch.Tensor Mask for CAV to remove padded 0. Returns ------- com_mask : torch.Tensor Combined mask. """ # (B, L, 1, 1, 1) cav_mask = cav_mask.unsqueeze(2).unsqueeze(3).unsqueeze(4) # (B, L, C, H, W) cav_mask = cav_mask.expand(roi_mask.shape) # (B, L, C, H, W) com_mask = roi_mask * cav_mask return com_mask
bigcode/self-oss-instruct-sc2-concepts
def pname(name, levels=None): """ Return a prettified taxon name. Parameters ---------- name : str Taxon name. Returns ------- str Prettified taxon name. Examples -------- .. code:: python3 import dokdo dokdo.pname('d__Bacteria;p__Actinobacteriota;c__Actinobacteria;o__Actinomycetales;f__Actinomycetaceae;g__Actinomyces;s__Schaalia_radingae') # Will print: 's__Schaalia_radingae' dokdo.pname('Unassigned;__;__;__;__;__;__') # PWill print: 'Unassigned' dokdo.pname('d__Bacteria;__;__;__;__;__;__') # Will print: 'd__Bacteria' dokdo.pname('d__Bacteria;p__Acidobacteriota;c__Acidobacteriae;o__Bryobacterales;f__Bryobacteraceae;g__Bryobacter;__') # Will print: 'g__Bryobacter' dokdo.pname('d__Bacteria;p__Actinobacteriota;c__Actinobacteria;o__Actinomycetales;f__Actinomycetaceae;g__Actinomyces;s__Schaalia_radingae', levels=[6,7]) # Will print: 'g__Actinomyces;s__Schaalia_radingae' """ if levels is None: ranks = list(reversed(name.split(';'))) for i, rank in enumerate(ranks): if rank in ['Others', 'Unassigned']: return rank if rank == '__': continue if rank.split('__')[1] is '': return ranks[i+1] + ';' + rank return rank else: ranks = name.split(';') if 'Others' in ranks: return 'Others' if 'Unassigned' in ranks: return 'Unassigned' return ';'.join([ranks[x-1] for x in levels])
bigcode/self-oss-instruct-sc2-concepts
def create_parameter(model, parameter_id, value, constant=True, units="dimensionless"): """ Creates new parameter for libsbml.Model. It is not necessary to assign the function to a value. The parameter is automatically added to the input model outside of the function. Parameters ---------- model : libsbml.Model Model for which species will be created. parameter_id : str Id for the new parameter. constant : {True, False} True if the new parameter can only be constant. And False if not. False does not mean that the parameter has to change but rather that it is allowed to. value : float Value of the parameter. units : str Units of the parameter. Returns ------- parameter : libsbml.Parameter Parameter defined for the model. """ parameter = model.createParameter() parameter.setId(parameter_id) parameter.setName(parameter_id) parameter.setConstant(constant) parameter.setValue(value) parameter.setUnits(units) return parameter
bigcode/self-oss-instruct-sc2-concepts
def datetime_to_string(datetime): """convert a datetime object to formatted string Arguments: datetime {datetime} Returns: [string] -- formatted datetime string """ return "/".join([str(datetime.day), str(datetime.month), str(datetime.year)])
bigcode/self-oss-instruct-sc2-concepts
import re def extract_options(text, key): """Parse a config option(s) from the given text. Options are embedded in declarations like "KEY: value" that may occur anywhere in the file. We take all the text after "KEY: " until the end of the line. Return the value strings as a list. """ regex = r'\b{}:\s+(.*)'.format(key.upper()) return re.findall(regex, text)
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def map_value( x: Union[int, float], in_min: Union[int, float], in_max: Union[int, float], out_min: Union[int, float], out_max: Union[int, float] ) -> float: """Maps a value from an input range to a target range. Equivalent to Arduino's `map` function. Args: x: the value to map. in_min: the lower bound of the value's current range. in_max: the upper bound of the value's current range. out_min: the lower bound of the value's target range. out_max: the upper bound of the value's target range. Returns: The mapped value in the target range. """ return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
bigcode/self-oss-instruct-sc2-concepts
def _get_workflow_input_parameters(workflow): """Return workflow input parameters merged with live ones, if given.""" if workflow.input_parameters: return dict(workflow.get_input_parameters(), **workflow.input_parameters) else: return workflow.get_input_parameters()
bigcode/self-oss-instruct-sc2-concepts
def autocov(v, lx): """ Compute a lag autocovariance. """ ch = 0 for i in range(v.shape[0]-lx): for j in range(v.shape[1]): ch += v[i][j]*v[i+lx][j] return ch/((v.shape[0]-lx)*v.shape[1])
bigcode/self-oss-instruct-sc2-concepts
def compute_score(segment, ebsd): """ Compute Dice measure (or f1 score) on the segmented pixels :param segment: segmented electron image (uint8 format) :param ebsd: speckle segmented out of the ebsd file (uint8 format) :return: Dice score """ segmented_ebsd = ebsd >= 128 segmented_segment = segment >= 128 co_segmented = (segmented_ebsd & segmented_segment).sum() normalization = segmented_segment.sum() + segmented_ebsd.sum() score = 2 * co_segmented / normalization return score
bigcode/self-oss-instruct-sc2-concepts
def get_graphlist(gg, l=None): """Traverse a graph with subgraphs and return them as a list""" if not l: l = [] outer = True else: outer = False l.append(gg) if gg.get_subgraphs(): for g in gg.get_subgraphs(): get_graphlist(g, l) if outer: return l
bigcode/self-oss-instruct-sc2-concepts
def heads(l): """ Returns all prefixes of a list. Examples -------- >>> heads([0, 1, 2]) [[], [0], [0, 1], [0, 1, 2]] """ return map(lambda i: l[:i], range(len(l) + 1))
bigcode/self-oss-instruct-sc2-concepts
def list_subtract(a, b): """Return a list ``a`` without the elements of ``b``. If a particular value is in ``a`` twice and ``b`` once then the returned list then that value will appear once in the returned list. """ a_only = list(a) for x in b: if x in a_only: a_only.remove(x) return a_only
bigcode/self-oss-instruct-sc2-concepts
def _patsplit(pat, default): """Split a string into an optional pattern kind prefix and the actual pattern.""" if ':' in pat: kind, val = pat.split(':', 1) if kind in ('re', 'glob', 'path', 'relglob', 'relpath', 'relre'): return kind, val return default, pat
bigcode/self-oss-instruct-sc2-concepts
def indent_level(level:int): """Returns a string containing indentation to the given level, in spaces""" return " " * level
bigcode/self-oss-instruct-sc2-concepts
import difflib def diff(a, b): """A human readable differ.""" return '\n'.join( list( difflib.Differ().compare( a.splitlines(), b.splitlines() ) ) )
bigcode/self-oss-instruct-sc2-concepts
import time def CreatePastDate(secs): """ create a date shifted of 'secs' seconds respect to 'now' compatible with mysql queries Note that using positive 'secs' you'll get a 'future' time! """ T=time.time()+time.timezone+secs tup=time.gmtime(T) #when="%d-%d-%d %d:%d:%d"%(tup[0],tup[1],tup[2],tup[3],tup[4],tup[5]) when="%d-%d-%d %d:%d:%d"%tup[0:6] return when
bigcode/self-oss-instruct-sc2-concepts
def decompose(field): """ Function to decompose a string vector field like 'gyroscope_1' into a tuple ('gyroscope', 1) """ field_split = field.split('_') if len(field_split) > 1 and field_split[-1].isdigit(): return '_'.join(field_split[:-1]), int(field_split[-1]) return field, None
bigcode/self-oss-instruct-sc2-concepts
def build_path(tmp_path_factory): """Provides a temp directory with various files in it.""" magic = tmp_path_factory.mktemp('build_magic') file1 = magic / 'file1.txt' file2 = magic / 'file2.txt' file1.write_text('hello') file2.write_text('world') return magic
bigcode/self-oss-instruct-sc2-concepts
def run_model(model, X_train, y_train, X_test, y_test, params): # pylint: disable=too-many-arguments """Train the given model on the training data, and return the score for the model's predictions on the test data. Specify parameters of the model with the provided params. Args: model (callable): model to be initialized with the specified parameters. X_train (list-like): features of train set. y_train (list-like): labels of train set. X_test (list-like): features of test set. y_test (list-like): labels of test set. params (dict): parameters to specify to the model. Returns: (float): the accuracy score of the model's predictions on the test set after being trained on the train set. """ clf = model(**params) clf.fit(X_train, y_train) return clf.score(X_test, y_test)
bigcode/self-oss-instruct-sc2-concepts
def user_agrees(prompt_message: str) -> bool: """Ask user a question and ask him/her for True/False answer (default answer is False). :param prompt_message: message that will be prompted to user :return: boolean information if user agrees or not """ answer = input(prompt_message + ' [y/N] ') return answer.lower() in ['y', 'yes', 't', 'true']
bigcode/self-oss-instruct-sc2-concepts
def get(yaml_config, key_path, default_value=None): """ Get a value in a yaml_config, or return a default value. :param yaml_config: the YAML config. :param key: a key to look for. This can also be a list, looking at more depth. :param default_value: a default value to return in case the key is not found. :return: the value at the given key path, or default_value if not found. """ if len(key_path) == 0: return default_value node = yaml_config for key in key_path: try: node = node[key] except Exception: return default_value return node
bigcode/self-oss-instruct-sc2-concepts
def error_margin_approx(z_star, sigma, n): """ Get the approximate margin of error for a given critical score. Parameters ---------- > z_star: the critical score of the confidence level > sigma: the standard deviation of the population > n: the size of the sample Returns ------- The approximate margin of error, given by z_star(sigma/root(n)). """ return z_star * (sigma / (n ** 0.5))
bigcode/self-oss-instruct-sc2-concepts
def find_user(collection, elements, multiple=False): """ Function to retrieve single or multiple user from a provided Collection using a dictionary containing a user's elements. """ if multiple: results = collection.find(elements) return [r for r in results] else: return collection.find_one(elements)
bigcode/self-oss-instruct-sc2-concepts
def extract_name_and_id(user_input): """Determines if the string user_input is a name or an id. :param user_input: (str): input string from user :return: (name, id) pair """ name = id = None if user_input.lower().startswith('id:'): id = user_input[3:] else: name = user_input return name, id
bigcode/self-oss-instruct-sc2-concepts
def selection_sort(integer_list): """ The selection sort improves on the bubble sort by making only one exchange for every pass through the list. In order to do this, a selection sort looks for the largest value as it makes a pass and, after completing the pass, places it in the proper location. As with a bubble sort, after the first pass, the largest item is in the correct place. After the second pass, the next largest is in place. This process continues and requires n−1n−1 passes to sort n items, since the final item must be in place after the (n−1)(n−1) st pass. This implementation starts from the end of the list integer_list -- A list of integers """ for index in range(len(integer_list)-1, 1, -1): largest_index = index for i in range(index): if integer_list[i] > integer_list[largest_index]: largest_index = i # Swap largest value with current index integer_list[largest_index], integer_list[index] = \ integer_list[index], integer_list[largest_index] return integer_list
bigcode/self-oss-instruct-sc2-concepts
def minsort(lst): """ Sort list using the MinSort algorithm. >>> minsort([24, 6, 12, 32, 18]) [6, 12, 18, 24, 32] >>> minsort([]) [] >>> minsort("hallo") Traceback (most recent call last): ... TypeError: lst must be a list """ # Check given parameter data type. if not type(lst) == list: raise TypeError('lst must be a list') # Get length of the list. n = len(lst) # For each list element. for i in range(n): # Find the minimum in list[i..n-1]. min_value = lst[i] min_index = i for j in range(i + 1, n): if lst[j] < min_value: min_value = lst[j] min_index = j # Swap minimum to position i. lst[i], lst[min_index] = lst[min_index], lst[i] return lst
bigcode/self-oss-instruct-sc2-concepts
import logging def possible_int(arg): """Attempts to parse arg as an int, returning the string otherwise""" try: return int(arg) except ValueError: logging.info(f'failed to parse {arg} as an int, treating it as a string') return arg
bigcode/self-oss-instruct-sc2-concepts
def find_two_sum(arr, target): """ Finds the two (not necessarily distinct) indices of the first two integers in arr that sum to target, in sorted ascending order (or returns None if no such pair exists). """ prev_map = {} # Maps (target - arr[i]) -> i. for curr_idx, num in enumerate(arr): # Putting this block *before* the next block allows for the possibility # that prev_idx == curr_idx. If this isn't desired, then put it after. comp = target - num if comp not in prev_map: # Don't overwrite the previous mapping. prev_map[comp] = curr_idx # Check if arr[curr_idx] matches some (target - arr[prev_idx]). if num in prev_map: prev_idx = prev_map[num] return prev_idx, curr_idx return None
bigcode/self-oss-instruct-sc2-concepts
import ast def read_data_from_txt(file_loc): """ Read and evaluate a python data structure saved as a txt file. Args: file_loc (str): location of file to read Returns: data structure contained in file """ with open(file_loc, 'r') as f: s = f.read() return ast.literal_eval(s)
bigcode/self-oss-instruct-sc2-concepts
import math def bounding_hues_from_renotation(hue, code): """ Returns for a given hue the two bounding hues from *Munsell Renotation System* data. Parameters ---------- hue : numeric *Munsell* *Colorlab* specification hue. code : numeric *Munsell* *Colorlab* specification code. Returns ------- tuple Bounding hues. References ---------- .. [11] **The Munsell and Kubelka-Munk Toolbox**: *MunsellAndKubelkaMunkToolboxApr2014*: *MunsellSystemRoutines/BoundingRenotationHues.m* Examples -------- >>> bounding_hues_from_renotation(3.2, 4) ((2.5, 4), (5.0, 4)) """ if hue % 2.5 == 0: if hue == 0: hue_cw = 10 code_cw = (code + 1) % 10 else: hue_cw = hue code_cw = code hue_ccw = hue_cw code_ccw = code_cw else: hue_cw = 2.5 * math.floor(hue / 2.5) hue_ccw = (hue_cw + 2.5) % 10 if hue_ccw == 0: hue_ccw = 10 code_ccw = code if hue_cw == 0: hue_cw = 10 code_cw = (code + 1) % 10 if code_cw == 0: code_cw = 10 else: code_cw = code code_ccw = code return (hue_cw, code_cw), (hue_ccw, code_ccw)
bigcode/self-oss-instruct-sc2-concepts
def get_div_winners(df_sim): """Calculate division winners with summarised simulation data :param df_sim: data frame with simulated scores summarised by iteration :return: data frame with division winners per iteration """ return ( df_sim .sort_values(by=['tot_wins', 'tot_pts'], ascending=[False, False]) .groupby(['iteration', 'divisionId']) .head(1) .sort_values(by=['divisionId', 'iteration']) .reset_index(drop=True) )
bigcode/self-oss-instruct-sc2-concepts
def _construct_version(major, minor, patch, level, pre_identifier, dev_identifier, post_identifier): """Construct a PEP0440 compatible version number to be set to __version__""" assert level in ["alpha", "beta", "candidate", "final"] version = "{0}.{1}".format(major, minor) if patch: version += ".{0}".format(patch) if level == "final": if post_identifier: version += ".{0}{1}".format("post", post_identifier) if dev_identifier: version += ".{0}{1}".format("dev", dev_identifier) else: level_short = {"alpha": "a", "beta": "b", "candidate": "rc"}[level] version += "{0}{1}".format(level_short, pre_identifier) if post_identifier: version += ".{0}{1}".format("post", post_identifier) if dev_identifier: version += ".{0}{1}".format("dev", dev_identifier) return version
bigcode/self-oss-instruct-sc2-concepts
def channel_parser(channel): """Parse a channel returned from ipmitool's "sol info" command. Channel format is: "%d (%x)" % (channel, channel) """ chan, xchan = channel.split(' (') return int(chan)
bigcode/self-oss-instruct-sc2-concepts
def find_col(table, col): """ Return column index with col header in table or -1 if col is not in table """ return table[0].index(col)
bigcode/self-oss-instruct-sc2-concepts
import torch def loss_fn(outputs, labels): """ Compute the cross entropy loss given outputs from the model and labels for all tokens. Exclude loss terms for PADding tokens. Args: outputs: (Variable) dimension batch_size*seq_len x num_tags - log softmax output of the model labels: (Variable) dimension batch_size x seq_len where each element is either a label in [0, 1, ... num_tag-1], or -1 in case it is a PADding token. Returns: loss: (Variable) cross entropy loss for all tokens in the batch Note: you may use a standard loss function from http://pytorch.org/docs/master/nn.html#loss-functions. This example demonstrates how you can easily define a custom loss function. """ # reshape labels to give a flat vector of length batch_size*seq_len labels = labels.view(-1) # since PADding tokens have label -1, we can generate a mask to exclude the loss from those terms mask = (labels >= 0).float() # indexing with negative values is not supported. Since PADded tokens have label -1, we convert them to a positive # number. This does not affect training, since we ignore the PADded tokens with the mask. labels = labels % outputs.shape[1] num_tokens = torch.sum(mask).item() # compute cross entropy loss for all tokens (except PADding tokens), by multiplying with mask. return -torch.sum(outputs[range(outputs.shape[0]), labels]*mask)/num_tokens
bigcode/self-oss-instruct-sc2-concepts
def get_taskToken(decision): """ Given a response from polling for decision from SWF via boto, extract the taskToken from the json data, if present """ try: return decision["taskToken"] except KeyError: # No taskToken returned return None
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def broadcast_variables(*variables): """Given any number of variables, return variables with matching dimensions and broadcast data. The data on the returned variables will be a view of the data on the corresponding original arrays, but dimensions will be reordered and inserted so that both broadcast arrays have the same dimensions. The new dimensions are sorted in order of appearence in the first variable's dimensions followed by the second variable's dimensions. """ # validate dimensions all_dims = OrderedDict() for var in variables: var_dims = var.dims if len(set(var_dims)) < len(var_dims): raise ValueError('broadcasting cannot handle duplicate ' 'dimensions: %r' % list(var_dims)) for d, s in zip(var_dims, var.shape): if d not in all_dims: all_dims[d] = s elif all_dims[d] != s: raise ValueError('operands cannot be broadcast together ' 'with mismatched lengths for dimension %r: %s' % (d, (all_dims[d], s))) dims = tuple(all_dims) return tuple(var.set_dims(all_dims) if var.dims != dims else var for var in variables)
bigcode/self-oss-instruct-sc2-concepts
def chunkFair(mylist, nchunks): """ Split list into near-equal size chunks, but do it in an order like a draft pick; they all get high and low indices. E.g. for mylist = [0,1,2,3,4,5,6], chunkFair(mylist,4) => [[0, 4], [1, 5], [2, 6], [3]] """ chunks = [None]*nchunks for i in range(nchunks): chunks[i] = [] i = 0 while i < len(mylist): j = 0 while (i < len(mylist)) & (j < nchunks): chunks[j].append(mylist[i]) j += 1 i += 1 return chunks
bigcode/self-oss-instruct-sc2-concepts
def unionRect(rect1, rect2): """Determine union of bounding rectangles. Args: rect1: First bounding rectangle, expressed as tuples ``(xMin, yMin, xMax, yMax)``. rect2: Second bounding rectangle. Returns: The smallest rectangle in which both input rectangles are fully enclosed. """ (xMin1, yMin1, xMax1, yMax1) = rect1 (xMin2, yMin2, xMax2, yMax2) = rect2 xMin, yMin, xMax, yMax = (min(xMin1, xMin2), min(yMin1, yMin2), max(xMax1, xMax2), max(yMax1, yMax2)) return (xMin, yMin, xMax, yMax)
bigcode/self-oss-instruct-sc2-concepts
import math def inverse_sigmoid(y): """A Python function for the inverse of the Sigmoid function.""" return math.log(y / (1 - y))
bigcode/self-oss-instruct-sc2-concepts
import math def image_entropy(img): """ calculate the entropy of an image """ hist = img.histogram() hist_size = sum(hist) hist = [float(h) / hist_size for h in hist] return -sum([p * math.log(p, 2) for p in hist if p != 0])
bigcode/self-oss-instruct-sc2-concepts
def strip_alias_prefix(alias): """ Splits `alias` on ':' to strip off any alias prefix. Aliases have a lab-specific prefix with ':' delimiting the lab name and the rest of the alias; this delimiter shouldn't appear elsewhere in the alias. Args: alias: `str`. The alias. Returns: `str`: The alias without the lab prefix. Example:: strip_alias_prefix("michael-snyder:B-167") # Returns "B-167" """ return alias.split(":")[-1]
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime import pytz def read_gpvtg(sentence, timestamp, do_print=False): """ Read and parse GPVTG message""" values = sentence.split('*')[0].split(',') result = {} # Linux timestamp try: result['linux_stamp'] = int(timestamp) except: result['linux_stamp'] = 0 result['linux_date'] = datetime.fromtimestamp(result['linux_stamp'], tz=pytz.UTC) # True Track try: result['truetrack'] = float(values[1]) except: result['truetrack'] = None # Magnetic Track try: result['magnetictrack'] = float(values[3]) except: result['magnetictrack'] = None # Groundspeed, knots try: result['groundspeed_knots'] = float(values[5]) except: result['groundspeed_knots'] = None # Groundspeed, km/h try: result['groundspeed_kmh'] = float(values[7]) except: result['groundspeed_kmh'] = None if do_print: if result['truetrack'] is None and \ result['magnetictrack'] is None and \ result['groundspeed_knots'] is None and \ result['groundspeed_kmh'] is None: pass else: print("Linux timestamp :", result['linux_stamp']) print("Linux datetime :", result['linux_date']) print(" True Track :", result['truetrack']) print(" Magnetic Track :", result['magnetictrack']) print(" Ground spd, knot:", result['groundspeed_knots']) print(" Ground spd, km/h:", result['groundspeed_kmh']) print("") return result
bigcode/self-oss-instruct-sc2-concepts
def COUNT_DISTINCT(src_column): """ Builtin unique counter for groupby. Counts the number of unique values Example: Get the number of unique ratings produced by each user. >>> sf.groupby("user", ... {'rating_distinct_count':tc.aggregate.COUNT_DISTINCT('rating')}) """ return ("__builtin__count__distinct__", [src_column])
bigcode/self-oss-instruct-sc2-concepts
def clamp(value, minimumValue, maximumValue): """clamp the value between the minimum and the maximum value :param value: value to clamp :type value: int or float :param minimumValue: minimum value of the clamp :type minimumValue: int or float :param maximumValue: maximum value of the clamp :type maximumValue: int or float :return: the clamped value :rtype: int or float """ # errors if not minimumValue < maximumValue: raise RuntimeError('minvalue is not strictly inferior to maxvalue') # execute return max(minimumValue, min(maximumValue, value))
bigcode/self-oss-instruct-sc2-concepts
def check_for_url_proof_id(id, existing_ids = None, min_id_length = 1, max_id_length = 21): """Returns (True, id) if id is permissible, and (False, error message) otherwise. Since we strip the id, you should use the returned one, not the original one""" id = id.strip() # maybe this is too restrictive, but I want to use the id directly in urls for c in id: if not c.lower() in "0123456789abcdefghijklmnopqrstuvwxyz@._-": return False, "The character '%s' is not allowed" %c if existing_ids and id.lower() in existing_ids: return False, "ID already exists" if len(id) < min_id_length: return False, "Must at least have %s characters" % min_id_length if len(id) > max_id_length: return False, "Must have less than %s characters" % max_id_length return True, id
bigcode/self-oss-instruct-sc2-concepts
def is_equal_1d(ndarray1, ndarray2, showdiff=False, tolerance=0.000001): """ Whether supplied 1d numpy arrays are similar within the tolerance limit? Parameters ---------- ndarray1 : numpy.ndarray[float64, ndim=1] First array supplied for equality with `ndarray2`. ndarray2 : numpy.ndarray[float64, ndim=1] Second array supplied for equality angainst `ndarray1`. showdiff : bool (default: False) If two array corresponding elements differ by morre than `tolerance` then stop further comparison and report position of mismatch. tolerance : float64 (default: 0.000001) A threshold value which can be tolerated for similarity of two corresponding elements of the supplied arrays. Returns ------- bool, str, list[str] if showdiff==True bool otherwise A thruth value of equality query of arguments, difference accepted within tolerance. Cause why two arguments dont match. A list of string showing first position and values of entries which do not match. """ result = True cause = '' diff_loc_val = [] if type(ndarray1) is not type(ndarray2): result = False cause = 'Dataset type mismatch: {0} and {1}' % ( type(ndarray1), type(ndarray2)) else: if ndarray1.shape != ndarray1.shape: result = False cause = 'dataset shape mismatch: {0} and {1}' % ( ndarray1.shape, ndarray2.shape) else: for i in range(ndarray1.shape[0]): d = ndarray1[i] - ndarray2[i] if d > tolerance: diff_loc_val.append((i, d)) result = False break if showdiff: return (result, cause, diff_loc_val) else: return result
bigcode/self-oss-instruct-sc2-concepts
def sort_and_uniq(linput): # @ReservedAssignment """ Función que elimina datos repetidos. :param linput: Lista :type linput: list :return: Lista modificada :rtype: list """ output = [] for x in linput: if x not in output: output.append(x) output.sort() return output
bigcode/self-oss-instruct-sc2-concepts
import asyncio def swait(co): """Sync-wait for the given coroutine, and return the result.""" return asyncio.get_event_loop().run_until_complete(co)
bigcode/self-oss-instruct-sc2-concepts
def get_indexes(table, col, v): """ Returns indexes of values _v_ in column _col_ of _table_. """ li = [] start = 0 for row in table[col]: if row == v: index = table[col].index(row, start) li.append(index) start = index + 1 return li
bigcode/self-oss-instruct-sc2-concepts
import json def load_json(filename): """Load a json file as a dictionary""" try: with open(filename, 'rb') as fid: data = json.load(fid) return data, None except Exception as err: return None, str(err)
bigcode/self-oss-instruct-sc2-concepts
def determine_Cd(w_10): """ Determining the wind speed drag coefficient Following Large & Pond (1981) https://doi.org/10.1175/1520-0485(1981)011%3C0324:OOMFMI%3E2.0.CO;2 """ return min(max(1.2E-3, 1.0E-3 * (0.49 + 0.065 * w_10)), 2.12E-3)
bigcode/self-oss-instruct-sc2-concepts
def pack(timestamp, temp, accel_data, gyro_data, magnet_data=None): """ 最新位置情報データを辞書化する。 引数: timestamp 時刻 temp 気温(float) accel_data 加速度データ(辞書) gyro_data 角速度データ(辞書) magnet_data 磁束密度データ(辞書):オプション 戻り値: 最新位置情報データ群(辞書) """ return_dict = {'accel': accel_data, 'gyro': gyro_data, 'temp': temp, 'timestamp': timestamp} if magnet_data is not None: return_dict['magnet'] = magnet_data return return_dict
bigcode/self-oss-instruct-sc2-concepts
import torch def lengths_to_mask(lengths, max_len): """ This mask has a 1 for every location where we should calculate a loss lengths include the null terminator. for example the following is length 1: 0 0 0 0 0 0 The following are each length 2: 1 0 0 0 0 3 0 0 0 0 if max_len is 3, then the tensor will be 3 wide. The longest tensors will look like: 1 2 0 3 4 0 5 7 0 Whils the rnn might not generate the final 0 each time, this is an error The mask for these length 3 utterances will be all 1s: 1 1 1 1 1 1 """ assert len(lengths.size()) == 1 N = lengths.size()[0] cumsum = torch.zeros(N, max_len, device=lengths.device, dtype=torch.int64).fill_(1) cumsum = cumsum.cumsum(dim=-1) l_expand = lengths.view(N, 1).expand(N, max_len) in_alive_mask = l_expand > cumsum - 1 return in_alive_mask
bigcode/self-oss-instruct-sc2-concepts
def check_line(line): """Check that: * a line has nine values * each val has length 1 * each val is either digital or "-" * digital values are between 1 and 9 """ vals = line.split() if not len(vals) == 9: return False for val in vals: if not len(val) == 1: return False if not (val.isdigit() or val == "-"): return False if val.isdigit() and not 1 <= int(val) <= 9: return False return True
bigcode/self-oss-instruct-sc2-concepts
import six def collect_ancestor_classes(cls, terminal_cls=None, module=None): """ Collects all the classes in the inheritance hierarchy of the given class, including the class itself. If module is an object or list, we only return classes that are in one of the given module/modules.This will exclude base classes that come from external libraries. If terminal_cls is encountered in the hierarchy, we stop ascending the tree. """ if terminal_cls is None: terminal_cls = [] elif not isinstance(terminal_cls, (list, set, tuple)): terminal_cls = [terminal_cls] if module is not None: if not isinstance(module, (list, set, tuple)): module = [module] module_strings = [] for m in module: if isinstance(m, six.string_types): module_strings.append(m) else: module_strings.append(m.__name__) module = module_strings ancestors = [] if (module is None or cls.__module__ in module) and cls not in terminal_cls: ancestors.append(cls) for base in cls.__bases__: ancestors.extend(collect_ancestor_classes(base, terminal_cls, module)) return ancestors
bigcode/self-oss-instruct-sc2-concepts
def bin2hex(binbytes): """ Converts a binary string to a string of space-separated hexadecimal bytes. """ return ' '.join('%02x' % ord(c) for c in binbytes)
bigcode/self-oss-instruct-sc2-concepts
import torch def calc_f1_micro(predictions, labels): """ Calculate f1 micro. Args: predictions: tensor with predictions labels: tensor with original labels Returns: f1 score """ preds = predictions.max(1)[1].type_as(labels) true_positive = torch.eq(labels, preds).sum().float() f1_score = torch.div(true_positive, len(labels)) return f1_score
bigcode/self-oss-instruct-sc2-concepts
def flatten(t): """ Helper function to make a list from a list of lists """ return [item for sublist in t for item in sublist]
bigcode/self-oss-instruct-sc2-concepts
def get_html_header() -> str: """Helper to get a HTML header with some CSS styles for tables."" Returns: A HTML header as string. """ return """<head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 768px } td, th { border: 1px solid #999999; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } </style> </head>"""
bigcode/self-oss-instruct-sc2-concepts
import glob def found_with_glob(value): """ Check if at least one file match the given glob expression. :param value: glob expression """ for _ in glob.glob(value): return True return False
bigcode/self-oss-instruct-sc2-concepts
import shutil def get_path_to_executable(executable): """ Get path to local executable. :param executable: Name of executable in the $PATH variable :type executable: str :return: path to executable :rtype: str """ path = shutil.which(executable) if path is None: raise ValueError( "'{}' executable not found in PATH.".format(executable)) return path
bigcode/self-oss-instruct-sc2-concepts
def _direction_to_index(direction): """Map direction identifier to index. """ directions = {-1: 0, 0: slice(None), 1: 1, '<=': 0, '<=>': slice(None), '>=': 1} if direction not in directions: raise RuntimeError('Unknown direction "{:d}".'.format(direction)) return directions[direction]
bigcode/self-oss-instruct-sc2-concepts
import requests import warnings def check_pypi_module(module_name, module_version=None, raise_on_error=False, warn_on_error=True): """ Checks that module with given name and (optionally) version exists in PyPi repository. :param module_name: name of module to look for in PyPi :param module_version: (optional) version of module to look for in PyPi :param raise_on_error: raise `ValueError` if module is not found in PyPi instead of returning `False` :param warn_on_error: print a warning if module is not found in PyPi :return: `True` if module found in PyPi, `False` otherwise """ r = requests.get('https://pypi.org/pypi/{}/json'.format(module_name)) if r.status_code != 200: msg = 'Cant find package {} in PyPi'.format(module_name) if raise_on_error: raise ValueError(msg) elif warn_on_error: warnings.warn(msg) return False if module_version is not None and module_version not in r.json()['releases']: msg = 'Cant find package version {}=={} in PyPi'.format(module_name, module_version) if raise_on_error: raise ImportError(msg) elif warn_on_error: warnings.warn(msg) return False return True
bigcode/self-oss-instruct-sc2-concepts
def postprocess_chain(chain, guard_solutions): """ This function post-processes the chains generated by angrop to insert input to pass the conditions on each gadget. It takes two arguments: chain - the ropchain returned by angrop guard_solutions - the required inputs to satisfy the gadget checks """ # we assemble the chain into bytes, since we will process it that way payload = chain.payload_str() # we iterate through the whole chain to fix up each gadget. The first 8 # bytes of the remaining "payload" string always correspond to the address # of the next gadget in chain._gadgets guarded_chain = payload[:8] payload = payload[8:] for g in chain._gadgets: # each gadget records how it changes the stack, which is the amount of # input that it pops from the payload, so we add that to our result guarded_chain += payload[:g.stack_change - 8] payload = payload[g.stack_change - 8:] # now, we add the input to spatisfy the conditions for triggering the # next gadget before going on to analyze it guarded_chain += guard_solutions[g.addr] guarded_chain += payload[:8] payload = payload[8:] assert len(payload) == 0 return guarded_chain
bigcode/self-oss-instruct-sc2-concepts
def _parse_top_section(line): """ Returns a top-level section name ("PATH", "GEM", "PLATFORMS", "DEPENDENCIES", etc.), or `None` if the line is empty or contains leading space. """ if line == "" or line[0].isspace(): return None return line
bigcode/self-oss-instruct-sc2-concepts
def remove_line_break_escapes(value): """ removes line break escapes from given value. it replaces `\\n` with `\n` to enable line breaks. :param str value: value to remove line break escapes from it. :rtype: str """ return value.replace('\\n', '\n')
bigcode/self-oss-instruct-sc2-concepts
def _get_id(name): """Gets id from a condensed name which is formatted like: name/id.""" return name.split("/")[-1]
bigcode/self-oss-instruct-sc2-concepts
def extract_endpoints(data): """ Turn the dictionary of endpoints from the config file into a list of all endpoints. """ endpoints = [] for nodetype in data: for interval in data[nodetype]: for api in data[nodetype][interval]: endpoints += ( data[nodetype][interval][api] ) return endpoints
bigcode/self-oss-instruct-sc2-concepts
import json import requests def getListOfPositions(position_name : str): """ Retrives all Microsoft publicily listed positions with name `position_name` by sending POST to Microsoft career endpoint. Args: position_name (str): Name of the position Returns: List of positions based on position_name and other criteria defined in body variables as JSON. Note: Actual JSON returned determined by endpoint """ if not position_name: print("Please specify a position_name") return None # Microsoft careers endpoint url = 'https://careers.microsoft.com/widgets' # Specific JSON data is expected by endpoint data = { # Edit these fields as you see fit. # They must conform to existing data fields found on career page "searchType":"professional", #professional or university "keywords": position_name, "selected_fields": { "country": ["United States"], "category": ["Engineering"], #"employmentType": ["Full-Time"], #"requisitionRoleType": ["Individual Contributor"] }, # Only change these fields if you know what you are doing "lang": "en_us", "deviceType": "desktop", "country": "us", "ddoKey": "refineSearch", "sortBy": "Most relevant", "subsearch": "", "from": 0, # Return the first `from` to `size` results. # Change this field iteratively if displaying only smaller portions of `size` results "jobs": True, "counts": True, "all_fields": ["country","state","city","category","employmentType","requisitionRoleType","educationLevel"], "pageName": "search-results", "size": 10000, # Use small numbers when testing - don't be a jerk to Microsoft. # Preferred max is 10000. # Note: This returns first `size` results that Microsoft returns. "clearAll": False, "jdsource": "facets", "isSliderEnable": False, "isMostPopular": True, "global": True } data_json = json.dumps(data) headers = {'Content-type':'application/json'} response = requests.post(url, data=data_json, headers=headers) return response.json()
bigcode/self-oss-instruct-sc2-concepts
def test_savestate(neuron_instance): """Test rxd SaveState Ensures restoring to the right point and getting the right result later. Note: getting the right result later was a problem in a prior version of NEURON, so the continuation test is important. The issue was that somehow restoring from a SaveState broke the rxd connection to the integrator. """ h, rxd, data, save_path = neuron_instance soma = h.Section(name="soma") soma.insert(h.hh) soma.nseg = 51 cyt = rxd.Region(h.allsec(), name="cyt") c = rxd.Species(cyt, name="c", d=1, initial=lambda node: 1 if node.x < 0.5 else 0) c2 = rxd.Species( cyt, name="c2", d=0.6, initial=lambda node: 1 if node.x > 0.5 else 0 ) r = rxd.Rate(c, -c * (1 - c) * (0.3 - c)) r2 = rxd.Reaction(c + c2 > c2, 1) h.finitialize(-65) soma(0).v = -30 while h.t < 5: h.fadvance() def get_state(): return ( soma(0.5).v, c.nodes(soma(0.5)).concentration[0], c2.nodes(soma(0.5)).concentration[0], ) s1 = get_state() s = h.SaveState() s.save() while h.t < 10: h.fadvance() s2 = get_state() s.restore() assert get_state() == s1 assert get_state() != s2 while h.t < 10: h.fadvance() assert get_state() != s1 assert get_state() == s2
bigcode/self-oss-instruct-sc2-concepts
def ask(message, options, allow_empty=False, help=None) -> str: """Ask user for input Parameters ---------- message : str Message. options : dict ``{command: description}`` mapping. allow_empty : bool Allow empty string as command. help : str If provided, add a "help" option that prints ``help``. Returns ------- command : str The user command. """ options = dict(options) if help is not None: assert 'help' not in options options['help'] = 'display help' print(message) print('---') print('\n'.join(f'{k}: {v}' for k, v in options.items())) while True: command = input(" > ") if command in options or (allow_empty and not command): if help is not None and command == 'help': print(help) else: return command else: print(f"Invalid entry - type one of ({', '.join(options)})")
bigcode/self-oss-instruct-sc2-concepts
import random def random_payload_shuffled_bytes(random_payload_bytes): """ Fixture that yields the randomly generated payload bytes but shuffled in a random order. """ return random.sample(random_payload_bytes, len(random_payload_bytes))
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def greeting(name: Optional[str] = None) -> str: """Says hello given an optional name. NOTE: `Optional` is just a convenience. It's equivalent to `Union[str, None]`. """ if name: return f"Hello {name}!" else: return "Hello you!"
bigcode/self-oss-instruct-sc2-concepts
import math def ecliptic_longitude_radians(mnlong, mnanomaly): """Returns ecliptic longitude radians from mean longitude and anomaly correction.""" return math.radians((mnlong + 1.915 * math.sin(mnanomaly) + 0.020 * math.sin(2 * mnanomaly)) % 360)
bigcode/self-oss-instruct-sc2-concepts
def buff_internal_eval(params): """Builds and evaluates BUFF internal energy of a model in parallelization Parameters ---------- params: list Tuple containing the specification to be built, the sequence and the parameters for model building. Returns ------- model.bude_score: float BUFF internal energy score to be assigned to particle fitness value. """ specification, sequence, parsed_ind = params model = specification(*parsed_ind) model.build() model.pack_new_sequences(sequence) return model.buff_internal_energy.total_energy
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def countdown( element: Dict[str, Any], all_data: Dict[str, Dict[int, Dict[str, Any]]] ) -> Dict[str, Any]: """ Countdown slide. Returns the full_data of the countdown element. element = { name: 'core/countdown', id: 5, # Countdown ID } """ countdown_id = element.get("id") or 1 try: return all_data["core/countdown"][countdown_id] except KeyError: return {"error": f"Countdown {countdown_id} does not exist"}
bigcode/self-oss-instruct-sc2-concepts
def is_csv_accepted(request): """ Returns if csv is accepted or not :return: True if csv is accepted, False otherwise """ return request.args.get('format') == "csv"
bigcode/self-oss-instruct-sc2-concepts
def can_copy(user, plan): """ Can a user copy a plan? In order to copy a plan, the user must be the owner, or a staff member to copy a plan they own. Any registered user can copy a template. Parameters: user -- A User plan -- A Plan Returns: True if the User has permission to copy the Plan. """ return plan.is_template or plan.is_shared or plan.owner == user or user.is_staff
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_classifcation_metrics_pkl(classification_pkl): """Load a classificationMetrics pickle file""" with open(classification_pkl, 'rb') as fh: cm_h = pickle.load(fh) return cm_h
bigcode/self-oss-instruct-sc2-concepts