content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def api_chart_scores(request): """ Used by report page line chart. Returns JSON in format needed for line chart. Used to load and chart a scoped set of Lighthouse runs. """ urlId = request.GET.get('urlid', None) rangeType = request.GET.get('range', None) ## Validate that...
bdf8820fa7f670ffc09fc24c058eca2b47b9b76a
3,601,900
import re def auto_discover(): """ Auto-map urls from controllers directory. Ignored only files and classes that start from underscore. """ urls = [ url(r'^admin/', admin.site.urls), ] # TODO: we can create python package to have a lot of controllers # in separate files d...
62dd782c23832afdc43bcce1557994159c444c71
3,601,901
def sel_init_cen(features, k): """ 随机选择K个初始聚类中心 :param features: [[r,g,b],[r,g,b]...] :return: centors=[cen1,cen2...] """ # 选取随机数 rands = [(int)(np.random.random() * (features.shape[0])) for _ in range(k)] # 选取初始中心 centors = [features[rands[i]] for i in range(k)] return centors
e61b3029297a610e04bca1b50067f7f32b11dad5
3,601,902
def cfgargparse( cfgspecfile, parser, parse=True, cfgfileopt="--cfgfile", cfgfile="config.cfg", exc=[], extraopts=None, args=None, getparser=False, getargs=True, **kwargs, ): """Merge configuration and commandline arguments Parameters ---------- cfgspecfile: ...
911bcfa13c1bbc5b977582b40953b4a5716bab49
3,601,903
import ast def _is_ast_str(node): """Determine whether this node represents a string.""" allowed_types = [ast.Str] if hasattr(ast, "Bytes"): allowed_types += [ast.Bytes] if hasattr(ast, "JoinedStr"): allowed_types += [ast.JoinedStr] if hasattr(ast, "FormattedValue"): allowed_types += [ast.Format...
132af7142404f885684ce6559d1472c622c9cd10
3,601,904
def as_dict(self, **kwargs): """ Convert this object in a json serializable dict (can be use in __init__). Optional keyword input parameter is for internal use only and may prevent json serializability. """ DataKeeper_dict = dict() DataKeeper_dict["name"] = self.name DataKeeper_dict["ph...
c2c9535a39d21a5946df41d67df29fd43b3f3692
3,601,905
def translate_xmile(xmile_file): """ Translate an xmile model file into a python class. Functionality is currently limited. """ py_model_file = build_python(xmile_file) return py_model_file
5740e05b91d966c6d5ea33752bb38010c522c5fe
3,601,906
def access_token_url(): """ URL for exchanging a verifier for an access token. """ return _BASE_URL_V1 % 'oauth/access_token/'
9422c7b8ceae38d9ae92a89b4dbd55c71fd32175
3,601,907
def SetSpDiff(ea, delta): """ Setup modification of SP made by the instruction @param ea: end address of the instruction i.e.the last address of the instruction+1 @param delta: the difference made by the current instruction. @return: 1-ok, 0-failed """ return idaapi.add_user...
606c7ec20dab0a5af1bb8f8d5e69f4e95163cee3
3,601,908
import itertools def score(data, synth, targets=[]): """ Compute the total variation distance between marginals of data and synth. :param data: an mbi.Dataset object :param synth: an mbi.Dataset object :param targets: A list of columns in the data domain """ workload = list(itertools.combinat...
4a8ca07b1197ca567678291cbaf3585b6f7843bf
3,601,909
import torch def create_train_and_validation_engines(train_func, val_func=None, device='cpu'): """ Helper function for creating an ignite Engine object with helpful defaults. This sets up an Engine that has four handlers attached to it: - prepare_batch: before a batch is passed to train_func or val_f...
6f0591196be25c5d1592200ac28b0317af54b22c
3,601,910
import lifelines def median_survival_times(model_or_survival_function) -> float: """ Compute the median survival time of survival function(s). Parameters ----------- model_or_survival_function: lifelines model or DataFrame This can be a univariate lifelines model, or a DataFrame of one o...
93e22de3c9673c12b9052fd2338ce2a304ba2a56
3,601,911
import random def create_bank(num_accounts=1): """Returns a new bank with the given number of accounts.""" names = ("Brandon", "Molly", "Elena", "Mark", "Tricia", "Ken", "Jill", "Jack") bank = Bank() upper_pin = num_accounts + 1000 for pin_number in range(1000, upper_pin): ...
a7c131d80520e7f8b7285fc10d24724091a75d82
3,601,912
def Linear(source, target): """ Performs basic linear interpolation in between a source and a target. """ if target.frame <= source.frame: raise ValueError("Target frame must be greater than source frame " "(source = {0}, target = {1})".format(source.frame, target.frame)) fdiff = fl...
89e6fb8ec03324cc971eee60291a1008b3834e32
3,601,913
def gaussian_mask(S): """ mask significant intensities in spectrum Parameters ---------- S : np.array, size=(m,n), dtype=complex array with spectrum, i.e.: S = np.fft.fft2(I) Returns ------- M : np.array, size=(m,n), dtype=bool frequency mask See Al...
a8cf0847dd796aead0577ce48c2511710af7546b
3,601,914
import tqdm def get_data(data_type: str, left_flank_size: int, right_flank_size: int, n_bins: int = 100, bin_value_type: str = 'mean') -> pd.DataFrame: """ Generates histone modification data by bins for each gene. :param data_type: 'seq' or 'histone' data :param left_flank_size: number ...
108fbcb77feb0734ecc564ef8bf4eaf782551c39
3,601,915
def make_dict_from_config(path, config_file): """ Function to make a dict from a configuration file Parameters --------------- path: str path dir to the config file config_file: str config file name Returns ---------- dict with the config file infos """ # open a...
fd928dde7bb9ea3d360237c34bc7c46f9f26b07a
3,601,916
def is_walrus_assignment(node: LN) -> bool: """Return True iff `node` is of the shape ( test := test )""" inner = unwrap_singleton_parenthesis(node) return inner is not None and inner.type == syms.namedexpr_test
5c9b594187d3e91330cb3089fe7bc21fafafa3f2
3,601,917
def createAccount(sessionId): """ create user account URL Path: sessionId: login session ID Body (required): - JSON string of account info HTTP Return Codes: - 200 OK: if the request successfully completed. - 403 Forbidden: Invalid session ID. - 400 Bad Request: URL a...
2cbec461074c7df367d1e90cd80c2c3fef8389a8
3,601,918
def extract_domain(email_address): """ Given an email address, extract the domain name from it. This is done by finding the @ and then splicing the email address and returning everything found after the @. If no @ is found then the entire email address string is returned. :param email_address: ...
3e09c9cef431c09d126d8de6854990dc9351ef0d
3,601,919
def get_sweep_info(pul, pgf, group_idx, series_idx): """ Find the associated record in the StimTree from the PulseTree """ pul_series = pul["ch"][group_idx]["ch"][series_idx] num_sweeps_in_recorded_data = pul_series["hd"]["SeNumberSweeps"] pul_sweep = pul_series["ch"][0] stim_idx = pul_swee...
ebb2f125f9dbf45f80e088d63314a6fd10069a06
3,601,920
def build_model(args: Namespace) -> nn.Module: """ Builds a MoleculeModel, which is a message passing neural network + feed-forward layers. :param args: Arguments. :return: A MoleculeModel containing the MPN encoder along with final linear layers with parameters initialized. """ output_size = a...
1eaa94e714f44bdaeb4afd1a71f4e5cdf876294a
3,601,921
import pandas as pd def google_scholar(root="./", download=True, full=False) -> Dataset: """Google Scholar dataset (Agrawal, et al.). The Google Scholar dataset contains an academic coauthorship graph: the nodes are authors, and two authors are connected by an edge if either author listed the other a...
87876024913826b8d9769a78f72cd944057c04ce
3,601,922
def standard_form(ich, stereo=True): """ Return an InChI string in standard form. Eventually we should just designate standard-form as standard InChI ordering for all but the hardcoded exceptions, put at the end. :param ich: InChI string :type ich: str :param stereo: parame...
554fa9d538e8b6e4f9983725f570ce28a6d6ae34
3,601,923
def check_solution(model, solution): """ Helper function. if solution is None, attempts to get it from the model. :param model: :param solution: :return: """ if solution is None: try: solution = model.solution except AttributeError: raise AttributeErr...
a03ee5e2033ee99caa0fd761f9d78d3d597a906b
3,601,924
import torch from unittest.mock import Mock def test_batch_verification_calls_custom_input_output_mappings(): """ Test that batch gradient verification can support different input and outputs with user-provided mappings. """ model = MultipleInputModel() def input_mapping(inputs): assert isinstanc...
367d7389bd09762d8059a2e66e4c7d9a64aacd76
3,601,925
def gather_files(files_in): """ Args: files_in (str): """ cubes = iris.load(files_in) cubes.sort(key=lambda x: x.name()) unify_time_units(cubes) # Add the names of custom output fields replace_names(cubes) # Remove hybrid height cubes and add as coordinates instead rep...
edf84eaf418d58fc18e90949fe87a89d4c38f5c2
3,601,926
def pose_disambiguation(x2, K, C2, R2, X_n): """ Returns the pose that minimizes reprojection error. :param x2: 2D points corresponding to X_n :param K: camera intrinsic matrix :param C2: four configurations of camera centers :param R2: four configurations of rotations :param X_n: four sets ...
a85926460e9d8a68267958977205a31f627601c4
3,601,927
import yaml def dict_from_yaml(yaml_file): """Gets the dict representation of a YAML file.""" try: yaml_dict = yaml.safe_load(yaml_file) assert isinstance(yaml_dict, dict) return yaml_dict except yaml.YAMLError as e: raise InvalidInputException(e)
94ea65e958cfb814658dfe320f4e020ae9fe338f
3,601,928
def plot_quantile_returns_violin(return_by_q, ylim_percentiles=None, ax=None): """ Plots a violin box plot of period wise returns for factor quantiles. Parameters ---------- return_by_q : pd.DataFrame - MultiIndex DataFrame w...
9c993c45a0fc655c581943ef6a99b279461fd0d8
3,601,929
def str_to_dict(value): """ Convert a newline terminated string of key=value into a dictionary. Parameters ---------- value : str The string object to convert to a dictionary Returns ------- dict Dictionary based on the string """ result_dict = {} for item ...
97a11fdbb715fad2da2e5866e30472a1b49e2c5e
3,601,930
import sys import urllib import re def _url2path(url, platform=sys.platform): """Convert normalized url path to system path.""" def _to_filename(url): parts = urllib.parse.urlsplit(url) newparts = [] for part, key in zip(parts, _CHANGE_TO): for char, repl in _CHANGE_TO[key]...
10053693566147896ba945b1e948378f5505adb5
3,601,931
def degTodms(ideg): """ Converts degrees to degrees:minutes:seconds :param ideg: objects coordinate in degrees :type ideg: float :return: degrees:minutes:seconds :rtype: string """ if (ideg < 0): s = -1 else: s = 1 ideg = abs(ideg) deg = int(ideg) + 0. m...
169cf4a89e7a2bd8526cf32acd1e88ec62d0237f
3,601,932
def convert_rgb565(image): """Converts the RGB image into a byte array in RGB565 format""" data = bytearray(128 * 160 * 2) i = 0 for (r, g, b) in image.getdata(): w = rgb888_to_rgb565(r, g, b) data[i] = w >> 8 i += 1 data[i] = w & 0xff i += 1 return data
e2fd92e73499a640280fa65936dd2603cade22d1
3,601,933
from datetime import datetime from typing import Tuple from typing import Dict import random def _create_new_row( table: Table, primary_key: int, parent_key: int = None, batch_id: int = None, timestamp: datetime = datetime.now(), ) -> Tuple: """ Create a new row for a table. Substitute cr...
2683930a49f33e25c97687b63687d70fcde709d4
3,601,934
def char_to_string(arr): """Like netCDF4.chartostring, but faster and more flexible. """ # based on: http://stackoverflow.com/a/10984878/809705 arr = np.asarray(arr) kind = arr.dtype.kind if kind not in ['U', 'S']: raise ValueError('argument must be a string') return arr.view(kind + ...
c25446c0a2d028249ad7e30fe6fd70245baea617
3,601,935
def extract_class(mask, class_to_extract, value_type): """ Extract either bits or values from an image. :param mask: Numpy array :param value_type: The type of the value to be extracted. Can be one of 'Bit', 'Value' or 'Threshold'. :param class_to_extract: The items to be extracted. In the case ...
6f12cb4d145d7fbea1b59e56f4d73ecfc8b84be3
3,601,936
import pandas import numpy def rolling_stat(stat, x, window): """ Calculate rolling statistics `stat` of `x` with sliding `window`. Parameters ---------- stat : 'snr', 'cv', 'fano', 'mean', 'median', ... Name (`str`) of the rolling statistics supported by pandas and `getstat` (e.g...
54ff5a66925390e291dc86eec60437abb4c0ecaf
3,601,937
import os def import_ase(file_path): """ Import general file using ase.io """ file_format = check_file_type(file_path) atoms = ase.io.read(file_path, format=file_format) struct = Structure.from_ase(atoms) file_name = os.path.basename(file_path) # Struct ID is filename before decimal ...
25d2c4ff1ed0765ee30337bd741a35703b7d2f7f
3,601,938
from typing import OrderedDict def evaluate_box_proposals(dataset, roidb): """Evaluate bounding box object proposals.""" res = _empty_box_proposal_results() areas = {'all': '', 'small': 's', 'medium': 'm', 'large': 'l'} for limit in [100, 1000]: for area, suffix in areas.items(): s...
e0a5ba8bad0711f0d1285925642029c64da54fde
3,601,939
def breakbarrier(self, *qargs): """Apply :class:`~qiskit.circuit.Barrier`. If qargs is None, applies to all.""" #from .barrier import Barrier qubits = [] if not qargs: # None for qreg in self.qregs: for j in range(qreg.size): qubits.appen...
22addde668d669e9574f4f929248b16ebb0481db
3,601,940
def build_command(input_device, rates, bits, buffers, sox_effects): """ :param input_device: device index e.g. 2 :param rates: [input, output] e.g. [48000, 48000] :param bits: [input, output] e.g. [16, 16] :param buffers: [input, sox] e.g. [512, 1024] :param sox_effects: [left, right] e.g. [['eq...
8c17f55ef8ff3d0abc8ffbdbe85a2d98306a6b37
3,601,941
def filter_sparse(timestamps): """ Create a sparse set of timestamps, by keeping only 1 timestamp for every 10 minute interval. """ if len(timestamps) == 0: return [] ok = [timestamps[0]] for vis_ts, ir_ts in sorted(timestamps, key=lambda x: x[0]): if (vis_ts - ok[-1][0]) >...
12030e7f9151c2c846d4fd7f0c31bcc1c28104ae
3,601,942
import argparse def parse_arguments(): """ Parse command line arguments :return: Parsed arguments """ # Define and parse input arguments parser = argparse.ArgumentParser() parser.add_argument("--modeldir", help="Folder the .tflite file is located.", ...
c93178c7101fadfd1c6d42c3986e9815129ceeb6
3,601,943
def extract_spectrogram_background_fit1D(data, err, deg=1, ws=(20, 30), pixel_step=1, sigma=5): """ Fit a polynomial background slice per slice along the x axis, with outlier removal, on lateral bands defined by the ws parameter. Parameters ---------- data: array The 2D array image. The...
4778ed9d7829cfa1db9e06c2cd062880a0a727b3
3,601,944
import six import os import sqlite3 def writeDB(filename, catalog, meta=None): """ Output an sqlite3 database containing one table for each source type Parameters ---------- filename : str Output filename catalog : list List of sources of type :class:`AegeanTools.models.Compo...
99b58d04e8bc16685a56745c2c5c3cd4da4ce225
3,601,945
from pathlib import Path def main() -> int: """ Execute the setup command.""" def data_files(*paths): """ Expand path contents for the `data_files` config variable. """ for path in map(Path, paths): if path.is_dir(): for root, _, files in walk(str(path)): ...
21538616157f4916184936c4ecf559cdb85eead7
3,601,946
from typing import Union def conditional_join( df: pd.DataFrame, right: Union[pd.DataFrame, pd.Series], *conditions, how: str = "inner", sort_by_appearance: bool = False, ) -> pd.DataFrame: """ This is a convenience function that operates similarly to ``pd.merge``, but allows joins on...
e70c1bc31111312d3c8df0b6b6556000673a923b
3,601,947
def prepare_results(cursor_description, rows): """ Generate result in JSON format with an entry consisting of key value pairs. :param cursor_description: a tuple with query result columns :param rows: list of returned sql query values :return: dictionary """ if rows is None or len(rows) == 0...
8fcc48f0a732a200c65d27817349a0de1a5f1172
3,601,948
from typing import List def merge_rgb(images: List[Image]) -> List[Image]: """Variant of images_to_stack that makes an RGB from 3 images.""" if not (len(images) == 3 and all(isinstance(x, Image) for x in images)): raise ValueError( trans._("merge_rgb requires 3 images layers", deferred=Tru...
c8dd9952a78f93720714ad8c5482fe5679ffc347
3,601,949
import os def _prepare_sfeal(): """ Preapring the meshes for PCA. :return: Prepared SFEAL model object. """ path = config["path"] volume = config["volume"] fitted_mesh_dir = config["fitted_mesh_dir"] subjects = config["subjects"] aligned_meshes = [] for sub in subjects: ...
4af5ea95117bea88a4b964aa034de5693eb90154
3,601,950
def signed_in_users(session=None, today=None, full_name=True): """Return list of names of currently signed in users. :param session: SQLAlchemy session through which to access the database. :param today: (optional) The current date as a `datetime.date` object. Used for testing. :param full_name: (optio...
55e394f778af9786c0ee3ba98b1bdcd20530b32e
3,601,951
def eval_hess_f(Y): """ compute the hessian of f in the forward mode of AD """ Y = algopy.UTPM.init_hessian(Y) retval = eval_f(Y) hessian = algopy.UTPM.extract_hessian(5, retval) return hessian
67272b4ae62def8cd993f77ec5751dbec71900b5
3,601,952
import os def process_workspace_list(arguments, config, calling_dir = os.getcwd()): """ Processes a list of arguments from command line and resolves it to a list of workspaces. Parameters ---------- arguments : list of str command line arguments to resolve to workspaces aliases : ...
d87672722a3f6ee568580efaa98cdafa8271a311
3,601,953
from typing import Tuple import re def get_name_version_from_requires_dist(string_parse: str) -> Tuple[str, str]: """Extract the name and the version from `requires_dist` present in PyPi`s metadata :param string_parse: requires_dist value from PyPi metadata :return: Name and version of a package ...
55545ec1b30a4db1944932070434d26205beefbd
3,601,954
import torch def _rescale(dat, mn_out=0, mx_out=511): """ Rescales image intensities between mn_out and mx_out. """ dtype = dat.dtype device = dat.device dat[(dat == dat.min()) | ~torch.isfinite(dat) | (dat == dat.max())] = 0 # Make scaling to set image intensities between mn_out and mx_out ...
3b502094e22fe97fadfeb4ff987774385442c52e
3,601,955
import pkg_resources def walk(module_name, dirname, topdown=True): """ Copy of :func:`os.walk`, please refer to its doc. The only difference is that we walk in a package_resource instead of a plain directory. :type module_name: basestring :param module_name: module to search in :type dirname: ...
8a001a4673b9a123f4c4260f2226eff0c360b698
3,601,956
def get_triplet_columns(data: DataFrame) -> DataFrame: """ Remove all columns except (protein, mutation, interactor) triplets. Parameters ---------- data : <DataFrame> The input dataframe whose non-triplet columns to be removed. Returns ------- triplet_data : <DataF...
9749479ea5b1fda2370541d89de33d2d9e018bbc
3,601,957
from typing import Iterable def test_alias() -> None: """Test that columns and indices can be aliased.""" class Schema(pa.SchemaModel): col_2020: Series[int] = pa.Field(alias=2020) idx: Index[int] = pa.Field(alias="_idx", check_name=True) @pa.check(2020) @classmethod ...
c83ecc20002d5e0e85be3ad168705a7adf09ede4
3,601,958
def p_methods(data, pv_index=0, alpha = 0.05): """ A summary dataframe with columns for the p-values, adjusted p-values for both Bonferroni and Benjamini-Hochberg (BH), adjusted significancelevel for Bonferroni and the critical value for BH Args: - data: dataframe or array containing at least a ...
2d7a9d6d0ff983f6fbc6811f96663b35f450754b
3,601,959
def create_client_entities(count, id_or_name=False): """Creates a list of client-style entities with random keys.""" return [ entity.to_client_entity() for entity in create_entities(count, id_or_name=id_or_name) ]
a38c0b5c16746c264fd26dcc78b90d3b35681555
3,601,960
def load_shapefile(): """ load Local Authorities Upper Tier shape file data. Do some merging and postprocessing to match COVID19 data as best as possible. Example usage of data: shp.lad19nm[shp.lad19nm == 'Wirral'] """ # Load shape file data shapefile = 'DATA/shapefile3/Counties_and_Unit...
969b80649840219bee2408513ac5f6ee845670d3
3,601,961
def _fn(request: Request) -> bool: """For testing purposes.""" return True
e2838f7ba88f7556a3ca786801d10ddab2d52b79
3,601,962
def _query_parser(): """ Construct a parser for the subset of SQL that is applicable to the export API """ whitespace = parsy.regex(r"\s*") lower = lambda x: x.lower() string = lambda x: parsy.string(x, lower) def lexeme(value): """A string or parser surrounded by whitespace""" ...
fc04ed9eb9bb5dc0ae55d2d5504ce83f52f74956
3,601,963
def get_flat_params(parameter_groups): """ :param parameter_groups: :return: List of parameters pulled out of parameter groups """ parameter_list = [] for parameter_group in parameter_groups: parameter_list += parameter_group['params'] return parameter_list
ef11030018341635594d07f56a23dd9aa3c1244e
3,601,964
def game_over(state): """ Return whether the game is over and if it is, indicate the winner, and other information if needed :param state: the state to evaluate :return: a tuple of [game_is_over, winner, metadata] """ for victory_condition in victory: if __is_victory(state.player1_st...
a2845e72476275b7c0680eae647d17bfd0fab852
3,601,965
def l_roots(n, mu=False): """Gauss-Laguerre quadrature Computes the sample points and weights for Gauss-Laguerre quadrature. The sample points are the roots of the `n`th degree Laguerre polynomial, :math:`L_n(x)`. These sample points and weights correctly integrate polynomials of degree :math:`2*n...
f71efc3a4a62b412b2b04470f777260cfbbabc20
3,601,966
def format_job_status(job): """ Convert job status dictionary into the format that cliff need for display. :param job: type dic :return: formatted result used for display """ start = job['begin_time'] end = job['end_time'] success, start = utc_to_local_time(start) success, end = utc_...
d99aacb62de00887dafc00e8f7ea772d3b01a799
3,601,967
def read_name_hash(read_name): """Takes a read name from an input bam and shortens & obfuscates it""" return str(abs(hash(read_name)) % 10**9)
bc1e048925f0a0e710481656f0b90e4c290c2341
3,601,968
import logging import sys import os def init_state(): """ Initializes logging and creates the webserver. """ global app logging.basicConfig(stream=sys.stdout, level=logging.INFO) app = FastAPI( docs_url="/api/docs", redoc_url="/api/redoc", ) # Add Origins for COR...
c67047865d9da46f4a2cea27a5ef18bf448cb8ea
3,601,969
def _get_updated_parsed(job_item): """ :param job_item: :return: """ return job_item.published.timetuple()
a1377d3adcbae990727abed8ecdabfb9fb2d610b
3,601,970
def top_split(dog, race): """ Retorna o melhor split do galgo """ history = History.objects.filter(dog=dog, race__track__track_id=race.track.track_id, distance=race.distance, grade__in=filter_grade(race.grade), split__gt=0).values_list('split', flat=True) if history: ...
1c3a91011251bf0cee066169067848376439b2e9
3,601,971
def prompt_bet(min_bet, max_bet): """ Prompt for an integer bet amount until one within bounds is given. """ print() print('How much do you want to bet?') user_bet = prompt_number( min_bet, max_bet, 'Please input a bet within range 5-500.' ) return user_bet
891805678c1da475d878c0cf60add0e64f0184c4
3,601,972
import argparse def getArguments(): """Arguments for script.""" parser = argparse.ArgumentParser() parser.add_argument("--name", default="sensorapp", help="name of the application") parser.add_argument("--app-port", type=int, default="8081", help="port to run application server") parser.add_argument("--hos...
3e9ce78bcf459a5f956b988265d0cc39834d5e41
3,601,973
def parse_performance_criterion(config, shared, logger): """Parse the CLI argument that determines the performance criterion to be met for a run to continue. Function parses argument ``--during_acc_criterion``. Args: config (argparse.Namespace): Command-line arguments. shared (argparse...
c19a70f85fee4c3d50d92b20a84000227fbbad08
3,601,974
def pressure_from_altitude(y): """ Calculate standard atmospheric pressure based on an altitude in m. The basic formula can be found many places. For instance, Munson, Young, and Okiishi, 'Fundamentals of Fluid Mechanics', p. 51. Enter: y: altitude in m. Exit: p: pressure in N/m/m. """ ...
b8f7d42b28d3448ac1a0f62079a0ae4ed672f9e9
3,601,975
import torch def classification_error( probabilities, targets, length=None, allowed_len_diff=3, reduction="mean" ): """Computes the classification error at frame or batch level. Arguments --------- probabilities : torch.Tensor The posterior probabilities of shape [batch, prob] or ...
af02f61b253466ab256a5eb76967c9916a6bfc9d
3,601,976
from lfs.catalog.models import Product, ProductPropertyValue def get_filtered_products_for_category(category, filters, price_filter, sorting, manufacturers_filter=None): """Returns products for given categories and current filters sorted by current sorting. """ if filters: if category.show_all...
a17418cc0d168878172b23a4f1f5ae74b98f3bde
3,601,977
import re import os def post_project(project): """ summary: create new project parameters: - name: project in: path required: true description: name of project schema: type: string """ # check string # must be lowercase only # consisting of a...
d243e831f96cd7558b8ffa6d82fc2a174bf46b5d
3,601,978
def tf_ensure_flat(x, ndims=2): """ Makes sure a tensor is flattened ONLY IF NEEDED, i.e. it has more dimensions than required ones. :param x: A tensor to be flattenned :param ndims: The number of dimensions to be left in the output tensor. :return: The flatened tensor, or the original, if it is fin...
18d8a37b070cdfb26d650c0498325a887c185163
3,601,979
def validate_crc16(data): """ Validate that the CRC of the contents of buffer is the residual OK value. The input is a bytestring. """ return crc16(data) == _CRC_OK_RESIDUAL
004247797a3337a3426dec2c3b6b48cda90404e0
3,601,980
from datetime import datetime def get_ahead_one_hour(datetime_str): """ 获得提前一小时的时间字符串和时间戳 :return: """ datetime_obj = datetime.datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S') datetime_obj_one_hour_ahead = datetime_obj + datetime.timedelta(hours=-1) return datetime_obj_one_hour_ahead.s...
12f334da38d36df927a3f26a08ca20a5183cb615
3,601,981
def fitting_tsne(X, n_comp, perp, metric='euclidean'): """Fit t-SNE""" tsne = TSNE(n_components=n_comp, perplexity=perp, metric=metric) X_tsne = tsne.fit_transform(X) return X_tsne
8ac465db99c48972d408ddfa32148a96258741cc
3,601,982
import pathlib def parse_image_args(args_iter, manual_binds): """Parse arguments to the container image, rebasing binds as necessary to make paths available inside the container. Typically used as the second pass of a CLI application (following parse_container_args, see e.g., bindit.docker.docker). A...
fda99eb9fa36b8250f1024d5080a97cd6941c0bd
3,601,983
def is_box_outside_rect(poly, rect): """ poly 是否在rect外, true 为outside """ poly = np.array(poly) xl, yt, xr, yd = rect if len(poly.shape) == 2: if poly[:, 0].max() <= xl or poly[:, 0].min() >= xr: return True if poly[:, 1].max() <= yt or poly[:, 1].min() >= yd: ...
11549b9cdf70871ded24cbf67b69de8edd3e57ae
3,601,984
import urllib def collect_request_attributes(scope): """Collects HTTP request attributes from the ASGI scope and returns a dictionary to be used as span creation attributes.""" server_host, port, http_url = get_host_port_url_tuple(scope) query_string = scope.get("query_string") if query_string and...
546c079779bfb5895e28f21f575ad91017289e85
3,601,985
def spatial_atleast3d(string_input): """ This function parses a 3-element tuple from a string input. The input will be padded with ones, if the length is less than 3. """ output_tuple = int_array(string_input) if len(output_tuple) < 3: # will pad the array with single dimensions ...
0d276d4c7eff5c642319f73eb889842fda3eb4d3
3,601,986
def email_validation_reset(request): """ Resend the validation email """ if request.user.is_authenticated(): try: resend = EmailValidation.objects.get(user=request.user).resend() response = "done" except EmailValidation.DoesNotExist: response = "faile...
a3734fe7a1a7a3a1c029064c2ac6f839742f1a3c
3,601,987
import os def repo_dir(repo, *path, mkdir=False): """Same as repo_path, but mkdir *path if absent if mkdir""" path = repo_path(repo, *path) if os.path.exists(path): if (os.path.isdir(path)): return path else: raise Exception("Not a directory %s" % path) if mkdi...
67887cb3724a42f93f7aa73255789f90697d36b0
3,601,988
from typing import List from typing import Dict from typing import Any def generate_tmap_config( filename: str, layer_data: List[FullLayerData], internal_shapes: bool = False ) -> Dict[str, Any]: """Generates a dict containing the tissumaps cfg of the napari layers to be saved. Parameters ---------- ...
3681ccd954c2a6870224233ecca47dbd9bd63778
3,601,989
def spacetime_integrated_kernel_3(a: float, b: float, c: float, d: float, h: float, k: float) -> float: """ Returns kernel integrated in time over [a,b] x [c, d], and in space over [0,h] x [0,k] """ assert a < b and c < d and h > 0 f_bd = fint_3(b, d, h, k) f_bc...
fc234f6c12a1b6133b17c38057fe334e360621ab
3,601,990
import array def hybrid(x, llim=None, ulim=None, period=None, return_all=False): """ Return hybrid statistic and corresponding periods for signal x Arguments: - return_all: whether to return the hybrid, ipdft, autocorr statistics as a numpy array, or just the hybrid statistic ...
04b6f83d74579af379a68c8af6e0affe236049c6
3,601,991
def read_pedigree(pedigree_file=None, keepInverse=True): """ Reading the pedigree file and dumping it in a ordered dictionary. Generates a dictionary with individual: [parent1, parent2] """ if not pedigree_file: pedigree_file = PEDIGREE_FILE pedigree = None with open(pedigree_file, '...
458dd8afc6924920890f15292e91d4ded4011dbc
3,601,992
import pandas as pd def _lsa_events_converter(events_file): """Make a model where each trial has its own regressor using least squares all (LSA) Parameters ---------- events_file : str File that contains all events from the bold run Yields ------ events : DataFrame A ...
4cc216bdf01f67dbefbd31005f0398cd217aa8a5
3,601,993
import torch from typing import OrderedDict def load_model(filepath = '../data/checkpoint.pth'): """ Function loads the model from checkpoint. INPUT: filepath - path for the saved model OUTPUT: model - loaded pytorch model """ print("Loading model from {} \n".format(filepath...
6bce5b826d4802a1ea0592a5a4446b9e0fb6ad6c
3,601,994
from typing import Union from typing import List def model_outputs(model: Union[str, ModelProto]) -> List: """ Get the output from an ONNX model :param model: the loaded model or a file path to the ONNX model to get the model outputs for :return: the output from the model """ model = ...
b3fc7928ad8f0f5f121f8411ccb077bcbecb35bc
3,601,995
def get_acc(preds, labels, threshold=0.5): """Gets the accuracy score of the predictions Parameters ---------- preds : array_like Class predictions for each sample labels : array_like Binary class labels of each sample threshold : float The decision threshold Return...
635d4dd4aa3a51825013b3adb8ecf15647fc8503
3,601,996
def is_untranslated_paragraph(service_name: str, line: str, source_lang: object) -> bool: """ Call the language detect function of each translate API :rtype: bool """ if service_name == const.TRANSLATION_SERVICE_GOOGLE_V2: return is_detected(line, source_lang) else: end_words = i...
c8cd20fbf22d1d20bd78a1616ad6a904b6c495ec
3,601,997
import os import inspect def current(): """ returns the current directory path """ current = os.path.abspath(inspect.getfile(inspect.currentframe())) head, tail = os.path.split(current) return head
da05645bd0c4868541d3612c4da8f6cb2702bd5f
3,601,998
from typing import Union from datetime import datetime from typing import Optional from typing import Callable from typing import Dict from typing import Any def daily_partitioned_config( start_date: Union[datetime, str], timezone: Optional[str] = None, fmt: Optional[str] = None, ) -> Callable[[Callable[[...
68730dd7f9243e1aff88d8f37b3e4b8a75dd3de7
3,601,999