content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def register_multi_sampler(name): """ A decorator with a parameter. This decorator returns a function which the class is passed. """ name = name.lower() def _register(sampler): if name in _registered_multi_sampler: raise ValueError("Name {} already chosen, choose a different ...
109f4c715e3fc5bc10679d6754d51563d1040f65
3,625,000
from datetime import datetime def overview(): """Shows an overview page""" # get a list of clients for the side bar clients = redshift.get_sponsored_client_list(cache) # get a list of all possible locales and countries locales = redshift.get_all_locales(cache) countries = redshift.get_all_co...
ebef91b226a573b1f59f05aa9285f4e8461cf275
3,625,001
import logging def get_attention_logger(file_path): """ Make python logger """ logger = logging.getLogger("attention") log_format = '%(message)s' formatter = logging.Formatter(log_format) file_handler = logging.FileHandler(file_path) file_handler.setFormatter(formatter) logger.addHandler(...
ee7767e86066a7f07fb251613367119aba2e59f0
3,625,002
import time def _acquire_lease_memcache(cache_arn, correlation_id, steps, retries, timeout=LEASE_DATA.LEASE_TIMEOUT): """ Acquires a lease from memcache. # https://www.quora.com/What-is-the-best-way-to-implement-a-mutex-on-top-of-memcached # http://martin.kleppmann.com/2016/02/08/how-to-do-distribute...
2dfbcd1d0c18699594e942f7b2c1470a9de446fa
3,625,003
from typing import List def transformer_tok2vec_v2( name: str, get_spans, tokenizer_config: dict, transformer_config: dict, pooling: Model[Ragged, Floats2d], grad_factor: float = 1.0, ) -> Model[List[Doc], List[Floats2d]]: """Use a transformer as a "Tok2Vec" layer directly. This does not a...
bb51b8e00cce5b92ffd1bf1e3f9c5f2d5a87cc69
3,625,004
def piece_together_fourth(Dp, Wp): """ Take the skew and symmetric parts of a algorithmic tangent and piece them back together """ sym_id = 0.5*(np.einsum('ik,jl', np.eye(3), np.eye(3)) + np.einsum('jk,il', np.eye(3), np.eye(3))) skew_id = 0.5*(np.einsum('ik,jl', np.eye(3), np.eye(3)) - np.einsum('jk,il', n...
fc386d688f0e571b3b184621885be100b5cd2306
3,625,005
def to_ragged_seq_set(data): """Convert dataset from mapping/array of sequences to lists of mappings of sequences.""" # data is a dict if is_mapping(data): new_data = {} for name, datum in data.items(): if not is_sequence_set(datum): # all sequences must at le...
5b8cce9846d861c564a23a77fe8a7ae03e3cdf8a
3,625,006
def get_atoms_list(mmtf_dict): """Creates a list of atom dictionaries from a .mmtf dictionary by zipping together some of its fields. :param dict mmtf_dict: the .mmtf dictionary to read. :rtype: ``list``""" return [{ "x": x, "y": y, "z": z, "alt_loc": a or None, "bvalue": b, "occupancy": o, ...
3b5f29362c077585ebc659b8d8a9ff5d60908ead
3,625,007
import traceback def register_augmentation(name): """Registers an augmentation. This decorator allows vertview to instantiate an augmentation from a configuration file. To use it, apply this decorator to an AugmentationBase2D subclass, like this: .. code-block:: python @register_augmentation(...
601ea1df05997ba46687d4e8e828be1254c3b29d
3,625,008
def get_os_fingerprint(data): """ Get the most accurate OS fingerprint for the given Data object, if any. :param data: Data object to query. :type data: Data :returns: Most accurate OS fingerprint. If no fingerprint is found, returns None. :rtype: OSFingerprint | None """ # Ge...
baca5b40cff177d8534f68d2334698852937caf2
3,625,009
def ring(symbols, domain, order=lex): """Construct a polynomial ring returning ``(ring, x_1, ..., x_n)``. Parameters ========== symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (non-empty) domain : :class:`~diofant.domains.domain.Domain` or coercible order : :class:`~diofant.polys.po...
d26eaf26d2b4c87c5b6e70d87dbf0b4bae80aace
3,625,010
def trimesh_swap_edge(mesh, u, v, allow_boundary=True): """Replace an edge of the mesh by an edge connecting the opposite vertices of the adjacent faces. Parameters ---------- mesh : :class:`compas.datastructures.Mesh` Instance of mesh. u : int The key of one of the vertices of ...
43f150bb52b1f4a9180f6c40a9d420fbe5e67e30
3,625,011
def perc_col_nans(col): """ Returns the percent of NaNs of a specific column in the dataset. Parameters: col (pandas Series): Column in the dataset Returns: col_perc_nans (float): Percent of NaNs in col """ col_perc_nans = count_col_nans(col) / len(col) return...
66db913b1299a280e867ff05bd8e438c25c03861
3,625,012
import os import contextlib import shutil def set_up_directory(day): """Make a new directory for working on an advent of code problem Args: day: int day of the month to work on Returns: new_dir: str path to the directory for that day """ this_dir = os.path...
ba76d4abe7ab40517adcfd54af66b8946df31886
3,625,013
def get_string(key): """ Get localized string. First, try language as set in config. Then, try English locale. Else - raise an exception. :param key: string name :return: localized string """ lang = strings.get(Config.BOT_LANGUAGE) if not lang: if not strings.get("en"): ...
90089fbe8bbbdfc0f1aa6560197489cbfb76f41a
3,625,014
def prompt_vial_range(): """Prompt user for first and last vial of run""" first_ic_vial = int(input('First IC vial? ')) last_ic_vial = int(input('Last IC vial? ')) return first_ic_vial, last_ic_vial
bf5cf536c0aae3808bf16dd6d87a9d83bfbdab04
3,625,015
import logging def precision_k_curve(y_true, y_pred, max_k=0): """ Calculate precision@k for various values of k. y_true indicates the products that the user actually interacted with. it must be a 'multilabel-indicator'. If max_k is zero, precision@k is calculated for all values of k from 1 to numbe...
74d13ef014afeca12e27fa40bec37d4fd81e556b
3,625,016
from collections import defaultdict def getFollowupPhotometry(candidate, djangoRawObject = None, conn = None): """Use the query followupPhotometryQuery but organise the data for plotting""" # We need to create a dictionary of filters which contain arrays of the data. # It's messy to do this from scratch,...
d4f496360cdfde82f4dc81bb199374606929137f
3,625,017
def generate_random_map( size=6, p=0.7, num_pseudo_rewards=0, only_optimal_pseudo_rewards=True ): """Generates a random valid map (one that has a path from start to goal) :param size: size of each side of the grid :param p: probability that a tile is empty :param num_pseudo_rewards: number of tiles ...
b50ce1575e0b8715b0ac4f271f3cf741e8a22b6f
3,625,018
def approx_count_distinct(col, rsd=None): """Returns a new :class:`Column` for approximate distinct count of ``col``. >>> df.agg(approx_count_distinct(df.age).alias('c')).collect() [Row(c=2)] """ sc = SparkContext._active_spark_context if rsd is None: jc = sc._jvm.functions.approx_count...
7e7736db6c1ecf7d7b2476fd13f5698498aa3cff
3,625,019
def VLBAGetSumCC(image, err, CCver=1, logfile='', check=False, debug=False): """ Sum fluxes in a CC table Sums the flux densities in a CC Table on an image Returns sum Returns with err set on error * image = Image with CC table * err = Python Obit Error/mes...
c7bc0d84d895db2b4e2521311cb9b2c6f6d6a613
3,625,020
def private_mean(x, epsilon, sum_sensitivity): """ Computes a private mean with privacy budget epsilon using the given sensitivity. :param x: Vector over which the mean will be computed. :param epsilon: The privacy budget. :param sum_sensitivity: The sensitivity of the sum calculation. :ret...
3b400c17e1fa9b899d1b322291459724cd6cece8
3,625,021
from vtk import vtkImageData def make_child_dataset(dataobject): """Creates a child dataset with the same size as the reference_dataset. """ new_child = vtkImageData() new_child.CopyStructure(dataobject) input_spacing = dataobject.GetSpacing() # For a reconstruction we copy the X spacing from ...
a7e460f21564559f4731df76c978eac3a951dbe7
3,625,022
def calc_residuals(Amat,Bvec,coeffs,perconf=False): """Calculate residuals and other performance metrics""" residuals = [] matmul = Bvec - Amat*coeffs residuals = matmul*627.51 r2 = 1-sum(residuals**2)/sum((Bvec*627.51)**2) rel_MAE = sum(abs(residuals))/sum(abs(Bvec*627.51)) if perconf: ...
fbeb72688f4e58dcca85b425be2ef0460a3cfcac
3,625,023
def bucket_by_sequence_length(data_reader, example_length_fn, bucket_boundaries, bucket_batch_sizes, trainer_nums, trainer_id): """Bucket entries in dataset by lengt...
4adfe4f0780b4e97934b6715ab9227e3647a2592
3,625,024
from typing import Any from typing import Dict def get_overridable_parameters(config: Any) -> Dict[str, param.Parameter]: """ Get properties that are not constant, readonly or private (eg: prefixed with an underscore). :param config: The model configuration :return: A dictionary of parameter names an...
9dbe89416d4dd0f232f3f714fc652bcb18ec80cc
3,625,025
def compute_score(sent, sents): """Computes the average score of sent vs the other sentences (the result of sent vs itself isn't counted because it's 1, and that's above UPPER_BOUND)""" if not len(sent): return 0 return sum(compare_sents_bounded(sent, sent1) for sent1 in sents) / float( ...
ba3e0a16551daba922e87de6698f8e95494b01cd
3,625,026
def computeCentroids(X, idx, K): """ returns the new centroids by computing the means of the data points assigned to each centroid. It is given a dataset X where each row is a single data point, a vector idx of centroid assignments (i.e. each entry in range [1..K]) for each example, and K, the n...
d21a5acd3ba481a9864a016dcfe79b629147f788
3,625,027
def async_track_time_interval_backoff(hass, action, intervals) -> CALLBACK_TYPE: """Add a listener that fires repetitively at every timedelta interval.""" if not iscoroutinefunction: _LOGGER.error("Action needs to be a coroutine and return True/False") return if not isinstance(intervals, (l...
be7d3619b9ddc8336251fb50196a74ab9f58c36b
3,625,028
import shlex def grr_grep(line): """Greps for a given content of a specified file. Args: line: A string representing arguments passed to the magic command. Returns: A list of buffer references to the matched content. Raises: NoClientSelectedError: Client is not selected to perform this operatio...
28c771f12d162e667009241cdba2f2e485736599
3,625,029
def convertMCFOSTdataToJy(data, wavelength, spatialUnit = 'arcsec', spatialResolution = None): """Convert data in MCFOST units into Jansky/pixel or Jansky/arcsec^2: Input: data: 2D array, MCFOST-generated data. wavelength: float, wavelength of the data to be converted in micron. spatial...
20e493989513e4e08e9211f7a6f7d606817aaa44
3,625,030
def defaults(dict=None): """ Adds a set of default values to the settings registry. These can and will be updated by any settings modules in effect, such as the Settings Manager. If dict is None, it'll return the current defaults. """ if dict: _defaults.update(dict) else: re...
8b7423d0fdbbd522a01e04cd77e6aca863951e9a
3,625,031
import os from .magics import register_magics from .hierarchymagic import load_ipython_extension as load_hierarchy def init(path=None, ipython=None): """Initiate noWorkflow extension. Load D3, IPython magics, and connect to database Keyword Arguments: path -- database path (default=current directory...
5b9692b70d98797f84bf1a5a9d64aa165965207e
3,625,032
def send_email(email_subject, recipient, message, config = None): """Send an email using SendGrid.""" try: config = current_app.config except: config = config sender = sendgrid.SendGridClient(config['SENDGRID_API_KEY']) email = sendgrid.Mail() email.set_subject(email_subjec...
18c20e086ddacc719898f2ad3e3a03f5c560d0fb
3,625,033
import sys from io import StringIO def redirect_stdout(func): """temporarily redirect stdout to new Unicode output stream""" @wraps(func) def wrapper(*args, **kwargs): original_stdout = sys.stdout out = StringIO() try: sys.stdout = out return func(out, *args...
585f490b0e0b8c9b365cf0e0f24e13f6346f59ff
3,625,034
import wsgiref def simulate_request(app, method='GET', path='/', query_string=None, headers=None, content_type=None, body=None, json=None, file_wrapper=None, wsgierrors=None, params=None, params_csv=False, protocol='http', host=helpers.DEFAULT_HOST, ...
15950c9b880ac791454bd64becf176aec0ab4d99
3,625,035
def rcnn_encode(bboxes, targets): """ :param bboxes: (N, 4) bounding boxes of [x0, y0, x1, y1] :param targets: (N, 4) target ground truth boxes of [x0, y0, x1, y1] :return: deltas """ bw = bboxes[:, 2] - bboxes[:, 0] + 1.0 bh = bboxes[:, 3] - bboxes[:, 1] + 1.0 bx = bboxes[:, 0] + 0.5 *...
919395705dd20e6872fac21ab8abf52a04ff8167
3,625,036
import argparse import sys def argparse_setup(): """Initialize the argument parser. Parameters: None Return: None """ parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() # Subparser for implementation listing info_parser = subparsers.add_parser("i...
10dbea13f782e9fd19371537984001d300a289ee
3,625,037
def is_alloc_promotable(alloc_inst: ir.Alloc): """ Check if alloc value is only used by load and store operations. """ assert isinstance(alloc_inst, ir.Alloc) if len(alloc_inst.used_by) != 1: return False addr_inst = list(alloc_inst.used_by)[0] if not isinstance(addr_inst, ir.AddressOf): ...
ac81c42fba5b5c618b5a083e7b3dbf2cc624e2f5
3,625,038
def mera_ansatz_parameters(num_qubits, depth, value): """Returns a Parameters object for the MERA Tensor network ansatz. Args: num_qubits : int Number of qubits in the parameterized circuit. depth : int [must equal log2(num_qubits)] Number of "hyperlayers" in MERA netwo...
8e491189527a95686c99a10da1527ec321c48036
3,625,039
def gaussianfilter(N, alpha, Ts, Fs): """ Generates a gaussian filter (FIR) impulse response. Parameters ---------- N : int Length of the filter in samples. alpha: float Roll off factor (Valid values are [0, 1]). Ts : float Symbol period in seconds. ...
8f3ce2f3aa155dcf3163f6a252b98aa506137013
3,625,040
def minimal_copy(ds: Dataset) -> Dataset: """Make reduced copy with only the attributes needed for a QueryResult""" res = Dataset() for attr in chain.from_iterable(chain(req_elems.values(), opt_elems.values())): val = getattr(ds, attr, None) if val is not None: setattr(res, attr,...
f0df04aa6e1a5447b7e6caf0a489cc89a7de9423
3,625,041
import numpy as np import io import torch def read_txt_embeddings(logger, path): """ Reload pretrained embeddings from a text file. """ word2id = {} vectors = [] # load pretrained embeddings # _emb_dim_file = params.emb_dim _emb_dim_file = 0 with io.open(path, 'r', encoding='utf-8', newline='\n', e...
1d7cc0845488bb3bd37eef4ca0cdeff67787f6e8
3,625,042
def corrected_chance(clustering1, clustering2, measure='jaccard_index', random_model='perm', norm_type='sum', n_samples=100): """ This function calculates the adjusted Similarity for one of six random models. .. note:: Clustering 2 is considered the gold-standard clustering for one...
86505ed8eeb38decb551fa77cbec00b8ba9d16f1
3,625,043
def update_account(): """Update account settings.""" form = AccountSettingsForm(request.form) if form.validate(): if 'user_id' not in request.form: return jsonify({'success': False, 'error': 'ID not found in edit!'}) edit_id = paranoid_clean(request.fo...
247d60dbf333f7ed162b091c485e9bffe8418062
3,625,044
def make_weighted_loss(loss_fn, weight=1.0): """ Adapts the given loss function by multiplying by a given constant. Parameters ---------- loss_fn: a function to create the loss weight: the value by which to weigh the loss. Returns ------- fn: The adapted loss """ def fn(*args, ...
bfe235e012cc134b98b5d995935327b11bba8651
3,625,045
def create_differences_matrix(rows, cols): """ Creates the central differences matrix A for an n by m shaped grid """ n = rows*cols M = np.zeros((n,n)) for r in range(rows): for c in range(cols): i = r*cols + c # Two inner diagonals if c > 0: M[i-1,i] ...
ea199ed8fb3f33e4e059d5748d347a46dc78d7d7
3,625,046
def isvalid_corr(corrmat): """ Check if 1. corrmat is symmetric 2. off-diagonal values in [-1, 1] 3. diagonal values = 1 4. the matrix is positive semidefinite. @param corrmat: numpy nxn ndarray @return: CorrDiagnostics object ---> evaluates to True if corrmat is valid and False otherwi...
6f2509daaf9901d3b35841bda08dd062d2b1caa1
3,625,047
def multi_JMI(X, y, is_disc, cost_vec, cost_param_vec, num_features_to_select = None, random_seed = 123, num_cores = 1): """ Cost-based JMI feature ranking with multiple penalization parameters. Function to obtain the rankings associated to different cost parameters, with the filter featu...
8e0f641d89b07548fde555225ff9c2dad094e484
3,625,048
def arcsin(x): """ Compute the inverse sine of x. Return the "principal value" (for a description of this, see `numpy.arcsin`) of the inverse sine of `x`. For real `x` such that `abs(x) <= 1`, this is a real number in the closed interval :math:`[-\\pi/2, \\pi/2]`. Otherwise, the complex princi...
6692bb51b5347ab77d2d12969a8fc98ccc43ac62
3,625,049
def run_queued(fn, params, processes=1, queued_params=None, logging_level=None): """ Same as run_function, but the function should be such that it accepts a parameter queue and reads its inputs from there; params still contains options for the function. If logging_level is not None, a QueueHandler ...
bef4ae414bbe8787ef6c606c5391a49832aa0e90
3,625,050
import signal def ExtractFrequencyTime(data, bands): """Computes the spectrogram of data, and the takes the sum of frequencies inside the band range. """ bands_results = {'all_spec':[], 'alpha':[], 'beta1':[], 'beta2':[], 'beta3':[]} f, t, Sxx = signal.spectrogram(data,window = 'hamming', fs = 500,n...
1ebf9e9a39d34d6a1657c6a2c440996e1ba88302
3,625,051
from typing import Any from typing import List def ensure_list(data: Any) -> List: """Ensure input is a list. Parameters ---------- data: object Returns ------- list """ if data is None: return [] if not isinstance(data, (list, tuple)): return [data] ret...
58016feaf49d63255944fa615e7e2e1dac6dcc76
3,625,052
def decode_logistic_mixture( targets, means, log_scales, logit_probs_softmax, # CDF input_string): """ NOTE: This function uses either the CUDA or CPU backend, depending on the device of the input tensors. NOTE: targets, means, log_scales, logit_probs_softmax must all be on the same device ...
66ad78e22a538c788729bdbd1bb6a74a88d24be3
3,625,053
def _match_up_provided_args_with_field_defs(field_defs, args, kwargs): """ Returns a list of provided values, aligned with the field definitions. Missing values are represented using the NVP (No Value Provided) token (as None can be a valid provided value). """ values = [NVP] * len(field_defs) ...
440b218e3bde552a10890304278ef9604d8f988b
3,625,054
def var_recode(TEDS_A_Imputed, user_target, TEDS_Af): """Recodes categorical variables present in the data. Returns A recoded data frame.""" # Identify the variable types col_list = list(TEDS_A_Imputed.columns) col_list_cat = [s for s in col_list if s != 'CASEID' and s != 'ADMY...
cc656e9a6840af4d95a6a114073459d815c533dc
3,625,055
def get_cannonical(group): """ For each variant, that is unique combination of #CHROM, POS, REF, ALT, it keeps CANONICAL transcript annotations. If more than consequence type is annotated, it keeps the most damaging or severe either if there is more than one entry (row) per variant or either is coma-sep...
31417a30fbfb7800dfdd46352ea9f9e5763be3e3
3,625,056
def get(blob_key): """Gets a `BlobInfo` record from blobstore. Does the same as `BlobInfo.get`. Args: blob_key: The `BlobKey` of the record you want to retrieve. Returns: A `BlobInfo` instance that is associated with the provided key or a list of `BlobInfo` instances if a list of keys was pro...
03c3fe9da40c2986ccce19b62e99c07abe49cbd0
3,625,057
from typing import List from typing import Dict def go_struct_variables(variables: List[Dict]) -> str: """Generate Go code containing struct field definitions.""" lines = [] for var in variables: if var["description"]: description = ( var["description"] ...
58f50207e33105752f8904046e281ae2288a3cdf
3,625,058
def init_split(df, featname, init_bins=100): """ 对df下的featname特征进行分割, 最后返回中间的分割点刻度 为了保证所有值都有对应的区间, 取两个值之间的中值作为分割刻度 注意这里的分割方式不是等频等常用的方法, 仅仅是简单地找出分割点再进行融合最终进行分割 注意, 分出的箱刻度与是否闭区间无关, 这个点取决于用户,这个函数仅考虑分箱的个数 同时, 分箱多余的部分会进入最后一个箱, 如101个分100箱, 则最后一个箱有两个样本 Parameters: ---------- df: dataframe,...
172f48bb019fd4cf4941b2ff0fefcb24709fe7a4
3,625,059
import os def read_image(point_file): """Read the corresponding image.""" head, tail = os.path.split(point_file) image_file = tail.split('.')[-2] img_jpg = os.path.join(head, image_file + ".jpg") img_png = os.path.join(head, image_file + ".png") if os.path.exists(img_jpg): img = cv2.im...
aa59c3618699e9ff93603cf72ffb58ce422a0824
3,625,060
def dist_of_entity_k(adjacency_dict: dict, levels_dict: dict, c_k: dict, c_notk: dict) -> int: """ Performs the final iterations of the algorithm proposed in the Alternative Geographic Spine document to find the "off spine entity distance" (OSED), which is the number of geounits that must be added or subtra...
787466d3de923fa495d93794823c6b0d51c22f5b
3,625,061
import tkinter def repr_content_and_tags(text_widget: tkinter.Text) -> str: """Represent the content, indices and the tag starts and ends as a text table.""" tbl = prettytable.PrettyTable() tbl.field_names = ["Index", "Char", "Tag starts", "Tag ends"] for index, character, tag_starts, tag_ends in en...
534c1642d77f0229322a1065b237c65e6b0ccf5c
3,625,062
from typing import Callable from typing import Union from typing import Iterable def build_dataset_reduce_fn( simulation_flag: bool = True ) -> Callable[[_ReduceFnCallable, Union[tf.data.Dataset, Iterable]], tf.Tensor]: # pylint: disable=g-bare-generic # TODO(b/162683412): remove `Iterable` after pytype fix. ...
7000bc59ed40c4bdc3af1aed6fcaec86236e0456
3,625,063
def isotropic_twirl_state(X, d): """ Applies the twirling channel X -> ∫ (U ⊗ conj(U))*X*(U ⊗ conj(U)).H dU to the input operator X acting on two d-dimensional systems. For d=2, this is equivalent to X -> (1/24)*sum_i (c_i ⊗ conj(c_i))*X*(c_i ⊗ conj(c_i)).H where the unitaries c...
5ff32bb3b4c6b2671e9acb8d7963683bcc3c3261
3,625,064
from functools import reduce def flatten_index(builder, index, const_shape): """Converts N-dimensional index into 1-dimensional one. index is of a form ``(i0, i1, ... iN)``, where *i* is ValueRefs holding individual dimension indices. First dimension is considered to be variable. Given array shape ...
2864701c5e3d0263d82fd585ad9d77c7c584ea2b
3,625,065
def init_conds(MdiscI, P): """ Function to convert a disc mass from solar masses to grams and an initial spin period in milliseconds into an angular frequency. :param MdiscI: disc mass - solar masses :param P: initial spin period - milliseconds :return: an array containing the disc mass in grams and th...
612411a3fad7f41309858f20e9aefad16904e16e
3,625,066
from bs4 import BeautifulSoup def fetch_feed() -> list[RenjiData]: """ Get news feed from renji.com """ logger.info("Start fetching info from renji.com ...") res = urlopen("https://www.renji.com/default.php?mod=article&fid=38") logger.info("Info fetched. Parsing ...") soup = BeautifulSoup(...
14cc274b17de03266626166592ae65e88bd54286
3,625,067
from typing import Optional def get_me_ssh_key(key_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetMeSSHKeyResult: """ Use this data source to retrieve information about an SSH key. ## Example Usage ```python import pulumi import pul...
fe957f701869608e818092e22f08dcb0e6d8b27d
3,625,068
import numpy def gower_distance_numpy(point1, point2, max_range): """! @brief Calculate Gower distance between two vectors using numpy. @param[in] point1 (array_like): The first vector. @param[in] point2 (array_like): The second vector. @param[in] max_range (array_like): Max range in each data di...
b97c40cd62654172b0d502e35bbef8ce9e9175c5
3,625,069
def is_fix_only_distro(distro_name: str) -> bool: """ Does the given distro's security feed/db support vulnerability records before a fix is available? :param distro_name: :return: bool """ return distro_name in FIX_ONLY_DISTROS
35eaf42b7111a3ddcec11dd351a7d00378607f86
3,625,070
def step_f(z: np.ndarray, scale: float, loc: float) -> np.ndarray: """ :param z: z-dimension :param scale: width of step function, always 0 :param loc: position of step :return: positioned step function """ new_z = z - loc f = np.ones_like(new_z) * 0.5 f[new_z <= -scale] = 0 ...
f94d0f18aa0805f6e0739927f88517c9e70a802a
3,625,071
def build_SVM(X_train, y_train, kernel_): """ The function builds SVM """ scaler = StandardScaler() X_train_std = scaler.fit_transform(X_train) """ for i in range(1, 5): svc = SVC(kernel=kernel_, random_state=0, gamma=i) model = svc.fit(X_train_std, y_train.values.ravel()) ...
a3ced31185a224b79366d44e3b2ce02f334f7ed6
3,625,072
def status(args: tuple[str]) -> list[res.Response]: """Batch `git status` command.""" return _call_git_use_case("status", args)
855160c530f606535956b5decf766b32abdbeb4d
3,625,073
def get_worker(project, object_id=None, global_id=None, user_id=None): """ Gets the identified worker. Exactly one form of identification should be provided. :param project: :param object_id: The worker's OBJECTID. :param global_id: The worker's GlobalID. :param user_id: The worker'...
bff455591f48c7a45f387364c13b1d6e70c5196d
3,625,074
import xml import re def xml_to_string(elem, pretty=False): """ Returns a string from an xml tree. """ try: if elem is not None: if PY2: xml_str = ElementTree.tostring(elem, encoding='utf-8') else: xml_str = ElementTree.tostring(elem, enc...
55d385a55d8cc998470b19286460267d24ddd26a
3,625,075
from typing import Type from typing import Optional from typing import List def build_config( config_file: str, task_cls: Type[GeneralizedRCNNTask], opts: Optional[List[str]] = None, ) -> CfgNode: """Build config node from config file Args: config_file: Path to a D2go config file o...
5387bf56461c3ad1c71bf25592abd5c77ab4b43c
3,625,076
def get_windowed_mean_expression(loom, list_of_gene_windows, patient_column='Patient_ID', patient=0, cell_type_column=None, cell_type=None, ...
4ce876d00d5f3320c535b43ccf4f1ec478ac6180
3,625,077
def parse_trajectory_file(fname): """ This routine reads a file of particle trajectory data generated by the ptm simulation. Data from ptm is output in formatted ascii, with the time history of a particle trajectory given by a 8-column array with an unknown number of rows. The data from each particle is...
3a18f05222e44f1d4f439cc513926b5209da4c72
3,625,078
def get_learner(config_args, train_loader, val_loader, test_loader, start_epoch, device): """ Return a new instance of model """ # Available models learners_factory = { "default": DefaultLearner, "selfconfid": SelfConfidLearner, "oodconfid": OODConfidLearner, } ...
71e566ac47f78598d9ea3e9a79bb0f3c5f9e0276
3,625,079
def localHomologyMultiproc( k, cplx, numProcs, localSimplices=None, iterate=True, rankOnly=False ): """Compute local homology relative to the star over a list of simplices in parallel""" if localSimplices is None: localSimplices = [] for ki in range(k + 1): localSimplices += ksi...
de3998fc755b8c002e960bf0cfd5b28ec9150426
3,625,080
def text_repr(diffs): """ Helper function to dump xml elements into plain string form for the sake of comparison. It also get rid of all attributes in xml elements if any. """ return {change_type:[etree.tostring(elem.attrib.clear() or elem).decode('utf-8') for elem in elems] for change_t...
9e9e2b6b4fff642bb82278642b9c6ea02d0519b3
3,625,081
def get_default_variables(defaults, source_id, model): """ Returns list of strings, representing selection default variable IDs Keyword Parameters: defaults -- List of strings, representing requested default query names source_id -- String, representing API ID of the selection source ...
260bd63b3c2366f4bf04edc0f0ebe6a78600cbd6
3,625,082
import json def search_nlucell(): """Search NluCell 搜索问答节点 Get:返回所有问答节点 POST:返回所有包含搜索关键词的问答节点 """ data = { 'skb': database.skb, 'result': [] } state = { 'success' : 0, 'message' : "请先选择知识库再搜索节点" } if not database.skb: return json.dumps(state)...
7a398ce5dddf9e6f2f5fe82b475eef7eba32b2cb
3,625,083
def generate_gate_swap_mat() -> np.ndarray: """Return the Hilbert-Schmidt representation matrix for a SWAP gate with respect to the orthonormal Hermitian matrix basis with the normalized identity matrix as the 0th element. The result is a 16 times 16 real matrix. Parameters ---------- Returns ...
df86f8ef3c2e4321695a87822a063ebee5c4f27c
3,625,084
import subprocess def disableRemoveIPCLog(cmd): """ function : disable remove IPCLog input : cmd output : NA """ (status, output) = subprocess.getstatusoutput(cmd) if status != 0: g_logger.debug("Failed to disbale RemoveIPC. Commands" " for disbale RemoveIPC...
9b61ac7ea453c179d389174f9c49393838101d7e
3,625,085
def can_register(extra, password_meta): """ :param extra: {str: any?}, additional fields that the user will fill out when registering such as gender and birth. :param password_meta: {'count': int, 'count_number': int, 'count_uppercase': int, 'count_lowercase': int, 'count_special'...
a6ba8cc6fc4a4180bbbceb9a8ae14b07d7dad809
3,625,086
def cross_entropy(output, target): """Calculate Cross-entropy loss.""" return F.cross_entropy(input=output, target=target)
e836dd4d0dbae597932aa3265a92776b7a032ccb
3,625,087
def plate_to_genesift_sequencing_order_spreadsheet(plate, output_file, sample_name_function, well_filter=None, direction='row'): """Generate an excel spreadsheet f...
bd317bd535bfa1e465ee0e0df6a020d299e83789
3,625,088
def hours_of_daylight(date, axis=23.44, latitude=39.87): """Compute the hours of daylight for the given date""" #date = datetime.strptime(start_time, "%Y-%m-%d") diff = date - pd.datetime(2000, 12, 21) day = diff.total_seconds() / 24. / 3600 day %= 365.25 m = 1. - np.tan(np.radians(latitude...
390cd02b805686a824b8e1bfa8641d1adeb01e9d
3,625,089
def reject(p, xs): """The complement of filter. Acts as a transducer if a transformer is given in list position. Filterable objects include plain objects or any object that has a filter method such as Array""" return filter(complement(p), xs)
a2556ab9d4514dfb18a513938960211473a508a9
3,625,090
import functools import copy def mutable_cache(maxsize=10): """In-memory cache like functools.lru_cache but for any object This is a re-implementation of functools.lru_cache. Unlike functools.lru_cache, it works for any objects, mutable or not. Therefore, it returns returns a copy and it is wrong if...
f8d5f76c035c9c6dda66dfc1a0787062684c6d75
3,625,091
from typing import OrderedDict def filter_excluded_fields(fields, Meta, exclude_dump_only): """Filter fields that should be ignored in the OpenAPI spec :param dict fields: A dictionary of of fields name field object pairs :param Meta: the schema's Meta class :param bool exclude_dump_only: whether to ...
a39a7665052cde0ba9f694696a57f2b1f6ca0603
3,625,092
def parse_xmpp_addresses(text): """.""" xmpp_addresses = ioc_grammars.xmpp_address.searchString(text) return _listify(xmpp_addresses)
36e5567e43bf48674787130a10bc77a69d9dcd54
3,625,093
def login_user(): """ This route handles user login """ user_info = request.get_json() user_instance = UserModel.query.filter_by(email=user_info["email"]).first() if not user_instance: return { "message": "Your email or password is not correct", "status": "failed", ...
de93dc48865c75ae96a43f7cc9534ac64aba443e
3,625,094
from typing import Any def test_email( email_to: EmailStr, current_user: models.User = Depends(deps.get_current_active_superuser), ) -> Any: """ Test emails. """ send_test_email(email_to=email_to) return {"msg": f"Test email sent to {email_to}"}
13e7bcb0e96ae11c910619f4a4f161738c10ac6f
3,625,095
def euclidean_distance(vects): """Compute Euclidean Distance between two vectors. Euclidean distance is defined as the length of a line segment between the two points. d(p,q) = √ [Σ(qi – pi)^2] Args: vects : vectors Returns: euclidean distance between vects. """ x, y ...
f48eac6ff7adaefee700fe48f60cd614655ac704
3,625,096
def process_typedef(line): """处理类型定义""" content = line.split(' ') type_ = type_dict[content[1]] keyword = content[2] if '[' in keyword: i = keyword.index('[') keyword = keyword[:i] else: keyword = keyword.replace('\n', '') # 删除行末分号 keyword = keyword.replace('\r'...
e36f0f6298e2cdf7edc1d843c3fbaae7aa428a97
3,625,097
def findNearestNeighbourPixel(img, seg, i, j, segSize, fourConnected): """ For the (i, j) pixel, choose which of the neighbouring pixels is the most similar, spectrally. Returns tuple (ii, jj) of the row and column of the most spectrally similar neighbour, which is also in a clump of size...
e205652d7b39c922a203162f3cdc58672347b938
3,625,098
import json def _load_json_as_list(path: str) -> list: """Load json file and convert it into list. :param path: path to json file :type path: str :return: dict :rtype: dict """ with open(path, "r") as json_data: data = json.load(json_data) if isinstance(data, list): re...
d7aa301a830a826937522dc9c737bf84bf6f4f9a
3,625,099