content
stringlengths
22
815k
id
int64
0
4.91M
def run(): """Runs the main script""" mobiles = [] route_list_html = requests.get(WEBSITE + ROUTES_LIST) route_list_soup = BeautifulSoup(route_list_html.text, 'html.parser') route_links = [] for link in route_list_soup.find_all('a'): if 'mobile-library-route' in link.get('href'): ...
5,333,000
def walk_dataset_timit(dataset_path: Path, hp: Map): """ Walk through all .wav files in the TIMIT dataset. :param dataset_path: path to TIMIT dataset :param hp: hyperparameters object :return: a generator of data samples """ for path in dataset_path.rglob("*.WAV"): yield preprocess_w...
5,333,001
def calc_wave_number(g, h, omega, relax=0.5, eps=1e-15): """ Relaxed Picard iterations to find k when omega is known """ k0 = omega ** 2 / g for _ in range(100): k1 = omega ** 2 / g / tanh(k0 * h) if abs(k1 - k0) < eps: break k0 = k1 * relax + k0 * (1 - relax) ...
5,333,002
def test_publish(session: nox.Session) -> None: """Publish this project to test pypi.""" publish(session, test=True)
5,333,003
def draw_contour_2d(points): """Draws contour of the 2D figure based on the order of the points. :param points: list of numpy arrays describing nodes of the figure. """ xs, ys = zip(points[-1], *points) plt.plot(xs, ys, color="blue")
5,333,004
def emit_live_notification_for_model(obj, user, history, *, type:str="change", channel:str="events", sessionid:str="not-existing"): """ Sends a model live notification to users. """ if obj._importing: return None content_type = get_typename_for_model_in...
5,333,005
def is_chitoi(tiles): """ Returns True if the hand satisfies chitoitsu. """ unique_tiles = set(tiles) return (len(unique_tiles) == 7 and all([tiles.count(tile) == 2 for tile in unique_tiles]))
5,333,006
def get_hpo_ancestors(hpo_db, hpo_id): """ Get HPO terms higher up in the hierarchy. """ h=hpo_db.hpo.find_one({'id':hpo_id}) #print(hpo_id,h) if 'replaced_by' in h: # not primary id, replace with primary id and try again h = hpo_db.hpo.find_one({'id':h['replaced_by'][0]}) hp...
5,333,007
async def download_category(soup, path, category): """ Category Wise """ event_names = [] event_links = [] body = soup.find("div", class_="list_wrapper row") for event in body.find_all("li"): event_year = event.get("data-sid") event_name = event_year + " " + event.div.a.picture.img...
5,333,008
def mcBufAir(params: dict, states: dict) -> float: """ Growth respiration Parameters ---------- params : dict Parameters saved as model constants states : dict State variables of the model Returns ------- float Growth respiration of the plant [mg m-2 s-1] ...
5,333,009
def gene_calling (workflow, assembly_dir, assembly_extentsion, input_dir, extension, extension_paired, gene_call_type, prokka_dir, prodigal_dir, threads, gene_file, gene_PC_file, protein_file, protein_sort, gene_info, complete_gene, complete_protein): ...
5,333,010
def space_boundaries_re(regex): """Wrap regex with space or end of string.""" return rf"(?:^|\s)({regex})(?:\s|$)"
5,333,011
def get_jobs(): """ this function will query USAJOBS api and return all open FEC jobs. if api call failed, a status error message will be displayed in the jobs.html session in the career page. it also query code list to update hirepath info. a hard-coded code list is used for backup if query fai...
5,333,012
def artanh(x) -> ProcessBuilder: """ Inverse hyperbolic tangent :param x: A number. :return: The computed angle in radians. """ return _process('artanh', x=x)
5,333,013
def fromtext(path, ext='txt', dtype='float64', skip=0, shape=None, index=None, labels=None, npartitions=None, engine=None, credentials=None): """ Loads series data from text files. Assumes data are formatted as rows, where each record is a row of numbers separated by spaces e.g. 'v v v v v'. You can ...
5,333,014
def flop_gemm(n, k): """# of + and * for matmat of nxn matrix with nxk matrix, with accumulation into the output.""" return 2*n**2*k
5,333,015
def index() -> str: """Rest endpoint to test whether the server is correctly working Returns: str: The default message string """ return 'DeChainy server greets you :D'
5,333,016
def get_git_hash() -> str: """Get the PyKEEN git hash. :return: The git hash, equals 'UNHASHED' if encountered CalledProcessError, signifying that the code is not installed in development mode. """ with open(os.devnull, 'w') as devnull: try: ret = check_output( # no...
5,333,017
def load_json_samples(path: AnyStr) -> List[str]: """ Loads samples from a json file :param path: Path to the target file :return: List of samples """ with open(path, "r", encoding="utf-8") as file: samples = json.load(file) if isinstance(samples, list): return samples ...
5,333,018
def openPort(path = SERIALPATH): """open the serial port for the given path""" try: port = Serial(path, baudrate = 115200) except : print("No serial device on the given path :" + path) sys.exit() return(port)
5,333,019
def test_skasch(): """ Run `python -m pytest ./day-03/part-2/skasch.py` to test the submission. """ assert ( SkaschSubmission().run( """ 00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010 """.strip() ) == 230 )
5,333,020
def decompress_lzma(data: bytes) -> bytes: """decompresses lzma-compressed data :param data: compressed data :type data: bytes :raises _lzma.LZMAError: Compressed data ended before the end-of-stream marker was reached :return: uncompressed data :rtype: bytes """ props, dict_size = struc...
5,333,021
async def on_guild_join(guild): """When the bot joins a server send a webhook with detailed information as well as print out some basic information.""" embed = discord.Embed( title = "Joined a server!", timestamp = datetime.datetime.utcnow(), color = 0x77DD77 ) embed.add_f...
5,333,022
def visualize_data_correlation(): """Large correlation plot""" df = pd.read_csv('sp500_joined_closes.csv') #df['AAPL'].plot() #plt.show() df_corr = df.corr() #print(df_corr.head()) data = df_corr.values fig = plt.figure() # plt.rcParams['figure.figsize'] = [4,2] ax = fig.add_su...
5,333,023
def save_dict_to_json(dictionary, filename): """ Saves a python dictionary to json file :param dictionary: dictionary object :param config: full filename to json file in which to save config :return: None """ with open(filename, 'w+') as f: json.dump(dictionary, f)
5,333,024
def AddCreateFlags(parser): """Adds all flags needed for the create command.""" GetDescriptionFlag().AddToParser(parser) group = base.ArgumentGroup( 'Manage the specific SKU reservation properties to create', required=True) group.AddArgument(GetRequireSpecificAllocation()) group.AddArgument(GetVmCount...
5,333,025
def generate_summary_table(bib): """Description of generate_summary_table Parse dl4m.bib to create a simple and readable ReadMe.md table. """ nb_articles = str(get_nb_articles(bib)) nb_authors = str(get_authors(bib)) nb_tasks = str(get_field(bib, "task")) nb_datasets = str(get_field(bib, "da...
5,333,026
def validate(request): """ Validate actor name exists in database before searching. If more than one name fits the criteria, selects the first one and returns the id. Won't render. """ search_for = request.GET.get('search-for', default='') start_from = request.GET.get('start-from', def...
5,333,027
def merge(left, right, on=None, left_on=None, right_on=None): """Merge two DataFrames using explicit-comms. This is an explicit-comms version of Dask's Dataframe.merge() that only supports "inner" joins. Requires an activate client. Notice ------ As a side effect, this operation concatena...
5,333,028
def extract_directory(directory): """Extracts bz2 compressed directory at `directory` if directory is compressed. """ if not os.path.isdir(directory): head, _ = os.path.split(os.path.abspath(directory)) print('Unzipping...', end=' ', flush=True) unpack_archive(directory + '.tar.bz2'...
5,333,029
def estimate_fs(t): """Estimates data sampling rate""" sampling_rates = [ 2000, 1250, 1000, 600, 500, 300, 250, 240, 200, 120, 75, 60, 50, 30, 25, ] fs_est = np.median(1 / np.diff(t))...
5,333,030
def get_case_number(caselist): """Get line number from file caselist.""" num = 0 with open(caselist, 'r') as casefile: for line in casefile: if line.strip().startswith('#') is False: num = num + 1 return num
5,333,031
def test_bam_to_h5_h5(expected_fixture, dir_out, sample): """ Test :py:const:`riboviz.workflow_r.BAM_TO_H5_R` H5 files for equality. See :py:func:`riboviz.h5.equal_h5`. :param expected_fixture: Expected data directory :type expected_fixture: str or unicode :param dir_out: Output directory :...
5,333,032
def build_param_float_request(*, scenario: str, value: float, **kwargs: Any) -> HttpRequest: """Send a post request with header values "scenario": "positive", "value": 0.07 or "scenario": "negative", "value": -3.0. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request buil...
5,333,033
def async_entries_for_config_entry( registry: DeviceRegistry, config_entry_id: str ) -> List[DeviceEntry]: """Return entries that match a config entry.""" return [ device for device in registry.devices.values() if config_entry_id in device.config_entries ]
5,333,034
def closure_js_binary(**kwargs): """Invokes actual closure_js_binary with defaults suitable for non-test JS files compilation. """ kwargs.setdefault("compilation_level", "ADVANCED") kwargs.setdefault("dependency_mode", "STRICT") kwargs.setdefault("language", "ECMASCRIPT5_STRICT") kwargs.setdefault("defs",...
5,333,035
def load_material(name: str) -> Material: """Load a material from the materials library Args: name (str): Name of material Raises: FileNotFoundError: If material is not found, raises an error Returns: Material: Loaded material """ try: with open( ...
5,333,036
def classify_checker(Classifier): """Type-checks the classifier input.""" if isinstance(Classifier, classifier.BaseClassifier) is False: raise TypeError('Classifier must be a BaseClassifier, ' 'was: %s', str(type(Classifier))) elif Classifier.classified is None: raise...
5,333,037
def reportBusniessModelSummaryView(request): """ รายงาน สรุปจำนวนผู้สมัครตามสถานะธุรกิจ ทุกขั้นตอน""" queryset = SmeCompetition.objects \ .values('enterpise__business_model', 'enterpise__business_model__name') \ .annotate(step_register=Count('enterpise__business_model')) \ .annotate(step...
5,333,038
def _get_announce_url(rjcode: str) -> str: """Get DLsite announce URL corresponding to an RJ code.""" return _ANNOUNCE_URL.format(rjcode)
5,333,039
def get_r_adv(x, decoder, it=1, xi=1e-1, eps=10.0): """ Virtual Adversarial Training https://arxiv.org/abs/1704.03976 """ x_detached = x.detach() with torch.no_grad(): pred = F.softmax(decoder(x_detached), dim=1) d = torch.rand(x.shape).sub(0.5).to(x.device) d = _l2_no...
5,333,040
def fetch_brats(datasetdir): """ Fetch/prepare the Brats dataset for pynet. Parameters ---------- datasetdir: str the dataset destination folder. Returns ------- item: namedtuple a named tuple containing 'input_path', 'output_path', and 'metadata_path'. """ ...
5,333,041
def init_app(app): """ Loads the entity modules. pylint disable as registration does not perform action yet. Parameters ---------- app (Flask): The flask application. """ init_routes(app)
5,333,042
def get_factors(shoppers, n_components=4, random_state=903, **kwargs): """ Find Factors to represent the shopper-level features in compressed space. These factors will be used to map simplified user input from application to the full feature space used in modeling. Args: shoppers (pd.DataFr...
5,333,043
def cols_to_array(*cols, remove_na: bool = True) -> Column: """ Create a column of ArrayType() from user-supplied column list. Args: cols: columns to convert into array. remove_na (optional): Remove nulls from array. Defaults to True. Returns: Column of ArrayType() """ ...
5,333,044
def suppress() -> None: """Suppress output within context.""" with open(os.devnull, "w") as null: with redirect_stderr(null): yield
5,333,045
def _git_repo_status(repo): """Get current git repo status. :param repo: Path to directory containing a git repo :type repo: :class:`pathlib.Path()` :return: Repo status :rtype: dict """ repo_status = { 'path': repo } options = ['git', '-C', str(repo), 'status', '-s'] ...
5,333,046
def _parseList(s): """Validation function. Parse a comma-separated list of strings.""" return [item.strip() for item in s.split(",")]
5,333,047
def true_segments_1d(segments, mode=SegmentsMode.CENTERS, max_gap=0, min_length=0, name=None): """Labels contiguous True runs in segments. Args: segments: 1D boolean tensor. mode: The SegmentsMode. Returns the start of each...
5,333,048
def get_user_language_keyboard(user): """Get user language picker keyboard.""" buttons = [] # Compile the possible options for user sorting for language in supported_languages: button = InlineKeyboardButton( language, callback_data=f'{CallbackType.user_change_language.val...
5,333,049
def splitDataSet(dataSet, index, value): """ 划分数据集,取出index对应的值为value的数据 dataSet: 待划分的数据集 index: 划分数据集的特征 value: 需要返回的特征的值 """ retDataSet = [] for featVec in dataSet: if featVec[index] == value: reducedFeatVec = featVec[:index] reducedFeatVec.extend(fe...
5,333,050
def weights_init(module, nonlinearity="relu"): """Initialize a module and all its descendents. Parameters ---------- module : nn.Module module to initialize. """ # loop over direct children (not grand children) for m in module.children(): # all standard layers if isi...
5,333,051
def spam(a, b, c): """The spam function Returns a * b + c""" return a * b + c
5,333,052
def show_rules(cli, nick, chan, rest): """Displays the rules.""" reply(cli, nick, chan, var.RULES)
5,333,053
def in_skill_product_response(handler_input): """Get the In-skill product response from monetization service.""" """ # type: (HandlerInput) -> Union[InSkillProductsResponse, Error] """ locale = handler_input.request_envelope.request.locale ms = handler_input.service_client_factory.get_monetization_servi...
5,333,054
def ipaddr( value: typing.Union[str, int], query: typing.Optional[str] = None, ) -> str: """Filter IP addresses and networks. .. versionadded:: 1.1 Implements Ansible `ipaddr filter <https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters_ipaddr.html>`_. """ return _utils....
5,333,055
def Run3dTests(tally): """Run all of the 3d tests on a single Globe.""" unpacker = Unpacker("../test_data/test.glb", False) RunTest(tally, TestGlobeImageryPacket, unpacker) RunTest(tally, TestGlobeTerrainPacket, unpacker) RunTest(tally, TestGlobeVectorPacket, unpacker) RunTest(tally, TestGlobeQtPacket, unpa...
5,333,056
def npoints_between(lon1, lat1, depth1, lon2, lat2, depth2, npoints): """ Find a list of specified number of points between two given ones that are equally spaced along the great circle arc connecting given points. :param float lon1, lat1, depth1: Coordinates of a point to start from. The first...
5,333,057
def maxPoolLayer(x, kHeight, kWidth, strideX, strideY, name, padding = "SAME"): """max-pooling""" return tf.nn.max_pool(x, ksize = [1, kHeight, kWidth, 1], strides = [1, strideX, strideY, 1], padding = padding, name = name)
5,333,058
def coo2st(coo): """ transform matrix in sparse coo_matrix to sparse tensor of torch INPUT coo - matrix in sparse coo_matrix format OUTPUT coo matrix in torch.sparse.tensor """ values = coo.data indices = np.vstack((coo.row, coo.col)) i = torch.LongTensor(indices) v = torc...
5,333,059
def test_stability( percentage_to_remove, x_features, y_labels, outer_cv_splits, inner_cv_splits, hyperparameter_space, model_name, max_iter=1000, export=True ): """Train model after removing specified features. Train elastic net model wit...
5,333,060
def make_dataset(data, nafc): """Create a PsiData object from column based input. Parameters ---------- data : sequence on length 3 sequences Psychometric data in colum based input, e.g.[[1, 1, 5], [2, 3, 5] [3, 5, 5]]. nafc : int Number of alternative choices in forced choi...
5,333,061
def TorchFFTConv2d(a, K): """ FFT tensor convolution of image a with kernel K Args: a (torch.Tensor): 1-channel Image as tensor with at least 2 dimensions. Dimensions -2 & -1 are spatial dimensions and all other dimensions are assumed ...
5,333,062
def pad(obj, pad_length): """ Return a copy of the object with piano-roll padded with zeros at the end along the time axis. Parameters ---------- pad_length : int The length to pad along the time axis with zeros. """ if not isinstance(obj, Track): raise TypeError("Suppo...
5,333,063
def main(): """Load possessions from pbpstats for all seasons on file, and store them""" season_info = seasons_on_file() for league, year, season_type in zip( season_info["league"], season_info["year"], season_info["season_type"] ): logger.info(f"Loading season data for {league} {year} {...
5,333,064
def validate_server_object(server_object): """ :param server_object: """ if isinstance(server_object, dict): for k, v in server_object.items(): if k not in ["url", "description", "variables"]: raise ValidationError( 'Invalid server object. Unknow...
5,333,065
def stat_mtime(stat): """Returns the mtime field from the results returned by os.stat().""" return stat[8]
5,333,066
def from_yaml_dictionary(yaml_gra_dct, one_indexed=True): """ read the graph from a yaml dictionary """ atm_dct = yaml_gra_dct['atoms'] bnd_dct = yaml_gra_dct['bonds'] atm_dct = dict_.transform_values( atm_dct, lambda x: tuple(map(x.__getitem__, ATM_PROP_NAMES))) bnd_dct = dict_.transf...
5,333,067
def _check_no_current_table(new_obj, current_table): """ Raises exception if we try to add a relation or a column with no current table. """ if current_table is None: msg = 'Cannot add {} before adding table' if isinstance(new_obj, Relation): raise NoCurrentTableException(msg.for...
5,333,068
def classifier_train( X_train, y_train, X_val, y_val, clf, k_fold_no=10, uo_sample_method=None, imbalance_ratio=1, print_results=False, train_on_all=False, ): """Trains a sklearn classifier using k-fold cross-validation. Returns the ROC_AUC score, with other parameters i...
5,333,069
def test_no_common_points(): """Tests relative position with no common points""" circle1 = Circle(Point(2.0, 1.0), 1.0) circle2 = Circle(Point(6.0, 4.0), 2.0) assert circle1.find_relative_position(circle2) == RelativePosition.NO_COMMON_POINTS circle1 = Circle(Point(2.0, 1.0), 9.0) circle2 = Circ...
5,333,070
def html_code_envir(envir, envir_spec): """ Return html tags that can be used to wrap formatted code This method was created to enhance modularization of code. See latex_code_envir in latex.py :param tuple[str, str, str] envir: code blocks arguments e.g. ('py','cod','-h') :param str envir_spec: opt...
5,333,071
def get_data_from_epndb(pulsar): """ Searches the EPN database and returns all information of the chosen pulsar Parameters: ----------- pulsar: string The name of the pulsar to search for Returns: -------- pulsar_dict: dictionary A dictionary in which each value is a li...
5,333,072
def apply_templates(X, templates): """ Generate features for an item sequence by applying feature templates. A feature template consists of a tuple of (name, offset) pairs, where name and offset specify a field name and offset from which the template extracts a feature value. Generated features are ...
5,333,073
def _variants_fields(fields, exclude_fields, info_ids): """Utility function to determine which fields to extract when loading variants.""" if fields is None: # no fields specified by user # by default extract all standard and INFO fields fields = config.STANDARD_VARIANT_FIELDS + info...
5,333,074
def make_rta_basecalls_1460(intensities_dir): """ Construct an artificial RTA Intensities parameter file and directory """ basecalls_dir = os.path.join(intensities_dir, 'BaseCalls') if not os.path.exists(basecalls_dir): os.mkdir(basecalls_dir) param_file = os.path.join(TESTDATA_DIR, 'rta_...
5,333,075
def calc_very_restricted_wage_distribution(df): """Compute per-period mean and std of wages for agents under two choice restrictions.""" return ( df.query("Policy == 'veryrestricted' and Choice == 'a' or Choice == 'b'") .groupby(["Period"])["Wage"] .describe()[["mean", "std"]] )
5,333,076
def eda2(data: pd.DataFrame): """ eda_metricで得たdataを可視化するメソッドver.2 :param data: :return: """ print(f"Label Count: {data['label'].sum()}, Query Count: {len(data)}") keys = ["SWEM", "BERT", "SBERT", "Ensemble"] for key in keys: data[f"{key}_rank"] = data[key].rank(ascending=False) ...
5,333,077
def compute_boundary_distance(idx_row, params, path_out=''): """ compute nearest distance between two segmentation contours :param (int, str) idx_row: :param dict params: :param str path_out: :return (str, float): """ _, row = idx_row name = os.path.splitext(os.path.basename(row['path_i...
5,333,078
def distrib_one_v_max( adata: anndata, celltype: str, ax, gene_highlight: Iterable[str], partition_key: str = "CellType", ): """ Parameters ---------- adata The corrected expression data. celltype Celltype to be plotted gene_highlight List of genes ...
5,333,079
def create_angler(request, report_a_tag=False): """This view is used to create a new tag reporter / angler. when we create a new angler, we do not want to duplicate entries with the same first name and last name by default. If there already angers with the same first and last name, add them to the ...
5,333,080
def override_template(view, template): """Override the template to be used. Use override_template in a controller method in order to change the template that will be used to render the response dictionary dynamically. The ``view`` argument is the actual controller method for which you want to repl...
5,333,081
def peak_1d_binary_search_iter(nums): """Find peak by iterative binary search algorithm. Time complexity: O(logn). Space complexity: O(1). """ left, right = 0, len(nums) - 1 while left < right: mid = left + (right - left) // 2 if nums[mid] < nums[mid + 1]: # If mid...
5,333,082
def add_site_users_sheet(ws, cols, lnth): """ """ for col in cols: cell = "{}1".format(col) ws[cell] = "='Total_Sites_MNO'!{}".format(cell) for col in cols[:2]: for i in range(2, lnth): cell = "{}{}".format(col, i) ws[cell] = "='Total_Sites_MNO'!...
5,333,083
def process(document, rtype=None, api=None): """ Extracts named entities in specified format from given texterra-annotated text.""" entities = [] if annotationName in document['annotations']: if rtype == 'entity': for token in document['annotations'][annotationName]: ent...
5,333,084
def get_out_hmm_path(new_afa_path): """Define an hmm file path for a given aligned fasta file path. """ new_exten = None old_exten = new_afa_path.rsplit('.', 1)[1] if old_exten == 'afaa': new_exten = 'hmm' elif old_exten == 'afna': new_exten = 'nhmm' # Check that it worked. ...
5,333,085
def log_predictions(logger, config): """ Log network predictions :param logger: logger instance :param config: dictionary with configuration options """ network = net.ml.VGGishNetwork( model_configuration=config["vggish_model_configuration"], categories_count=len(config["categor...
5,333,086
def transformer_decoder_block(name, n_layers, x, x_mask, output_size, init, **kwargs): """A transformation block composed of transformer d...
5,333,087
def compute_rolling_norm( signal: Union[pd.DataFrame, pd.Series], tau: float, min_periods: int = 0, min_depth: int = 1, max_depth: int = 1, p_moment: float = 2, ) -> Union[pd.DataFrame, pd.Series]: """ Implement smooth moving average norm (when p_moment >= 1). Moving average corresp...
5,333,088
def msort(liste, indice): """ This function sorts a vector regarding values of the indice 'indice' Indice start from 0 """ tmp = [[tbl[indice]]+[tbl] for tbl in liste] tmp.sort() liste = [cl[1] for cl in tmp] del tmp return liste
5,333,089
def _Net_forward(self, blobs=None, start=None, end=None, **kwargs): """ Forward pass: prepare inputs and run the net forward. Take blobs: list of blobs to return in addition to output blobs. kwargs: Keys are input blob names and values are blob ndarrays. For formatting inputs for...
5,333,090
def get_job_details(): """Reads in metadata information about assets used by the algo""" job = dict() job["dids"] = json.loads(os.getenv("DIDS", None)) job["metadata"] = dict() job["files"] = dict() job["algo"] = dict() job["secret"] = os.getenv("secret", None) algo_did = os.getenv("TRAN...
5,333,091
def test_stack_hasnt_script_mandatory_key(sdk_client_fs: ADCMClient): """Test upload bundle with action without script field""" stack_dir = utils.get_data_dir(__file__, "script_mandatory_key") with pytest.raises(coreapi.exceptions.ErrorMessage) as e: sdk_client_fs.upload_from_fs(stack_dir) with ...
5,333,092
def main(): """ メイン """ # DBファイル名 dbname = 'history.sqlite3' # DB接続・カーソル取得 conn = sqlite3.connect(dbname) cur = conn.cursor() create_sql = """ CREATE TABLE COUNT ( reading TEXT, count INTEGER NOT NULL, PRIMARY KEY(reading)); """ cur.executescript(...
5,333,093
def mre(actual: np.ndarray, predicted: np.ndarray, benchmark: np.ndarray = None): """ Mean Relative Error """ # return np.mean( np.abs(_error(actual, predicted)) / (actual + EPSILON)) return np.mean(_relative_error(actual, predicted, benchmark))
5,333,094
def _get_fusion_kernel(patch_size, fusion='gaussian', margin=0): """ Return a 3D kernel with the same size as a patch that will be used to assign weights to each voxel of a patch during the patch-based predictions aggregation. :param patch_size: int or tuple; size of the patch :param fusion: str...
5,333,095
def __validate_node__(node: dict): """ Validate that a given nodes parameters are valid. Expected signature: {'class_name': 'NewWorker', 'parent': 'SpectrumCoordinator', 'args': (), 'kwargs':{}} Args: - node: node signature to validate. """ if not isinst...
5,333,096
def transforma( vetor: list, matriz_linha: bool = True, T: callable = lambda x: transposta(x) ) -> list: """Transforma um vetor em uma matriz linha ou matriz coluna.""" matriz = [] if matriz_linha: matriz.append(vetor) else: matriz.append(vetor) matriz = T(matriz) return ...
5,333,097
def trace_partition_movement( points, distance, interval, break_interval=None, include_inaccurate=True): """Wrapper to optionally split stops at data gaps greater than break_interval.""" pll = break_interval \ and trace_split_sparse(points, break_interval) ...
5,333,098
def post(event, context): """ :param event: AWS Log Event. :param context: Object to determine runtime info of the Lambda function. See http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html for more info on context. Process an AWS Log event and post it to a Slack Channel. "...
5,333,099