sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
40728d7d31bc5241f618392c5dfd9b50a18124f95ba216f098ebe20ecf6cfde6
Python
775
26
from pathlib import Path import cv2 from neuralib.typing import PathLike from rscvp.util.util_sort import anatomical_sort_key def make_dir_animation(directory: PathLike, output: PathLike, suffix: str = '*.png', fps: int = 20): """make animatio...
fabf36483579315fd758c50004dd7d0b12803da8ba974a5bfc23487877eafad4
Python
776
31
# -*- coding: utf-8 -*- from flair.parser.modules.dropout import SharedDropout import torch.nn as nn class MLP(nn.Module): def __init__(self, n_in, n_hidden, dropout=0, identity = False): super(MLP, self).__init__() self.linear = nn.Linear(n_in, n_hidden) self.identity = identity ...
50c0d50c26c7ed7a2ec5a02897c211f5ebf9336336c542093addbb66f8098db8
Python
777
13
import os import ClearMap.Settings as settings filename = os.path.join(settings.ClearMapPath, 'Test/Data/ImageAnalysis/cfos-substack.tif'); import ClearMap.Visualization.Plot as plt import ClearMap.IO as io data = io.readData(filename, z = (0,26)); import ClearMap.ImageProcessing.BackgroundRemoval as bgr dataBGR = bgr....
12bc248228df9c0095aade2e249f92223ad647e0fac6a814e69d9352a6e8f19b
Python
778
29
""" SETUP: Ensure the drive is mapped on the linux worker system sudo mount -t drvfs '\\10.99.66.32\Team Spider' /mnt/z Start a scheduler: dask-scheduler --port 9999 --dashboard-address 9998 Start worker(s) (on linux) *in the directory containing this repository code* dask-wor...
52c0ca4f904763dce7f70f32e3dd2ecd28629ad4d428a1ed6e22d3c5338a8497
Python
778
26
# ----------------------------------------------------------------------------- # Copyright © 2009- The Spyder Development Team # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """Provides QtQuickWidgets clas...
5488df71b92d7f16c9b08125d733327bbfa505bd234299048ec79840a3e214a5
Python
778
30
# -*- coding: utf-8 -*- import torch import torch.nn as nn class ScalarMix(nn.Module): def __init__(self, n_layers, dropout=0): super(ScalarMix, self).__init__() self.n_layers = n_layers self.dropout = dropout self.weights = nn.Parameter(torch.zeros(n_layers)) self.gamm...
4a1dfdf0ecc52e4e91c380e31adca6b4666a539bd454a68975f3da3c431db4b1
Python
779
27
# ----------------------------------------------------------------------------- # Copyright © 2014-2015 Colin Duquesnoy # Copyright © 2009- The Spyder Development Team # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------...
5645038f7fc4b979bb30270f4a292f24b94c5c2e4268d065b4101c506af316fb
Python
780
31
''' A collection of general python utilities ''' import time class Timer(object): """ modified from: http://stackoverflow.com/questions/5849800/tic-toc-functions-analog-in-python a helper class for timing use: with Timer('foo_stuff'): # do some foo # do some stuff as an alternative...
90ece7183661ff17cfd0450147c201fa8de3792e77a70dc74c6bb335b749ce8c
Python
780
30
from functools import cached_property import numpy as np import AFQ.recognition.utils as abu class PreprocPlan: def __init__(self, tg): self.tg = tg @cached_property def fgarray(self): return np.asarray(abu.resample_tg(self.tg, 20), dtype=np.float32) @cached_property def crosse...
9491618f87669e5397bc6d22ad21b0e0915137ca029cac89bb255ee7d109f15e
Python
780
26
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT import requests from django.conf import settings from health_check.backends import BaseHealthCheckBackend from health_check.exceptions import HealthCheckException from cvat.utils.http import make_requests_session class OPAHealthCheck(BaseHealthChe...
ac2f21e6ed9f15b1574e0841901c884caccb3b16fcf2a9d3e7794fe75e9934fb
Python
780
29
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT import importlib from django.apps import AppConfig class AccessTokensConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "cvat.apps.access_tokens" verbose_name = "API Access Tokens" def ready(self): ...
330c259273f9e2443a5190b7733a61c233e194bee0e04a1f971616b44935d9c5
Python
781
19
""" Pytest configuration for the comet test suite. teneto (a test-only reference implementation used to cross-check comet's output) still imports `from nilearn.input_data import NiftiLabelsMasker`. That module was deprecated in nilearn 0.11 and removed in 0.13+. When CI installs a fresh env against comet's `nilearn >=...
80c8d51fb11f9c625cfb3eaeeaf9d232559239d44c390c5047c97d92d4dfadbb
Python
781
31
import sys import pandas as pd import numpy as np def get_coords(index): coords = pd.DataFrame(index=index) coords['x'] = index.str.split('x').str.get(0).map(float) coords['y'] = index.str.split('x').str.get(1).map(float) return coords def main(): counts = pd.read_csv('data/adata_heart_9_data.cs...
94cb989b0773bcdefcd78f8f8fae83585e20fa809c5e236eb968a0a639a11dc1
Python
781
23
from .base import (load_conte69, load_sc, load_fc, load_fsa, load_fsa5, load_subcortical, structural_covariance, fetch_ahba, risk_genes, load_example_data, load_summary_stats, load_fc_as_one, load_sc_as_one, nfaces, getaffine, load_mask, write_...
afee2a04d7f2f6205b6b2ff16f5ad27ae43f7e2356a0997444bc458edaa52fc0
Python
781
32
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT # Generated by Django 5.2.16 on 2026-09-04 04:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("iam", "0003_move_user_content_type"), ] operations = [ migrations.Add...
b3f4b92c0c39789ef3abf170e75346300872eb59754f02c73ddb05e5dd1a948c
Python
781
29
import numpy as np from pathlib import Path from typing import Dict, Tuple def inspect_npz(filepath: Path) -> Dict[str, Tuple[int, ...]]: """ 加载 .npz 文件并返回其中所有数组的名称及形状。 参数 ---- filepath : Path .npz 文件路径 返回 ---- Dict[str, Tuple[int, ...]] 键为数组名称,值为对应的 shape 元组 """ ...
dc2f9c74d81c5afa0c848d19e2ad9e52eac0ab9a341ed20c154c9e3e06cab1fe
Python
781
29
import json from subprocess import Popen, PIPE def test_cli(): process = Popen(['mmsplice', 'run'], stdin=PIPE, stdout=PIPE) options = {} process.stdin.write((json.dumps(options) + '\n').encode()) process.stdin.flush() assert process.stdout.readline().decode() == 'MMSPLICE-RESPONSE:1\n' vari...
ea1379ea074d7c0ed8f1cc9edd63f7e7e787691d24b5169162e3d28bd2ff7dca
Python
781
18
###### Visualization configs ################################################################ from matplotlib.colors import LinearSegmentedColormap, BoundaryNorm, ListedColormap colors = [(1, 1, 1), (0, 1, 0), (1.0, 0, 0.0)] # Color for 1 (red) # Create a ListedColormap incmap = ListedColormap(c...
d2f314d8b43bfa9113d8469fa5d0ad6d1729f7081e1917334372f3154700e6ce
Python
782
23
#!/usr/bin/env python3 import pandas as pd import matplotlib.pyplot as plt import sqlite3 conn = sqlite3.connect("data2.db") df = pd.read_sql_query("""SELECT SUM(CASE typ WHEN 5 THEN volume ELSE 0 END) AS volume5, SUM(CASE typ WHEN 6 THEN volume ELSE 0 END) AS volume6, SUM(CASE typ WHEN 7 THEN volume ELSE 0 END...
0c7af2e77d05be9c1b1fe63728840d3624c21acdde5cc411c22b0ad5c37b52a8
Python
783
28
# Generated by Django 4.2.6 on 2023-11-21 19:52 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("engine", "0076_remove_storages_that_refer_to_deleted_cloud_storages"), ] operations = [ migrations.AlterFiel...
a4dfc160e60f932546e14821ff09d1c9abeee30bc279d075675b601fde8ffd90
Python
783
28
import pytest from qtpy import PYQT5, PYQT_VERSION from tests.utils import pytest_importorskip def test_qtwebenginecore(): """Test the qtpy.QtWebEngineCore namespace""" QtWebEngineCore = pytest_importorskip("qtpy.QtWebEngineCore") assert QtWebEngineCore.QWebEngineHttpRequest is not None @pytest.mark.s...
18adf738c387aa53c3fc60d6f27cd95370ac26ec1b07ddf66ca57391e3b9c304
Python
784
33
############################################################################### CNtoColor = {} CNtoColor[0]= '224,224,224' CNtoColor[1]= '160,160,160' CNtoColor[2]= '0,0,0' CNtoColor[3]= '0,0,153' CNtoColor[4]= '51,51,255' CNtoColor[5]= '0,255,255' CNtoColor[6]= '0,153,0' CNtoColor[7]= '255,255,0' CNtoC...
4f62362978560b7236fa30b44c6a60b631fe75d83fcf2421e77f5aa5a06f73c8
Python
784
26
import os from glob import glob # Adjust import based on your package structure from stack_corr.warp import warp_image #type: ignore # Configuration input_folder = '/path/to/input_images' output_folder = '/path/to/output_images' reference_image = '/path/to/reference_image.tif' os.makedirs(output_folder, exist_ok=Tr...
660bde497c0442d198de167540ade63c77dbbd0d69cf346ce7142a8e265e319c
Python
784
33
from qtpy.QtWidgets import ( QVBoxLayout, QLabel, QTextEdit, QPushButton, QWidget, ) class LogWidget(QWidget): def __init__(self): super().__init__() layout = QVBoxLayout() # TextEdit: log window widget self.log_box = QTextEdit() self.l...
9d07438b1199b905f121877a247ad22307a462ff33c42a3b5c25bb7b301a8a96
Python
784
30
""" Repairs self intersections """ import SVMTK as svm from pathlib import Path if __name__ == "__main__": print("Start ",__file__) outdir = Path("results") outdir.mkdir(exist_ok=True) pial = svm.Surface("../Data/lh-pial.stl") print("Number of self intersections", pial.num_self_intersections()...
c6c781bb6006957646754a36af4a598388dee9a51e42876d3daeac4ac91c1179
Python
784
25
# Copyright (C) 2021-2022 Intel Corporation # # SPDX-License-Identifier: MIT from allauth.account import app_settings as allauth_settings from allauth.account.models import EmailAddress from rest_framework import exceptions from rest_framework.authentication import BasicAuthentication class BasicAuthenticationEx(Ba...
ee062c9b0c1a95092f33b8e81cd7166f52f9f708776295563a10c23b95714688
Python
784
7
from brainscore_vision import model_registry from brainscore_vision.model_helpers.brain_transformation import ModelCommitment from .model import get_model, get_layers model_registry['alexnet_w1_mlp4096_simclr_baseline_64715_probe0'] = lambda: ModelCommitment(identifier='alexnet_w1_mlp4096_simclr_baseline_64715_probe0'...
22f5c99babd23e302d2c37cd8acb0580a6981f475c3b3cc1d332b357f015dec6
Python
785
28
# loss function import tensorflow as tf import tensorflow.keras.backend as K # the loss function def loss_function(y_true, y_pred): # mse squared_diff = tf.square(y_true - y_pred) mse_loss = tf.reduce_mean(squared_diff) # fft label_fft1 = tf.signal.rfft2d(y_true) pred_fft1 = tf.signal.rff...
d0f16f409c529ec5433fca648dadff8706a02445050b2a9576b52214eba7f8cb
Python
785
31
# Copyright 2015 Numenta Inc. # # Copyright may exist in Contributors' modifications # and/or contributions to the work. # # Use of this source code is governed by the MIT # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. import unittest from nab.util import getProbationPeri...
db33b2df54d80a1c26afbf1dc00a0ad181a3fe2eec302e15813d28ed3b88c653
Python
785
26
#!/usr/bin/env python3 """Train and evaluate the eye movement artifact detector.""" import logging from artifact_identification.detectors.eye_movement import EyeMovementDetector def main(): logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = loggin...
036029c17a33c45b4c7db91de88a6533fa9f3dd36a8787860d296afd49dae146
Python
786
26
#!/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=['others.zip']) tmp_dir = tempfile.Tempo...
4cdd499049f043785b6750b21c982bc4255bbeacb82cad86ebbc46c8229c3069
Python
786
38
#!/usr/bin/env python """ Read data in UCSC wiggle format and write it to an "array tree" file. usage: %prog array_length output.array_tree < input.wig """ import sys from bx.arrays.array_tree import ( array_tree_dict_from_reader, FileArrayTreeDict, ) from bx.arrays.wiggle import WiggleReader def main(): ...
57c88c4320d11fe327264cc675afaad9307f62e674cfdb66966f6b41c6645c30
Python
786
22
import torch import numpy as np import pandas as pd from torch_geometric.data import Data, HeteroData from datetime import datetime as dt # dataset # from dataset import fast_merge,df_to_mask from tqdm import tqdm import os print(os.getcwd()) # node=pd.read_json("/data2/whr/czl/TwiBot22-baselines/datasets/cresci-2015/...
1ba9a697de07ba2724b33a8b8315debd91bb5a4ff3ea3d6c11e7a2c04340dd2b
Python
787
31
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT import PIL.Image import cvat_sdk.auto_annotation as cvataa import cvat_sdk.models as models from ._torchvision import TorchvisionFunction class _TorchvisionClassificationFunction(TorchvisionFunction): _label_type = "tag" def detect( ...
27a22aae23b6a3fd0cfd19ca91c0d017cd2cf4b4d03402356b74ebea374bfad6
Python
787
25
#!/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=['others.zip']) tmp_dir = tempfile.Tempo...
39244064dd83bb466314b0fd1e6fce72f45854fb4d2cdfd8d9f6edc675a73f83
Python
787
30
# -*- coding: utf-8 -*- """ Created on Mon Sep 2 19:22:50 2019 @author: czz """ from gluoncv import data, utils from mxnet import gluon import mxnet as mx import cv2 classes = ['hat', 'person'] ctx = mx.gpu() frame = '1.jpg' img = cv2.imread(frame) x, img = data.transforms.presets.yolo.load_test(f...
71a36c1602ee23b6942dcaefacb284b2274a3254cec17746546f6e8f162387b6
Python
787
37
#!/usr/bin/env python """ Read a maf from stdin and print the chromosome number for each alignment. It searches for 'chr' in each alignment block src, and may not be robust if other src formats are used. NOTE: See 'align_print_template.py' for a more general variation of this program. usage: %prog refindex [op...
899032871185e1bcf6b334f393f8c3ed396523e8eec882362b82501b92e942c3
Python
787
29
from nibabel import load as load_mri, save as save_mri, Nifti1Image from multiprocessing import Pool import numpy as np mri_paths = None # to define mask_paths = None # to define dest_paths = None # to define N_PROCS = None # to define MEDIAN = 500 def process_mri(mri_path, mask_path, dest_path): print(f"Start ...
9a2acb10e703eb214977d48226bfe576ebbe8afc934f9513a81728d5bdfd8fbc
Python
787
26
#!/usr/bin/env python3 """Train and evaluate the muscle artifact detector.""" import logging from artifact_identification.detectors.muscle import MuscleArtifactDetector def main(): logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogg...
c4141a62e3067bad74705330ec1843dbaf796ad8fc89d56ef28ea93fe582587a
Python
788
28
# define utility functions import torch from torch.fft import * from torch.optim.lr_scheduler import LambdaLR def ifft2c(k): return ifftshift(ifft2(fftshift(k))) def fft2c(x): return fftshift(fft2(ifftshift(x))) def view_as_complex(x): x = torch.chunk(x, chunks=2, dim=1) x = x[0] + 1j * ...
0c3fbfb2b612b0bd0c37683de32dfdcc2d8c59d60d141e6b29dea24e8cbcdaf0
Python
789
23
#!/usr/bin/env python3 from setuptools import setup setup( name='featurevis', version='0.2.1', description='Visualize features cells are responsive to via gradient ascent', author='Erick Cobos', author_email='ecobos@bcm.edu', license='MIT', url='https://github.com/cajal/featurevis', key...
d6fa9304cee23f14977dcd33a9da0a33f731a4be48b36897a36f35b074f1dee6
Python
790
32
# -*- coding: utf-8 -*- """ Created on Fri Apr 11 19:03:57 2025 @author: axthi """ import sys # -------------------------------------------------- # NOTE: Update this path to fit to your installation path_to_utils = 'C:/Users/axthi/simnibs/memoslap_utils/' sys.path.append(path_to_utils) from simnibs_memoslap_utils.ut...
e709c0b5ee6f42d5fc12d3a3e0948b25a2c922693240826d032511492a54b61e
Python
790
25
#!/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=['tracking.zip']) tmp_dir = tempfile.Tem...
1d676f8a4ad828455e90b8fcb033bc8a2e29269d3c9676f50db3c7f73b60ab6f
Python
791
28
# -*- coding: utf-8 -*- """ Created on Thu Jun 18 15:21:44 2020 @author: Yoshi """ import numpy as np def polar_coordinates_calculator(responsive_locations,corner): # Converts cartesian coordinates to polar coordinates polar_coordinates = [] for cell_location in responsive_locations: x_cor...
7228b6c5695ec93c42945dab9f65f4362236af7a475522fe0084f87c52592776
Python
792
23
import dtiplayground.dmri.tractography as base import dtiplayground.dmri.common as common import yaml logger=common.logger.write class @MODULENAME@(base.modules.DTITractographyModule): def __init__(self,config_dir,*args,**kwargs): super().__init__(config_dir) def generateDefaultProtocol(self,...
ae803cf7fcf490bc3b9d094d6f95e803d374c8c6c0eaf57d33535759fced7c3f
Python
792
34
import matplotlib # color the depth, kitti magma_r, nyu jet #def colorize(value, cmap='magma_r', vmin=None, vmax=None): def colorize(value, cmap='magma_r', vmin=None, vmax=None): # TODO: remove hacks # for abs # vmin=1e-3 # vmax=80 # for relative # value[value<=vmin]=vmin # vmin=None ...
fe9ccc147b89efaf691d3f7d68bf175cbb90107d0093d3e334645dfe34383c10
Python
792
23
import dtiplayground.dmri.fiberprofile as base import dtiplayground.dmri.common as common import yaml logger=common.logger.write class @MODULENAME@(base.modules.DTIFiberProfileModule): def __init__(self,config_dir,*args,**kwargs): super().__init__(config_dir) def generateDefaultProtocol(self,...
9e4b8f902ce84cb70552a59b7188193a7bc8eb1fc354fd6d603be8341a576ba8
Python
793
28
# data_loaders/spectra_inference_dataset_loader.py import torch from torch.utils.data import Dataset import pandas as pd import numpy as np class class_ls(Dataset): def __init__(self, x, transform=None): df = pd.read_pickle(x) self.X = df['coo_format_data'].tolist() self.N = df['Precursor'...
c17dff88070de0af11f31aa9ba10d34235524f4a6529e3f9aee1c7b90c2d8736
Python
793
28
from dataclasses import fields import numpy as np def array_safe_eq(a, b) -> bool: """Check if a and b are equal, even if they are numpy arrays""" if a is b: return True if isinstance(a, np.ndarray) and isinstance(b, np.ndarray): return a.shape == b.shape and (a == b).all() try: ...
45be4e4465751bb7910b3fdc5f8702ad1d5cfc6f271bdb024f258bd809f0c85c
Python
794
32
from impedancefitter.utils import get_equivalent_circuit_model import numpy as np from impedancefitter.cpe import cpe_ct_model, cpe_ct_w_model omega = 2. * np.pi * np.logspace(1, 8, num=20) def test_cpe_RCT(): k = 1e-7 alpha = 0.9 Rct = 100 model = 'parallel(CPE, R)' m = get_equivalent_circuit_...
49d08b87e413a349ab0bd13d8edf0963762f6f317708290a324c4830476b84d5
Python
794
29
import sys import torch from model.GeminiMol import GeminiMol if __name__ == '__main__': # check GPU print('CUDA available:', torch.cuda.is_available()) # Should be True print('CUDA capability:', torch.cuda.get_arch_list()) print('GPU number:', torch.cuda.device_count()) # Should be > 0 # read d...
66873351624cc1b163ae4d82f9c63625bf7916bf79d0b1806f590ed7338799c6
Python
794
31
'''Test ogo setup version is correct''' import unittest from packaging import version import re import ogo class TestVersionIsCompliant(unittest.TestCase): '''Test the ogo version is PEP compliant''' def test_get_version(self): '''Can access __version__''' ogo.__version__ def test_get_v...
8ebd64dfd11acb8b0718d6c307840decdfdfeb2ca3c5224766830ac569c6cefa
Python
794
17
def diceFunction(pred, ground): if pred.shape != ground.shape: raise ValueError("Shape mismatch: pred and ground must have the same shape.") intersection = np.logical_and(pred, ground) if ((pred.sum() == 0) and (ground.sum() == 0)): return 1.0 return (2.0 * intersection.sum()) / (pred.s...
8ee57bb772db82bcc3eb44ab25b34ae922582ce466849bcf84714b83c69e1f3b
Python
795
22
""" Plot the impedance measured with a frequency response analyser. For that, we first convert the data measured with a MokuGo and a Rohde&Schwarz oscilloscpe. Both devices have an input impedance of 1MOhm. We wanted to measure a 47Ohm resistor. Thus, we connected a 100Om resistor in series with the 47Ohm resistor. Thi...
08da5936d245afc80b3db3aa160a4c257caf3b51e50faf76a416dd7ee40da3a5
Python
796
32
from typing import Dict import torch from skoots.validate.stats import get_volume, get_surface_area from torch import Tensor def stats_per_instance(x: Tensor, anisotropy: Tensor) -> Dict[str, Tensor]: """ :param x: :param anisotropy: :return: """ summary = {} object_id = torch.unique(x)...
831b8af5da87d485bce1c9774bf6671e477decf5e2e4478ff489bf3e57b2de90
Python
796
23
import torch from batchgeneratorsv2.transforms.base.basic_transform import BasicTransform class RandomTransform(BasicTransform): def __init__(self, transform: BasicTransform, apply_probability: float = 1): super().__init__() self.transform = transform self.apply_probability = apply_probab...
8fdc4f702536fb653dafdf08ca04221a9d8551525585f6a90cc3bdadf58b08df
Python
796
23
import dtiplayground.dmri.fiberprofile as base import dtiplayground.dmri.common as common import yaml logger=common.logger.write class IDENTITY_Process(base.modules.DTIFiberProfileModule): def __init__(self,config_dir,*args,**kwargs): super().__init__(config_dir) def generateDefaultProtocol(s...
3ae568e9e9e15934d5c52e1150af8099e10bb3efdbea570ef9fc7f3bea2e91cc
Python
797
29
from __future__ import annotations from typing import Final import imgviz import numpy as np from numpy.typing import NDArray _LABEL_COLORMAP: Final[NDArray[np.uint8]] = imgviz.label_colormap() def resolve_shape_color( *, config: dict, label: str, label_index: int ) -> tuple[int, int, int]: mode = config["...
ba4c3d43a22d5b0fee55f60eb4ec876ad83f27a4eccef683e4cf93206d32e916
Python
797
37
#!/usr/bin/env python """ Read a PAIRWISE maf from stdin and print the percent identity of each alignment, where percent identity is defined as the number of matching columns over the number of aligned (non-gap) columns. TODO: Generalize for more than two species usage: %prog < maf > out """ import sys from bx.ali...
bc3bb4a395da187cfdd9aab407e60c67d07109aa7cefcd2efbee7f58c0410823
Python
797
29
import pytest import subprocess import logging CORES = "2" LOGGER = logging.getLogger(__name__) def run(cmd, dir_path, report_stdout=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs): shell = isinstance(cmd, str) response = subprocess.run( cmd, cwd=dir_path, shell=shell, stdout=...
cc2925ae29f6f7966d59e8ea5cc3bbe6b5f59a3fad265f36c485fe40f62e5979
Python
797
31
from scipy import stats import numpy as np from .base import Distribution class Beta(Distribution): """Beta prior. Parameters ---------- alpha : scalar or ndarray Parameter of distribution beta : scalar or ndarray Parameter of distribution """ def __init__(self, alpha, ...
e0cdc453f2b77810e3954e2fb47a533dfd955b65304513207866b4e0d3839a28
Python
797
35
"""Example script for calculating static power/coherence spectra. """ print("Setting up") import os import numpy as np from osl_dynamics.analysis import static from osl_dynamics.data import Data # Make a directory to hold output files os.makedirs("spectra", exist_ok=True) # Load data data = Data( [ f"/w...
110fc0d03bb42379752c676dbdf01507a9d3c7fcfde6827553f99931528aba97
Python
798
29
import pytest from qtpy import PYQT5, PYQT_VERSION def test_qtsensors(): """Test the qtpy.QtSensors namespace""" QtSensors = pytest.importorskip("qtpy.QtSensors") assert QtSensors.QAccelerometer is not None assert QtSensors.QAccelerometerFilter is not None assert QtSensors.QAccelerometerReading ...
25b990abe41cbc8ed8db11327a7f5c79aa8cddb85f6e75cdcf584b174d777e3d
Python
800
26
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from contextlib import contextmanager from django.db import connection, transaction __all__ = ("transaction_with_repeatable_read",) @contextmanager def transaction_with_repeatable_read(): with transaction.atomic(): match connection.ve...
40aa26c0abafe9b50b588301b024ae7e4106bb635ad480d14057669c8f8a9012
Python
800
24
import argparse import yaml from wandb_utils import WandbLogger WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' def create_dataset_artifact(opt): with open(opt.data) as f: data = yaml.safe_load(f) # data dict logger = WandbLogger(opt, '', None, data, job_type='Dataset Creation') if __name__ == '__ma...
4a15a735ad2870562b01c705814ab4fab02761ed3ba75671094e51782aa7d5e7
Python
800
27
#!/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 fetch_data(get_testing_files_dict(), keys=['processing.zip']) tmp_dir = tempfile.TemporaryDirectory() def test_help_option(script_runner): ret...
5d44325ecd2dea6281684393c6e8122bfc67cdd8698316c6376bf4a50f6b6127
Python
800
23
#!/usr/bin/env python3 import pandas as pd import matplotlib.pyplot as plt from pathlib import Path # 1. 读取净获益数据 # 假设已有 CSV: threshold, net_benefit, treat_all, treat_none df = pd.read_csv(Path(__file__).parents[1] / "results" / "decision_curve_data.csv") # 2. 绘图 plt.figure(figsize=(6, 4)) plt.plot(df["threshold"], df...
9daa37ce7531a45c5fe773b3db3083c001fd0f28cd298d7dc824a7208ec66152
Python
800
26
from dataclasses import dataclass from enum import Enum, auto class AxonModificationMode(Enum): KEEP_AXON = auto() MYELINATED_AXON = auto() REPLACE_WITH_STRAIGHT_AXON = auto() REPLACE_WITH_MYELINATED_STRAIGHT_AXON = auto() @dataclass class CellModificationParameters: """A dataclass with paramete...
c05d137aa30580b963a956ecf242946eb47f7b6983ca4e5b52679af206bb6ee7
Python
800
12
from brainscore_vision import benchmark_registry from .benchmark import Hebart2023fmri benchmark_registry['Hebart2023_fmri.V1-ridge'] = lambda: Hebart2023fmri('V1', 'ridge') benchmark_registry['Hebart2023_fmri.V2-ridge'] = lambda: Hebart2023fmri('V2', 'ridge') benchmark_registry['Hebart2023_fmri.V4-ridge'] = lambda: H...
cd2aa970d03c348479f9b9414a8a81940934baa8dffca71fd5cc212d27a740c3
Python
801
35
#!/usr/bin/env python import os import sys sys.path.append('.') import click as ck import numpy as np import pandas as pd import gzip from collections import Counter import logging logging.basicConfig(level=logging.INFO) @ck.command() @ck.option( '--data-file', '-df', default='data/swissprot_exp.pkl', help=...
dbdb512b8db7b3eceb679be7def6708ec0f26495df397989de7a4a3e7885f0a2
Python
801
18
import logging import sys import csv import argparse import hierarchy if __name__ == '__main__': parser = argparse.ArgumentParser(description='extend a tree using node mapping.') parser.add_argument('hierarchy_file', type=file, help='path to hierarchy file') parser.add_argument('mapping_file', type=file, h...
e215783e646299b359f76437c28571c68a436ef249f76ad753d6a6b0dfaf2d7f
Python
801
16
from testsetclass import TestsetClass class ADIM6(TestsetClass): def __init__(self): self.weak = 1.0 self.molecules = ['AM5', 'AD3', 'AM2', 'AD4', 'AM7', 'AD6', 'AM3', 'AD5', 'AD2', 'AD7', 'AM6', 'AM4'] self.exp_values = {'0': 1.34, '1': 1.99, '2': 2.89, '3': 3.78, '4': 4.60, '5': 5.55} ...
144ccca4f6ff8f45199716a1f0cbb3a6982279d134bcc8f6db01ff1ff0f84a14
Python
802
28
"""test_fast_knn.py""" import functools import numpy as np import impyute as impy from impyute.ops.testing import return_na_check # pylint:disable=invalid-name SHAPE = (5, 5) def test_return_type(knn_test_data): imputed = impy.fast_knn(knn_test_data) return_na_check(imputed) def test_impute_value(test_data...
080554d4642e4907bc11aadf35c31cd101a0ee758de642477fe938b0d87bd2a0
Python
803
33
import subprocess import pytest from deepreg import log logger = log.get(__name__) def execute_commands(cmds): for cmd in cmds: try: logger.info(f"Running {cmd}") out = subprocess.check_output(cmd, shell=True).decode("utf-8") logger.info(out) except subproces...
1ff7d9d9dfde19f18b9eedbcf641ecaf61f1fa8d2ef3b1b5b581dcfa3b3becae
Python
803
7
highlevel={} highlevel["SOCIAL_IQ_COVAREP"]="http://immortal.multicomp.cs.cmu.edu/Social-IQ/acoustic/SOCIAL_IQ_COVAREP.csd" highlevel["SOCIAL-IQ_QA_BERT_LASTLAYER_BINARY_CHOICE"]="http://immortal.multicomp.cs.cmu.edu/Social-IQ/qa/SOCIAL-IQ_QA_BERT_LASTLAYER_BINARY_CHOICE.csd" highlevel["SOCIAL-IQ_QA_BERT_MULTIPLE_CHOIC...
39541bc1890c0f2de4795b07bb90d50746ac003851385fe35f2c56f1994ab58b
Python
803
42
''' Abstract class for controlling a hardware valve. Function names were derived from original valveChain and hamilton classes. George Emanuel 2/16/2018 ''' from abc import ABC, abstractmethod class AbstractValve(ABC): @abstractmethod def changePort(self, valve_ID, port_ID, direction = 0): pass ...
5ba542627b728eb921cc50ae0e4455c1e2ddd6820aae29813cba6ac6681d0b83
Python
803
29
import platform from importlib.util import find_spec """ Adapted from: https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pytorch_lightning/utilities/imports.py """ def _module_available(module_path: str) -> bool: """Check if a path is available in your environment. >>> _module_available(...
5f126e464dc4387d2f87a25d6307ee91a339b8127addfd8dc38cfb73ef2533fe
Python
804
27
# Generated by Django 3.2.18 on 2023-03-13 21:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("engine", "0066_auto_20230319_1252"), ] operations = [ migrations.AlterField( model_name="cloudstorage", name="crede...
c7e4392d02701ceb03b5ce9eed3d68c9d7c7e6bdb2fe341a8423430108daf737
Python
804
29
from dataclasses import dataclass from typing import Literal from eir.models.output.tabular.linear import LinearOutputModuleConfig from eir.models.output.tabular.mlp_residual import ResidualMLPOutputModuleConfig from eir.models.output.tabular.shared_mlp_residual import ( SharedResidualMLPOutputModuleConfig, ) @d...
2405fd9705b17937f397b8f8fb857c70044d951085541743668d235106ec16fa
Python
805
44
#!/usr/bin/env python. """ Read a maf and print the text as a fasta file. usage: %prog < maf > fasta """ import sys from bx.align import maf def __main__(): maf_reader = maf.Reader(sys.stdin) # Confusing since maf_to_concat_fasta takes names. # if len( sys.argv ) > 1: # comps = map( int, sys...
65241891e93ba866eb84dc3215212a2a0a71497dac444f3c250a3a24d1af17ef
Python
805
30
import sys from argparse import ArgumentParser from connectomics.utils.evaluate import adapted_rand from connectomics.data.utils.data_io import readvol def evaluate(seg, gt): arand, prec, rec = adapted_rand(seg, gt, all_stats=True) print(f"Adapted Rand Error: {arand}") print(f"Precision: {prec}") prin...
711a6de6059cb6391e8a805794d6a285c324ca4c230f343258ab23d837e4762b
Python
805
31
import base64 import requests def encode_image_to_base64(file_path: str) -> str: with open(file_path, "rb") as image_file: image_bytes = image_file.read() return base64.b64encode(image_bytes).decode("utf-8") def send_request(url: str, payload: list[dict]) -> list[dict]: response = requests....
763745fbfee3dcd02b75a0e8a5f11d1093b4e5dc179414cb3af2314db4ed7958
Python
805
33
from setuptools import setup import string import os.path as op from setuptools_scm import get_version def local_version(version): """ Patch in a version that can be uploaded to test PyPI """ scm_version = get_version() if "dev" in scm_version: gh_in_int = [] for char in version.n...
d7c972b42a005055c5495e2d261e02b9ab1139d2ccb8a20073130f3547798e3c
Python
805
26
#!/usr/bin/env python """ Test correlation lock. Hazen 09/19 """ import numpy import storm_analysis.simulator.draw_gaussians_c as dg import storm_control.sc_hardware.utility.corr_lock_c2dg as cl2DG def test_c2dg(): clf = cl2DG.CorrLockFitter(roi_size = 8, sigma = 1.0, threshold = 0.1) for i in range(10): ...
fee77f73fc765216d78c5a6c0c8a8223d36ebbdad587cd16adcd14bf40d5bd96
Python
805
37
# Train a Linear Regressor # Imports import numpy.typing as npt from sklearn.linear_model import LinearRegression from modules.tools.types_abbrv import LINEAR_REG_TYPE def train( X: npt.NDArray[float], y: npt.NDArray[float] ) -> tuple[LINEAR_REG_TYPE, dict]: """Train a linear regression predictor Para...
8823825ee4c3f389468a83cf92bb304af9cfc41546445415cdfa7c730e00874b
Python
806
31
"""SFCN with a softmax output for categorical classification.""" from tensorflow import Tensor from tensorflow.keras.layers import Dense from .sfcn import SFCN class CategoricalSFCN(SFCN): """SFCN for multi-class classification tasks. The prediction head is a Dense layer with softmax activation, produc...
a9a7f34ec00feb8cf22f0e501799863e41c533c60c2374c799bf15f5cced9939
Python
806
37
import pandas as pd import glob import os import sys ChiThresh = 9 # Step 1: Find all your CSV files csv_files = glob.glob("results/batch_*/output_ID_*.csv") print(f"Found {len(csv_files)} result files.") # Step 2: Collect transformed rows rows = [] for file in csv_files: df = pd.read_csv(file) # Drop 'St...
2d5572af4297391c70e5cd48c1252ba6a6b52fb77dde504e941542a7b123bc08
Python
807
37
import pandas as pd import glob import os import sys ChiThresh = 12 # Step 1: Find all your CSV files csv_files = glob.glob("results/batch_*/output_ID_*.csv") print(f"Found {len(csv_files)} result files.") # Step 2: Collect transformed rows rows = [] for file in csv_files: df = pd.read_csv(file) # Drop 'S...
7a407acd58489609c7a4eb9e412854dbfc5a6aeeba973ec4935fa2a611eb900d
Python
807
27
import skimage.io as io import numpy as np import torch from torch import Tensor from typing import Optional def imread(image_path: str, pin_memory: Optional[bool] = False) -> Tensor: """ Imports an image from file and returns in torch format :param image_path: path to image :param pin_memo...
7eeddcd99d7d74d2fa89cfe641c22274822151677f9bb043fb1972eccfbef40b
Python
807
27
from EIANN import utils as ut network_pkl_name = '20231129_EIANN_2_hidden_mnist_van_bp_relu_SGD_config_G_complete_optimized_66049_257.pkl' path = f'/scratch/yc1376/data/eiann/{network_pkl_name}' net = ut.load_network(path) name = path.split('/')[-1].split('.')[0] print(f'Network Name: {name}') print(f'Final Val Accur...
b62429fbaf2800cef198f270808349c00550d79a128a8cc5c294cd03bc46c92d
Python
807
37
import pandas as pd import glob import os import sys ChiThresh = 11 # Step 1: Find all your CSV files csv_files = glob.glob("results/batch_*/output_ID_*.csv") print(f"Found {len(csv_files)} result files.") # Step 2: Collect transformed rows rows = [] for file in csv_files: df = pd.read_csv(file) # Drop 'S...
13cae19bf6f8180723710e4d6d01e1cad1feed8deb5e6bf290d7a5240e36ee00
Python
808
34
"""Print free energy. """ from sys import argv if len(argv) != 2: print("Please pass the number of states, e.g. python 3_print_free_energy.py 8") exit() n_states = int(argv[1]) output_dir = f"results/models/{n_states:02d}_states" import pickle import numpy as np def get_best_run(min_, max_): best_fe ...
2598774fa91247a77c30f6f67845eda081f3c1e824c93b767a819de46b81edac
Python
808
28
# ----------------------------------------------------------------------------- # Copyright © 2009- The Spyder Development Team # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """Provides QtPurchasing classe...
32e9bb02602ef503f0c494dc5de083a313ade85e78739bf86c8aaa7eef8998bb
Python
808
37
import pandas as pd import glob import os import sys ChiThresh = 6.4 # Step 1: Find all your CSV files csv_files = glob.glob("results/batch_*/output_ID_*.csv") print(f"Found {len(csv_files)} result files.") # Step 2: Collect transformed rows rows = [] for file in csv_files: df = pd.read_csv(file) # Drop '...
4702235e6e52fa4f7ef3af20480a87ceed10101065274dcafbc8714e84eb8451
Python
808
26
#!/usr/bin/env python import warnings warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.ufunc size changed") import pandas as pd import numpy as np from sklearn.externals import joblib from PAINTeR import global_vars import PAINTeR.connectivity as con...
969de2a851f5772244e28aaca964d01263d9e3574f3a27c33fc934f63526629c
Python
808
25
# Created by David Coggan on 2024 06 26 import brainscore_vision import numpy as np def test_Coggan2024_fMRI_stimuli(): stimulus_set = brainscore_vision.load_stimulus_set('Coggan2024_fMRI') assert len(stimulus_set) == 24 assert len(set(stimulus_set['object_name'])) == 8 assert len(set(stimulus_set['o...
68ebe56d6faf0cc4dbf0fa845d9e43a35dcb6e91ac2664cc7defb23b403b280f
Python
810
31
""" Create a mesh with multiple surfaces """ import SVMTK as svm import numpy as np from pathlib import Path if __name__ == "__main__": print("Start ",__file__) surf = svm.Surface(); outdir = Path("results") outdir.mkdir(exist_ok=True) sphere1 = svm.Surface() sphere2 = svm.Surface() spher...
aacf55eaef10a77d2c41f8e16f32666957c92ae1e5ba15dfecb955f10679d3c9
Python
810
31
import torch from torch import nn, Tensor class CustomEmbedding(nn.Module): # A custom embedding class to circumvent error of default implementation. def __init__(self, num_classes, embedding_dim): super(CustomEmbedding, self).__init__() self.num_classes = num_classes self.embeddin...
cce9f7960ba7fbd0244853fa22a180dc4b2858d789bd5e7bdd5dc585e80230d9
Python
810
35
#!/usr/bin/env python """ For each interval in `bed1` count the number of intersecting regions in `bed2`. usage: %prog bed1 bed2 """ import sys from bx.intervals import ( Intersecter, Interval, ) bed1, bed2 = sys.argv[1:3] ranges = {} for line in open(bed2): fields = line.strip().split() chrom = fi...
218476e690a6d8fd799c1fcd86b35fa49e34492e07477c62423584cfc5d3c6b5
Python
811
21
from matplotlib import pyplot as plt, rcParams FIG_WIDTH = 7.5 # width of figure in inches BASE_FONT_SIZE = 6 RATIO = FIG_WIDTH / BASE_FONT_SIZE TINY_SIZE = 6 SMALL_SIZE = TINY_SIZE + 2 MEDIUM_SIZE = SMALL_SIZE + 2 BIGGER_SIZE = MEDIUM_SIZE + 2 plt.rc('font', size=SMALL_SIZE) # controls default text sizes plt.rc('...