sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
6c66ff00b25df30aad047b4a566479209a5b45f8e6abda2505cb2ad919e2f525
Python
2,505
69
from provdbconnector import ProvDb from provdbconnector.db_adapters.in_memory import SimpleInMemoryAdapter import pkg_resources # create the api prov_api = ProvDb(adapter=SimpleInMemoryAdapter, auth_info=None) # create the prov document from examples prov_document_buffer = pkg_resources.resource_stream("examples", "f...
86e05289abe89905e6608fd3ba139f3e7d65ac8bac5181ee3e1889b0da4e71d8
Python
2,505
55
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://w...
7a8bdd92e2fdf2afda0b1c6959b6afd23a012e4b65e9274e0911d0dfecbf9d66
Python
2,506
58
import numpy as np import pandas as pd def analyze_switch( sub_data, num_pre_switch_trials, num_post_switch_trials, switch_key="is_switch", correct_key="is_correct_cue", ): """ Analyzes the choice accuracy window around rule switch events to create an average learning curve (e.g., how ...
826c336c862dc93191ea3f4473949cef4501c1968202081ee64a6e8c1d0f260c
Python
2,506
64
# %% from urllib.request import urlretrieve from bs4 import BeautifulSoup import os import shutil # %% def resolve_symlinks_in_html(url, save_path): # Download the HTML file urlretrieve(url, save_path) # Parse the HTML file with open(save_path, 'r') as html_file: soup = BeautifulSoup(html_file...
570491f5db27183ed59296373997159fb203dedea82c183001d36199e4cb377c
Python
2,508
99
from __future__ import annotations from pathlib import Path import sys from nipype.utils.filemanip import which import pytest from heudiconv.cli.run import main as runner from heudiconv.queue import clean_args from .utils import TESTS_DATA_PATH @pytest.mark.skipif(bool(which("sbatch")), reason="skip a real slurm ...
b189760d5b15ddc9a1bea43f1585338acd25375ed119d1a50cd48769f87c7529
Python
2,509
70
# SPDX-License-Identifier: Apache-2.0 import numpy as np import cv2 as cv from PIL import Image import cityscapes_labels def get_palette(): # get train id to color mappings from file trainId2colors = {label.trainId: label.color for label in cityscapes_labels.labels} # prepare and return palette palett...
f88184c9c088b894e2e56a15fe27ca0f4387b1d954ab873abe588666267aa43f
Python
2,509
79
from .common import * @pytest.fixture(scope="session") def adata_factory(): def adata_factory_(pca=False, n_top_genes=None, neighbors=False): adata = sc.datasets.paul15() adata.obs['celltype'] = adata.obs['paul15_clusters'] np.random.seed(42) adata.obs['batch'] = np.random.randint(...
2a4792a8f917bec78b747db9d2340a7f02749c775821f8c46e4c1bc7621c01e8
Python
2,510
97
# CURIE prefixes used in Babel # # The point here is to keep prefixes in one place so that we can easily deal with things like PUBCHEM->PUBCHEM.COMPOUND # In principle, we should generate this off of the context file? MESH = "MESH" NCIT = "NCIT" CL = "CL" CLO = "CLO" GO = "GO" FMA = "FMA" UBERON = "UBERON" SNOMEDCT = ...
0e424b8a7238c94863e8e4a6f7be72bfccfe083d13eaa2067689f0a5484593f6
Python
2,512
75
import click import subprocess from pathlib import Path import pandas as pd import torch from allertrans.model import load_models, predict_ensemble from allertrans.utils import load_h5_embeddings, load_esm_embeddings model_protT5, model_cat = load_models() @click.group() def run_cli(): """AllerTrans C...
54ebe6d5d65725365c5e493fe3bcbccac4cc14ab3b5705cc07b698e0ed174b6e
Python
2,512
49
## Restormer: Efficient Transformer for High-Resolution Image Restoration ## Syed Waqas Zamir, Aditya Arora, Salman Khan, Munawar Hayat, Fahad Shahbaz Khan, and Ming-Hsuan Yang ## https://arxiv.org/abs/2111.09881 ## Download training and testing data for Defocus Deblurring task import os # import gdown import shutil ...
81eda826299c51425251f0279ae37835accc3915c6e70d0f0ef7d504077f64ba
Python
2,512
81
_base_ = './maskformer_r50-d32_8xb2-160k_ade20k-512x512.py' checkpoint_file = 'https://download.openmmlab.com/mmsegmentation/v0.5/pretrain/swin/swin_tiny_patch4_window7_224_20220317-1cdeb081.pth' # noqa backbone_norm_cfg = dict(type='LN', requires_grad=True) depths = [2, 2, 6, 2] model = dict( backbone=dict( ...
be636faa9483718955c64eff7ca2354747908821f8a4dc537d983ef005ee6399
Python
2,512
79
checkpoint_file = 'https://download.openmmlab.com/mmsegmentation/v0.5/pretrain/swin/swin_small_patch4_window7_224_20220317-7ba6d6dd.pth' # noqa _base_ = './maskformer_r50-d32_8xb2-160k_ade20k-512x512.py' backbone_norm_cfg = dict(type='LN', requires_grad=True) depths = [2, 2, 18, 2] model = dict( backbone=dict( ...
c74374b0aa676a7861deaf4300826d06a191e014571c974b5b78ebb47f492569
Python
2,512
75
from CybORG.Shared import Observation from CybORG.Simulator.Actions import Action from CybORG.Simulator.Actions.ConcreteActions.DensityScout import DensityScout from CybORG.Simulator.Actions.ConcreteActions.SigCheck import SigCheck class Analyse(Action): """ Checks for malware on a single host. Targets a sin...
9f6352d3314d509812d5011503e634adb6717d88204545c05493fe2cdfd9dad3
Python
2,513
77
import shutil from pathlib import Path import pytest from guppy.testing import compare_output_folders from guppy.testing.api import locate_run_folder, step1, step2, step3, step4 from guppy_test_data import TESTING_DATA, event_ts_offset_for CONSISTENCY_CASES = [ ( "SampleData_csv/sample_data_csv_1", ...
a593dd37c04c1eead9c41125817a5fb77b46237d4aeb7cccbc373084b92e05b2
Python
2,514
71
"""Filesystem extension for loading files from registered providers.""" import typing as t from pathlib import Path from fsspec.implementations.dirfs import DirFileSystem from fsspec.implementations.local import LocalFileSystem from zndraw.extensions.abc import Category, Extension from zndraw.io import open_frames ...
4fdd020e5670b2dabc5b1dc4505765cbe9ef92d752cca29552d13e8b426add38
Python
2,515
107
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 25 13:55:49 2023 @author: george """ import numpy as np import pandas as pd import pyqtgraph as pg import os import skimage.io as skio from skimage.filters import threshold_otsu from skimage import data, color, measure from skimage.transform import...
f746622feb2e089a3c745f4eba937f541b83a7d27ad123541583bcea6fa0d34f
Python
2,515
85
from copy import deepcopy from medperf.exceptions import InvalidArgumentError from medperf.tests.mocks.benchmarkmodel import generate_benchmarkmodel import pytest from medperf.commands.association.priority import AssociationPriority TEST_ASSOCIATIONS = [ generate_benchmarkmodel(priority=0, model=1), generate_...
fc0d781747ede9f2fd33ae1f452c2552e403e8ea6998b79c0fc00053f5217b0f
Python
2,515
68
import shutil from batchgenerators.utilities.file_and_folder_operations import * import SimpleITK as sitk from nnunet_mednext.paths import nnUNet_raw_data if __name__ == '__main__': #data is available at http://medicalsegmentation.com/covid19/ download_dir = '/home/fabian/Downloads' task_id = 69 task...
5bc081797d0ae985070bd842b0264360983a3c6f7e0aa5db0e6b558b9e309a52
Python
2,516
59
import nibabel as nib import numpy as np import matplotlib.pyplot as plt # Load the first Jacobian determinant map # mouse jacobian # jacobian_img_1 = nib.load('b0_correction_analysis/data/phantom_jacobian/jacobian_determinant_b0.nii') jacobian_img_1 = nib.load('b0_correction_analysis/data/mouse_data/mouse_ph...
f7fdddd352c6323cc0bff439ce85149be577916ca68efd665a5a1fe953042fa4
Python
2,517
71
import requests from medperf.exceptions import CommunicationRetrievalError from medperf import config from medperf.utils import remove_path, log_response_error from .source import BaseSource import validators import os class DirectLinkSource(BaseSource): prefix = "direct:" @classmethod def validate_resou...
fdf599e273636c95510435cecb80b7e34b62278c7a3d47d5e95b436528f7e600
Python
2,518
83
from .ProvenanceObject import ProvenanceObject from .extractor_cartridge import ExtractorCartridge from .extractor_extension import ExtractorExtension class Extractor(ProvenanceObject): """ This class represents and conceptual extractor. Attributes: - tag (str): Extractor tag. - cartridge...
e449ccc7d78517b57cdfec665b7cb888f1cdbdf0250859c8c8cef45130265bf2
Python
2,519
91
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # pyre-strict # pyre-ignore-all-errors[2,3] from typing import Any, Dict, Iterable, Iterator, Tuple from tabulate import tabulate class Registry(Iterable[Tuple[str, Any]]): """ The registry that provides name -> object mapping, to suppor...
6c8120210ac2c6c100c368b83f853e0621715bdd2b7d74b77ccd6dc405016947
Python
2,523
71
import torch def init_edge_rot_mat(edge_distance_vec): edge_vec_0 = edge_distance_vec edge_vec_0_distance = torch.sqrt(torch.sum(edge_vec_0**2, dim=1)) # Make sure the atoms are far enough apart #assert torch.min(edge_vec_0_distance) < 0.0001 if torch.min(edge_vec_0_distance) < 0.0001: ...
dad0b2f06fca6568e1ac6b4ca48657bf75727f29faeacb2b3990505b67f5a25a
Python
2,523
82
_base_ = [ '../_base_/models/san_vit-b16.py', '../_base_/datasets/coco-stuff164k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py' ] crop_size = (640, 640) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations'), dict( type='RandomChoiceResiz...
0edffde506b26fe84e24aeba831cbe96f16742390724486e9aa49618bdd257fa
Python
2,525
77
from fastapi import Query, Request, Form, APIRouter, status, Security from fastapi.responses import HTMLResponse, RedirectResponse from medperf.web_ui.auth import security_token, AUTH_COOKIE_NAME from medperf.web_ui.common import templates, api_key_cookie, sanitize_redirect_url from medperf.utils import print_web...
33f4ca4cd7c11dbb077c119ba3ebfcadac936598a5c17b56f4afedc919e55a8f
Python
2,525
72
from __future__ import annotations from typing import Any import numpy as np from CybORG.Agents.Wrappers import BlueEnterpriseWrapper from ray.rllib.env.multi_agent_env import MultiAgentEnv class EnterpriseMAE(BlueEnterpriseWrapper, MultiAgentEnv): """A wrapper designed to support CAGE Challenge 4 (RLlib Compat...
56cb694dc7fca3141cf23c05d5c8cfc06520d5882e5d0180d96ff2397d3fbc9d
Python
2,526
68
import torch from torch.optim import AdamW, SGD from torch.utils.tensorboard import SummaryWriter from torch.optim.lr_scheduler import CosineAnnealingLR, OneCycleLR from yolov9_model import YOLOv9_GPU, YOLOv9_FPGA from dataset_preprocessing import get_datasets, get_data_loaders import torch.nn as nn class FocalLoss(nn...
d1fe3d81f28d554c784702550a9eac2a1fddef9fdd422070ed1788bbd5878f2b
Python
2,526
87
from __future__ import annotations from glob import glob import os import os.path as op from pathlib import Path import shutil import stat import pytest from .utils import TESTS_DATA_PATH from ..parser import get_extracted_dicoms def _get_dicoms_archive(tmpdir: Path, fmt: str) -> list[str]: tmp_file = tmpdir /...
d3ac93e9e158d00783e7996ec9ba4d3580a5369c247f4f297bf674d3d4864b77
Python
2,526
95
from itertools import chain from typing import Generator, Any, Dict, Optional from kgx.config import get_graph_store_class from kgx.graph.base_graph import BaseGraph from kgx.source.source import Source from kgx.utils.kgx_utils import sanitize_import class GraphSource(Source): """ GraphSource is responsible ...
7f322c361b988d461b6c6cb49ffbff83cebb7bc56e27a41d81f79a9345de39c3
Python
2,528
72
# -*- coding: utf-8 -*- # Albert Cardona 2014-11-21 # This file is meant to be run from within ./manage.py shell in the environment, like: # [1] load export_all_csv.py # [2] project_id = 12 # [2] export(project_id, "all") from django.db import connection from django.db import transaction import gzip def writeOneSkel...
1d0f5e5770e3e27c748229e1d5f069f12ffda0e7f08d0a9fed02baf6e4fe10c4
Python
2,529
65
import sys sys.path.append('/home/luxin1/stGRL') from stGRL import stGRL import os import torch import pandas as pd import scanpy as sc from sklearn import metrics import tqdm import numpy as np import matplotlib.pyplot as plt from pathlib import Path sample_list = ['151507', '151508', '151509', '151510', ...
b51bd422b4219f4b70a605d8d319ad58d97289bb6080eeca6e1d2e9945fc0f94
Python
2,530
69
# tests/test_router_job_list.py """Tests for job listing and details endpoints using shared fixtures.""" import pytest from conftest import make_room_address from zndraw_joblib.exceptions import ProblemDetail from zndraw_joblib.schemas import JobResponse, JobSummary, PaginatedResponse @pytest.fixture def multi_job_...
f04940f171a3b69c316280694f1a38d4425dfd113128cb90509df39b510f86c1
Python
2,530
71
import pytest from unittest.mock import patch, MagicMock from requests.exceptions import HTTPError from neuprint import Client from neuprint.tests import NEUPRINT_SERVER, DATASET def test_arrow_endpoint_version_check(): c = Client(NEUPRINT_SERVER, DATASET) # Test with version higher than 1.7.3 with p...
68bdc3b97da82e43b01fad45583bde0dc5ad564d8eccd3fc99ee86fe28d10670
Python
2,531
93
import os import sys import subprocess from heudiconv.cli.run import main as runner from heudiconv.queue import clean_args, which from .utils import TESTS_DATA_PATH import pytest @pytest.mark.skipif(bool(which("sbatch")), reason="skip a real slurm call") @pytest.mark.parametrize( 'invocation', [ "--files ...
c82cab3f063d87393baec2f16bd911e5a39b8b61217be8756a7fe57f14eab890
Python
2,531
77
#!/usr/bin/env python import os import sys import time import yaml import hashlib import argparse from six.moves import urllib required_keys = ['caffemodel', 'caffemodel_url', 'sha1'] def reporthook(count, block_size, total_size): """ From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/ ...
07aac51f8b8862a1b85b8cada4c2f97196a43fdf87b57eba8e38f5115f487043
Python
2,532
59
import imageio from create_dataset import * from utils import * from PDFN import PDFN from options import * from saver import resume, save_img_single from tqdm import tqdm #from thop import profile def main(): # parse options parser = TestOptions() opts = parser.parse() # define mod...
e0c9b017c62c83692a0c205f365209a0400aa408e85d4bb376405f37dee90d65
Python
2,532
90
"""Path tracing renderer configuration as a scene object.""" import enum from pydantic import BaseModel, ConfigDict, Field class EnvironmentPreset(enum.StrEnum): """HDRI environment preset options for path tracing.""" none = "none" apartment = "apartment" city = "city" dawn = "dawn" forest ...
b6b4972739174eabb4f3599ad6ec43e8d5083760ce9cc0118e823c08342da718
Python
2,533
80
from pysisyphus.constants import AU2EV, BOHR2ANG from mace.calculators import mace_off_finetuned, mace_off import torch def get_mace_calculator(device="cpu", ver='finetuned'): # Disable CUDA if using CPU to prevent CUDA initialization errors if device == "cpu": # Temporarily disable CUDA to prevent ini...
3f906bb9538805b12bb922d06ca7e9af6e94471cf1923b25cc94740146a9b776
Python
2,534
65
from grid_cell.lole import LOLE, LOCF from grid_cell.manifold_fitter import label_mesh from sklearn.linear_model import MultiTaskLasso, LinearRegression, LogisticRegression from grid_cell.grid_cell_processor import Speed_Processor from global_setting import * def compute_locf(label, feamap, x_bound, y_bound, speed_mi...
a39d1f996e395c2d3f4ad91572cc6dc9fe958c3e928536a39652d347cde3501d
Python
2,534
74
#!/usr/bin/env python # -*- encoding: utf-8 -*- from fastapi import FastAPI from pydantic import BaseModel import os import sys # 导入功能模块目录 sys.path.append("../") from qa_chain.QA_chain_self import QA_chain_self # os.environ["HTTP_PROXY"] = "http://127.0.0.1:7890" # os.environ["HTTPS_PROXY"] = "http://127.0.0.1:7890" ...
85698c1be8dc0ead09457e77caeffa76966b326d15cf857ec0e386835323ab94
Python
2,535
49
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://w...
be114c33749dfa1de946cb1ce14ae2804055d4bc47bbd659a53bd4fba84a18cc
Python
2,535
77
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os.path as osp from mmengine.config import Config, DictAction from mmengine.utils import ProgressBar from mmseg.registry import DATASETS, VISUALIZERS from mmseg.utils import register_all_modules def parse_args(): parser = argparse.ArgumentPa...
c36ae02aab5838b721bbe9d7529f45e4bcd2baff025300edcc96f83e15e89faa
Python
2,535
59
import imageio from create_dataset import * from utils import * from PDFN import PDFN from options import * from saver import resume, save_img_single from tqdm import tqdm #from thop import profile def main(): # parse options parser = TestOptions() opts = parser.parse() # define mod...
b3837b54631bb6855e32bc7eee1109d9ae06c980a736deaf855066915e962ee0
Python
2,537
95
""" Demo for using cross validation =============================== """ import os import numpy as np import xgboost as xgb # load data in do training CURRENT_DIR = os.path.dirname(__file__) dtrain = xgb.DMatrix( os.path.join(CURRENT_DIR, "../data/agaricus.txt.train?format=libsvm") ) param = {"max_depth": 2, "et...
8c637fc1f662d693d636b0d9314ccf636ca7c14db5b68f5769bfc9d5a73838d3
Python
2,538
72
from behavior_analysis.experiment import PreyCaptureExperiment, TrialData import numpy as np import h5py from sklearn.decomposition import PCA from collections import defaultdict if __name__ == "__main__": # Experiment directory = r"D:\percomorph_analysis" video_directory = None expt = PreyCaptureEx...
ca8897d3cec42d8f3c1d6605297834585cbf5234ed701cb9fc664f7750728865
Python
2,538
85
from collections import Counter import numpy as np from rdkit import Chem from rdkit.Chem import Descriptors from simgen.analysis import ( BaseReport, RDKitReport, analyse_base, analyse_rdkit, ) from simgen.utils import initialize_mol def test_analyse_base(): atoms = initialize_mol("C") repo...
e0ea47e729cfadad018544e13aab0ff1c35394043d12e5b0fc15261ffa8c81bf
Python
2,538
67
#!/usr/bin/env python3 # -*- coding:utf-8 -*- ### # File: /root/CAMP/std_logger.py # Project: /home/richard/projects/CAMP # Created Date: Saturday, July 30th 2022, 3:51:24 pm # Author: Ruochi Zhang # Email: zrc720@gmail.com # ----- # Last Modified: Sun Aug 28 2022 # Modified By: Ruochi Zhang # ----- # Copyright (c) 202...
3079a8664ab7a5d04e05143766401a582b4bfb3c4c8e747399ce7bb4d92f27c4
Python
2,539
57
from grid_cell.util import compute_correlation_and_p_values import numpy as np import seaborn as sns import matplotlib.pyplot as plt import hickle as hkl import os from global_setting import * def compute_corr(label, axes, fmt='.2f', feature_names=['x', 'y', 't', 'speed']): correlation_matrix, p_value_matrix = com...
68462d0c8bcf617ba5a29d3452550ff2f59ae9cf7e42ca06525dc2cb90758a29
Python
2,539
74
'''Mixin class to make dictionaries''' from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import # Disabling lines below, generate error when loading ephys.examples # from future import standard_library # standard_library.instal...
5ae5749d6ad59b3a03313f4555eb021339d7a3c69ef4a2e0ef03cbfc54ebeef6
Python
2,541
56
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Read the CSV files into DataFrames df = pd.read_csv('../CSV/Predictions/auc_random_mol6710_classification.csv') df2 = pd.read_csv('../CSV/Predictions/auc_random_mol6710_regression.csv') df3 = pd.read_csv('../CSV/Predictions/auc_random_m...
603a0263c4deb86570b017e3900a3af89418d6e172d117e4ff108c2c9cea26c9
Python
2,541
75
import pytest from unittest.mock import MagicMock, patch import random import numpy as np import keras from keras import ops import matplotlib.pyplot as plt import tsgm def _get_labels(num_samples, output_dim): labels = None for i in range(num_samples): sample = random.randint(0, output_dim - 1) ...
9bd6286157a7be32d5b95c9521e06526f0696c51f9495ad0cfb5cb047c6d17d0
Python
2,542
75
# %% import os, glob from os.path import join # %% def extract_bids_metadata(filename): """ Extract BIDS (Brain Imaging Data Structure) metadata from a given filename. Parameters: filename (str): The filename from which to extract metadata. Returns: dict: A dictionary containing the extracted ...
ebb6b17c3c0f0927d939fbddf448bce452c2bcb56239604c90fa66def2b3796b
Python
2,542
70
import mne from scipy.signal import detrend import sys, os from tqdm import tqdm from glob import glob import numpy as np import itertools import pandas as pd import pickle # go to base directory and import globals base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #ptmp_dir = "/ptmp/kroma/m4d/" os...
ec51a538e3def7a8a10bf869b9c6e63cd6abdebd16539920dd14174caf16536c
Python
2,543
61
# -*- coding: utf-8 -*- import json from django.http import HttpRequest, JsonResponse from django.shortcuts import get_object_or_404 from catmaid.models import UserRole, Project from catmaid.control.authentication import requires_user_role from catmaid.control.graph import _skeleton_graph from catmaid.control.skelet...
15ef1b5cfba0608d5d120c33c17ff350e1e6f15314324006f24eb0b1498d7f38
Python
2,546
87
import logging from fastapi import APIRouter, Depends, Form, Request from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse from medperf.entities.asset import Asset from medperf.commands.asset.submit import SubmitAsset from medperf.entities.model import Model import medperf.config as config from ...
7063155cea306998f53cb844e31ed4b56b9a3011ab19e891a5490e491b0e66a6
Python
2,550
81
import pytest from medperf.exceptions import MedperfException from medperf.commands.mlcube.utils import check_access_to_container from medperf.tests.mocks.cube import TestCube PATCH_UTILS = "medperf.commands.mlcube.utils.{}" CONTAINER_ID = 1 USER_ID = 100 @pytest.fixture def mock_user(mocker): mocker.patch( ...
6b3051204374920f9b2ed70a366b6e53635338aa4611dc3e0bfeae2f002bd201
Python
2,553
47
"""medperf URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based...
47b1f872de3fb95323fd5932ca03b28d939e7201ef76e05b5a7a4190ce343aa0
Python
2,554
79
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from pathlib import Path base_path = Path("aDBS_UPDRS.csv") df = pd.read_csv(base_path) metrics = ['total_updrs_iii_score', 'updrs_iii_bradykinesia', 'updrs_iii_tremor', 'updrs_iii_rigidity'] metric_labels = ['Total MDS-UPDRS III Score','Brady...
75a0993843a06a3f43751aeb13f750998ba880753900ae0bfe8670937f7497d9
Python
2,554
67
from os import path as osp from torch.utils import data as data from torchvision.transforms.functional import normalize from basicsr.data.data_util import paths_from_lmdb from basicsr.utils import FileClient, imfrombytes, img2tensor, scandir class SingleImageDataset(data.Dataset): """Read only lq images in the t...
77ab503b7780c11cb7c99d41e96b9c108de45b50dec95dd52e3f86f973534ea5
Python
2,554
83
from nnunet_mednext.network_architecture.mednextv1.MedNextV1 import MedNeXt def create_mednextv1_small(num_input_channels, num_classes, kernel_size=3, ds=False): return MedNeXt( in_channels = num_input_channels, n_channels = 32, n_classes = num_classes, exp_r=2, ...
14d58c0853b902feca69b80dc10acb0f5a841667530c53a90009e34a48c63efb
Python
2,555
56
#!/usr/bin/env python """ Use the openmoltools wrappers of OpenEye and Antechamber to rebuild input files for the FreeSolv database. Looks for freesolve database using environment variable FREESOLV_PATH Outputs two LOCAL directories of files: ./tripos_mol2/ and ./mol2files_gaff/ """ import os import openmoltools impor...
87816616474ad9fa0aa53860f1aa594b39822ca0dd0e05649c8413602f500206
Python
2,555
86
# written by Lee Hwee Kuan, 31Dec2021 # written by Lee Hwee Kuan, 11Feb2022 # # the problem with cosine annealing is that the lr oscillates and # at larger lr, it can throw off the optimiser. usually cosine lr # scheduler is use for small enough max lr. added a functionality # that have a decay max lr but operate li...
cfcb9ccc774eb16ee7a99a3a8b62abb02f74e886be815b9464ba80770c214947
Python
2,555
98
from medperf.exceptions import InvalidArgumentError import pytest from medperf.commands.benchmark.update_committee_members import UpdateCommitteeMembers def test_both_file_and_list_raises(): # Act & Assert with pytest.raises(InvalidArgumentError): UpdateCommitteeMembers( 1, co...
70185abcf616fb36081fb63c7b12c91dea54fdf53cce3e992ce0273b61e7f502
Python
2,556
90
import os import shutil from utils import get_collaborator_cn def collaborator_pre_training_hook( data_path, labels_path, node_cert_folder, ca_cert_folder, plan_path, output_logs, init_nnunet_directory, workspace_folder, ): import nnunet_setup cn = get_collaborator_cn() o...
d89ffce1dbdd9ba06e7b4554bd2053becc91932f47b63754d653856cced9ae79
Python
2,559
75
# MagellanMapper unit testing for detector """Unit testing for the MagellanMapper detector module.""" import unittest import numpy as np from magmap.cv import detector class TestDetector(unittest.TestCase): def make_random_blobs(self) -> "detector.Blobs": """Make blobs with random coordinates. ...
18dd13ae327d11264a60f782629c2f3a5fdf7b1bd924467378e3fea3a72170e3
Python
2,561
79
# Copyright (c) OpenMMLab. All rights reserved. import torch from torch import nn as nn from torch.nn import functional as F class LinearAttention(nn.Module): """Multi-Head linear attention proposed in "Transformers are RNNs". Source: https://github.com/KU-CVLAB/CAT-Seg/blob/main/cat_seg/modeling/transformer...
824706009b2f87607d9d684fd730fd87fd66ee8341e075ee01a072f2be05c8ea
Python
2,561
70
"""Unit testing for the chunking module""" import unittest from typing import Sequence import numpy as np from magmap.cv import chunking, detector from magmap.settings import config class TestChunking(unittest.TestCase): @staticmethod def stack_split_remerge( roi: np.ndarray, max_pixels: S...
76420afa7f91ae784cef0ef9c92292b00f6c0ee86dc57f8036f55e1756d27e80
Python
2,565
58
import nibabel as nib import numpy as np from sklearn.preprocessing import normalize from nilearn import masking def filter_voxels_by_patient_count(lesion_files, min_patient_count, normalize_vector, output_folder): """ Filter voxels by the number of patients they are involved in. """ no_of_pat...
c4d5e7c02d498f2b9f0ea3c5cb88bf3fedaa5b01a6a13fe8c7c285564b77d55c
Python
2,565
65
import io import pickle from pathlib import Path from typing import Callable, Optional, Tuple, Sequence, Union import numpy as np import torch class DiskCachedDataset(torch.utils.data.Dataset): def __init__(self, dataset:Sequence, cache_path: Union[str, Path], num_copies: int = ...
552924f21cb8737c4dd7bd222f084839cc282eac208517bee9f2d1e73c2b25bc
Python
2,566
70
from CybORG.Agents import BaseAgent from CybORG.Shared import Scenario from CybORG.Shared.RewardCalculator import RewardCalculator class ScenarioGenerator: """The ScenarioGenerator class is an abstract class that defines the interface for other ScenarioGenerator classes. Attributes ---------- updat...
642c6c588330f664f31d000877eb83fc4ac32ce7a600bca245d13e99cedc545f
Python
2,567
89
import os import argparse import SimpleITK as sitk import numpy as np def check_subject_validity(subject_dir): """Checks if a subject folder is valid. Args: subject_dir (str): The subject folder. Returns: bool: True if the subject folder is valid, False otherwise. """ subject_va...
cad2b558644c233b69b254ef26f0389a41781f60443a6515356e35aecba17698
Python
2,568
59
from jaxkineticmodel.load_sbml.sbml_model import SBMLModel import jax.numpy as jnp from jaxkineticmodel.utils import get_logger from jaxkineticmodel.simulated_dbtl.dbtl import DesignBuildTestLearnCycle logger = get_logger(__name__) # load model (Messiha et. al (2013)) filepath = ("models/sbml_models/working_models/Mes...
28ea1576377c781eb0aa406a155658aed857266f9c0956d749b6feec6d31edbf
Python
2,569
67
import medperf.config as config from medperf.entities.aggregator import Aggregator from medperf.entities.training_exp import TrainingExp from medperf.entities.cube import Cube from medperf.utils import remove_path class SubmitTrainingExp: @classmethod def run(cls, training_exp_info: dict): """Submits ...
57e32e17d65d4c2d0076f424e07642aad40e1c9e998e437af61ec3595e961b6a
Python
2,571
67
#!/usr/bin/env python3 # -*- coding:utf-8 -*- ### # File: /root/CAMP/std_logger.py # Project: /home/richard/projects/pepland/inference/cpkt/model/code/utils # Created Date: Saturday, July 30th 2022, 3:51:24 pm # Author: Ruochi Zhang # Email: zrc720@gmail.com # ----- # Last Modified: Sat Dec 23 2023 # Modified By: Ruoch...
b7f3dcaf7abb080f6285d01f28a69c1ca817dcd8a5f2da1deaff488eee4b0097
Python
2,572
62
"""Live contract tests for :mod:`guppy.utils.dandi_filter`. These hit the real DANDI Archive and are intended for **local use only**. They are deselected in CI (see ``.github/workflows/run-tests.yml``) because the archive is subject to network flakiness and its contents change as datasets are published. Run locally w...
5cac0f2022d8bc319e8e332d13c85feedc8c80961ba0661666a9889055ee3173
Python
2,574
70
# pytest unit tests for sct_crop_image import pytest import logging from spinalcordtoolbox.image import Image from spinalcordtoolbox.scripts import sct_crop_image from spinalcordtoolbox.utils.sys import sct_test_path logger = logging.getLogger(__name__) @pytest.mark.sct_testing @pytest.mark.parametrize("path_in,pa...
d7ef027834322b4ea0e10a7344723647b7a78993c523a33d73ea337397070ddd
Python
2,574
53
import catmaid.fields import datetime from django.conf import settings import django.contrib.postgres.fields.jsonb import django.contrib.postgres.functions from django.db import migrations, models import django.db.models.deletion forward = """ ALTER TABLE catmaid_deep_link DROP CONSTRAINT catmaid_deep_link_active...
5483b4f1490280ea2e44f3cdea23256f6c2fb667a4badde3f54d3b7a2ade5791
Python
2,575
66
import yaml import typer from prepare import prepare_data from sanity_check import check from stats import get_stats app = typer.Typer() @app.command("prepare") def prepare( data_path: str = typer.Option(..., "--data_path"), labels_path: str = typer.Option(..., "--labels_path"), params_file: str = typer....
757e69a1af34ea38aeac69bdbe93030d273dd1a93662f3ed10ae63e8b9a217df
Python
2,575
96
"""Smoke tests confirming APSO works as used in the Poison26 singularity container. Mirrors the workflow in manuscripts/Poison26/bin/attack/poison_MNIST.py. """ import pytest import torch import torch.nn as nn from Adversarial_Observation.Swarm import PSO IMG_DIM = 1 * 28 * 28 N_PARTICLES = 10 TARGET_CLASS = 3 @pyte...
870900d68c15f4a4a2cd21d72a57d886b496d0ed65cf0ebf5de6868f19323073
Python
2,576
84
import os from grid_cell.gkr_fitting_helper import load_and_process_data, fit_gkr_models import hickle as hkl import numpy as np from global_setting import * dataset_name = ['r1m1', 'r1m2', 'r1m3', 'r2m1', 'r2m2', 'r2m3', 's1m1', 'q1m1', 'q1m2'] preprocessed_file_name = 'preprocessed_data_OF.hkl' n_sample_data = 10000...
2a98693b532536b9e1dfdfa6abf870a2b74be93f0fda45b9b98134f05871debc
Python
2,577
76
# Copyright (c) OpenMMLab. All rights reserved. import pytest import torch from mmseg.models.decode_heads import ASPPHead, DepthwiseSeparableASPPHead from .utils import _conv_has_norm, to_cuda def test_aspp_head(): with pytest.raises(AssertionError): # pool_scales must be list|tuple ASPPHead(in_...
a1411fd7135235f982e0c9ace3c717baaa56500d2c31aa947d705a13d7566d02
Python
2,579
59
import os from concurrent.futures import ThreadPoolExecutor, as_completed # Path to your main folder #main_folder = '/work/hdd/bbse/wklai/AdversarialData/APSO_Poison/manuscripts/POISON25/MNIST_train_model1' main_folder = '/work/hdd/bbse/wklai/AdversarialData/APSO_Poison/manuscripts/POISON25/MNIST_train_model2' def pr...
beb5518f4a519ab9168e11784fa5aaf623d0ae82cafa3a9164a76f749210b81a
Python
2,580
69
# Copyright (c) OpenMMLab. All rights reserved. import argparse import warnings from mmengine import Config, DictAction from mmseg.apis import init_model def parse_args(): parser = argparse.ArgumentParser(description='Print the whole config') parser.add_argument('config', help='config file path') parser...
f7a032b779acb0822d94238883c7272bb4fb94b43324b5cb4fac1ad91320ccd9
Python
2,580
63
import numpy as np import torch from torch.utils.data import Dataset class SyntheticVisualFlowDataset(Dataset): def __init__(self, num_samples=1000, dimensions=8, max_value=1, var_scaler=0.01, speed_func="random", num_speeds=11): assert speed_func in ["random", "random_walk", "mismatch"] assert di...
79d579faedca3f46c17cec7e91e4f55994319572576902bb5412bf702554d736
Python
2,581
76
""" Script to create symbolic links to data sources (to enable easier handling when training on different machines) """ import os.path import glob import numpy as np from utils import * # input and output folders: folder_in_WS = ("/PATH1/TO/CONVERTED/RAW/DATA/") folder_in_WS_sim = ("/PATH1/TO/SIMULATED/DATA/") folder_...
c771e95a76d398f90d5904ffd699b934f13feccd7fbeaf88ef62c243dc4138b9
Python
2,582
79
import os import random import json from tqdm import tqdm import argparse import pathlib import openai openai.organization = os.getenv('OPENAI_ORG') openai.api_key = os.getenv('OPENAI_API_KEY') from load_aokvqa import load_aokvqa random.seed(0) def main(): parser = argparse.ArgumentParser() parser.add_arg...
8b94cdafffb06dfdae98d71c5155b49ad11ed8460f3b5d079a82b85375ccb687
Python
2,583
82
import seaborn as sns import pandas as pd from qtools.data_tracking import metadata from qtools.variable_output_dims import ( create_lineplot, calculate_quartet_scores, calculate_losses, calculate_non_zero_features, load_json_as_table ) # Configuration MODEL_TYPES = ['siameseloss', 'quartetloss',...
b9071ef4db4e4374c9aca2650b26c14e32983152ab5646f5b6eb4023b5ff69f2
Python
2,587
84
import sys import os import time import random pwd = os.getcwd() # Print all command line arguments for i, arg in enumerate(sys.argv): print(f"Argument {i}: {arg}",flush = True) # Print all command line arguments random_sleep_time = random.uniform(5,10) print("Start : %s" % time.ctime(),flush = True) time.sleep( ...
ca59af61de932669c0b54cd4010a0d7dad8487b73883520d4e17a18f048b8b2d
Python
2,587
68
""" Example of training controller with NVFlare =========================================== """ import multiprocessing from nvflare.apis.client import Client from nvflare.apis.fl_context import FLContext from nvflare.apis.impl.controller import Controller, Task from nvflare.apis.shareable import Shareable from nvflare...
dbc1e72e5fa754cdc451382f914ebbe9cb2a593af9e9bd48b883b4c0601b453b
Python
2,589
58
from CybORG.Shared import Observation from CybORG.Simulator.Actions.ConcreteActions.TargetedLocalAction import TargetedLocalAction from CybORG.Simulator.Host import Host from CybORG.Simulator.Process import Process from CybORG.Simulator.State import State class StopProcess(TargetedLocalAction): """ A sub-action f...
ec2ad336c699d1d24fe77deb248c4b5bc75d08e40062d7325b0760c0fdd963f3
Python
2,589
95
"""MLCube handler file""" import typer import subprocess app = typer.Typer() def exec_python(cmd: str) -> None: splitted_cmd = cmd.split() subprocess.run(splitted_cmd, cwd=".", check=True) class PrepareTask(object): """ Task for preparing the data Arguments: - data_path: data locat...
36dca75fd607a262a6498df9e9908749cf9dcf2490f8e76a497786675eebe22c
Python
2,590
102
import os from kgx.transformer import Transformer from tests import RESOURCE_DIR, TARGET_DIR def test_jelly_roundtrip_basic(): """ Test basic roundtrip: transform TSV to Jelly format and back. """ input_args = { "filename": [ os.path.join(RESOURCE_DIR, "graph_nodes.tsv"), ...
6b816d5d13fbe56ccba9f81f096d554013380c6430ee5be5c5408237714fc2b5
Python
2,590
88
# model settings backbone_norm_cfg = dict(type='LN', eps=1e-6, requires_grad=True) norm_cfg = dict(type='SyncBN', requires_grad=True) data_preprocessor = dict( type='SegDataPreProcessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_val=0, seg_pad_val=255) mo...
07ee84bed2383a89f59eae715c4afabf849d04bcef158da3d5022e70be4485f2
Python
2,591
102
# -*- coding: utf-8 -*- import argparse import math # Respected precision epsilon = 0.001 def same(a, b, eps=epsilon) -> bool: return abs(a - b) < eps class Point3D: """A simple container to hold three coordinate values. """ def __init__(self, x, y, z): self.x, self.y, self.z = x, y, z ...
d417a6225ecb789e1aac4e3cc60ba7b8bafe05e65a743b47cd2f4e363c1dd2b1
Python
2,591
88
# model settings backbone_norm_cfg = dict(type='LN', eps=1e-6, requires_grad=True) norm_cfg = dict(type='SyncBN', requires_grad=True) data_preprocessor = dict( type='SegDataPreProcessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_val=0, seg_pad_val=255) mo...
16333c44f844127e9a0511275dbc8469b6bf2c034440f61034c847a5fdb3e9dd
Python
2,593
80
"""Experimental support for MPI.""" import inspect import os import re from collections.abc import Mapping, MutableMapping from typing import TypeVar from schema_salad.utils import yaml_no_ts MpiConfigT = TypeVar("MpiConfigT", bound="MpiConfig") MPIRequirementName = "http://commonwl.org/cwltool#MPIRequirement" cl...
e62b0359d1fa6b0c85d4187c2c1dc7306d2b6c4ebf405565990786985fc63684
Python
2,594
54
# Provided by the FeTS Initiative (www.fets.ai) as part of the FeTS Challenge 2022 # Contributing Authors (alphabetical): # Brandon Edwards (Intel) # Patrick Foley (Intel) # Sarthak Pati (Intel) # Micah Sheller (Intel) """This package includes dependencies of the fets project.""" from setuptools import setup with ...
91ed0b7dd4ad05b12c4c46529d8cd90d20ed8b07ef70959345e6d305e671dd48
Python
2,597
70
#!/usr/bin/env python3 # -*- coding:utf-8 -*- ### # File: /home/richard/projects/biology_llm_platform/mlm/pepland/inference.py # Project: /home/richard/projects/biology_llm_platform/mlm/pepland # Created Date: Thursday, November 28th 2024, 10:05:57 am # Author: Ruochi Zhang # Email: zrc720@gmail.com # ----- # Last Modi...
9369fefa92aa6845f8f9734e84f4e3d5b544d155dfe96f85b08a5933b495fcab
Python
2,597
84
import logging from typing import Optional import torch from torch import nn from ocpmodels.common import distutils class L2MAELoss(nn.Module): def __init__(self, reduction: str = "mean") -> None: super().__init__() self.reduction = reduction assert reduction in ["mean", "sum"] def ...
d7bb787e7576274097fdb02d34583fa13f0f626646bbaef07b6abc8e016500fb
Python
2,597
83
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 13 17:33:14 2023 @author: george """ import warnings warnings.simplefilter(action='ignore', category=Warning) import numpy as np import pandas as pd from distutils.version import StrictVersion from tqdm import tqdm import os, glob, sys import skim...