content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def plot_feature_importance(feature_keys, feature_importances, ax=None, **kwargs): """ Plot features importance after model training (typically from scikit-learn) Parameters ---------- feature_keys: list of string feature_importances: `numpy.ndarray` ax: `matplotlib.pyplot.axes` Return...
aa3a747002d7c82f91de52e011b269b105c4bb70
9,080
def simulate_timestamps_till_horizon(mu, alpha, beta, Thorizon = 60, \ seed=None, node=None, output_rejected_data=False): """ Inputs: mu, alpha, beta are parameters of intensity function of HP """ ################# # Initialisation ################# rng = default_rng(seed) # get ins...
6d9e7a7c747c7a07fe94069017b32a47e3d35ac2
9,081
import logging import time import torch from datetime import datetime def jp_inference_on_dataset(model, data_loader, evaluator): """ Run model on the data_loader and evaluate the metrics with evaluator. Also benchmark the inference speed of `model.forward` accurately. The model will be used in eval m...
e18113b4fc47bf48562bdee8dc8e4a2bdbe4c884
9,082
def boolToYes(b): """Convert a Boolean input into 'yes' or 'no' Args: b (bool): The Boolean value to be converted Returns: str: 'yes' if b is True, and 'no' otherwise. """ if b: return "yes" else: return "no"
ff94b66b5a166592062bf1d5b286b425e7997304
9,083
def top_symptoms(dic, title): """Find and plot top symptoms in the dictionary based on count Args: dic (dict): Dictionary containing text-count pair Returns: [dictionary]: Top 5 symptoms with their count """ assert isinstance(dic, dict) and len(dic) > 0, "dic is not a nonempty dict...
1acfcec04d2a5c11f7f1a4e90eb9142de042c875
9,084
def _calc_z(h: DataArray, zice: DataArray, zeta: DataArray, s: DataArray, Cs: DataArray, hc: float, Vtransform: int) -> DataArray: """ Calculate grid z-coord depth given water depth (h), iceshelf depth (zice), sea surface (zeta), and vertical grid transformation parameters. Inpu...
6580d3c2825cbea0bba33d03b2c0ad62bbd5b227
9,085
def gap_loss(preds, D, A): """ This module implement the loss function in paper [Azada Zazi, Will Hang. et al, 2019] Nazi, Azade & Hang, Will & Goldie, Anna & Ravi, Sujith & Mirhoseini, Azalia. (2019). GAP: Generalizable Approximate Graph Partitioning Framework. Args: preds (tensor(float)): output ...
9418ee8bda3e7b1a5284c36412fefa158eec0f91
9,086
def number_of_hole(img, hole_img, hole_counter): """ 判斷hole的數量去執行相對應的函式 0個hole執行zero_of_hole 1個hole執行one_of_hole 2個hole執行my_text.set("Answer : 8") 大於2個hole則執行my_text.set("Error : holes number = " + str(hole_counter) + "( > 2 )")) """ switcher = { ...
583fd05b0f10e3ea1c7cee11bd416b8d41d7f840
9,087
def get_merged_by_value_coords(spans_value, digits=None): """returns adjacent spans merged if they have the same value. Assumes [(start, end, val), ..] structure and that spans_value is sorted in ascending order. Arguments: - digits: if None, any data can be handled and exact values are ...
c186c503972b4b48e627c14df77bd5a780b59f5b
9,088
def vint_mask_for_length(length): """ Returns the bitmask for the first byte of a variable-length integer (used for element ID and size descriptors). :arg length: the length of the variable-length integer :type length: int :returns: the bitmask for the first byte of the variable-length integer :rtype: int ...
92fe3cb0fa09713ff4b650349294a2b241bb3918
9,089
from itertools import tee def parse(tokens): """ S-expr ::= ( S-expr* ) | AtomSymbol | ' S-expr ' S-expr = (quote S-expr) """ def _parse(tokens): while True: token = next(tokens) if token == "(": s_expr = [] while True: ...
90c8e3cd8482899749d30d5344390cfd5f24989f
9,090
import numpy import warnings def preproc(raw, dark=None, flat=None, solidangle=None, polarization=None, absorption=None, mask=None, dummy=None, delta_dummy=None, normalization_factor=1.0, empty=None...
9a21af39470b1f48c81d043a1d4a9ca045804093
9,091
import scipy def lB_2_T(lB, T0=298, sigma=4E-10, ret_res=False): """Solves for temperature at given Bjerrum length under condition from Adhikari et al. 2019 that lB/l = 1.2 at 298 K.""" def cond(T, lB, sigma=sigma): """condition function whose root gives the temperature T given Bjerrum length lB.""" ...
73d349d95cd69076874e7147280322535b6b1651
9,092
from typing import Iterable from typing import Union import dataclasses def make_datacls( cls_name: str, fields: Iterable[Union[tuple[str, type], tuple[str, type, dataclasses.Field]]], init: bool = True, **kwargs, ) -> type: """ Return a new dataclass. This function wraps the Python dataclasse...
d3797443212504605310ed75fbcb5ce37570b868
9,093
def square_loss(X, y, theta, reg_beta=0.0): """Computes squared loss and gradient. Based on mean square margin loss. X: (k, n) data items. y: (k, 1) result (+1 or -1) for each data item in X. theta: (n, 1) parameters. reg_beta: optional regularization strength, for L2 regularization. Retu...
3a1cc74eed3abd9c3a7921c9ea02e2169594f504
9,094
def load_graph(model_file): """Loads a TensorFlow graph from file.""" graph = tf.Graph() with graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(model_file, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(o...
41e097afd34631ce8b2b94c9a67121886a568ede
9,097
def find_children(node, tag, xml_ns, ns_key): """ Finds the collection of children nodes Parameters ---------- node : ElementTree.Element tag : str xml_ns : None|dict ns_key : None|str """ if xml_ns is None: return node.findall(tag) elif ns_key is None: retu...
b51d9f588661c3f609dc53adaa328f974e17d5fb
9,098
import re def normalize_string(string, ignore_spaces, ignore_punctuation): """Normalizes strings to prepare them for crashing comparison.""" string = string.upper() if ignore_punctuation: string = re.sub(r"[^1-9a-z \n\r\t]", "", string, flags=re.I) if ignore_spaces: string = re.sub(r"\...
31de2b9644eb0943470430c6c3f2ea8a94dfb3cf
9,099
def word_to_forms(word): """Return all possible forms for a word. Args: word (unicode) Returns: forms (set[unicode]) """ forms = set() lemmas = lemmatize(word) for lemma in lemmas: forms.update(lemma_to_forms(lemma)) return forms
eee7fee2389d180664ff6e07718461043716ba7e
9,100
def load_decamCorners(): """ Returns the CCD corners of the DECam camera. Returns: decamCorners : *list* of *float* A list of the angular degree offsets of the CCD corners. """ with open('%s/DECam_corners.dat' % data_dir) as f: corners_dct = eval(''.join(f.readlines())) ...
5dd58af44029c87db5623dfa38a6223570836665
9,101
def reduce_expr(expr): """ Reduces a boolean algebraic expression based on the identity X + XY = X Args: expr (str): representation of the boolean algebraic expression Returns: A string representing the reduced algebraic expression """ reduced = True ...
2c278e6ea6f133c51c5e98796f288f366fd10cb3
9,102
def arcColor(renderer, x, y, rad, start, end, color): """Draws an arc to the renderer with a given color. The start and end of the arc are defined in units of degrees, with 0 being the bottom of the arc circle and increasing counter-clockwise (e.g. 90 being the rightmost point of the circle). If t...
3297a32236afe2881979b105992df17742dd06c3
9,106
def dos_element_spd( folder, element_spd_dict, output='dos_element_spd.png', fill=True, alpha=0.3, linewidth=1.5, sigma=0.05, energyaxis='x', color_list=None, legend=True, total=True, figsize=(4, 3), erange=[-6, 6], spin='up', combination_method='add', fon...
bf20cee25ace85e91a32f3b05016b0cd34f20600
9,107
import yaml def load(m, schema=UPLOAD_MANIFEST_SCHEMA): """ Load and validate a manifest. """ manifest = yaml.load(m) validate( manifest, schema=schema, ) return manifest
2bdbaf856a476b14b7ca0a353c4cdd56b3de2ae0
9,108
def transform_phenotype(inv_root, y, fam_indices, null_mean = None): """ Transform phenotype based on inverse square root of phenotypic covariance matrix. If the null model included covariates, the fitted mean is removed rather than the overall mean """ # Mean normalise phenotype if null_mean is...
d16699bb04a578050608910a9eea0ee6ea0b450d
9,109
import json import requests def download_site_build(event_file: str, download_path: str = "build-site.tar.gz") -> int: """Will download the site bulid if this is a forked PR bulid. Args: event_file (str): event file from the workflow Returns: int: PR num of the build if relevant """ ...
62250aa4a420a11745b76e41cffd111c7d675a3a
9,110
def createVskDataDict(labels,data): """Creates a dictionary of vsk file values from labels and data. Parameters ---------- labels : array List of label names for vsk file values. data : array List of subject measurement values corresponding to the label names in `labels`. Returns -------...
a4669e4a173aaeef534d13faceaeab869eb62cb3
9,111
def window_partition(x, window_size): """ Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) """ B, H, W, L, C = x.shape #print(x.shape) #print(window_size[0]) x = x.view(B, H // window_size[0], wind...
cfc97230e044f9d3a8fdfa7dde4b17a43f351169
9,112
def _get_unique(node_list, key, mode=None): """ Returns number or names of unique nodes in a list. :param node_list: List of dictionaries returned by Neo4j transactions. :param key: Key accessing specific node in dictionary. :param mode: If 'num', the number of unique nodes is returned. :return...
8f639dfce0efe9f7d40f2bba5f2b8757706cd6d7
9,113
def calculate_cpufreq_weighted_time_in_state( final_time_in_cpufreq_state_by_cpu, time_in_cpufreq_state_by_cpu): """Calculate the weighted average in each CPU frequency state. Args: final_time_in_cpufreq_state_by_cpu: Final time in each CPU frequency state. See the return value of parse_cpufreq_stat...
8f8f3646bbfef89c1d2c3f65d6b3a56b76fb19e4
9,114
from PIL import Image def array2imgdata_pil(A, format='PNG'): """get png data from array via converting to PIL Image""" if A.shape[2] == 3: mode = 'RGB' elif A.shape[2] == 4: mode = 'RGBA' else: mode = 'L' img = Image.fromstring(mode, A.shape[:2], A.tostring()) return p...
f206dc6eaefec2065c10c02b0ecafa5662f9d21c
9,115
def h_eval(data): """ Function takes dictionary Evaluate values and convert string to correct type (boolean/int/float/long/string) """ if isinstance(data, dict): for _k in list(data.keys()): data[_k] = h_eval(data[_k]) if data[_k] is None or (isinstance(data[_k], dic...
28a3529283719cab321c712a9e8723d5ff314ef8
9,116
def _recursive_simplify(expr): """ Simplify the expression as much as possible based on domain knowledge. """ input_expr = expr # Simplify even further, based on domain knowledge: # windowses = ('WIN32', 'WINRT') apples = ("MACOS", "UIKIT", "IOS", "TVOS", "WATCHOS") bsds = ("FREEBSD", "...
40b9dcc6d0a5b176f36ed2e01fc35a005c3c851f
9,117
import uuid def dropzone(url, **kwargs): """Dropzone component A basic dropzone component that supports drag and drop uploading of files which are posted to the URL provided. >>> zoom.system.site = zoom.sites.Site() >>> zoom.system.site.packages = {} >>> zoom.system.request = zoom.utils.Bunc...
d8626b158b8adb738a4f74f6009da93043365cc4
9,118
import math def fmt_bytes(size_bytes): """Return a nice 'total_size' string with Gb, Mb, Kb, and Byte ranges""" units = ["Bytes", "KB", "MB", "GB"] if size_bytes == 0: return f"{0} Bytes" for unit in units: digits = int(math.log10(size_bytes)) + 1 if digits < 4: ret...
40613403092bdc9d8dca8b0b487d5af6c887b075
9,119
from typing import Union import warnings def get_valid_split(records: dict, train_val_test: Union[list, np.ndarray]) -> dict: """ Gets a train, val, test split with at least one instance of every class Keep doing train_test_split until each split of the data has at least one single example of every behavior...
ce575ba0937e32b527e5d70de9855b6fa9f4a686
9,121
def _random_op(sites, ldim, hermitian=False, normalized=False, randstate=None, dtype=np.complex_): """Returns a random operator of shape (ldim,ldim) * sites with local dimension `ldim` living on `sites` sites in global form. :param sites: Number of local sites :param ldim: Local ldimens...
202fe112e896b14abb38a8477afa9eab7689f7f6
9,122
def minimize(system, positions, platform=None, tolerance=1.0*unit.kilocalories_per_mole/unit.angstroms, maxIterations=50): """Minimize the energy of the given system. Parameters ---------- platform : simtk.openmm.Platform or None, optional If None, the global GLOBAL_ALCHEMY_PLATFORM will be use...
d8dc9d1eab96c512aa72da36909490adfa8bbd6f
9,123
import aiohttp async def fetch(url="", headers=DEFAULT_HEADERS, params={}, payload={}, method="GET", loop=None): """fetch content from the url""" if not url: return async with aiohttp.ClientSession(loop=loop, headers=headers) as session: _method = getattr(session, method.lower()) a...
9be522a373532a3452a85ec1e8aae10e7659e999
9,124
import json def retrieve_prefix_fixture(): """Load test fixture data.""" j = json.load(open("./tests/fixtures/s3_prefix_list.json")) return j
5befb33c577263976edee6546bafca40b47e25bb
9,125
def parse_args(version: str) -> Namespace: """ Parse arguments passed to the application. A custom argument parser handles multiple commands and options to launch the desired function. Parameters ---------- version : string A ``string`` of the Bobber version. Returns -----...
20cbacbb611d9495fcd6ad444b258a5588c1bddb
9,126
def grid_reference_to_northing_easting(grid_reference): """ Needs to include reference :param grid_reference: :return: """ grid_reference = grid_reference.strip().replace(' ', '') if len(grid_reference) == 0 or len(grid_reference) % 2 == 1 or len(grid_reference) > 12: return None, No...
3da96e36f9be1e369d0425f2b9c34e432eb5ca77
9,127
def sn_random_numbers(shape, antithetic=True, moment_matching=True, fixed_seed=False): """Returns an ndarray object of shape with (pseudo)random numbers that are standard normally distributed. Parameters ---------- shape : tuple (o, n, m) Generation of array with shape...
ca173cf02f51a8bb6cd976fc84f42597497cd426
9,129
def blue(N: int) -> np.ndarray: """ Blue noise. * N: Amount of samples. Power increases with 6 dB per octave. Power density increases with 3 dB per octave. https://github.com/python-acoustics """ x = white(N) X = rfft(x) / N S = np.sqrt(np.arange(X.size)) # Filter y = irf...
80e0c449f6548b19546a4e58fa3b3e108f21d6df
9,130
from typing import Dict def _remove_attribute(note_dict: Dict, attribute: str) -> Dict: """ Create a copy of the note where a single attribute is removed """ d = dict(note_dict) d[attribute] = None return d
d2659b887c1a2a7c67f6785889db2aa2039f9627
9,131
from pathlib import Path import yaml def get_config(path: str) -> config_schema: """Load the config from the path, validate and return the dcitionary Args: path (str): Path the config.yaml Returns: config_schema: The configuration dictionary """ config_path = Path(path) c...
bf355508b52192eb78857eadedde923b623ecc56
9,132
def compare_chars(first, second): """ Returns the greater of the two characters :param first: :param second: :return: char """ return chr(max(ord(first), ord(second)))
aee1e5767d6ab767bc8da27d382acc105f62d9f5
9,133
import re def find_author(): """This returns 'The NeuroKit's development team'""" result = re.search( r'{}\s*=\s*[\'"]([^\'"]*)[\'"]'.format("__author__"), open("../neurokit2/__init__.py").read(), ) return str(result.group(1))
bcf7fb52021cd23ef48b57aae9444676bc26a862
9,136
from ecpy.utils.util import is_enable_native, _native from ecpy.fields.Zmod import ZmodElement from ecpy.fields.ExtendedFiniteField import ExtendedFiniteFieldElement def tate_pairing(E, P, Q, m, k=2): """ Calculate Tate Pairing Args: E: The Elliptic Curve P: A point over E which has order m Q: A poi...
804f8d9730df010f690b363b658ba59361e87f47
9,137
def kl_loss(img,decoded_img,encoder_log_var,encoder_mu): """ LK loss for VAEs """ kl_loss = -0.5 * tf.reduce_sum( (1+encoder_log_var-tf.exp(encoder_log_var)-encoder_mu**2), axis=[1,2,3],name='klloss' ) return tf.reduce_mean(kl_loss,axis=0)
bd6f644bea86fbc2e5c4426e0e556a432256bb07
9,138
import warnings def steady(L, maxiter=10, tol=1e-6, itertol=1e-5, method='solve', use_umfpack=True, use_precond=False): """ Deprecated. See steadystate instead. """ message = "steady has been deprecated, use steadystate instead" warnings.warn(message, DeprecationWarning) return stea...
36cf008c0b2c773359df5f2251282a2eb12dc613
9,139
def and_intersection(map_list): """ Bitwise or a list of HealSparseMaps as an intersection. Only pixels that are valid in all the input maps will have valid values in the output. Only works on integer maps. Parameters ---------- map_list : `list` of `HealSparseMap` Input list of map...
183df05210cdd29bf5dd0a5654ca08297cb9f72a
9,140
import re def parse(url): """Parses a cache URL.""" config = {} url = urlparse.urlparse(url) # Handle python 2.6 broken url parsing path, query = url.path, url.query if '?' in path and query == '': path, query = path.split('?', 1) cache_args = dict([(key.upper(), ';'.join(val)) f...
48328a0863272f17c8ad1e848af0bb29e0118545
9,141
def states_state(id=""): """ displays a HTML page with a list of cities by states """ states = storage.all(State).values() states = sorted(states, key=lambda k: k.name) found = 0 state = "" cities = [] for i in states: if id == i.id: state = i found = 1 ...
b00bd67a8242a2a21f32226b34df69e214db8856
9,142
def make_tree_item(parent, text, icon, first_col_text=None, second_col_text=None): """ 构造树的子项 :param parent: 要构造子项的父节点元素 :param text: 构造的子节点信息 :param icon: 图标,该元素的展示图标对象 :param first_col_text: 第一列隐藏信息 :param second_col_text: 第二列隐藏信息 """ item = MyTreeWidgetItem(parent) item.setIco...
a93e9d75ac9841c27fa472575054f00e6d1b1cb4
9,143
def get_boundary_condition(name): """ Return a boundary condition by name """ try: return _BOUNDARY_CONDITIONS[name] except KeyError: ocellaris_error( 'Boundary condition "%s" not found' % name, 'Available boundary conditions:\n' + '\n'.join( ...
29ba4d456452cb33cf48c44cace337683d1feab8
9,144
from datetime import datetime import json def run(ts): """ Actually do the hard work of getting the USDM in geojson """ pgconn = get_dbconn('postgis') cursor = pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor) # Look for polygons into the future as well as we now have Flood products # with...
b9e8f853f5d039fa8bb5fdc70a9f281ea94d7e37
9,145
def mtxslv_user_ratings(user_id, dataset): """ Receives user_id and dataset. Look for all occurences of user_id in dataset and returns such subset. If no user_id is found, return an empty numpy array. """ subset = [] # the same thing as I_i (set of item user_id has voted) for it in range(0,np.shape...
7b494b95af316d93e6f9b0a20a351179eb2906b9
9,146
def random_rotation(min, max, prng=DEFAULT_PRNG): """ Construct a random rotation between -max and max. Args min: a scalar for the minimum absolute angle in radians max: a scalar for the maximum absolute angle in radians prng: the pseudo-random number generator to use. Returns ...
58ae95edf57886164e0e123a89534000ef2f8182
9,147
def country_code_from_name(country_names,l3=False): """2 letter ['BE'] or 3 letter codes ['BEL'] from country names Accepts string or list of strings e.g, 'Serbia' or ['Belgium','Slovakia'] Update 3/1/2022: also accepts non uppercase titles, e.g. ['united Kingdom', 'hungary'] Arguments: *co...
d45a48b4f11de383def2817609c6682157de4443
9,148
def steem_amount(value): """Returns a decimal amount, asserting units are STEEM""" return parse_amount(value, 'STEEM')
12ce78e0c9002dd8cd0b136563ad81ab05817ff7
9,149
def get_edge_angle(fx,fy): """エッジ強度と勾配を計算する関数 """ # np.power : 行列のn乗を計算 # np.sqrt : 各要素の平方根を計算 edge = np.sqrt(np.power(fx.astype(np.float32),2)+np.power(fy.astype(np.float32),2)) edge = np.clip(edge, 0, 255) fx = np.maximum(fx, 1e-5) angle = np.arctan(fy/fx) return edge,angle
80c7acc05867b6443aa7b4643d75d4fb79e792a9
9,150
def write_site_pair_score_data_to_file(sorted_data_list, output_file_path, algorithm_used, max_iterations=None, num_threads=None): """Since site indices are starting from zero within python we add one to each of them when they are being written to output file. """ formater = '#' + '='*100 formater +...
5ee4ec97fbc1b6f86e36946ee6d925604858b063
9,151
def cs_2tuple_list(value): """ Parses a comma separated 2-tuple strings into a python list of tuples >>> cs_2tuple_list('') [] >>> cs_2tuple_list('(foobar, "test")') [('foobar', 'test')] >>> cs_2tuple_list('(foobar, "test"), ('"'barfoo', "' lalala) ') [('foobar', 'test'), ('bar...
f6d5b5d440ef524c9c2f2c79f410c432229a8099
9,152
def expectatedCapacityFactorFromDistribution( powerCurve, windspeedValues, windspeedCounts): """Computes the expected capacity factor of a wind turbine based on an explicitly-provided wind speed distribution """ windspeedValues = np.array(windspeedValues) windspeedCounts = np.array(windspeedCounts) ...
fbcea908265cfbfcd9eb49632ac1027538417bfe
9,153
def setup_2d_em_pic(): """ Returns a 2D electromagnetic PIC for testing """ params = { "length": [2 * np.pi, 2 * np.pi], "cells": [32, 32], "dimensions": 2, "nppc": 10, "single_stream": { # defaults for single stream instability "stream_v": ...
136e8e83b63329866dc4c547075dcfd603279de6
9,155
def young_laplace(Bo,nPoints,L): """ Bo = float - Bond number nPoints = int - number of integration points desired L = float - final arc length for range of integration """ #integration range and number of integration points s1=L N=nPoints #set initial values ...
80ceaf8d66e4c309a9f0c16e329c90a26a9b43a0
9,156
import torch def get_uncertain_point_coords_on_grid(uncertainty_map, num_points): """ Find `num_points` most uncertain points from `uncertainty_map` grid. Args: uncertainty_map (Tensor): A tensor of shape (N, 1, H, W) that contains uncertainty values for a set of points on a regular H...
a9d622c232f22359ac030679a49ed6f36345623c
9,157
def amex_credit_card(input_filename, month): """Format is just contents. date, description, amount""" test = _make_month_test(0, month) def transform(xs): return [xs[0], xs[1], '-' + xs[2] if xs[2][0] != '-' else xs[2][1:]] return _csv_transform(input_filename, test, trans...
c60bedd7b0afeda40e1fe9a34e27b0fd796f25f2
9,158
def loadf(file_like, *args, attributes=None, **kwargs): """Read a data file and load it -- scaled -- in memory. This function differs from `read` in several ways: * The output data type should be a floating point type. * If an affine scaling (slope, intercept) is defined in the file, ...
528c11132a83b7d341bb9688a75a4483aa59c155
9,159
from typing import List def _backsubstitution(A: MatrixData, B: List[float]) -> List[float]: """ Solve equation A . x = B for an upper triangular matrix A by backsubstitution. Args: A: row major matrix B: vector of floats """ num = len(A) x = [0.0] * num for i in range(num - ...
789c94842da2b751008e47a1ef661abeaded2da7
9,161
def deiterize(func): """The inverse of iterize. Takes an "iterized" (a.k.a. "vectorized") function (i.e. a function that works on iterables), and That is, takes a func(X,...) function and returns a next(iter(func([X], ...))) function.""" return Pipe(wrap_first_arg_in_list(func), iter, next)
7ef4786ec858f1cbd8fb79b8cfee0e4b03bcb33c
9,162
def ecg_data(rdb, day, patient, time): """ Returns DatFrame to plot ecg signal """ sql = """SELECT * FROM ECG where "Day"='{0}' and "Patient"='{1}' and "Date"::time='{2}' """.format(day, patient, time) try: df = pd.read_sql(sql, rdb) except: df = pd.DataFrame() return df
4a384f920c0fdf45e1818633d2ef125a29b4a562
9,163
def evaluate(data_set_file_or_name, data_format=None, data_directory=None, map_features=None, feature_selection=None, example_filter=None, noisy_preprocessing_methods=None, preprocessing_methods=None, split_data_set=None, splitting_method=None, splitting_fraction=None...
399411ca9560d9e48e73846c9fb70898f028f90a
9,164
def deploy_new_company(company_id): """ Deploy new company contract :param company_id: Company off chain id for deploy :return: True in case of successful, false otherwise """ try: instance = Company.objects.get(pk=company_id) except Company.DoesNotExist: logger.error('Compan...
3871f2ae9948001a1fe24a4c4d2791b7d12f79d7
9,165
import random def MEMB(G,rb,cycle=0): """ It returns a dictionary with {box_id:subgraph_generated_by_the_nodes_in_this_box} The box_id is the center of the box. cycle: Ignore this parameter. Use the default cycle=0. """ adj = G.adj number_of_nodes = G.number_of_nodes() covered_nodes = ...
dfe522aa1e6140e98d32d2eee039aec366d76a8d
9,166
def shownames(namespace, **args): """helper method to generate a template keyword for a namespace""" ctx = args['ctx'] repo = ctx.repo() ns = repo.names[namespace] names = ns.names(repo, ctx.node()) return showlist(ns.templatename, names, plural=namespace, **args)
29105570ad822975c69c7b1d30b94e368d554873
9,168
def only_half_radius( subsampled_radius: float, full_diameter: float, radius_constraint: float ): """ Check if radius is smaller than fraction of full radius. """ assert 0.0 <= radius_constraint <= 1.0 return subsampled_radius <= ((full_diameter / 2) * radius_constraint)
565c301932d5445e8bbb594085e65df63814663a
9,169
def complete_from_man(context: CommandContext): """ Completes an option name, based on the contents of the associated man page. """ if context.arg_index == 0 or not context.prefix.startswith("-"): return cmd = context.args[0].value def completions(): for desc, opts in _pars...
4312ff8323a72a405737a8476cb7ad541dbff718
9,170
def sanitise_description(original: str) -> str: """ Remove newlines from ticket descriptions. :param original: the string to sanitise :return: the same string, with newlines as spaces """ return original.replace("\n", " ")
741aa7df758fb342a0d9a0fa182d24a643f5dbbc
9,171
def dnsdomain_get_all(context): """Get a list of all dnsdomains in our database.""" return IMPL.dnsdomain_get_all(context)
fc7bde05cdb35f60c30943f1ebebdb4217af9467
9,172
def mockselect(r, w, x, timeout=0): # pylint: disable=W0613 """Simple mock for select() """ readable = [s for s in r if s.ready_for_read] return readable, w[:], []
920810aea2f7813885805011d646ddaabfd1901c
9,173
def solve_5c2c9af4(x): """ Required Transformation: The input contains 3 cells with non-zero value. The non-zero valued cells are diagonally positioned with some amount of gap between each non-zero valued cells. The program should identify the colour and their position in the grid and form a squared box...
fcb9701c4bccabe237481ed2acd052b7501abd3f
9,175
def kernel_primitive_zhao_vec(x, s0=0.08333, theta=0.242): """ Calculates the primitive of the Zhao kernel for given values. Optimized using nd-arrays and vectorization. :param x: points to evaluate, should be a nd-array :param s0: initial reaction time :param theta: empirically determined cons...
26cd9230e23f4217ec5a7eee2e8522bef0a40c4e
9,176
def scaled_dot_product_attention(q, k, v, mask): """Calculate the attention weights. q, k, v must have matching leading dimensions. k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v. The mask has different shapes depending on its type(padding or look ahead) but it must be b...
94498a5fd499a09e24a964a6ac975420d702c536
9,178
from typing import List def merge(input_list: List, low: int, mid: int, high: int) -> List: """ sorting left-half and right-half individually then merging them into result """ result = [] left, right = input_list[low:mid], input_list[mid : high + 1] while left and right: result.app...
0d53b0670899b4853563c9dda0eb47a8c66bae00
9,181
def fc_caps(activation_in, pose_in, ncaps_out, name='class_caps', weights_regularizer=None): """Fully connected capsule layer. "The last layer of convolutional capsules is connected to the final capsule layer which has one capsule per output class." We call ...
eb190d36c718d0c518b12c172e2a13b49d7ba012
9,182
def get_optional_relations(): """Return a dictionary of optional relations. @returns {relation: relation_name} """ optional_interfaces = {} if relation_ids('ceph'): optional_interfaces['storage-backend'] = ['ceph'] if relation_ids('neutron-plugin'): optional_interfaces['neutron-...
bdb1dcd04cfd31130e5463772d3d31f8aac7d894
9,183
def splitmod(n, k): """ Split n into k lists containing the elements of n in positions i (mod k). Return the heads of the lists and the tails. """ heads = [None]*k tails = [None]*k i = 0 while n is not None: if heads[i] is None: heads[i] = n if tails[i] is not...
a4a1885ce0c9541c534145d0236996a511cbdd00
9,184
def find_flats(flats, flat2_finder=find_flat2): """Find flat pairs.""" file1s = sorted([item.strip() for item in flats if item.find('flat1') != -1]) return [(f1, flat2_finder(f1)) for f1 in file1s]
7003bc35ef0ed6a4fe71b1d686b7c46b99e6d8ca
9,186
def binary_accuracy(a,b): """ Calculate the binary acc. """ return ((a.argmax(dim=1) == b).sum().item()) / a.size(0)
5f9b09199b2e88169a0cbe9ee7cb4bb351c09e4a
9,187
def add_ice_post_arrow_hq_lq_arguments2(parser): """Add quiver QV threshold to mark an isoform as high-quality or low-quality.""" # if isinstance(parser, PbParser): # #parser = _wrap_parser(parser) # arg_parser = parser.arg_parser.parser # tcp = parser.tool_contract_parser # tcp....
f2fabe409df095be26b4085ccbd635e4ab6ce88a
9,188
def dev_step(tset, train_m, test_m, net, dataset, args, nd_possible_rating_values): """ Evaluates model on a dev set """ batch_size = 256 #print("tset:",tset) user_te = np.array(list(tset.keys())) #print("user_te:",user_te) user_te2 = user_te[:, np.newaxis] #user_te2 = user_te l...
73c77d15d4221a0116454e06f3d7823ffc66a323
9,189
def email_change_view(request, extra_context={}, success_url='email_verification_sent', template_name='email_change/email_change_form.html', email_message_template_name='email_change_request', form_class=EmailChangeForm): """All...
1b54394a04d07bea0d121574b71ba6a1a840f401
9,190
def check_is_pair(record1, record2): """Check if the two sequence records belong to the same fragment. In an matching pair the records are left and right pairs of each other, respectively. Returns True or False as appropriate. Handles both Casava formats: seq/1 and seq/2, and 'seq::... 1::...' an...
225cd65d8c33968556c04a67ba304ebbc65ad4f2
9,191
import bz2 def decompress_bzip2_from_hdu(hdu): """Decompress data in a PyFits HDU object using libz2. """ data = hdu.data.field(0) source_type = np.dtype(hdu.header['PCSRCTP']) return (np.fromstring(bz2.decompress(data.tostring()), dtype=source_type), numpy_...
0fb99decefdc70ae082728c2d5b1228f79d13264
9,192
def grid_values(grid): """ Convert grid into a dict of {square: char} with '123456789' for empties. Args: grid : string A grid in string form. Returns: grid : dict Keys are the boxes (e.g., 'A1'). Values are the values in each box (e.g., '8'). ...
560fb700d6fc91b3ab94c2a5573a82d92ac4eb9d
9,193
from typing import List import re def get_ftp_files(build_type, tag_name, config) -> List[ReleaseFile] : """! @brief Gets file metadata for nightlies hosted on FTP, as determined by config["ftp"] attributes @param [in] `build_type` Unknown str @param [in] `tag_name` Github tag name of the relea...
f56bc55df5a7880f215c3ebd0a1eeb6796840798
9,194
def variables(i, o): """ WRITEME :type i: list :param i: input L{Variable}s :type o: list :param o: output L{Variable}s :returns: the set of Variables that are involved in the subgraph that lies between i and o. This includes i, o, orphans(i, o) and all values of all intermedia...
18f07280dae8471cd9c4f447061342d733e7b3c7
9,195
def ldns_resolver_dnssec_cd(*args): """LDNS buffer.""" return _ldns.ldns_resolver_dnssec_cd(*args)
eeaa2f7e7d385d64c575926f93247ad44594d09e
9,197