content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def clean_euler_path(eulerian_path: list) -> list: """Cleans a Eulerian path so that each edge (not directed) appears only once in the list. If a edge appears more than once, only the first occurrence is kept. Arguments: eulerian_path {list} -- Eulerian path Returns: list -- cleaned Euleri...
207d5d5ef6747b5d537c6c8502dd536638ccee9d
22,644
def frame_idx(fname): """Get frame index from filename: `name0001.asc` returns 1""" return int(fname[-8:-4])
af3e6a4c693fa77b7516e5560c20f50d3a5f925a
22,645
import pickle def load_calib(filename): """ Loads calibration parameters from '.pkl' file. Parameters ---------- filename : str Path to load file, must be '.pkl' extension Returns ------- calib_params : dict Parameters for undistorting images. """ # read python dict back from the file pk...
93700abe123df3ebcd17bddf16a6acd1a42ea1a7
22,647
import re def get_molecular_barcode(record, molecular_barcode_pattern): """Return the molecular barcode in the record name. Parameters ---------- record : screed record screed record containing the molecular barcode molecular_barcode_pattern: regex pattern ...
1507cf7ad3c39c02b6dfdfdd12c6800155346253
22,648
import shlex def read_from_file(path): """ Reads plot file Returns data sets data_set: [(f,val)] -> 1 2\n2 5\n3 8 data_sets: [data_set] -> data1\n\n\ndata2 """ opened_file = open(path, "rU") joined = opened_file.read() opened_file.close() datasets = [[shlex.split(line) for lin...
3049e6080a259bccf83a914c4cd4c19310744b16
22,650
import string import random def generate_random_password() -> str: """Generates truly random password""" letters = string.ascii_letters password = ''.join(random.choice(letters) for _ in range(random.randint(5, 14))) return password
6bbfead5832b48cf9bd4e4d9af5a2a0463e776ec
22,652
def int_to_bytes(x): """Changes an unsigned integer into bytes.""" return x.to_bytes((x.bit_length() + 7) // 8, 'big')
5f441a6a5767d8cd1292e8976a24b0c9c4ca157e
22,653
def extend_xmax_range(xmax_bins, templates): """ Copy templates in empty xmax bins, helps to prevent problems from reaching the edge of the interpolation space. :param templates: dict Image templates :return: dict Extended image templates """ # Create dictionary for our new...
ac622fde3a0bd7c8919b8fd63f459596ea13d88c
22,654
import uuid def get_uuid(data): """Compute a UUID for data. :param data: byte array """ return str(uuid.uuid3(uuid.NAMESPACE_URL, data))
f91e6e76c14736c1678bc000b7246ac6b518171f
22,656
from collections import OrderedDict def aggregate_instruction_forms(instruction_forms): """Hierarhically chains instruction forms Combines operand types that differ only by a single operand together """ nested_operand_types = { ("1", "imm8"), ("3", "imm8"), ("rel8", "rel32"),...
95f449fed39d74f7d9ca0b8b17f844760d734379
22,657
def ssqrange(charge, sz, nsingle): """ Make a list giving all possible :math:`S^{2}` values for given charge and :math:`S_{z}`. Parameters ---------- charge : int Value of the charge. sz : int Value of sz. nsingle : int Number of single particle states. Returns ...
b05451081b0b13dd8f43a14e88eaf591ba6324ec
22,658
def split(iterable, **split_options): """Perform a split on iterable. This method is highly inspired in the `iter` global method (in conjunction with its __iter__ counterpart method) for iterable classes. :param iterable: An iterable, which will typically be a Storage<Collection> :param split_opti...
ac3e8743393d66ab9553db0e4735e2425d97518c
22,659
def scale_vector(vector, scale): """Scale a 3D vector's components by scale.""" return vector[0] * scale, vector[1] * scale, vector[2] * scale
292269d2e54db362b823c547b0415f53d93e3e4c
22,661
import requests import json def query_clone_infos_airlab(ids): """ Use rauls API to query clone info from clone ids :param ids: :return: dict with the response """ resp_dict = dict() for id in ids: resp = requests.get('http://airlaboratory.ch/apiLabPad/api/getInfoForClone/' + str(...
251f0c86ddc341ed9dc7cc235837abb1bc23e437
22,663
import math import torch def log_mv_gamma(p, a): """Simple implementation of the log multivariate gamma function Gamma_p(a) Args: p (int): dimension a (float): argument Will be made obsolete by https://github.com/pytorch/pytorch/issues/9378 """ C = p * (p - 1) / 4 * math.log(math...
70fb7cb7e55387d286c1d7bb5a0bad6fdaa1f376
22,664
def num_round(x) -> str: """comma separated with only the largest 2 units as non-zero""" if x > 100: x = round(x, 2 - len(str(int(x)))) elif x < 100: x = round(x, 3 - len(str(int(x)))) elif abs(x) > 10: x = round(x, -1) else: x = x x = int(round(x)) return f'{...
d1b6268ee8bc419e649f8fd0b399e8fa5413be5c
22,665
def getYearDigits(a_year): """Returns year digits , given year""" return abs(a_year % 100)
f0ad0c65a77ade0514ca97d6b60165d433421e9e
22,666
def lr_lambda(epoch, base=0.99, exponent=0.05): """Multiplier used for learning rate scheduling. Parameters ---------- epoch: int base: float exponent: float Returns ------- multiplier: float """ return base ** (exponent * epoch)
24ac54a8e54fa64e44ab941125a72ac4bbb269fd
22,667
def partition(pred, iterable): """ Returns tuple of allocated and unallocated systems :param pred: status predicate :type pred: function :param iterable: machine data :type iterable: list :returns: ([allocated], [unallocated]) :rtype: tuple .. code:: def is_allocated(d): ...
997466771c67995f0bd7f5d7bbbecf73c444ccdd
22,668
import string def isValidMapKey(key): """Returns ``True`` if the given string is a valid key for use as a colour map or lookup table identifier, ``False`` otherwise. A valid key comprises lower case letters, numbers, underscores and hyphens. """ valid = string.ascii_lowercase + string.digits + '_...
2e9167c3351b6c80bcc12c129279c4048f511e24
22,670
def factory_class_name(model_class_name): """Return factory class name from model class""" return model_class_name + 'Factory'
acfde8e129fb44f2db108a778b15938efbcc237b
22,671
import pathlib import json import re def check_markers(test_mode=False): """Validate markers in PinNames.h files""" mbed_os_root = pathlib.Path(__file__).absolute().parents[3] errors = [] with ( mbed_os_root.joinpath("targets", "targets.json") ).open() as targets_json_file: targe...
27f303542d83f99c75df5d1804ec103f1377959d
22,672
import os def remove(base, target): """ Remove file from given directory if exists. base: base directory of target file target: path to target file relative to base directory """ remove = os.path.join(base, target) if not os.path.isfile(remove): return False os.remove(remove...
7a6edaa13edb7ef51520a56f7a97fa8c5d388091
22,673
import argparse def get_arguments(): """ Obtains command-line arguments. :rtype argparse.Namespace """ parser = argparse.ArgumentParser() parser.add_argument( '--model-input', required=True, metavar='MODEL-INPUT', help='read the base model from Pickle file %(...
35da3f18e6a2b13ca92079a8360cfd6b4240fadb
22,674
import numpy def first_order_rotation(rotvec): """First order approximation of a rotation: I + skew(rotvec) cfo, 2015/08/13 """ R = numpy.zeros((3,3), dtype=numpy.float64) R[0,0] = 1.0 R[1,0] = rotvec[2] R[2,0] = -rotvec[1] R[0,1] = -rotvec[2] R[1,1] = 1.0 R[2,1] = rotvec[...
0b7543574a97b8bc902694eedf1c1ed871d1ed84
22,675
def greeting_service(create_service_meta): """ Greeting service test instance with `log` dependency mocked """ return create_service_meta("log")
a7d732b610f2d8a311e8299eba4a1c99b93f7351
22,676
def enum_rocket(): """ 返回王炸 """ return [('BJ-CJ', 0)]
c8e303c54d77a8b2ee71a97cbb98f2dd743391b7
22,677
def _group_counts_to_group_sizes(params, group_counts): """Convert numbers of groups to sizes of groups.""" _, out_channels, _ = params group_sizes = [out_channels // count for count in group_counts] return group_sizes
fdcf6c86dd4c90507d1cc2f9b5968d5110df264b
22,678
def __read_sequence_ids(data): """ Reads SequenceIDs.txt (file included in OrthoFinder Output) and parses it to a dict :param data: list of lines in SequenceIDs.txt :return: dict with key: OrthoFinder ID en value: the proper name """ output = {} for l in data: if l.strip() != '': ...
7855cf70398e22c45516b822ceff3ec9702ce5e5
22,679
def snap_value(input, snap_value): """ Returns snap value given an input and a base snap value :param input: float :param snap_value: float :return: float """ return round((float(input) / snap_value)) * snap_value
1b2f967ecca2a151c5229cbb9eb57d6c67853925
22,680
from typing import Union from typing import List from typing import Dict import json def convert_argstr(s: str) -> Union[None, bool, int, str, List, Dict]: """Convert string to suitable argument type""" s = s.strip() if s in ('None', 'null'): return None elif s in ('True', 'true'): ret...
416f6fe12aa58a8d7162a3ca0a70b01e5d0c90c2
22,681
from pathlib import Path def fixture(name: str): """ Construct an absolute path to the fixture directory """ return str(Path(Path(__file__).parent.absolute(), 'fixtures', name))
0055b7076615893531977afaba49e421c3440224
22,682
def _read_node( data, pos, md_total, val_total ): """ 2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2 The quantity of child nodes. The quantity of metadata entries. Zero or more child nodes (as specified in the header). If a node has no child nodes, its value is the sum of its metadata entries. So, the value of node B is 1...
e2fd6e53bb7a9078486794ff4f9e6b98639aa67b
22,683
import json def make_policy(bucket_name, prefix, allow_get_location=False): """Produces a S3 IAM text for selective access of data. Only a prefix can be listed, gotten, or written to when a credential is subject to this policy text. """ bucket_arn = "arn:aws:s3:::" + bucket_name prefix_arn = ...
8c76f0be774b7b0de2169552cf4ba5a961e83023
22,684
from datetime import datetime def parseDate(timestamp): """Parses an EXIF date.""" return datetime.strptime(timestamp, '%Y:%m:%d %H:%M:%S')
d59d2c0b1c1370035a93ed8e4a93834db6915646
22,685
import torch def one_hot_vector(length, index, device=torch.device('cpu')): """ Create a one-hot-vector of a specific length with a 1 in the given index. Args: length: Total length of the vector. index: Index of the 1 in the vector. device: Torch device (GPU or CPU) to load the ve...
88dca8d63792b5a8eb58abbf12eb2800e28b3264
22,686
def partial(func, *args, **kwargs): """ Create a partial function during processing of a filter pipeline, like in x:fun(a,b) - the returned function represents application of (a,b) to a `fun`; whatever argument will be supplied later, it will be PREPENDED to the argument list, unlike in functools.partia...
d5075c21a922524370baa3bd025bb7bb01291902
22,687
def XORs(alen,array): #incorrect, and too slow """xors=0 donedex=[] for i in xrange(alen): for j in xrange(1,alen): if (i!=j) and ((i,j) not in donedex): if (i^j)%2==1: donedex.append((i,j)) donedex.append((j,i)) ...
aec2c5d96d5f61fb3bf22c5f28428481ff813c6a
22,690
def get_minutes(seconds): """Convert seconds to minutes.""" return seconds // 60
7ca290c4e581a786af32f333d1c1f771de6b91c9
22,691
def compat_middleware_factory(klass): """ Class wrapper that only executes `process_response` if `streaming` is not set on the `HttpResponse` object. Django has a bad habbit of looking at the content, which will prematurely exhaust the data source if we're using generators or buffers. """ ...
b6a9aefee305b808481e3611033b7660e6113904
22,692
def make_topic(*levels): """Create a valid topic. >>> make_topic('foo', 'bar') 'foo/bar' >>> make_topic(('foo', 'bar')) 'foo/bar' """ if len(levels) == 1 and isinstance(levels[0], tuple): return make_topic(*levels[0]) return "/".join(levels)
6ab9218864d9b6a2eaefcc994414a8e089bbbd0e
22,693
def parse_type(s): """ Checks the type of 's' and adds plics to it except for NULL and NOT NULL. :param s: value to be checked. :return: Parsed value """ string = "'%s'" % s return string.upper()
83ff8a90acbb21345ae68f7be897f31fea206ece
22,694
import math def sumlog(v1, v2): """Returns the sum of two logspaced values in logspace.""" if v1 < v2: v1, v2 = v2, v1 return math.log(1 + math.exp(v2 - v1)) + v1
3942f5a05da47065161c29164d57b0f22bda478a
22,695
import argparse def parse_arguments(): """Parse command line arguments.""" parser = argparse.ArgumentParser(description="Create amplicon variant table.") parser.add_argument('master_file', help="Amplicon master file.") parser.add_argument('amplicon_coverage', help='Per-amplicon mean coverage.') pa...
929dc57397b7490924c30a1f088f688c87dfb54c
22,697
import re def split_names(voters): """Representative(s) Barbuto, Berger, Blake, Blikre, Bonner, Botten, Buchanan, Burkhart, Byrd, Campbell, Cannady, Childers, Connolly, Craft, Eklund, Esquibel, K., Freeman, Gingery, Greear, Greene, Harshman, Illoway, Jaggi, Kasperik, Krone, Lockhart, Loucks, Lubnau, Madden, McOmi...
77e0abbf441b45757a638017199b773cb73d9976
22,698
def run_nlp(tweets): """Processes the tweet text through the model.""" results = '' for tweet in tweets: results += tweet['text'] + '; ' return results
024ce527767fedae8294a83da2c3cd8d81befcc1
22,699
import requests def _get_bin_count(fpath, delimiter=',', encoding='ISO-8859-1'): """ Gets the number of bins in the file. :param fpath: A path or url for the file (if a url it must include `http`, and if a file path it must not contain `http`). :type fpath: string :param del...
5bc02857ba87beb736b2a74baca665924863c68f
22,701
import random def rSel(iterable): """ rSel(iterable)\nrandom select a element""" if type(iterable) == dict: return random.choice(list(iterable.items())) else: idx = random.randint(0, len(iterable) - 1) return iterable[idx]
d7c2a146bbd1088c182e51f1d535b53c6f00d550
22,703
from pathlib import Path def get_garbage_frames(): """Init list with garbage objects.""" garbage_objects = [garbage_object.read_text() for garbage_object in Path(__file__).resolve().parent.glob('*.txt')] return garbage_objects
210420f7d5fa3b1b36021afe3f2316a1ccb88575
22,705
import time def current_datetimestring(): """Return a string with the date and time""" return " ".join([time.strftime('%x'), time.strftime('%X')])
e2e50bf2d2a9132e429dce28e092805575c509a4
22,706
def is_auxiliary_relation(token1, token2): """Return True if `token1` is an auxiliary dependent of `token2`.""" return ( (token1.upos == "AUX") and (token1.deprel in ["aux", "aux:pass"]) and (token2.upos == "VERB") and (token1.head == token2.id) )
1d0e6a50523e8c61e8cb77e68064db1a2750118f
22,707
from datetime import datetime def convert_string_date_to_datetime(now_str: str) -> datetime: """ Converts string of the format yyyy-dd-yy-hh-mm-ss to datetime format. :param now_str: str. String of the format yyyy-dd-yy-hh-mm-ss. """ numbers = [int(string_number) for string_number in now_str.split...
f1eb59bb618758ffe82fa09db820fb141b5e7781
22,708
def toCategorical(df): """ This function change object datatype in pandas.DataFrame into category datatype. Parameters ---------- df : pandas.DataFrame with train or test DataFrame. Returns ------- df : pandas.DataFrame with new datatypes. """ columns=['availability','g...
18ec1010be4404d340d2a3f55353c11fae64b844
22,709
def seperate_list(all_list, pred): """Given a predicate, seperate a list into a true and false list. Arguments: all_list {list} -- all items pred {function} -- predicate function """ true_list = [] false_list = [] for item in all_list: if pred(item): true_l...
9ef7f2f3a16eb83478c75f7c8bb8ec95af5e5eba
22,710
def count_parameters(model): """ Compute the number of trainable parameters of the model. :param model: type nn.Module :return: number of parameters, type int """ return sum(p.numel() for p in model.parameters() if p.requires_grad)
2d57e514e5480538d5a9586229af15b7a32b3791
22,711
from typing import Any from typing import Dict from typing import OrderedDict def convert_dict_to_ordered_dict(qconfig_dict: Any) -> Dict[str, Dict[Any, Any]]: """ Convert dict in qconfig_dict to ordered dict """ # convert a qconfig list for a type to OrderedDict def _convert_to_ordered_dict(key, qcon...
bf5a8543a2b306d79824902a7b60200ee1994a4c
22,712
import sys import platform def multiarch_args(): """Returns args requesting multi-architecture support, if applicable.""" # On MacOS we build "universal2" packages, for both x86_64 and arm64/M1 if sys.platform == 'darwin': args = ['-arch', 'x86_64'] # ARM support was added in XCode 12, whi...
ba63f02534d364630fc5e4676d49fc56d4a61b56
22,713
def _extract_table_arrays(table): """Get buffer info from arrays in table, outputs are padded so dim sizes are rectangular. Args: table: A pyarrow.Table Return: tuple of: array_buffer_addrs: 3-dim list of buffer addresses where dims are columns, c...
81ca91d95305ab1b6541e603d90472ecd254f4df
22,714
import math def euclidean_distance(point1, point2): """ returns the euclidean distance between 2 points :param point1: The first point (an array of integers) :param point2: The second point (an array of integers) """ return math.sqrt(sum((point1 - point2) ** 2))
78888479fa3cfd3e53e235fa1d525b7dbe3314e1
22,715
def _is_pt_file(path: str) -> bool: """Returns true if the path is a tar archive and false otherwise.""" return path.endswith('.pt')
5f1dc9a9130f5cb25d44ac7b72b63af831538eb5
22,716
def checkEmblFile(filin): """Check EMBL annotation file given by user""" line = filin.readline() # TEST 'ID' if line[0:2] != 'ID': return 1 else: return 0
8087a78a35193545070f76dbd969b617c7c92b0c
22,717
import os def output(input_file, input_path, output_path, change = True, extra = None, begin = False, output_extension = None): """ Output filename from input filename. Parameters ---------- input_file : str Input filename. input_path : str Path from input file. output_pat...
132a836f28f0ca151db857005ff15e4a923aa765
22,718
import math def calc_distance(asteroid1, asteroid2): """Calculates the distance between two asteroids""" x1, y1 = asteroid1 x2, y2 = asteroid2 dx = x2 - x1 dy = y2 - y1 return math.sqrt(dx * dx + dy * dy)
1c424a94c7638c0a913675c42f4e4226f0c7c97b
22,719
def get_value(item: str, json_package: dict) -> dict: """Return dict item.""" return_dict = {} if item in json_package: return_dict[item] = json_package[item] return return_dict
980325c5f8dfb51fa0551726081b3fea76ed3238
22,720
def gzipOA(directory=None, cmdverbose : int =0, add_check : bool = True, unzip_text : bool = False): """ Create script to compress all oa files in a directory with gzip """ if directory is not None: cmd = 'cd %s\n' % directory else: cmd = '' if cmdverbose>=2: cmd += 'echo ...
6f8dfa12369a654c7bc8dd24a3ac7f1faa650d71
22,721
def parse_response(data): """ Parse response and return json array of sites + associated data :param data: json data returned by Alexa API, such as that returned in fn(query_api_url) :return: json """ return data['Ats']['Results']['Result']['Alexa']['TopSites']['Country']['Sites']['Site']
077c1ee5e34538738218fb66c1eed04dfe8c18b8
22,722
def api_error(request): """Fallback error handler for frontend API requests.""" request.response.status_int = 500 # Exception details are not reported here to avoid leaking internal information. return { "message": "A problem occurred while handling this request. Hypothesis has been notified." ...
3281c15f044a6c5b29ef0686e10cdf878fc445d1
22,723
def get_record_count(hook, database, table): """ gets the row count for a specific table """ query = '''SELECT t.row_count as record_count FROM "{}".information_schema.tables t WHERE t.table_name = '{}';'''.format(database, table) return hook.get_records(query).pop()[0]
24d5ae81093bd4ae411d13571ee9ee0d8e36da4e
22,724
import fnmatch def fpath_has_ext(fname, exts, case_sensitive=False): """returns true if the filename has any of the given extensions""" fname_ = fname.lower() if not case_sensitive else fname if case_sensitive: ext_pats = ['*' + ext for ext in exts] else: ext_pats = ['*' + ext.lower() ...
6283429081ceed9a825d7d1541a660e1d12f9a2d
22,725
def area_triangle(base: float, height: float) -> float: """ Calculate the area of a triangle given the base and height. >>> area_triangle(10, 10) 50.0 >>> area_triangle(-1, -2) Traceback (most recent call last): ... ValueError: area_triangle() only accepts non-negative values >>...
33520e4457a027157886ab14f1822b1675b2fa92
22,726
def map_category(category): """ Monarch's categories don't perfectly map onto the biolink model https://github.com/biolink/biolink-model/issues/62 """ return { 'variant' : 'sequence variant', 'phenotype' : 'phenotypic feature', 'sequence variant' : 'variant', 'phenoty...
7481a12360e2f5e5fb33fb1b351633aae8eb1e64
22,727
import math def get_3d_pos_from_x_orientation(x_orientation, norm=1): """ Get a 3d position x, y, z for a specific x orientation in degrees Args: - (float) orientation around x axis - (float) norm to rescale output vector Return: - (float) x position [0; 1] * norm - (f...
9cbecf86db3d3de5e203bde3381d6c3f05115577
22,728
def get_field_value(field, with_defaults) -> str: """ This helper need to extract value from field. """ if field.is_not_none: return field.failure_safe_value elif field.default and with_defaults: return field.default return ''
ad2529ac6a2bada2e235c4ad79891e8407108392
22,729
def make_system_simple(support, sampling_locations): """ Make measurement system from the samples and output support: signal support as binary array sampling locations: sampling locations N: number of samples to use """ M = sampling_locations.dot(support.T)...
6c12dc126777aa3b7b3223663503cac2f1ea32bd
22,730
import math def invertedCantorParingFunction(z): """ @see http://en.wikipedia.org/wiki/Pairing_function >>> invertedCantorParingFunction(0) (0, 0) >>> invertedCantorParingFunction(1) (1, 0) >>> invertedCantorParingFunction(2) (0, 1) >>> invertedCantorParingFunction(3) (2, 0) ...
963b663949485cdbf3f1b738d49d684ce18cd28b
22,731
def get_filters(filters): """The conditions to be used to filter data to calculate the total sale.""" query_filters = [] if filters.get("company"): query_filters.append(["company", '=', filters['company']]) if filters.get("from_date"): query_filters.append(["posting_date", '>=', filters['from_date']]) if filte...
29d0da9d4d19702d032d33e04292e7a8d288e2ab
22,734
def IDX(n) -> bool: """Generate in index into strings from the tree legends. These are always a choice between two, so bool works fine. """ return bool(n)
ebeed641df5dabf046a25ffc66d28aa4d1a29ab4
22,735
import os def abspath(path): """Convert path to absolute path, with uppercase drive letter on win32.""" path = os.path.abspath(path) if path[0] != '/': # normalise Windows drive letter path = path[0].upper() + path[1:] return path
b26761a90a3d9e87761b4b4df77512daf44e11b9
22,736
import logging def dismiss_cancelled_notifications(notifications: list[dict], cancelled_notifications: list[dict]): """Remove the cancelled notifications from the notifications data structure. Parameters: notifications(list[dict]): A list of notifications, which are in dictionary format. ...
e496ff8f1c0b6581bd2f68f287e02f3a61f02f93
22,738
def extract_data(source:str): """Read list of newline delineated ints from text file.""" with open(source, "r") as f: data = f.readlines() data = [int(el) for el in data if el != "/n"] return data
a3ea4301699bad013fa479503ac9fc460781a34e
22,739
def yes_no_dialog(prompt: str) -> bool: """Return true/false based on prompt string and Y/y or N/n response.""" while True: print() print(prompt) print() s = input("Y/n to confirm, N/n to reject >") if s in ("Y", "y"): return True if s in ("N", "n"):...
d0b8de6173621c38b8f2072ecaf2f6536a188cd1
22,740
def gatherIntel(analyzer, scs, sds): """Gather all of the intelligence about the program's different features. Args: analyzer (instance): analyzer instance to be used scs (list): list of (sark) code segments to work on sds (list): list of (sark) data segments to work on Return Valu...
d4a4a395f40a26287b1fd136712b070ed7f3e989
22,743
import operator def merge_sequences(target, other, function=operator.add): """ Merge two sequences into a single sequence. The length of the two sequences must be equal. """ assert len(target) == len(other), 'sequence lengths must match' return type(target)([function(x, y) for x, y in zip(targ...
a1d734c8bceb08c4af7d39d8ad048fdc53cda79d
22,744
def substitute(vars,s): """This function replaces words in percent signs in our in.txt file""" #get rid of things in dollar signs and replace with their corresponding key for key in vars.keys(): s = s.replace("%"+key+"%", vars[key]) return s
e22eb64962ff96bcffe052f5e5ac3784bb343b67
22,745
def getHuffmanCoding( tree, prefix="", code = {} ): """ Projde rekurzivně předaný strom a ohodnotí jednotlivé znaky dle pravidel Huffmanova kódování. To znamená, že hrana jdoucí od svého rodiče nalevo, má ohodnocení 0 a hrana napravo ohodnocení 1. Ohodnocení samotného vrcholu je tvořen posloupn...
691d5c2545a250a7036a878cc90c47c16be22f66
22,746
from typing import Dict from typing import OrderedDict def _scores_to_ranks( *, scores: Dict, reverse: bool = False ) -> Dict[str, float]: """ Go from a score (a scalar) to a rank (integer). If two scalars are the same then they will have the same rank. Takes a dictionary where the keys are the p...
ee86ea631167e043c1c4dabee5d3c316a46d6a68
22,748
import os def strip_path(filepath): """ 'same/path/to/filename.jpg' -> 'filename.jpg' For example usage see doc of file_exists. """ return os.path.split(filepath)[1]
a2c5cb832f71c143bb00310333b0bfd2ceeb2d39
22,750
def get_unique_words(sentences): """ Input: An array of sentences(array of words) obtained after preprocessing Output: A dictionary of unique words, each with an assigned index to define the order """ # A dictionary to track whether a word has been seen before or not dic = {} # Initialize an empty set of ...
797ac7c1effca9b2c085709b6d7c564c3818f084
22,751
def construct_policy(mode, name, value='', vtype=''): """Map the mode and return a list containing the policy dictionary.""" default = { 'policy_type': 'unknown' } policy_map = { 'set_reg_value': { 'policy_type': 'regpol', }, 'delete_reg_value': { ...
c8510729ed9497e4d25ee71be43588ecffd37f49
22,752
def get_resource(requests, reference): """ Fetches a resource. ``reference`` must be a relative reference. e.g. "Patient/12345" """ response = requests.get(endpoint=reference, raise_for_status=True) return response.json()
107fdde1ee4db029b2c279e3548f6969e2e6c16a
22,753
def printTime(t): """ Takes time in seconds, and print in the output in human friendly format (DD:hh:mm:ss) """ t = round(t) if t < 60: return ("%d seconds" %t), (0, 0, 0, t) else: m = int(t/60) s = t%60 if (m < 60) & (m > 1): return ("%d minutes, %d s...
7cb8c5bf225b66b84bd97e9e1ffefc7f905339e8
22,754
from typing import List def get_currencies(self) -> List: """ Shows active currencies list :return: the list of currencies that are active at the moment, with their names as identified in the system """ method = 'GET' api_url = '/api/v1/currency' path = self._host + api_url ...
a9427c34ef96182415ad859a6091f42d33e8dd1d
22,755
import re def sanitizeTitle(title): """Sanitizes the passed title string to allow the file to be saved on windows without introducing illegal characters""" matches = re.findall(r"[^/\\:*?\"<>|]+", title) fullstring = "" for match in matches: fullstring += match return fullstring
26fe9ee3ca5d03eae75a7f9f621c135e318cfeef
22,758
def get_alias(dataset): """Get alias for dataset. Parameters ---------- dataset : dict Dataset metadata. Returns ------- str Alias. """ alias = f"{dataset['project']} dataset {dataset['dataset']}" additional_info = [] for key in ('mip', 'exp', 'ensemble'): ...
36d3322caca81a77301c0b28993e73a186f5bb8a
22,760
import bz2 def compress(data): """ Helper function to compress data (using bz2) """ c = bz2.BZ2Compressor() a = c.compress(data) b = c.flush() return a+b
5d6bbcb357f71f69d80a25803279064c2458333c
22,762
import six def lowercase_value(value): """ Lowercase the provided value. In case of a list, all the string item values are lowercases and in case of a dictionary, all of the string keys and values are lowercased. """ if isinstance(value, six.string_types): result = value.lower() e...
693cbf5477abf0a54dca0e4e6914f6c7bf2d9b46
22,763
import re def check_gline(rnames_line, gline_in, rct_cmpds, sort_rcts=[], verbose= True, map_dict=dict({})): """Function to take a reaction line and a Gstr line and make sure that the reactants in the Gstr line is what are actually are the rcts in the rxn line!!! Will OVERWRITE the Gs-line if differenc...
1394ebfed1e752791284af5a706aea1c73de3ce7
22,764
from pathlib import Path def get_package_list(): """ We get all the package names from which the documentation is available. """ package_list = [] for stuff in (Path().resolve().parent / "code_documentation").glob("*"): if stuff.is_dir(): package_list.append(stuff.name) pac...
35539738dc82190f123f19b5906b1071b4e3d192
22,765
import pkg_resources from typing import Dict def get_package_versions() -> Dict[str, str]: """A utility function that provides dependency package versions At the moment it is and experimental utility. Everything is under try-catch in case something goes wrong :return: A dictionary with versions """ ...
f2eb0569c1ddf887949ed6eeaddb12f80c0c43ba
22,767
def are_checksums_equal(checksum_a_pyxb, checksum_b_pyxb): """Determine if checksums are equal. Args: checksum_a_pyxb, checksum_b_pyxb: PyXB Checksum objects to compare. Returns: bool - ``True``: The checksums contain the same hexadecimal values calculated with the same algorithm. Ide...
533151d79a4f5fabc62d52f9e021b7daf6bd8d71
22,768