content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def pairs_to_annotations(annotation_pairs): """ Convert an array of annotations pairs to annotation array. :param annotation_pairs: list(AnnotationPair) - annotations :return: list(Annotation) """ annotations = [] for ap in annotation_pairs: if ap.ann1 is not None: annota...
b0e08889f541b14d596616d08b366f59b7f8ddd3
26,600
def sanitize_param(value, valid_characters=valid_chars, character_map=mapped_chars, invalid_character='X'): """Clean incoming parameters (strings or lists)""" if isinstance(value, string_types): return sanitize_text(value, valid_characters=valid_characters, character_map=character_map, invalid_character...
e3ed0d1a62bdbff0c2b3a204836d4d3afe467ced
26,601
def default_meta(inherit=True): """Initialize default meta for particular plugin. Default Meta is inherited by all children comparing to Meta which is unique per plugin. :param inherit: Whatever to copy parents default meta """ def decorator(plugin): plugin._default_meta_init(inherit)...
174b37f389160c007e7a609a78b5071031970004
26,602
def get_default_database_name(): """ gets default database name. :rtype: str """ return get_component(DatabasePackage.COMPONENT_NAME).get_default_database_name()
23bf228a284b5880a5155beced606ef4d6f81d16
26,603
def npm_local_packages(): """ Get list of local packages :return: a tuple of dicts """ local_dependencies = {} local_dev_dependencies = {} package_json = get_package_json() for name, version in package_json.get("dependencies", {}).items(): match = LOCAL_PACKAGE.match(version) ...
cb9f52bb97f402b00e3dac0c6a69332f2199ccd5
26,604
def lagrangian_descriptor(u, v, p_value = 0.5): """ Vector field equation for Lagrangian descriptor. Parameters ---------- v : ndarray, shape(n,2) Vector field at given point. p_value : float, optional Exponent in Lagrangian descriptor definition. 0 is the a...
ddd6bb7fb8538b6d44f2507e7b065cbe70338c39
26,605
def xymatch(x1, y1, x2, y2, tol=None, nnearest=1): """Fast cross-matching of xy coordinates: from https://gist.github.com/eteq/4599814""" x1 = np.array(x1, copy=False) y1 = np.array(y1, copy=False) x2 = np.array(x2, copy=False) y2 = np.array(y2, copy=False) if x1.shape != y1.shape: rais...
0c81add24308fdbe90144776fb4b72e9801ddd11
26,606
def get_infection_probas_mean_field(probas, transmissions): """ - probas[i,s] = P_s^i(t) - transmissions = csr sparse matrix of i, j, lambda_ij(t) - infection_probas[i] = sum_j lambda_ij P_I^j(t) """ infection_probas = transmissions.dot(probas[:, 1]) return infection_probas
70d5585b405bdff54f65bced166dead6ae45d26b
26,607
import time import ast def eval_task(algo, specific_testsets, measures, head_items, crossfold_index, save_path=None, load_path=None, uid_plus_iid_to_row=None): """ Evaluate on specific testsets. This function exists to make testset evaluation easier to parallelize. """ ret = [] if load_path an...
4f5171ea4473505237b2c353e164ba4b78d07357
26,608
def newton(RJ, x0, verbose = False, rtol = 1.0e-6, atol = 1.0e-10, miter = 50, linesearch = 'none', bt_tau = 0.5, bt_c = 1.0e-4): """ Manually-code newton-raphson so that I can output convergence info, if requested. Parameters: RJ function return the residual + jacobian x0 ...
b6baa3288c6f417ca4ec7284237ea35d4f2442dd
26,609
from typing import List from pathlib import Path def gen_oltp_trace( tpcc_weight: str, tpcc_rates: List[int], pattern_iter: int) -> bool: """ Generates the trace by running OLTP TPCC benchmark on the built database :param tpcc_weight: Weight for the TPCC workload :param tpcc_rates: Arrival ra...
8ac09fd8f85d7c83944759829775c3dbb1b0741e
26,610
def plot_hmesh(mesh, box=None, proj='pc', figsize=[9,4.5], title=None, do_save=None, do_lsmask='fesom', color_lsmask=[0.6, 0.6, 0.6], linecolor='k', linewidth=0.2, linealpha=0.75, pos_extend=None,): """ ---> plot FESOM2 horizontal mesh: ___INPUT:_____________________________...
9a921224440f359c33686822411b928ebd939550
26,611
def _get_feature_proportion(features_percentage: int, indices_number: int) -> int: """ Computes a number of features based on the given percentage. """ assert (isinstance(features_percentage, int) and 0 <= features_percentage <= 100 and isinstance(indi...
78a5d5515b479b20fcfbbf25cdd2339f0bc8b99f
26,612
def orthoProjectionMatrix(left, right, bottom, top, nearClip=0.01, farClip=100., out=None, dtype=None): """Compute an orthographic projection matrix with provided frustum parameters. Parameters ---------- left : float Left clipping plane coordinate. right : flo...
f1b80b8eeda514ff02142ffe6dcdd761cd789e73
26,613
def get_nsnames(zone): """Get list of nameservers names to query""" if Prefs.NO_NSSET: if not Prefs.ADDITIONAL: print("ERROR: -n requires specifying -a") usage() return Prefs.ADDITIONAL answers = dns.resolver.resolve(zone, 'NS', 'IN') return Prefs.ADDITIONAL + s...
1c5da972922afc0724144545a57bc1d01012dd11
26,614
def pbmcs_10x_cite_seq( save_path: str = "data/", protein_join: str = "inner", run_setup_anndata: bool = True, ) -> anndata.AnnData: """ Filtered PBMCs from 10x Genomics profiled with RNA and protein. Datasets were filtered for doublets and other outliers as in https://github.com/YosefLab/t...
eccb235496b6c466ffd2e234ab6b20487c7cf233
26,615
def binom(n, k): """Binomial coefficients for :math:`n choose k` :param n,k: non-negative integers :complexity: O(k) """ prod = 1 for i in range(k): prod = (prod * (n - i)) // (i + 1) return prod
73e06e4c312f6634d9a97914f330ade845a9ce00
26,616
import os def resource_map(): """Dynamically generate a map of resources that will be managed for a single hook execution. """ resource_map = deepcopy(BASE_RESOURCE_MAP) release = os_release('keystone') if CompareOpenStackReleases(release) < 'liberty': resource_map.pop(POLICY_JSON) ...
2d63bcf12687269c171d76f565d2e0c396511246
26,617
def get_not_found_swagger_schema(): """ """ class NotFoundResponseModel(Schema): """ """ type = "object" properties = { "message": { "type": "string", } } return NotFoundResponseModel
c1ac8c85224c2e885ade68593a1d250af09a465b
26,618
def find_project(testrun_url): """ Find a project name from this Polarion testrun URL. :param testrun_url: Polarion test run URL :returns: project name eg "CEPH" or "ContainerNativeStorage" """ url_suffix = testrun_url[59:] index = url_suffix.index('/') return url_suffix[:index]
a19019846fa084398a4967cb99417e7aebc90499
26,619
def c2ip(c2, uname): """ return complete ip address for c2 with substituted username """ return c2['ip_address'].replace('USER', uname)
c6f79b2330e78c8ebc85a3fb99ce1c5be407f158
26,620
def beacon(config): """ Watch the configured directories Example Config .. code-block:: yaml beacons: watchdog: - directories: /path/to/dir: mask: - create - modify - delete ...
5981f150276c2f9b9512c33864de02b0ce37094e
26,621
import json def scenario(request): """ Retrieve the parameters and nodes for a scenario Parameters: model_uuid (uuid): required scenario_id (int): required Returns: HttpResponse Example: GET: /component/scenario/ """ model_uuid = request.GET['model_uuid'] scenario_id = ...
795bad706c97c20b566d9fcc999b7e01b0b79194
26,622
def already_voted(replied: str, user_id: str, db: dataset.Database) -> bool: """Search in the database for an existing vote of the user on the replied message Args: replied: id of the message which the vote is a reply user_id: id of the user who's voting Returns: The return value. ...
89ec426df156776ab4a494f0dab0079881b45db2
26,623
def create_bi_sequence_embedding(inputs, seq_lengths, repr_dim, vocab_size, emb_name, rnn_scope, reuse_scope=False): """ Bidirectional encoding :param inputs: tensor [d1, ... ,dn] of int32 symbols :param seq_lengths: [s1, ..., sn] lengths of instances in the batch :param repr_dim: dimension of embed...
1f160100745801ac4baf3d82d8ee7b76900c0547
26,624
import mmap async def input_checker(user_guess: str) -> bool: """Check if the user's input is actually a word. Method for checking if input is in text file: https://stackoverflow.com/a/4944929""" if len(user_guess) != 5: valid = False else: with open(wordfile_path, encoding='utf-8', ...
60ffad6529b1a7b6d68309cc9804ff6e39e2e539
26,625
def pascal_voc_vgg16_config(): """Specify the parameters to tune below.""" mc = base_model_config('PASCAL_VOC') mc.DEBUG_MODE = False # Data Augmentation #mc.LOSS_TYPE = 'YOLO' mc.DATA_AUG_TYPE = 'YOLO' # Network Architecture mc.BN = True mc.IMAGE_WIDTH ...
0502074d7c376308a502509a38a532facd327ede
26,626
def computeBasisFunctionsReferenceElement(edge_orientation, face_orientation, Nord, points): """Compute the basis function for the reference element. :param ndarray edges_orientation: orientation for edges :param ndarray faces_orientation: orientation for faces :param int Nord: polynomial order of nede...
10579b5b6af4d5d270faf043186197c345a593d2
26,627
def load_wxbmp(name="", mask=False, image=None, maskpos=(0, 0), f=None, retry=True, can_loaded_scaledimage=True, noscale=False, up_scr=None): """pos(0,0)にある色でマスクしたwxBitmapを返す。""" if sys.platform <> "win32": assert threading.currentThread() <> cw.cwpy if not f and (not cw.binary.image....
d1611ac0740049d42495dd49e31cca869c73022c
26,628
def get_xixj(nodes_disjoint, knn, k): """ Get the features of each edge in the graph. Paramters --------- nodes : tf.Tensor shape (None, n_features) knn : tf.Tensor shape (None, k) int32, for each point, the indices of the points that are the nearest neighbors. ...
f07e0083b6a51053c5b08ccd299d9834e0dd7018
26,629
def t_returns(inv, pfl, prices, date): """ Computes the total return of a portfolio. Parameters: - `inv` : :class:`list` investment session `db` row - `pfl` : :class:`string` name of the portfolio - `prices` : :class:`dict` latest investment's ticker prices - `date` ...
8a928e0806b0e87d2a0539ff905112ad0d3d66ae
26,630
def center_crop_pad(img, buffer=0, min_mean=10): """dynamically center crop image, cropping away black space left and right""" g = np.array(img).mean(-1) h, w = g.shape zeros = g.mean(0) zero_inds = np.where(zeros < min_mean)[0] lo, hi = zero_inds[zero_inds < w // 2].max(), zero_inds[zero_inds >...
97326539464826441f283303e21a17b6ae2954d6
26,631
import os def resolve_settings_file(): """Returns path to buildtest settings file that should be used. If there is a user defined buildtest settings ($HOME/.buildtest/config.yml) it will be honored, otherwise default settings from buildtest will be used. """ # if buildtest settings file exist ret...
0acaf5d9da339e554e98fcb3bdbf3bfac5264622
26,632
def DiagPart(a): """ Diag op that returns only the diagonal elements. """ return np.diagonal(a),
4993f7034042303926f94f3dae28d7d8f8dc5058
26,633
def prometh_hosts(): """ 从apollo查询prome地址 :return: list """ external = env_file_conf('EXTERNAL', conf_type='bool') if not external: conf_name = 'prome_host' else: conf_name = 'prome_external_host' if external: print('Conneting to apollo from extern...
3370997eb9b44620fcc6e590c87aae07f04d7334
26,634
def _ensure_webhook_access(func): """Decorate WS function to ensure user owns the webhook ID.""" @callback @wraps(func) def with_webhook_access(hass, connection, msg): # Validate that the webhook ID is registered to the user of the websocket connection config_entry = hass.data[DOMAIN][D...
c1b64e5f435f79e52e8c69788b4354481d2a6f5b
26,635
import copy def episode_to_examples(episode, histsz): """Converts an episode (list of Parleys) into self-feeding compatible examples WARNING: we no longer require a histz when making a self-feeding file. Shortening of the history is typically done in the teacher file or in interactive mode. """ e...
a95abd0183dc70e195312d82117b16720d2c4353
26,636
import torch def camera_from_polyhedron(polyhedronFcn, camera_distance=1, to_spherical=False, device='cuda:0'): """ Returns the positions of a camera lying on the vertices of a given polyhedron Parameters ---------- polyhedronFcn : callable the polyhedron creation function camera_dist...
30c782b616299c101cc7130703563fae1327d364
26,637
def cifar10(args, dataset_paths): """ Loads the CIFAR-10 dataset. Returns: train/valid/test set split dataloaders. """ transf = { 'train': transforms.Compose([ transforms.RandomHorizontalFlip(0.5), transforms.RandomCrop((args.crop_dim, args.crop_dim), padding=args.pad...
867d3a6e7ff4ed72c02583c2eafab2885218c0ad
26,638
import sys import os import shutil import random def cleanthread(thread, settings): """ Reset thread parameters in preparation for the next step of aimless shooting after the previous one has completed. Add the next step to the itinerary if appropriate. Also write to history and output files, implement fo...
9d9b2c8819126fdc284805e94b6d37e75d0abb9a
26,639
def read_words(file="words.txt"): """ Reads a list of words from a file. There needs to be one word per line, for this to work properly. Args: file: the file to read from Returns: An array of all the words in the file """ with open(file, "r") as f: return f.read()....
d3d82c4f9afc7db73b4f82f4715cab9b2e99973c
26,640
def get_intersphinx_label(is_map, cur_project_dir): """ The top set of keys in the intersphinx map are shortname labels that intersphinx uses to identify different projects A sub-tuple in the dict (here invdata[1]) is a list of possible locations for the project's objects.inv file This utility checks a...
87115f45c966b838566d6909d3a66af5359a2a1d
26,641
async def patch_user(user: User): """update a `user` in the list of users""" try: session = Session() selected_user = session.query( UserTable ).filter( UserTable.key == user.key ).first() selected_user.firstname = user.firstname selected_u...
911b2c3f5f5e5c2ec7aa7be7595b5106ccf17b0d
26,642
import torchvision def get_test_dataloader(mean, std, batch_size=16, num_workers=2, shuffle=True,task="cifar100",train=False): """ return training dataloader Args: mean: mean of cifar100 test dataset std: std of cifar100 test dataset path: path to cifar100 test python dataset b...
402e119430a3d260e0e15238e6f55b91f929848a
26,643
from typing import Set def get(tags: Set[str]): """ get options marked by `tags` Options tagged by wildcard '*' are always returned """ # use specifically tagged options + those tagged with wildcard * return (o for tag in ('*',) + tuple(tags) for o in _options[tag])
164e808c5dcd76febad488b8fb5bf0b76835ec2a
26,644
def jitter_boxes(boxes, noise_scale=0.025): """Jitter the box coordinates by some noise distribution. Args: boxes: a tensor whose last dimension is 4 representing the coordinates of boxes in ymin, xmin, ymax, xmax order. noise_scale: a python float which specifies the magnitude of noise. The ru...
e0ac4b003b77190390f397f3ef80a915ca5214d3
26,645
def soil_props(soil_type, depth): """ Parameters c, Ks, n, Beta, s_h, s_w, s_bal, s_fc, bulk_d: Laio et al., 2001, Plants in water-controlled ecosystems: active role in hydrologic processes and response to water stress: II. Probabilistic soil moisture dynamic Parameters p1 through p5: Ezlit et al.,...
a6d421d5606d4a00e6a621a513939af8ce2ad62c
26,646
from typing import List def DoMeshesBelongToSameMainMesh(list_mesh_identifiers: List[str]) -> bool: """checks whether all meshes given a list of mesh identifiers belong to the same main mesh Throws if an mesh identifier does not belong to a mesh """ main_mesh_identifiers = [] for mesh_identifier i...
2e8e47c0b5bf4e6d67adf5a0a46a35bacba42bce
26,647
import random def test_ps_push_http(): """ test pushing to http endpoint """ if skip_push_tests: return SkipTest("PubSub push tests don't run in teuthology") zones, ps_zones = init_env() bucket_name = gen_bucket_name() topic_name = bucket_name+TOPIC_SUFFIX # create random port for the...
d7712d42d57d20edebadc4063fca87bb252e0320
26,648
import os def returnPaths(jsonObj): """ takes a json dict with new/old and path, construct paths and return result :param jsonObj: json dict :return: tuple of paths (oldPath, newPath) """ assert isinstance(jsonObj, dict), "In object not a dict" paths = coll.namedtuple("paths", ["oldPath",...
479752b65f1382c68f2301c2ef51f0948f3df000
26,649
def active_roles(account, days_back): """ Returns query for finding active roles (since days_back value). """ query_string = f"""SELECT DISTINCT useridentity.sessioncontext.sessionissuer.arn FROM behold WHERE account = '{account}' AND useridentity.type = 'AssumedRole' AND from_is...
e6842696aa40d4f0b30f17d0d53afdcc5d1d0de9
26,650
def sample_user(email='user@test.com', password='Test123'): """ Helper method to create a sample user for our test cases! :param email: Email address of the sample user :param password: A password for account creation. This can be a weak password as well since this is restricted to our testing e...
c07efd2bbbbfd120b97516d93645d4bd6f004804
26,651
import asyncio async def run_command(*args, **kwargs): """Shortcut for asyncronous running of a command""" fn = asyncio.subprocess.create_subprocess_exec if kwargs.pop("shell", False): fn = asyncio.subprocess.create_subprocess_shell check = kwargs.pop("check", False) process = await fn(*ar...
948ccb127afb8cf1c2a1731a5198bc493a1e9fe4
26,652
import torch def scaled_dot_product_attention(q, k, v, mask=None): """ #计算注意力权重。 q, k, v 必须具有匹配的前置维度。 且dq=dk k, v 必须有匹配的倒数第二个维度,例如:seq_len_k = seq_len_v。 #虽然 mask 根据其类型(填充或前瞻)有不同的形状, #但是 mask 必须能进行广播转换以便求和。 #参数: q: 请求的形状 == (..., seq_len_q, depth) k: 主键的形状 == (..., seq_len...
3d51de38ca553c3b769bd1ba4936159034cd68e0
26,653
def _get_parent_entity(entities, entity_id): """ Gets the parent entity from the collection, or throws ParentDoesNotExist. """ try: return entities[entity_id] except KeyError: raise ParentDoesNotExist(object_type='Entity', key=entity_id)
d898252058f191a2685803fc6d4495eb75ce56eb
26,654
def tstop(f): """ Dust stopping time """ units = sutil.get_all_units(f) grainSize = f['u_dustGrainSize'] grainDensity = SimArray(sutil.get_snap_param(f, 'dDustGrainDensity'), units['rho_unit']) if sutil.is_isothermal(f): gamma = 1. else: gamma = sutil.get_snap_gamma(...
e1f13c3b87104d366dd0c5239dd5d24de954897c
26,655
def solve_2d_discrete_observations_continuous_modelling( cond_xy0s_list: tp.List[tp.Tuple[float, float]], cond_xytGammas_list: tp.List[tp.Tuple[float, float, float]], cond_f0s_list: tp.List[float], cond_fGammas_list: tp.List[float], a: float, b: float, c: float, ...
a8139c014c292b44aee1cf4533a7576413a7e685
26,656
import logging from typing import Callable from typing import Any def log_calls_on_exception( logger: logging.Logger, log_exception: bool = True ) -> GenericDecorator: """ Log calls to the decorated function, when exceptions are raised. Can also decorate classes to log calls to all its methods. ...
98a186d116547c2929c010b66b9395ba5d5c8603
26,657
from typing import Callable from typing import Optional def _minimize_lbfgs( fun: Callable, x0: Array, maxiter: Optional[float] = None, norm=jnp.inf, maxcor: int = 10, ftol: float = 2.220446049250313e-09, gtol: float = 1e-05, maxfun: Optional[float] = None, maxgrad: Optional[float]...
da9c1efe5a69cdb2f7181826032f0d00bdad6f0f
26,658
def convert_2d_list_to_string(data): """Utility function.""" s = '' for row in data: c = '{' for e in row: c += str(e) + ',' s += c[:-1] + '},\n' return s[:-2]
a6ac2c05f481a339c68ffc3543baba1f1d0d5e8e
26,659
import argparse def _setup_argparser(): """Setup the command line arguments""" # Description parser = argparse.ArgumentParser( description="N-CREATE", usage="ncreate [options] peer port dcmfile-in") # Parameters req_opts = parser.add_argument_group('Parameters') req_opts.add_a...
57ef788da2e13f395c95704a0fec52f1aa76c407
26,660
def get_info(sheet, row_num, percentage, sheet_name, mandatory_tables): """ Function is used to create a dictionary that contains the number of flawed records for a particular site. :param sheet (dataframe): pandas dataframe to traverse. Represents a sheet with numbers indicati...
76552ee6cd366642d29c945a289b69efda28ba37
26,661
def get_structural_topology_reactions(filename, dset_path="readdy/config/structural_topology_reactions"): """ Construct a dictionary where the keys are reaction ids and value is corresponding name. :param filename: the file name :param dset_path: path to the dataset :return: dictionary of reactions...
a3bb4f75740b540c8428d760c087df4dea782a4e
26,662
def PyMapping_Keys(space, w_obj): """On success, return a list of the keys in object o. On failure, return NULL. This is equivalent to the Python expression o.keys().""" return space.call_function(space.w_list, space.call_method(w_obj, "keys"))
452b384a421fd675a53ff20d868b8f7353eb3d79
26,663
import aiohttp import json import asyncio async def safebooru(ctx, tag, page='1'): """Searches safebooru. Usage: safebooru [tags]""" async with aiohttp.ClientSession() as session: invoker = ctx.message.author post = await fetch(session, "https://safebooru.org/index.php?page=dapi&s=post&q=index...
782000d62de1d36abc4b81e0bb4b025707e79940
26,664
import re def is_arabicrange(text): """ Checks for an Arabic Unicode block characters @param text: input text @type text: unicode @return: True if all charaters are in Arabic block @rtype: Boolean """ if re.search(u"([^\u0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff\u0750-\u077f])", text): ...
70862e901236eb94fec95ac6f7eb673729397e49
26,665
def del_pool(batch_client, config, pool_id=None): # type: (azure.batch.batch_service_client.BatchServiceClient, dict, # str) -> bool """Delete a pool :param batch_client: The batch client to use. :type batch_client: `azure.batch.batch_service_client.BatchServiceClient` :param dict config:...
fad5a672920a98305f12e9a7e7c6d665ff874f0a
26,666
def str_repeat(space, s, repeat): """Repeat a string.""" return space.newstr(s * repeat)
3e947da1fa3bf403b0836bd4e7ae0052d310636e
26,667
def alarm(duration=250): """ Red alarm; flashing bright red to dark red. :param int duration: The duration between hi/lo brightness,in milliseconds. :returns: An infinite Flow consisting of 2 transitions. :rtype: Flow """ return Flow(count=0, action=Action.recover, transitions=transitions....
a501c6a85c78cd37eadba200ca327660945dd4d7
26,668
def mkvc(x, numDims=1): """Creates a vector with the number of dimension specified e.g.:: a = np.array([1, 2, 3]) mkvc(a, 1).shape > (3, ) mkvc(a, 2).shape > (3, 1) mkvc(a, 3).shape > (3, 1, 1) """ if type(x) == np.matrix: ...
e749e0feadcdf69625355477fd22e2f9d363768f
26,669
def location_distance_meters(a: Location, b: Location) -> float: """Calculates the distance between two points. Returns: A number of meters between two points. """ return location_distance_kilometers(a, b).m
91179bc0fc2647d502a290ecc1df28eda8b149f5
26,670
import json def file_to_dict(file: str): """Dump json file to dictionary""" try: with open(file) as json_file: return json.load(json_file) except json.decoder.JSONDecodeError: print(f'File {file} is not a valid json file. Returning empty dict') return {} except File...
2265f2ad5e10931e93a08bafd8e8a7e20c91ae93
26,671
def fieldtype(field): """Return classname""" return field.__class__.__name__
afda2f7a13a2d0be991eadf31ac591762c519f05
26,672
from typing import Dict def basic_extractor( data: Dict, ) -> list: """ Returns list of the total_recieved token, the total sent token and the number of transactions the wallet participated in. """ return [data["total_received"],data["total_sent"],data["n_tx"]]
946611423cf98c6104fa49e0ccb82308d741f900
26,673
def expand_stages_cfg(stage_cfgs): """ For a list of stages """ assert isinstance(stage_cfgs, list) ret = [] for x in stage_cfgs: ret.append(expand_stage_cfg(x)) return ret
bb562da9ca5a547fc1c442e3ba8d73b7f7d0768e
26,674
def find_team(): """find a team by using filters from request arguments""" # partial -> allow skipping of required fields ts = TeamSchema( partial=True, only=( "name", "event_id", "team_identifier", "payment_status", "single", ...
98aa1a67450aa9c117c5d9d7c158c169c2f7969c
26,675
def clusterbased_permutation_1d_1samp_1sided(results, level=0, p_threshold=0.05, clusterp_threshold=0.05, n_threshold=2, iter=1000): """ 1-sample & 1-sided cluster based permutation test for 2-D results Parameters ---------- results : array A re...
ade205fdd4c256567e0f1ce908f7a711caad2f5d
26,676
def getObjectsContainers(mQueryObject = []): """ Return a list of containers that the passed in objects reside in. @param [] mQueryObject: list of objects you are wanting to know, in which container they exists. @return: key = container name, value = container MObject. @rtype: {} """ contai...
83da454e85067a2d74f2f251f255a74f3bba41ee
26,677
from webdnn.backend.webgl.attributes.texture_shape import TextureShape from webdnn.backend.webgl.attributes.channel_mode import ChannelMode from typing import Optional def dump_dot(graph: Graph, name: Optional[str] = None) -> str: # pragma: no cover """ Dumps graph into dot language for visualization. A...
61e993c7383e939109463fd872501a6d7bda3d0d
26,678
def RPL_LUSERCLIENT(sender, receipient, message): """ Reply Code 251 """ return "<" + sender + ">: " + message
4863c4d6945378f315932fadbf8f2615f020c611
26,679
def multiply_inv_gaussians_batch(mus, lambdas): """Multiplies a series of Gaussians that is given as a list of mean vectors and a list of precision matrices. mus: list of mean with shape [..., d] lambdas: list of precision matrices with shape [..., d, d] Returns the mean vector, covariance matrix, and p...
3239ee6c472506c0b0fcc90c8543deeca0edb02e
26,680
def replace_if_present_else_append( objlist, obj, cmp=lambda a, b: a == b, rename=None): """ Add an object to a list of objects, if that obj does not already exist. If it does exist (`cmp(A, B) == True`), then replace the property in the property_list. The names are c...
f76b3a76fe973ef91176f8ff4afd34d52ce89317
26,681
def rating_value(value): """Check that given value is integer and between 1 and 5.""" if 1 <= int(value) <= 5: return int(value) raise ValueError("Expected rating between 1 and 5, but got %s" % value)
cadb45a131a423940e1b3a763935f5e40d84285b
26,682
def hsc_to_hs(ctx): """Process all hsc files into Haskell source files. Args: ctx: Rule context. Returns: list of File: New Haskell source files to use. """ ghc_defs_dump = _make_ghc_defs_dump(ctx) sources = [] for f in ctx.files.srcs: if f.extension == "hsc": sources.append(_process_h...
7672ad9b3679fc663b461f4bcb9eb421293dc185
26,683
from shapely.geometry import Polygon def calculate_iou_box(pts1, pts2): """ Measure the two list of points IoU :param pts1: ann.geo coordinates :param pts2: ann.geo coordinates :return: `float` how Intersection over Union of tho shapes """ try: except (ImportError, ModuleNotFoundError)...
fe915dc952852e28214ce1a16f781c55600fc1ec
26,684
def nextafter(x, direction, dtype, itemsize): """Return the next representable neighbor of x in the appropriate direction.""" assert direction in [-1, 0, +1] assert dtype.kind == "S" or type(x) in (bool, float, int) if direction == 0: return x if dtype.kind == "S": return stri...
c14f6695eb4285afe3001ac6db019af26a95c78c
26,685
def integrated_circular_gaussian(X=None, Y=None, sigma=0.8): """Create a circular Gaussian that is integrated over pixels This is typically used for the model PSF, working well with the default parameters. Parameters ---------- X, Y: `numpy.ndarray` The x,y-coordinates to evaluate the ...
63201f6c37fba1e3750881cd692057c2bd5011b0
26,686
def nPairsToFracPairs(hd_obj, all_pairs_vs_rp, redshift_limit = 2): """ Function to convert the number of pairs into a fractional number density per shell @redshift_limit :: the initial redshift limit set on the sample (needed for opening dir) """ num_pairs = all_pairs_vs_rp[1:] - all_pairs_vs_rp[:-...
d9d8f72d8f05cff4e984b43f4a22da406dfe1c05
26,687
import os import argparse def is_valid_image(arg): """ Verifies that a given argument is a valid image files arg: string representing filepath Returns ------- img : A W*H*3 array representing a color image """ if not os.path.isfile(arg): raise argparse.ArgumentTypeError(f"{a...
6fd4551be4961a5734f6c65f7e270c6063a93677
26,688
def default_decode(events, mode='full'): """Decode a XigtCorpus element.""" event, elem = next(events) root = elem # store root for later instantiation while (event, elem.tag) not in [('start', 'igt'), ('end', 'xigt-corpus')]: event, elem = next(events) igts = None if event == 'start' a...
36e0b4b13cb357d74cee20623e5a71cf9a5dd02a
26,689
def attention_guide(dec_lens, enc_lens, N, T, g, dtype=None): """Build that W matrix. shape(B, T_dec, T_enc) W[i, n, t] = 1 - exp(-(n/dec_lens[i] - t/enc_lens[i])**2 / (2g**2)) See also: Tachibana, Hideyuki, Katsuya Uenoyama, and Shunsuke Aihara. 2017. “Efficiently Trainable Text-to-Speech System Base...
2af05dedb5260e52150d96b181fab063cd17efb8
26,690
from typing import Union import os from pathlib import Path import gzip def flex_load(file_path: Union[str, os.PathLike, PurePath], default_serializer=None, default_is_gzipped=False) -> Union[dict, list]: """ Determines which serializer is needed to open the file and whether it's c...
322e15958fda033904696d3db6988e027db54906
26,691
def two_step_colormap(left_max, left, center='transparent', right=None, right_max=None, name='two-step'): """Colormap using lightness to extend range Parameters ---------- left_max : matplotlib color Left end of the colormap. left : matplotlib color Left middle of the colormap. ...
226dfd9a9beaadf5a47167c6080cdb3ba8fa522f
26,692
def _broadcast_arg(U, arg, argtype, name): """Broadcasts plotting option `arg` to all factors. Args: U : KTensor arg : argument provided by the user argtype : expected type for arg name : name of the variable, used for error handling Returns: iterable version of arg...
3a441b9156f7cf614b2ab2967159349252802bed
26,693
import os import subprocess import locale import sys def _exec_command(command, use_shell=None, use_tee = None, **env): """ Internal workhorse for exec_command(). """ if use_shell is None: use_shell = os.name=='posix' if use_tee is None: use_tee = os.name=='posix' if os.name =...
16bb0ad58c4372519e749564f2d4154ec208d7a3
26,694
import signal def xkcd_line(x, y, xlim=None, ylim=None, mag=1.0, f1=30, f2=0.05, f3=15): """ Mimic a hand-drawn line from (x, y) data Definition ---------- def xkcd_line(x, y, xlim=None, ylim=None, mag=1.0, f1=30, f2=0.05, f3=15): Input ----- x, y ...
ea36487d6e2f4f9d5d0bc9d5cea23459a5b8a5a4
26,695
def generate_mutation() -> str: """ Retrieve staged instances and generate the mutation query """ staged = Node._get_staged() # localns = {x.__name__: x for x in Node._nodes} # localns.update({"List": List, "Union": Union, "Tuple": Tuple}) # annotations = get_type_hints(Node, globalns=global...
789e6042226ed25451d7055bc9b383b81fd10ddf
26,696
from datetime import datetime def start(fund: Fund, start_date: datetime) -> Fund: """ Starts the fund by setting the added USD and the market value of the manager as the current market value. Meaning that at the beginning there is only the manager's positions. :param fund: The fund to start :...
e7f4a273b4c48eb3f9e440f663fee45847df902a
26,697
def _make_experiment(exp_id=1, path="./Results/Tmp/test_FiftyChain"): """ Each file specifying an experimental setup should contain a make_experiment function which returns an instance of the Experiment class with everything set up. @param id: number used to seed the random number generators @p...
6cf51f8957e091175445b36aa1d6ee7b22465835
26,698
def find_largest_digit_helper(n, max_n=0): """ :param n: int,待判別整數 :param max_n: int,當下最大整數值 :return: int,回傳n中最大之 unit 整數 """ # 特殊情況:已達最大值9,就不需再比了 if n == 0 or max_n == 9: return max_n else: # 負值轉換為正值 if n < 0: n *= -1 # 用餘數提出尾數 unit_n = n % 10 # 尾數比現在最大值 if unit_n > max_n: max_n = unit_n ...
cd60a0cdb7cdfba6e2374a564bb39f1c95fe8931
26,699