content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def from_bar(bar): """ Generate DbBarData object from BarData. """ db_bar = dict( index = bar.datetime, volume = bar.volume, open_int = bar.open_interest, open = bar.open_price, high = bar.high_price, low = bar.low_price, close = bar.close_price ...
eacb71333234f80bcc3d73264798f928ca1052e6
630,120
def merge_latest_price(data_point): """ For any record in get_ticker_data, flat map the latest price data into the object itself :param data_point: :return: """ sorted_price_list = sorted(data_point['price_list'], key=lambda l: 0 if l['last_updated'] is None else l...
9b4dac2f8eab4e0e1f88b8385663a7613eb9d514
630,121
def read_file(filename): """De read_file functie leest het bestand in dat is meegegeven. Het returnt een lijst met daarin elke rij van de sudoku als geneste lijst. """ with open(filename) as f: return [[int(i)for i in line.split()] for line in f]
1a3fab9b156a10e03e2b9fd3b772fb733f9e995a
630,122
def _lookup_enum_in_ns(namespace, value): """Return the attribute of namespace corresponding to value.""" for attribute in dir(namespace): if getattr(namespace, attribute) == value: return attribute
542228608ee601220e9993d073f14dc430c9a8e6
630,123
def is_instance_or_subclass(x, cls): """Return True if ``x`` is either a subclass or instance of ``cls``.""" try: return issubclass(x, cls) except TypeError: return isinstance(x, cls)
278c6c885b96f2f2acc37662c6a9091f90ef7b6a
630,124
import re def infer_extensions(key, ext): """guess extensions if possible""" # Handle special case of hive partitions # see https://www.qubole.com/blog/direct-writes-to-increase-spark-performance/ if re.fullmatch(r".c\d{3,5}", ext) or re.fullmatch(r".*-c\d{3,5}$", key): return ".parquet" r...
ddd1a9a804c721a72d00ca7ed879a45da16ddff0
630,125
from sys import getsizeof def detail_prop(self, prop_name, tab_level=1): """Detail the content of the property""" tab = "" for _ in range(tab_level): tab += " " mem_str = "" prop = getattr(self, prop_name) for attr in dir(prop): if ( # Not method no...
6bb213237ad4c7d83f6f8bf49ae0f1f3eb69033f
630,126
def three(data, known): """ >>> known = easy_ones(SAMPLE) >>> three(SAMPLE, known) 'fbcad' """ len5 = list(filter(lambda d: len(d) == 5, data[0])) for digit in len5: if ( len(set(digit) - set(known[7])) == 2 and len(set(digit) - set(known[4])) == 2 ): ...
9045be6f79f4695e58c4dc2776b5d47366981ca7
630,127
def is_host(ip): """ Checks whether an address is a subnet address or a single address :param ip: ip address or subnet :return: True if host """ r = ip.split("/") if len(r) > 1: return False return True
2daf11ce81376a1045d11241ffb62e50e1b45817
630,128
def get_ssa_def(mlil, var): """ Gets the IL that defines var in the SSA form of mlil """ return mlil.ssa_form.get_ssa_var_definition(var)
56953dc0d2cbd76d06134322692e3f7e37f00800
630,129
def __getmappinglabel__(mapping, value): """ Gets index of label value in mapping. :param mapping: mapping dictionary :param value: value for which the mapping is searched for :return: index of value in mapping """ if value in mapping["labels"]: return mapping["labels"].index(value) ...
e6911d789cb61064fbd2a286ec659bc48e49bc98
630,130
import argparse def parse_args(): """Parse arguments. Returns: args: The parsed arguments. """ parser = argparse.ArgumentParser( description='Convert an obj 3D Description file ' 'into a urdf file with collision convex meshes.') parser.add_argument('--input', ...
e91bec29c20845a4226015fbfad0a761c0714451
630,131
def _strip_frbr_section_from_pnx(pnx_xml): """ We must strip the frbr section from a PNX record before re-inserting it """ for frbr_section in pnx_xml.findall('frbr'): pnx_xml.remove(frbr_section) return(pnx_xml)
bcc3f45a0cf8f787602c9b3d861ad8c69d2c198d
630,132
import re def __parameterize(parameters): """Convert multi-word parameter/value pairs to a dictionary.""" parameters = re.sub(r"\s*=\s*", r"=", parameters) # Remove gaps between keys and values pattern = re.compile(r"([A-z]+)=") params = {} match = pattern.match(parameters) while match is no...
ec69515e11a6b2fe9a8b36675d9add38ce09a621
630,133
def gupdate(fields, indx): """ Update winning outcome totals """ tnumb = indx for game, _ in enumerate(fields): val = tnumb % 2 tnumb //= 2 fields[game][val] += 1 return fields
92e77e6d21b000c63c74e074a62218f5f153894c
630,134
def speed_func(t_n): """ Returns the normalised velocity U(t)/U0. """ return min(1,t_n)
dfebbb3420900d8df120b2b4de362a5bf0b349bd
630,136
import subprocess import time def wait(machine='localhost', sleep=1): """ Subroutine which returns when all jobs on the remote machine have finished. Checks the status of the jobs every <sleep> minutes. The method works in the same way a human would, by examining the output of fab <machine> stat. ...
75565f0b55971b86fc5142e93545d1505ae9538d
630,137
def motion_0(input_line, cur, count): """Go to the first character of the line. See Also; `motion_base()`. """ return 0, False, False
06c72b7c8563315c9b0da6f2aeaa3ab1a649be33
630,138
def getFileConfigHash(ConfigPathFile): """ return the path where is stored the hash used to received data from the server : string """ FileConfigHash = "doc/hash_config.txt" line = "" line_split = "" with open(ConfigPathFile) as conf: for line in conf: line_split = line.s...
6b7b534f99dc0f26e40d884534bce5a4988829b4
630,139
def dataParseTabDelToColumns(inputdata,headerline): """Creates a python dictionary of lists corresponding to columns of data in the line seperated input (uses tabs '\t' to split columns)""" headercolumns=inputdata[headerline].replace('\n','\t').split('\t') datadict={} for i in range(len(headercolumns)):...
90e5c80471013a79ddbf07563272b3b9ad88004c
630,140
def IsInRangeInclusive(a, low, high): """ Return True if 'a' in 'low' <= a >= 'high' """ return (a >= low and a <= high)
08729cc281c3465e37d9e52b1b31935fcd713288
630,141
import sys import importlib def _get_deps_info(): """Overview of the installed version of main dependencies Returns ------- deps_info: dict version information on relevant Python libraries """ deps = ["pip", "setuptools", "Cython"] def get_version(module): try: ...
f62b79d2c9e775ffe2d4279fc62e053c2fd649ba
630,142
def qualify(name, prefix): """ Qualify a property name with the given prefix """ return "{prefix}:{name}".format(name=name, prefix=prefix)
a32cc1b7544220364eeb74005ed856cf2570619c
630,143
def bulk_of_jsons(d): """Replace serialized JSON values with objects in a bulk array response (list).""" def _f(b): for index, item in enumerate(b): if item is not None: b[index] = d(item) return b return _f
30a6488f44c5d7d06a5fb5800647db98bcff1783
630,144
import copy def filterSubPaths(pathGraph={}): """ Given a Graph of Paths, filter out SubPaths What is a SubPath? In this graph {'query1': ['a', 'b'], ['a', 'c'], ['a', 'b','c','d']] ['a','b'] is a SubPath of ['a','b','c','d'] Preconditions: Graph in Xaya Format Keys are selections ...
bdb9fb01990508b8a3a00df51379afbc853c8612
630,145
def get_dataset_features(dataset): """ Takes in the name of a dataset and returns the relevant parameters """ groups_to_drop = [] if dataset == 'COMPAS': path = 'datasets/compas-scores-two-years.csv' label = 'two_year_recid' # binary group = 'race' # 'sex' also an option ...
1dc0793b4f398c8f8bc88d8c9a6bea5090b41354
630,146
import string def preprocess_article(text): """ Changes an articles text to lowercase, removes punctuation """ return text.encode('ascii', 'ignore').lower().replace("\n", "").translate(None, string.punctuation)
b3a67951ef9c66e7b77041ce2fa0cb7a0223bca6
630,147
def padded_slice_filter(value, page_number): """ Templatetag which takes a value and returns a padded slice """ try: bits = [] padding = 5 page_number = int(page_number) if page_number - padding < 1: bits.append(None) else: bits.append(pag...
5ae3134c5a7e49b1bacbe57f88bf8045a9b71b48
630,148
import csv def read_csv(path): """Input a two column csv. Groups second column entries based on matching texts in the first column """ answers = [] #descriptions images = [] #image titles with open(path, 'rU') as csvfile: reader = csv.reader(csvfile) index = 0 for row in reader: im = (row[0]) both...
9d299a53990f3df173d452dba8989d501952f1d7
630,149
import copy def replace_with_element(pending_iterable, pattern_tuple): """ 对于可迭代对象根据提供的模式进行元素值替换 @日期: 过去的某个时刻 @作者: 徐嘉辉 Args: pending_iterable: 可迭代对象 pattern_tuple: 模式元组(待替换元素,用于替换元素,待替换元素,用于替换元素...) Returns: 返回替换完毕的原可迭代对象的列表副本 """ # 判断pattern_tuple长度是否为偶数 ...
1838c57b10aabe6cb53cb678f6e963545abd8edd
630,150
import array def up(scanline, previous, filter_unit): """Undo up filter.""" scanline_length = len(scanline) if previous is None: previous = array.array('B', [0] * scanline_length) return array.array('B', [scanline[index] + previous[index] & 0xff for index in range(scanline_length)])
eed8f4e08cc196f8ed0a7ded51a22914eb69abc7
630,151
def _break(s, find): """Break a string s into the part before the substring to find, and the part including and after the substring.""" i = s.find(find) return s[:i], s[i:]
fd4ec716795c971194ffe692682e0dd9f7701fd3
630,152
import math def phi(x): """ phi functino is the cumulative density function (CDF) of a standard normal (Gaussian) random variable. It is closely related to the error function erf(x). https://www.johndcook.com/erf_and_normal_cdf.pdf From: https://www.johndcook.com/blog/python_phi/ """ ...
64ec2796b7866034b16a75b10e1c0e9bc8a34b11
630,153
def lucas(n): """ overview of lucas """ prev = 2 current_lucas = 1 if (n + 1) == prev: return(prev) else: for i in range(n - prev): prev, current_lucas = current_lucas, (prev + current_lucas) return(current_lucas)
64ec3fc58057e6e65eb1acb99b5ab086108d2dae
630,154
def merge(first, *second, **third): """ merge :param first: 参数一 :param second: 参数二 :param third: 参数三 :return: 字符串拼接结果 """ result = first for s in second: result += s for k, v in third.items(): result += k return result
c1e8491e951e6c98f8323f8ee55c61c59b097cb2
630,156
def id_name(module, operand): """Return a pretty-printed name for the ID.""" if operand in module.id_to_symbol_name: return module.id_to_symbol_name[operand] elif operand in module.type_id_to_name: return module.type_id_to_name[operand] else: return str(operand)
35e82d5322fd71ea7585e58db2af61c9cfea1ef2
630,157
import re from typing import List def find_arxiv_id(string: str) -> str: """ Try to extract an arxiv id from a string. Looking for one of two forms: 1. New form -- 1603.00324 2. Old form -- hep-th/0002839 Parameters ---------- string : str String in which to perform t...
a9385980cdbb932fe4c3255c0a00b5bf5555a0bf
630,158
def get_entrypoint_name(): """Returns the entry_point name which will be registered when installing the package. Returns: str: entry_point name which will be used to register when installing this package. """ return "matlab_proxy_configs"
268c9ecc02b55c0d82ab5949a26cbf7a9cd02a99
630,159
from typing import Union def soring_date2target(sorting_date: Union[int, float]) -> int: """Convert `sorting_date` to `target`. If `sorting_date` <= 1600 then `target` is 0. If 1600 < `sorting_date` <= 1700 then `target` is 1. If 1700 < `sorting_date` <= 1800 then `target` is 2. If 1800 < `sortin...
83fb60e99b08579e63d1d6f52d25e4a9991c41a7
630,160
def _get_short_lang_code(lang: str) -> str: """Returns an alternative short lang code""" return lang if "zh" in lang else lang.split("-")[0]
bb9eb45b6015acc7657e06bcf6c22f9673a6415b
630,161
def custom_error_name_func(func_name, kwargs): """Disregard `func` argument, use the error only.""" return '{func_name}__{error_type}'.format( func_name=func_name, error_type=kwargs['error'].__name__ )
cc6cbe9a4d77642760af20bdbd3a01d254fe36e0
630,162
def thirdMax(self, nums): # ! 64ms """ :type nums: List[int] :rtype: int """ nums.sort() num_set = list(set(nums)) num_set.sort() if len(num_set) < 3: return num_set[-1] return num_set[-3]
6da26006095e696e749220b5b07bbdfcb5248d2d
630,163
import struct import io def _update_image_flash_params(esp, address, args, image): """ Modify the flash mode & size bytes if this looks like an executable bootloader image """ if len(image) < 8: return image # not long enough to be a bootloader image # unpack the (potential) image header ma...
63a358c2f6728246781fcf3240e40f87cfc51119
630,164
def get_zamid_n(zamid): """Gets the number of neutrons (n) from a nuclide's z-a-m id. Parameters ---------- zamid: str z-a-m id of a nuclide """ a = int(zamid[-4:-1]) z = int(zamid[:-4]) return a - z
0011ff511243c8b30dc257d661f4492ddf77c364
630,165
def _all_in_set_(cands, s): """ Test if all elements of 'cands' are in set 's' """ if len(cands) == 0: return False for c in cands: if not c in s: return False return True
07ffa7d6d10fe60313c6308374b55802ea9c5ea5
630,168
def test_4(self, request): """Test 4: Fortunes""" fortunes = [f.to_dict() for f in self.query()] fortunes.append({ 'id': 0, 'message': 'Additional fortune added at request time.' }) return {'fortunes': sorted(fortunes, key=lambda x: x['message'])}
a5ae12e2024d88c47bd003f133faf774d89cb0f8
630,169
def is_post(request): """Check request is a POST""" return request.method == 'POST'
fab3cc2205db7555978fd3e56b404976f89b11b7
630,171
import torch def generate_runs(data, run_classes, run_indices, batch_idx, batch_few_shot_runs=100): """ Generates a few-shot run. Args: data: data to be used for the few-shot run run_classes: classes of the few-shot run run_indices: indices of the few-shot run batch_idx: in...
6248f3a3418e8f35e20dc9e045d827c228a9fe98
630,172
def arb_step_mock(context): """No real reason, other than to mock the existence of a run_step.""" return 'from arb step mock'
53f3ec7ddcdf3c4b94918f428514dd589ee749ac
630,173
def increment_bytes(val: bytes) -> bytes: """increment a bytes value""" length = len(val) int_val = int.from_bytes(val, byteorder="big") int_val += 1 return int_val.to_bytes(length, byteorder="big")
4b826322bd63e02e4df38ec2916911e8d6af5e70
630,174
def drop_complements(list_all, values): """ Identify and remove complements. Parameters ---------- list_all : List of tuples. Tuples with combinations. values : List. All relevant values. Returns ------- list_wo_compl : List of Tuples. List_all with complements removed. """ ...
34b15d6c80139865b55d1719904a17275134396c
630,176
def f_TU_P_aux(r_intmit): """タンクユニットの補機の消費電力を求める関数 (27) Args: r_intmit(ndarray): 1時間平均のヒートポンプユニットの断続運転率 Returns: ndarray: タンクユニットの補機の消費電力 (W) """ return 5 + 10 * r_intmit
85e3d522812d20a32d3a105132807440691a7b27
630,177
import torch def load_state(filename): """ Loads the PyTorch files saved at ``filename``, converting them to be able to run with CPU or GPU, depending on the availability on the machine. """ if torch.cuda.is_available(): return torch.load(filename) else: return torch.load(filen...
0ec77e2ab4aae2d54f84ebe37f68487650dcd70e
630,179
def emscripten_test_linkopts(): """Emscripten-specific linkopts for unit tests.""" return [ "-s ASSERTIONS=2", "-s ENVIRONMENT=node,shell,web", "-s ERROR_ON_UNDEFINED_SYMBOLS=1", "-s DEMANGLE_SUPPORT=1", "-s EXIT_RUNTIME=1", "-s ALLOW_MEMORY_GROWTH=1", ]
ab888a33e3d9df63405bd0c724e687f3238c6230
630,180
import torch def batchify(fn, chunk): """Constructs a version of 'fn' that applies to smaller batches. """ if chunk is None: return fn def ret(inputs): return torch.cat([fn(inputs[i:i+chunk]) for i in range(0, inputs.shape[0], chunk)], 0) return ret
5539d92fe9c1413cbb3d20bb96a17459b3671b54
630,181
def lmap(function, *iterables): """ >>> lmap(pow, (2, 3, 10), (5, 2, 3)) [32, 9, 1000] """ return list(map(function, *iterables))
f3dcb19a222da743f1a32f69870a300a1eecddaa
630,182
def _error_connection_handler(sock, client_addr, header): """ utility handler that does nothing more than provide a rejection header @param sock: socket connection @type sock: socket.socket @param client_addr: client address @type client_addr: str @param header: request header @type h...
d69ca5d9e6731a7ef3e22ed2ac6eaa0d471600ae
630,183
import os def get_test_cpc(): """ Return the CPC name of the CPC to be tested. This is taken from the value of the 'TESTCPC' environment variable. If that variable is not set or empty, `None` is returned. Returns: string: Name of CPC to be tested, or `None` if no CPC has been defined. ...
bd923611d66f0993715541a35d2fa87ea50c5e70
630,184
def butlast(thing): """ BUTLAST wordorlist BL wordorlist if the input is a word, outputs a word containing all but the last character of the input. If the input is a list, outputs a list containing all but the last member of the input. """ if isinstance(thing, str): return thin...
4f59c38dc8e79c6d3690ba1b645a3b21ba2c01b1
630,185
from typing import List from typing import Tuple import random def get_noises(trajectory_len: int, noise_magnitude: float, random_seed: int) -> List[Tuple[float, float]]: """ Get `trajectory_len` noise values where each noise value is a tuple (noise_0, noise_1), noise_i is a Gaussian white noise generated fro...
576fbcdb2996cccfcedf064cf378484f39981b5f
630,186
def bsuccessors(state): """Return a dict of {state:action} pairs. A state is a (here, there, t) tuple, where here and there are frozensets of people (indicated by their times) and/or the light, and t is a number indicating the elapsed time.""" here, there, t = state if 'light' in here: retu...
fa1a585248579a498b0324600217d1616f825a07
630,187
import functools def listify(f): """Decorator to turn generator results into lists""" @functools.wraps(f) def wrapper(*args, **kwargs): return list(f(*args, **kwargs)) return wrapper
57d071d0d6be866c40f48d019ff16aa0b827f8a3
630,188
def chinese_leap(date): """Return 'leap' element of a Chinese date, date.""" return date[3]
4124b3c4a647894e96d3c32cd81113b79da0191a
630,189
from typing import Any from pathlib import Path def json_encoder_default(obj: Any) -> Any: """Convert Home Assistant objects. Hand other objects to the original method. """ if isinstance(obj, set): return list(obj) if hasattr(obj, "as_dict"): return obj.as_dict() if isinstance...
e62909018eeb337054a8d8b21220a5c41c5d14da
630,190
def get_starting_model(interaction_dict, verbose=False): """Returns as a starting model one of the CustomModel of the chain with more recorded interactions""" if verbose: print("Selecting best interaction from where to start modeling...") max_len = 0 interaction_key = None for key in interac...
7747d23883628a17b55c6f73eb9660c63a1e692e
630,191
def build_class(): """__build_class__: Low level class maker. Prefer types.new_class(...).""" return __build_class__(lambda: None, 'NiceClass')().__class__.__name__
40d773eb9a45a318479c4e29a78bf2df5aa89e4d
630,192
def scale(X, min=0, max=1): """Scale X to given range. Parameters ---------- X : np.array of shape=(n_samples, n_features) Data to scale. min : float, default = 0 Minimum value to scale to. max : float, default = 1 Maximum value to scale...
b2895bf3b7330c454e5db1baaf627e294d2ff836
630,194
from typing import List def _get_abc_from_superclass_name(qualified_superclass_name: str) -> str: """ Get the corresponding abstract base class name """ qualified_abc_name_list: List[str] = qualified_superclass_name.split(".") qualified_abc_name_list.insert(1, "abc") return ".".join(qualified_...
69ff9e76068ad3ddcc96e21e62e53eba6ff10864
630,195
def problem_found(status): """ Check if there is an Rfam issue. """ return str(bool(status["has_issue"]))
d03bae3fd985c9ebf75ef0b605355fc2cd1283a8
630,196
def get_bin_list(n, nmax): """ return a list of digits of the binary representation of n nmax is the maximum theoretical value of n, used to add 0 at the front of the list if necessary """ if n == 0: return [0 for _ in range(len(bin(nmax))-3)] n = bin(n) digits = [] for i in rang...
3fa8d1a7e7e025f24ccca4fc287f5a96add937fe
630,197
from typing import Union def lbytes(filepath: str) -> Union[bytes, bytearray]: """Read bytes from file path :param filepath: filepath as as string to read bites from :return: some bytes... """ with open(filepath, "rb") as file: return file.read()
316bf2e0011aa83ae489b83e1f7f24b762624441
630,200
def filter_methods(standardized_methods, methods_to_filter): """ Filters a standardized methods DataFrame on methods name :param pd.DataFrame standardized_methods: Dataframe constituted by one or many method(s) aggregated, ie. constituted of several columns representing impact categories no...
2b0b8fb0a5dae8648b99247e9793ddec6b1813e0
630,201
import torch def compute_confusion_matrix(true, pred): """Computes a confusion matrix using numpy for two np.arrays true and pred. """ true = true + 1 pred = pred + 1 K = 3 result = torch.zeros((K, K)) for i in range(K): for j in range(K): result[i][j] = torch.sum((...
6df65b0cb68e1cbeac228909aec2ac84bff4d27d
630,202
def fpassthru(space, args_w): """ fpassthru - Output all remaining data on a file pointer """ if len(args_w) != 1: space.ec.warn("fpassthru() expects exactly " "1 parameter, %d given" % len(args_w)) return space.w_False w_res = args_w[0] if w_res.tp != space.tp_file...
111bce8442357c6f4bd0ec7ab715c0049125b926
630,203
def _unfold_parallel(lists, n_jobs): """Internal function to unfold the results returned from the parallization Parameters ---------- lists : list The results from the parallelization operations. n_jobs : optional (default=1) The number of jobs to run in parallel for both `fit` and...
e62b819965328c143d20fb4db134aeb053e1b2d6
630,204
def low(self): """Low edge of first bin. :returns: low edge of first bin :rtype: float """ ax = self.GetXaxis() return ax.GetXmin()
c23c886df8e39ae2fda47e2d28faa5b2d2d42264
630,205
def make_missing_swift_child(child): """ Generates a Swift call to make the raw syntax for a given Child object. """ if child.is_token(): token = child.main_token() tok_kind = token.swift_kind() if token else "unknown" if token and not token.text: tok_kind += '("")' ...
a47a6280c8c4c32a92736214a27e3d77b6fad89c
630,206
def form_name_entries_special(pos, provenance, pw_id, pw_entry, kb_id, kb_entry): """ Create name match entries :param pos: :param pw_id: :param pw_entry: :param kb_id: :param kb_entry: :return: """ entries = [] for pw_name in set(pw_entry['aliases']): entries.append(...
31a7111dcd7259dc199c354b6322a527222434ee
630,207
def is_list(klass): """ Determine whether klass is a List """ return klass.__origin__ == list
ffb30cb7ff225f4772904eb038bb083951760d5d
630,210
from typing import OrderedDict def trim_source(source_map, context): """ get part of a source listing, with extraneous indentation removed """ indent_type = None min_indent = 9000 for ln in context: (snippet0, *meta0), *remaining_line = source_map[ln] if snippet0.startswith('...
b824601b9e00e414d7546175af0582e70789dd69
630,212
def findclosest(list, value): """Return (index, value) of the closest value in `list` to `value`.""" a = min((abs(x - value), x, i) for i, x in enumerate(list)) return a[2], a[1]
e994fb9b421474347de91eea812543d45c370080
630,213
def ipvalid(ipstring): """ checks string for validity as IP address input: single string output: - list of intergers if valid - UserWarning if invalid >>> ipvalid("10.0.0.0"); Analysing ip address ip address is valid [10, 0, 0, 0] """ iplist = ipstring.split("."...
26c61ab49de3b3f2a47283f15ad47d18f880b2a5
630,214
def true(*ignore, **everything): """Give True regardless of the input.""" return True
c4dc5a2e458b8f181798c0923d7a1e8546f94bbd
630,215
import socket import contextlib def find_free_port() -> int: """ :return: a free port; mind that this is not multi-process safe and can lead to race conditions. """ skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) with contextlib.closing(skt): skt.bind(('', 0)) _, port = skt...
bc71b9b59e5d0e1e669a311a9b1f4fa95ea47c7f
630,216
def isket(state): """Checks whether a state is a ket based on its shape. Args: state (:obj:`jnp.ndarray`): input state Returns: bool: ``True`` if state is a ket and ``False`` otherwise """ return state.shape[1] == 1
421587d90657fcc746b88dbac4052ae8bed7c2ca
630,217
def kmerize_orf(orf, k, t): """ Creates kmers of certain size and type from provided sequence. :param orf: nucleotide sequence :param k: size of a kmer :param t: type of a kmer, i.e. 'simple', 'all' or 'codon' :return kmers: list of kmers """ kmers = [] if t == 'simple': sto...
0b06e21e478db592ed92a97a2e197c34aa9223c3
630,218
def _downsample(n_samples_in, n_samples_out): """Compute downsample rate""" downsample = int(n_samples_in // n_samples_out) if downsample < 1: raise ValueError("Number of samples should always decrease") if n_samples_in % n_samples_out != 0: raise ValueError("Number of samples for two co...
b016cc3c304568774b1aec874ceece902909379e
630,219
def overlap_distance(p1, p2): """Measures the distance between two sequences of symbols. The distance beetween two sequences is measued as the number of symbols that has to be concatenated to the second, and equally many removed from the start of the sequence, to transform it to the second sequenc...
370d54f8b3f792e6c6bb41c8118626a1671e4007
630,220
def clean_str(s: str) -> str: """ Remove characters the pronouncing library can't handle. Parameters: s (str): The string to sanitize. Returns: The sanitized string. """ DEL_CHARS = ["(", ")", "[", "]", "{", "}", ",", ":", ";", "."] SWAP_CHARS = [("-", " ")] for char in DEL_CHARS: s = s.replace(char,...
763b897b4a58ab273d72f3577dce5e86aca72879
630,222
def get_features(): """ returns features from medicare part b data which is everything but the label. the label is in the exclusion column """ return [ 'provider_type', 'description_flag', 'drug_name', 'generic_name', 'bene_count', 'total_claim_cou...
f5dde465cbb50c5d7eb193080864ec0780abfd90
630,223
import platform def get_hostname(): """ returns the hostname of the current host """ return str(platform.node()).split(".")[0]
18e820d43106005110353ff373963d44189c4940
630,224
import pkg_resources import json def load_vocabularies(project): """Load project vocabularies from json file. Load from project json data files all accepted values for facets. Args: project (str): data project Returns: a series of lists (list): one for each facets, elements are acce...
3b960ce13e2c4320349bbfe44d8236338a153ca4
630,225
def vecs2tuples(vecs): """ Convert list of vectors into set of tuples """ return set(tuple(v) for v in vecs)
f28eb164032666f65bc9122269520f8b9324089d
630,228
def mat_mul(mat1, mat2, MOD=0): """ Multiplies two matrices If value of MOD is provided the find remainder wrt MOD """ arr = [[0 for i in range(len(mat2[0]))] for j in range(len(mat1))] for i in range(0, len(mat1)): for j in range(0, len(mat2[0])): for k in range(0, len...
2c97e2adb9607c3462aa89fc29e2ae87bf281931
630,230
def unliteral(lit_type): """ Get base type from Literal type. """ if hasattr(lit_type, '__unliteral__'): return lit_type.__unliteral__() return getattr(lit_type, 'literal_type', lit_type)
c5d800eb93bc5f9f49ea42539a52a1379e9fefc6
630,231
def __decorator_boolval(fn): """ 将形如'true' 或 'false'的字符串装换为 Python中的布尔值,如果不是则返回原值 """ def wrapper(*args, **kwargs): r = fn(*args, **kwargs) if isinstance(r, str): if r.lower() == 'true': return True elif r.lower() == 'false': return False ...
392670c15c2d99a891e9e49c2e144886a10d5b12
630,232
import torch def rifeat(points_r, points_s): """generate rotation invariant features Args: points_r (B x N x K x 3): points_s (B x N x 1 x 3): """ # [*, 3] -> [*, 8] with compatible intra-shapes if points_r.shape[1] != points_s.shape[1]: points_r = points_r.expand(-1, poin...
862f4fd3b527acc056488392cf20c2ee54a1f5a1
630,234
def fib_memory_flash(n): """采用缓存(内存,不永久)的方式求值""" data = {0: 0, 1: 1, 2: 1} for i in range(n + 1): if i not in data: data[i] = data[i - 1] + data[i - 2] return data[n]
e1151032822b7ce8bf38e695e2ef6947b0b57b4b
630,235
def top_basemap_layer_url(layers): """Returns the URL of the top map layer if it exists""" if layers[-1].is_basemap and len(layers) > 1: return layers[-1].url return None
2484b1afb319f3650f24f89487dfda9ffb18864d
630,236
def registracija_get(): """Prikaži formo za registracijo.""" return {'napaka' : None, 'up_ime' : None }
625a797d93143062113b60476310e865393bd229
630,237