content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_tracer(request): """ Utility function to retrieve the tracer from the given ``request``. It is meant to be used only for testing purposes. """ return request['__datadog_request_span']._tracer
facd1ff0922dcc7743814cfd738d022316ba5d6d
30,400
import asyncio import os import sys async def stdio(loop=None): """Set up stdin/stdout stream handlers""" if loop is None: loop = asyncio.get_event_loop() reader = asyncio.StreamReader() reader_protocol = asyncio.StreamReaderProtocol(reader) writer_transport, writer_protocol = await loop...
dd720ac8defec4fe6ac4250aba9367296f987cd6
30,401
def local_self_attention_layer(hparams, prefix): """Create self-attention layer based on hyperparameters.""" return transformer_layers.LocalSelfAttention( num_heads=hparams.get(prefix + "num_heads"), num_memory_heads=hparams.get(prefix + "num_memory_heads"), radius=hparams.local_attention_radius, ...
0b49b116cacdec203f531dfb28b389748a84b9b6
30,402
import pickle def hwtrain(X_csv: str, y_csv: str, model: str = 'lm') -> str: """ Read the feature matrix and label vector from training data and fit a machine learning model. The model is saved in pickle format. Parameters ---------- X_csv The path to the feature ...
fde68a010249859a95264552bfe767f9c4636d7c
30,403
def convert_ban_to_quan(str_ban): """半角转全角""" str_quan = "" for uchar in str_ban: inside_code = ord(uchar) if inside_code == 32: #半角空格直接转化 inside_code = 12288 elif inside_code >= 32 and inside_code <= 126: #半角字符(除空格...
b8e7417c0680dcf113377d32dbb2c43738c0af6c
30,404
import requests def update_user_permissions(userid, profile="grafana", **kwargs): """ Update a user password. userid Id of the user. isGrafanaAdmin Whether user is a Grafana admin. profile Configuration profile used to connect to the Grafana instance. Default is ...
4f5b2ed94896dcb0f7d76b066ed7767700ada682
30,405
def to_xepsilon(_): """ :param _: :return: """ return xepsilon()
69e4e478f3e4d7978cb2a5f76aaf12053458c64a
30,406
def build_permissions_response(): """ Build a response containing only speech """ output = "I'm sorry, I was not able to lookup your home town. "\ "With your permission, I can provide you with this information. "\ "Please check your companion app for details" return { 'outp...
4b01a0fa32958127f7c373b0cedf5d518074e29e
30,407
def simple_tokenizer(text): """ Example for returning a list of terms from text. 1. Normalizes text by casting to lowercase. 2. Removes punctuation from tokens. 3. Returns tokens as indicated by whitespace. """ text = text.lower() # Remove punctuation from file if isinstance(te...
5b26c2dfdb5cc794fd5238e5a2ecdacb18ae1e19
30,408
def progress(*args, **kwargs): """ The HTML <progress> Element is used to view the completion progress of a task. While the specifics of how it's displayed is left up to the browser developer, it's typically displayed as a progress bar. Javascript can be used to manipulate the value of progress ...
f2c41b3b3562485d21c2f1f990f2fa368627c7e7
30,409
def openssl_error(): """Return the OpenSSL error type for use in exception clauses""" return _OpenSSLError
f1782d0cdce002b2214ead438f153631afdf51ab
30,410
def load_path(path, visitor=TokenVisitor): """ Args: path (str): Path to file to deserialize visitor (type(TokenVisitor)): Visitor to use Returns: (list): Deserialized documents """ with open(path) as fh: return deserialized(Scanner(fh), visitor)
e938f08c45737ec60f5258f96ea9d5f08053f99e
30,411
def get_card_names(cards): """ :param cards: List of card JSONs :return: List of card names (str) """ names = [] for card in cards: name = card.get("name") names.append(name) return names
a30ad1ef7d8beaab0451d6f498254b0b5df3cf6d
30,412
import platform def pyversion(ref=None): """Determine the Python version and optionally compare to a reference.""" ver = platform.python_version() if ref: return [ int(x) for x in ver.split(".")[:2] ] >= [ int(x) for x in ref.split(".")[:2] ] else: retur...
2e31c7710b171ad67e56f9dbc1181685e0f32de1
30,413
import tqdm def opt_tqdm(iterable): """ Optional tqdm progress bars """ try: except: return iterable else: return tqdm.tqdm(iterable)
5bcdde21f706f1eb3907beafc9ddeebf6891e0ec
30,414
def get_dataset_config(): """Gets the config for dataset.""" config = config_dict.ConfigDict() # The path to the specification of grid evaluator. # If not specified, normal evaluator will be used. config.grid_evaluator_spec = '' # The directory of saved mgcdb84 dataset. config.dataset_directory = '' # T...
52a026e7c67d09cff9eab3045508f5fb17363db6
30,415
import pathlib import tests import json import yaml def stub_multiservo_yaml(tmp_path: pathlib.Path) -> pathlib.Path: """Return the path to a servo config file set up for multi-servo execution.""" config_path: pathlib.Path = tmp_path / "servo.yaml" settings = tests.helpers.BaseConfiguration() measure_...
572d438f406bb1a1d8ced68be6612dced7cdca9b
30,416
import os def _escape_space(program): """escape spaces in for windows""" if os.name == "nt" and ' ' in program: return '"' + program + '"' else: return program
67a8fa1544f524e9a2591c3221f48c2c130ef86b
30,417
import collections def rename_internal_nodes(tree, pg_dict): """Rename internal nodes (add phylogroups to the name). """ numbers = collections.defaultdict(lambda: 0) for node in tree.traverse("postorder"): if node.is_leaf(): continue pgs = node_to_pg(node, pg_dict) ...
ed77d3d4df42164919a3394fcebc8d49f5bd80eb
30,418
import math import torch import tqdm def assign_by_euclidian_at_k(X, T, k): """ X : [nb_samples x nb_features], e.g. 100 x 64 (embeddings) k : for each sample, assign target labels of k nearest points """ # distances = sklearn.metrics.pairwise.pairwise_distances(X) chunk_size = 1000 ...
31033b8ddf3a2427ec98fdacecb253f6381d38d4
30,419
def _svd_classification(dataset='mnist_small'): """ svd on classificaiton dataset Inputs: dataset: (str) name of dataset Outputs: accuracy on predicted values """ if dataset=='rosenbrock': x_train, x_valid, x_test, y_train, y_valid, y_test = load_dataset('rosenbrock', n...
55eae147130a4552ba33f466f6127ab5df1323b9
30,420
def set_answer(set_number): """ get result answer >>> set_answer(600851475143) 6857 >>> set_answer(3000) 5 """ while True: prime_fac = prime_factorization(set_number) if prime_fac < set_number: set_number //= prime_fac else: return set_numb...
b601a764123b737993c1b822ff466f47ca5caea6
30,421
import torch def model_infer(model, test_images, test_affinities, test_beliefs, args): """ Parameters: model: object with the trained model test_images: batch of images (float32), size: (test_batch_size,3,x,y) test_affinities: batch of affinity maps (float32), size: (test_batch_size,16,x/8,y/8) ...
32534691056c96e3c96adaebfc112da7525ef6dd
30,422
import re def clean_value(value, suffix): """ Strip out copy suffix from a string value. :param value: Current value e.g "Test Copy" or "test-copy" for slug fields. :type value: `str` :param suffix: The suffix value to be replaced with an empty string. :type suffix: `str` :return: Strippe...
d2ec3b3affbf71411039f234c05935132205ae16
30,423
def list_devices_to_string(list_item): """Convert cfg devices into comma split format. Args: list_item (list): list of devices, e.g. [], [1], ["1"], [1,2], ... Returns: devices (string): comma split devices """ return ",".join(str(i) for i in list_item)
717f40d3fd0c24b93d5859491d3f9f16a2b0a069
30,424
def trace_module(no_print=True): """ Trace plot series module exceptions """ mname = 'series' fname = 'plot' module_prefix = 'putil.plot.{0}.Series.'.format(mname) callable_names = ( '__init__', 'data_source', 'label', 'color', 'marker', 'interp', 'li...
b46e69836257de525e55346872f01cb338e036c9
30,425
def get_ids(values): """Transform numeric identifiers, corpora shortcodes (slugs), and two-letter ISO language codes, into their corresponding numeric identifier as per the order in CORPORA_SOURCES. :return: List of indices in CORPORA_SOURCES :rtype: list """ if "all" in values: ids...
482c3940a0a8492820d94d5a9af41c5891c82406
30,426
import click def quiet_option(func): """Add a quiet option.""" def _callback(ctx, unused_param, value): _set_verbosity(ctx, -value) return value return click.option('-q', '--quiet', count=True, expose_value=False, help='Decreases verbosity.', ...
b13dd670cd06136fbccfccff23ed27233efcb7bd
30,427
def _compute_gaussian_fwhm(spectrum, regions=None): """ This is a helper function for the above `gaussian_fwhm()` method. """ fwhm = _compute_gaussian_sigma_width(spectrum, regions) * gaussian_sigma_to_fwhm return fwhm
b5e83752141830911a3d1e26cce10c82b1414740
30,428
from re import T from typing import Optional from typing import Callable from typing import Any from typing import List async def sorted( iterable: AnyIterable[T], *, key: Optional[Callable[[T], Any]] = None, reverse: bool = False, ) -> List[T]: """ Sort items from an (async) iterable into a n...
628336093c282f340f3ad2f750227e1286ceefef
30,429
def config_split(config): """ Splits a config dict into smaller chunks. This helps to avoid sending big config files. """ split = [] if "actuator" in config: for name in config["actuator"]: split.append({"actuator": {name: config["actuator"][name]}}) del(config["actua...
2006534ece382c55f1ba3914300f5b6960323e53
30,430
def transl(x, y=None, z=None): """ Create or decompose translational homogeneous transformations. Create a homogeneous transformation =================================== - T = transl(v) - T = transl(vx, vy, vz) The transformation is created with a unit rotation...
d3b47af2ea8f130559f19dea269fbd1a50a8559c
30,431
def find_next_square2(sq: int) -> int: """ This version is just more compact. """ sqrt_of_sq = sq ** (1/2) return -1 if sqrt_of_sq % 1 != 0 else int((sqrt_of_sq + 1) ** 2)
62246b78cc065b629961a7283671e776481a8659
30,432
import colorsys def hex_2_hsv(hex_col): """ convert hex code to colorsys style hsv >>> hex_2_hsv('#f77f00') (0.08569500674763834, 1.0, 0.9686274509803922) """ hex_col = hex_col.lstrip('#') r, g, b = tuple(int(hex_col[i:i+2], 16) for i in (0, 2 ,4)) return colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)
a80e9c5470dfc64c61d12bb4b823411c4a781bef
30,433
from pathlib import Path def _drivers_dir() -> str: """ ドライバ格納ディレクトリのパスを返します :return: ドライバ格納ディレクトリのパス """ return str(Path(__file__).absolute().parent.parent.joinpath('drivers'))
45b173099f6df24398791ec33332072a7651fa4f
30,434
import types def create_list_response_value( *, authorization: types.TAuthorization, uri: types.TUri, auth_info: types.CredentialsAuthInfo, ) -> types.TResponseValue: """ Calculate the response for a list type response. Raises NotFoundError when the uri is not linked to a known spec. ...
492d5a93b7db393dafde48c66d323dda64c7e32c
30,435
def get_variables(expr): """ Get variables of an expression """ if isinstance(expr, NegBoolView): # this is just a view, return the actual variable return [expr._bv] if isinstance(expr, _NumVarImpl): # a real var, do our thing return [expr] vars_ = [...
6326ae90f0fa6daa04e0dedc95cf52f4081fa359
30,436
def tousLesIndices(stat): """ Returns the indices of all the elements of the graph """ return stat.node2com.keys() #s=stat.node2com.values() global globAuthorIndex global globTfIdfTab #pprint(globAuthorIndex) #pprint(stat.node2com.values()) #glob node->index return [glo...
fa847ee3913d521778ee3462c8e946f0ff001c76
30,437
def edit_tx_sheet(request, sheet_id): """Allows the user to edit treatment sheet fields and updates the date of the sheet""" tx_sheet = get_object_or_404(TxSheet, id=sheet_id) form = TxSheetForm(instance=tx_sheet) if request.user == tx_sheet.owner: if request.method == 'POST': for...
04ef22e069cc329d4eceae5ae567867fb31f787c
30,438
import warnings def system( W, L_x, L_sc_up, L_sc_down, z_x, z_y, a, shape, transverse_soi, mu_from_bottom_of_spin_orbit_bands, k_x_in_sc, wraparound, infinite, sc_leads=False, no_phs=False, rough_edge=None, phs_breaking_potential=False): """Create zigzag system Parameters ...
101f3fffeb333cb9c53c2ef930e17fa0f7e08966
30,439
import os def list_files(root_dir, mindepth = 1, maxdepth = float('inf'), filter_ext=[], return_relative_path=False): """ Usage: d = get_all_files(rootdir, mindepth = 1, maxdepth = 2) This returns a list of all files of a directory, including all files in subdirectories. Full paths are returned....
8df0e009f40e77ef7ed86ef870a9f1e508d876d5
30,440
def get_state_x1_pure_state_vector() -> np.ndarray: """Returns the pure state vector for :math:`|-\\rangle`. :math:`|-\\rangle := \\frac{1}{\\sqrt{2}} (|0\\rangle - |1\\rangle)` Returns ------- np.ndarray the pure state vector. """ vec = (1 / np.sqrt(2)) * np.array([1, -1], dtype=n...
81d52d34492a0b57206d3cf55ceb9dd939a7cdf8
30,441
def user_create(user_data): """ Cria um usuário no banco de dados e retorna o objeto criado """ user_model = get_user_model() user = user_model.objects.create_user(**user_data) return user
163c742601d25a7b04e572ea6b32de6625b99de5
30,442
from typing import Counter def shannon_entropy(text: str) -> float: """ same definition as in feature processor for feature extraction calculates shannon entropy of a given string """ content_char_counts = Counter([ch for ch in text]) total_string_size = len(text) entropy: float = 0 fo...
e3092f8620b809a3d935ad16290d077122f6b1df
30,443
def solve(inputmatrix): """ This function contains a solution to the data in 4be741c5.json posed by the Abstraction and Reasoning Corpus (ARC). The problem presents an n x m grid, with some rows containing 0-m coloured squares with repetition over a row or colomuns. The solution req...
33f27b9bd57ce00972d8c29e7ae3a0ac71dd2455
30,444
def compute_rewards(s1, s2): """ input: s1 - state before action s2 - state after action rewards based on proximity to each goal """ r = [] for g in TASKS: dist1 = np.linalg.norm(s1 - g) dist2 = np.linalg.norm(s2 - g) reward = dist1 - dist2 r.append(rew...
1a6ee67ce581dc07d735e15fe62d09561cf0453f
30,445
import ipaddress def decode(i_dunno): """ Decode an I-DUNNO representation into an ipaddress.IPv6Address or an ipaddress.IPv4Address object. A ValueError is raised if decoding fails due to invalid notation or resulting IP address is invalid. The output of this function SHOULD NOT be presented to huma...
557da5af7b33d988754f67ecd4574be9bdc85784
30,446
def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X: A numpy array of shape (N, D) containing a minib...
01a85b6af46f5baf25b2e73b1b52cc9026d79fb6
30,447
def location_descriptors(): """Provide possible templated_sequence input.""" return [ { "id": "NC_000001.11:15455", "type": "LocationDescriptor", "location": { "sequence_id": "ncbi:NC_000001.11", "interval": { "start...
da13824ff6f91caa635700759a29fb1f36aae1be
30,448
from typing import Optional def positional_features_gamma(positions: tf.Tensor, feature_size: int, seq_length: Optional[int] = None, bin_size: Optional[int] = None, stddev=None, ...
20dc2154a194d99ec1a9931e10fca2b43d360a6e
30,449
from typing import List def _get_frame_data(mapAPI: MapAPI, frame: np.ndarray, agents_frame: np.ndarray, tls_frame: np.ndarray) -> FrameVisualization: """Get visualisation objects for the current frame. :param mapAPI: mapAPI object (used for lanes, crosswalks etc..) :param frame: the ...
65f3733e858f595877af83e0574bb53c5568390c
30,450
def calculate_gc(x): """Calculates the GC content of DNA sequence x. x: a string composed only of A's, T's, G's, and C's.""" x = x.upper() return float(x.count('G') + x.count('C')) / (x.count('G') + x.count('C') + x.count('A') + x.count('T'))
aae64ff550ef26e75518bdad8a12b7cda9e060d2
30,451
import os def listdir(path): """ Lists content of a folder. :param str path: Folder to get list from :returns: Directory content list :rtype: tuple example:: dirs, files = xbmcvfs.listdir(path) """ dirs = [] files = [] path = safe_path(path) for item_name in os.l...
c82dfa985eb2003278d16fa7c7df3a1e2c83a948
30,452
def no_float_zeros(v): """ if a float that is equiv to integer - return int instead """ if v % 1 == 0: return int(v) else: return v
a33321408c43d164a8ca2c7f1d1bc6270e5708ec
30,453
import torch def quat_mult(q_1, q_2): """Multiplication in the space of quaternions.""" a_1, b_1, c_1, d_1 = q_1[:, 0], q_1[:, 1], q_1[:, 2], q_1[:, 3] a_2, b_2, c_2, d_2 = q_2[:, 0], q_2[:, 1], q_2[:, 2], q_2[:, 3] q_1_q_2 = torch.stack( ( a_1 * a_2 - b_1 * b_2 - c_1 * c_2 - d_1...
dac82e246221f9af552f44ca26089443b8eaadd7
30,454
def _flip_dict_keys_and_values(d): """Switches the keys and values of a dictionary. The input dicitonary is not modified. Output: dict """ output = {} for key, value in d.items(): output[value] = key return output
b861fc3bd194d26ee05b9a56faad3394939064bf
30,455
from typing import Tuple from typing import Optional def set_dative_bonds( mol: Chem.rdchem.Mol, from_atoms: Tuple[int, int] = (7, 8) ) -> Optional[Chem.rdchem.Mol]: """Replaces some single bonds between metals and atoms with atomic numbers in fromAtoms with dative bonds. The replacement is only done if t...
8e67732e7f10ac273e51a0ae1b3f6c3cff27b291
30,456
from typing import Optional def _b2s(b: Optional[bool]) -> Optional[str]: """转换布尔值为字符串。""" return b if b is None else str(b).lower()
6030b7fd88b10c4bdccd12abd1f042c518e8a03f
30,457
from typing import Set def color_csq(all_csq: Set[str], mane_csq: Set[str]) -> str: """ takes the collection of all consequences, and MANE csqs if a CSQ occurs on MANE, write in bold, if non-MANE, write in red return the concatenated string NOTE: I really hate how I've implemented this :p...
1e6792bf446799a4c4c22770c7abfc1718c88516
30,458
def hasattrs(object, *names): """ Takes in an object and a variable length amount of named attributes, and checks to see if the object has each property. If any of the attributes are missing, this returns false. :param object: an object that may or may not contain the listed attributes :param n...
f3a2fc308d041ed0de79e3389e30e02660a1d535
30,459
def pano_stretch_image(pano_img, kx, ky, kz): """ Note that this is the inverse mapping, which refers to Equation 3 in HorizonNet paper (the coordinate system in the paper is different from here, xz needs to be swapped) :param pano_img: a panorama image, shape must be [h,w,c] :param kx: stretching a...
f5b151e3e124e3333304b8ff6c217971fb10ba35
30,460
def blue_process(infile, masterbias=None, error=False, rdnoise=None, oscan_correct=False): """Process a blue frame """ # check to make sure it is a blue file ccd = ccdproc.CCDData.read(infile, unit=u.adu) try: namps = ccd.header['CCDAMPS'] except KeyError: namps = ccd.header['CCD...
c3b251a3ae99031b54e8dc5af4d5c95511f31c75
30,461
def _rand_sparse(m, n, density, format='csr'): """Helper function for sprand, sprandn""" nnz = max(min(int(m*n*density), m*n), 0) row = np.random.random_integers(low=0, high=m-1, size=nnz) col = np.random.random_integers(low=0, high=n-1, size=nnz) data = np.ones(nnz, dtype=float) # duplicate ...
08221cdc9798e0ddf9266b5bf2ca3dfe21451278
30,462
import os def return_filepath_or_absent(acl_id): """ Forms a file path from the acl id, checks if it is present in the input directory, and returns either the full file path or None (NaN)""" filepath = '{}/{}.txt'.format(acl_filepath, acl_id) if os.path.exists(filepath): return filepath el...
184d3498b1e47818fdbee7beb386dd2b5e807ff1
30,463
import random def _generate_trace(distance): """ 生成轨迹 :param distance: :return: """ # 初速度 v = 0 # 位移/轨迹列表,列表内的一个元素代表0.02s的位移 tracks_list = [] # 当前的位移 current = 0 while current < distance - 3: # 加速度越小,单位时间的位移越小,模拟的轨迹就越多越详细 a = random.randint(10000, 12000)...
6ce298de2a1977c7662f83346e7554c546b41131
30,464
import sqlite3 def update_nt_uid_acc(cachepath, uid, accession): """Update nt UID GenBank accession.""" # Path must be string, not PosixPath, in Py3.6 conn = sqlite3.connect(str(cachepath)) results = [] with conn: cur = conn.cursor() cur.execute(SQL_UPDATE_UID_ACC, (accession, uid)...
45c9514ffeca9281269c8f27ac09b3b863de2eff
30,465
def bool_env(env_val): """ check for boolean values """ if env_val: if env_val in TRUE_LIST: return True if env_val in FALSE_LIST: return False # print("Return:%s" % env_val) return env_val else: if env_val in FALSE_LIST: return Fa...
afb9d2f35c6469a1fd6f32250376b94a05db1de0
30,466
import json def try_parse_json(json_): """Converts the string representation of JSON to JSON. :param str json_: JSON in str representation. :rtype: :class:`dict` if converted successfully, otherwise False. """ if not json_: return False try: return json.loads(json_) excep...
077819cf82e307aacf3e56b11fbba26a79559968
30,467
def svn_ra_get_file(*args): """ svn_ra_get_file(svn_ra_session_t session, char path, svn_revnum_t revision, svn_stream_t stream, apr_pool_t pool) -> svn_error_t """ return _ra.svn_ra_get_file(*args)
2e887ace5ed3538ac7f3e401be9fa71ddfc100cc
30,468
def version_microservices(full=True): """ Display Zoomdata microservice packages version. CLI Example: full : True Return full version. If set False, return only short version (X.Y.Z). .. code-block:: bash salt '*' zoomdata.version_microservices """ ms_version = '' ms...
aff0ece640e33e2d880c3e4a13ad7e13911aaa68
30,469
import os def permissions(file): """ Returns the permissions for a given file. """ octal = {'0': 'no permission', '1': 'execute', '2': 'write', '3': 'write and execute', '4': 'read', '5': 'read and execute', '6': 'read and write', '7': 'read, write and execute'} permissions = {} correct_path =...
a304f2549e41afb6c5b24cf845da689fdd62f99a
30,470
import os def gatk_variant_recalibrator(job, mode, vcf, ref_fasta, ref_fai, ref_dict, annotations, hapmap=None, omni=None, phase=None, dbsnp=None, mills=None, ...
5de437d43b2e146c191be2baf06e0e552b241638
30,471
import os def generate_times(fnames, sat_id, freq='1S'): """Construct list of times for simulated instruments Parameters ---------- fnames : (list) List of filenames. Currently, only the first is used. Does not support multi-file days as of yet. sat_id : (str or NoneType) ...
9d033868167544053b9e0f669838a29442338f9b
30,472
def KGCOVID19( directed = False, preprocess = "auto", load_nodes = True, load_node_types = True, load_edge_weights = True, auto_enable_tradeoffs = True, sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None, cache_sys_var = "GRAPH_CACHE_DIR", version = "current", **kwargs ) -> Graph: """...
24e419d80cd9634f5dab352f37db1fd6a19661d2
30,473
def _cryptodome_encrypt(cipher_factory, plaintext, key, iv): """Use a Pycryptodome cipher factory to encrypt data. :param cipher_factory: Factory callable that builds a Pycryptodome Cipher instance based on the key and IV :type cipher_factory: callable :param bytes plaintext: Plaintext data to ...
99774fe7d4e4783af68e291213823096b9c2ac50
30,474
def is_gh_online(): """ Check if GitHub is online. The different services of GitHub are running in seperat services and thus just being GitHub online does not mean, that required parts are online. """ return _is_online("github.com", "/", 200, "OK")
8c5dc7090f9d851e5b5c303ffa376da5f926202a
30,475
import math def get_items_with_pool( source_key: str, count: int, start_index: int = 0, workers: int = 4 ) -> Items: """Concurrently reads items from API using Pool Args: source_key: a job or collection key, e.g. '112358/13/21' count: a number of items to retrieve start_index: an ...
cbf07015872fc72bfa0e70be5c6a4553e5bef363
30,476
import torch def batch_data(words, sequence_length, batch_size): """ Batch the neural network data using DataLoader :param words: The word ids of the TV scripts :param sequence_length: The sequence length of each batch :param batch_size: The size of each batch; the number of sequences in a batch ...
871ecfbcec2d142074bf2341fb0fb51c74c75227
30,477
from typing import Tuple def calc_portfolio_holdings(initial_investment: int, weights: pd.DataFrame, prices: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame]: """ Calculate the initial portfolio holdings given am amount of cash to invest. :param initial_investment: The initial investment used to purchas...
7adf46894b27c679eec16f94a80bcad3c7539c88
30,478
def ford_fulkerson(G, s, t, capacity='capacity'): """Find a maximum single-commodity flow using the Ford-Fulkerson algorithm. This is the legacy implementation of maximum flow. See Notes below. This algorithm uses Edmonds-Karp-Dinitz path selection rule which guarantees a running time of `O(nm^2)`...
dd8e8e351829feb98cd144f4148f8c9bf62cb239
30,479
def index(): """ Show the main page of Stream4Flow :return: Empty dictionary """ # Do not save the session session.forget(response) return dict()
531c10ca17406086fcf14a5dfcdcecce5cc60119
30,480
from typing import Type def create_temporary_table_sql(model: Type[Model]) -> str: """ Get the SQL required to represent the given model in the database as a temporary table. We cache the results as this will be called for each request, but the model should never change (outside of tests), so we ...
3074b4e6bb0c9147faa9da3243d0d66a3fee7517
30,481
def field_paths(h5, key='externalFieldPath'): """ Looks for the External Fields """ if key not in h5.attrs: return [] fpath = h5.attrs[key].decode('utf-8') if '%T' not in fpath: return [fpath] path1 = fpath.split('%T')[0] tlist = list(h5[path1]) pa...
578e1a2d0971a94afa665f368e9b72c8f6e449d3
30,482
def get_quantifier(ch, input_iter): """ Parse a quantifier from the input, where "ch" is the first character in the quantifier. Return the minimum number of occurrences permitted by the quantifier and either None or the next character from the input_iter if the next character is not part of the...
36dea445aa416be79e86bb1e7c6f9dbe454c6c2a
30,483
from typing import List def get_defined_vars( operation: "OperationDefinitionNode", ) -> List["VariableNode"]: """ Retrieve a list of VariableNode defined inside the variableDefinitionNode list of an OperationDefinitionNode :param operation: the operation definition node to look through :type ope...
f39cd2b205bdfba5347884e9b675949e08877a5f
30,484
def snv(img): """ standard normal variates (SNV) transformation of spectral data """ mean = np.mean(img, axis=0) std = np.std(img, axis=0) return (img - mean[np.newaxis, ...])/std[np.newaxis, ...]
63c549f1e319ab4cc4b4beb4ea602b136d71168f
30,485
def fredkin(cell: int, live_count: int, neighbors: Neighbors = None) -> int: """\"Fredkin\" Game of Life rule This rule can be specified using these strings: - ``B1357/S02468`` - ``2468/1357`` - ``fredkin`` Parameters ---------- cell: int Value of the current cell. ...
ef08d99fa90c6d615bf3aabd6a4fe72903ecfb62
30,486
def mad(arr): """ Median Absolute Deviation: a "Robust" version of standard deviation. Indices variabililty of the sample. https://en.wikipedia.org/wiki/Median_absolute_deviation """ arr = np.ma.array(arr).compressed() # should be faster to not use masked arrays. med = np.median(arr) ...
f02919fcb082c815602d8b57cb59d5c71cb6a219
30,487
def get_logs_directory(): """Return path of logs directory""" LDAModel_directory = get_LDAModel_directory() logs_directory = LDAModel_directory / 'logs' if not logs_directory.is_dir(): create_directory(logs_directory) return logs_directory
eb37ca64a07280d55584ac0146b6babc02051b3d
30,488
def svn_ra_rev_proplist(*args): """ svn_ra_rev_proplist(svn_ra_session_t session, svn_revnum_t rev, apr_hash_t props, apr_pool_t pool) -> svn_error_t """ return apply(_ra.svn_ra_rev_proplist, args)
2f6c1f25f6b62d1306aa746dc0dc04f39370aa0e
30,489
from re import DEBUG def gen_poly_model(XVALS, DATA_FLAT, degree: int = 15, debug: bool = DEBUG): """Polynomial fit model for data calculation. Uses np.polynomial.polyfit. Args: XVALS (array_like): one-dimensional array of x-values of data. DATA_FLAT (array_like): one-dimensional array of y-v...
1372aae35ad5999c40dd99a65cb8d8e65bd9c6cb
30,490
from datetime import datetime def parse_date(s): """ Given a string matching the 'full-date' production above, returns a datetime.date instance. Any deviation from the allowed format will produce a raised ValueError. >>> parse_date("2008-08-24") datetime.date(2008, 8, 24) >>> parse_date("...
d21ab8b08d52bf155d5e8af192f19036307568b5
30,491
def setup_config(quiz_name): """Updates the config.toml index and dataset field with the formatted quiz_name. This directs metapy to use the correct files Keyword arguments: quiz_name -- the name of the quiz Returns: True on success, false if fials to open file """ try: ...
28aba9399926f27da89953c8b0c6b41d95a12d96
30,492
def unitary_connection(h_pre, h_post, n_pre, n_post, X): """ Gives the connectivity value between the n_pre unit in the h_pre hypercolumn and the n_post unit in the h_post column """ hits_pre = X[:, h_pre] == n_pre hits_post = X[:, h_post] == n_post return np.sum(hits_pre * hits_post)
d272b92abfed50d7f89c2d4b40ff3c4e5a417d5e
30,493
def mase(y, y_hat, y_train, seasonality=1): """Calculates the M4 Mean Absolute Scaled Error. MASE measures the relative prediction accuracy of a forecasting method by comparinng the mean absolute errors of the prediction and the true value against the mean absolute errors of the seasonal naive mode...
7373ef660ae9784ecd83a83457c143debb721685
30,494
def _resize_along_axis(inputs, size, axis, **kwargs): """ Resize 3D input tensor to size along just one axis. """ except_axis = (axis + 1) % 3 size, _ = _calc_size_after_resize(inputs, size, axis) output = _resize_except_axis(inputs, size, except_axis, **kwargs) return output
a7cc206171ffe1cf6df22da3756cefcc6c5fcd86
30,495
def getTournamentMatches(tourneyId): """ Return a dictionary from match id to match data for a tournament. """ if tourneyId not in matchDatas: refreshMatchIndex(tourneyId) return matchDatas[tourneyId]
a6d5386e9034b126405aedee75ba36b1718c3dc9
30,496
def compute_protien_mass(protien_string): """ test case >>> compute_protien_mass('SKADYEK') 821.392 """ p={'A':'71.03711','C':'103.00919','D':'115.02694','E':'129.04259','F':'147.06841','G':'57.02146','H':'137.05891','I':'113.08406','K':'128.09496','L':'113.08406','M':'131.04049','N':'114.04293...
86a3ffd0ce3e95fcdf6d510d2865b35aeb93d779
30,497
import logging def find_duration(data): """Finds the duration of the ECG data sequence Finds the duration by looking at the last time value as the first value is always at time = 0 seconds :param data: 2D array of time sequences and voltage sequences :return: Time duration of data sequence ...
e65135457e23886c402e0671d720fe9c5ed257a1
30,498
def response(data, **kwd): """Returns a http response""" return HttpResponse(data, **kwd)
8d88295751ee5f53f99ea8a134d01e1df7cb1fd5
30,499