sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
ba93e4ee3753dd87574998e4a14f2ace97e172201f5c13bc2e79a0d2d33cdbe5
Python
1,166
33
import zipfile import os import subprocess import time import zenodo_get def unzip_file(zip_file_path, extracted_folder_path): # Open the zip file with zipfile.ZipFile(zip_file_path, 'r') as zip_ref: # Extract each file one by one for file_info in zip_ref.infolist(): zip_ref.extract...
0adc952fffcb2b4f3a413e273f918eba93355f2df2cdd453f2456d92db0cada1
Python
1,168
44
import plotly.plotly as py import plotly.figure_factory as ff import plotly.graph_objs as go data = [['', 'Emma', 'Isabella', 'Ava', 'Olivia', 'Sophia', 'row-sum'], ['Emma', 16, 3, 28, 0, 18, 65], ['Isabella', 18, 0, 12, 5, 29, 64], ['Ava', 9, 11, 17, 27, 0, 64], ['Olivia', 19, 0, 31, 1...
3e256e3069a7d4d9dc1aacaf969b9d26149e91e73d6fc2717f90cea488a3e615
Python
1,168
38
import pandas as pd import numpy as np def load_database(): # set up to run the R code try: import rpy2.robjects as robjects from rpy2.robjects.packages import importr import anndata2ri anndata2ri.activate() robjects = robjects importr("CellChat") except I...
920d5efb80e861b85396e55ce28284ae76c5f6521b5bc325d209d52c875828ac
Python
1,168
27
import os import sys import pandas as pd from model.Ouroboros import Ouroboros from utils.chem import prepare if __name__ == "__main__": model_name = sys.argv[1] smiles_col = sys.argv[2] extrnal_data = pd.read_csv(sys.argv[3]) job_name = f'{os.path.splitext(os.path.basename(sys.argv[3]))[0]}_{os.path.b...
a5ba8ab965f9be66300a66259689b978302d1038b63ab811dbd15aea5feeaac6
Python
1,168
28
from typing import Union, Tuple, Callable import numpy as np RandomScalar = Union[int, float, Tuple[float, float], Callable[..., Union[int, float]]] def sample_scalar(scalar_type: RandomScalar, *args, **kwargs): if isinstance(scalar_type, (int, float)): return scalar_type elif isinstance(scalar_type...
ec20b0f99499dca9095e7eee9d85f0e1d33d8b20a41d60d9d40158a2787782e8
Python
1,168
34
# -*- coding: utf-8 -*- """ Temporal correction This scripts performs slice timing correction and temporal regridding on a nifti time series. The script needs an installation of afni. """ # local inputs from fmri_tools.preprocessing.slice_timing_correction import slice_timing_correction # input file_in = [ "/da...
30452e1e68a2b81645dd5804d1ee19133184eab4e40e4b6e137bb4395395e2aa
Python
1,169
36
""" Create a cube mesh with perserved sharp edges in a plane """ # TODO USE POLYLINES import SVMTK as svm from pathlib import Path if __name__ == "__main__": print("Start ",__file__) outdir = Path("results") outdir.mkdir(exist_ok=True) surf = svm.Surface() # Center coordinates x,y,z = 0,0,0 ...
6b52d1c5511e6f187a92d0628eda30ea7444fc9f59e68df4f59b93a8e55dea2a
Python
1,169
49
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse USAGE = '''usage: %(prog)s [options] arg1 arg2''' def get_args(): """TODO: Docstring for get_args. :returns: TODO """ parser = argparse.ArgumentParser(usage=USAGE) parser.add_argument('-i', action='store', default='', required=Tru...
4ec2fb90d57ad007a4c4ef0a3eaf7ea304912478165e62a5da43bae945648a5d
Python
1,170
44
"""Calculate summary statistics. """ from sys import argv if len(argv) != 3: print("Please pass the number of states and run id, e.g. python 5_calc_summary_stats.py 8 1") exit() n_states = int(argv[1]) run = int(argv[2]) #%% Import packages print("Importing packages") import os import pickle import numpy a...
7820679cb0371f021ddc61a7d05901d447a76e56f2ed4305cf9efb5f91468f87
Python
1,170
37
"""Top-level Pydantic configuration for a finetuning run.""" import os from pydantic import BaseModel, Field, field_validator from .data_split_configuration import DataSplitConfiguration from .dataset_configuration import FastSurferDatasetConfiguration from .sfcn_configuration import SFCNConfiguration from .target_c...
e876fef4da371030e203671c91178742cdc24a691c96b244724ca70051f13539
Python
1,170
39
import numpy as np import torch def torch_detrend(x: torch.Tensor) -> torch.Tensor: """ Detrends a tensor along the last axis using a linear fit. :param x: Array to detrend :returns: Detrended array """ m = x.mean(dim=-1, keepdim=True) samples = torch.linspace(-1, 1, x.shape[-1], device=x...
02fa0e8053587934a39c0c1e5d5c42052441f7e3cef924f3c11352070e5443af
Python
1,171
36
"""Test QtWinExtras.""" import sys import pytest from qtpy import PYQT6, PYSIDE2, PYSIDE6 from tests.utils import using_conda @pytest.mark.skipif( PYQT6 or PYSIDE6, reason="Not available on Qt6-based bindings", ) @pytest.mark.skipif( sys.platform != "win32" or using_conda(), reason="Only available ...
7020268b35bf4181c26f33c6ee143010d15c74f80a356a2835f6df143ccb31c4
Python
1,171
34
from setuptools import setup, find_packages with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() with open("requirements.txt") as f: requirements = [line.strip() for line in f if line.strip() and not line.startswith("#")] setup( name="avpenet", version="1.0.0", author...
82d3771fb6d57d03441d89be78f0e5af590868001be8aca0a45299971434fbe5
Python
1,171
36
from collections import Counter import numpy as np from probeinterface import read_spikeglx from probeinterface.neuropixels_tools import build_neuropixels_probe def test_spikeglx_reader_is_available_from_public_api() -> None: assert callable(read_spikeglx) def test_np2013_catalogue_geometry_matches_four_shank_...
8f81427e8fb6a22accb120192010069c9275bd4dfebe4991c4cd6e91b818b5fc
Python
1,172
30
"""Cooperative cancellation for pipeline runs. The pipeline is long-running (spike detection + probabilistic thresholding can take minutes). To let the GUI's Stop button actually interrupt a run, each step periodically calls ``check_cancel(should_cancel)`` — typically once per recording — which raises :class:`Pipeline...
fb39b6629b89b3fe16c22c34761154b197de9803107988668043e7f0b91d4c58
Python
1,172
50
# The Python wrapper generated using pybind11 is a compiled dynamic library, # with a name like _arbor.cpython-38-x86_64-linux-gnu.so # # The library will be installed in the same path as this file, which will imports # the compiled part of the wrapper from the _arbor namespace. from ._arbor import * # noqa: F403 #...
736c9879f7f753c45cd9bad2bbe34fada5370ebe1ae5f13ef268398b67a0547d
Python
1,173
29
import matplotlib.pyplot as plt def plot_3d_z_indices(vol, idx_list, transpose=True, num_rows=1, num_cols=1, label_loc_x=5, label_loc_y=5, im_origin = "lower", figsize=(18,16)): """Plot z-index slices of a 3d volume as subplots""" vol = vol.sq...
91fbfd7a82f54eb94a83827d59259bd670870226f9285009eefb0f19eaf4b5f4
Python
1,173
45
from setuptools import setup, find_packages import versioneer author = 'David S. Fischer, Florian R. Hölzlwimmer' author_email='david.fischer@helmholtz-muenchen.de, diffxpy@frhoelzlwimmer.de' description="Fast and scalable differential expression analysis on single-cell RNA-seq data" with open("README.rst", "r") as f...
b597db3636bc36ccf0b9f0fe98a6707a9583ea4f8f9f163391d27454e458da7b
Python
1,173
45
"""Module for logger.""" import logging import os import sys def get(name: str) -> logging.Logger: """ Configure the logger with formatter and handlers. The logger should be used as: .. code-block:: python from deepreg import log logger = log.get(__name__) The log level depend...
6b189d849e4fa5993ae7f7e8e826e973c924290f0150f3b0de2ee8f2f65b667d
Python
1,174
32
import torch from .base_reducer import BaseReducer class DivisorReducer(BaseReducer): def unpack_loss_info(self, loss_info): losses, loss_indices, reduction_type, kwargs = super().unpack_loss_info( loss_info ) if reduction_type != "already_reduced": kwargs = {"divi...
9d477599b3b0cfa123cba299856522e7baf8a093b4b9f91701f316051570d285
Python
1,174
30
import torch import torch.nn as nn import torch.nn.functional as F from .efficientnet3d import EfficientNet3DB0 class sTSCnetDual(nn.Module): """ eTSC-Net (sTSCnet_dual): - Dual input (T2W and FLAIR) - Two EfficientNet3D-B0 feature extractors - Trainable fusion weights - Final classi...
38ac4b5d5021613716ab3494feacb24d29d1130824351efbf04c7d7d67671c29
Python
1,175
54
"""Dual estimation of observation model parameters. """ from sys import argv if len(argv) != 3: print("Please pass the number of states and run id, e.g. python 4_dual_estimation.py 8 1") exit() n_states = int(argv[1]) run = int(argv[2]) #%% Import packages print("Importing packages") import os import pickl...
5c3728012eaa588cb5da0e181fe2a1c85c01f619f039a6710bfef39555cfa5d8
Python
1,175
36
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from django.db.models.signals import post_save from django.dispatch import receiver from cvat.apps.engine.models import Project, Task from cvat.apps.quality_control.models import ( QualitySettings, ensure_base_quality_requirements, ) def _...
d3acd0702a691dad33386c492dab785bd5a44c9d2c3f2f76d5657e3fc958548f
Python
1,176
38
# -*- coding: utf-8 -*- """Tools for smoothing 3D nifti data.""" from pathlib import Path import numpy as np import nibabel as nb from dipy.denoise.nlmeans import nlmeans from dipy.denoise.noise_estimate import estimate_sigma __all__ = ["nlm"] def nlm(file_in, file_out, n=64, scale=1.0): """Apply edge-preservin...
4d841dac9099c9f779dd9bdd418359f09b41a51b854d56343fc4842599a41392
Python
1,178
54
#!/usr/bin/env python """ Remove any blocks from a maf that overlap any of a set of intervals. usage: %prog interval files... < maf """ import sys import bx.align.maf from bx import intervals from bx.cookbook import doc_optparse def __main__(): options, args = doc_optparse.parse(__doc__) try: ass...
ff5c08e10e45167cbb02c89bfb4a663c6d2bfcfd927d090fb8afe90e4222af95
Python
1,178
31
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from django.core.management.base import BaseCommand, CommandError from rest_framework.exceptions import ValidationError from cvat.apps.engine.user_deletion import delete_user_with_cleanup from cvat.apps.iam.models import User class Command(BaseCom...
8ef0718491363490f54e9fa35b5befbd7d424eabfd006494c7b4b32848c57005
Python
1,179
41
import torch import torchio import numpy as np from torchio.transforms import Transform class NormalizeXvals(Transform): def __init__(self, normalization_factor, **kwargs): self.normalization_factor = normalization_factor super().__init__(**kwargs) def apply_transform(self, subject): ...
519703d7c8134787e872555235426c8670df583364b9aa1dc1168e12aff4a9ab
Python
1,180
31
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['connectivity.zip']) tmp_dir = tempfile...
9a30420a88330fc6daa7af782782c16445e4165411c609ee842412293b3ae3b5
Python
1,180
46
#!/usr/bin/env python """ Test HAL error handling. """ import os import pytestqt import sys from PyQt5 import QtCore, QtGui, QtWidgets import storm_analysis.sa_library.datareader as datareader import storm_control.hal4000.hal4000 as hal4000 import storm_control.sc_library.hdebug as hdebug import storm_control.sc_lib...
a0ea959ed8691fece73bd4728a4b77c1c832466d7c5deccf20a152f7d8fe0a52
Python
1,180
53
from pathlib import Path import nibabel as nib def get_full_case_id(cid): try: cid = int(cid) case_id = "case_{:05d}".format(cid) except ValueError: case_id = cid return case_id def get_case_path(cid): # Resolve location where data should be living data_path = Path(__fi...
1147c6832130134d8751b70be782bdcec1520552378508688762e8350170e040
Python
1,181
39
import numpy as np from PIL import Image from scipy.ndimage import gaussian_filter from skimage import morphology from brainways.utils.image import convert_to_uint8 class PreProcess: def __init__(self): self.remove_outer_speckles = RemoveOuterSpeckles() self.pseudo_flatfield = PseudoFlatField() ...
e4b0eae20dde040501a69181b7ccfca2a8571a1fcef0d0fec146e55e7373bfbd
Python
1,181
31
import sys import subprocess from glob import glob import os import yaml lick_exptypes = ['Detection']#'Detection',,'Association' --> association sucks, ditch it! script1 = 'preprocessing/lick_extraction/run_licktrace_icadet.py' scripts = [script1]#script1, pathpath = 'PATHS/artifact_paths.yml' with open(pathpath, 'r...
f92250721afd37fbb7d7d08a62aa292471b1335915bb1256aa1ea03b94caab86
Python
1,181
37
import os import subprocess from dataclasses import dataclass @dataclass(frozen=True) class ReadsData: dir_path: str fwd: bool = True rev: bool = False def run_cmd(command: list): os.system(" ".join(command)) def qiime2_version(): o, e = run_cmd(["conda", "env", "list"]) qi...
6827538db3950cc518786d44735c452120bc36df595449656db05165ef83f825
Python
1,183
40
import yaml from pathlib import Path import os def get_project_root(): current_dir = Path(__file__).resolve().parent while not (current_dir / 'README.md').exists(): # Find dir with README.md (project root) if current_dir.parent == current_dir: return Path.cwd() current_dir = curren...
cd160c69ba1d222604e046f786a0648cc738e12454b07e7622f3e2c5957c1b5f
Python
1,183
43
from napari_dmc_brainmap.utils import dropdown_utils def test_available_atlases_uses_v3_listing_api(monkeypatch) -> None: monkeypatch.setattr( dropdown_utils, "get_all_atlases_lastversions", lambda: { "admba_3d_e11_5_mouse_16um": "3.0", "allen_mouse_25um": "1.2", ...
d1398a06b305f3dae43e800bd7f6c80deded5049221bd51c99de60cac93371ad
Python
1,183
34
import torch from eir.data_load.data_preparation_modules import common def test_sample_sequence_uniform(): test_tensor = torch.arange(0, 100) sampled_tensor = common._sample_sequence_uniform( tensor=test_tensor, tensor_length=len(test_tensor), max_length=50 ) assert len(sampled_tensor) == 50...
fc3907db2060f8993a29b9be7fc13bc004dd23c6c203b07735b70aa3c9c061d9
Python
1,183
32
import cv2 from nicety.conf import get_conf from glob import glob from tqdm import tqdm from connectomics.data.utils.data_io import readvol, savevol def apply_tiled_clahe(vol, clip_limit=2.0, tile_grid_size=(8, 8), kernel_size=256): clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=tile_grid_size) fo...
76ccfaff7294a65f56f58cfb212159f3234122e348e5ab5f9eae3a6ec430b8f1
Python
1,185
37
class TestTrain: # Parse command line arguments with all required arguments provided def test_parse_with_all_required_arguments(self): # Given import sys from argparse import Namespace from unittest.mock import patch from python.segmentation.train import parse ...
9724cdb6be17660dca5042eae427cbc1373744c8836d3cdc7dd02e146ac79c0f
Python
1,185
37
class TestTrain: # Parse command line arguments with all required arguments provided def test_parse_with_all_required_arguments(self): # Given import sys from argparse import Namespace from unittest.mock import patch from python.segmentation.train import parse ...
9df23b2e972aad5090d29bb0b3fdb003fc5c96954d6c22b140e460567b6a5b4d
Python
1,185
45
# myelinfccoupling/util.py from pathlib import Path from typing import Dict, List import pandas as pd def ensure_dir(path: Path) -> None: """Create a directory (and parents) if it does not exist.""" path.mkdir(parents=True, exist_ok=True) def sanitize_label(label: str) -> str: """ Make a label safe...
4956f2f83249b6440945ba5bf51cf41cda936b46c915a646b871c9999c458476
Python
1,187
44
#!/usr/bin/env python """ QPushButton specialized to be a shutter button. Hazen 4/17 """ from PyQt5 import QtWidgets class QtShutterButton(QtWidgets.QPushButton): def __init__(self, parent = None, **kwds): kwds["parent"] = parent super().__init__(**kwds) self.cam_fn = None self....
60080ebb92eb8df876690bcef34fbd50d3d38af60b720e7035aa93686c4fe2ab
Python
1,187
52
import numpy as np from impedancefitter import get_equivalent_circuit_model from impedancefitter.loss import Z_in, Z_loss omega = 2.0 * np.pi * np.logspace(1, 8, num=20) L = 1 C = 1 R = 1 def test_loss_type(): """Test return type.""" Z = Z_loss(omega, L, C, R) assert isinstance(Z, np.ndarray) def tes...
a79699cc51cc19681865a74acdacd16fa073e250fb062198a3ab9accc8888096
Python
1,187
37
import networkx as nx import logging from zigzag.classes.stages.Stage import Stage from zigzag.classes.workload.dummy_node import DummyNode logger = logging.getLogger(__name__) class WorkloadStage(Stage): """ Class that iterates through the nodes in a given workload graph. """ def __init__(self, l...
c0fb22bababa7cce9b09e2351b0f71c0d70fb4a30e1119d7ea663edaa73ee56f
Python
1,187
23
from brainscore_vision import stimulus_set_registry from brainscore_core.supported_data_standards.brainio.s3 import load_stimulus_set_from_s3 BIBTEX = """@inproceedings{NEURIPS2019_97af07a1, author = {Barbu, Andrei and Mayo, David and Alverio, Julian and Luo, William and Wang, Christopher and Gutfreund, Dan and Tenen...
339cfbe34fdec07bd4f31ebf3628edcd75d7eb5cf344f43f29cafd77a3ef6a53
Python
1,188
36
def replace_with_custom_fn_if_matches_filter( model, replacement_fn, filter_fn, cur_fqn='' ) -> None: """ For each `child` in `model`, replaces it with `replacement_fn(child)` if `filter_fn(child)` is `True` """ name_to_child = dict(model.named_children()) for name, child in name_to_child.it...
7ad1468b5f09ab54dd84097a742e24e9ff9f268f25c24589a31b93aec06f03bd
Python
1,188
41
import torch import numpy as np def replace_numpy_with_torchtensor(obj): # assume obj comprises either list or dictionary # replace all the numpy instance with torch tensor. if isinstance(obj, dict): for key in obj.keys(): if isinstance(obj[key], np.ndarray): obj[key] =...
c5b0a8774b113761c0b665c35faf281d37f1c1328375faef6d59ee97dee711b9
Python
1,188
39
import unittest import sys import random import jellyfish class TestHashCounter(unittest.TestCase): def setUp(self): jellyfish.MerDNA.k(100) self.hash = jellyfish.HashCounter(1024, 5) def test_info(self): self.assertEqual(100, jellyfish.MerDNA.k()) self.assertEqual(1024, self.h...
e1deeb70ae745f0eb1375e4d6ebc5da305fb6579325924b0151956f032c96d6e
Python
1,189
41
from setuptools import setup import sys CLASSIFIERS = [ "Development Status :: 4 - Beta", "Natural Language :: English", "License :: OSI Approved :: MIT", "Operating System :: OS Independent", "Programming Language :: Python :: 3.7", "Topic :: Scientific/Engineering :: Bio-Informatics", ] if s...
0d9d5424a8c6aa6abaf97bcf52de280f3fc7fe3efc3f9c0f8da29b344fd1f3cb
Python
1,190
73
from .application import ApplicationBackend from .widgets import ( CheckBox, ComboBox, Container, DateEdit, DateTimeEdit, Dialog, FloatRangeSlider, FloatSlider, FloatSpinBox, Image, Label, LineEdit, LiteralEvalLineEdit, MainWindow, Menu, MenuBar, Passw...
fe9a62ddd0e70ff3e9ac6e6f20fc02ed32a68f960fca3a9270c906d7917aef44
Python
1,190
32
cdict = {'rA':'grey','rB':'k',\ 'c1':'firebrick','c2':'dodgerblue','c3':'goldenrod','c4':'darkviolet'} c_empty = 'w' Adom_c23Imbalance = {'reg_prob_dict':{'rA':0.7},\ 'cat_labels':['c1','c2','c3'],\ 'cond_dict':{('c1','rA'):0.6, \ ...
12dc88151234d1108f05acd2dac4b63fd3929255ec74b3bdc93016c5002bb4e0
Python
1,191
45
import functools import numpy as np def arrayize(type): def decorator(func): def wrapper(*args, **kwargs): return np.fromiter(func(*args, **kwargs), type) return functools.update_wrapper(wrapper, func) return decorator @arrayize(int) def detect_peaks(y, min_high_ratio=0....
256f79882d40cbc2f3dd8fe203c9c9295e39c539b360f51eb3f8a3ddbf49c56a
Python
1,192
44
import torch import numpy as np class Cutout(object): """Randomly mask out one or more patches from an image. Args: n_holes (int): Number of patches to cut out of each image. length (int): The length (in pixels) of each square patch. """ def __init__(self, n_holes, length): se...
27530511063cb592fd0a3fd6d4a29b0758ad3e94c944542d573ea01b8b78f63e
Python
1,192
39
# laminar_rs/config.py from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import List @dataclass class LaminarConfig: """ Configuration for a single subject / dataset. Parameters ---------- data_dir : Path-like Directory containing th...
55185478b378869a4ce41a2c8f67659d28488e4c697859148100128f9d54a8ce
Python
1,192
43
from pathlib import Path import click from tqdm import tqdm from brainways.project.brainways_subject import BrainwaysSubject from brainways.utils.cell_detection_importer.utils import ( cell_detection_importer_types, get_cell_detection_importer, ) @click.command() @click.option( "--input", type=Path,...
986f209a10a26c8ada3c21bdd451f1a2baea0493e3dacb3843ac00b70cc4ff4b
Python
1,194
44
# -*- coding: utf-8 -*- """ Created on Thu Apr 6 21:08:42 2023 @author: axthi """ from simnibs import sim_struct def get_simu_template(): """ returns standard simulation settings Returns ------- S : SESSION sim-struct a SESSION sim-struct with standard simulation settings defined, ...
ab076a681fb05fb75a0d049092469afe15278e6025504076db75d2856b483fa3
Python
1,194
32
_base_ = ['RepLKNet-31B_22Kpretrain_upernet_160k_ade20k_640.py',] model = dict( backbone=dict( channels=[192, 384, 768, 1536], drop_path_rate=0.3, ), decode_head=dict( in_channels=[192, 384, 768, 1536] ), auxiliary_head=dict( in_channels=768 ), ) lr_config = dict...
bed0fb294fb7cb16ee9ddb178adb8b5956ed973a80e3b069b105256e9b2cd100
Python
1,195
47
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from enum import StrEnum from django.conf import settings from cvat.apps.iam.permissions import OpenPolicyAgentPermission class UserGrowthDataPermission(OpenPolicyAgentPermission): class Scopes(StrEnum): LIST = "list" VIEW = "...
c695c24b8a7ff5ab2d1241a68511fbb0adbda4978db606651244bd5a8ebfe5b0
Python
1,195
28
import numpy as np import pytest from brainscore_vision import load_dataset, load_stimulus_set SESSIONS = {'190923': 1200, '201025': 1200, '210225': 1200, '211022': 1600} @pytest.mark.private_access class TestStimulusSet: @pytest.mark.parametrize('session, num_stimuli', SESSIONS.items()) def test_stimulus_se...
ba4b7a221318c1a9bc42034d999de480f41eb9509189f5b2eec6237aad1aece5
Python
1,197
40
import os import sys import numpy as np import pickle as pkl from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import GroupKFold sys.path.append('/home/garullie/CEBRA_analysis/') from dataset_load import data_load #index = int(os.environ["SLURM_ARRAY_TASK_ID"]) - 1 index=10 print(f"SLURM...
f3c83f53a0693203167e3207c0b94183eb51573a7cf7d002615701b6db2904d9
Python
1,197
45
#!/usr/bin/env python3 """ merge_xtc.py Script to reconstruct MD trajectory files (.xtc) that were split into multiple parts for Zenodo upload. Works for both CNA-bound and Unbound systems. Usage: python merge_xtc.py Requirements: - Python 3 - All .part files must be in the same directory as ...
c60ae7433139b220a34d07e5e1bf0e92a77bca6af418f35d6c2fbc1ac999e438
Python
1,198
43
import logging import sys def setup_logger(name=None, level=logging.INFO): """Set up a logger with consistent formatting. This function configures a logger with a standard format that includes timestamp, logger name, log level, and message. It ensures that handlers are not duplicated if the logger al...
40431ef96938d1c64ca0b1fe283c948470116490adfaab534c9ce1f3b48f1253
Python
1,199
46
import os import numpy as np import nibabel as nib dsi_file = "/mnt/e/Neuroimage/workdir/fix/sub-TI001_ses-6m_acq-DSIb4000_dir-AP_space-preprocdwi_dwiref.nii.gz" ref_file = "/mnt/e/Neuroimage/workdir/fix/b0_ref.nii.gz" out_file = "/mnt/e/Neuroimage/workdir/fix/sub-TI001_ses-6m_acq-DSIb4000_dir-AP_space-preprocdwi_dwi...
5cb9470d6bf0caab446adaa6aeb7e6cb5a87c3718479cbec500267c00cb198ab
Python
1,199
37
from typing import Literal import torch from torch.nn.functional import pad def process_tensor_to_length( tensor: torch.Tensor, max_length: int, sampling_strategy_if_longer: Literal["from_start", "uniform"], padding_value: int = 0, ) -> torch.Tensor: tensor_length = len(tensor) if tensor_len...
a05f3b26bc246769e1e685f7a8d5ff9e334d4ec2f6276697ac67a5f580478065
Python
1,199
42
import os import logging import sys def make_dir_if_not_exists( pathstring, ): # pathstring sollte #das hier ist unnötig sobald ich alles als stream mache, dann mache ich einfach aus prinzip ein directory. totalpath = os.path.join(os.getcwd(), pathstring) if not os.path.isdir(totalpath): try: ...
d6e08af56c31f41ef0c7d9c73a9088c3f6615729910cb71c51bad33809a483b5
Python
1,199
39
import os import sys import numpy as np import pickle as pkl from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import GroupKFold sys.path.append('/home/garullie/CEBRA_analysis/') from dataset_load import data_load index = int(os.environ["SLURM_ARRAY_TASK_ID"]) - 1 print(f"SLURM ID = {ind...
efb9440afe36cfda5d691dc2eafa17242fc5df47e027c98a29b04dc00a39ada7
Python
1,199
33
import dtiplayground.dmri.preprocessing as prep import yaml, os from pathlib import Path import dtiplayground.dmri.common.tools as tools class IDENTITY_Process(prep.modules.DTIPrepModule): def __init__(self,config_dir,*args,**kwargs): super().__init__(config_dir,*args,**kwargs) global logger ...
fae4db3fd0aacfe61068ccaeb5be9e94d1e4ba74f8a9e18d303c2bd33eb10a92
Python
1,199
34
#!/usr/bin/env python import math import stl from stl import mesh import numpy import sys import argparse import glob #command line interface parser = argparse.ArgumentParser() parser.add_argument("-f", action = "store", dest = "foldername", help = "Store the root folder's name") parser.add_argument("-o", action = "st...
9e87f96702133f1ea568a61f3d1b617c4a100195dede0839e8e90cee52f91499
Python
1,200
28
import matlab.engine def dict_to_matlab_struct(pars_dict): """ Converts a Python dictionary to a MATLAB struct. :param pars_dict: A dictionary where keys represent the names of fields in the MATLAB struct and the values represent the corresponding field values. :type pars_dict: di...
bba9e6a920c0d0dd651acef2ab143bf1b63a8b464b0dee96fbea4f5c949480dc
Python
1,200
55
#!/usr/bin/env python """ Application to convert LAV file to MAF file. Reads a LAV file from standard input and writes a MAF file to standard out; some statistics are written to standard error. usage: lav_to_maf [--silent] [path=replacement] < lav_file > maf_file """ import sys import bx.align.lav import bx.align.ma...
cdf4a5dd18c88625a1f6745d6b1b32d81399f1107aa0a7eaf2f9565958bbe66a
Python
1,200
37
# Generated by Django 4.2.20 on 2025-04-28 16:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("quality_control", "0009_qualitysettings_quality_settings_task_or_project"), ] operations = [ migrations.AddConstraint( model_na...
e4cfea2fee53392dc847c4f14d9661490a3bc67bc4d6adbe601f3015bfd9f925
Python
1,201
50
import numpy as np from PIL import Image as PILImage from .base import Stimulus from brainscore_vision.model_helpers.activations.temporal.utils import batch_2d_resize class Image(Stimulus): def __init__(self, path: str, size: int): self._path = path self._size = size def copy(self): ...
05c161908997ebe1af8ee81c5d7588ee845c2e3c744fb83b5331eb202204ede8
Python
1,202
43
""" Creates a cylinder mesh with boundary segmentations """ # TODO: complete import SVMTK as svm from pathlib import Path if __name__ == "__main__": print("Start ",__file__) outdir = Path("results") outdir.mkdir(exist_ok=True) surf = svm.Surface() # Lower and upper cylinder center coordinates. x0,y...
9486131a23def554c82054213d0bbb87a400d4f22bd9f49ac0385eb70b7fb013
Python
1,202
32
import gdb import re ns_pattern = re.compile(r'nlohmann(::json_abi(?P<tags>\w*)(_v(?P<v_major>\d+)_(?P<v_minor>\d+)_(?P<v_patch>\d+))?)?::(?P<name>.+)') class JsonValuePrinter: "Print a json-value" def __init__(self, val): self.val = val def to_string(self): if self.val.type.strip_typedef...
6b3019cfcf0b15afc68557ab615dea06f416e8e1d366290b3a7b327de5e8156b
Python
1,203
49
import sys _atom=[] _posit=[] for rl in open(sys.argv[1],'r'): _atom.append(int(rl[6:11])) _x=float(rl[30:38]) _y=float(rl[38:46]) _z=float(rl[46:54]) _posit.append([_x,_y,_z]) print('[ moleculetype ]') print('; Name Exclusions') print('Protein_DON 1') print('\n') print("[ atoms ]") # ...
dc24bd15df6628f18a1d670c7a2fab2bfc231f63f8efaf95f2c05ccbf9506d2e
Python
1,203
32
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['connectivity.zip']) tmp_dir = tempfile...
a1aea9031eb78be5a17b1a2dafe5c86086df95fb2284bbb617a84bf42e599723
Python
1,204
30
#!/usr/bin/env python3 import pandas as pd import argparse import os import gzip parser = argparse.ArgumentParser(description='Combine significant pairs from multiple eQTL mapping runs.') parser.add_argument('signifpair_list_file', help="File listing of 'signifpairs' outputs from eQTL pipeline.") parser.add_argument('...
ad3929d46f69dd8904430809cde892a2519a60370458d965e9cef4c8f2a3eb6a
Python
1,204
22
"""Tests for the extractor mask and connected-component numbering (numpy only).""" import numpy as np from surface_morphometrics import extract_patches as ep from surface_morphometrics import label_connected_components as lcc def test_mask_from_property(): v = np.array([1.0, 5.0, np.nan, 30.0, 31.0, 0.0]) as...
c0fe6f7a521520601d7031872fff8d76f965c151e1928febf56e6825dae2d7b1
Python
1,204
62
#!/usr/bin/env python3 from dataclasses import dataclass from scipy.integrate import solve_ivp import numpy as np @dataclass class Params: # coupling w_ee: float = 12 w_ei: float = 10 w_ie: float = 15 w_ii: float = 0 # input P: float = 1.25 Q: float = 0 # decay tau_e: float = ...
f1d1c8be5bad2dd010d0e1887480469d986cc3e41a409e7851e114628d81b1bb
Python
1,205
42
import scipy as s from .basic_distributions import Distribution from mofapy2.core.utils import * class Bernoulli(Distribution): """ Class to define Bernoulli distributions Equations: """ def __init__(self, dim, theta, E=None): Distribution.__init__(self, dim) # Initialise parame...
2abe4cb0dbd0a05960ed770b4808edf20a268450cde97e8435d37505f6f7dcb6
Python
1,206
48
# -*- coding: utf-8 -*- # python standard library inputs import os import sys import subprocess # local inputs from ..io.get_filename import get_filename def upsample_surf_mesh(file_in, file_out, n_iter, method): """Upsample surf mesh. The scripts takes generated FreeSurfer surfaces and upsamples them ...
58dee11626abcd44725d52a7b98f97098c56ee3f481ca0afd77fdc0d89a8e1ad
Python
1,207
42
import pandas as pd import numpy as np import os from pcafeat import select_ttest_features np.random.seed(42) n_samples = 100 n_features = 1000 df_X_train = pd.DataFrame(np.random.randn(n_samples, n_features)) df_X_train.columns = [f'feature_{i}' for i in range(n_features)] df_X_train.iloc[:50, :10] += 0.5 df_X_trai...
c2aa6231ae0a5e014ae4ebdb722f0b185baf1dc6451d078620c7b03efcbe6dee
Python
1,207
43
"""Calculate summary statistics. """ from sys import argv if len(argv) != 3: print("Please pass the number of modes and run id, e.g. python 5_calc_summary_stats.py 6 1") exit() n_modes = int(argv[1]) run = int(argv[2]) #%% Import packages print("Importing packages") import os import pickle import numpy as ...
fb6710eea1d78a36397ee9b7791e006f1aa88d7b9f1f4720957ae0779ea0f0f4
Python
1,207
42
# Copyright (c) DP Technology. # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np from . import BaseWrapperDataset, data_utils class SortDataset(BaseWrapperDataset): d...
0dffdbc60c840443d80a8757e5f084e25c5a201134b934494fd959bf8d6ff75a
Python
1,208
45
# imagecodecs/tests/conftest.py """Pytest configuration.""" from __future__ import annotations import glob import os import pathlib import sys from typing import Any DATA_PATH = pathlib.Path(os.path.dirname(__file__)) / 'data' if os.environ.get('VSCODE_CWD'): # work around pytest not using PYTHONPATH in VSCode...
64a03f7eb6a88136e5a50254973c7e0baebf8075fec9860e27d157bf7050a8ab
Python
1,208
38
# ruff: disable=F401 import click from _cli import LazyGroup @click.group( cls=LazyGroup, lazy_subcommands={ "mixed-t1map": "gmri2fem.mixed_t1map.mixed_t1map", "looklocker-t1map": "gmri2fem.looklocker_t1map.looklocker_t1map", "hybrid-t1map": "gmri2fem.hybrid_t1map.hybrid_t1map", ...
793a0bdf22f93d1fade4c35bf139d0b6221d2d23dccfc4ef504612b2cc9b795f
Python
1,208
42
"""Merge all the Therapeutics Data Commons (TDC) ADMET datasets into a single dataset.""" from functools import reduce from pathlib import Path import pandas as pd from tqdm import tqdm from tdc_constants import ADMET_ALL_SMILES_COLUMN def merge_tdc_admet_all(data_dir: Path, save_path: Path) -> None: """Merge ...
263ece7118988c71fe7b5d381f8c538238d1e56e9a3c1e260519dd6da48f9a05
Python
1,209
41
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from .ai_gym import AIGym from .analytics import Analytics from .distance_calculation import DistanceCalculation from .heatmap import Heatmap from .instance_segmentation import InstanceSegmentation from .object_blurrer import ObjectBlurrer from .objec...
36f26f2b033017ae57e373b5c62f41e42d63b35f2a026aed9f83f7fc5cf30d60
Python
1,209
38
#!/usr/bin/env python3 """Run inference for one preprocessed 3D volume.""" from __future__ import annotations import argparse from pathlib import Path import numpy as np try: from .apis.inference import run_inference except ImportError: from apis.inference import run_inference def parse_args() -> argparse....
f91e6296ec0ccec99eee7572d978e1ad95f62873956ff8fc52efc6106c49e3ef
Python
1,209
20
import torch def lr_scheduler(scheduler, optimizer, ReduceLROnPlateau_factor = 0.1, ReduceLROnPlateau_patience = 5): if scheduler =="scheduler_LambdaLR": lr_scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda epoch: L...
0df8fa11051fc92eb989a27d99aff0e73deee4c4163f19d55a1c58a500692e12
Python
1,210
25
# -*- coding: utf-8 -*- """ ClearMap analysis and statistics toolbox. This part of ClearMap provides a toolbox for the statistical analysis and visualization of detected cells or structures and region specific analysis of annotated data. For cleared mouse brains aligned to the Allen brain atlas, a wide range of sta...
128df1d38156a676955d673a3a3e52a6199f3330f7c4f1ba2556246dccae1b19
Python
1,210
38
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from scilpy import SCILPY_HOME from scilpy.io.fetcher import fetch_data, get_testing_files_dict # If they already exist, this only takes 5 seconds (check md5sum) fetch_data(get_testing_files_dict(), keys=['processing.zip']) tmp_dir = tempfile.T...
5e4d8cc03c2ad30e21074b3175ae055a78f7eec9c2e7e07e833f59c75c00c662
Python
1,210
47
from typing import ClassVar, Literal from argclz import argument from .cli_suite2p import Suite2pOptions from .cli_treadmill import TreadmillOptions __all__ = ['ShuffleBaseOptions', 'PositionShuffleOptions', 'SHUFFLE_METHOD'] SHUFFLE_METHOD = Literal['cyclic', 'random'] class ShuffleBaseOptio...
866c5012c7e02036d9bdd06b876f0e4c0a9b0072ebb2a3d6d8aa5b248bbdbe03
Python
1,210
58
#!/usr/bin/env python """ Application to convert AXT file to FASTA file. Reads an AXT file from standard input and writes a FASTA file to standard out. usage: %prog < axt_file > fasta_file """ __author__ = "Bob Harris (rsharris@bx.psu.edu)" import sys import bx.align.axt def usage(s=None): message = """ axt_t...
bb20d33559f131f058e30f4fb9b54babb41f011988f939a51899d66038ce46e4
Python
1,210
18
from testsetclass import TestsetClass class ALK8(TestsetClass): def __init__(self): self.weak = 1.0 self.molecules = ['li3_me', 'na2', 'na+', 'li_h', 'li_me', 'li4_me4', 'na8', 'na2_h2', 'li4_c', 'li8', 'li2', 'li5_ch', 'li_ch2n', 'li_na_h2', 'li2_ch2n_2', 'li2_ch4', 'li+'] self.exp_values...
f98786f801eaec9835fb89b69a32e072f0aa030e2cf363b9da1763f8c4c2afd9
Python
1,210
46
#!/usr/bin/env python """ Tool for adding a column to a table. Expressions for the column are similar to those supported by table_filter.py usage: %prog expression colname < table -H, --header: keep header in output -C, --comments: keep comments in output """ import sys import bx.tabular.io from bx.cook...
52c0fa9fb4265d36d687db785f39b63233e1193568dfa56d76c178b3e2b729bf
Python
1,211
43
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT import io from collections.abc import Callable from contextlib import closing from typing import ClassVar import attrs from PIL import Image from shared.tasks.base import TaskSpecBase from shared.tasks.enums import SourceDataType from shared.utils....
70f8bdeceffa0293c65981cc43821b1ee0f6ec863cb5462927774eb2acb1fabe
Python
1,211
37
from ._ai_assisted_annotation_widget import AiAssistedAnnotationWidget from ._ai_text_to_annotation_widget import AiTextToAnnotationWidget from ._brightness_contrast_dialog import BrightnessContrastDialog from ._canvas import Canvas from ._empty_state import EmptyStateWidget from ._label_dialog import LabelDialog from ...
d5e8c882c29c4106a4d22ee5f505aea2841ab5d2f95a28818d782ee015ba4b9b
Python
1,211
36
import torch from torch import Tensor import torch.nn as nn class ConcatConv3D(nn.Module): def __init__(self, in_channels: int, out_channels: int): super(ConcatConv3D, self).__init__() self._in_channels = in_channels self._out_channels = out_channels self.conv = nn.Conv3d(in_chann...
26ebb01eeadbfb9b85d22ceddc0846cc5ea01a99d75e75c827d8cccdd7886306
Python
1,212
39
import numpy as np from gensim.parsing.preprocessing import preprocess_string,strip_non_alphanum,preprocess_documents from tqdm import tqdm from gensim.models import KeyedVectors import torch from torch.nn.utils.rnn import pad_sequence import argparse parser = argparse.ArgumentParser() parser.add_argument('dataset', ty...
a1ac156e70dc3373620ee640f47c8e4fc1f4d8a0d015df0985b4693a948c915d
Python
1,212
29
from tests.utils import pytest_importorskip def test_qt3dinput(): """Test the qtpy.Qt3DInput namespace""" Qt3DInput = pytest_importorskip("qtpy.Qt3DInput") assert Qt3DInput.QAxisAccumulator is not None assert Qt3DInput.QInputSettings is not None assert Qt3DInput.QAnalogAxisInput is not None a...