content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def _metatile_contents_equal(zip_1, zip_2): """ Given two open zip files as arguments, this returns True if the zips both contain the same set of files, having the same names, and each file within the zip is byte-wise identical to the one with the same name in the other zip. """ names_1 = s...
3b5ec1cfbea5cef52a24450ca4b22bc382c2d6be
571,920
def _broadcast_strides(X_shape, X_strides, res_ndim): """ Broadcasts strides to match the given dimensions; returns tuple type strides. """ out_strides = [0] * res_ndim X_shape_len = len(X_shape) str_dim = -X_shape_len for i in range(X_shape_len): shape_value = X_shape[i] ...
04e25a196a80e957eb84cba176aac26614894bb9
512,598
def solution2array(solution): """ rewrites an solution of the form {(1,1): [4], (1,2): [5] , .... (9,9) : [1]} to an 2dimensional array. this is useful if we want to output it in a human readable form. this is also used as intermediate step for rewriting the sudoku back to the original format. ...
507b9dfe7b4c2e1296670c2d1a948c40098d7a3c
691,857
def dimensions(mesh): """ Returns the extent of the mesh in [x, y, z] directions, i.e. of the axis aligned bbox. :param mesh: open3d.geometry.TriangleMesh :return: (3) np array """ return mesh.get_max_bound().flatten() - mesh.get_min_bound().flatten()
d4a9ffecdaa84eec63887f784fec70ce4cb3214c
189,629
import re def expand_ios_ifname(ifname: str) -> str: """Get expanded interface name for IOSXR/XE given its short form :param ifname: str, short form of IOSXR interface name :returns: Expanded version of short form interface name :rtype: str """ ifmap = {'BE': 'Bundle-Ether', 'BV...
9cd8f6f5dc858b94436cbce60c9eb0e755a2fccf
623,060
def read_text_file_to_lines(text_file_path): """ Read a text file and return all the lines """ # read the file and return all the lines with open(text_file_path) as file: return file.readlines()
32d7f2ea159c37a577985dcad28e326831563a6c
360,380
import re def shorten(CSTAG: str) -> str: """Convert long format of cs tag into short format Args: CSTAG (str): cs tag in the **long** format Return: str: cs tag in the **short** format Example: >>> import cstag >>> cs = "cs:Z:=ACGT*ag=CGT" >>> cstag.shorten(cs)...
653de1947a3cdf06103b01c1a7efc3dbc16ea4ab
14,250
from unittest.mock import call import re def is_release() -> bool: """Return if current branch is a release branch.""" tag_name = call("git describe --tags").replace("\n", "") return re.match(r"^v\d+\.\d+\.\d+$", tag_name) is not None
f3eb14cdf279ff0b974b7ae16b4f430364fd50d5
641,328
def summation(num): """Return sum of 0 to num.""" x = [i for i in range(num + 1)] return sum(x)
f2ff68b73a924011dad05dcc3270e1c87f36e214
562,847
from typing import Optional from typing import List from typing import Tuple def is_valid_atom_index(index: int, coordinates: Optional[dict] = None, existing_indices: Optional[List[int]] = None, ) -> Tuple[bool, str]: """ Check whether an...
311b106f00994f617b953d6b630f8f3515f8dd8b
666,099
def matrix_equals(a, b, tolerance=1e-10): """ Compares two matrices with an imperfection tolerance Args: a (list, tuple): the matrix to check b (list, tuple): the matrix to check against tolerance (float): the precision of the differences Returns: bool : True or False ...
ff330b834ec5cb448f39b4d918c263ba2f75edd5
428,507
def find_contiguous_sum_to(num_list, target_sum): """Find range of numbers in list that sums to target_sum""" total = 0 range_start = 0 for i, curr_num in enumerate(num_list): total += curr_num while total > target_sum: total -= num_list[range_start] range_start +...
28e829fda1e54957ec6c66ab705808ac99240520
374,586
def relative_levels(levels, station): """Converts a list of level data to a list of relative level data for a given station""" if not station.typical_range_consistent(): return None else: min, max = station.typical_range return [(i - min)/(max - min) for i in levels]
84250d7748cc4ed76a411e203ddd7dc071eee2ae
282,494
def transfer_function_Rec1886_to_linear(v): """ The Rec.1886 transfer function. Parameters ---------- v : float The normalized value to pass through the function. Returns ------- float A converted value. """ g = 2.4 Lw = 1 Lb = 0 # Ignoring legal t...
7a2a2a2348d701e7fd7dd90c5d016dbf8a2e0c56
17,484
def get_traitset_map(pop): """ Utility method which returns a map of culture ID's (hashes) and the trait set corresponding to a random individual of that culture (actually, the first one we encounter). """ traitsets = {} graph = pop.agentgraph for nodename in graph.nodes(): tra...
c80f1f05e0dd5268990e62e6b87726d5349b53f7
699,911
import math import cmath def dirN(c): """Given a complex number, return its phase as a compass heading""" if c is None: value = None else: value = (450 - math.degrees(cmath.phase(c))) % 360.0 return value
2f6ddce35f0bdd62c31dc2cfb27ec3665dc6607b
347,222
def is_valid_field(field, allow_quote=False, minimum=None, maximum=None): """ Validates a generic user inputted field, such as a "name" for an object. For now, it basically only validates whether single quote characters should be allowed in the string. :type field: str :param field: The data t...
375b96d891a37115d8a367bc228e020f719da946
43,085
from typing import List from typing import Dict from pathlib import Path def collect_file_pathes_by_ext( target_dir: str, ext_list: List[str] ) -> Dict[str, List[Path]]: """Return the list of Path objects of the files in the target_dir that have the specified extensions. Args: target_dir (str): D...
18b6287d12a301b7cff98e37a4122474ae3a7958
30,162
from typing import Optional def to_field_element(val: int, prime: Optional[int]) -> int: """ Converts val to an integer in the range (-prime/2, prime/2) which is equivalent to val modulo prime. """ if prime is None: return val half_prime = prime // 2 return ((val + half_prime) % pr...
0f7318d67bc8a3c257d43a4fc403fc1675c78361
185,720
def upto_sum(n): """Sum 1...n with built-in sum and range""" return sum(range(n))
9fb4fb7d4590dee1726406866dbebae891310402
389,483
def get_ip_port_kwargs(ipString): """ Parse IP and port into kwargs suitable for reactor.listenTCP """ ip, port = ipString.split(':') ip, port = ( '' if ip == '*' else ip ), int(port) return dict(interface=ip, port=port)
311ab5fcb0e70e685cf94149b8aa08fce745ed37
336,539
def read_codelines(filepath): """ Reads a source code file and returns all lines. """ with open(filepath) as f: lines = f.readlines() return lines
c4136e260486f78aff76be3714edd1e8ea4a9885
398,936
def cubrt(x): """Returns the cubed root of x""" return round(x ** (1/3), 12)
41e500d1ee6ccc61c4442ea618c17daebea76c4e
644,007
import ast def empty_list(lineno=None, col=None): """Creates the AST node for an empty list.""" return ast.List(elts=[], ctx=ast.Load(), lineno=lineno, col_offset=col)
2def486baf5537d2754312c6234a7908c4aa46dd
23,612
import re def human2bytes(s): """ >>> human2bytes('1M') 1048576 >>> human2bytes('1G') 1073741824 """ symbols = ('Byte', 'KiB', 'MiB', 'GiB', 'T', 'P', 'E', 'Z', 'Y') num = re.findall(r"[0-9\.]+", s) assert (len(num) == 1) num = num[0] num = float(num) for i, n in enumer...
8ed56b6ea327cdc12b58c662268e54719e568f1d
678,466
import typing import inspect def tidy_fn_call(fn: typing.Callable, args: typing.Iterable, kwargs: dict): """ Put args to kwargs if they matches. This works like a function call parser. Parameters ---------- fn : typing.Callable The function to be called (it won't be called). args...
6acedf601f3d19b84d49c48b65b0ba2b0cd1d9b4
113,324
from typing import Sequence from typing import Callable from typing import List from typing import Any def join(processors: Sequence[Callable[[List[Any]], List[Any]]])-> Callable[[List[Any]], List[Any]]: """ Creates a processor from a list of processor. The processor created is equivalent to applying each...
f38cf67b5bab7e44849685f22c88e82d0be117db
338,862
def get_map_class_signature(deploy_annotations): """ Returns for every class its signature as defined in the cost annotations """ class_to_signature = {} for i in deploy_annotations: class_name = i["class"] for j in i["scenarios"]: if j["name"]: class_to_signature[(class_name,j["name"])]...
5259e041d084c670ffc63e2f8bcaf09d9cc4986c
523,817
def trip_mode_type(roundSpeed, vehicle_speed_cutoff, bicycle_speed_cutoff, walk_speed_cutoff): """ Estimate trip transportation mode. :param roundSpeed: fix speed value (in km/h) :param vehicle_speed_cutoff: speed greater than this value (in Km/h) will be marked as vehicle :param bi...
67db1ac87f41874f3d1583940f6b10573b7dc4c1
283,506
def get_container_name(framework): """Translate the framework into the docker container name.""" return 'baseline-{}'.format({ 'tensorflow': 'tf', 'pytorch': 'pyt', 'dynet': 'dy' }[framework])
172dfb49d25646aa1253bc257db5bc712c1229e9
681,340
from typing import List from typing import Dict def confusion_matrix_binary( y_true: List[int], y_pred: List[int] ) -> Dict[str, int]: """ Compute tp, tn, fp, fn Parameters ---------- y_true : list of ints True labels y_pred : list os ints Predicted labels ...
6297ae5f736c349cf482f36429d6ca1eb4461d1f
117,583
from typing import Mapping def subdict(d: Mapping, keys=None): """Gets a sub-dict from a Mapping ``d``, extracting only those keys that are both in ``keys`` and ``d``. Note that the dict will be ordered as ``keys`` are, so can be used for reordering a Mapping. >>> subdict({'a': 1, 'b': 2, 'c': 3,...
ffd0578fa0ad642f6573ae392cb17e8c9220569f
666,546
def get_iteration_prefix(i, total): """ Return a String prefix for itarative task phases. :param i int current step. :param total int total steps. """ return " [{0}/{1}]".format(i, total)
a1131b8ad931aaa07ccd8fb714ec91ddd985f0f3
673,917
def firstlemma(lemmastring): """selects the first lemma from a string denoting a "set" of lemmas, e.g. |bla|blub|""" lemmastring = lemmastring.strip("|") lemmalist = lemmastring.split("|") return(lemmalist[0])
93a5f9752dfdac4beb78f49fe8e88ac4d1f2f241
342,065
def has_group(user, group_name): """Check if user is member of a group""" return user.groups.filter(name=group_name).exists()
63f56cc4d1cebc40345a453cabeb72892173a7dc
562,104
def _get(elements, index): """Return element at the given index or None.""" return None if index is None else elements[index]
9d105f64e7416bc8f33593653f1235a4ea544f42
219,531
def exception_to_dict(error): """Takes in an exception and outputs its details, excluding the stacktrace, to a dict Args: error (Exception): The exception to serialize Returns: dict: The serialized exception """ return {"type": str(type(error).__name__), "message": str(error)}
a677e151079a7b0005a7da1065f08b49cbf559be
29,891
def flatten_dict(input_dict: dict, separator: str = '_', prefix: str = ''): """ Flatten a (possibly nested) dictionary Args: input_dict: the input dictionary to flatten separator: string used to merge nested keys. It defaults to "_" prefix: used in the recursive calls. Do not set manual...
5a1a6a5bfbaa30af639df1ee7bd2c9a6c0ef4034
504,444
def colour_column_volc(df, xcol, ycol): """Generates red/blue/gray colour column for volcano plot data according to the value in x and y cols for each protein.""" df['colours'] = 'gray' df.loc[(df[xcol] > 1) & (df[ycol] > 1.3), ['colours']] = 'red' df.loc[(df[xcol] < -1) & (df[ycol] > 1.3), ['colours']]...
bc1f6df807b1076e5dfd126f404496bc6194d10a
364,149
import re def GetVersion(native_heap): """Get the version of the native heap dump.""" re_line = re.compile("Android\s+Native\s+Heap\s+Dump\s+(?P<version>v\d+\.\d+)\s*$") matched = 0 with open(native_heap, "r") as f: for line in f: m = re_line.match(line) if m: return m.group('version'...
fc90392cc009e154c5fa043becf92cb0a611a30f
557,442
def winphone(alert, title=None, _open_page=None, extras=None): """MPNS specific platform override payload. Must include exactly one of ``alert``, ``title``, ``_open_page``, or ``extras``. """ if len(list(filter(None, (alert, _open_page, title)))) != 1: raise ValueError("MPNS payload must have ...
6cedbb59c7a12a01c9832173d6020ce4732fae86
555,856
import csv def read_csv(file): """ Reads a csv file and returns all rows (including field names) """ with open(file, newline='') as csv_file: reader = csv.DictReader(csv_file, delimiter=',') rows = [row for row in reader] return rows
4ec479b87272cbd60fcda6df671ef37f5702adf9
425,645
def tweet_with_accident_veichle_and_person(text): """ check if tweet contains words indicating an accident between person and veichle :param text: tweet text :return: boolean, true if tweet contains words, false for others """ if ((u'הולך רגל' in text or u'הולכת רגל' in text or u'נהג' in text ...
d7a478e9d6f7ec9ef44562aac00a6d2b9d0b85c6
317,692
def retrieve_cnv_data(store, solution, chromosome=''): """ Retrieve copy number data for a specific solution """ cnv = store['solutions/solution_{0}/cn'.format(solution)] if chromosome != '': cnv = cnv[cnv['chromosome'] == chromosome].copy() cnv['segment_idx'] = cnv.index return cnv
2c77415909ff27a3b3fd00e7abb8d25b67b6ea8f
701,920
def valid_cmd(cmd: str): """ Returns true if the given command is valid. Valid commads are of the form: ACTION TICKER AMOUNT """ if cmd in ("q" or "quit"): return False tokens = cmd.split(" ") if len(tokens) != 3: print("Incorrect format: require ACTION TICKER AMOUN...
5edc4b4646ef0264cd4831ab10de02dab5d72bbd
280,095
def limit_data(data_dict: dict, limit: int = -1) -> dict: """apply limitation to data set Args: data_dict (dict): set with source and target limit (int, optional): limit of data to process. Defaults to -1. Returns: [dict]: dict with limited source and target """ if ...
7ec0990659092ae98882dca90d5a288e5b23d2dc
614,550
import re def to_mb(s): """Simple function to convert `disk_quota` or `memory` attribute string values into MB integer values. """ if s is None: return s if s.endswith('M'): return int(re.sub('M$', '', s)) elif s.endswith('G'): return int(re.sub('G$', '', s)) * 1000 ...
870f276552ef90bbd5034551ea8ade0f5160491b
7,145
import warnings def deprecate(version, msg=None): """Decorator to deprecate Python classes and functions Parameters ---------- version : str A string containing the version with which the callable is removed msg : str, optional An additional message that will be displayed alongside ...
0ea05fde9547886afd225f9b143bf71bc2aa985d
374,472
def split_version(version): """ Separate a string including digits separated by periods into a tuple of integers. """ return tuple(int(ver) for ver in version.split('.'))
f39f23d7e14a2b38ae50df479e05f5d76d5be6f8
562,874
def mock_return_false(*args): """A mock function to return False""" return False
d903b188e94774c4b286e4dc83bb4ff90c27030d
497,018
def make_checkout_web3modal_url( currency_type, amount_in_ether_or_token, wallet_address, chainId=1 ): """ Build a checkout.web3modal.com link that uses web3modal to create a tx to pay in ETH/DAI on a chain to a certain address. Note: amount_in_ether_or_token is in decimals. """ if currency_...
c1c5622af89afa73920d0dbb9ff331f632897fd2
409,674
import torch as th def _topk_torch(keys, k, descending, x): """Internal function to take graph-wise top-k node/edge features according to the rank given by keys, this function is PyTorch only. Parameters ---------- keys : Tensor The key for ranking. k : int The :math:`k` in "t...
f23a681dbb22d422d659edcd4ccbb4b202473d68
88,965
import re def find_startend_time(s): """ Find starttime and endtime from a given string """ starttime, endtime = '', '' ts = re.findall(r'(\d+\:\d+\s?(?:AM|PM|am|pm|A.M.|P.M.|a.m.|p.m.))', s) if len(ts) == 1: starttime = ts[0] endtime = '' elif len(ts) == 2: startti...
be0781fe2a723bf545ce32ed903e7c3eae6e7f7b
314,125
def merge_tweets(labels_tweets): """ Merge tweets for each cluster. labels_tweets: DataFrame return: a dict of lables and their text """ pass labels = set(labels_tweets['label']) labels_text = dict() for label in labels: qry = "label == {}".format(label) res = labels_...
5a7737de089d622f0dc8e444b3243f8575b95ab2
184,098
def process(container_): """ Testing pythons default sorting operations :param container_: container of array (vector) of scalars :return: sorted container """ return sorted(container_)
581768a493e56789ae4340f5e3940881fe28250e
273,471
def reconstruct_path(current): """ Uses the cameFrom members to follow the chain of moves backwards and then reverses the list to get the path in the correct order. """ total_path = [current] while current.cameFrom != None: current = current.cameFrom total_path.append(current) ...
85000ca0d9ed4150afc536ff8ac8a500586df5fb
660,778
def get_highest_priority_reachable(Sr): """ Sr: The remaining unconsidered part of the original solution Return: the highest priority rule which is also reachable, i.e. that is to say it is in table 1. Or None if no rules are reachable. """ reachable = [r for r in Sr if r.tab...
0db461c71b79f10f0e239fd6c48658c0d1fdfc2e
629,411
def readbinary(filename): """Given a filename, read a file in binary mode. It returns a single string.""" filehandle = open(filename, 'rb') thisfile = filehandle.read() filehandle.close() return thisfile
1fb214aa355e3a3b8b2b5674e73aa28807b7023d
580,920
import torch def stable_softmax(scores, mask=None, epsilon=1e-9): """ :param scores: tensor of shape (batch_size, sequence_length) :param mask: (optional) binary tensor in case of padded sequences, shape: (batch_size, sequence_length) :param epsilon: epsilon to be added to the normalization factor ...
2a5a036307853318d2c576dbbdd4d7c60745182f
471,354
def r(line): """ Selects rho from a given line. """ r, _ = line return r
555f4fecc67f895ddf69f568b856ab7a8bdad3dd
681,037
def col(red, green, blue): """Convert the given colours [0, 255] to HTML hex colours.""" return "#%02x%02x%02x" % (red, green, blue)
8ae52c0f16fb65e90e2017efc8076ea64b738f6d
426,191
def extract_entities(input_data_tokens, entity_dict): """Extracts valid entities present in the input query. Parses the tokenized input list to find valid entity values, based on the given entity dataset. Args: input_data_tokens: A list of string tokens, without any punctuation, ba...
516d0d9ae0df4a318808125b7e44bc327ecb8cff
25,434
import re def clean_val(val): """ Returns cleaned value after replacing underscores (`'_'`) and asterisks (`'*'`) with an empty whitespace. :param val: Raw parsed string :type val: str :return: A :py:class:`str` object after removing underscores and asterisks """ return re.sub(r'[_*]', ' ', val).strip()
8289cee081989cb5d6bed712c9b3d7c497298d9c
212,655
def node_to_GeoJSON(node, graph, color="#F5A207"): """Convert node to GeoJSON string.""" data = graph.nodes[node] lat = data['lat'] lon = data['lon'] node_string = '' node_string += '{ "type" : "Feature",\n' node_string += '"geometry" : {"type": "Point", "coordinates": [%f,%f]},\n'%(lon, lat...
5efb1f477904ce24b232ccdb03cab8e1537fe65b
474,029
def dVdc_calc(Vdc,Ppv,S,C): """Calculate derivative of Vdc""" dVdc = (Ppv - S.real)/(Vdc*C) return dVdc
59d2708726e078efb74efce0bac2e397ba846d89
9,004
def short_bucket_name(bucket_name): """Returns bucket name without "luci.<project_id>." prefix.""" parts = bucket_name.split('.', 2) if len(parts) == 3 and parts[0] == 'luci': return parts[2] return bucket_name
b182955198c927f4fe2ab470a34fe002e5634041
390,363
def true_positives(T, X, margin=5): """Compute true positives without double counting >>> true_positives({1, 10, 20, 23}, {3, 8, 20}) {1, 10, 20} >>> true_positives({1, 10, 20, 23}, {1, 3, 8, 20}) {1, 10, 20} >>> true_positives({1, 10, 20, 23}, {1, 3, 5, 8, 20}) {1, 10, 20} >>> true_posi...
58bf0edb83d8d2f823fc3c6e10e827109f401c3e
581,604
def normalize(msg): """ Normalizes the plain text removing all invalid characters and spaces :param msg: Plain text to be normalized :return: the normalized message without invalid chars """ return "".join([let.lower() for let in msg if let.isalpha() or let.isdigit()])
d0bea7e7a813196d49cda8873d756849ec61b36d
646,550
def _neighbors(text: str, pos: list[int]) -> dict[str, str]: """Finds the characters neighboring a position Args: text (str): The text to use when finding neighbors pos (list[int]): The location in the form [row, column] Returns: dict[str, str]: A dictionary of neighbors of the for...
f1faa6f032479d631a7f5f4a4aeb214153565017
412,834
def get_number_of_usable_hosts_from_raw_address(raw_address: str) -> int: """ Return number of usable host ip addresses. >>> get_number_of_usable_hosts_from_raw_address("192.168.1.15/24") 254 >>> get_number_of_usable_hosts_from_raw_address("91.124.230.205/30") 2 """ slash_ind = raw_add...
be06cb197dd3aad98974ee006a93738f085a5c05
100,570
import collections def merge_dicts(dict1: dict, dict2: dict) -> dict: """ Merges two dicts adding up the values. :param dict1: The first dict. :param dict2: The second dict. :return: A dict with the added values of first and second dicts. """ return dict(collections.Counter(dict1) + colle...
d3a46f01a201fe97c69e93bc9c571f6b03c99bec
357,338
def fillna_value(df, value=0.0): """Set NaN to zero.""" return df.mask(df.isnull(), value)
dbce52b67c31f947d57440d358767815a7cb0439
412,872
import re def matchall(text, patterns): """Scans through a string for substrings matched some patterns. Args: text: A string to be scanned. patterns: a list of regex pattern. Returns: a list if matched. empty if not. """ ret = [] for pattern in patterns: try:...
06e2003780b0d8bf22b138bd92161b1c1cb7d367
512,249
def binary_search_recursive(array, elem, offset=0): """ Binary search algorithm. Complexity of algorithm is log(n). :param array: should be sorted list of elements :param elem: element to find in array :param offset: default is 0, used for recursive call :return: index of element in array if...
1b1dff1bcd7ea4cd42e75a2a3bfc881ccb3b282b
464,447
import requests def get_node(name, api_url, headers, validate_certs=True): """Returns a dict containing API results for the node if found. Returns None if not just one node is found """ url = "{}/v3/nodes?name={}".format(api_url, name) node_search = requests.get(url, headers=headers, verify=valid...
d6df2228d3a49cf82f2f38caff3204a738ea5547
664,642
def negation(f): """Negate a filter. Args: f: filter function to invert Returns: A filter function that returns the negation of f. """ def keep(paths): l = set(paths) r = set(f(paths)) return sorted(list(l-r)) return keep
b732a7ebab22b8647f8e0d957b77258fff95e52b
611,601
def get_next_super_layer(layer_dependency_graph, super_nodes, current_layer): """ Return the immediate next super layer of current layer. :param layer_dependency_graph: dependency graph of the model :param super_nodes: list of all super nodes :param current_layer: the layer whose next super layer n...
d7a0e606c10974510d0d250d15d26537f8440494
660,396
def filter_objlist(olist, fieldname, fieldval): """ Returns a list with of the objetcts in olist that have a fieldname valued as fieldval @param olist: list of objects @param fieldname: string @param fieldval: anything @return: list of objets """ return [x for x in olist if getattr(x, ...
f39c90261ac259c04e7daa70fa951156818719bc
291,077
def file_get_contents(path_to_file): """ Function get content of file (analog of php file_get_contents()) """ fh = open(path_to_file, 'r') content = fh.read() fh.close() return content
35ce52bdf33aa22c4359fe3aab8085e24780071b
584,411
from typing import Union def hex256(x: Union[int, str]) -> str: """Hex encodes values up to 256 bits into a fixed length By including this amount of leading zeros in the hex string, lexicographic and numeric ordering are identical. This facilitates working with these numbers in the database without n...
1bc19b38c46114e15fc62305d58e62b1e9fcbe8f
213,726
def get_vcf_column_headers(line, sample_ids, sample_indices): """Get VCF column headers, including only relevant samples Parameters ---------- line : str A line from a vcf file (e.g. from an open file descriptor) sample_ids : list, tuple All sample IDs in the input VCF file ...
496616202b820224c54b91111678c54554bca771
580,019
import math def get_cosine(question_vector, sentence_vector): """ Implementation of Cosine Similarity (https://en.wikipedia.org/wiki/Cosine_similarity). Formula = [SUM(1,n) of Ai * Bi] / {[Square root of (SUM(1,n) Ai^2)] * [Square root of (SUM(1,n) Bi^2)]} :param question_vector: The question's vector....
17c44f1946b42071df2cd47960ce660c5c1cd048
413,843
from typing import Dict from typing import Any def get_role_dependency_link(metadata: Dict[str, Any]) -> str: """ Returns role dependency link Args: metadata (Dict[str, Any]): role metadata Returns: str: role dependency link """ role_name = metadata.get("role_name", None) ...
c7018ccfa49c6ff7a7cc483fce6af64c27d6bc94
499,299
def derive_table_from(source): """Ease the typical use case /somewhere/TAB.txt -> TAB.json.""" table = source.stem.upper() return table, f'{table}.json'
08f364d70750c887915ca8464fe76fb09e7687d8
654,903
import inspect def get_args(frame): """Gets dictionary of arguments and their values for a function Frame should be assigned as follows in the function itself: frame = inspect.currentframe() """ args, _, _, values = inspect.getargvalues(frame) return dict((key, value) for key, value in values.ite...
87bb968522657c762962e58a9c90023e97bc118e
667,640
def _ensure_cr(text): """ Remove trailing whitespace and add carriage return Ensures that `text` always ends with a carriage return """ return text.rstrip() + '\n'
1f70b470070f0d3640af0739d3320684d2116141
457,978
def _is_decoy_suffix(pg, suffix='_DECOY'): """Determine if a protein group should be considered decoy. This function checks that all protein names in a group end with `suffix`. You may need to provide your own function for correct filtering and FDR estimation. Parameters ---------- pg : dict ...
77da0255f7fe9672f502817bd5ab07f0bd6e3159
689,370
def _rgb2hex(c_rgb): """RGB to Hex. Parameters ---------- c_rgb : tuple (255, 255, 255) rgb colors in range 0-255. Returns ------- str. Hex color. Examples -------- hexcolor = _rgb2hex([255,255,255]) """ # Components need to be integers for hex to make ...
e64f11cc599c88670c16f439afb6553113dad879
150,038
def sample_image(imgGray, sampleRect, maxVal): """ Sample image in a given rectangle, represented as [x0,y0,w,h], where x0,y0 is the top-left coordinates of the sampling region """ y0, x0, w, h = sampleRect sampleSum = 0 for y in range(h): for x in range(w): sampleSum += imgGray[y0...
c6e7bde238b0f7fe5ff0b9cc2224e33dada410bc
557,645
import time import hmac import hashlib def create_auth_headers(url, access_key, secret, body=None): """ get HTTP headers for API authentication :param url: API url. (e.g. https://coincheck.com/api/accounts/balance ) :param access_key: Access Key string for API authentication :param secret: Secret ...
7f34aecf72a4fef230b7b081cfed9ecba6d9dd2a
204,412
def get_event_abi(abi, event_name): """Helper function that extracts the event abi from the given abi. Args: abi (list): the contract abi event_name (str): the event name Returns: dict: the event specific abi """ for entry in abi: if 'name' in entry.keys() and entry...
fe8c7e6c16991d7b44439b70adfbad7b87fb57c3
505,954
def move1(state,b1,dest): """ Generate subtasks to get b1 and put it at dest. """ return [('get', b1), ('put', b1,dest)]
c84a2d8246017fa94a73dd2e3408f7f05cf3573d
696,739
import inspect def getPublicTypeMembers(type_, onlyValues=False): """ Useful for getting members from types (e.g. in enums) >>> [_ for _ in getPublicTypeMembers(OS, True)] ['Linux', 'Windows'] """ retVal = [] for name, value in inspect.getmembers(type_): if not name.startswith("...
859dcce8245e6eac372fc8db5e4559366600b309
664,964
import hashlib def proof_of_work(unique_trxn_data, nonce): """[CHANGING DIFFICULTY: Look for the 'difficulty = X' row, and change X to another integer] The Bitcoin SHA256 proof-of-work. Takes transaction data, and requires the miner to find a nonce (number only used once) that will result in a SHA256 has...
bc6370639cb4cbd2e625b7cf0eb2d1bc89b91b61
543,240
def _string_from_cmd_list(cmd_list): """Takes a list of command line arguments and returns a pretty representation for printing.""" cl = [] for arg in map(str, cmd_list): if ' ' in arg or '\t' in arg: arg = '"' + arg + '"' cl.append(arg) return ' '.join(cl)
773fcc8b93b4ff31fdb18c1939f396d0b19b1d96
537,460
from typing import Dict from pathlib import Path def read_image_to_bytes(filename: str) -> Dict: """ Function that reads in a video file as a bytes array Parameters ---------- filename : str Path to image file Returns ------- JSON Object containing "filename" and byte...
d90721ff1231e7f1e0d2f7ea4bcf81facd2b1686
72,735
import string def letterDensity(authors): """ Calculate the empirical distribution of first letters. """ authors['firstLetter'] = authors.firstLetter.apply(lambda x: x.lower()) authors = authors[authors['firstLetter'].isin([i for i in string.ascii_lowercase])] byLetter = authors.groupby('firstLett...
d5b1533a66293b06e1035d1bf1a353c0a267106c
218,388
from datetime import datetime def _iso8601_date(time: datetime) -> str: """Formats the timestamp in ISO-8601 format, e.g. '2020-06-01T00:00:00.000Z'.""" return f"{time.replace(tzinfo=None).isoformat(sep='T', timespec='milliseconds')}Z"
17a9363f7ba7f7c45f0a5dedf838cfc003ac58d8
562,657
from typing import List def txt_python_func(func_list: List[str], func_type: str) -> str: """This method creates strings from which the python file in which the simulation functions are defined is created. func_list contains the names of all process functions for which a string representation should be gener...
443aadda78530493ec9a8007912f1925f517a0d1
112,713
import logging def get_logger(log_file=None):# {{{ """Set logger and return it. If the log_file is not None, log will be written into log_file. Else, log will be shown in the screen. Args: log_file (str): If log_file is not None, log will be written into the log_file. Return...
25cbf7d9cd9150ee5b86929c9ab56d748ae0fdc3
19,318