content
stringlengths
22
815k
id
int64
0
4.91M
def write_linux_hash_testvec(f, vec): """Format a hash test vector for Linux's crypto tests.""" write_linux_testvec_hexfield(f, "key", vec['input']['key']) write_linux_testvec_field(f, "ksize", len(vec['input']['key'])) write_linux_testvec_hexfield(f, "plaintext", vec['input']['message']) length = l...
37,400
def get_query_string_from_process_type_string(process_type_string: str) -> str: # pylint: disable=invalid-name """ Take the process type string of a Node and create the queryable type string. :param process_type_string: the process type string :type process_type_string: str :return: string that c...
37,401
def test_key_to_fuzzer_and_benchmark(): """Tests that key_to_fuzzer_and_benchmark returns the correct result.""" assert (coverage_data_utils.key_to_fuzzer_and_benchmark('afl libpng-1.2.56') == (FUZZER, BENCHMARK))
37,402
def get_column(fn): """Get column from Cellomics filename. Parameters ---------- fn : string A filename from the Cellomics high-content screening system. Returns ------- column : string The channel of the filename. Examples -------- >>> fn = 'MFGTMP_14020618000...
37,403
def json_to_csv(input_json, output_file): """Reads a JSON file, generated by the VGG Image Annotator, and generates a single CSV file""" with open(input_json) as f: images = json.load(f) annotations = [] for entry in images: filename = images[entry]['filename'] for region in im...
37,404
def add_tables(): """ Generates tables in postgres database according to SQLAlchemy model when this script is invoked directly via terminal. """ return database.Base.metadata.create_all(bind=database.engine)
37,405
def isloggedin(userdir): """If user has sent us an in date, valid cookie then return updated cookie header, otherwise return False.""" try: rawcookie = os.environ['HTTP_COOKIE'] except KeyError: return False thecookie = SimpleCookie(rawcookie) try: cookiestring = thecooki...
37,406
def enable(name, start=False, **kwargs): """ Start service ``name`` at boot. Returns ``True`` if operation is successful name the service's name start : False If ``True``, start the service once enabled. CLI Example: .. code-block:: bash salt '*' service.enable <...
37,407
def docs(runtime, environment): """ Build the html documentation. """ parameters = get_parameters(runtime, environment) commands = [ "edm run -e {environment} -- sphinx-build -b html " "-d build/doctrees source build/html", ] with do_in_existingdir(os.path.join(os.getcwd(), 'doc...
37,408
def label_vertices(ast, vi, vertices, var_v): """Label each node in the AST with a unique vertex id vi : vertex id counter vertices : list of all vertices (modified in place) """ def inner(ast): nonlocal vi if type(ast) != dict: if type(ast) == list: # pr...
37,409
def standardize_batch(inputs, is_training, decay=0.999, epsilon=1e-3, data_format="NHWC", use_moving_averages=True, use_cross_replica_mean=None): """Adds TPU-enabled batch normalization ...
37,410
def process_misc_info_txt(framework_target_files_temp_dir, vendor_target_files_temp_dir, output_target_files_temp_dir, framework_misc_info_keys): """Performs special processing for META/misc_info.txt. This function merges the contents of...
37,411
def test_relation_isattrs_return_right_bools(relation, m2m, multi, direct): """ All "is" attributes on Relation objects should return the correct truth values for the type of relation that is represented. """ assert relation.is_m2m == m2m assert relation.is_multi == multi assert relation.is_...
37,412
def dict_to_hierarchy(tree, create_nodes=True, node_type="transform"): """Parent DAG nodes based on a dictionnary. Args: tree (dict): Dictionary representing the hierarchy. node_type (str): Type of node to be created if the children doesn't exist """ if tree: for parent, child_t...
37,413
def bias_variable(shape): """Create a bias variable with appropriate initialization.""" #initial = tf.constant(0.1, shape=shape) initial = tf.constant(0.0, shape=shape) return tf.Variable(initial)
37,414
def getPortNumber(): """ Check the command-line arguments for the port number. The program can exit in this method if Too few arguments are passed into the program Too many arguments are passed into the program The port number argument is non-numeric The port number argument is less than 0 since port number...
37,415
def object_gatekeeper(obj, is_auth, ignore_standalone=False): """ It's OK to use available_to_public here because the underlying logic is identical. """ if not obj: return False if is_auth: return True else: try: return obj.available_to_public except: ...
37,416
def l1_l2_regularizer(scale_l1=1.0, scale_l2=1.0, scope=None): """Returns a function that can be used to apply L1 L2 regularizations. Args: scale_l1: A scalar multiplier `Tensor` for L1 regularization. scale_l2: A scalar multiplier `Tensor` for L2 regularization. scope: An optional scope name. Retur...
37,417
def test013_ip_range(): """ to run: kosmos 'j.data.types.test(name="iprange")' """ ipv4 = j.data.types.get("iprange", default="192.168.0.0/28") assert ipv4.default_get() == "192.168.0.0/28" assert ipv4.check("192.168.23.255/28") is True assert ipv4.check("192.168.23.300/28") is False ...
37,418
def _create_hive_cursor(): """ Initializes a hive connection and returns a cursor to it :return: hive cursor """ _print_info('Initializing hive cursor.') return _initialize_hive_connection()
37,419
def load_pretrained_wts(featurizer_params, ExtendedEncoder_params): """Merging pre-trained and initialised parameters""" param_idx = config['restart_from']//config['total_steps'] if os.path.isfile(config['params_dir']+f'params_{param_idx}'): with open(config['params_dir']+f'params_{param_idx}',...
37,420
def to_vector_single(text, embeddings, maxlen=300): """ Given a string, tokenize it, then convert it to a sequence of word embedding vectors with the provided embeddings, introducing <PAD> and <UNK> padding token vector when appropriate """ tokens = tokenizeAndFilterSimple(clean_text(text)) ...
37,421
def eval_tensor_density( tens: tf_compat.Tensor, sess: tf_compat.Session = None ) -> float: """ Get the density (fraction of non zero values) in a tensor :param tens: the tensor to get the density for :param sess: the session to use for evaluating the tensor, if not supplied will use the de...
37,422
def get(key, default): """Get a config bloc from the YAML config file. Args: default (dict): The default bloc if the key is not available Returns: dict: The config bloc (or the default one) """ if not key.lower() in _YAML_DICT or isinstance(_YAML_DICT[key.lower()], collections.Mapp...
37,423
def adaptsim(f, a, b, eps=1e-8, max_iter=10000): """自适应 Simpson 求积 P.S. 这个函数名来自 Gander, W. and W. Gautschi, “Adaptive Quadrature – Revisited,” BIT, Vol. 40, 2000, pp. 84-101. 该文档可以在 https://people.inf.ethz.ch/gander/ 找到。 但该函数的实现并没有使用此文中的递归方法。 Args: f: 要求积的函数 ...
37,424
def runHmmer(args, list_path, file_path, f): """run prodigal and hmmsearch on chr files""" if not os.path.exists( str(args.data) + '/tmp'): os.makedirs(str(args.data) + '/tmp') # get the sample group head, group = os.path.split(os.path.split(file_path)[0]) basename = os.path.splitext(str(ntpath.basename(str(file...
37,425
def get_next_position(grid): """Returns best next position to send.""" width = len(grid[0]) unprepared = [inspect_around_position(grid, x) for x in range(1, width - 1)] return unprepared.index(max(unprepared)) + 2
37,426
def which_subdir(sha: str) -> Optional[str]: """ Determine which subset (if any) sha is represented in """ fname = sha + '.json' for k, v in subdir_contents.items(): if fname in v: subdir_contents[k].remove(fname) return k subdir_contents[MISSING_FILE].add(fname) retu...
37,427
def smoothedEnsembles(data,lat_bounds,lon_bounds): """ Smoothes all ensembles by taking subsamples """ ### Import modules import numpy as np import sys print('\n------- Beginning of smoothing the ensembles per model -------') ### Save MM newmodels = data.copy() mmean = n...
37,428
def conv7x7_block(in_channels, out_channels, strides=1, padding=3, use_bias=False, use_bn=True, bn_eps=1e-5, activation="relu", data_format="channels_last", *...
37,429
def alpha_to_weights(alpha): """归一化. 最终截面绝对值和为2. """ alpha = alpha - np.nanmean(alpha, axis=1, keepdims=True) mask_pos = (alpha > 0) mask_neg = (alpha < 0) alpha_pos = imposter(alpha) alpha_pos[mask_pos] = alpha[mask_pos] alpha_pos = alpha_pos / np.nansum(alpha_pos, 1, keepdims=True) ...
37,430
def complete_with_fake_data_for_warmup(minimum_n_rows_to_fit, X=None, fv_size=None): """Makes fake data to warmup a partial fit process. If no X is given, will return a random minimum_n_rows_to_fit x fv_size matrix (with values between 0 and 1) If X is given, will repeat the rows in a cycle until the minimu...
37,431
def check_integrity(signify: Dict[str, str], snapshot: Path, url: str) -> bool: """Check the integrity of the snapshot and retry once if failed files. signify -- the signify key and a signify signed file with SHA256 checksums snapshot -- the directory where the snapshot is stored url -- the snapshots'...
37,432
def exp_slow(b, c): """ Returns the value b^c. Property: b^c = b * b^(c-1) Parameter b: the number to raise to a power Precondition: b is a number Parameter c: the exponent Precondition: c is an int >= 0 """ # get in the habit of checking what you can assert type(b) in [floa...
37,433
def recur_gen3(a0,a1,a2,a3,a4,a5): """ homogeneous general third-order linear recurrence generator with fixed coefficients a(0) = a0, a(1) = a1, a(2) = a2, a(n) = a3\*a(n-1) + a4\*a(n-2) + a5\*a(n-3) EXAMPLES:: sage: from sage.combinat.sloane_functions import recur_gen3 sage: ...
37,434
def test_parser_label(): """Labels are correctly recognised""" for command in _parser(["(label1)", "(102)", ]): assert command["instruction"] == "label" assert isinstance(command["label"], str)
37,435
def pick_theme(manual): """ Return theme name based on manual input, prefs file, or default to "plain". """ if manual: return manual pref_init() parser = cp.ConfigParser() parser.read(PREFS_FILE) try: theme = parser.get("theme", "default") except (cp.NoSectionError, c...
37,436
def ip2host(ls_input): """ Parameters : list of a ip addreses ---------- Returns : list of tuples, n=2, consisting of the ip and hostname """ ls_output = [] for ip in ls_input: try: x = socket.gethostbyaddr(ip) ls_output.append((ip, x[0])) except ...
37,437
def process_all_content(file_list: list, text_path: str) -> Tuple[list, list]: """ Analyze the whole content of the project, build and return lists if toc_items and landmarks. INPUTS: file_list: a list of all content files text_path: the path to the contents folder (src/epub/text) OUTPUTS: a tuple containing ...
37,438
def fuel(bot, mask, target, args): """Show the current fuel for Erfurt %%fuel [<city> <value> <type>]... """ """Load configuration""" config = { 'lat': 50.9827792, 'lng': 11.0394426, 'rad': 10 } config.update(bot.config.get(__name__, {})) sort_type = 'all' ...
37,439
def is_executable_binary(file_path): """ Returns true if the file: * is executable * is a binary (i.e not a script) """ if not os.path.isfile(file_path): return False if not os.access(file_path, os.X_OK): return False return is_binary(file_path)
37,440
def findElemArray2D(x, arr2d): """ :param x: a scalar :param arr2d: a 2-dimensional numpy ndarray or matrix Returns a tuple of arrays (rVec, cVec), where the corresponding elements in each are the rows and cols where arr2d[r,c] == x. Returns [] if x not in arr2d. \n Example: \n arr2d =...
37,441
def merge(cluster_sentences): """ Merge multiple lists. """ cluster_sentences = list(itertools.chain(*cluster_sentences)) return cluster_sentences
37,442
def reverse_str(s: str) -> str: """Reverse a given string""" # Python strings are immutable s = list(s) s_len = len(s) # Using the extra idx as a temp space in list s.append(None) for idx in range(s_len // 2): s[s_len] = s[idx] s[idx] = s[s_len - idx - 1] s[s_len - id...
37,443
def readme(): """Get text from the README.rst""" with open('README.rst') as f: return f.read()
37,444
def exact_account(source_account_id): """ Get the BU id, OU id by the account id in dynamodb table. """ try: response = dynamodb_table.get_item(Key={'AccountId': source_account_id}) except Exception as e: failure_notify("Unable to query account id {0}, detailed exception {1}".format(...
37,445
def test_catalog_to_markers_xy(): """Test convert.catalog_to_markers using xy coords""" helpers.disbale_tqdm() helpers.setup(with_data=True) out_dir = helpers.TEST_PATH wcs_file = os.path.join(out_dir, "test_image.fits") rows_per_col = np.inf catalog_file = os.path.join(out_dir, "test_catal...
37,446
def filter_output(output, regex): """Filter output by defined regex. Output can be either string, list or tuple. Every string is split into list line by line. After that regex is applied to filter only matching lines, which are returned back. :returns: list of matching records """ resu...
37,447
def carteiralistar(request): """ Metódo para retornar o template de listar carteiras """ usuario = request.user try: # Pega o objeto carteira se já existir carteira = CarteiraCriptomoeda.objects.get(usuario=usuario) # Pega a chave da API e o saldo chave_api = carteira...
37,448
def import_cson(ctx, filename, boostnote_json, workspace_id, folder_id): """Import a cson document from old Boostnote """ if workspace_id is None and folder_id is None: print('error: either workspace id or folder id is required', file=sys.stderr) sys.exit(1) if workspace_id is not None and folder_id is not...
37,449
def test_chain_tuner_classification_correct(data_fixture, request): """ Test ChainTuner for chain based on hyperopt library """ data = request.getfixturevalue(data_fixture) train_data, test_data = train_test_data_setup(data=data) # Chains for classification task chain_simple = get_simple_class_chai...
37,450
def scrub(text, stop_chars=DEFAULT_STOP_CHARS, reorder_chars=DEFAULT_REORDER_CHARS): """ Scrub text. Runs the relevant functions in an appropriate order. """ text = reorder_stop_chars(text, stop_chars=stop_chars, reorder_chars=reorder_chars) text = remove_columns(text) text = split_as_one_senten...
37,451
def simulate_evoked_osc(info, fwd, n_trials, freq, label, loc_in_label=None, picks=None, loc_seed=None, snr=None, mu=None, noise_type="white", return_matrix=True, filtering=None, phase_lock=False): """Simulate evoked oscillatory data based on a...
37,452
def token_request(): """ Request a Access Token from Vipps. :return: A Access Token """ headers = config['token_request'] url = base_url + '/accesstoken/get' response = requests.post(url, headers=headers) return response.json()
37,453
async def test_cancel_not_joined_yet(): """ When we cancel the nursery, it hasn't been joined yet. This should cancel it anyway. """ async def cleaner(): await asyncio.sleep(0.2) Scope.get_current().cancel() await asyncio.sleep(10) before = time.time() async with Sc...
37,454
def train(args, train_dataset, model, tokenizer, labels, pad_token_label_id): """ Train the model """ if args.local_rank in [-1, 0]: tb_writer = SummaryWriter() args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) train_sampler = RandomSampler(train_dataset) if args.local_...
37,455
def get_gv(title, model_id, mojo_path): """ Utility function to generate graphviz dot file from h2o MOJO using a subprocess. Args: title: Title for displayed decision tree. model_id: h2o model identifier. mojo_path: Path to saved model MOJO (Java scoring artifact); ...
37,456
def extract_tunneled_layer(tunnel_packet: scapy.layers.l2.Ether, offset: int, protocol: str): """ Extract tunneled layer from packet capture. Args: tunnel_packet (scapy.layers.l2.Ether): the PDU to extract from offset (int): the byte offset of the tunneled protocol in data field of 'packet'...
37,457
def draw_bbox(img, detections, cmap, random_color=True, figsize=(10, 10), show_text=True): """ Draw bounding boxes on the img. :param img: BGR img. :param detections: pandas DataFrame containing detections :param random_color: assign random color for each objects :param cmap: object colormap ...
37,458
def print_total_eval_info(data_span_type2model_str2epoch_res_list, metric_type='micro', span_type='pred_span', model_strs=('DCFEE-O', 'DCFEE-M', 'GreedyDec', 'Doc2EDAG'), target_set='test'): """Print the final pe...
37,459
def build_sentence_representation(s): """ Build representation of a sentence by analyzing predpatt output. Returns a weighted list of lists of terms. """ s = merge_citation_token_lists(s) s = remove_qutation_marks(s) lemmatizer = WordNetLemmatizer() raw_lists = [] rep_lists = [] ...
37,460
def load_qconfig(): """ Attemps to load the Qconfig.py searching the current environment. Returns: module: Qconfig module """ try: modspec = importlib.util.find_spec(_QCONFIG_NAME) if modspec is not None: mod = importlib.util.module_from_spec(modspec) ...
37,461
def scopus_serial_title(journal_title_list, apikey, d_path): """ Scrape the SerialTitle Args: journal_title_list: A list of unique journal titles apikey: the same key used for the search queries d_path: output path for data """ print('************ Now Scraping Scopus for J...
37,462
def create_glucose_previous_day_groups(day_groups: dict) -> dict: """ Create a dictionary of glucose subseries, unique to each day in the parent glucose series. Subseries data of each dictionary item will lag item key (date) by 1 day. Keys will be (unique dates in the parent series) + 1 day. Values ...
37,463
def mean_abs_scaling(series: pd.Series, minimum_scale=1e-6): """Scales a Series by the mean of its absolute value. Returns the scaled Series and the scale itself. """ scale = max(minimum_scale, series.abs().mean()) return series / scale, scale
37,464
def init_dmriprep_wf( anat_only, debug, force_syn, freesurfer, hires, ignore, layout, longitudinal, low_mem, omp_nthreads, output_dir, output_spaces, run_uuid, skull_strip_fixed_seed, skull_strip_template, subject_list, use_syn, work_dir, ): ""...
37,465
def count_total_parameters(): """ Returns total number of trainable parameters in the current tf graph. https://stackoverflow.com/a/38161314/1645784 """ total_parameters = 0 for variable in tf.trainable_variables(): # shape is an array of tf.Dimension shape = variable.get_shape(...
37,466
def create_gradient_rms_plot(sticher_dict: dict[str, GDEFSticher], cutoff_percent=8, moving_average_n=1, x_offset=0, plotter_style: PlotterStyle = None) -> Figure: """ Creates a matplotlib figure, showing a graph of the root meean square of the gradient of the GDEFSticher objects ...
37,467
def disp_img(img_arr): """Display an image from a numpy ndarray (height, width, channels)""" img = Image.fromarray(img_arr) img.show()
37,468
def show_chart(graph: alt.Chart): """Wrapper function to ensure container width.""" st.altair_chart(graph, use_container_width=True)
37,469
def reverse(ls: List[T]) -> List[T]: """ Reverses a list. :param ls: The list to be reversed :return: The reversed list """ for i in range(len(ls) // 2): ls[i], ls[len(ls) - 1 - i] = ls[len(ls) - 1 - i], ls[i] return ls
37,470
def test_post_self_links( app, client_with_login, location, minimal_community, headers ): """Test self links generated after post""" client = client_with_login #Creta a community res = client.post( '/communities', headers=headers, json=minimal_community) assert res.status_code =...
37,471
def test_get_annotations_not_5( test_gb_file, test_accession, coordination_args, monkeypatch ): """Test get_annotations when length of protein data is not 5.""" def mock_get_gb_file(*args, **kwargs): gb_file = test_gb_file return gb_file def mock_get_record(*args, **kwargs): re...
37,472
def increment_with_offset(c: str, increment: int, offset: int) -> str: """ Caesar shift cipher. """ return chr(((ord(c) - offset + increment) % 26) + offset)
37,473
def uploadfiles(): """ function to upload csv to db :return: renders success.html """ # get the uploaded file uploaded_file = request.files['filename'] if uploaded_file.filename != '': csv_to_db(uploaded_file) return render_template('success.html') logging.info("No file u...
37,474
def static_html(route): """ Route in charge of routing users to Pages. :param route: :return: """ page = get_page(route) if page is None: abort(404) else: if page.auth_required and authed() is False: return redirect(url_for("auth.login", next=request.full_path...
37,475
def checkLogExistence(): """Checks to see if the CrashTrakr_Log file exists and creates it if it does not.""" if not os.path.isfile("CrashTrakr_Log.txt"): log_start=["LOG START @ {0}\n".format(str(datetime.datetime.now()))] log_file = open("CrashTrakr_Log.txt", mode="wt", encoding="ut...
37,476
def getCenterFrequency(filterBand): """ Intermediate computation used by the mfcc function. Compute the center frequency (fc) of the specified filter band (l) This where the mel-frequency scaling occurs. Filters are specified so that their center frequencies are equally spaced on the mel scale "...
37,477
def phi_analytic(dist, t, t_0, k, phi_1, phi_2): """ the analytic solution to the Gaussian diffusion problem """ phi = (phi_2 - phi_1)*(t_0/(t + t_0)) * \ numpy.exp(-0.25*dist**2/(k*(t + t_0))) + phi_1 return phi
37,478
def getAll(): """ init """ with open(ipLocationCache, "r", encoding="utf-8") as target: global cache cache = json.load(target)
37,479
def get_home_timeline(count=None, since_id=None, max_id=None, trim_user=None, exclude_replies=None, include_entities=None, tweet_mode=None): """ Returns a collection of the most recent Tweets and retweets posted by the authenticating user and the users they follow. :param coun...
37,480
def get_changed_files(base_commit: str, head_commit: str, subdir: str = '.'): """ Get the files changed by the given range of commits. """ cmd = ['git', 'diff', '--name-only', base_commit, head_commit, '--', subdir] files = subprocess.check_output(cmd) return files.decod...
37,481
def geometric_median(X, eps=1e-5): """ calculate the geometric median as implemented in https://stackoverflow.com/a/30305181 :param X: 2D dataset :param eps: :return: median value from X """ y = np.mean(X, 0) while True: D = cdist(X, [y]) nonzeros = (D != 0)[:, 0] ...
37,482
def cprint(*strings): """ compile all given strings and print them """ print(*map(compile, strings))
37,483
def test_find_pyproject_toml(): """ Automatically find a pyproject.toml within the current current working directory. """ # .parent == tests/, .parent.parent == repo root expected_pyproject_path = Path(__file__).parent.parent / "pyproject.toml" # We want to find the pyproject.toml for THIS pro...
37,484
def distance(bbox, detection): """docstring for distance""" nDetections = detection.shape[0] d = np.zeros(nDetections) D = detection - np.ones([nDetections,1])*bbox for i in xrange(nDetections): d[i] = np.linalg.norm(D[i],1) return d
37,485
def _read_float(line: str, pos: int, line_buffer: TextIO ) -> Tuple[float, str, int]: """Read float value from line. Args: line: line. pos: current position. line_buffer: line buffer for nnet3 file. Returns: float value, line string and current pos...
37,486
def psd_explore( data_folder, channel_index, plot=True, relative=False, reverse=False, export_to_csv=False): """PSD Explore. This assumes use with VR300 for the AD Feedback experiment. data_folder: path to a BciPy data folder with raw data and triggers c...
37,487
def pk_to_p2wpkh_in_p2sh_addr(pk, testnet=False): """ Compressed public key (hex string) -> p2wpkh nested in p2sh address. 'SegWit address.' """ pk_bytes = bytes.fromhex(pk) assert is_compressed_pk(pk_bytes), \ "Only compressed public keys are compatible with p2sh-p2wpkh addresses. See BIP49...
37,488
def remove_imaginary(pauli_sums): """ Remove the imaginary component of each term in a Pauli sum :param PauliSum pauli_sums: The Pauli sum to process. :return: a purely hermitian Pauli sum. :rtype: PauliSum """ if not isinstance(pauli_sums, PauliSum): raise TypeError("not a pauli su...
37,489
def test_post_method_not_allowed_on_subscribers_api(flask_app): """Test Depot not known yet. Verify that post method is not allowed on IMEI-Pairings API. """ rv = flask_app.post(url_for('v2.imei_get_subscribers_api', imei='64220297727231')) assert rv.status_code == 405 assert b'The method is no...
37,490
def log_sigmoid_deprecated(z): """ Calculate the log of sigmod, avoiding overflow underflow """ if abs(z) < 30: return np.log(sigmoid(z)) else: if z > 0: return -np.exp(-z) else: return z
37,491
def roty(t): """Rotation about the y-axis.""" c = np.cos(t) s = np.sin(t) return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
37,492
def ranks_to_metrics_dict(ranks): """Calculates metrics, returns metrics as a dict.""" mean_rank = np.mean(ranks) mean_reciprocal_rank = np.mean(1. / ranks) hits_at = {} for k in (1, 3, 10): hits_at[k] = np.mean(ranks <= k)*100 return { 'MR': mean_rank, 'MRR': mean_reciprocal_rank, 'hi...
37,493
def bias_correction(input_data, output_filename='', mask_filename='', method="ants", command="/home/abeers/Software/ANTS/ANTs.2.1.0.Debian-Ubuntu_X64/N4BiasFieldCorrection", temp_dir='./'): """ A catch-all function for motion correction. Will perform motion correction on an input volume depending on the 'm...
37,494
def execute_sql( connection: psycopg2.extensions.connection, sql_query: str, data: Union[dict, tuple], commit=True, ) -> None: """ Execute and commit PostgreSQL query Parameters ---------- connection : psycopg2.extensions.connection _description_ sql_query : str ...
37,495
def randperm2d(H, W, number, population=None, mask=None): """randperm 2d function genarates diffrent random interges in range [start, end) Parameters ---------- H : {integer} height W : {integer} width number : {integer} random numbers population : {list or num...
37,496
def get_engine(db_credentials): """ Get SQLalchemy engine using credentials. Input: db: database name user: Username host: Hostname of the database server port: Port number passwd: Password for the database """ url = 'postgresql://{user}:{passwd}@{host}:{port}/{db}'.format( ...
37,497
def numpy_to_vtkIdTypeArray(num_array, deep=0): """ Notes ----- This was pulled from VTK and modified to eliminate numpy 1.14 warnings. VTK uses a BSD license, so it's OK to do that. """ isize = vtk.vtkIdTypeArray().GetDataTypeSize() dtype = num_array.dtype if isize == 4: if...
37,498
def denormalize_ged(g1, g2, nged): """ Converts normalized ged into ged. """ return round(nged * (g1.num_nodes + g2.num_nodes) / 2)
37,499