content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def solve_with_log(board, out_fname): """Wrapper for solve: write log to out_fname""" log = [] ret = solve(board, log) with open(out_fname, 'w') as f: f.write(json.dumps({'model': log}, indent=4)) return ret
c550980f252df724d68f9eb22159463e361997bc
3,650,800
def discrepancy(sample, bounds=None): """Discrepancy. Compute the centered discrepancy on a given sample. It is a measure of the uniformity of the points in the parameter space. The lower the value is, the better the coverage of the parameter space is. Parameters ---------- sample : array_...
f54cf5efa3cf12410d5522971983d41ea767767f
3,650,801
def rz(psi, r): """ Wrapper for ERFA function ``eraRz``. Parameters ---------- psi : double array r : double array Returns ------- r : double array Notes ----- The ERFA documentation is below. - - - - - - e r a R z - - - - - - Rotate an r-matrix abou...
1ea4e9322ba187e91d3b976d74d416ae99a74ee6
3,650,802
import locale def _get_ticklabels(band_type, kHz, separator): """ Return a list with all tick labels for octave or third octave bands cases. """ if separator is None: separator = locale.localeconv()['decimal_point'] if band_type == 'octave': if kHz is True: ticklabels ...
95ebdc670a23fdb8561a431e863901df6734fdb9
3,650,803
def SpearmanP(predicted, observed): """abstracts out p from stats.spearmanr""" if np.isnan(np.min(predicted)) or np.isnan(np.min(observed)): return np.asarray([np.nan]) coef, p = stats.spearmanr(np.squeeze(predicted).astype(float), np.squeeze(observed).astype(float)) return p
41986483ea3d466d94af5c86cedee62165d81d98
3,650,804
def get_zebra_route_type_by_name(route_type='BGP'): """ Returns the constant value for Zebra route type named "ZEBRA_ROUTE_*" from its name. See "ZEBRA_ROUTE_*" constants in "ryu.lib.packet.zebra" module. :param route_type: Route type name (e.g., Kernel, BGP). :return: Constant value for Zebra...
8cdc3a8384f71c4c04172a8c37f51e3789929e42
3,650,805
def preprocess(arr): """Preprocess image array with simple normalization. Arguments: ---------- arr (np.array): image array Returns: -------- arr (np.array): preprocessed image array """ arr = arr / 255.0 arr = arr * 2.0 - 1.0 return arr
3bccf2f4433c4da62954db4f25f5e9bfabc03c3a
3,650,806
def remove_const(type): """removes const from the type definition If type is not const type, it will be returned as is """ nake_type = remove_alias(type) if not is_const(nake_type): return type else: return nake_type.base
b00d7cca79222d5ac2b6a12019b73a8169df96b7
3,650,807
def populate_institute_form(form, institute_obj): """Populate institute settings form Args: form(scout.server.blueprints.institutes.models.InstituteForm) institute_obj(dict) An institute object """ # get all other institutes to populate the select of the possible collaborators insti...
836850a55a02b199b2c7607a236f77e6b95051e0
3,650,808
def closestMedioidI(active_site, medioids, distD): """ returns the index of the closest medioid in medioids to active_site input: active_site, an ActiveSite instance medioids, a list of ActiveSite instances distD, a dictionary of distances output: the index of the ActiveSite close...
379f98a84751c0a392f8f9b1703b89b299979676
3,650,809
from typing import Dict from typing import Any import traceback import sys def watchPoint(filename, lineno, event="call"): """whenever we hit this line, print a stack trace. event='call' for lines that are function definitions, like what a profiler gives you. Switch to 'line' to match lines inside fu...
5c7017a180e254f5651c6cf737ca798d570d669c
3,650,810
def no_op_job(): """ A no-op parsl.python_app to return a future for a job that already has its outputs. """ return 0
ad8d6379ba35dae14ce056d9900fb6e62c769d85
3,650,811
def identity(dim, shape=None): """Return identity operator with appropriate shape. Parameters ---------- dim : int Dimension of real space. shape : int (optional) Size of the unitary part of the operator. If not provided, U is set to None. Returns ------- id : P...
0cd40246f4ccf2805a852dcea09d451e7f8c63a5
3,650,812
def configure_checkout_session(request): """ Configure the payment session for Stripe. Return the Session ID. Key attributes are: - mode: payment (for one-time charge) or subscription - line_items: including price_data because users configure the donation price. TODOs ...
f53bd6ecd488d214d3ebc43a2c049bf4315c1494
3,650,813
import os import json def load_schemas(): """Return all of the schemas in this directory in a dictionary where the keys are the filename (without the .json extension) and the values are the JSON schemas (in dictionary format) :raises jsonschema.exceptions.SchemaError if any of the JSON files in this ...
cbd14a4cdcc37f7fc861e00de84928abd3f8a557
3,650,814
from typing import Optional from typing import Union import torch from pathlib import Path import json def load_separator( model_str_or_path: str = "umxhq", targets: Optional[list] = None, niter: int = 1, residual: bool = False, wiener_win_len: Optional[int] = 300, device: Union[str, torch.dev...
bb9d0ecf47174ebac9181710a1bc4689ca122ecf
3,650,815
from datetime import datetime def transform_datetime(date_str, site): """ 根据site转换原始的date为正规的date类型存放 :param date_str: 原始的date :param site: 网站标识 :return: 转换后的date """ result = None if site in SITE_MAP: if SITE_MAP[site] in (SiteType.SINA, SiteType.HACKERNEWS): try: ...
647ab633b0d5ce0887042ef42a762f1bc3196242
3,650,816
import re import numpy def ParseEventsForTTLs(eventsFileName, TR = 2.0, onset = False, threshold = 5.0): """ Parses the events file from Avotec for TTLs. Use if history file is not available. The events files does not contain save movie start/stops, so use the history file if possible @param eventsFileName: name...
59fa31df066424df3625e55496f0ccefa39f2d64
3,650,817
def _to_native_string(string, encoding='ascii'): """Given a string object, regardless of type, returns a representation of that string in the native string type, encoding and decoding where necessary. This assumes ASCII unless told otherwise. """ if isinstance(string, str): out = string ...
b50fd0fc62b2cfc024c847b98e1f85b4b67d07e3
3,650,818
def load(path: str) -> model_lib.Model: """Deserializes a TensorFlow SavedModel at `path` to a `tff.learning.Model`. Args: path: The `str` path pointing to a SavedModel. Returns: A `tff.learning.Model`. """ py_typecheck.check_type(path, str) if not path: raise ValueError('`path` must be a non-...
1bd16ed7b4a7955f2a78fc638e896bbd6d1ee5ac
3,650,819
import os def plot_feature_importance(obj, top_n=None, save_path=None): """ 输出LGBM模型的feature importance,并绘制条形图 Parameters ---------- obj: lgbm object or DataFrame 训练好的Lightgbm模型,或是已经计算好的feature importan DataFrame top_n: int, default None 展示TOP N的变量,若不填则展示全部变量,为保证显示效果,建议当变量个数多于3...
e1d8fc6d05693ad4381281d21e0e5672b54a863e
3,650,820
def parameters_from_object_schema(schema, in_='formData'): """Convert object schema to parameters.""" # We can only extract parameters from schema if schema['type'] != 'object': return [] properties = schema.get('properties', {}) required = schema.get('required', []) parameters = [] ...
7508fb066d6924fc0af4a10338636b70ef64b9b2
3,650,821
import os def env_vars(request): """Sets environment variables to use .env and config.json files.""" os.environ["ENV"] = "TEST" os.environ["DOTENV_FILE"] = str(DOTENV_FILE) os.environ["CONFIG_FILE"] = str(CONFIG_FILE) os.environ["DATABASE_URL"] = get_db_url() return True
22f4953d9f2defd4f2af159b821e408bb60e7db7
3,650,822
def any_toggle_enabled(*toggles): """ Return a view decorator for allowing access if any of the given toggles are enabled. Example usage: @toggles.any_toggle_enabled(REPORT_BUILDER, USER_CONFIGURABLE_REPORTS) def delete_custom_report(): pass """ def decorator(view_func): @w...
25f48e9227f5c6ff74ae9874ac0b3b7ad010861b
3,650,823
def moguls(material, height, randomize, coverage, det, e0=20.0, withPoisson=True, nTraj=defaultNumTraj, dose=defaultDose, sf=True, bf=True, optimize=True, xtraParams=defaultXtraParams): """moguls(material, radius, randomize, det, [e0=20.0], [withPoisson=True], [nTraj=defaultNumTraj], [dose = 120.0], [sf=True], [bf=...
182aa248962877636e18860b46d20335eb535074
3,650,824
def link_datasets(yelp_results, dj_df, df_type="wages"): """ (Assisted by Record Linkage Toolkit library and documentation) This functions compares the Yelp query results to database results and produces the best matches based on computing the qgram score. Depending on the specific database table c...
326857d5060ac5cedcac3de90ce284048b2d2fa7
3,650,825
def hello(): """Say Hello, so that we can check shared code.""" return b"hello"
7197ed31c5fde419d4607ca1b5dbec7f8cb20608
3,650,826
def loglog_mean_lines(x, ys, axis=0, label=None, alpha=0.1): """ Log-log plot of lines and their mean. """ return _plot_mean_lines(partial(plt.loglog, x), ys, axis, label, alpha)
2f4461ca21c2f8db9ddfd763f474ebc73f3bf636
3,650,827
import osgeo.ogr def read_lines_from_shapefile(fpath): """ Read coordinates of cutting line segments from a ESRI Shapefile containing line features. Parameters ---------- fpath Name of a file containing coordinates of cutting lines Returns -------- ...
9eca9204a577dc0f7d675703c75ba5d407a0338b
3,650,828
def generate_identifier(endpoint_description: str) -> str: """Generate ID for model.""" return ( Config.fdk_publishers_base_uri() + "/fdk-model-publisher/catalog/" + sha1(bytes(endpoint_description, encoding="utf-8")).hexdigest() # noqa )
30bfc15c12b47f637627391a45bb9b5f9355c4f7
3,650,829
def depthFirstSearch(problem): """Search the deepest nodes in the search tree first.""" stack = util.Stack() # Stack used as fringe list stack.push((problem.getStartState(),[],0)) return genericSearch(problem,stack)
67452934a29e9857f90b88f3fead67d101468471
3,650,830
import argparse def parse_cli_args() -> argparse.Namespace: """ Parse arguments passed via Command Line Interface (CLI). :return: namespace with arguments """ parser = argparse.ArgumentParser(description='Algorithmic composition of dodecaphonic music.') parser.add_argument( '-...
9014ee342b810ec1b63f7ed80811f55b7ed4d00f
3,650,831
def create_app(): """ Method to init and set up the Flask application """ flask_app = MyFlask(import_name="dipp_app") _init_config(flask_app) _setup_context(flask_app) _register_blueprint(flask_app) _register_api_error(flask_app) return flask_app
bfb64ac71fcd076fe26c3b342c33af30370be8db
3,650,832
def find_consumes(method_type): """ Determine mediaType for input parameters in request body. """ if method_type in ('get', 'delete'): return None return ['application/json']
785e70e41629b0386d8b86f247afaf5bff3b7ba9
3,650,833
def preprocess(text): """ Simple Arabic tokenizer and sentencizer. It is a space-based tokenizer. I use some rules to handle tokenition exception like words containing the preposition 'و'. For example 'ووالدته' is tokenized to 'و والدته' :param text: Arabic text to handle :return: list of tokenized sen...
48a44391413045a49d6d9f2dff20dcd89734b4f2
3,650,834
def login(client, password="pass", ): """Helper function to log into our app. Parameters ---------- client : test client object Passed here is the flask test client used to send the request. password : str Dummy password for logging into the app. Return ------- post re...
5adca2e7d54dabe47ae92f0bcebb93e0984617b1
3,650,835
def define_dagstermill_solid( name, notebook_path, input_defs=None, output_defs=None, config_schema=None, required_resource_keys=None, output_notebook=None, output_notebook_name=None, asset_key_prefix=None, description=None, tags=None, ): """Wrap a Jupyter notebook in a s...
48097a7bed7ef84ad8d9df4eeef835f3723cb391
3,650,836
import torch def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor: """De-normalizes LAFs from scale to image scale. B,N,H,W = images.size() MIN_SIZE = min(H,W) [a11 a21 x] [a21 a22 y] becomes [a11*MIN_SIZE a21*MIN_SIZE x*W] [a21*MIN_...
51b8c81359237a9e102c1cd33bb7d1ab16c39893
3,650,837
import os import shutil def project_main(GIS_files_path, topath): """ This main function reads the GIS-layers in GIS_files_path and separates them by raster and vector data. Projects the data to WGS84 UMT37S Moves all files to ../Projected_files Merges the files named 'kV' to two merged shape file of ...
a686608a7c82aed75e7a8606e2ca1ca5b3bc7f02
3,650,838
import re def parse_regex_flags(raw_flags: str = 'gim'): """ parse flags user input and convert them to re flags. Args: raw_flags: string chars representing er flags Returns: (re flags, whether to return multiple matches) """ raw_flags = raw_flags.lstrip('-') # compatibilit...
71816c57f4e4f6dac82b4746b534a680745bc730
3,650,839
import argparse def create_parser(): """ Create argparse object for this CLI """ parser = argparse.ArgumentParser( description="Remove doubled extensions from files") parser.add_argument("filename", metavar="file", help="File to process") return parser
c5acd1d51161d7001d7a6842fa87ff0cf61a03ef
3,650,840
def has_answer(answers, retrieved_text, match='string', tokenized: bool = False): """Check if retrieved_text contains an answer string. If `match` is string, token matching is done between the text and answer. If `match` is regex, we search the whole text with the regex. """ if not isinstance(answe...
f0107006d2796e620cd1a47ef9e79c1c5cc1fd7a
3,650,841
def get_utm_zone(srs): """ extracts the utm_zone from an osr.SpatialReference object (srs) returns the utm_zone as an int, returns None if utm_zone not found """ if not isinstance(srs, osr.SpatialReference): raise TypeError('srs is not a osr.SpatialReference instance') if srs.IsProjec...
3ee1f9780ce0fbfd843ea6b72627e90e16fd1549
3,650,842
def get_documents_meta_url(project_id: int, limit: int = 10, host: str = KONFUZIO_HOST) -> str: """ Generate URL to load meta information about the Documents in the Project. :param project_id: ID of the Project :param host: Konfuzio host :return: URL to get all the Documents details. """ re...
b538d028844a2f769e8700995d1052b440592046
3,650,843
def parse_params_from_string(paramStr: str) -> dict: """ Create a dictionary representation of parameters in PBC format """ params = dict() lines = paramStr.split('\n') for line in lines: if line: name, value = parse_param_line(line) add_param(params, name, value) ...
fbf8c8cfffd0c411cc4a83760f373dd4e02eec1e
3,650,844
def hstack(gctoos, remove_all_metadata_fields=False, error_report_file=None, fields_to_remove=[], reset_ids=False): """ Horizontally concatenate gctoos. Args: gctoos (list of gctoo objects) remove_all_metadata_fields (bool): ignore/strip all common metadata when combining gctoos error_...
5da84b3db052dd54c8f3a41ecf0cc20dd3d2f187
3,650,845
def number_fixed_unused_variables(block): """ Method to return the number of fixed Var components which do not appear within any activated Constraint in a model. Args: block : model to be studied Returns: Number of fixed Var components which do not appear within any activated ...
a6432160bc52ac3e5682b255c951388242bbc2b0
3,650,846
def tunnelX11( node, display=None): """Create an X11 tunnel from node:6000 to the root host display: display on root host (optional) returns: node $DISPLAY, Popen object for tunnel""" if display is None and 'DISPLAY' in environ: display = environ[ 'DISPLAY' ] if display is None: ...
a0e824bef4d23dd3a8a5c25653bf778731de180e
3,650,847
import os def static_docs(file_path): """Serve the 'docs' folder static files and redirect folders to index.html. :param file_path: File path inside the 'docs' folder. :return: Full HTTPResponse for the static file. """ if os.path.isdir(os.path.join(document_root, 'docs', file_path)): ret...
14af4c310d09756e3dcd63335bc3d03d2be28dca
3,650,848
import collections def get_aws_account_id_file_section_dict() -> collections.OrderedDict: """~/.aws_accounts_for_set_aws_mfa から Section 情報を取得する""" # ~/.aws_accounts_for_set_aws_mfa の有無を確認し、なければ生成する prepare_aws_account_id_file() # 該当 ini ファイルのセクション dictionary を取得 return Config._sections
51eb94857d62b91c5fcfe978b3cd2a32cbefb6ae
3,650,849
from datetime import datetime def profile(request, session_key): """download_audio.html renderer. :param request: rest API request object. :type request: Request :param session_key: string representing the session key for the user :type session_key: str :return: Just another django mambo...
ba39b5a69c062ab62f83f46f7044f403120016ca
3,650,850
import requests def pipFetchLatestVersion(pkg_name: str) -> str: """ Fetches the latest version of a python package from pypi.org :param pkg_name: package to search for :return: latest version of the package or 'not found' if error was returned """ base_url = "https://pypi.org/pypi" reques...
f1a49d31f4765a1a2ddc5942792a74be211fef49
3,650,851
import subprocess def _GetLastAuthor(): """Returns a string with the author of the last commit.""" author = subprocess.check_output(['git', 'log', '-1', '--pretty=format:"%an"']).splitlines() return author
82159cf4d882d6cace29802892dacda1bfe6b6b2
3,650,852
def mock_datasource_http_oauth2(mock_datasource): """Mock DataSource object with http oauth2 credentials""" mock_datasource.credentials = b"client_id: FOO\nclient_secret: oldisfjowe84uwosdijf" mock_datasource.location = "http://foo.com" return mock_datasource
8496f6b9ac60af193571f762eb2ea925915a1223
3,650,853
def find_certificate_name(file_name): """Search the CRT for the actual aggregator name.""" # This loop looks for the collaborator name in the key with open(file_name, 'r') as f: for line in f: if 'Subject: CN=' in line: col_name = line.split('=')[-1].strip() ...
853ec62b69feebd86c7a56e1d47b2c12e7f56d63
3,650,854
import sys import os import imp def _find_module(module): """Find module using imp.find_module. While imp is deprecated, it provides a Python 2/3 compatible interface for finding a module. We use the result later to load the module with imp.load_module with the '__main__' name, causing it to exec...
b76b72cfc666e78b5b880c95bdc196b469722822
3,650,855
from typing import List def float2bin(p: float, min_bits: int = 10, max_bits: int = 20, relative_error_tol=1e-02) -> List[bool]: """ Converts probability `p` into binary list `b`. Args: p: probability such that 0 < p < 1 min_bits: minimum number of bits before testing relative error. ...
1b25f84255ace0503f06ae2ab9f8dc650206176c
3,650,856
def bin_thresh(img: np.ndarray, thresh: Number) -> np.ndarray: """ Performs binary thresholding of an image Parameters ---------- img : np.ndarray Image to filter. thresh : int Pixel values >= thresh are set to 1, else 0. Returns ------- np.ndarray : Binariz...
9064fb5f50c22aabc73bf63d3a818b6898a19a58
3,650,857
from mathutils import Matrix, Vector, Euler def add_object_align_init(context, operator): """ Return a matrix using the operator settings and view context. :arg context: The context to use. :type context: :class:`bpy.types.Context` :arg operator: The operator, checked for location and rotation pr...
6bd32226c7024245b1252c3a51f5ae713f43a1b2
3,650,858
import pickle def load_dataset(): """ load dataset :return: dataset in numpy style """ data_location = 'data.pk' data = pickle.load(open(data_location, 'rb')) return data
9467826bebfc9ca3ad1594904e9f3195e345c065
3,650,859
def video_feed(): """Return camera live feed.""" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame')
87c9ae8aa84fe17a16b040d56fbdaac6351e0706
3,650,860
def area_in_squaremeters(geodataframe): """Calculates the area sizes of a geo dataframe in square meters. Following https://gis.stackexchange.com/a/20056/77760 I am choosing equal-area projections to receive a most accurate determination of the size of polygons in the geo dataframe. Instead of Gall-Pet...
47a2ae042c8cda7fa6b66ccd011d0293afb36504
3,650,861
import scipy def add_eges_grayscale(image): """ Edge detect. Keep original image grayscale value where no edge. """ greyscale = rgb2gray(image) laplacian = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]) edges = scipy.ndimage.filters.correlate(greyscale, laplacian) for index,value in np.nd...
0cba5152578722693d0d796252a99973e980b365
3,650,862
def generateFromSitePaymentObject(signature: str, account_data: dict, data: dict)->dict: """[summary] Creates object for from site chargment request Args: signature (str): signature hash string account_data (dict): merchant_account: str merchant_domain: str ...
149434694e985956dede9bf8b6b0da1215ac9963
3,650,863
def deal_weights(node, data=None): """ deal the weights of the custom layer """ layer_type = node.layer_type weights_func = custom_layers[layer_type]['weights'] name = node.layer_name return weights_func(name, data)
a2a271ea0aeb94a1267dbc06da8997985b81633e
3,650,864
def label_brand_generic(df): """ Correct the formatting of the brand and generic drug names """ df = df.reset_index(drop=True) df = df.drop(['drug_brand_name', 'drug_generic_name'], axis=1) df['generic_compare'] = df['generic_name'].str.replace('-', ' ') df['generic_compare'] = df['generic_compare']...
a421eece6e595159847821abcaf2cf7dd8dc88c5
3,650,865
def RMSRE( image_true: np.ndarray, image_test: np.ndarray, mask: np.ndarray = None, epsilon: float = 1e-9, ) -> float: """Root mean squared relative error (RMSRE) between two images within the specified mask. If not mask is specified the entire image is used. Parameters ---------- i...
6b377b2588ef0c02f059248d3214e0d7960ca25b
3,650,866
import PIL import logging def getImage(imageData, flag): """ Returns the PIL image object from imageData based on the flag. """ image = None try: if flag == ENHANCED: image = PIL.Image.open(imageData.enhancedImage.file) elif flag == UNENHANCED: image = PIL....
a3aaa80bc396fcdf099d5963706d21d63a6dcf0d
3,650,867
def save_record(record_type, record_source, info, indicator, date=None): """ A convenience function that calls 'create_record' and also saves the resulting record. :param record_type: The record type, which should be a value from the RecordTyp...
903eb7333cfd2cc534812c5417e5e32a7769ffe4
3,650,868
def update_product_price(pid: str, new_price: int): """ Update product's price Args: pid (str): product id new_price (int): new price Returns: dict: status(success, error) """ playload = {'status': ''} try: connection = create_connection() with connectio...
fff3723a9138724f1957cd9a669cdcf79e4ed4e5
3,650,869
def select_n_products(lst, n): """Select the top N products (by number of reviews) args: lst: a list of lists that are (key,value) pairs for (ASIN, N-reviews) sorted on the number of reviews in reverse order n: a list of three numbers, returns: a list of...
ed052708010512758845186ae9e4fb33b41bc511
3,650,870
def load_vanHateren(params): """ Load van Hateren data and format as a Dataset object Inputs: params [obj] containing attributes: data_dir [str] directory to van Hateren data rand_state (optional) [obj] numpy random state object num_images (optional) [int] how many images to extract. Default...
ca32f182f5534da89df0bd5454e74a586c6ca4d6
3,650,871
import argparse def build_parser() -> argparse.ArgumentParser: """Builds and returns the CLI parser.""" # Help parser help_parser = argparse.ArgumentParser(add_help=False) group = help_parser.add_argument_group('Help and debug') group.add_argument('--debug', help='Enable d...
0be83ee2e497f2c5ccfd21c4a4414c587304e6ee
3,650,872
import argparse import sys def parse_args(): """Parse command-line args. """ parser = argparse.ArgumentParser(description = 'Upload (JSON-encoded) conformance resources from FHIR IGPack tar archive.', add_help = False) parser.add_argument('-h', '--help', action = 'store_true', help = 'show this help ...
7c0ae02e07706ef212417ee7d0c4dd11a1de945c
3,650,873
import torch def wrap_to_pi(inp, mask=None): """Wraps to [-pi, pi)""" if mask is None: mask = torch.ones(1, inp.size(1)) if mask.dim() == 1: mask = mask.unsqueeze(0) mask = mask.to(dtype=inp.dtype) val = torch.fmod((inp + pi) * mask, 2 * pi) neg_mask = (val * mask) < 0 va...
7aca43bb2146c1cad07f9a070a7099e6fb8ad857
3,650,874
import pandas def if_pandas(func): """Test decorator that skips test if pandas not installed.""" @wraps(func) def run_test(*args, **kwargs): try: except ImportError: pytest.skip('Pandas not available.') else: return func(*args, **kwargs) return run_test
b39f88543559c4f4f1b9bb5bb30768916d3708d6
3,650,875
def handle_front_pots(pots, next_pots): """Handle front, additional pots in pots.""" if next_pots[2] == PLANT: first_pot = pots[0][1] pots = [ [next_pots[2], first_pot - 1]] + pots return pots, next_pots[2:] return pots, next_pots[3:]
53ec905a449c0402946cb8c28852e81da80a92ef
3,650,876
import types def environment(envdata): """ Class decorator that allows to run tests in sandbox against different Qubell environments. Each test method in suite is converted to <test_name>_on_environemnt_<environment_name> :param params: dict """ #assert isinstance(params, dict), "@environment ...
9ce82ff8ee3627f8795b7bc9634c298e8ff195bc
3,650,877
def get_domain_name(url): """ Returns the domain name from a URL """ parsed_uri = urlparse(url) return parsed_uri.netloc
00160285a29a4b2d1fe42fb8ec1648ca4c31fa8b
3,650,878
def get_answer_str(answers: list, scale: str): """ :param ans_type: span, multi-span, arithmetic, count :param ans_list: :param scale: "", thousand, million, billion, percent :param mode: :return: """ sorted_ans = sorted(answers) ans_temp = [] for ans in sorted_ans: ans...
734015503ccec63265a0531aa05e8bd8514c7c15
3,650,879
def user_0post(users): """ Fixture that returns a test user with 0 posts. """ return users['user2']
5401e7f356e769b5ae68873f2374ef74a2d439c6
3,650,880
import os def initialize(): """ Initialize some parameters, such as API key """ api_key = os.environ.get("api_key") # None when not exist if api_key and len(api_key) == 64: # length of a key should be 64 return api_key print("Please set a valid api_key in the environment variables.")...
2589aeea4db2d1d1f20de03bc2425e1835eb2f69
3,650,881
def plot_tuning_curve_evo(data, epochs=None, ax=None, cmap='inferno_r', linewidth=0.3, ylim='auto', include_true=True, xlabel='Bandwidths', ylabel='Average Firing Rate'): """ Plot evolution of TC averaged ove...
f571339b8a306304e1807ef3dd0f4b93e6856dd5
3,650,882
import json def transportinfo_decoder(obj): """Decode programme object from json.""" transportinfo = json.loads(obj) if "__type__" in transportinfo and transportinfo["__type__"] == "__transportinfo__": return TransportInfo(**transportinfo["attributes"]) return transportinfo
8a311cb419e9985ef0a184b82888220c0f3258b2
3,650,883
def group_events_data(events): """ Group events according to the date. """ # e.timestamp is a datetime.datetime in UTC # change from UTC timezone to current seahub timezone def utc_to_local(dt): tz = timezone.get_default_timezone() utc = dt.replace(tzinfo=timezone.utc) lo...
de2f2031bdcaaf2faffdb99c67bbbb1e15828ef8
3,650,884
def create_matrix(PBC=None): """ Used for calculating distances in lattices with periodic boundary conditions. When multiplied with a set of points, generates additional points in cells adjacent to and diagonal to the original cell Args: PBC: an axis which does not have periodic boundary condition....
7470803fe8297ef2db1ce4bd159e9d9c93d34787
3,650,885
def get_additive_seasonality_linear_trend() -> pd.Series: """Get example data for additive seasonality tutorial""" dates = pd.date_range(start="2017-06-01", end="2021-06-01", freq="MS") T = len(dates) base_trend = 2 state = np.random.get_state() np.random.seed(13) observations = base_trend *...
034b4ca9e086e95fa1663704fda91ae3986694b4
3,650,886
def is_client_trafic_trace(conf_list, text): """Determine if text is client trafic that should be included.""" for index in range(len(conf_list)): if text.find(conf_list[index].ident_text) != -1: return True return False
0b7fdf58e199444ea52476d5621ea9353475b0a0
3,650,887
def isinf(x): """ For an ``mpf`` *x*, determines whether *x* is infinite:: >>> from sympy.mpmath import * >>> isinf(inf), isinf(-inf), isinf(3) (True, True, False) """ if not isinstance(x, mpf): return False return x._mpf_ in (finf, fninf)
4d5ca6ac2f8ed233a70c706b7fff97bf171c4f21
3,650,888
def formalize_switches(switches): """ Create all entries for the switches in the topology.json """ switches_formal=dict() for s, switch in enumerate(switches): switches_formal["s_"+switch]=formalize_switch(switch, s) return switches_formal
8dbb9987e5bc9c9f81afc0432428a746e2f05fc4
3,650,889
def arp_scores(run): """ This function computes the Average Retrieval Performance (ARP) scores according to the following paper: Timo Breuer, Nicola Ferro, Norbert Fuhr, Maria Maistro, Tetsuya Sakai, Philipp Schaer, Ian Soboroff. How to Measure the Reproducibility of System-oriented IR Experiments. ...
0e23eb1d6ee3c2502408585b1d0dbb0993ca7628
3,650,890
from typing import Tuple from typing import Optional import scipy def bayesian_proportion_test( x:Tuple[int,int], n:Tuple[int,int], prior:Tuple[float,float]=(0.5,0.5), prior2:Optional[Tuple[float,float]]=None, num_samples:int=1000, seed:int=8675309) -> Tuple[float,floa...
5f63424b9dcb6e235b13a9e63f0b9a2dc1e95b31
3,650,891
import torch def _create_triangular_filterbank( all_freqs: Tensor, f_pts: Tensor, ) -> Tensor: """Create a triangular filter bank. Args: all_freqs (Tensor): STFT freq points of size (`n_freqs`). f_pts (Tensor): Filter mid points of size (`n_filter`). Returns: fb (...
1ad5bd58d673626a15e27b6d9d68829299fe7636
3,650,892
def convert_millis(track_dur_lst): """ Convert milliseconds to 00:00:00 format """ converted_track_times = [] for track_dur in track_dur_lst: seconds = (int(track_dur)/1000)%60 minutes = int(int(track_dur)/60000) hours = int(int(track_dur)/(60000*60)) converted_time = '%...
3d5199da01529f72b7eb6095a26e337277f3c2c9
3,650,893
def sync_xlims(*axes): """Synchronize the x-axis data limits for multiple axes. Uses the maximum upper limit and minimum lower limit across all given axes. Parameters ---------- *axes : axis objects List of matplotlib axis objects to format Returns ------- out : yxin, xmax ...
a377877a9647dfc241db482f8a2c630fe3eed146
3,650,894
def algo_config_to_class(algo_config): """ Maps algo config to the IRIS algo class to instantiate, along with additional algo kwargs. Args: algo_config (Config instance): algo config Returns: algo_class: subclass of Algo algo_kwargs (dict): dictionary of additional kwargs to pa...
884ab7a91d9d8c901d078f9b477d5d21cba3e5ff
3,650,895
def group_by_key(dirnames, key): """Group a set of output directories according to a model parameter. Parameters ---------- dirnames: list[str] Output directories key: various A field of a :class:`Model` instance. Returns ------- groups: dict[various: list[str]] ...
b291cd889c72fb198400b513e52ff9417c8d93b7
3,650,896
def redistrict_grouped(df, kind, group_cols, district_col=None, value_cols=None, **kwargs): """Redistrict dataframe by groups Args: df (pandas.DataFrame): input dataframe kind (string): identifier of redistrict info (e.g. de/kreise) group_cols (list): List of colu...
21f6514ca15d5fff57d03dab9d0bb7693c132e95
3,650,897
from typing import Tuple from typing import List import torch def count_wraps_rand( nr_parties: int, shape: Tuple[int] ) -> Tuple[List[ShareTensor], List[ShareTensor]]: """Count wraps random. The Trusted Third Party (TTP) or Crypto provider should generate: - a set of shares for a random number ...
b16e21be2d421e134866df8929a319a19bdd304a
3,650,898
from typing import Sequence def text_sim( sc1: Sequence, sc2: Sequence, ) -> float: """Returns the Text_Sim similarity measure between two pitch class sets. """ sc1 = prime_form(sc1) sc2 = prime_form(sc2) corpus = [text_set_class(x) for x in sorted(allClasses)] vectorizer = Tfidf...
6479ad4916fb78d69935fb9b618c5eb02951f05a
3,650,899