content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def generate_extra(candidate: tuple, expansion_set, murder_list=None, attempted=None) -> list: """ Special routine for graph based algorithm :param candidate: :param expansion_set: :param murder_list: :param attempted: :return: """ check = manufacture_lambda(attempted, murder_list) ...
e38d605df2a562b269189c8e7714ec97e89d8f36
20,100
from typing import Tuple from typing import Dict def extract_oe_stereochemistry( molecule: Molecule, oe_mol: "OEMol" ) -> Tuple[Dict[int, AtomStereochemistry], Dict[int, BondStereochemistry]]: """Extracts the CIP stereochemistry of each atom and bond in a OE molecule.""" atom_stereo = { oe_atom.G...
0d051e847c94a81585a1478fc10bfac335d700a6
20,101
from dipy.denoise.nlmeans import nlmeans from scipy.ndimage.morphology import binary_erosion from scipy import ndimage def nlmeans_proxy(in_file, settings, snr=None, smask=None, nmask=None, out_file=None): """ Uses non-local means to deno...
69629ef536830ccecdee09e5acfadf02d892cc9d
20,102
from typing import Union import os from typing import Any from typing import Optional from typing import List from pathlib import Path def dissolve( input_path: Union[str, 'os.PathLike[Any]'], output_path: Union[str, 'os.PathLike[Any]'], explodecollections: bool, groupby_columns: Opt...
3f3d89bf99f025ea23c338d0c36f9e7cc9e9c6ae
20,103
def jointImgTo3D(sample): """ Normalize sample to metric 3D :param sample: joints in (x,y,z) with x,y in image coordinates and z in mm :return: normalized joints in mm """ ret = np.zeros((3,), np.float32) # convert to metric using f ret[0] = (sample[0]-centerX)*sample[2]/focalLengthX ...
43726ed712e268c9fd2434fa2734ff8aa0ee2d0a
20,104
from typing import Set from typing import Callable from typing import List import logging def _find_registered_loggers( source_logger: Logger, loggers: Set[str], filter_func: Callable[[Set[str]], List[logging.Logger]] ) -> List[logging.Logger]: """Filter root loggers based on provided parameters.""" root_...
a15464298030821cea0beb61eaf1c679732e4155
20,105
def build_param_obj(key, val, delim=''): """Creates a Parameter object from key and value, surrounding key with delim Parameters ---------- key : str * key to use for parameter value : str * value to use for parameter delim : str * str to surround key with when adding to...
0fba11c4564ef57eab45ffd02bed887c42a14121
20,106
def copy_fixtures_to_matrixstore(cls): """ Decorator for TestCase classes which copies data from Postgres into an in-memory MatrixStore instance. This allows us to re-use database fixtures, and the tests designed to work with those fixtures, to test MatrixStore-powered code. """ # These meth...
b64ef9b23afc76b8f1b2cf1ae6b56635cd6e4f56
20,107
def intersect_description(first, second): """ Intersect two description objects. :param first: First object to intersect with. :param second: Other object to intersect with. :return: New object. """ # Check that none of the object is None before processing if first is None: retur...
93d35314f8ab6ef0978de942ecfad3719c8f4971
20,108
def smooth_correlation_matrix(cor, sigma, exclude_diagonal=True): """Apply a simple gaussian filter on a correlation matrix. Parameters ---------- cor : numpy array Correlation matrix. sigma : int, optional Scale of the gaussian filter. exclude_diagonal : boolean, optional ...
753337cc12578b5c2333392f01e028204ac2f0e0
20,109
def quantize_iir_filter(filter_dict, n_bits): """ Quantize the iir filter tuple for sos_filt funcitons Parameters: - filter_dict: dict, contains the quantized filter dictionary with the following keys: - coeff: np.array(size=(M, 6)), float representation of the coefficients - coeff_scale: n...
a8e93302072733d77acb563cd758725f14c05420
20,110
import json import traceback def add_goods(request, openid, store_id, store_name, dsr, specification, brand, favorable_rate, pic_path, live_recording_screen_path, daily_price, commission_rate, pos_price, preferential_way, goods_url, hand_card, storage_condition, shelf_life, u...
e7a04a316e3fba3a803f20eb459dc8691ccc2642
20,111
import argparse def cli_to_args(): """ converts the command line interface to a series of args """ cli = argparse.ArgumentParser(description="") cli.add_argument('-input_dir', type=str, required=True, help='The input directory that contains pngs and svgs o...
db9502472d1cab92b7564abde2969daa06dbc4aa
20,112
import random import argparse import base64 import os def main(): """ Run the generator """ util.display(globals()['__banner'], color=random.choice(list(filter(lambda x: bool(str.isupper(x) and 'BLACK' not in x), dir(colorama.Fore)))), style='normal') parser = argparse.ArgumentParser( pr...
f5c30d902f6123ce66579c7ba9c5dbe4f5ed580b
20,113
import string def _get_metadata_from_configuration( path, name, config, fields, **kwargs ): """Recursively get metadata from configuration. Args: path: used to indicate the path to the root element. mainly for trouble shooting. name: the key of the metadata section. ...
57dcbf0de49499391d8336d09b5b47d6c0f0d2e8
20,114
def calcOneFeatureEa(dataSet: list, feature_idx: int): """ 获取一个特征的E(A)值 :param dataSet: 数据集 :param feature_idx: 指定的一个特征(这里是用下标0,1,2..表示) :return: """ attrs = getOneFeatureAttrs(dataSet, feature_idx) # 获取数据集的p, n值 p, n = getDatasetPN(dataSet) ea = 0.0 for attr in attrs: ...
fc800b285bc24246ad9c40070d33ff429e395183
20,115
def translate_mapping(mapping: list, reference: SimpleNamespace, templ: bool=True, nontempl: bool=True, correctframe: bool=True, filterframe: bool=True, filternonsense: bool=True): """ creates a protein mapping from a dna mapping. :param mapping: a list/tuple of ops. :param referen...
3a05ae38d9bccb8b855c91af850a92426c5031f3
20,116
from copy import copy from numpy import zeros, unique from itertools import product def trainModel(label,bestModel,obs,trainSet,testSet,modelgrid,cv,optMetric='auc'): """ Train a message classification model """ pred = zeros(len(obs)) fullpred = zeros((len(obs),len(unique(obs)))) model = copy(bestMode...
8cea9f0044246972e80684fac584693a500198cc
20,117
def get_device_state(): """Return the device status.""" state_cmd = get_adb_command_line('get-state') return execute_command( state_cmd, timeout=RECOVERY_CMD_TIMEOUT, log_error=True)
e517e7df3f5a7a1bf3925a46ce6a780dbc862910
20,118
def character_state(combat, character): """ Get the combat status of a single character, as a tuple of current_hp, max_hp, total healing """ max_hp = Max_hp(character.base_hp) total_h = 0 for effect in StatusEffect.objects.filter(character=character, combat=combat, effect_typ__typ='M...
d80315934ac653d34dd73cc1a9861b9c6e2f2c9c
20,119
def load_textfile(path) : """Returns text file as a str object """ f=open(path, 'r') recs = f.read() # f.readlines() f.close() return recs
8e12a93bb4918cbae7d7e9aad6f09f562eca0c16
20,120
import scipy def interp1d_to_uniform(x, y, axis=None): """Resample array to uniformly sampled axis. Has some limitations due to use of scipy interp1d. Args: x (vector): independent variable y (array): dependent variable, must broadcast with x axis (int): axis along which to resam...
379071e0e0b718b4d4f8cc970a2b098cf3cab155
20,121
import os def get_walkthrought_dir(dm_path): """ return 3 parameter: file_index[0]: total path infomation file_index[1]: file path directory file_index[2]: file name """ file_index = [] for dirPath, dirName, fileName in os.walk(dm_path): for ...
74ecef62531001c27e05ab42b731739120656695
20,122
from typing import Dict def flatten_dict(d: Dict): """Recursively flatten dictionaries, ordered by keys in ascending order""" s = "" for k in sorted(d.keys()): if d[k] is not None: if isinstance(d[k], dict): s += f"{k}|{flatten_dict(d[k])}|" else: ...
26663b52ccda2a695aa2367cbaf324698a47d56a
20,123
def getPVvecs(fname): """ Generates an ensemble of day long PV activities, sampled 3 different days for each complete pv data set """ datmat = np.zeros((18,48)) df = dd.read_csv(fname) i = 0 for unique_value in df.Substation.unique(): ttemp, ptemp = PVgettimesandpower("2014-06", unique_value, fname) t, ...
322cf6d29d4104953678ec5e4dfbd5a82564ce1c
20,124
def vis9(n): # DONE """ O OO OOO OO OOO OOOO OOO OOOO OOOOO Number of Os: 6 9 12""" result = 'O' * (n - 1) + 'O\n' result += 'O' * (n - 1) + 'OO\n' result += 'O' * (n - 1) + 'OOO\n' return result
c06c9fdf5d71ef89ce83d5fc2136b9854f018988
20,125
def derivative_circ_dist(x, p): """ Derivative of circumferential distance and derivative function, w.r.t. p d/dp d(x, p) = d/dp min_{z in [-1, 0, 1]} (|z + p - x|) Args: x (float): first angle p (float): second angle Returns: float: d/dp d(x, p) """ # pylin...
36a4cc04cda32e8c6e5896d405f96068def8be41
20,126
def get_MB_compatible_list(OpClass, lhs, rhs): """ return a list of metablock instance implementing an operation of type OpClass and compatible with format descriptor @p lhs and @p rhs """ fct_map = { Addition: get_Addition_MB_compatible_list, Multiplication: get_Multiplication_M...
172ca13f218f52e5834592fd09abf9444369d60c
20,127
import torch import random def create_mock_target(number_of_nodes, number_of_classes): """ Creating a mock target vector. """ return torch.LongTensor([random.randint(0, number_of_classes-1) for node in range(number_of_nodes)])
1be4d86a0291d24f0be555d4eea7d29f0994db29
20,128
def is_iterable(obj): """ Return true if object has iterator but is not a string :param object obj: Any object :return: True if object is iterable but not a string. :rtype: bool """ return hasattr(obj, '__iter__') and not isinstance(obj, str)
c7a1353f7f62a567a65d0c4752976fefde6e1904
20,129
import logging def convert_loglevstr_to_loglevint(loglevstr): """ returns logging.NOTSET if we fail to match string """ if loglevstr.lower() == "critical": return logging.CRITICAL if loglevstr.lower() == "error": return logging.ERROR if loglevstr.lower() == "warning": return logging.WARNING if loglevstr.l...
7d821ac54368012f60c220fd2f8d56267daa0006
20,130
def get_operator_module(operator_string): """ Get module name """ # the module, for when the operator is not a local operator operator_path = ".".join(operator_string.split(".")[:-1]) assert len(operator_path) != 0, ( "Please specify a format like 'package.operator' to specify your opera...
82b4ddc419b09b5874debbe64262b4a4f414cb8f
20,131
def is_fraction(obj): """Test whether the object is a valid fraction. """ return isinstance(obj, Fraction)
ab0a1b11274f837f479fb62648a144f0e689b499
20,132
def getExtrusion(matrix): """calculates DXF-Extrusion = Arbitrary Xaxis and Zaxis vectors """ AZaxis = matrix[2].copy().resize3D().normalize() # = ArbitraryZvector Extrusion = [AZaxis[0],AZaxis[1],AZaxis[2]] if AZaxis[2]==1.0: Extrusion = None AXaxis = matrix[0].copy().resize3D() # = ArbitraryXvector else:...
ec6133bddc9093310ffe1e807ae24882aa24edc3
20,133
def _build_class_include(env, class_name): """ If parentns::classname is included and fabric properties such as puppet_parentns__classname_prop = val1 are set, the class included in puppet will be something like class { 'parentns::classname': prop => 'val1', } """ include_def = ...
f58633fefb3ca853ef292f554eea4f98126c3ecb
20,134
async def mention_html(user_id, name): """ The function is designed to output a link to a telegram. """ return f'<a href="tg://user?id={user_id}">{escape(name)}</a>'
eed9dd188f36e4d23bb16e274382372c6464f890
20,135
from plasma.flex.messaging.messages import small def blaze_loader(alias): """ Loader for BlazeDS framework compatibility classes, specifically implementing ISmallMessage. .. seealso:: `BlazeDS (external) <http://opensource.adobe.com/wiki/display/blazeds/BlazeDS>`_ :since: 0.1 """ i...
956acd6aa9c36c186081a43e271b6a3c61b7a53f
20,136
def get_user_pic(user_id, table): """[summary] Gets users profile picture Args: user_id ([int]): [User id] table ([string]): [Table target] Returns: [string]: [Filename] """ try: connection = database_cred() cursor = connection.cursor() curso...
28ea65c793e88b967889fa39dc8588e4afd75e91
20,137
def convert_file_format(files,size): """ Takes filename queue and returns an example from it using the TF Reader structure """ filename_queue = tf.train.string_input_producer(files,shuffle=True) image_reader = tf.WholeFileReader() _,image_file = image_reader.read(filename_queue) image =...
0a889dbf8b851716f7a7788cee6cc1f7e7b4c0fc
20,138
def validate_access_rule(supported_access_types, supported_access_levels, access_rule, abort=False): """Validate an access rule. :param access_rule: Access rules to be validated. :param supported_access_types: List of access types that are regarded valid. :param sup...
2ce7ba446ec583b5b46dbd6a8eceeafe6cc46a6e
20,139
import tqdm def track_viou_video(video_path, detections, sigma_l, sigma_h, sigma_iou, t_min, ttl, tracker_type, keep_upper_height_ratio): """ V-IOU Tracker. See "Extending IOU Based Multi-Object Tracking by Visual Information by E. Bochinski, T. Senst, T. Sikora" for more information. Args: ...
c2167172943e0fb45311c109aa932adee9dcbe17
20,140
def deduplicate(inp: SHAPE) -> SHAPE: """ Remove duplicates from any iterable while retaining the order of elements. :param inp: iterable to deduplicate :return: new, unique iterable of same type as input """ return type(inp)(dict.fromkeys(list(inp)))
d80ad3e00ce0bfa9a0625308267c5e25d8e3f3c9
20,141
def access_rules_synchronized(f): """Decorator for synchronizing share access rule modification methods.""" def wrapped_func(self, *args, **kwargs): # The first argument is always a share, which has an ID key = "share-access-%s" % args[0]['id'] @utils.synchronized(key) def sou...
03fe6b1905d825de1f20ed2967eb003f96fb2cce
20,142
def import_python(path, package=None): """Get python module or object. Parameters ---------- path : str Fully-qualified python path, i.e. `package.module:object`. package : str or None Package name to use as an anchor if `path` is relative. """ parts = path.split(':') if ...
ff2755964c0c24c5366e3243a1b2997176b33a4c
20,143
from typing import Callable from typing import Awaitable async def feature_flags_scope_per_request( request: Request, call_next: Callable[[Request], Awaitable[Response]] ) -> Response: """Use new feature flags copy for each request.""" # Create new copy of the feature flags, as we'll be modifying them la...
9169a2f66f7fa60066695cfef5a320eedd566145
20,144
import tempfile import os def fakepulsar(parfile, obstimes, toaerr, freq=1440.0, observatory="AXIS", flags="", iters=3): """Returns a libstempo tempopulsar object corresponding to a noiseless set of observations for the pulsar specified in 'parfile', with observations happening at times (MJD) given in the...
e40ea56e7fa460a651898d6a73b4d3aa661ae174
20,145
def get_scenes_need_processing(config_file, sensors): """ A function which finds all the processing steps for all the scenes which haven't yet been undertaken. This is per scene processing rather than per step processing in the functions above. Steps include: * Download * ARD Production ...
a600cd352980184ebe8382a5cabf9d8b09d9f688
20,146
def startingStateDistribution(env, N=100000): """ This function samples initial states for the environment and computes an empirical estimator for the starting distribution mu_0 """ rdInit = [] sample = {} # Computing the starting state distribution mu_0 =...
2685ebe6315a085ffdabbb82786499191c33d957
20,147
from pathlib import Path import itertools import copy import math import csv def get_shapley(csv_filename, modalities = ["t1", "t1ce", "t2", "flair"]): """ calculate modality shapeley value CSV with column: t1, t1c, t2, flair, of 0 / 1. and perforamnce value. :param csv: :return: """ # con...
ba80c0a9a17b7f86b909cbeb9829b6b8cc20f1ca
20,148
def get_changepoint_values_from_config( changepoints_dict, time_features_df, time_col=cst.TIME_COL): """Applies the changepoint method specified in `changepoints_dict` to return the changepoint values :param changepoints_dict: Optional[Dict[str, any]] Specifies the changepoint c...
0c38283e5744f180fbd326a549a4ee37b461c213
20,149
def jitChol(A, maxTries=10, warning=True): """Do a Cholesky decomposition with jitter. Description: U, jitter = jitChol(A, maxTries, warning) attempts a Cholesky decomposition on the given matrix, if matrix isn't positive definite the function adds 'jitter' and tries again. Thereaf...
ac2cbc35a3a0c33208456765512893554d91f75c
20,150
import requests def stock_individual_info_em(symbol: str = "603777") -> pd.DataFrame: """ 东方财富-个股-股票信息 http://quote.eastmoney.com/concept/sh603777.html?from=classic :param symbol: 股票代码 :type symbol: str :return: 股票信息 :rtype: pandas.DataFrame """ code_id_dict = code_id_map_em() ...
6d04941cb1aeaed49450eff61e957aab26bbf21a
20,151
def InverseDynamicsTool_safeDownCast(obj): """ InverseDynamicsTool_safeDownCast(OpenSimObject obj) -> InverseDynamicsTool Parameters ---------- obj: OpenSim::Object * """ return _tools.InverseDynamicsTool_safeDownCast(obj)
3060244716c54e10953df5aa8db1c55076a040a2
20,152
import os import re def in_incident_root(current_dir_path): """ Helper function to determine if a sub directory is a child of an incident directory. This is useful for setting default params in tools that has an incident directory as an input :param current_dir_path: String of the path being evaluated...
62b8f9d9bddcc8ecfa232a65f205bd8414320928
20,153
def build_decoder(encoding_dim,sparse): """"build and return the decoder linked with the encoder""" input_img = Input(shape=(28*28,)) encoder = build_encoder(encoding_dim,sparse) input_encoded = encoder(input_img) decoded = Dense(64, activation='relu')(input_encoded) decoded = Dense(128, activ...
207535e38fd45e7ea6e0143c34607213747328ba
20,154
def find_usable_exits(room, stuff): """ Given a room, and the player's stuff, find a list of exits that they can use right now. That means the exits must not be hidden, and if they require a key, the player has it. RETURNS - a list of exits that are visible (not hidden) and don't require a key! ...
529bacbf33b5680774b291782fdcefe650cafeca
20,155
def get_normal_map(x, area_weighted=False): """ x: [bs, h, w, 3] (x,y,z) -> (nx,ny,nz) """ nn = 6 p11 = x p = tf.pad(x, tf.constant([[0,0], [1,1], [1,1], [0,0]])) p11 = p[:, 1:-1, 1:-1, :] p10 = p[:, 1:-1, 0:-2, :] p01 = p[:, 0:-2, 1:-1, :] p02 = p[:, 0:-2, 2:, :] p12 = p...
1b087113d6bc68a24195459ece006c7a74848a63
20,156
def _ros_group_rank(df, dl_idx, censorship): """ Ranks each observation within the data groups. In this case, the groups are defined by the record's detection limit index and censorship status. Parameters ---------- df : pandas.DataFrame dl_idx : str Name of the column in the ...
f4495eb57d158745603899086e59643edec1e489
20,157
def f_all(predicate, iterable): """Return whether predicate(i) is True for all i in iterable >>> is_odd = lambda num: (num % 2 == 1) >>> f_all(is_odd, []) True >>> f_all(is_odd, [1, 3, 5, 7, 9]) True >>> f_all(is_odd, [2, 1, 3, 5, 7, 9]) False """ return all(predicate(i) for i i...
c0a0e52587a7afc9da143ac936aab87ad531b455
20,158
from typing import List from typing import Tuple from typing import Set from typing import Dict def _recursive_replace(data): """Searches data structure and replaces 'nan' and 'inf' with respective float values""" if isinstance(data, str): if data == "nan": return float("nan") if d...
b5c21d806b462070b2d1eec7d91a5dc700f6b0ed
20,159
def trans_text_ch_to_vector(txt_file, word_num_map, txt_label=None): """ Trans chinese chars to vector :param txt_file: :param word_num_map: :param txt_label: :return: """ words_size = len(word_num_map) to_num = lambda word: word_num_map.get(word.encode('utf-8'), words_size) i...
83370ca18303e1286b099d646362db14cd4b5dbd
20,160
def adjust_bag(request, item_id): """ Adjust the quantity of a product to the specified amount""" quantity = int('0'+request.POST.get('quantity')) bag = request.session.get('bag', {}) if quantity > 0: bag[item_id] = quantity else: messages.error(request, 'Value must greather than o...
a2814adcffbc04ee02b18bd14fc7daf0dbe58677
20,161
import os def get_file_paths_in_dir(idp, ext=None, target_str_or_list=None, ignore_str_or_list=None, base_name_only=False, without_ext=False, sort_result=True, ...
f450f8b5f04c2fb22975e4a46725ae566346a94b
20,162
def _condexpr_value(e): """Evaluate the value of the input expression. """ assert type(e) == tuple assert len(e) in [2, 3] if len(e) == 3: if e[0] in ARITH_SET: return _expr_value(e) left = _condexpr_value(e[1]) right = _condexpr_value(e[2]) if type(left...
3973a22b5c5553c2c1b70b94f97be4d54f224766
20,163
import socket def in6_isincluded(addr, prefix, plen): """ Returns True when 'addr' belongs to prefix/plen. False otherwise. """ temp = inet_pton(socket.AF_INET6, addr) pref = in6_cidr2mask(plen) zero = inet_pton(socket.AF_INET6, prefix) return zero == in6_and(temp, pref)
4003d9b61ddb8f37207a2d332a31e4ee3a97cad7
20,164
def vis_channel(model, layer, channel_n): """ This function creates a visualization for a single channel in a layer :param model: model we are visualizing :type model: lucid.modelzoo :param layer: the name of the layer we are visualizing :type layer: string :param channel_n: The channel ...
b6f1b72be81fa317fc59b3582b9f43afb640a4d6
20,165
from typing import Tuple import time def processing(log: EventLog, causal: Tuple[str, str], follows: Tuple[str, str]): """ Applying the Alpha Miner with the new relations Parameters ------------- log Filtered log causal Pairs that have a causal relation (->) follows ...
5841c82462432edddddf1b0dfd965b1043bc7277
20,166
from typing import List import re def word_tokenize(string: str, language: str = "english") -> List[str]: """tokenizes a given string into a list of substrings. :param string: String to tokenize. :param language: Language. Either one of ``english'' or ``german''. """ if language not in ["english"...
00cb30031fc5a9e7ddbfcffeae9fad031f463cb3
20,167
import re import sys def get_project_id(file_name): """ Extracts project ID from intput BAM filename. :param file_name: string e.g. "/PITT_0452_AHG2THBBXY_A1___P10344_C___13_cf_IGO_10344_C_20___hg19___MD.bam" :return: string e.g. "P10344_C" """ regex = "(?<=___)P[0-9]{5}[_A-Z,a-z]*...
fea6447851aa3b0fe0983db28e3f7707f315063a
20,168
import torch def modify_scaffolds_with_coords(scaffolds, coords): """ Gets scaffolds and fills in the right data. Inputs: * scaffolds: dict. as returned by `build_scaffolds_from_scn_angles` * coords: (L, 14, 3). sidechainnet tensor. same device as scaffolds Outputs: corrected scaf...
6d0853c3749fbf251cb3147109dab8951603c99c
20,169
import pickle from .stem import _classification_textcleaning_stemmer def multinomial(**kwargs): """ Load multinomial toxicity model. Parameters ---------- validate: bool, optional (default=True) if True, malaya will check model availability and download if not available. Returns ...
78bb3ceffefd6b38c304758eda8c0bafe36462ab
20,170
import logging def create_bucket(bucket_name, region="us-west-2"): """Create an S3 bucket in a specified region :param bucket_name: Bucket to create :param region: String region to create bucket in, e.g., 'us-west-2' :return: True if bucket created, else False """ # Create bucket try: # get list of existing...
c2d655982563c233a027dc94f9b73e8899aeddb7
20,171
def create_client(): """Return a client socket that may be connected to a remote address.""" return _new_sock()
5d0515c731d4c087c7b118923aa579d4bcd1e881
20,172
import warnings import copy def derivative_surface(obj): """ Computes the hodograph (first derivative) surface of the input surface. This function constructs the hodograph (first derivative) surface from the input surface by computing the degrees, knot vectors and the control points of the derivative sur...
f9b846c0b2b17e315ae4b98138719361675df557
20,173
def configure(config): """ | [bing ] | example | purpose | | -------- | ------- | ------- | | api_key | VBsdaiY23sdcxuNG1gP+YBsCwJxzjfHgdsXJG5 | Bing Primary Account Key | """ chunk = '' if config.option('Configuring bing search module', False): config.interactive_add('bing', 'api_k...
87ccd4694cfbf34d24e6e31f2b485aaa465ba68b
20,174
def CVRMSE(ip1,ip2): """ The normalized RMSE (= Root Mean Square Error) is defined as CVRMSE(X,Y) = sqrt[ sum_i(Yi-Xi)^2 / N ] / mean(Yi) ) """ stats = ip1.getStatistics() return RMSE(ip1,ip2) / stats.mean
0981637da92d2a60c6281f216587fa5bc798d554
20,175
def get_verified_aid_pairs(ibs): """ Example: >>> # DISABLE_DOCTEST >>> from wbia_cnn._plugin import * # NOQA >>> import wbia >>> ibs = wbia.opendb('NNP_Master3', allow_newdir=True) >>> verified_aid1_list, verified_aid2_list = get_verified_aid_pairs(ibs) """ # Gr...
91eb788a6b1f781e5796b03f56292a807aaee60d
20,176
def audio_sort_key(ex): """Sort using duration time of the sound spectrogram.""" return ex.src.size(1)
ec940df6bf2b74962f221b84717f51beba5c4f5f
20,177
from pathlib import Path def _filename_to_title(filename, split_char="_"): """Convert a file path into a more readable title.""" filename = Path(filename).with_suffix("").name filename_parts = filename.split(split_char) try: # If first part of the filename is a number for ordering, remove it ...
f62ae56901f0a58e53e84e63423bcb9f2ccf4c5a
20,178
def basis_function_contributions(universe, mo, mocoefs='coef', tol=0.01, ao=None, frame=0): """ Provided a universe with momatrix and basis_set_order attributes, return the major basis function contributions of a particular molecular orbital. .. code-block:: python ...
afe695d15d3aa43baae0ce7e0dcf2fb84f53c699
20,179
from re import S def bspline_basis(d, knots, n, x, close=True): """The `n`-th B-spline at `x` of degree `d` with knots. B-Splines are piecewise polynomials of degree `d` [1]_. They are defined on a set of knots, which is a sequence of integers or floats. The 0th degree splines have a value of one o...
266a8ef3176e11cc598015ebb963c13ddcee9e31
20,180
def is_versioned(obj): """ Check if a given object is versioned by inspecting some of its attributes. """ # before any heuristic, newer versions of RGW will tell if an obj is # versioned so try that first if hasattr(obj, 'versioned'): return obj.versioned if not hasattr(obj, 'Versio...
7f5ad90ffce6a8efde50dba47cdc63673ec79f60
20,181
def preprocess_and_suggest_hyperparams( task, X, y, estimator_or_predictor, location=None, ): """Preprocess the data and suggest hyperparameters. Example: ```python hyperparams, estimator_class, X, y, feature_transformer, label_transformer = \ preprocess_and_suggest_hyperpa...
cd388bea6c9bfbb5d38001c549f2fe92d16aff41
20,182
def passphrase_from_private_key(private_key): """Return passphrase from provided private key.""" return mnemonic.from_private_key(private_key)
aed1c465795d22fd80680c0484d377fa6cabf0c8
20,183
def merge_on_empty_fields(base, tomerge): """Utility to quickly fill empty or falsy field of $base with fields of $tomerge """ has_merged_anything = False for key in tomerge: if not base.get(key): base[key] = tomerge.get(key) has_merged_anything = True return has...
f8cb14047d2e17e2155beb1ab86eab7cdf531af0
20,184
def clear_rows(grid, locked): """Deletes the row, if that row is filled.""" increment = 0 for i in range(len(grid) - 1, -1, -1): row = grid[i] if (0, 0, 0) not in row: increment += 1 index = i for j in range(len(row)): try: ...
5974a129ac0bb756ee1038f61c9eeaf625ccbb72
20,185
import shlex def call(cmd_args, suppress_output=False): """ Call an arbitary command and return the exit value, stdout, and stderr as a tuple Command can be passed in as either a string or iterable >>> result = call('hatchery', suppress_output=True) >>> result.exitval 0 >>> result = call(['h...
1556d52de9d620e74c8a4b946c3120cf3579dede
20,186
def provides(interface): """ A validator that raises a :exc:`TypeError` if the initializer is called with an object that does not provide the requested *interface* (checks are performed using ``interface.providedBy(value)`` (see `zope.interface <http://docs.zope.org/zope.interface/>`_). :param ...
9b6e29aa8c3e0a1757daa1c0f3eb455ec66fa594
20,187
def v_t(r): """ Mean thermal velocity """ return (8/np.pi)**0.5*c(r)
af475d1376a549abe501b7b47e5f9fa35d8258c1
20,188
from typing import Callable from typing import cast def _state_stateful_alarm_controller( select_state: Callable[[str], OverkizStateType] ) -> str: """Return the state of the device.""" if state := cast(str, select_state(OverkizState.CORE_ACTIVE_ZONES)): # The Stateful Alarm Controller has 3 zones...
3663d8dda26586dae416ce6d5dbe55fafdb821c8
20,189
def _connect_new_volume(module, array, answer=False): """Connect volume to host""" api_version = array._list_available_rest_versions() if AC_REQUIRED_API_VERSION in api_version and module.params['lun']: try: array.connect_host(module.params['host'], module....
f6b5dea4e78f832b536fdc269dfe1b9c040cb9b7
20,190
def is_mongo_configured(accessor): """ works out if mongodb is configured to run with trackerdash i.e. first time running """ return accessor.verify_essential_collections_present()
c0487f6d899e6cee4f6bbb31bffbd17890812c30
20,191
from cms.api import add_plugin def create_default_children_plugins(request, placeholder, lang, parent_plugin, children_conf): """ Create all default children plugins in the given ``placeholder``. If a child have children, this function recurse. Return all children and grandchildren (etc.) created ...
121106100c50d7ebdace254b711e6d31611dbf3d
20,192
import sympy import math def _split_value_equally(delta, count): """Splits an integer or rational into roughly equal parts.""" numer = sympy.numer(delta) denom = sympy.denom(delta) return [int(math.floor((numer + i) / count)) / denom for i in range(count)]
e241444100b2e0f3c1a589d87c41aa8710fe5b8e
20,193
import ast def maybe_get_docstring(node: ast.AST): """Get docstring from a constant expression, or return None.""" if ( isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str) ): return node.value.value elif ( is...
23171c739f3c9ae6d62ecf3307ac7c3409852d6b
20,194
import logging def part_work(NPCorpsList): """获取军团LP兑换物品及其信息 Args: NPCorpList: NPC军团id列表 Returns: NPCorpList: 可以兑换物品的NPC军团id列表 [123,124,125...244,245,246] NPCorps: 可以兑换物品的NPC军团信息字典,key为id [ '物品id': { ...
96e85555a5aa74c6f065c897938ffd4c6d970739
20,195
def read_metadata(image_dir_path): """Read image metadata from an image directory.""" return jsons.load_dataobject( ImageMetadata, _get_metadata_path(image_dir_path) )
132306a228550ebff155d83e3c3d5020aad0263a
20,196
def subtract(list_1, list_2): """Subtracts list_2 from list_1 even if they are different lengths. Length of the returned list will be the length of the shortest list supplied. Index 0 is treated as the oldest, and the older list items are truncated. Args: list_1 (list of float): List to be su...
e41b02a6875ea971ffded30f82b1b51bcd33b9e8
20,197
def get_available_time_slots() -> list: """ An application is ready for scheduling when all the payment rules are satisfied plus: - the application has been paid - the window to schedule the review has not elapsed """ return [ {"try": middleware.create_correlation_id, "fail": []}...
9e04168f908abd0a9c37c969769477fc04cbd805
20,198
def library_detail(request, lib_id): """ Display information about all the flowcells a library has been run on. """ lib = get_object_or_404(Library, id=lib_id) flowcell_list = [] flowcell_run_results = {} # aka flowcells we're looking at for lane in lib.lane_set.all(): fc = lane.fl...
493a0ababcb9da6bffd859044ac0a11e854b03d5
20,199