seed
stringlengths
1
14k
source
stringclasses
2 values
def fake_agent() -> str: """ The original FAKE_USER_AGENT in config.py: 'Mozilla/5.0 (Windows NT 6.1; rv:84.0) Gecko/20100101 Firefox/84.0' Works with Startpage when nothing else will. :return: static user agent string. """ # NOTE that the Firefox ver can be any from firefox_agent() return 'Mozilla/5.0 (Windows NT 6.1; rv:84.0) Gecko/20100101 Firefox/84.0'
bigcode/self-oss-instruct-sc2-concepts
import math def optimum_qubit_size(precision: int, error: float) -> int: """ Return the number of qubit required for targeted number of decimal and error rate. """ return math.ceil(precision + math.log2(2+1/(2*error)))
bigcode/self-oss-instruct-sc2-concepts
def get_current_weather_desc(data): """Get the current weather description. These values are undocumented. :param data: :return: e.g. 'Partly Cloudy', 'Light Rain' """ return data['current_condition'][0]['weatherDesc'][0]['value']
bigcode/self-oss-instruct-sc2-concepts
import csv def save_to_csv(data: list, file_name: str) -> bool: """ Saved given data to .csv file. Parameters ---------- data: list, required Data produced by function prepare_data_to_save(). file_name: str, required Path and file name to where save file. It should not include ".csv" at the end. Returns ------- True if file created or false if not. Example ------- >>> save_to_csv(prepare_data, 'test') """ with open(f'{file_name}.csv', 'w+', newline='') as csvfile: fieldnames = ['name', 'date', 'amount'] writer = csv.writer(csvfile) writer.writerow(fieldnames) for value in data: writer.writerow(value) if writer: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def formatargvalues(args, varargs, varkw, locals, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value)): """Format an argument spec from the 4 values returned by getargvalues. The first four arguments are (args, varargs, varkw, locals). The next four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional function to format the sequence of arguments.""" def convert(name, locals=locals, formatarg=formatarg, formatvalue=formatvalue): return formatarg(name) + formatvalue(locals[name]) specs = [] for i in range(len(args)): specs.append(convert(args[i])) if varargs: specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) if varkw: specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) return '(' + ', '.join(specs) + ')'
bigcode/self-oss-instruct-sc2-concepts
def get_roi_names(contour_data): """ This function will return the names of different contour data, e.g. different contours from different experts and returns the name of each. Inputs: contour_data (dicom.dataset.FileDataset): contour dataset, read by dicom.read_file Returns: roi_seq_names (list): names of the """ roi_seq_names = [roi_seq.ROIName for roi_seq in list(contour_data.StructureSetROISequence)] return roi_seq_names
bigcode/self-oss-instruct-sc2-concepts
def is_empty(any_structure): """Helper method to check if structure is empty.""" if any_structure: return False else: return True
bigcode/self-oss-instruct-sc2-concepts
def shift_induction_times(exp, min_start=20, min_end=30): """ Shifts the induction start and end times forward or backward by separately specified numbers of minutes. Returns an experiment object with a new induction record. :param min_start: int Number of minutes to shift induction start times forward. :param min_end: int Number of minutes to shift induction end times forward. :return: new_exp: dynomics.Experiment An experiment object with a new induction record, where the start and end times have been shifted by the desired amount. """ new_induction_record = exp.induction_record.copy() new_transition_times =\ new_induction_record.transition_time.add(min_start * 60) new_transition_times.iloc[0] =\ new_transition_times.iloc[0] - min_start * 60 new_end_times = new_induction_record.end_time.add(min_end * 60) new_end_times.iloc[-1] = new_end_times.iloc[-1] - min_end * 60 new_induction_record.transition_time = new_transition_times new_induction_record.end_time = new_end_times new_exp = exp.set(induction_record=new_induction_record) return new_exp
bigcode/self-oss-instruct-sc2-concepts
def phalf_from_ps(bk, pk, ps): """Compute pressure of half levels of hybrid sigma-pressure coordinates.""" return ps*bk + pk
bigcode/self-oss-instruct-sc2-concepts
def get_shape_points(cur, shape_id): """ Given a shape_id, return its shape-sequence. Parameters ---------- cur: sqlite3.Cursor cursor to a GTFS database shape_id: str id of the route Returns ------- shape_points: list elements are dictionaries containing the 'seq', 'lat', and 'lon' of the shape """ cur.execute('''SELECT seq, lat, lon, d FROM shapes where shape_id=? ORDER BY seq''', (shape_id,)) shape_points = [dict(seq=row[0], lat=row[1], lon=row[2], d=row[3]) for row in cur] return shape_points
bigcode/self-oss-instruct-sc2-concepts
def preprocess_rsa_key(key_str): """Make Android and iOS RSA keys compatible with cryptography library. Android and iOS have slightly wonky, non-standard key formats. This updates the key to be standardized and compatible with pyca/cryptography. """ if key_str.startswith("-----BEGIN CERTIFICATE"): key_str = key_str.replace("CERTIFICATE", "PUBLIC KEY") elif key_str.startswith("-----BEGIN RSA"): key_str = key_str.replace("BEGIN RSA", "BEGIN").replace("END RSA", "END") return key_str
bigcode/self-oss-instruct-sc2-concepts
import random def reproduce(parent1, parent2): """generate offspring using random crossover""" # random crossover point crossover = random.randrange(0, len(parent1)) # construct children child1 = parent1[0:crossover] + parent2[crossover:] child2 = parent2[0:crossover] + parent1[crossover:] # return children return child1, child2
bigcode/self-oss-instruct-sc2-concepts
import torch def transfer_weights(tf_model, torch_model): """ Example function on how to transfer weights from tensorflow model to pytorch model Parameters ---------- tf_model : tensorflow model Weight donor torch_model : pytorch model (torch.nn.Modules) Weight recipient Returns ------- torch_model : pytorch model Model with updated weights """ def convert_weight(W): return torch.tensor(W.transpose(3, 2, 0, 1), dtype=torch.float) def convert_bias(B): return torch.tensor(B, dtype=torch.float) all_tf_weights = tf_model.get_weights() torch_model.conv1.conv.weight.data = convert_weight(all_tf_weights[0]) torch_model.conv1.conv.bias.data = convert_bias(all_tf_weights[1]) torch_model.conv2.conv.weight.data = convert_weight(all_tf_weights[2]) torch_model.conv2.conv.bias.data = convert_bias(all_tf_weights[3]) torch_model.conv3.conv.weight.data = convert_weight(all_tf_weights[4]) torch_model.conv3.conv.bias.data = convert_bias(all_tf_weights[5]) torch_model.conv4.conv.weight.data = convert_weight(all_tf_weights[6]) torch_model.conv4.conv.bias.data = convert_bias(all_tf_weights[7]) torch_model.conv5.conv.weight.data = convert_weight(all_tf_weights[8]) torch_model.conv5.conv.bias.data = convert_bias(all_tf_weights[9]) return torch_model
bigcode/self-oss-instruct-sc2-concepts
def service_level(orders_received, orders_delivered): """Return the inventory management service level metric, based on the percentage of received orders delivered. Args: orders_received (int): Orders received within the period. orders_delivered (int): Orders successfully delivered within the period. Returns: Percentage (float) of orders received that were delivered within th period. """ return (orders_delivered / orders_received) * 100
bigcode/self-oss-instruct-sc2-concepts
def easy_emptylist(l): """Takes a list and returns True for empty list, False for nonempty""" return not l
bigcode/self-oss-instruct-sc2-concepts
def remove_dash(string): """ Removes the dash from the end of the string if there is one there. :string: (str) an input string :returns: (str) input string with no dash at the end of it """ if string[-1]=='-': return string[:-1] else: return string
bigcode/self-oss-instruct-sc2-concepts
def skewed_percentile_to_label(percentile): """ Assigns a descriptive term to the MMSE T-score based on its degree of skewness. """ if percentile > 24: return 'WNL' elif 9 <= percentile <= 24: return 'Low Average' elif 2 <= percentile <= 8: return 'Below Average' elif percentile < 2: return 'Exceptionally Low'
bigcode/self-oss-instruct-sc2-concepts
def deleted_genes_to_reactions(model, genes): """ Convert a set of deleted genes to the respective deleted reactions. Arguments: model (CBModel): model genes (list): genes to delete Returns: list: list of deleted reactions """ if isinstance(genes, str): genes = [genes] active_genes = set(model.genes) - set(genes) active_reactions = model.evaluate_gprs(active_genes) inactive_reactions = set(model.reactions) - set(active_reactions) return inactive_reactions
bigcode/self-oss-instruct-sc2-concepts
def paramsDictNormalized2Physical(params, params_range): """Converts a dictionary of normalized parameters into a dictionary of physical parameters.""" # create copy of dictionary params = dict(params) for key, val in params.items(): params[key] = val * (params_range[key][1]-params_range[key][0]) + params_range[key][0] return params
bigcode/self-oss-instruct-sc2-concepts
def REDUCE(_input, initial_value, _in): """ Applies an expression to each element in an array and combines them into a single value. See https://docs.mongodb.com/manual/reference/operator/aggregation/reduce/ for more details :param _input: Can be any valid expression that resolves to an array. :param initial_value: The initial cumulative value set before in is applied to the first element of the input array. :param _in: A valid expression that reduce applies to each element in the input array in left-to-right order. :return: Aggregation operator """ return {'$reduce': {'input': _input, 'initialValue': initial_value, 'in': _in}}
bigcode/self-oss-instruct-sc2-concepts
def linear(x: float) -> float: """ Linear activation function (simply returns the input, unchanged). """ return x
bigcode/self-oss-instruct-sc2-concepts
def _pop_next_function(function_list): """Pops and returns the next function in the list.""" if not function_list: raise IndexError('in _pop_next_function: list of functions is empty') return function_list.pop(0)
bigcode/self-oss-instruct-sc2-concepts
def get_symbols(bv): """Return all symbols in binary. Args: bv (BinaryView): top-level binary view handler. Lots of interesting methods can be accessed. Returns: list: list of symbols in binary. """ total_symbols = list() for s in bv.symbols.values(): if isinstance(s, list): total_symbols.extend(s) else: total_symbols.append(s) return total_symbols
bigcode/self-oss-instruct-sc2-concepts
def _flatten_list(nested_list): """ Given a nested list, returns flat list of all its elements :param nested_list: nested list :return: flat list """ if not isinstance(nested_list, list): return [nested_list] res = [] for sub_list in nested_list: res += _flatten_list(sub_list) return res
bigcode/self-oss-instruct-sc2-concepts
def dict_subset(d, keys): """Return a dict with the specified keys""" result = {} for key in keys: if '.' in key: field, subfield = key.split('.', 1) if isinstance(d.get(field), dict): subvalue = dict_subset(d[field], [subfield]) result.setdefault(field, {}).update(subvalue) elif field in d: result[field] = d[field] else: if key in d: result[key] = d[key] return result
bigcode/self-oss-instruct-sc2-concepts
def ALMAGetBandLetter( freq ): """ Return the project observing band letter from frequency * freq = Frequency in Hz """ if freq<117.0e9: return "A3" elif freq<163.0e9: return "A4" elif freq<211.0e9: return "A5" elif freq<275.0e9: return "A6" elif freq<375.0e9: return "A7" elif freq<510.0e9: return "A8" elif freq<730.0e9: return "A9" elif freq<960.0e9: return "A10" if freq<2000.0e9: return "A11" else: return "UK"
bigcode/self-oss-instruct-sc2-concepts
import requests def is_active(url:str) -> bool: """Checks if the url we are parsing is active link. Args: url (str): [description] Returns: bool: True if get a 200 response else """ resp = requests.get(url) return True if resp.status_code == 200 else False
bigcode/self-oss-instruct-sc2-concepts
def is_peer_tuple(p): """Is p a (str,int) tuple? I.E. an (ip_address,port)""" if type(p) == tuple and len(p) == 2: return type(p[0]) == str and type(p[1]) == int else: return False
bigcode/self-oss-instruct-sc2-concepts
def convert_to_int(s): """ Convert string to integer :param s: Input string :return: Interpreted value if successful, 0 otherwise """ try: nr = int(s) except (ValueError, TypeError): nr = 0 return nr
bigcode/self-oss-instruct-sc2-concepts
def create_language_method(language_code): """ Creates a manager method that filters given language code """ def get_language(self): return self.filter(i18n_language=language_code) return get_language
bigcode/self-oss-instruct-sc2-concepts
def addArray(pdo, field, vtkArray): """ Adds an array to a vtkDataObject given its field association """ # Point Data if field == 0: pdo.GetPointData().AddArray(vtkArray) # Cell Data: elif field == 1: pdo.GetCellData().AddArray(vtkArray) # Field Data: elif field == 2: pdo.GetFieldData().AddArray(vtkArray) # Row Data: elif field == 6: pdo.GetRowData().AddArray(vtkArray) else: raise Exception('Field association not defined. Try inputing Point, Cell, Field, or Row data.') return pdo
bigcode/self-oss-instruct-sc2-concepts
def to_bytes(value, bytes_num, order='big', signed=False) -> bytes: """ Convert value to bytes representation. # Arguments value: int, Value to be converted. bytes_num: int > 0, Number of bytes in representation of `value`. Must be sufficiently big to store `value` order: 'big' or 'small', Ordering of bytes in representation. singed: Boolean, Wether to represent `value` as a signed number. """ return value.to_bytes(bytes_num, byteorder=order, signed=signed)
bigcode/self-oss-instruct-sc2-concepts
def bunch(**kw): """ Create object with given attributes """ x = type('bunch', (object, ), {})() for k, v in kw.items(): setattr(x, k, v) return x
bigcode/self-oss-instruct-sc2-concepts
def str2seq(st, func=int, sep=None): """ "1 2 3" -> [func('1'), func('2'), func('3')]""" # XXX check usage of this, check if we need list() at all if sep is None: return list(map(func, st.split())) else: return list(map(func, st.split(sep)))
bigcode/self-oss-instruct-sc2-concepts
def detection_collate_fn(batch): """ Collate function used when loading detection datasets using a DataLoader. """ return tuple(zip(*batch))
bigcode/self-oss-instruct-sc2-concepts
def set_combinations(iterable): """ Compute all combinations of sets of sets example: set_combinations({{b}},{{e},{f}}) returns {{b,e},{b,f}} """ def _set_combinations(iter): current_set = next(iter, None) if current_set is not None: sets_to_combine_with = _set_combinations(iter) resulting_combinations = set() for c in current_set: if not sets_to_combine_with: resulting_combinations.add(frozenset(c)) for s in sets_to_combine_with: resulting_combinations.add(frozenset(c.union(s))) return resulting_combinations return set() return _set_combinations(iter(iterable))
bigcode/self-oss-instruct-sc2-concepts
def _tuple_2_id(num_single, idx): """Transfrom from tuple representation to id. If idx is a tuple representation of a member of a couple, transform it to id representation. Otherwise do nothing. Raises: TypeError if idx is neither an integer or a tuple """ if isinstance(idx, int): return idx elif isinstance(idx, tuple): return num_single + 2 * idx[0] + idx[1] else: raise TypeError("Cannot recognize idx as single or couple")
bigcode/self-oss-instruct-sc2-concepts
def remove_title(soup): """ Remove the title element and return the str representation. Args: soup (BeautifulSoup): HTML parsed notebook. Effect: Changes soup object to have title (h1) element removed. Returns: (str): Title text """ title = str(soup.h1.contents[0]) soup.h1.decompose() # escape colon character to avoid Jekyll issues title = title.replace(':', '&#58;') return title
bigcode/self-oss-instruct-sc2-concepts
def translate_points(points, translation): """ Returns the points translated according to translation. """ return points + translation
bigcode/self-oss-instruct-sc2-concepts
def _check_byte_size(size: int) -> bool: """ Checks whether size is a valid size. Sizes include None or >= 0 :param size: The size to check :type size: int :return: Whether the size is valid :rtype: bool """ if size is None: return True return size >= 0
bigcode/self-oss-instruct-sc2-concepts
def _check_boolean(input, name): """Exception raising if input is not a boolean Checks whether input is not ``None`` and if not checks that the input is a boolean. Parameters ---------- input: any The input parameter to be checked name: str The name of the variable for printing explicit errors in ``Exception`` Returns ------- bool Returns the input if all checks pass Raises ------ ValueError If input is None TypeError If input does not have correct type """ if input is None: raise ValueError(f"`{name}` is None") if not ((input is True) or (input is False)): raise TypeError(f"`{name}` must be type {bool} but is " + f"{type(input)}") return input
bigcode/self-oss-instruct-sc2-concepts
def time_at_timestamp(timestamp_ms: int) -> float: """Convert millisecond Epoch timestamp to Python float time value. Args: timestamp_ms: Epoch timestamp in milliseconds. Returns: Python time value in float. """ return float(timestamp_ms) / 1000.0
bigcode/self-oss-instruct-sc2-concepts
def args_to_str( args, positional_arg=None, fields=None, to_flag=True, arg_joiner=' ', val_sep=' ', list_joiner=' ', ): """Convert an argparse.ArgumentParser object back into a string, e.g. for running an external command.""" def val_to_str(v): if isinstance(v, list): return list_joiner.join(map(str, v)) return str(v) def arg_to_str(k, v): if to_flag: k = f"--{k.replace('_', '-')}" if v is True: return k if v is False: return "" else: v = val_to_str(v) return k + val_sep + v if positional_arg: pos_args = val_to_str(args.__dict__[positional_arg]) + val_sep else: pos_args = "" if fields is None: items = args.__dict__.items() else: items = [(k, args.__dict__[k]) for k in fields] return pos_args + arg_joiner.join([ arg_to_str(k, v) for k, v in items if v is not None and k != positional_arg])
bigcode/self-oss-instruct-sc2-concepts
def _acer_input(endfin, pendfin, aceout, dirout, mat, temp=293.6, iprint=False, itype=1, suff=".00", header="sandy runs acer", photons=True, **kwargs): """Write acer input for fast data. Parameters ---------- endfin : `int` tape number for input ENDF-6 file pendfin : `int` tape number for input PENDF file aceout : `int` tape number for output ACE file dirout : `int` tape number for output ACE file mat : `int` MAT number temp : `float` temperature in K (default is 293.6 K) local : `bool` option to deposit gamma rays locally (default is `False`) iprint : `bool` print option (default is `False`) itype : `int` ace output type: 1, 2, or 3 (default is 1) suff : `str` id suffix for zaid (default is ".00") header : `str` descriptive character string of max. 70 characters (default is "sandy runs acer") photons : `bool` detailed photons (default is `True`) Returns ------- `str` acer input text """ text = ["acer"] text += ["{:d} {:d} 0 {:d} {:d} /".format(endfin, pendfin, aceout, dirout)] text += ["1 {:d} {:d} {} 0 /".format(int(iprint), itype, suff)] text += ["'{}'/".format(header)] text += ["{:d} {:.1f} /".format(mat, temp)] text += ["1 {:d} /".format(int(photons))] text += ["/"] return "\n".join(text) + "\n"
bigcode/self-oss-instruct-sc2-concepts
def _splitnport(host, defport=-1): """Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. Return numerical port if a valid number are found after ':'. Return None if ':' but not a valid number.""" host, delim, port = host.rpartition(':') if not delim: host = port elif port: try: nport = int(port) except ValueError: nport = None return host, nport return host, defport
bigcode/self-oss-instruct-sc2-concepts
def create_draft_files_bp(app): """Create draft files blueprint.""" ext = app.extensions["invenio-rdm-records"] return ext.draft_files_resource.as_blueprint()
bigcode/self-oss-instruct-sc2-concepts
def list_pairs(validation_dates): """ For a set of ndates dates, return a list of indexes and IDs for all possible unique pairs. For example, for ndates=3 -> [(0, 1), (0,2), (1,2)] """ ndates = len(validation_dates) indexes = [] pair_ids = [] for k1 in range(ndates): for k2 in range(k1 + 1, ndates): indexes.append((k1, k2)) date1 = validation_dates[k1] date2 = validation_dates[k2] pair_ids.append(f"{date1[:4]}_{date2[:4]}") # year1_year2) return indexes, pair_ids
bigcode/self-oss-instruct-sc2-concepts
def _right_child(node): """ Args: node: index of a binary tree node Returns: index of node's right child """ return 2 * node + 2
bigcode/self-oss-instruct-sc2-concepts
def have_program(c, name): """ Returns whether connected user has program ``name`` in their ``$PATH``. """ return c.run("which {}".format(name), hide=True, warn=True)
bigcode/self-oss-instruct-sc2-concepts
def has_remote(repo, remote_name): """Returns true if the given repository already has the named remote. Args: repo: The git.Repo object representing the repository. remote_name: The remote name to be looked for. """ return remote_name in [x.name for x in repo.remotes]
bigcode/self-oss-instruct-sc2-concepts
def count_format_specifiers(format_string): """Return the number of format specifiers in string format_string. >>> count_format_specifiers("foo bar foo") 0 >>> count_format_specifiers("foo %d bar foo") 1 >>> count_format_specifiers("foo %d bar %i foo") 2 >>> count_format_specifiers("foo %d bar %i foo %% foo") 2 >>> count_format_specifiers("foo %d bar %i foo %% foo %d foo") 3 >>> count_format_specifiers("foo %d bar %i foo %% foo %*d foo") 4 """ assert(type(format_string) is str) n = 0 in_specifier = False for i, char in enumerate(format_string): if format_string[i - 1:i + 1] == "%%" or format_string[i:i + 2] == "%%": pass elif char == "%": in_specifier = True n += 1 elif char in "aAcdeEfFgGinopsuxX": in_specifier = False elif in_specifier and char == "*": n += 1 return n
bigcode/self-oss-instruct-sc2-concepts
import functools def cached_property(fun): """A memoize decorator for class properties. Adapted from: http://code.activestate.com/recipes/576563-cached-property/ """ @functools.wraps(fun) def get(self): try: return self._cache[fun] except AttributeError: self._cache = {} except KeyError: pass ret = self._cache[fun] = fun(self) return ret return property(get)
bigcode/self-oss-instruct-sc2-concepts
def merge(source1, source2): """Merge two dicts, source2 could override existing keys based on source1""" return {**source1, **source2}
bigcode/self-oss-instruct-sc2-concepts
import itertools def make_multidim(col, ndim): """Take a col with length=2 and make it N-d by repeating elements. For the special case of ndim==1 just return the original. The output has shape [3] * ndim. By using 3 we can be sure that repeating the two input elements gives an output that is sufficiently unique for the multidim tests. """ if ndim > 1: idxs = [idx for idx, _ in zip(itertools.cycle([0, 1]), range(3 ** ndim))] col = col[idxs].reshape([3] * ndim) return col
bigcode/self-oss-instruct-sc2-concepts
import csv def get_image_value_list(csv_file_name): """ Expects a csv file with header/structure: filename, TE, mean_background skips the first (header) line returns a list of tuples with (filename, TE) """ image_value_list = [] with open(csv_file_name) as csvfile: readCSV = csv.reader(csvfile, delimiter=',') # skip the header (first) line next(readCSV) for row in readCSV: image_value_list.append((row[0], row[1].strip())) return image_value_list
bigcode/self-oss-instruct-sc2-concepts
import json def load_json_from_file(file_path): """Load json from a json file""" with open(file_path) as json_data: return json.load(json_data)
bigcode/self-oss-instruct-sc2-concepts
async def in_voice_channel(ctx): """Checks that the command sender is in the same voice channel as the bot.""" voice = ctx.author.voice bot_voice = ctx.guild.voice_client if voice and bot_voice and voice.channel and bot_voice.channel and voice.channel == bot_voice.channel: return True else: await ctx.send("You need to be in the channel to do that") return False
bigcode/self-oss-instruct-sc2-concepts
def place(cards, pos, card): """ Replaces the card at a given position in a list. Example: > place([1,4,7,10,12], 2, 9) [1,4,9,10,12] """ result = cards[:] result[pos] = card return result
bigcode/self-oss-instruct-sc2-concepts
def text_of_list(t): """ Convert a string list to multiline text. """ return '\n'.join(t)
bigcode/self-oss-instruct-sc2-concepts
def trapmf(x, a, b, c, d): """ Trapezoidal membership function generator. Parameters ======== x : single element array like abcd : 1d array, length 4 Four-element vector. Ensure a <= b <= c <= d. Returns ======== y : 1d array Trapezoidal membership function. """ assert ( a <= b and b <= c and c <= d ), "abcd requires the four elements \ a <= b <= c <= d." # Compute y1 if x > a and x < b: y = (x - a) / (b - a) elif x >= b and x <= c: y = 1.0 elif x > c and x < d: y = (d - x) / (d - c) else: y = 0.0 return y
bigcode/self-oss-instruct-sc2-concepts
from typing import Set def import_declarations(import_set: Set[str]) -> str: """ Generate the import declaration(s) given the import specs. :param import_set: import specs :return: Go import declaration >>> import_declarations(set()) '' >>> import_declarations({'time'}) 'import "time"' >>> print(import_declarations({'time', 'regexp'})) import ( "regexp" "time" ) """ if len(import_set) == 0: return '' elif len(import_set) == 1: return 'import "{}"'.format(list(import_set)[0]) else: parts = ['import (\n'] for package in sorted(import_set): parts.append(' "{}"\n'.format(package)) parts.append(')') return ''.join(parts)
bigcode/self-oss-instruct-sc2-concepts
def get_version(fname): """Reads PKG-INFO file generated by setuptools and extracts the Version number.""" res = "UNK" with open(fname, "r") as f: for line in f.readlines(): line = line[:-1] if line.startswith("Version:"): res = line.replace("Version:", "").strip() break if res in ["UNK", ""]: raise ValueError(f"Missing Version number in {fname}") return res
bigcode/self-oss-instruct-sc2-concepts
def to_subscription_key(uid, event): """Build the Subscription primary key for the given guid and event""" return u'{}_{}'.format(uid, event)
bigcode/self-oss-instruct-sc2-concepts
def format_pathname( pathname, max_length): """ Format a pathname :param str pathname: Pathname to format :param int max_length: Maximum length of result pathname (> 3) :return: Formatted pathname :rtype: str :raises ValueError: If *max_length* is not larger than 3 This function formats a pathname so it is not longer than *max_length* characters. The resulting pathname is returned. It does so by replacing characters at the start of the *pathname* with three dots, if necessary. The idea is that the end of the *pathname* is the most important part to be able to identify the file. """ if max_length <= 3: raise ValueError("max length must be larger than 3") if len(pathname) > max_length: pathname = "...{}".format(pathname[-(max_length-3):]) return pathname
bigcode/self-oss-instruct-sc2-concepts
def encode_binary(x, width): """Convert integer x to binary with at least width digits.""" assert isinstance(x, int) xb = bin(x)[2:] if width == 0: assert x == 0 return '' else: assert len(xb) <= width pad = width - len(xb) return '0' * pad + xb
bigcode/self-oss-instruct-sc2-concepts
def dist(pt1, pt2): """Distance between two points""" return ((pt2[0] - pt1[0])**2 + (pt2[1] - pt1[1])**2 + (pt2[2] - pt1[2])**2)**0.5
bigcode/self-oss-instruct-sc2-concepts
def filter_by_bidder_id(bids, bidder_id): """ >>> bids = [ ... {"bidder_id": "1", "amount": 100}, ... {"bidder_id": "1", "amount": 200}, ... {"bidder_id": "2", "amount": 101} ... ] >>> filter_by_bidder_id(bids, "1") [{'amount': 100, 'bidder_id': '1'}, {'amount': 200, 'bidder_id': '1'}] >>> filter_by_bidder_id(bids, "2") [{'amount': 101, 'bidder_id': '2'}] """ return [bid for bid in bids if bid['bidder_id'] == bidder_id]
bigcode/self-oss-instruct-sc2-concepts
def get_distance(pt1, pt2): """ Finds the distance between two points. """ x1 = pt1[0] y1 = pt1[1] x2 = pt2[0] y2 = pt2[1] return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** (1 / 2)
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import Callable def docfill( *args, template: Optional[str] = None, **kwargs ): """Format the decorated function's docstring using given args and kwargs This is useful if some functions share many common inputs or if the range of valid values for a parameter is specified by some global constant. Notes: - If a template string is provided, then args and kwargs are formatted into this string to produce the decorated function's docstring - If no template string is provided and the decorated function's docstring is not None, then this docstring is formatted with the given args and kwargs. Args: args: values to be formatted in docstring as positional arguments, e.g., {0}, {1}, etc. kwargs: values to be formatted in docstring as keyword arguments, e.g, {some_var}, {the_value}, etc. template: string to use as template for decorated function's docstring Examples: >>> @docfill([1, 2, 42], valid_animals={"cat", "dog"}) >>> def func(numbers, animals): >>> \"\"\"This is a function >>> Args: >>> numbers: options are {0} >>> animals: valid choices are {valid_animals} >>> \"\"\" >>> help(func) Help on function func in module __main__: func(numbers, animals) This is a function Args: numbers: options are [1, 2, 42] animals: valid choices are {'dog', 'cat'} """ def decorator(fn: Callable) -> Callable: if template is not None: fn.__doc__ = template if fn.__doc__ is not None: fn.__doc__ = fn.__doc__.format(*args, **kwargs) return fn return decorator
bigcode/self-oss-instruct-sc2-concepts
def app_request_type_label(app, request_type) -> str: """Format a label based on the application name and request type.""" return f"{app}\n({request_type})"
bigcode/self-oss-instruct-sc2-concepts
import torch def scalar_mult(x, y): """A function that does complex scalar multiplication between two complex scalars, x and y. :param x: A complex scalar. (x[0], x[1]) = (real part, imaginary part). :type x: torch.doubleTensor :param y: A complex scalar. (x[0], x[1]) = (real part, imaginary part). :type y: torch.doubleTensor :raises ValueError: If x or y do not have 2 entries (one for the real and imaginary parts each), then this function will not execute. :returns: The product of x and y. :rtype: torch.doubleTensor """ if list(x.size())[0] < 2 or list(y.size())[0] < 2: raise ValueError('An input is not of the right dimension.') z = torch.zeros(2, dtype=torch.double) z[0] = x[0]*y[0] - x[1]*y[1] z[1] = x[0]*y[1] + x[1]*y[0] return z
bigcode/self-oss-instruct-sc2-concepts
def decode_text(value): """ Decode a text-like value for display. Unicode values are returned unchanged. Byte strings will be decoded with a text-safe replacement for unrecognized characters. """ if isinstance(value, bytes): return value.decode('ascii', 'replace') else: return value
bigcode/self-oss-instruct-sc2-concepts
def znes_colors(n=None): """Return dict with ZNES colors. Examples -------- >>> znes_colors().keys() # doctest: +ELLIPSIS dict_keys(['darkblue', 'red', 'lightblue', 'orange', 'grey',... Original author: @ckaldemeyer """ colors = { 'darkblue': '#00395B', 'red': '#B54036', 'lightblue': '#74ADC0', 'orange': '#EC6707', 'grey': '#BFBFBF', 'dimgrey': 'dimgrey', 'lightgrey': 'lightgrey', 'slategrey': 'slategrey', 'darkgrey': '#A9A9A9' } # allow for a dict of n colors if n is not None: if n > len(colors): raise IndexError('Number of requested colors is too big.') else: return {k: colors[k] for k in list(colors)[:n]} else: return colors
bigcode/self-oss-instruct-sc2-concepts
def get_tags_string(tags): """ Returns a comma-delimited k=v string Args: tags (dict): A dictionary of key/value pairs Returns: str """ return ','.join([f'{k}={v}' for k, v in tags.items()])
bigcode/self-oss-instruct-sc2-concepts
def is_dataset(dataset): """ Check if input is a hdf dataset e.g. is_dataset(hdf_group.get(address)) """ return hasattr(dataset, 'size')
bigcode/self-oss-instruct-sc2-concepts
def get_last_completed_launch(fw): """ Given a Firework object returns the last completed launch """ return next((l for l in reversed(fw.archived_launches + fw.launches) if l.state == 'COMPLETED'), None)
bigcode/self-oss-instruct-sc2-concepts
def _check_value(item, allowed_values, item_name=None, extra=None): """ Check the value of a parameter against a list of valid options. Parameters ---------- item : object Item to check. allowed_values : tuple of objects Allowed values to be checked against. item_name : str | None Name of the item to show inside the error message. extra : str | None Extra string to append to the invalid value sentence, e.g. "when using ico mode". Raises ------ ValueError When the value of the item is not one of the valid options. """ if item not in allowed_values: item_name = "" if item_name is None else " '%s'" % item_name extra = "" if extra is None else " " + extra msg = ( "Invalid value for the{item_name} parameter{extra}. " "{options}, but got {item!r} instead." ) allowed_values = tuple(allowed_values) # e.g., if a dict was given if len(allowed_values) == 1: options = "The only allowed value is %s" % repr(allowed_values[0]) elif len(allowed_values) == 2: options = "Allowed values are %s and %s" % ( repr(allowed_values[0]), repr(allowed_values[1]), ) else: options = "Allowed values are " options += ", ".join([f"{repr(v)}" for v in allowed_values[:-1]]) options += f", and {repr(allowed_values[-1])}" raise ValueError( msg.format( item_name=item_name, extra=extra, options=options, item=item ) ) return item
bigcode/self-oss-instruct-sc2-concepts
def play_tictactoe_turn(action, board_state, turn): """ Input: action: 0-8 an index into the board array board_state: (0,1,0,None,None,None,None,None,None) a tuple of the board's state turn: 1/0 the player's who's turn it is Output: a new board state and the next person's turn: (0,1,0,None,None,None,None,None,1) """ board = list(board_state) board[action] = int(turn) turn = not turn new_board_state = tuple(board) return new_board_state, turn
bigcode/self-oss-instruct-sc2-concepts
def filter_startswith_prefix(dataframe, prefix="TALON"): """Filter out rows where 'annot_gene_id' column value starts with prefix. Args: dataframe: pandas DataFrame prefix: string Returns: pandas DataFrame """ not_starts_with_prefix = dataframe["annot_gene_id"].apply( lambda x: not x.startswith(prefix) ) return dataframe[not_starts_with_prefix]
bigcode/self-oss-instruct-sc2-concepts
def int_to_varint_hex(int_value): """ VARINT <= 0xfc example: 12 <= 0xffff example: fd1234 Prefix is fd and the next 2 bytes are the VarInt (in little-endian). <= 0xffffffff example: fe12345678 Prefix is fe and the next 4 bytes are the VarInt (in little-endian). <= 0xffffffffffffffff example: ff1234567890abcdef Prefix is ff and the next 8 bytes are the VarInt (in little-endian). :param int_value: integer value which we want to convert to hex format varint :return: varint hex string in little-endian """ if int_value <= 0xfc: return hex(int_value)[2:] elif int_value <= 0xffff: return 'fd' + int_value.to_bytes(2, byteorder='little').hex() elif int_value <= 0xffffffff: return 'fe' + int_value.to_bytes(4, byteorder='little').hex() elif int_value <= 0xffffffffffffffff: return 'ff' + int_value.to_bytes(8, byteorder='little').hex() else: raise Exception('Too big varint: {}'.format(int_value))
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import List def validate_entry_context(entry_context: Any, keys: List[str], unpack_nested_elements: bool): """ Validate entry context structure is valid, should be: - For unpack_nested_elements==False: 1. List[Dict[str, str/bool/int/float]] 2. List[str/bool/int/float] 3. Dict[str, str/bool/int/float] - for developer it will be in first index of a list. - For unpack_nested_elements==True: 1. Dict[str, Any] Args: entry_context: Entry context to validate keys: keys to collect data from unpack_nested_elements: True for unpacking nested elements, False otherwise. Raises: ValueError: If structure is not valid. data_type (str): The type of information in the context path. """ exception_msg = "When unpack_nested_elements argument is set to True, the context object for the path should be " \ "of type dict" if unpack_nested_elements: if not isinstance(entry_context, dict): raise ValueError(exception_msg) else: return exception_msg = "The context object for the specified path should be of one of the following types:" \ " dict[str,str] or list[dict[str,str]] or List[str/bool/int/float]" if not isinstance(entry_context, (list, dict)): raise ValueError(exception_msg) data_type = 'dicts' if isinstance(entry_context, dict): return data_type has_seen_dict = False for item in entry_context: if not isinstance(item, dict): if not has_seen_dict: break else: raise ValueError(exception_msg) has_seen_dict = True for key, value in item.items(): if key in keys: if not isinstance(value, (str, int, float, bool)): raise ValueError(exception_msg) if not has_seen_dict: data_type = 'list' for item in entry_context: if not isinstance(item, (str, int, float, bool)): raise ValueError(exception_msg) return data_type
bigcode/self-oss-instruct-sc2-concepts
def progessbar(new, tot): """Builds progressbar Args: new: current progress tot: total length of the download Returns: progressbar as a string of length 20 """ length = 20 progress = int(round(length * new / float(tot))) percent = round(new/float(tot) * 100.0, 1) bar = '=' * progress + '-' * (length - progress) return '[%s] %s %s\r' % (bar, percent, '%')
bigcode/self-oss-instruct-sc2-concepts
def p1_for(input_list): """Compute some of numbers in list with for loop.""" out = 0 for i in input_list: out += i return out
bigcode/self-oss-instruct-sc2-concepts
def precision(c, tweets): """Computes precision for class `c` on the specified test data.""" tp = 0 fp = 0 for tweet in tweets: if c in tweet['predictions']: if c in tweet['tags']: tp+=1 else: fp+=1 if(tp+fp == 0): return float('nan') else: return tp/(tp+fp)
bigcode/self-oss-instruct-sc2-concepts
def getBondedNeighborLists(atoms, bondProxies): """ Helper function to produce a dictionary of lists that contain all bonded neighbors for each atom in a set of atoms. :param atoms: Flex array of atoms (could be obtained using model.get_atoms() if there are no chains with multiple conformations, must be a subset of the atoms including all in the base conformation and in a particular conformation otherwise). :param bondProxies: Flex array of bond proxies for the atoms. This could be obtained using model.get_restraints_manager().geometry.get_all_bond_proxies(sites_cart = model.get_sites_cart())[0] if the model has only a single conformation. Otherwise, it should be a flex array of atom positions for the atoms that are in the first argument. :returns a dictionary with one entry for each atom that contains a list of all of the atoms (within the atoms list) that are bonded to it. """ atomDict = {} for a in atoms: atomDict[a.i_seq] = a bondedNeighbors = {} for a in atoms: bondedNeighbors[a] = [] for bp in bondProxies: try: first = atomDict[bp.i_seqs[0]] second = atomDict[bp.i_seqs[1]] bondedNeighbors[first].append(second) bondedNeighbors[second].append(first) except Exception: # When an atom is bonded to an atom in a different conformer (not in our atom list) # we just ignore it. pass return bondedNeighbors
bigcode/self-oss-instruct-sc2-concepts
def format_fasta(title, sequence): """ This formats a fasta sequence Input: title - String - Title of the sequence sequence - String - Actual sequence Output: String - Fully formatted fasta sequence """ fasta_width = 70 # Number of characters in one line n_lines = 1 + len(sequence) // fasta_width # Number of lines lines = [ sequence[i*fasta_width: (i+1)*fasta_width] for i in range(n_lines)] lines = "\n".join(lines) formatted = f"> {title}\n{lines}\n\n" return formatted
bigcode/self-oss-instruct-sc2-concepts
def vecBetweenBoxes(obj1, obj2): """A distance function between two TextBoxes. Consider the bounding rectangle for obj1 and obj2. Return vector between 2 boxes boundaries if they don't overlap, otherwise returns vector betweeen boxes centers +------+..........+ (x1, y1) | obj1 | : +------+www+------+ : | obj2 | (x0, y0) +..........+------+ """ (x0, y0) = (min(obj1.x0, obj2.x0), min(obj1.y0, obj2.y0)) (x1, y1) = (max(obj1.x1, obj2.x1), max(obj1.y1, obj2.y1)) (ow, oh) = (x1-x0, y1-y0) (iw, ih) = (ow-obj1.width-obj2.width, oh-obj1.height-obj2.height) if iw<0 and ih<0: # if one is inside another we compute euclidean distance (xc1, yc1) = ( (obj1.x0+obj1.x1)/2, (obj1.y0+obj1.y1)/2 ) (xc2, yc2) = ( (obj2.x0+obj2.x1)/2, (obj2.y0+obj2.y1)/2 ) return (xc1-xc2, yc1-yc2) else: return (max(0, iw), max(0, ih))
bigcode/self-oss-instruct-sc2-concepts
def clip(string: str, length: int, suffix = "...") -> str: """Clip string to max length If input `string` has less than `length` characters, then return the original string. If `length` is less than the number of charecters in `suffix`, then return `string` truncated to `length`. Otherwise returns truncated string with suffix appended, such that the resulting string has `length` characters. Args: string (str): String to clip length (int): Max chars in output string suffix (str, optional): String appended to output if original string is clipped. Defaults to "...". Returns: str: Clipped string """ if len(string) <= length: return string if length < len(suffix): return string[:length] return string[:length - len(suffix)] + suffix
bigcode/self-oss-instruct-sc2-concepts
def normalize(string): """Returns a string without outer quotes or whitespace.""" return string.strip("'\" ")
bigcode/self-oss-instruct-sc2-concepts
import ast def is_ast_equal(node_a: ast.AST, node_b: ast.AST) -> bool: """ Compare two ast tree using ast dump """ return ast.dump(node_a) == ast.dump(node_b)
bigcode/self-oss-instruct-sc2-concepts
def decode_text_field(buf): """ Convert char[] string in buffer to python str object :param buf: bytearray with array of chars :return: string """ return buf.decode().strip(b'\x00'.decode())
bigcode/self-oss-instruct-sc2-concepts
def is_prime(number): """Check if a number is prime.""" if number < 2: return False if number == 2: return True if number % 2 == 0: return False for _ in range(3, int(number ** 0.5) + 1, 2): if number % _ == 0: return False return True
bigcode/self-oss-instruct-sc2-concepts
import torch def subtract_pose(pose_a, pose_b): """ Compute pose of pose_b in the egocentric coordinate frame of pose_a. Inputs: pose_a - (bs, 3) --- (x, y, theta) pose_b - (bs, 3) --- (x, y, theta) Conventions: The origin is at the center of the map. X is upward with agent's forward direction Y is rightward with agent's rightward direction """ x_a, y_a, theta_a = torch.unbind(pose_a, dim=1) x_b, y_b, theta_b = torch.unbind(pose_b, dim=1) r_ab = torch.sqrt((x_a - x_b) ** 2 + (y_a - y_b) ** 2) # (bs, ) phi_ab = torch.atan2(y_b - y_a, x_b - x_a) - theta_a # (bs, ) theta_ab = theta_b - theta_a # (bs, ) theta_ab = torch.atan2(torch.sin(theta_ab), torch.cos(theta_ab)) x_ab = torch.stack( [r_ab * torch.cos(phi_ab), r_ab * torch.sin(phi_ab), theta_ab,], dim=1 ) # (bs, 3) return x_ab
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def setup(opts): """Set up directory for this GenomeHubs instance and handle reset.""" Path(opts["hub-path"]).mkdir(parents=True, exist_ok=True) return True
bigcode/self-oss-instruct-sc2-concepts
def accuracy(true_positives, true_negatives, false_positives, false_negatives, description=None): """Returns the accuracy, calculated as: (true_positives+true_negatives)/(true_positives+false_positives+true_negatives+false_negatives) """ true_positives = float(true_positives) true_negatives = float(true_negatives) false_positives = float(false_positives) false_negatives = float(false_negatives) if (true_positives + true_negatives + false_positives + false_negatives) < 1e-15: return 0.0 return (true_positives+true_negatives)/(true_positives+false_positives+true_negatives+false_negatives)
bigcode/self-oss-instruct-sc2-concepts
def rate_color(rate: int, units: str = '') -> str: """ Get color schema for percentage value. Color schema looks like red-yellow-green scale for values 0-50-100. """ color = '[red]' if 30 > rate > 20: color = '[orange_red1]' if 50 > rate > 30: color = '[dark_orange]' if 70 > rate > 50: color = '[orange1]' if 90 > rate > 70: color = '[yellow4]' if rate >= 90: color = '[green1]' return f'{color}{rate}{units}[/]'
bigcode/self-oss-instruct-sc2-concepts
import time def get_duration_timestamp(day=7): """ 获取当前时间和7天前的时间戳 :param day: :return: """ # 当前时间对应的时间戳 end = int(round(time.time() * 1000)) # 7天前的时间戳 start = end - day * 24 * 60 * 60 * 1000 return start, end
bigcode/self-oss-instruct-sc2-concepts
def pass_through_filter(cloud, filter_axis='z', axis_limit=(0.6, 1.1)): """ Cut off filter Params: cloud: pcl.PCLPointCloud2 filter_axis: 'z'|'y'|'x' axis axis_limit: range Returns: filtered cloud: pcl.PCLPointCloud2 """ # Create a PassThrough filter object. passthrough = cloud.make_passthrough_filter() # Assign axis and range to the passthrough filter object. passthrough.set_filter_field_name(filter_axis) passthrough.set_filter_limits(axis_limit[0], axis_limit[1]) return passthrough.filter()
bigcode/self-oss-instruct-sc2-concepts
def clean_text_up(text: str) -> str: """ Remove duplicate spaces from str and strip it. """ return ' '.join(text.split()).strip()
bigcode/self-oss-instruct-sc2-concepts
def case_convert(snakecase_string: str) -> str: """Converts snake case string to pascal string Args: snakecase_string (str): snakecase string Returns: str: Pascal string """ return snakecase_string.replace("_", " ").title().replace("Cnn", "CNN")
bigcode/self-oss-instruct-sc2-concepts