content
stringlengths
22
815k
id
int64
0
4.91M
def getFormatter(name): """Return the named formatter function. See the function "setFormatter" for details. """ if name in ( 'self', 'instance', 'this' ): return af_self elif name == 'class': return af_class elif name in ( 'named', 'param', 'parameter' ): return af_name...
42,300
def quality(context): """Check code quality.""" pass
42,301
def test_useful_due_to_invalid_method_args( assert_errors, parse_ast_tree, mode, code, statements, super_args, method_args, default_options, ): """Testing situations with useful overwriting due to invalid method args.""" formatted_code = mode(code.format( decorator='', ...
42,302
def _mat_vec(v: PyTree, oks: PyTree) -> PyTree: """ compute S v = 1/n ⟨ΔO† ΔO⟩v = 1/n ∑ₗ ⟨ΔOₖᴴ ΔOₗ⟩ vₗ """ res = tree_conj(vjp(oks, jvp(oks, v).conjugate())) return tree_cast(res, v)
42,303
def get_recordio_iterator(path_to_rec, batch_size, data_shape=(3, 227, 227)): """ Creates mxnet recordio iterator for recordio files. For more details see https://beta.mxnet.io/api/gluon-related/_autogen/mxnet.image.ImageIter.html """ data_iter = mx.io.ImageRecordIter( path_imgrec=path_to_rec...
42,304
def raxisa(matrix: ndarray) -> Tuple[ndarray, float]: """ Compute the axis of the rotation given by an input matrix and the angle of the rotation about that axis. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/raxisa_c.html :param matrix: Rotation matrix. :return: Axis of the rotatio...
42,305
def call_errno_test(): """ Test procedure. """ import errno from six.moves import builtins ObjectBrowser.create_browser(errno, 'errno') ObjectBrowser.create_browser(builtins, 'builtins') exit_code = ObjectBrowser.execute() return exit_code
42,306
def download_cp_lvl4_align_moa(profile_link=None, pertinfo_file=None, data_dir=None): """ This function downloads the Cell painting level-4 profiles data from its github repo, perform dose recode, feature selection and align its compounds and MOAs (Mechanism of actions) with the ones found in L1000 pr...
42,307
def use_item(entity, player, new_fov_radius, max_fov_radius, sound): """ Item settings when used """ player.fighter.hp += entity.item.healing if player.fighter.hp > player.fighter.max_hp: player.fighter.hp = player.fighter.max_hp sound.play() new_fov_radius = max_fov_radius use_messa...
42,308
def parse_recommendation(line): """ Parses a recommendation record. Format: userId\t avg_rating\t rmse\t labels Parameters ---------- line : str The line that contains user information Returns ------- list : list A list containing userID, avg_rating, rmse, labels ""...
42,309
def two_props_diff_conf_interval(values1: np.ndarray, values2: np.ndarray, conf_level: float) -> tuple: """Calculates the confidence interval for the diff between two proportions Args: values1 (np.array): sample 1 binary(0/1) values values2 (np.array): sample 2 ...
42,310
def generate_random_text(n_tokens: int, tokens: Sequence[str], probabilities: Sequence[float]) -> str: """Return random text with tokens chosen based on token probabilities. Parameters ---------- n_tokens: int the length of the text in number of tokens tokens: Sequence[str] the list...
42,311
def usage(verbose=True): """Print usage information.""" programName = sys.argv[0] def warn(line=''): sys.stderr.write("%s\n" % line) warn("""\ Usage: %s [options] [<filename, or '-' for stdin> [<argument>...]] Welcome to EmPy version %s.""" % (programName, __version__)) warn() warn("Vali...
42,312
def pad(array_like: ArrayLike, begin: Shape, end: Shape, fill_type: BorderType) -> ShapeletsArray: """ Pads an array Parameters ---------- array_like: ArrayLike Input array begin: Shape Full 4 dimensional tuple specifying how many elements to add at the beggining of the ...
42,313
def test_list_moderators_many_moderator( client, private_channel, staff_user, staff_api, reddit_factories ): """ List moderators in a channel as a logged in moderator of that channel """ url = reverse("moderator-list", kwargs={"channel_name": private_channel.name}) mod_users = [] for i in r...
42,314
def read_validated_ID(): """_summary_ It checks for files inside the ValidatedInputs folder. Then it prints out the names of the files and prompts the user to choose whichone's content to print out into the terminal. Then using the with open 'r' method it reads the file and prints out its c...
42,315
def test_var_name_constraint(): """Test var_name constraint.""" cubes_in = iris.cube.CubeList([ iris.cube.Cube(0, var_name='a', long_name='aaa'), iris.cube.Cube(1, var_name='a', long_name='bbb'), iris.cube.Cube(2, var_name='b', long_name='a'), iris.cube.Cube(3, var_name='c', long...
42,316
def create_examfield(exam_id, field_name, num_of_q, answer_list): """ create exam field to fill correct answers of exam with given id """ url = current_app.config['DATABASE'] with psycopg2.connect(url) as conn: with conn.cursor() as cur: cur.execute(CREATE_EXAMFIELD_TEMPLATE_STATEMENT, (...
42,317
def request_csv_rows(settings, courseware_objects): """Fake coupon request spreadsheet data rows (loaded from CSV)""" fake_request_csv_filepath = os.path.join( settings.BASE_DIR, "sheets/resources/coupon_requests.csv" ) with open(fake_request_csv_filepath) as f: # Return all rows except ...
42,318
def verify(y_f: GFE, v: Iterable[bytes], c: FiniteFieldPolynomial) -> GFE: """Check whether a alleged secret share belongs to a group of shares. The group of shares is specified by the public `v` and `c` values returned by `split`. If the share belongs to the group, this returns the x value correspondi...
42,319
def compute_bottom_border(b, dims, mat=False): """Compute the bottom border for a given border size.""" x, y = dims return b + _A(b, x, mat)
42,320
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Load the saved entities.""" # Print startup message _LOGGER.info( "Version %s is starting, if you have any issues please report" " them here: %s", VERSION, ISSUE_URL, ) hass.data.setdefault(DOMAI...
42,321
def name(): """ """ response = PhoneInterface() text = request.form if text: result = to_noun(text['SpeechResult']) response.speak('Is your name {}?'.format(result)) new_user = User.query.get(response.get_user_id()) new_user.name = result db.save() respons...
42,322
def bbduk_trim(forward_in, forward_out, reverse_in='NA', reverse_out='NA', trimq=20, k=25, minlength=50, forcetrimleft=15, hdist=1, returncmd=False, **kwargs): """ Wrapper for using bbduk to quality trim reads. Contains arguments used in OLC Assembly Pipeline, but these can be overwritten by ...
42,323
def to_csv(dataframe, config): """ Note: save the dataframe to the given path and with the given name from the config file. """ path = config['data_path'] file_name = config['out_file'] dataframe.to_csv(path + '/' + file_name)
42,324
def view_message_with_storage_url(): """ https://sw.api.mailgun.net/v3/domains/2048.zeefarmer.com/messages/{storage_url} :return: """ params = { "limit": 1 } storage_url = client.events.get(domain=domain, filters=params).json()["items"][0]["storage"]["url"] req = client.domains_...
42,325
def db_session_manager(commit=False): """ :param commit: Changes will be committed when context ends. """ try: db = DbUtils() yield db if commit: db.commit() except SQLAlchemyError: db.session.rollback() msg = "Failed to commit." logger.ex...
42,326
def bonferonni_posthoc(*args, ttest_type='equal'): """Computes T-Tests between groups, should adjust your significance value, a.k.a. bonferonni correction to minimize family wide error rates Args: group1: Input group 1 as a numpy array group2: Input group 2 as a numpy array ...
42,327
def list_subject(_type: str, limit: int = 10, offset: int = 0) -> Dict: """ 获取subject列表 """ url_path = "/api/v1/web/subjects" params = {"type": _type, "limit": limit, "offset": offset} return _call_iam_api(http_get, url_path, data=params)
42,328
def run_test(pcd, rgbd, intrinsics, extrinsics, bp_alg=dict(radii=[0.02, 0.02]), poisson=dict(depth=8), callback=None, stride=2): """Demonstrate Polygon Extraction on both unorganized and organized point cloud Args: pcd (o3d.geometry.PointCloud): Open3D point cloud rgbd (np.ndarray): MXN Numpy ...
42,329
def test_forward(): """ Test that we can instantiate the Seq2Seq class """ params = Params() dataset = Dataset( params.data_path, max_src_len=params.max_src_len, max_tgt_len=params.max_tgt_len, truncate_src=params.truncate_src, truncate_tgt=params.truncate_tgt...
42,330
def linprog_feasible(A_ub, b_ub, A_eq=None, b_eq=None, max_steps=100, t0=1.0, mu=2.0, eps=0.001, callback=None): # TODO increase t0 once line search implemented """Returns a strictly feasible point for the given LP.""" assert max_steps >= 1 assert (A_eq is None) ==...
42,331
def get_all_envs(envs_file): """Get list of all intercepted environment variables.""" return list(iter_envs(envs_file))
42,332
def _deserialize_primitive(data, klass): """Deserializes to primitive type. :param data: data to deserialize. :param klass: class literal. :return: int, long, float, str, bool. :rtype: int | long | float | str | bool """ try: value = klass(data) except UnicodeEncodeError: value = six...
42,333
def highlight_seam(img: np.ndarray, seam: np.ndarray) -> np.array: """ Function to highlight the seam Args: img (np.array): Image array seam (np.array): Seam array with length equals height of the image array The x-coordinates of the pixel to remove from each row Returns: ...
42,334
def _maybe_encode_unicode_string(record): """Encodes unicode strings if needed.""" if isinstance(record, str): record = bytes(record, "utf-8").strip() return record
42,335
def filter(x): """ applies modified bilateral filter to AB channels of x, guided by L channel x -- B x 3 x H x W pytorch tensor containing an image in LAB colorspace """ h = x.size(2) w = x.size(3) # Seperate out luminance channel, don't use AB channels to measure similarity xl = x[:,:...
42,336
def series_not_found(): """ Formats error message for event with missing series. :return: error message :rtype: str """ error = "event(s) where their series could not be found" return error
42,337
def write_script(h, Tmax, t_end, cool_time, species, t_step, T0=T0): """ Write the bash script that will run the simulation and saves it in the current directory. This script is meant to be run from my home directory on cmole. It creates new directories and runs `ligpy.py`. If you are running this...
42,338
def compiler(language, config, permit_undefined_jinja=False): """Support configuration of compilers. This is somewhat platform specific. Native compilers never list their host - it is always implied. Generally, they are metapackages, pointing at a package that does specify the host. These in turn may be...
42,339
def get_info(raw_address: str): """ Get info about the given raw address. >>> get_info('91.124.230.205/30') IP address: 91.124.230.205 Network Address: 91.124.230.204 Broadcast Address: 91.124.230.207 Binary Subnet Mask: 11111111.11111111.11111111.11111100 First usable host IP: 91.124.2...
42,340
def get_user_permissions(options, pos, prompt_prefix): """ Get user permissions to apply """ user_permissions_regex = r"^([A-Za-z0-9_-]+(\s+[A-Za-z0-9_-]+)*)?$" user_permissions_prompt = "%s permissions: "%prompt_prefix user_permissions = getargvalue(getarg(options.args, pos), user_permissions_...
42,341
def fingers(path): """Fingers Fingers A dataset with 12 observations on the following 3 variables. `Subject` `I`, `II`, `III`, or `IV` `Drug` `Caffeine`, `Placebo`, or `Theobromine` `TapRate` Finger taps in a fixed time interval The data was found in Statistics in Biology, Vol. 1, by C. I. ...
42,342
def iter_contour_segments(points: Contour) -> Iterable[Segment]: """Given points A, B, ...N returns (A, B), (B, ...), (..., N), (N, A).""" # "contour" frequently has shape (N, 1, 2); remove "1" middle layer. if len(points.shape) > 2: size = points.size points = points.view() points.s...
42,343
def _make_structures(args): """Makes a VASP POSCAR file for the desired structures.""" (system, structure_data) = _read_enum_out(args) if args["append"]!="t": os.system("rm {}".format(args["outfile"])) # for each structure write the vasp POSCAR for structure in structure_data: # s...
42,344
def set_env(**environ: Dict[str, str]): """ Temporarily set the process environment variables. Example: with set_env(VAR_NAME='value'): # Use VAR_NAME here pass """ old_environ = dict(os.environ) os.environ.update(environ) try: yield finally: ...
42,345
def intword(value): """ Converts a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'. """ value = int(value) if value < 1000000: ...
42,346
def __validate_archive_file_arg(required_arg_map): """ Verify that the archive file exists. :param required_arg_map: the required arguments map :return: the archive file name :raises CLAException: if the archive file is not valid """ _method_name = '__validate_archive_file_arg' archive_...
42,347
def suite(description=None, name=None, rank=None): """ Decorator, mark a class as a suite class. :param description: suite's description (by default, the suite's description is built from the name) :param name: suite's name (by default, the suite's name is taken from the class's name) :param rank: ...
42,348
def parse_arguments(): """ Define the command line arguments for choosing a model etc. Returns ------- args object """ parser = argparse.ArgumentParser(description='') add_pipeline_args(parser, model_list) add_poseestimator_args(parser) add_coco_args(parser) return vars(pars...
42,349
def clean(self): """Routine to return TIMED SABER data cleaned to the specified level Note ---- 'clean' All parameters should be good, suitable for statistical and case studies 'dusty' All paramers should generally be good though same may not be great 'dirty' There are d...
42,350
def mercator_to_gcj02(mer_matrix): """ Mercator coordinates to National Bureau of Survey and Measurement coordinates :param mer_matrix: :return: """ return wgs84_to_gcj02( mercator_to_wgs84(mer_matrix) )
42,351
def delete_menu_item(current_user, item_id): """Delete menu item by id""" if current_user['admin']: resp = menu_inst.del_menu(item_id) if resp: return jsonify({"Message": "Item deleted"}), 200 return jsonify({"Message": "Item not found"}), 404 return jsonify({"Message": "...
42,352
def generate_parameters(system: params.CollisionSystem) -> Tuple[np.ndarray, np.ndarray, int, Dict[int, params.SelectedRange]]: """ Generate the analysis parameters. This can be called multiple times if necessary to retrieve the parameters easily in any function. Args: system: Collision system. ...
42,353
def merge_extras(extras1, extras2): """Merge two iterables of extra into a single sorted tuple. Case-sensitive""" if not extras1: return extras2 if not extras2: return extras1 return tuple(sorted(set(extras1) | set(extras2)))
42,354
def test_login_social_connect(social_config, active_user, db_session): """Connect and logs user in.""" user = db_session.merge(active_user) profile = { 'accounts': [{'domain': text_type('facebook.com'), 'userid': text_type('2343')}], 'displayName': text_type('teddy'), 'preferredUser...
42,355
def netdev_get_driver_name(netdev): """Returns the name of the driver for network device 'netdev'""" symlink = '%s/sys/class/net/%s/device/driver' % (root_prefix(), netdev) try: target = os.readlink(symlink) except OSError, e: log("%s: could not read netdev's driver name (%s)" % (netdev,...
42,356
def register(linter): """required method to auto register this checker""" linter.register_checker(GherkinCompliantChecker(linter))
42,357
def _get_content(item, base_url=None): """ Return a dictionary of content, for documents, objects and errors. """ return { _unescape_key(key): _primitive_to_document(value, base_url) for key, value in item.items() if key not in ("_type", "_meta") }
42,358
def scatter(xs, ys, labels=None, colormap="plot", uniqueLabels=None): """ Draws a scatter plot. The x coordinates, y coordinates and labels of the points are specified via `xs`, `ys`, `labels`. If no labels are given, the points will not be colored. Otherwise, points will be colored according to th...
42,359
def _cluster_by_adjacency(sel_samples): """Function for clustering selected samples based on temporal adjacency. Input arguments: sel_samples - A vector of booleans indicating which samples have been selected. Output arguments: clusters - A vector of cluster numbers indicating...
42,360
def send_mail(email, email_string): """ handles email sending procedures :param email :param email_string :return: """ key = MAILGUN_KEY recipient = email request_url = MAILGUN_URL data = { 'from': MAILGUN_TESTMAIL_ADDR, 'to': recipient, 'subject': 'Dail...
42,361
def _get_incremental_value(initial, next_, step): """ return incremental value in two stage e.g.) - step = 0 or 1, return 10 - step >= 2, return 30 >>> g = _get_incremental_value(10, 30, 2) >>> g.next() 10 >>> g.next() 10 >>> g.next() 30 """ for i in itertools.count(): if i < step: yield initial e...
42,362
def _relu_3_ramp(x): """ Relu(x) ** 3 ramp function returns f(x) = relu(x) ** 3 df/dx(x) = relu(x) ** 2 """ rx = torch.relu(x) ramp = rx.pow(3) grad = rx.pow(2) * 3.0 return ramp, grad
42,363
def get_ham_ising_tube(dtype, Ly, lam=-3.044): """Return the local term for the 2+1D Ising Hamiltonian on a narrow torus. Defines the global Hamiltonian: $H = -\sum_{\langle i, j \rangle} X_i X_j + lam * \sum_i Z_i ]$ Represents the Hamiltonian for the 2D torus as a 1-dimensional Hamiltonian, where each "si...
42,364
def processed_for_entities_query_clause(): """ :return: A solr query clause you can use to filter for stories that have been tagged by any version of our CLIFF geotagging engine (ie. tagged with people, places, and organizations) """ return "(tags_id_stories:({}))".format(" ".join([str(t) for t in ...
42,365
def get_shared_prefix(w1, w2): """Get a string which w1 and w2 both have at the beginning.""" shared = "" for i in range(1, min(len(w1), len(w2))): if w1[:i] != w2[:i]: return shared else: shared = w1[:i] return shared
42,366
async def get_poll_ops(op_type=None, block_range=None) -> Result: """Returns a list of 'polls' ops within the specified block or time range.""" sql = SearchQuery.poll_ops( op_type=op_type, block_range=block_range ) result = [] if sql: res = db.db.select(sql) or [] for...
42,367
def _set_splits_samples(split2samples: DefaultDict[str, List[Sample]], db: NuPlanDB, split2log: Dict[str, List[str]], broken_extractions: Optional[Set[str]] = None, sort_train: bool = True) -> None: """ Populates spl...
42,368
def _loop_mgr(loop: asyncio.AbstractEventLoop)->None: """起一个线程执行事件循环的`run_forever`方法. [Start up a thread for running the eventloop's `run_forever` method.] 当它被终止时会清理未完结的协程,但不会关闭事件循环 [When it shutdown, all the coroutines will be closed.but the eventloop will not close.] Params: ...
42,369
def list_of_divisors_v1(n): """Return [ list of divisors ]""" """ This is a slow algorithm. But it is correct. """ if n == 1: return [1] if n == 2: return [1,2] L = {} if n > 0: L[1] = True if n > 1: L[n] = True for i in list_of_prime_factors(n): ...
42,370
def get_optimal_train_size( nb_vectors: int, index_key: str, current_memory_available: Optional[str], vec_dim: Optional[int], ) -> int: """ Function that determines the number of training points necessary to train the index, based on faiss heuristics for k-means clustering. """ matching = re.fi...
42,371
def click_checkout_key(): """ This function clicks the checkout button on the BestBuy cart page :rtype: object """ checkout_button = driver.find_element_by_css_selector( ".btn-lg") checkout_button.click() print("checkout started")
42,372
def _initialize_gui(frame, view=None): """Initialize GUI depending on testing mode.""" if _testing_mode(): # open without entering mainloop return frame.edit_traits(view=view), frame else: frame.configure_traits(view=view) return frame
42,373
def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. Th...
42,374
def cls_token(idx): """ Function helps in renaming cls_token weights """ token = [] token.append((f"cvt.encoder.stages.{idx}.cls_token", "stage2.cls_token")) return token
42,375
async def get_pillow_object_from_url(url: str): """Takes a url string containing an image and returns a pillow Image object""" async with httpx.AsyncClient() as client: while True: logger.debug(f"Creating pillow Image object from url {url}") request = await client.get(url) ...
42,376
def fast_betweenness(G, weight=None, kind = 'edge', norm=True, cutoff=None): """ Gets betweenness centrality. For relativelly large graphs, this func is faster than networkx Parameters ---------- G : NetworkX DiGraph or Graph The graph to be considered. weight: string edge...
42,377
def regularizer(regularization_type, regularization_rate, params): """ Our params all have different dimensions. So, we loop through each w or b in our params, apply operation, sum, then use the resulting scalar for the next, final sum in either L1 or L2 regularization """ if regulariz...
42,378
def get_eq_crc(devices): """ Builds a CRC string based on device id and device status. This function is reverse engineered and translated to python. It is based on the CoderUtils class in the elro app :param devices: An dictionary of devices statuses, where the id of the device is the index of the dict ...
42,379
def get_hash_for_filename(filename, hashfile_path): """Return hash for filename in the hashfile.""" filehash = '' with open(hashfile_path, 'r') as stream: for _cnt, line in enumerate(stream): if line.rstrip().endswith(filename): filehash = re.match(r'^[A-Za-z0-9]*', line)...
42,380
def process_download_to_xml_corpus(path, subreddit_name, subreddit_id, download_date, save_source=False): """ Create a subreddit corpus object and store comments and submissions from a given download folder into this corpus object structured as a tree. """ corpus = SubredditCorpus(subreddit_name, subre...
42,381
def align_images(im1, im2, warp_mode=cv2.MOTION_TRANSLATION, debug=False): """Algin two images. warp_mode is either cv2.MOTION_TRANSLATION for affine transformation or cv2.MOTION_HOMOGRAPHY for perspective one. Note that under OpenCV < 3.4.0 if images cannot be aligned, the function fails crashing t...
42,382
def test_parking(): """Build a sample Parking Entity .. _NGSI-LD Specification Context Information Management (CIM) ; NGSI-LD API []ETSI GS CIM 009 V1.1.1 (2019-01)] """ e = Entity( "OffStreetParking", "OffStreetParking:Downtown1", ctx=[ "http://uri.etsi.org/ngs...
42,383
def main(): """ Connects the dbf contents with the excel file generator using the files listed in the file iteration function :return: None """ parser = argparse.ArgumentParser(description="Excel") parser.add_argument("--path",type=str, help="Donde quieres hacer campeon") args = parse...
42,384
def resonance_mass_distributions(axes): """ Verification of mass disributions for several resonance species. Grey dashed lines are the Breit-Wigner distributions with mass-dependent width, grey solid lines are the same distributions with momentum integrated out, and colored lines are histograms of ...
42,385
def test_keycloak_delete_user_by_username_user_not_exist(): """Delete user by invalid username. Assert response is None, error code data not found.""" response = None try: response = KEYCLOAK_SERVICE.delete_user_by_username(ADD_USER_REQUEST_SAME_EMAIL.get('username')) except BusinessException as...
42,386
def get_logger(): """ Get named logger """ return logging.getLogger(__name__)
42,387
def word_match(reg_, str_): """function compares words of equal length Invokes char_match for each character""" if not reg_: return True elif not str_: if reg_ == "$": return True return False if len(reg_) == 1: return char_match(reg_[0], str_[...
42,388
async def async_entry_updated(hass, config_entry): """Handle entry updates.""" Logger.info("Configuration changed, reloading...") await hass.config_entries.async_reload(config_entry.entry_id)
42,389
def fdp_to_model(package, table_name, resource, field_translator): """ Create a Babbage Model from a Fiscal DataPackage descriptor :param package: datapackage object :param table_name: db table name to use :param resource: resource to load (in the datapackage object) :param field_translator: dic...
42,390
def PN_gen(N_bits,m=5): """ Maximal length sequence signal generator. Generates a sequence 0/1 bits of N_bit duration. The bits themselves are obtained from an m-sequence of length m. Available m-sequence (PN generators) include m = 2,3,...,12, & 16. Parameters ---------- N...
42,391
def df_to_dataset(df: pd.DataFrame, **kwargs): """ :param kwargs: kwargs are additional keys to pass to `df` For example if kwargs is {'some': 3}, than df gets new column `some` with value set to 3 in every row """ df = df.replace(np.nan, '', regex=True) for key, value in kwargs.items(): ...
42,392
def zstandarization(value, distribution=None): """ Apply a z standarization to the value. Value can be another distribution. """ value = np.array([float(i) for i in value]) if distribution: return (np.array(value)-np.mean(np.array(distribution)))/np.std(np.array(distribution)) else: ...
42,393
def test_cray_hsm_inventory_ethernetinterfaces_delete(cli_runner, rest_mock): """Test `cray hsm inventory ethernetInterfaces delete` with valid params """ runner, cli, config = cli_runner url_template = '/apis/smd/hsm/v1/Inventory/EthernetInterfaces' ethinterface_id = 'ffffffffffff' result...
42,394
def test_duplicate_cubes(temperature_only): """Test that an exception is raised if duplicate cubes are passed in.""" cubes = iris.cube.CubeList([*[temperature_only] * 3]) with pytest.raises(ValueError, match="Duplicate input cube provided."): FreezingRain()(cubes)
42,395
def assert_allclose( actual: List[float], desired: List[float], rtol: float, atol: float ): """ usage.scipy: 4 """ ...
42,396
def _determine_default_project(project=None): """Determine default project ID explicitly or implicitly as fall-back. In implicit case, supports three environments. In order of precedence, the implicit environments are: * GCLOUD_PROJECT environment variable * Google App Engine application ID * ...
42,397
def assert_redis_matches_db(test_redis): """Make sure all nonempty queues are present in the redis DB and have the correct amount of data, as determined by the DB.""" for q in Queue.objects.all(): data_count = q.data.count() if data_count > 0: assert test_redis.exists("queue:" +...
42,398
def test_config_set_option_global_only(run_cli_command, config_with_profile_factory): """Test that `global_only` options are only set globally even if the `--global` flag is not set.""" config_with_profile_factory() option_name = 'autofill.user.email' option_value = 'some@email.com' options = ['con...
42,399