content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_angle_direction(v1, v2, axis): """ Return the direction of rotation to get v1 onto v2 about the provided axis. """ axes_dict = {'x':0, 'y':1, 'z':2, 'X':0, 'Y':1, 'Z':2} if axis in axes_dict: axis = axes_dict[axis] v1, v2 = np.atleast_2d(v1, v2) # vectors will be (1,3) or (N,3...
3dad8268f3437f629c970c892e30df59b1b5c30b
51,356
def _estimate_log_gaussian_prob(X, means, precisions_chol, covariance_type): """Estimate the log Gaussian probability. Parameters ---------- X : array-like of shape (n_samples, n_features) means : array-like of shape (n_components, n_features) precisions_chol : array-like Cholesky dec...
1c5d5d4e16687b362ee01612fa9ab0c04efde85e
51,358
def _build_draw_line(append): """Specialize a line plotting kernel for a given append/axis combination""" @ngjit def draw_line(x0i, y0i, x1i, y1i, i, plot_start, clipped, *aggs_and_cols): """Draw a line using Bresenham's algorithm This method plots a line segment with integer coordinates on...
acd77b3259fc4c9efe9afbc6312f11737c14509d
51,359
def zeros(shape): """ :param shape: tuple with the shape of the wanted output (filters_amount, depth, height, width) :return: array (it's shape=param shape) with initialized values using 'zeros' initializer """ return np.zeros(shape=shape)
034f61b27e23b829c8c8828f9d2e5fffad3e7055
51,361
def addr_generator(start_ip, port, count): """Generator a list of (ip, port). """ def tostr(ip): return '.'.join([str(_) for _ in ip]) ip = [int(_) for _ in start_ip.split('.')] addr_list = [(tostr(ip), port)] for i in range(count-1): ip[-1] += 1 addr_list.append((tostr(i...
100288629f35d9108e0b364266242da0110dd8f7
51,362
def filter_threshold(delta_f, threshold_value): """ Return indices of the data whose values are above the acceptable level """ return delta_f >= threshold_value
a0c34eba86a0fb4539174d75f2cde19994aaa8cf
51,363
def handler(event, context) -> utils.Response: """lambda entry point.""" return handlers.SnsEventHandler( name="twitter", event=utils.LambdaEvent(event), context=utils.LambdaContext(context), action=post_status, ).response
67b6b16b978bc229e44929d8fc0f1b18d86834d5
51,364
from functools import reduce def vector_sum(vectors): """一系列向量相加""" return reduce(vector_add, vectors)
a4ffe3cf55c1b9c75ea811e2d77a66fceeb256d8
51,365
import random import time def retry(func, *args, **kwargs): """Repeats a function until it completes successfully or fails too often. Args: func: The function call to repeat. args: The arguments which are passed to the function. kwargs: Key-word arg...
cf6f7d3e434b54cf178b2867f7565f338e985968
51,366
def build_model_columns(): """ :param data = df_preprocess_noNA Builds a set of wide and deep feature columns. """ # Continuous variable columns speed = tf.feature_column.numeric_column('speed') inv_speed = tf.feature_column.numeric_column('inv_speed') ais_rem_time = tf.feature_column.numeric_column('ai...
5f5df227c12948dd1e8cee34af485db42a7a23d4
51,368
def test_custom_timeout(monkeypatch, fake_response, aqhttp): """Timeout should override from the aqhttp.post method.""" class FakeRequest: def __init__(self, status_code=200, url="myfakeurl.com", method="post"): self.status_code = status_code self.url = url self.meth...
6b03e8f6124557119ef8b30191ab6d35f3d3e002
51,369
def create_tags(dataframe, periods): """ Función para clasificar los registros de cierre como subidas/bajadas fuertes, subidas/bajada, o matiene de un día con respecto a otro. Parámetros: ---------- df pd.DataFrame: DataFrame que se quiere clasificar. periods int: ...
2431b8d52fac840bbebf55bd33aa18327f0b0a01
51,370
def encrypt(data, key): """RC4""" S = list(range(256)) j = 0 out = [] for i in range(256): j = (j + S[i] + key.encode()[i % len(key)]) % 256 S[i], S[j] = S[j], S[i] i = j = 0 for char in data: i = (i + 1) % 256 j = (j + S[i]) % 256 S[i], S[j] = S[j]...
6c2ced51fc2ad443ffbfee1435092b3c60207bdb
51,371
from re import A def crop_by_range(anim: Animation[A], start: float, finish: float) -> Animation[A]: """ Render a range of an animation. `start` and `finish` should be floats from 0 to 1. """ if not (0 <= start < finish <= 1): raise ValueError( "Invalid range ({}, {}). Expected...
40b90adecb659aad60b14387ec2978be67e36c0b
51,372
def hist_match(cdf_org, cdf_tar): """ Build the lookup table described in step 3. Arguments: ----------- cdf_org: dict The cumulative distribution function of orginal image. cdf_tar: dict The cumulative distribution function of target image. Returns: ----------- l...
a5a428aeed6bafcbb9d2d39c6068a2bd1717179b
51,373
def run_one_step(dataframe, start_centers): """ Performs one iteration of K-Means. This function takes a dataframe with dense feature vectors, a set of centroids, and returns a new set of centroids along with the total distance of points to centroids. This function calculates for each point the cl...
b3d3012b167ae8484ddfadd029d60442d12d9292
51,374
def report_options(func): """Common report options.""" func = all_option(func) func = count_option(func) func = length_option(func) func = end_option(func) func = start_option(func) func = exclude_option(func) func = include_option(func) return func
76506f9644695fb4dbd24d23ec5f868dd2ee3886
51,375
import random def train_test_split_adjacenty(total_size, test_ratio, test_indexes): """ Parameters ---------- A: scipy.sparse.spmatrix connected sparse unweighted adjacency matrix test_indexes: list tuple with (x, y, val) for each idx in test datasets Returns ------- t...
9b826a234da30f253c0d433123a16f912843d658
51,376
import torch def _chunk_slice( t: torch.Tensor, flat_start: int, flat_end: int, no_batch_dims: int, ): """ Equivalent to t.reshape((-1,) + t.shape[no_batch_dims:])[flat_start:flat_end] but without the need for the reshape call, which can be memory-int...
f77f8ea76fbc382eeb8a512f0944b809087e3266
51,377
def dimshuffle(arr, pattern): """ Based on theano's dimshuffle function. Permutes the axes of an array and inserts new singleton axes. e.g. if x has shape (2,3), then dimshuffle(x, [1,0,'x']) has shape (3,2,1) note that dimshuffle can not drop dimensions. inputs ------ pattern: list...
3134f33ac002171d18775b66d04577ad06103d72
51,378
import pytz def utc_to_local(utc_dt, local_tz): """Accepts a datetime object in UTC time, and returns the same time, in the timezone that was also passed""" local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz) return local_tz.normalize(local_dt)
15ade0c4d1b732b4fd9ef5c2f7de0eb32a3c6936
51,379
def within_limits(cave: ArrayLike, coord: tuple[int, int]) -> bool: """Check whether a given coordinate is within the limits of the cave.""" return ( (0 <= coord[0]) & (coord[0] <= cave.shape[1] - 1) & (0 <= coord[1]) & (coord[1] <= cave.shape[0] - 1) )
f3ed4a65c5c1289a7bdc1707b7c7320e8c4e2231
51,380
def unpack_from(fmt, buf, offset=0): """ Unpack the buffer, containing packed C structure data, according to fmt starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt). See struct.__doc__ for more on format strings. """ try: o = _cache[fmt] except KeyError: o = _c...
a7f020cd7564f92d0c4d8f67a979e000a7c18724
51,383
def load_single_mat(mat_file_floder,n_clip=1,dataset="Avenue",vis=True): """ :param mat_file: mat file path :return: anomaly boundary [num ,2] """ filename = '%s/%d_label.mat' % (mat_file_floder, n_clip) data=sio.loadmat(filename) volLabel=data["volLabel"] n_bin = np.array([np.sum(vol...
021dd4c8a0267b49bef187bbb57f6abe35b7d285
51,384
def _ScatterAddNdimShape(unused_op): """Shape function for ScatterAddNdim Op.""" return []
7c59fb40e177fea1bf1cd3970c364f4583fc37f9
51,385
def sanitize_name(original_name: str): """Sanitize name for output into compiler artifacts Parameters ---------- original_name : str Original name to sanitize """ return _backend.SanitizeName(original_name)
6bc6ab6037c0925c07f5b59821a4356a673aa8c9
51,386
def parse(sql, category=None): """ Returns data structure for SQL statement. @param category expected statement category if any, like "table" @return ({..}, None), or (None, error) """ result, err = None, None try: result, err = Parser().parse(sql, category) except...
2381eef37d4102037920712bb665ca3b3dfbebd7
51,387
def store_to_flat_XML(model, vpath): """Store current LO document to vpath, as a ODF flat XML file""" return store_to__by_extn(model, vpath, '.fodt') or \ store_to__by_extn(model, vpath, '.fods') or False
bdac5d13b0e57db39575fff91ce163e98e365c28
51,388
def eDFA(F: np.ndarray) -> np.ndarray: """ In the reference indicated below a measure of nonstationarity was added by including a subsequent calculation of the extrema of the DFA. Denoted :math:`dF_q^2(s)` the difference of the extrema at each segment, i.e., .. math:: dF_q^2(s) = \max[F_q^...
7df59a38ad2b414efcfd0be16f67dbcf264df4c6
51,389
import time import tqdm import torch from typing import OrderedDict def train(loader, model, epoch, criterion, optimizer, threshold, class_weights=None, use_cuda=None): """ :param loader: :param model: :param epoch: :param criterion: :param optimizer: :param threshold: :param class_w...
5cac64cc77d67ae6b4504f86c6cc101eda696105
51,390
def memoize(timeout=None, fast=False): """ Cache a function based on its arguments. Args: timeout: Time the result stays valid in the cache. Returns: The functions result. """ assert (not fast or (fast and timeout is not None) ), "You cannot set fast cache without a ...
dd290a19b675c25327668215e583b5b30f077a18
51,391
def get_appliance_bgp_neighbors( self, ne_id: str, ) -> dict: """Returns appliance BGP neighbor configuration .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - bgp - GET - /bgp/config/neighbor/{neId} :param ...
f8e777f9e9fabbdb9610ce0bf5f0824b888a9e04
51,392
def pages_sub_menu(context, page, url='/'): """Get the root page of the given page and render a nested list of all root's children pages. Good for rendering a secondary menu. :param page: the page where to start the menu from. :param url: not used anymore. """ lang = context.get('lang', pag...
f718d6513da8f05683a7b85e2bebcdc359487616
51,393
def JsonToMessage(message_type, message): """Convert the given JSON to a message of type message_type.""" return _ProtoJsonApiTools.Get().decode_message(message_type, message)
b642c5160e6c06ff60daffedbb4d665b8005b711
51,394
import torch def generate_angular_spectrum_kernel(shape, pixel_size, wavelength, \ numerical_aperture=None, flag_band_limited=True, \ dtype=torch.float32, device=torch.device('cuda')): """ Function that generates angular spectrum propa...
b07e54f087b8271ef27f88497717ed96ae3136a2
51,395
from typing import List def getBarcodesFromSnap(fname: str) -> List[str]: """Read barcodes from a snap file Attributes: fname - a snap-format file Return: a dictionary contains all barcode in the snap file """ with h5py.File(fname, "r") as f: barcodes: List[str] = [item.d...
4fb9821e3184886688c795429742bf123aed49f8
51,396
def slicing_where(condition, full_input, true_branch, false_branch): """Split 'full_input' between 'true_branch' and 'false_branch' on 'condition'. Args: condition: A boolean Tensor with shape [B_1, ..., B_N]. full_input: A Tensor or nested tuple of Tensors of any dtype, each with shape [B_1, ..., B_...
8d1faf5c2b1b3f9ddc9e3a27529ef06de740551c
51,397
def radiation_pressure_length_noise( ff, Pin, finesse, mass=2.92, lam=1064e-9, ): """Radiation pressure length noise for a single optic in a cavity in units of m/rtHz. Inputs: ------- ff: float audio frequency in Hz Pin: float cavity input power in watts fines...
1be70f39ac1739acf430ec9980a3ddbd645ff8aa
51,398
def snic_distance_mod(pos_i, pos_j, col_i, col_j, si, mi): """ Computes the SNIC pixel distance None of the components can be negative -> omitting the root does not change item order :param pos_i: position of pixel i :param pos_j: position of pixel j :param col_i: color of pixel i :param col...
0d083e9f28bd36f0fc38e149371ad033b4bf54e5
51,399
import inspect def get_gradient_clip_fn(hparams=None): """Creates a gradient clipping function based on the hyperparameters. See the :attr:`gradient_clip` field in :meth:`~texar.core.optimization.default_optimization_hparams` for all hyperparameters and default values. The gradient clipping func...
88dedd060763b529eafe4982a4f3abd9d27b0455
51,400
def find_delimiter_in(value): """Find a good delimiter to split the value by""" for d in [';', ':', ',']: if d in value: return d return ';'
4a60fbe6294fff048645a6fbc397ec96fd748d67
51,401
from nzmath.prime import generator_eratosthenes as generator_eratosthenes def powerDetection(n, largest_exp=False): """ param positive integer n param boolean largest_exp return integer x, k s.t. n == x ** k (2 <= k if exist else x, k == n, 1) if largest_exp is true then return l...
5e5a4e374957660b60a5bb51b7b780801ce8e570
51,402
def get_parser_from_config(): """ Uses the 'parser' field in the config file to find and return the parser :return: """ parser_instance = config.read_config_option("parser") return parsers.parser_factory(parser_instance)
a83a8ba2e2b88c29276400b3fb405227950027ec
51,403
def _SeqPaddingLength(inputs_nmap): """Returns the lengths of paddings at the beginning and end of the sequence. Args: inputs_nmap: A `.NestedMap` of tensors that may have 'padding' Every tensor's 0-th dim has the same size. Returns: padding length at the beginning, padding length at th...
9ceeccca913dd8ed0738db88073a7bc8c791480e
51,404
def get_ROT(ch,pe,te,ze,verbose=True): """ calculate ROT and depol ratio """ args = [ch, pe, ze, te, MISSING, verbose] ROT, depol_ratio, rc = VLIDORT_POLAR_.rot_calc(*args) return ROT,depol_ratio
54b6173db6d676f6eaeb45b3980b3af74a6ffa0d
51,405
def getFailsafeQueue(): """ Method returns failsafe queue """ global failsafeq return failsafeq
43ee8f9090e6cc719946176b2673a93553be8aae
51,406
def wait_for_read(socks, timeout=None): """Waits for reading to be available from a list of sockets or optionally a single socket if passed in. Returns: A list of sockets that can be read from immediately. """ return _wait_for_io_events(socks, EVENT_READ, timeout)
ba254b3fe46c104d90252d212e79587f2a5fd38a
51,407
def group_frame(frame_partitions, num_new_parts, key_columns): """Group frame to prepare for the join """ return [ local_shuffle(part, num_new_parts, key_columns) for part in frame_partitions ]
116b32cd69655c6f88dd6835af3d939a83d24074
51,410
def read(**kwds): """ Read all data. """ title = kwds.get("title") text = kwds.get("text") tags = kwds.get("tags") offset = kwds.get("offset") limit = kwds.get("limit") query = Article.query if title: query = query.filter(Article.title.contains(title)) if text: ...
d277e43384d3487941cf5ed7e16ccde5f02a27f9
51,412
from datetime import datetime def project_with_max_gross_value_added(): """Test fixture returns an investment project with the max gross value.""" gva_multiplier = GVAMultiplierFactory( multiplier=Decimal('9.999999'), financial_year=1980, ) with mock.patch( 'datahub.investment...
a0ec8d6a700f54c6e56f33ab3750e51dcd4a2283
51,415
def Adaptor3d_HSurfaceTool_VResolution(*args): """ :param S: :type S: Handle_Adaptor3d_HSurface & :param R3d: :type R3d: float :rtype: float """ return _Adaptor3d.Adaptor3d_HSurfaceTool_VResolution(*args)
3d26f8bca3ff02ac58d607c43f885d75e878e183
51,416
def enhance_contrast(im, cmap='pink', display_contrast=1): """Enhance contrast of the input image.""" im = ensure_positive(im) color_img = ind2cmap(im, cmap) color_img = color_img * 255 * display_contrast color_img[color_img > 255] = 255 color_img = np.uint8(color_img) return color_img
5a150d658f89bf09a6238cdaa01a6b9d986a3555
51,418
def drift_stability_ind( missing_recs_drift, drift_tab, missing_recs_stability, stability_tab ): """ This function helps to produce the drift & stability indicator for further processing. Ideally a data with both drift & stability should produce a list of [1,1] Parameters ---------- missing_recs...
6964f0b258d0c531e242b47ccc864b54c72d4dd0
51,420
import time def sample_function(integer1: int, integer2: int): """ This function takes as input two integers (integer1 and integer2) and returns integer1 raised to the power of integer2 Parameters: ----------- integer1 (int) a number greater than or equal to zero ...
2e3ff92a398adda8cc558c8a20f939614b0e0b94
51,421
def get_dfs(path): """ Grabs the different data splits and converts them into dataframes. Expects format from Code Search Net Challenge. """ dfs = [] for split in ["train", "valid", "test"]: files = sorted((path/split).glob("**/*.gz")) df = jsonl_list_to_dataframe(files, ...
6d293f2a4562c132675bab091d8f5d0b314e939d
51,422
def _get_entropy(data): """ helper function that calculates the entropy of the input array """ H = 0 for value in data: if value > 0: H -= value * np.log2(value) return H
0cf33bc39964571c9fb52ccef694e41bf91b003d
51,424
def make_doc(): """ Only used for sphinx documentation to add the prefix """ doc_app = Flask(__name__) doc_app.register_blueprint(bp, url_prefix='/tmp_dids') return doc_app
045b16f10aae4b55fd9c11f8309b6092f03b1bb0
51,425
def tf_box_4c_to_box_3d(boxes_4c, ground_plane): """Vectorized box_4c to box_3d conversion Args: boxes_4c: Tensor of boxes_4c (N, 10) ground_plane: Tensor of ground plane coefficients (4,) Returns: Tensor of boxes_3d (N, 7) """ format_checker.check_box_4c_format(boxes_4c) ...
f8ac4d71577510e58ed3b00255657fb4fe89be21
51,426
def timed(function): """ Log how long a function took :param function: Function to time :return: Result of the function """ @wraps(function) def wrapper(*args, **kwargs): start = timer() result = function(*args, **kwargs) print("{} took {} ms".format(function.__name__...
f2932a6acd13730eb2d450c24dc1bde8910a0096
51,427
def tfmatrix2tf(sys): """Convert a matrix of transfer functions to a MIMO transfer function. Parameters ---------- sys: list of (list of control.xferfcn.TransferFunction) The transfer function matrix representing a MIMO system. sys[i][j] is the transfer function from the i+1...
6e0ee5224162a0784e3fc30fde6ecb78ca5f4191
51,428
def active_genes_and_tf(active): """ From differentially expressed genes, return the genes and transcription factors. """ active = list(active) t_factors = list({gene.regulatory_product for gene in active if\ isinstance(gene.regulatory_product, TranscriptionFactor)}) return t_fac...
74a6393294f3f69666235ffae1e7d1a97b200566
51,429
def get_cmap(name: str) -> np.ndarray: """Retrieve the given colormap and return RGB values as a uint8 NumPy array of shape (255, 3)""" name = name.lower() if name not in AVAILABLE_CMAPS: raise ValueError(f'Unknown colormap {name}, must be one of {AVAILABLE_CMAPS}') with _get_cmap_data(name) a...
527c51d3c0cae517637509f9907c5d37215df3e8
51,430
def _addvFuncNumba( mNrmNext, mNrmGridNext, vNvrsNext, vNvrsPNext, MPCminNvrsNext, hNrmNext, CRRA, PermShkVals_temp, PermGroFac, DiscFacEff, ShkPrbs_temp, EndOfPrdvP, aNrmNow, BoroCnstNat, mNrmGrid, cFuncNow, mNrmMinNow, MPCmaxEff, MPCminNow, )...
1736d5451cf573067f19f7cab63490cb0cf6731e
51,431
def rename_get_variable(mapping): """ Args: mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'} Returns: A context where the variables are renamed. """ def custom_getter(getter, name, *args, **kwargs): splits = name.split('/') basename = s...
17aded74fb06d7aeaba7ecedccb07622775d5d96
51,432
import functools def with_color(color_code: str): """Coloring decorator Arguments: color_code {str} -- e.g.: '\033[91m' """ def wrapper(func): @functools.wraps(func) def inner(args): result = func(f'{color_code}{args}\033[0m') return result retu...
3f5ecd79b3d4579ba4348b2492eaaa3688201907
51,433
def compute_accuracy(idxR,idx,k): """ # =============================== #----- INPUT # idxR : real labels # idx : estimated labels # k : number of class #----- OUTPUT # ACC_glob : global accuracy # tab_acc : accuracy per class # =============================== """ ...
bf70ac41be460cd7623ccf8dcc85073c7bac69a6
51,434
def tri_lexique_lemme(corpus,lex_5g,lex_4g,lex_3g,lex_2g,dict_lexique): """ dans un corpus, retrouve les mwes d'un lexique donné en passant par les lemmes entrée : - corpus .conllu (lu par read_file()) - lexiques de mwe ordonnées par tailles de mwe - dico {'mwe' : 'POS associée'} sortie : - dico {phrase : [lis...
814d07ef0a8517c7161aa0038d7c2b3cca44f298
51,435
def count_ones(value: bytes) -> int: """Count the number of 1's in the binary string.""" return bin(value).count("1")
0752a267b977df5a6ff11160deb6ef2d14712d92
51,437
def test_kernel_shap_with_a1a_sparse_nonzero_background(): """ Check with a sparse non zero background matrix. """ np.set_printoptions(threshold=100000) np.random.seed(0) X, y = shap.datasets.a1a() # pylint: disable=unbalanced-tuple-unpacking x_train, x_test, y_train, _ = sklearn.model_selectio...
6eb54eee11efc99f983c37d55e6439344a6a0f5f
51,438
def is_lyrics_content_ok(title, text): """Compare lyrics text to expected lyrics for given title""" setexpected = set(LYRICS_TEXTS[lyrics.slugify(title)].split()) settext = set(text.split()) setinter = setexpected.intersection(settext) # consider lyrics ok if they share 50% or more with the referen...
330f60eab27ea754d383cd98d9671926e0801bff
51,439
def ratio_enum(anchor, ratios): """Enumerate a set of anchors for each aspect ratio wrt an anchor """ base_w, base_h, x_ctr, y_ctr = genwhctrs(anchor) size = base_w * base_h # 16 * 16 size_ratios = size / ratios # (2*16**2, 1*16**2, 0.5*16**2) a_w = np.round(np.sqrt(size_ratios)) a_h = np.round(a_w * ra...
16871ffa286ef0091ffb9074b143e87474e26c57
51,440
import shlex from typing import Sequence def escape_value(value: OptionValueType) -> OptionValueType: """Escapes an option value based on its type.""" if isinstance(value, str): return shlex.quote(value) elif isinstance(value, Sequence): return [shlex.quote(v) for v in value] else: ...
20636c3239edc5cf8c328a5df68478cf0366e979
51,441
def over(funcs): """Creates a function that invokes all functions in `funcs` with the arguments it receives and returns their results. Args: funcs (list): List of functions to be invoked. Returns: function: Returns the new pass-thru function. Example: >>> func = over([max...
6cd1a966366ee372c18dd35d71adf91028a04b1c
51,442
import logging def get_logger(): """retrieves logger ("singleton"). Returns ------- logging.Logger logger for this module """ global module_name try: get_logger.logger except AttributeError: get_logger.logger = logging.getLogger(module_name) return get_...
ba83ed2db59f879ccaf8b04f8a0a5ee2bb7e4d5e
51,443
def load_labels_map(labels_map_path): """Loads the labels map from the given path. The labels mmap must be in the following plain text format:: 1:label1 2:label2 3:label3 ... The indexes are irrelevant to this function, they can be in any order and can start from zero,...
8ff1e41b87fedffa053981299c48488add754ff9
51,444
def get_user(email): """ Return a user object by email lookup """ model = get_user_model() return model.objects.get(email=email)
3d85bdac487c06c33cf754976be87bb9873b335f
51,445
def generate_pruned_random_no_correlations_dataset(n_token, n_docs, n_subjects, min_samples): """Generate random data without any subject correlations, but with minimum samples per subject.""" dataset = generate_random_dataset(n_token, n_docs, n_subjects) return filter_subjects_with_insufficient_samples(dat...
ae31b487da75f7bc4c079aa3981cd41b10c9e1ac
51,446
async def m_aggregate(table, pipeline, **kwargs): """ aggregate """ db, kwargs = get_motor(**kwargs) plan = await db.command(SON([("aggregate", table), ("pipeline", pipeline)])) return plan
08e1969a22250cba648a2880a207f8699e0a6bb6
51,447
from typing import List def neurons_values(lstm_layer: md.ml.nn.layers.LSTMLayer, data: List[float], ppty_name: str) -> List[np.ndarray]: """ Get the activation values for a LSTM layer Args: lstm_layer: LSTM layer data: data to process ppty_name: the type of values to get Returns: List where each position ...
780fcf16698385e71f3426274f4f34782ec2a005
51,448
import math def bbox_to_integer_coords(t, l, b, r, image_h, image_w): """ t, l, b, r: float Bbox coordinates in a space where image takes [0; 1] x [0; 1]. image_h, image_w: int return: t, l, b, r int Bbox coordinates in given ima...
90fb198e2d6cd170a2e7a2b648f15554a9997389
51,450
def load_config(args): """Tries to load the configuration file or throws ExitWithError.""" config = ConfigManager(DEFAULT_CONFIG) config_dir = home_dir.get() try: if args.config_file is not None: filename_override = os.path.abspath(args.config_file) else: filename...
4f8070d8d5373571d44d6c72a9c5e04f7b33497e
51,451
import numpy as np def circular_layout(G, scale=1, center=None, dim=2): # dim=2 only """Position nodes on a circle. Parameters ---------- G : NetworkX graph or list of nodes A position will be assigned to every node in G. scale : number (default: 1) Scale factor for positions...
eb679719704fa260381b26b558d505deeb09a8a0
51,452
def sdp_sub(f, g, u, O, K): """Subtract distributed polynomials in `K[X]`. """ h = dict(f) for monom, c in g: if h.has_key(monom): coeff = h[monom] - c if not coeff: del h[monom] else: h[monom] = coeff else: h[...
2c82175cca3f209327ac48a8ef436300231d3337
51,453
def create_meeting(): """ При GET запросе возвращает страницу для создания встречи. При POST запросе, в случае успешной валидации сохраняет новую встречу в БД. """ title = 'Создание встречи' meeting_form = MeetingForm(request.form) with db_session() as session: meet_data = GameMe...
473ac76693589b5f46d846ea05d0e623e991b85b
51,454
def correlation_ratio(col1: ndarray, col2: ndarray) -> float: """Returns the correlation ratio for col1 and col2. Used for categorical - numerical variable pairs. Args: col1 (ndarray): A categorical column with no null values col2 (ndarray): A numerical column with no null values""" uni...
016ff428c1895bf4cb5380baac95fbba9ec76c74
51,455
def read_txt_tensor(filePath): """ read tensor data from text file. Parameters ---------- filePath : str the path of file Returns ------- tensor three-way numpy array """ tensor = pd.read_csv(filePath, header=0, names= ["v1", "v2", "v3", "v4"]) rowIndices ...
15f65958d9937f00c532dbc383bac5b2cb4ef990
51,456
from typing import Tuple from typing import Any def train_sequence_model(data: Tuple[Any, Any], output_dir: str, embedding_dim: int = 200, dropout_rate: float = 0.2, filters: int = 3, kernel_size: int = 3, pool_size: int = 3, num_classes: int = 3, learning_rate: float...
da3769bfa017e68ec9e7bca2c40a4692c1f6a028
51,457
def get_pose3_vector(num_poses: int) -> Pose3Vector: """Generate camera poses for use in triangulation tests""" # Looking along X-axis, 1 meter above ground plane (x-y) upright = Rot3.Ypr(-np.pi / 2, 0.0, -np.pi / 2) pose1 = Pose3(upright, Point3(0, 0, 1)) # create second camera 1 meter to the rig...
196c33faec30cb74b59a2302397ac41866bc0d3a
51,459
def from_datestring(datestring): """Parse an arbitrary datestring and return a datetime object using dateutils' parser. """ if dateutil_available: return parser.parse(datestring) else: raise RuntimeError('from_datestring requires the python-dateutil library')
98efc647c609c6cf34474ecdb18c985551975089
51,461
def clean_word(word): """Clean the word. Parameters ---------- word : str Returns ------- str """ new_word = (word .replace('(', '') .replace(')', '') .replace(':', '') .replace(';', '') .replace('+', '...
5d776bd9ad6bcb7824e56bafb15d6fec0fae6024
51,462
from emonitor.extensions import scheduler from emonitor.lib.osm.loaddata import parseOsmData def getAdminData(self, **params): """ Deliver admin content of module maps (ajax) :return: rendered template as string or json dict """ if request.args.get('action') == 'checkpath': if os.path.exi...
cda30d64a5294b30716cfa35598efcf29bbb969d
51,464
def get_attrib_recursive(element, *attribs): """Find the first attribute in attribs in element or its closest ancestor that has any of the attributes in attribs. Usage examples: get_attrib_recursive(el, "fallback-langs") get_attrib_recursive(el, "xml:lang", "lang") Args: elemen...
d04ba71a280bd1697cc61b79af21df46023473d2
51,465
def _antisymmetricity_score(v_1: float, v_2: float, coef_lambda: float): """ degree of the anti-symmetry between two values. z = exp(-\lambda*d(v_1,v_2)) d(v_1,v_2) = |v_1 + v_2| :param v_1: a value :param v_2: another value :param lambda: exponential decay parameter. :return: z """ ...
8e8912cae7b009a27303a33a79c30898da7ac88f
51,466
def find_extra_inferred_properties(spec_dict: dict) -> list: """Finds if there are any inferred properties which are used. Args: spec_dict: Dict obj containing configurations for the import. Returns: List of properties that appear in inferredSpec but are not part of 'pvs' section. """ re...
3be2950a227cfca8d0ab4c4413322f8aa8b22cc0
51,467
import time def signup(driver, Users, ISAAC_WEB, WAIT_DUR, **kwargs): """Test whether users can sign up to Isaac using an email address. - 'driver' should be a Selenium WebDriver. - 'Users' must be a TestUsers object. - 'ISAAC_WEB' is the string URL of the Isaac website to be tested. ...
1f9cfd19c48984c93cf721033e0218fbb1463153
51,468
import torch def collate(data, tokenizer, block_size, device): """ Collate formats the data passed to the data loader. In particular we tokenize the data batch after batch to avoid keeping them all in memory. We output the data as a namedtuple to fit the original BertAbs's API. """ data = [x f...
bb5b04bf69b33f033570910020dc4985f93670e4
51,469
def _read_json(nc): """ This is easily the laziest piece of code in this library. In the future, I want to modify this to be a simple CFG parser to identify valid JSON, but in the meantime, performance wasn't my priority, and this gets the job done. """ json_str = '' last_char = '' whil...
11f5e7259d106044f5fd0d33711c367b92dba96c
51,470
def zeroDistanceByFit(analysis, axis='y', useTrap='pm'): """ Find the trap distance at which the beads touch and use this as an offset to calculate the extension. Args: analysis (:class:`.TweezersAnalysis`): analysis file to check axis (str): axis on which to do the correction, either 'y' (...
89c7906a166dc3d66e58f74da65b3b1df697300f
51,471
def log_file_path(): """ Provides the path where tor's log file resides, if one exists. :returns: **str** with the absolute path of tor log file, or **None** if one doesn't exist """ controller = tor_controller() for log_entry in controller.get_conf('Log', [], True): entry_comp = lo...
b485955858b55c14f88a5349be46204ec85eebaa
51,472
def topics(request): """显示所有的主题""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context)
b31f6094d8a138e681414c7518dd746c0bcf924f
51,473