seed
stringlengths
1
14k
source
stringclasses
2 values
import time def get_range_query_args_from_duration(duration_secs=240): """Get start and end time for a duration of the last duration_secs.""" return (int(time.time()) - duration_secs, int(time.time()))
bigcode/self-oss-instruct-sc2-concepts
def search_non_residue(p): """Find a non residue of p between 2 and p Args: p: a prime number Returns: a integer that is not a quadratic residue of p or -1 if no such number exists """ for z in range(2, p): if pow(z, (p - 1) // 2, p) == p - 1: return z return -1
bigcode/self-oss-instruct-sc2-concepts
def unique_list(obj, key=None): """ Remove same element from list :param obj: list :param key: key function :return: list """ checked = [] seen = set() for e in obj: _e = key(e) if key else e if _e not in seen: checked.append(e) seen.add(_e) return checked
bigcode/self-oss-instruct-sc2-concepts
def get_function_input(function): """ Return a with the single input that is documented using api.decoratos.input """ parameters = [] if hasattr(function, 'doc_input'): (description, return_type, required) = function.doc_input parameters.append({ 'name': 'body', 'description': description, 'type': return_type, 'paramType': 'body', 'required': bool(required) }) return parameters
bigcode/self-oss-instruct-sc2-concepts
def same_orientation(lineA, lineB): """Return whether two paired end reads are of the same orientation.""" # SAM flags reverse = 16 mate_reverse = 32 flagA = int(lineA.split()[11]) flagB = int(lineB.split()[11]) return ((flagA & reverse) == (flagB & reverse) and (flagA & mate_reverse) == (flagB & mate_reverse))
bigcode/self-oss-instruct-sc2-concepts
def latest_lines(lines, last): """Return lines after last and not empty >>> latest_lines(['a', 'b', '', 'c', '', 'd'], 1) 6, ['c', 'd'] """ last_lnum = len(lines) latest = [l for n, l in enumerate(lines, 1) if n > last and l.strip()] return last_lnum, latest
bigcode/self-oss-instruct-sc2-concepts
def gradient_t(prev_image, image): """Find gradient along time: time derivative using two images Arguments: prev_image {tensor} -- image at timestamp 1 image {tensor} -- image at timestamp 2 Returns: tensor -- time derivative of image """ return prev_image-image
bigcode/self-oss-instruct-sc2-concepts
def _indentation(line): """Returns the length of the line's leading whitespace, treating tab stops as being spaced 8 characters apart.""" line = line.expandtabs() return len(line) - len(line.lstrip())
bigcode/self-oss-instruct-sc2-concepts
def sum_fuel_across_sectors(fuels): """Sum fuel across sectors of an enduse if multiple sectors. Otherwise return unchanged `fuels` Arguments --------- fuels : dict or np.array Fuels of an enduse either for sectors or already aggregated Returns ------- sum_array : np.array Sum of fuels of all sectors """ if isinstance(fuels, dict): sum_array = sum(fuels.values()) return sum_array else: return fuels
bigcode/self-oss-instruct-sc2-concepts
import itertools def element_ancestry(element): """Iterates element plus element.parents.""" return itertools.chain((element,), element.parents)
bigcode/self-oss-instruct-sc2-concepts
def dasherize(word: str) -> str: """Replace underscores with dashes in the string. Example:: >>> dasherize("foo_bar") "foo-bar" Args: word (str): input word Returns: input word with underscores replaced by dashes """ return word.replace("_", "-")
bigcode/self-oss-instruct-sc2-concepts
def log2floor(n): """ Returns the exact value of floor(log2(n)). No floating point calculations are used. Requires positive integer type. """ assert n > 0 return n.bit_length() - 1
bigcode/self-oss-instruct-sc2-concepts
def standardize(X): """ Standardize data set by mean and standard deviation """ mu = X.mean(axis=0, keepdims=True) s = X.std(axis=0, keepdims=True) return (X-mu)/s
bigcode/self-oss-instruct-sc2-concepts
def detection_center(detection): """Computes the center x, y coordinates of the object""" #print(detection) bbox = detection['bbox'] center_x = (bbox[0] + bbox[2]) / 2.0 - 0.5 center_y = (bbox[1] + bbox[3]) / 2.0 - 0.5 return (center_x, center_y)
bigcode/self-oss-instruct-sc2-concepts
import requests def get_countries_names() -> list: """ Function for getting list of all countries names procived by public COVID-19 api on site "https://api.covid19api.com" Returns ------- List with all countries names. Example ------- >>> countries_names = get_countries_names() """ countries_names = [] url = "https://api.covid19api.com/countries" payload = {} headers = {} response = requests.request("GET", url, headers=headers, data=payload) for element in response.json(): countries_names.append(element['Slug']) return countries_names
bigcode/self-oss-instruct-sc2-concepts
def overlaps(pattern_a, pattern_b): """Returns a boolean indicating if two patterns are overlapped. Args: pattern_a: SimilarPattern or TimeSpan. pattern_b: SimilarPattern or TimeSpan. Returns: boolean indicating if the patterns are overlapped. """ start_a = pattern_a.start_time start_b = pattern_b.start_time end_a = pattern_a.start_time + pattern_a.duration end_b = pattern_b.start_time + pattern_b.duration a_falls_in_b = start_b < end_a and end_a < end_b b_falls_in_a = start_a < end_b and end_b < end_a return a_falls_in_b or b_falls_in_a
bigcode/self-oss-instruct-sc2-concepts
def distance_residues(r1, r2): """Return the distance between two residues.""" center_1 = r1.get_mass_center() center_2 = r2.get_mass_center() return (sum(map(lambda t: (t[0] - t[1])**2, zip(center_1, center_2))))**0.5
bigcode/self-oss-instruct-sc2-concepts
def max_weighted_independent_set_in_path_graph(weights): """ Computes the independent set with maximum total weight for a path graph. A path graph has all vertices are connected in a single path, without cycles. An independent set of vertices is a subset of the graph vertices such that no two vertices are adjacent in the path graph. Complexity: O(n); Space: O(n) Args: weights: list, of vertex weights in the order they are present in the graph. Returns: list, format [max_weight: int, vertices: list] """ # 0. Initialization: A[i] - max total weight of the independent set for # the first i vertices in the graph. a = [0] * (len(weights)+1) a[0] = 0 # Max weight for empty graph. a[1] = weights[0] # Max weight for the graph with only the first weight. # 1. Compute the max total weight possible for any independent set. for i in range(2, len(weights)+1): a[i] = max(a[i-1], a[i-2]+weights[i-1]) max_weight = a[len(weights)] # 2. Trace back from the solution through the subproblems to compute the # vertices in the independent set. vertices = [] i = len(weights) while (i>0): if a[i-2] + weights[i-1] >= a[i-1]: vertices.insert(0, weights[i-1]) i -= 2 else: i -= 1 return [max_weight, vertices]
bigcode/self-oss-instruct-sc2-concepts
def select_with_processing(selector, cluster_sim): """A selection wrapper that uses the given operator to select from the union of the population and the currently processing individuals. """ def select(population): return selector(population + cluster_sim.processing) return select
bigcode/self-oss-instruct-sc2-concepts
def get_si(simpos): """ Get SI corresponding to the given SIM position. """ if ((simpos >= 82109) and (simpos <= 104839)): si = 'ACIS-I' elif ((simpos >= 70736) and (simpos <= 82108)): si = 'ACIS-S' elif ((simpos >= -86147) and (simpos <= -20000)): si = ' HRC-I' elif ((simpos >= -104362) and (simpos <= -86148)): si = ' HRC-S' else: si = ' NONE' return si
bigcode/self-oss-instruct-sc2-concepts
import json def get_parameters(template): """ Builds a dict of parameters from a workflow manifest. Parameters ---------- template : dict Returns ------- dict Parameters. """ parameters = {} prefix = "PARAMETER_" for var in template["container"]["env"]: name = var["name"] value = var.get("value") if name.startswith(prefix): name = name[len(prefix):] if value is not None: value = json.loads(value) parameters[name] = value return parameters
bigcode/self-oss-instruct-sc2-concepts
def create_index_of_A_matrix(db): """ Create a dictionary with row/column indices of the A matrix as key and a tuple (activity name, reference product, unit, location) as value. :return: a dictionary to map indices to activities :rtype: dict """ return { ( db[i]["name"], db[i]["reference product"], db[i]["unit"], db[i]["location"], ): i for i in range(0, len(db)) }
bigcode/self-oss-instruct-sc2-concepts
import io def decode_int8(fh: io.BytesIO) -> int: """ Read a single byte as an unsigned integer. This data type isn't given a special name like "ITF-8" or "int32" in the spec, and is only used twice in the file descriptor as a special case, and as a convenience to construct other data types, like ITF-8 and LTF-8. """ return int.from_bytes(fh.read(1), byteorder='little', signed=False)
bigcode/self-oss-instruct-sc2-concepts
def full_qualified(pkg, symbols): """ パッケージ名と、文字列表記されたシンボルのリスト(このEus_pkgクラスと対応するEuslispのパッケージ以外のシンボルが含まれていても良い)を受け取る。 対応するパッケージ内のシンボルのみを取り出し、それぞれパッケージ接頭語(大文字)をつけ、リストにして返す。 >>> full_qualified("TEST", ['var1', 'OTHER-PACK::var2', 'LISP::var3']) ['TEST::var1', 'LISP::var3'] Args: pkg (str): パッケージ名。大文字表記でprefixなしのもの。 symbols (list): 文字列表記されたシンボルのリスト。パッケージ名は小文字表記でも大文字表記で登録されていても良い。(['test::tmp']でも、['TEST::tmp']でも可) Returns: result (list): 文字列表記されたシンボルのリスト。 """ result = [] for symbol in symbols: if '::' in symbol: pkg_of_symbol , suffix_of_symbol = symbol.split('::') # ここは'user'や'test'といった小文字表記で返ってくることがほとんど pkg_of_symbol = pkg_of_symbol.upper() symbol = pkg_of_symbol + '::' + suffix_of_symbol elif ':' in symbol: pkg_of_symbol , suffix_of_symbol = symbol.split(':') # ここは'compiler'といった小文字表記がほとんどだろう。compiler:identifierはCOMPILER:identifierなるシンボルになる pkg_of_symbol = pkg_of_symbol.upper() symbol = pkg_of_symbol + ':' + suffix_of_symbol else: pkg_of_symbol = pkg symbol = pkg_of_symbol + '::' + symbol # LISP packageの組み込み関数などはパッケージ接頭語なしに使えるようになっている。この特定のパッケージ内からもあたかもパッケージ内の関数かのように使えるようにする。 if pkg_of_symbol == pkg or pkg_of_symbol == "LISP": result.append(symbol) # cls_pkg(大文字) + '::' or ':' + cls_name return result
bigcode/self-oss-instruct-sc2-concepts
import pickle def LoadModel(filname): """ Load a model using pickle Parameters ---------- filname : str model file name. Returns ------- model : dict Output of BuildModel methode, a dict with: -"model" an sklearn trained random forest classifier. -"features" the list of the model features. """ model = pickle.load(open(filname, 'rb')) return model
bigcode/self-oss-instruct-sc2-concepts
import ctypes def _malloc_char_array(n): """ Return a pointer to allocated UTF8 (C char) array of length `n'. """ t = ctypes.c_char * n return t()
bigcode/self-oss-instruct-sc2-concepts
def configure_camera_url(camera_address: str, camera_username: str = 'admin', camera_password: str = 'iamironman', camera_port: int = 554, camera_stream_address: str = 'H.264', camera_protocol: str = 'rtsp') -> str: """Configure camera url for testing.""" return (f'{camera_protocol}://{camera_username}:{camera_password}@' f'{camera_address}:{camera_port}/{camera_stream_address}')
bigcode/self-oss-instruct-sc2-concepts
def filer_elements(elements, element_filter): """Filter elements. Ex.: If filtered on elements [' '], ['a', ' ', 'c'] becomes ['a', 'c'] """ return [element for element in elements if element not in element_filter]
bigcode/self-oss-instruct-sc2-concepts
def any_true_p (seq, pred) : """Returns first element of `seq` for which `pred` returns True, otherwise returns False. """ for e in seq : if pred (e) : return e else : return False
bigcode/self-oss-instruct-sc2-concepts
def _resize(im, width, height): """ Resizes the image to fit within the specified height and width; aspect ratio is preserved. Images always preserve animation and might even result in a better-optimized animated gif. """ # resize only if we need to; return None if we don't if im.size.width > width or im.size.height > height: im = im.resized(im.size.fit_inside((width, height))) return im
bigcode/self-oss-instruct-sc2-concepts
def valid(x, y, n, m): """Check if the coordinates are in bounds. :param x: :param y: :param n: :param m: :return: """ return 0 <= x < n and 0 <= y < m
bigcode/self-oss-instruct-sc2-concepts
def _is_control_defined(node, point_id): """ Checks if control should be created on specified point id Args: name (str): Name of a control point_id (int): Skeleton point number Returns: (bool) """ node_pt = node.geometry().iterPoints()[point_id] shape_name = node_pt.stringAttribValue('shape_name') return True if shape_name != '' else False
bigcode/self-oss-instruct-sc2-concepts
def levelFromHtmid(htmid): """ Find the level of a trixel from its htmid. The level indicates how refined the triangular mesh is. There are 8*4**(d-1) triangles in a mesh of level=d (equation 2.5 of Szalay A. et al. (2007) "Indexing the Sphere with the Hierarchical Triangular Mesh" arXiv:cs/0701164) Note: valid htmids have 4+2n bits with a leading bit of 1 """ htmid_copy = htmid i_level = 1 while htmid_copy > 15: htmid_copy >>= 2 i_level += 1 if htmid_copy < 8: raise RuntimeError('\n%d is not a valid htmid.\n' % htmid + 'Valid htmids will have 4+2n bits\n' + 'with a leading bit of 1\n') return i_level
bigcode/self-oss-instruct-sc2-concepts
import pprint def fargs(*args, **kwargs): """ Format `*args` and `**kwargs` into one string resembling the original call. >>> fargs(1, [2], x=3.0, y='four') "1, [2], x=3.0, y='four'" .. note:: The items of `**kwargs` are sorted by their key. """ items = [] for arg in args: items.append(pprint.pformat(arg)) for kw in sorted(kwargs): items.append(kw + "=" + pprint.pformat(kwargs[kw])) return ", ".join(items)
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from pathlib import Path def operating_system() -> Tuple[str, str]: """Return what operating system we are running. Returns: A tuple with two strings, the first with the operating system and the second is the version. Examples: ``('ubuntu', '20.04')``, ``('centos', '7')``. """ os_release = Path("/etc/os-release").read_text().split("\n") os_release_ctxt = {k: v.strip("\"") for k, v in [item.split("=") for item in os_release if item != '']} id_ = os_release_ctxt["ID"] version = os_release_ctxt.get("VERSION_ID", "") return (id_, version)
bigcode/self-oss-instruct-sc2-concepts
def get_max_key(d): """Return the key from the dict with the max value.""" return max(d, key=d.get)
bigcode/self-oss-instruct-sc2-concepts
def generate_sample(id, name, controlled_metadata, user_metadata, source_meta): """ Create a sample record """ sample = { 'node_tree': [{ "id": id, "type": "BioReplicate", "meta_controlled": controlled_metadata, "meta_user": user_metadata, 'source_meta': source_meta }], 'name': name, } return sample
bigcode/self-oss-instruct-sc2-concepts
def readline_comment(file, symbol='#'): """Reads line from a file object, but ignores everything after the comment symbol (by default '#')""" line = file.readline() if not line: return '' result = line.partition(symbol)[0] return result if result else readline_comment(file)
bigcode/self-oss-instruct-sc2-concepts
import re def collect_subroutine_calls(lines,ifbranch_lines): """ Collect a dictionary of all subroutine call instances. In the source code on entry the "subroutine call" is given in the form of a function call, e.g. t5 = nwxc_c_Mpbe(rhoa,0.0d+0,gammaaa,0.0d+0,0.0d+0) we need to know the "nwxc_c_Mpbe(rhoa,0.0d+0,gammaaa,0.0d+0,0.0d+0)" part. The key in the dictionary is going to be the variable name (i.e. "t5") as we will have to replace those variable instances with an array element reference. The resulting dictionary is returned. """ (lineno_start,lineno_end) = ifbranch_lines dict = {} pattern = re.compile("nwxc") line = lineno_start while line <= lineno_end: if pattern.search(lines[line]): aline = lines[line] aline = aline.split(" = ") key = aline[0].lstrip() dict[key] = aline[1] line += 1 return dict
bigcode/self-oss-instruct-sc2-concepts
import xxhash def get_hash(fname: str) -> str: """ Get xxHash3 of a file Args: fname (str): Path to file Returns: str: xxHash3 of file """ xxh = xxhash.xxh3_64() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): xxh.update(chunk) return xxh.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def split_dataset_sizes(stream_list, split_sizes): """Splits with different sizes Args: stream_list (list): list of stream path split_sizes (list): batch size per worker """ out = [] start = 0 total = sum(split_sizes) for split_size in split_sizes[:-1]: num = int(split_size / total * len(stream_list)) end = start + num out.append(stream_list[start:end]) start = end out.append(stream_list[start:]) return out
bigcode/self-oss-instruct-sc2-concepts
def all_nums(table): """ Returns True if table contains only numbers (False otherwise) Example: all_nums([[1,2],[3,4]]) is True all_nums([[1,2],[3,'a']]) is False Parameter table: The candidate table to modify Preconditions: table is a rectangular 2d List """ result = True # Walk through table for row in table: # Walk through the row for item in row: if not type(item) in [int,float]: result = False return result
bigcode/self-oss-instruct-sc2-concepts
def _itemNames(comb): """ Item names from result of knapsack01 Args: comb tuple of tuples result of knapsack01 Returns: tuple sorted item ids """ return tuple(sorted(item for item,_,_ in comb))
bigcode/self-oss-instruct-sc2-concepts
def split_def_command(command): """Split command in parts: variable name, specific command, definition. Return None if command is invalid. """ # procedo per casi # il che significa che dopo un '@' non posso usare un ':' # perché verrebbe intercettato per primo! valid_commands = [":", "@"] specific_command = "--invalid--" for comm_char in valid_commands: comm_pos = command.find(comm_char) if comm_pos > -1: specific_command = comm_char break if "--invalid--" == specific_command: return None return command.partition(specific_command)
bigcode/self-oss-instruct-sc2-concepts
def get_ingredients(drink_dict): """ Create a list of ingredients and measures Form data is passed as a dictionary. The functions iterates through the key/value pairs and appends the ingredients and measures to its own list called ingredients. Args: drink_dict : The dictionary containing the ingredients Returns: A list of alternating measures and ingredients """ ingredients = [] for k, v in list(drink_dict.items()): if ('ingredient' in k) or ('measure' in k): ingredients.append(v) drink_dict.pop(k) return ingredients
bigcode/self-oss-instruct-sc2-concepts
def linear (x, parameters): """Sigmoid function POI = a + (b * x ) Parameters ---------- x: float or array of floats variable parameters: dict dictionary containing 'linear_a', and 'linear_b' Returns ------- float or array of floats: function result """ a = parameters['linear_a'] b = parameters['linear_b'] return a + (b * x)
bigcode/self-oss-instruct-sc2-concepts
def rax_clb_node_to_dict(obj): """Function to convert a CLB Node object to a dict""" if not obj: return {} node = obj.to_dict() node['id'] = obj.id node['weight'] = obj.weight return node
bigcode/self-oss-instruct-sc2-concepts
from typing import List import random def unique_floats_sum_to_one(num: int) -> List[float]: """return a list of unique floats summing up to 1""" random_ints = random.sample(range(1, 100), k=num) total = sum(random_ints) return [(n / total) for n in random_ints]
bigcode/self-oss-instruct-sc2-concepts
def get_timeouts(builder_cfg): """Some builders require longer than the default timeouts. Returns tuple of (expiration, hard_timeout). If those values are None then default timeouts should be used. """ expiration = None hard_timeout = None if 'Valgrind' in builder_cfg.get('extra_config', ''): expiration = 24*60*60 hard_timeout = 7*60*60 return expiration, hard_timeout
bigcode/self-oss-instruct-sc2-concepts
import torch def _skip(x, mask): """ Getting sliced (dim=0) tensor by mask. Supporting tensor and list/dict of tensors. """ if isinstance(x, int): return x if x is None: return None if isinstance(x, torch.Tensor): if x.size(0) == mask.size(0): return x[mask] elif x.size(1) == mask.size(0): return x[:, mask] if isinstance(x, list): return [_skip(x_i, mask) for x_i in x] if isinstance(x, dict): return {k: _skip(v, mask) for k, v in x.items()} raise NotImplementedError
bigcode/self-oss-instruct-sc2-concepts
def _get_zip_filename(xml_sps, output_filename=None): """ Obtém o nome canônico de um arquivo ZIP a partir de `xml_sps: packtools.sps.models.sps_package.SPS_Package`. Parameters ---------- xml_sps : packtools.sps.models.sps_package.SPS_Package output_filename: nome do arquivo zip Returns ------- str "1414-431X-bjmbr-54-10-e11439.zip" """ if not output_filename: return f'{xml_sps.package_name}.zip' else: return output_filename
bigcode/self-oss-instruct-sc2-concepts
def asic_cmd(asic, cmd, module_ignore_errors=False): """ Runs a command in the appropriate namespace for an ASIC. Args: asic: Instance of SonicAsic to run a command. cmd: Command string to execute. module_ignore_errors: Flag to pass along to ansible to ignore any execution errors. Returns: The output of the SonicHost.command() execution. """ if asic.namespace is not None: fullcmd = "sudo ip netns exec {} {}".format(asic.namespace, cmd) return asic.sonichost.command(fullcmd, module_ignore_errors=module_ignore_errors) else: return asic.sonichost.command(cmd, module_ignore_errors=module_ignore_errors)
bigcode/self-oss-instruct-sc2-concepts
import configparser def _config_ini(path): """ Parse an ini file :param path: The path to a file to parse :type file: str :returns: Configuration contained in path :rtype: Dict """ conf = configparser.ConfigParser() conf.read(path) return dict(conf)
bigcode/self-oss-instruct-sc2-concepts
def read_messages_count(path, repeat_every): """ Count the predictions given so far (may be used in case of retraining) """ file_list=list(path.iterdir()) nfiles = len(file_list) if nfiles==0: return 0 else: return ((nfiles-1)*repeat_every) + len(file_list[-1].open().readlines())
bigcode/self-oss-instruct-sc2-concepts
import math def percent(n, precision=0): """ Converts `n` to an appropriately-precise percentage. """ # 'or 1' prevents a domain error if n == 0 (i.e., 0%) places = precision - math.floor(math.log10(abs(n) or 1)) return '{0:.{1}%}'.format(n, places)
bigcode/self-oss-instruct-sc2-concepts
def Focal_length_eff(info_dict): """ Computes the effective focal length give the plate scale and the pixel size. Parameters ---------- info_dict: dictionary Returns --------- F_eff: float effective focal length in m """ # F_eff = 1./ (info_dict['pixelScale'] * # np.pi/(3600*180) / info_dict['pixelSize']) if isinstance(info_dict["focal_length"], dict): info_dict["foc_len"] = info_dict["focal_length"][info_dict["channel"]] else: info_dict["foc_len"] = info_dict["focal_length"] return info_dict
bigcode/self-oss-instruct-sc2-concepts
def irb_decay_to_gate_infidelity(irb_decay, rb_decay, dim): """ Eq. 4 of [IRB], which provides an estimate of the infidelity of the interleaved gate, given both the observed interleaved and standard decay parameters. :param irb_decay: Observed decay parameter in irb experiment with desired gate interleaved between Cliffords :param rb_decay: Observed decay parameter in standard rb experiment. :param dim: Dimension of the Hilbert space, 2**num_qubits :return: Estimated gate infidelity (1 - fidelity) of the interleaved gate. """ return ((dim - 1) / dim) * (1 - irb_decay / rb_decay)
bigcode/self-oss-instruct-sc2-concepts
def jaccard(words_1, words_2): """words_1 และ words_2 เป็นลิสต์ของคำต่าง ๆ (ไม่มีคำซ้ำใน words_1 และ ไม่มีคำซ้ำใน words_2) ต้องทำ: ตั้งตัวแปร jaccard_coef ให้มีค่าเท่ากับ Jaccard similarity coefficient ที่คำนวณจากค่าใน words_1 และ words_2 ตามสูตรที่แสดงไว้ก่อนนี้ Doctest : >>> words_1 = ['x', 'y', 'z', 'xyz'] >>> words_2 = ['y', 'x', 'w'] >>> jaccard(words_1,words_2) 0.4 """ # Check intersect in_other = 0 for i in words_1: if i in words_2: in_other += 1 # Make list of total member in both list both_list = [] for i in words_1: if i not in both_list: both_list.append(i) for i in words_2: if i not in both_list: both_list.append(i) jaccard_coef = in_other / len(both_list) return jaccard_coef
bigcode/self-oss-instruct-sc2-concepts
import json def get_rev_list_kwargs(opt_list): """ Converts the list of 'key=value' options to dict. Options without value gets True as a value. """ result = {} for opt in opt_list: opt_split = opt.split(sep="=", maxsplit=1) if len(opt_split) == 1: result[opt] = True else: key, raw_val = opt_split try: val = json.loads(raw_val.lower()) result[key] = val except json.JSONDecodeError: result[key] = raw_val return result
bigcode/self-oss-instruct-sc2-concepts
def collectReviewTeams(reviewers): """collectReviewTeams(reviewers) -> dictionary Takes a dictionary as returned by getReviewersAndWatchers() or getPendingReviewers() and transform into a dictionary mapping sets of users to sets of files that those groups of users share review responsibilities for. The same user may appear in number of sets, as may the same file. If None appears as a key in the returned dictionary, the set of files it is mapped to have changes in them with no assigned reviewers.""" teams = {} for file_id, file_reviewers in reviewers.items(): if None in file_reviewers: teams.setdefault(None, set()).add(file_id) team = frozenset(filter(None, file_reviewers.keys())) if team: teams.setdefault(team, set()).add(file_id) return teams
bigcode/self-oss-instruct-sc2-concepts
def int_to_lower_mask(mask): """ Convert an integer into a lower mask in IPv4 string format where the first mask bits are 0 and all remaining bits are 1 (e.g. 8 -> 0.255.255.255) :param mask: mask as integer, 0 <= mask <= 32 :return: IPv4 string representing a lower mask corresponding to mask """ return '.'.join([str((0xffffffff >> mask >> i) & 0xff) for i in [24, 16, 8, 0]])
bigcode/self-oss-instruct-sc2-concepts
def zero_fill(value: bytearray) -> bytearray: """ Zeroing byte objects. Args: value: The byte object that you want to reset. Returns: Reset value. """ result = b'' if isinstance(value, (bytes, bytearray)): result = b'/x00' * len(value) result = bytearray(result) return result
bigcode/self-oss-instruct-sc2-concepts
def get_user_choice(choices): """ ask the user to choose from the given choices """ # print choices for index, choice in enumerate(choices): print("[" + str(index) + "] " + choice) # get user input while True: user_input = input("\n" + "input: ") if (user_input.isdigit() is False) or (int(user_input) not in range(len(choices))): print("wrong input!") else: return int(user_input)
bigcode/self-oss-instruct-sc2-concepts
def get_size_from_block_count(block_count_str, size_step=1000, sizes = ["K", "M", "G", "T"], format_spec=":2.2f"): """Transforms block count (as returned by /proc/partitions and similar files) to a human-readable size string, with size multiplier ("K", "M", "G" etc.) appended. Kwargs: * ``size_step``: size of each multiplier * ``sizes``: list of multipliers to be used *``format_spec``: value formatting specification for the final string """ block_count = float(block_count_str) size_counter = 0 while block_count >= float(size_step): block_count /= size_step size_counter += 1 return ("{"+format_spec+"}{}").format(block_count, sizes[size_counter])
bigcode/self-oss-instruct-sc2-concepts
import functools def memoize(f): """ Minimalistic memoization decorator (*args / **kwargs) Based on: http://code.activestate.com/recipes/577219/ """ cache = {} @functools.wraps(f) def memf(*args, **kwargs): fkwargs = frozenset(kwargs.items()) if (args, fkwargs) not in cache: cache[args, fkwargs] = f(*args, **kwargs) return cache[args, fkwargs] return memf
bigcode/self-oss-instruct-sc2-concepts
import cgi def check_api_v3_error(response, status_code): """ Make sure that ``response`` is a valid error response from API v3. - check http status code to match ``status_code`` :param response: a ``requests`` response :param status_code: http status code to be checked """ assert not response.ok assert response.status_code == status_code # Should return json anyways.. content_type = cgi.parse_header(response.headers['content-type']) assert content_type[0] == 'application/json' assert content_type[1]['charset'] == 'utf-8' data = response.json() # This is an error! assert data['success'] is False assert 'error' in data assert 'result' not in data return data
bigcode/self-oss-instruct-sc2-concepts
def fail(s): """ A function that should fail out of the execution with a RuntimeError and the provided message. Args: s: The message to put into the error. Returns: A function object that throws an error when run. """ def func(): raise RuntimeError(s) return func
bigcode/self-oss-instruct-sc2-concepts
def is_simple_locale_with_region(locale): """Check if a locale is only an ISO and region code.""" # Some locale are unicode names, which are not valid try: lang, sep, qualifier = locale.partition('_') except UnicodeDecodeError: return False if '-' in lang: return False # Only allow qualifiers that look like a country code, without any suffix if qualifier and len(qualifier) == 2: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def format_output_mesmer(output_list): """Takes list of model outputs and formats into a dictionary for better readability Args: output_list (list): predictions from semantic heads Returns: dict: Dict of predictions for whole cell and nuclear. Raises: ValueError: if model output list is not len(8) """ expected_length = 4 if len(output_list) != expected_length: raise ValueError('output_list was length {}, expecting length {}'.format( len(output_list), expected_length)) formatted_dict = { 'whole-cell': [output_list[0], output_list[1][..., 1:2]], 'nuclear': [output_list[2], output_list[3][..., 1:2]], } return formatted_dict
bigcode/self-oss-instruct-sc2-concepts
import torch def extract_torchmeta_task(cs, class_ids): """ Extracts a single "episode" (ie, task) from a ClassSplitter object, in the form of a dataset, and appends variables needed by DatasetDistance computation. Arguments: cs (torchmeta.transforms.ClassSplitter): the ClassSplitter where to extract data from class_ids (tuple): indices of classes to be selected by Splitter Returns: ds_train (Dataset): train dataset ds_test (Dataset): test dataset """ ds = cs[class_ids] ds_train, ds_test = ds['train'], ds['test'] for ds in [ds_train, ds_test]: ds.targets = torch.tensor([ds[i][1] for i in range(len(ds))]) ds.classes = [p[-1] for i,p in enumerate(cs.dataset._labels) if i in class_ids] return ds_train, ds_test
bigcode/self-oss-instruct-sc2-concepts
import unicodedata def full2half(uc): """Convert full-width characters to half-width characters. """ return unicodedata.normalize('NFKC', uc)
bigcode/self-oss-instruct-sc2-concepts
def simple_function(arg1, arg2=1): """ Just a simple function. Args: arg1 (str): first argument arg2 (int): second argument Returns: List[str]: first argument repeated second argument types. """ return [arg1] * arg2
bigcode/self-oss-instruct-sc2-concepts
def _object_type(pobj): ############################################################################### """Return an XML-acceptable string for the type of <pobj>.""" return pobj.__class__.__name__.lower()
bigcode/self-oss-instruct-sc2-concepts
import re def smi_tokenizer(smi): """ Tokenize a SMILES """ pattern = "(\[|\]|Xe|Ba|Rb|Ra|Sr|Dy|Li|Kr|Bi|Mn|He|Am|Pu|Cm|Pm|Ne|Th|Ni|Pr|Fe|Lu|Pa|Fm|Tm|Tb|Er|Be|Al|Gd|Eu|te|As|Pt|Lr|Sm|Ca|La|Ti|Te|Ac|Si|Cf|Rf|Na|Cu|Au|Nd|Ag|Se|se|Zn|Mg|Br|Cl|U|V|K|C|B|H|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\\\|\/|:|~|@|\?|>|\*|\$|\%\d{2}|\d)" regex = re.compile(pattern) tokens = [token for token in regex.findall(smi)] return tokens
bigcode/self-oss-instruct-sc2-concepts
def b2s(binary): """ Binary to string helper which ignores all data which can't be decoded :param binary: Binary bytes string :return: String """ return binary.decode(encoding='ascii', errors='ignore')
bigcode/self-oss-instruct-sc2-concepts
def get_intersection_difference(runs): """ Get the intersection and difference of a list of lists. Parameters ---------- runs set of TestSets Returns ------- dict Key "intersection" : list of Results present in all given TestSets, Key "difference" : list of Results present in at least one given TestSet but not in all. """ intersection = set(runs[0]) difference = set() for r in runs: intersection = intersection & r difference.update(r) difference -= intersection return { "intersection": intersection, "difference": difference, }
bigcode/self-oss-instruct-sc2-concepts
def Nxxyy2yolo(xmin, xmax, ymin, ymax): """convert normalised xxyy OID format to yolo format""" ratio_cx = (xmin + xmax)/2 ratio_cy = (ymin + ymax)/2 ratio_bw = xmax - xmin ratio_bh = ymax - ymin return (ratio_cx, ratio_cy, ratio_bw, ratio_bh)
bigcode/self-oss-instruct-sc2-concepts
def all_children(mod): """Return a list of all child modules of the model, and their children, and their children's children, ...""" children = [] for idx, child in enumerate(mod.named_modules()): children.append(child) return children
bigcode/self-oss-instruct-sc2-concepts
def normalize_filename(filename): """Normalizes the name of a file. Used to avoid characters errors and/or to get the name of the dataset from a url. Args: filename (str): The name of the file. Returns: f_name (str): The normalized filename. """ if not isinstance(filename, str): raise ValueError("filename must be a str, not {}".format(type(filename))) if filename == "": return "" first_part = filename.split('?')[0] f_parts = [s for s in first_part.split('/') if s != ""] f_name = f_parts[-1] return f_name
bigcode/self-oss-instruct-sc2-concepts
def find_double_newline(s): """Returns the position just after a double newline in the given string.""" pos1 = s.find(b'\n\r\n') # One kind of double newline if pos1 >= 0: pos1 += 3 pos2 = s.find(b'\n\n') # Another kind of double newline if pos2 >= 0: pos2 += 2 if pos1 >= 0: if pos2 >= 0: return min(pos1, pos2) else: return pos1 else: return pos2
bigcode/self-oss-instruct-sc2-concepts
import re def promote_trigger(source: list, trigger: str) -> list: """Move items matching the trigger regex to the start of the returned list""" result = [] r = re.compile(trigger) for item in source: if isinstance(item, str) and r.match(item): result = [item] + result else: result.append(item) return result
bigcode/self-oss-instruct-sc2-concepts
def oscar_calculator(wins: int) -> float: """ Helper function to modify rating based on the number of Oscars won. """ if 1 <= wins <= 2: return 0.3 if 3 <= wins <= 5: return 0.5 if 6 <= wins <= 10: return 1.0 if wins > 10: return 1.5 return 0
bigcode/self-oss-instruct-sc2-concepts
import math def initial_compass_bearing(lat1, lng1, lat2, lng2): """ Calculates the initial bearing (forward azimuth) of a great-circle arc. Note that over long distances the bearing may change. The bearing is represented as the compass bearing (North is 0 degrees) Args: lat1 (str): The latitude of the first coordinate pair. lng1 (str): The longitude of the first coordinate pair. lat2 (str): The latitude of the second coordinate pair. lng2 (str): The longitude of the second coordinate pair. Returns: compass_bearing: The initial compass bearing. """ lat1 = math.radians(lat1) lat2 = math.radians(lat2) deltaLng = math.radians(lng2 - lng1) x = math.sin(deltaLng) * math.cos(lat2) y = (math.cos(lat1) * math.sin(lat2)) - (math.sin(lat1) * math.cos(lat2) * math.cos(deltaLng)) initial_bearing = math.atan2(x, y) # Normalize the initial bearing (-180 degrees to 180 degrees) # to a compass bearing (360 degrees) initial_bearing = math.degrees(initial_bearing) compass_bearing = (initial_bearing + 360) % 360 return compass_bearing
bigcode/self-oss-instruct-sc2-concepts
def clean_meta_args(args): """Process metadata arguments. Parameters ---------- args : iterable of str Formatted metadata arguments for 'git-annex metadata --set'. Returns ------- A dict mapping field names to values. """ results = {} for arg in args: parts = [x.strip() for x in arg.split("=", 1)] if len(parts) == 2: if not parts[0]: raise ValueError("Empty field name") field, value = parts else: raise ValueError("meta argument isn't in 'field=value' format") if not value: # The `url_file` may have an empty value. continue results[field] = value return results
bigcode/self-oss-instruct-sc2-concepts
def _default_filter(meta_data): """The default meta data filter which accepts all files. """ return True
bigcode/self-oss-instruct-sc2-concepts
import uuid def generate_fwan_process_id() -> str: """ Generates a new Firmware Analysis Process ID """ return str(uuid.uuid4())
bigcode/self-oss-instruct-sc2-concepts
import keyword def pykeyword(operation='list', keywordtotest=None): """ Check if a keyword exists in the Python keyword dictionary operation: Whether to list or check the keywords. Possible options are list and check. The default is 'list'. keywordtotest: The keyword to test for if the operation is 'check'. The default is None. """ if operation == 'list': return str(keyword.kwlist) elif operation == 'check': return keyword.iskeyword(str(keywordtotest))
bigcode/self-oss-instruct-sc2-concepts
def validate(contacts, number): """ The validate() function accepts the contacts array and number as arguments and checks to see if the number inputted is in the range of the contacts array. It returns a number inputted by the user within that range. """ while number<1 or number>len(contacts): print() print("Please enter a number from 1 to ", len(contacts)) number = int(input("Number: ")) return number
bigcode/self-oss-instruct-sc2-concepts
def thresh_hold_binarization(feature_vector, thresh_hold): """ Turn each value above or equal to the thresh hold 1 and values below the thresh hold 0. :param feature_vector: List of integer/float/double.. :param thresh_hold: Thresh hold value for binarization :return: Process and binarized list of data. """ return [1 if data >= thresh_hold else 0 for data in feature_vector]
bigcode/self-oss-instruct-sc2-concepts
def transform_okta_user(okta_user): """ Transform okta user data :param okta_user: okta user object :return: Dictionary container user properties for ingestion """ # https://github.com/okta/okta-sdk-python/blob/master/okta/models/user/User.py user_props = {} user_props["first_name"] = okta_user.profile.firstName user_props["last_name"] = okta_user.profile.lastName user_props["login"] = okta_user.profile.login user_props["email"] = okta_user.profile.email # https://github.com/okta/okta-sdk-python/blob/master/okta/models/user/User.py user_props["id"] = okta_user.id user_props["created"] = okta_user.created.strftime("%m/%d/%Y, %H:%M:%S") if okta_user.activated: user_props["activated"] = okta_user.activated.strftime("%m/%d/%Y, %H:%M:%S") else: user_props["activated"] = None if okta_user.statusChanged: user_props["status_changed"] = okta_user.statusChanged.strftime("%m/%d/%Y, %H:%M:%S") else: user_props["status_changed"] = None if okta_user.lastLogin: user_props["last_login"] = okta_user.lastLogin.strftime("%m/%d/%Y, %H:%M:%S") else: user_props["last_login"] = None if okta_user.lastUpdated: user_props["okta_last_updated"] = okta_user.lastUpdated.strftime("%m/%d/%Y, %H:%M:%S") else: user_props["okta_last_updated"] = None if okta_user.passwordChanged: user_props["password_changed"] = okta_user.passwordChanged.strftime("%m/%d/%Y, %H:%M:%S") else: user_props["password_changed"] = None if okta_user.transitioningToStatus: user_props["transition_to_status"] = okta_user.transitioningToStatus else: user_props["transition_to_status"] = None return user_props
bigcode/self-oss-instruct-sc2-concepts
def _compare_fq_names(this_fq_name, that_fq_name): """Compare FQ names. :param this_fq_name: list<string> :param that_fq_name: list<string> :return: True if the two fq_names are the same """ if not this_fq_name or not that_fq_name: return False elif len(this_fq_name) != len(that_fq_name): return False else: for i in range(0, len(this_fq_name)): if str(this_fq_name[i]) != str(that_fq_name[i]): return False return True
bigcode/self-oss-instruct-sc2-concepts
def remove_element_from_list(x, element): """ Remove an element from a list :param x: a list :param element: an element to be removed :return: a list without 'element' Example: >>>x = [1, 2, 3] >>>print(arg_find_list(x, 3)) [1, 2] """ return list(filter(lambda a: a != element, x))
bigcode/self-oss-instruct-sc2-concepts
def equal(param1, param2, ignore_case=False): """ Compare two parameters and return if they are equal. This parameter doesn't run equal operation if first parameter is None. With this approach we don't run equal operation in case user don't specify parameter in their task. :param param1: user inputted parameter :param param2: value of entity parameter :return: True if parameters are equal or first parameter is None, otherwise False """ if param1 is not None: if ignore_case: return param1.lower() == param2.lower() return param1 == param2 return True
bigcode/self-oss-instruct-sc2-concepts
import torch def BCEFlat(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: """Same as F.binary_cross_entropy but flattens the input and target. Args: x : logits y: The corresponding targets. Returns: The computed Loss """ x = torch.sigmoid(x) y = y.view(x.shape).type_as(x) return torch.nn.functional.binary_cross_entropy(x, y)
bigcode/self-oss-instruct-sc2-concepts
def _parse_message(exc): """Return a message for a notification from the given exception.""" return '%s: %s' % (exc.__class__.__name__, str(exc))
bigcode/self-oss-instruct-sc2-concepts
import string def printable_substring(the_str): """Returns the printable subset of the_str :param str the_str: a putative string :return str the_pr_str: the portion of the_str from index 0 that is printable """ i = 0 the_pr_str = '' while i < len(the_str): if the_str[i] in string.printable: the_pr_str += the_str[i] i += 1 else: return the_pr_str return the_pr_str
bigcode/self-oss-instruct-sc2-concepts
def make_read_only(tkWdg): """Makes a Tk widget (typically an Entry or Text) read-only, in the sense that the user cannot modify the text (but it can still be set programmatically). The user can still select and copy text and key bindings for <<Copy>> and <<Select-All>> still work properly. Inputs: - tkWdg: a Tk widget """ def killEvent(evt): return "break" def doCopy(evt): tkWdg.event_generate("<<Copy>>") def doSelectAll(evt): tkWdg.event_generate("<<Select-All>>") # kill all events that can change the text, # including all typing (even shortcuts for # copy and select all) tkWdg.bind("<<Cut>>", killEvent) tkWdg.bind("<<Paste>>", killEvent) tkWdg.bind("<<Paste-Selection>>", killEvent) tkWdg.bind("<<Clear>>", killEvent) tkWdg.bind("<Key>", killEvent) # restore copy and select all for evt in tkWdg.event_info("<<Copy>>"): tkWdg.bind(evt, doCopy) for evt in tkWdg.event_info("<<Select-All>>"): tkWdg.bind(evt, doSelectAll)
bigcode/self-oss-instruct-sc2-concepts
def is_array(value): """Check if value is an array.""" return isinstance(value, list)
bigcode/self-oss-instruct-sc2-concepts
import random def expand_model_parameters(model_params, expansion_limit): """Expand a model template into random combinations of hyperparameters. For example, if model_params is: {name: regression, l2_strength: [0, 1], train_steps: [100, 50] } Then the returned new_model_params will be the following: [ {name: regression_0, l2_strength: 0, train_steps: 50 }, {name: regression_1, l2_strength: 0, train_steps: 100 } {name: regression_2, l2_strength: 1, train_steps: 50 } {name: regression_3, l2_strength: 1, train_steps: 100 } ] Args: model_params: dict(string => list/string/int/float), a member of config.model_spec and the template we want to expand. expansion_limit: int, the number of time we are allowed to expand this model. Returns: new_model_params: list(dict), up to `expansion_limit` instantations of the provided model parameters. """ new_model_params = [] def random_spec(kv_pairs, model_id): out = [] for key, value in kv_pairs: if key == 'name': value += '_%s' % model_id if isinstance(value, list): out += [(key, random.choice(value))] else: out += [(key, value)] return out n_config_options = sum( len(x) if isinstance(x, list) else 0 for x in model_params.values()) + 1 for i in range(min(expansion_limit, n_config_options)): new_model_params += [dict(random_spec(model_params.items(), i))] return new_model_params
bigcode/self-oss-instruct-sc2-concepts
import json def mock_hue_put_response(request, context): """Callback for mocking a Philips Hue API response using the requests-mock library, specifically for a put request. This mock response assumes that the system has a single light with light_id of '1', and the expected request is to set the 'on' state as well as 'hue' state. See https://requests-mock.readthedocs.io/en/latest/response.html for usage details. Args: request: The requests.Request object that was provided. The request method is assumed to be a put request. context: An object containing the collected known data about this response (headers, status_code, reason, cookies). Returns: The response text with confirmation of the arguments passed in. """ expected_path = '/lights/1/state' if expected_path not in request.url: context.status_code = 400 return 'invalid Philips Hue url' try: body_dict = json.loads(request.body) except json.JSONDecodeError: context.status_code = 400 return 'put request body should be a JSON-encoded string' try: on = body_dict['on'] hue = body_dict['hue'] except KeyError: context.status_code = 400 return 'missing keys in put request body' context.status_code = 200 response = [] if on: response.append({'success':{'/lights/1/state/on': 'true'}}) else: response.append({'success':{'/lights/1/state/on': 'false'}}) response.append({'success':{'/lights/1/state/hue': f'{hue}'}}) return str(response)
bigcode/self-oss-instruct-sc2-concepts