sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
61a4c37ec918086e73ebf01cd63a1269db2678c7844d412b6087e1a4c1a83708 | Python | 3,295 | 100 | import torch
import numpy as np
from ._base import register_transform, _get_CB_positions
@register_transform('corrupt_chi_angle')
class CorruptChiAngle(object):
def __init__(self, ratio_mask=0.1, add_noise=True, maskable_flag_attr=None):
super().__init__()
self.ratio_mask = ratio_mask
se... |
635fe9fc1c4927241704ff263f4a6d7466a905f8814476a8900623c7032004a6 | Python | 3,295 | 99 | # FCN model
# when tuning start with learning rate->mini_batch_size ->
# momentum-> #hidden_units -> # learning_rate_decay -> #layers
import tensorflow.keras as keras
import tensorflow as tf
import numpy as np
import time
from utils.utils import save_logs
from utils.utils import calculate_metrics
class Classifier_... |
45bdb0a61dd4c1c6a848ada9c7aaa26d80ec10be5812e31f298a92cf4bd28f11 | Python | 3,296 | 90 | # -*- coding: utf-8 -*-
from os.path import dirname, join, realpath
import os
from shutil import copytree, copyfile
from jinja2 import Environment, FileSystemLoader
ONLINE_LIBS = ['js/FileSaver.js',
'js/StreamSaver.min.js',
'js/dark-mode-switch.js',
'js/scripts.js',
... |
4eeb4a9c33a82470e326d69e0ec74dc749a02e2b4921c48a9661ac0467b6a151 | Python | 3,296 | 131 | """Figures REST API endpoints for room Plotly figures."""
from fastapi import APIRouter, status
from sqlmodel import select
from zndraw.broadcast import broadcast_to_room
from zndraw.dependencies import (
AccessReadDep,
SessionDep,
SioDep,
WritableRoomDep,
)
from zndraw.exceptions import (
FigureN... |
4edb5f1bfc6902937f1a80cc07cbc233c6aef14cb41df4694f02662f0f96a364 | Python | 3,297 | 93 | 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.exceptions import CleanExit, InvalidArgumentError
from medperf.utils import (
approval_prompt,
dict_pretty_print,
gener... |
b02aa30f35231137d21b0980514f3b372d5c27315622245a661deba8b64437f8 | Python | 3,298 | 136 | import numpy as np
import pathlib as pl
from myphdlib.general.toolkit import psth, smooth
class Neuron():
"""
"""
def __init__(self, clusterNumber, singleUnitData, samplingRate=30000):
self.cluster = clusterNumber
self.clusterNumber = clusterNumber
clusterMask = singleUnitData[:, 0... |
fa82acb0608f375e133aecd4680c90ffa4062d5785b70fc78db5f68e05517721 | Python | 3,298 | 85 | # MLCube Entrypoint
#
# This script shows how you can bridge your app with an MLCube interface.
# MLCubes expect the entrypoint to behave like a CLI, where tasks are
# commands, and input/output parameters and command-line arguments.
# You can provide that interface to MLCube in any way you prefer.
# Here, we show a wa... |
1b97ffee2a30a56c7bdf522bd1593204eb2c08e29d6b0ca5619729666877471b | Python | 3,299 | 99 | import os
import networkx as nx
from kgx.graph.nx_graph import NxGraph
from kgx.graph_operations.clique_merge import clique_merge
from kgx.transformer import Transformer
from tests import TARGET_DIR, RESOURCE_DIR
prefix_prioritization_map = {"biolink:Gene": ["HGNC", "NCBIGene", "ENSEMBL", "OMIM"]}
def test_clique_g... |
6e4c4819d5d16b6bca3e5fd1dfbeabf42a93042901023fe277c1cfd467f52011 | Python | 3,299 | 60 | import os,shutil,argparse
def Extract_Files_From_Prep(sourse_path, target_folder, keyword_for_replace='.anat'):
"""[This Python script is used to copy the various preprocessed resulting images into the specified folder.]
Args:
sourse_path ([str]): [The path of folder which contains preprocessed images... |
d89f5fe2a22a9323497691035e2604d9ff6d45db6ff701eaacee9ae6fa77dd5e | Python | 3,299 | 120 | from functools import reduce
from io import BufferedReader
from provdbconnector.exceptions.utils import ParseException, NoDocumentException
import six
from prov.model import ProvDocument
import logging
log = logging.getLogger(__name__)
def form_string(content):
"""
Take a string or BufferedReader as argumen... |
a9feff070a9db8b2dddf803dfc663c14849b0f9568d1d3d47da7501da4b49308 | Python | 3,300 | 84 | """Regression tests: non-superuser stranger must not read content from a private room.
Covers the existence-leak + unauthorized-read vulnerability in frames /
trajectory / screenshots / isosurface / progress / frame-selection routes.
"""
import pytest
from helpers import _register_and_login, create_room_via_api, crea... |
89801824e6f3547d607fb247642049b1e4d84fb67eb5f7cfab2ec8d4caca1e26 | Python | 3,302 | 94 | """
Fetch HCP/Neurosynth/Allen Human Brain Atlas/etc cortical maps and distance matrices and eigenmodes
"""
from pathlib import Path
import os.path as op
import numpy as np
from eigenstrapping_analysis.datasets.data_fetcher import fetch_data
from eigenstrapping_analysis.utils import (
get_rootdir, get_medial, joi... |
bee4f999511340ca2b97651fce339e837fd01c8a51b343525ce189d56d952e87 | Python | 3,302 | 99 | #!/usr/bin/env python3
"""
Rebuild KGX Schema Script
This script orchestrates the process of building the complete KGX schema:
1. Starts with core kgx.yaml that imports biolink
2. Materializes the imports to create a merged schema
3. Generates a transformation spec for adding inheritance relationships
4. Applies the t... |
3e978e6185d6b09b9963293a5fead1071adcad9463c64f34d109a1acbf51db60 | Python | 3,303 | 98 | import torch
from timm.scheduler.cosine_lr import CosineLRScheduler
from timm.scheduler.step_lr import StepLRScheduler
from timm.scheduler.scheduler import Scheduler
def build_scheduler(args, optimizer, n_iter_per_epoch):
# num_steps = int(args.epochs * n_iter_per_epoch)
# warmup_steps = int(args.warmup_epoch... |
0e0965ded14bf78110bfd3accd64c00fb66535a949a491a05c1211aaead5007e | Python | 3,304 | 110 | from Utils.dataloader_BrainTumorMRI import *
from Utils.config import *
from Utils.models import *
from Utils.TrainModel import *
from multiprocessing import Process
from codecarbon import EmissionsTracker
def task(lr, data_partition:float=None, run_idx:int=None, backbone:str='dense121'):
_cuda = 'cuda:0'
_i... |
5827be7f2d1ee36985c74c9028ec7053a8b84ced1199ae127e525d39a7579177 | Python | 3,304 | 94 | from behavior_analysis.kinematics import find_threshold
import h5py
import json
import numpy as np
import pandas as pd
from experiment import *
if __name__ == "__main__":
for species in expt.species_names:
print(species)
params = get_params(species)
# Get params
n_components = ... |
b37f1119d2e5d0cd8e046e4dabe90ceb442a475c9e3c2ca8533f11dd71fb8ded | Python | 3,306 | 69 | #################################
#Generating simulation data(missing cell, shifting cell coordinates, cell type misclassification )
#Reproducibility for Figure.2A,B,C
#################################
import igraph as ig
import pandas as pd
import random
import numpy as np
from sklearn.neighbors import NearestNeig... |
107117e58b418c2ccfa1e201ba344388464af9027b6c4372f36de8620682460f | Python | 3,307 | 102 | #!/usr/bin/env python
"""
MetaWIBELE: join_family_abundance module
Join the abundance of families
Copyright (c) 2019 Harvard School of Public Health
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Softwa... |
8813082008a254cb391d3490cdd337b4e58901ca848541a97880306f36133bb0 | Python | 3,307 | 85 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import numpy as np
import torch
# pyre-ignore-all-errors
def to_float_tensor(numpy_array: np.ndarray) -> torch.Tensor:
"""
Convert the numpy array to torch float tensor with dimension of NxCxHxW.
Pytorch is not fully supporting uint8... |
f08098c50bd1e237e213c07e56a40b71086992d5ec4fd8c5935ca5b396f50a1b | Python | 3,307 | 105 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import os
import shutil
import numpy as np
from dmriqcpy.io.report import Report
from dmriqcpy.io.utils import (add_online_arg, add_overwrite_arg,
assert_inputs_exist, assert_outputs_exist,
l... |
378ff15a443aa6d193fb056904f75f51f0ded98f56c304b3f61caee953b73d84 | Python | 3,308 | 103 | import logging
import random
import time
from dataclasses import dataclass
from functools import wraps
import pandas as pd
from DiastereomericResolutions.main.molecule_db import MoleculeDatabase
@dataclass
class RetryConfig:
times: int = 10
delay: float = 0.5
max_delay: float = 60.0
exponential: boo... |
7fe1c7e796b3b6c4d5b5ec561f9a18dc7e12e235d34ee4583aa5c9d04fb1f232 | Python | 3,308 | 80 | import torch
import torch.nn as nn
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, output_size, num_embeddings, final_activation):
super().__init__()
# padding_idx is important, otherwise predict... |
eb2cffd4d1e8af826f3f7e9dfcb6e631b59fc7b59ab8c3cc44039c0b04b0889e | Python | 3,309 | 100 | # pytest unit tests for spinalcordtoolbox.gui
import logging
import unittest
import spinalcordtoolbox.image as msct_image
from spinalcordtoolbox.gui import base, centerline, sagittal
from spinalcordtoolbox.gui.base import InvalidActionWarning
from spinalcordtoolbox.utils.sys import sct_test_path
logging.basicConfig... |
ce088d74bf774539c2f77f5c3a8643f241e692913f02d335c730ae757f91e40a | Python | 3,312 | 68 | import h5py
from experiment import *
import numpy as np
import pandas as pd
if __name__ == "__main__":
strike_dist_mm = params["strike_dist_mm"]
offset_time = params["strike_offset_time"]
min_mov_dist = params["min_prey_movement"]
for species_id in expt.species_names:
try:
ego_dir... |
419551792d127eb8084e4fb43b411f3450c797abff11c4bdf5f53e167ecaf267 | Python | 3,314 | 79 | """Mixin of contract tests for :mod:`guppy.utils.dandi_preview`.
Bound twice: once in ``test_dandi_preview.py`` against the mock NWB files in
``stubbed_testing_data/nwb/``, and once in ``test_dandi_preview_live.py`` against a real asset
streamed from the archive. The mock files are genuine ndx-fiber-photometry output ... |
b17ca1bc327caf0eac428c2916419b26b20872772de43458573e93af3773172e | Python | 3,315 | 74 | import numpy as np
import pandas as pd
from pathlib import Path
from sklearn.model_selection import train_test_split
from AddingLabel import adding_label
def random_splitter(df, repeat_split=10):
print('with all length', len(df))
df = df[df['Monomer_Length'].isin([6, 7, 10])]
print('length 6, 7, 10 only'... |
ca1ad6da0bd04cb7dc135eff1031c964aa6838edac242ddae336139619c7c238 | Python | 3,315 | 104 | import os
from ray import tune
import copy
CONFIG = dict()
common_config = {
"env": "MyEnv",
"trainer_config": { },
"env_config": { },
"framework": "torch",
"extra_python_environs_for_driver": { },
"extra_python_environs_for_worker": { },
"model": {
"custom_model": "MyModel",
... |
b2fe70cf36a8de2fa251721334f1e251831aadab6ad2a8e51db6036d226f459f | Python | 3,317 | 108 | import os
import json
import argparse
def get_parser():
parser = argparse.ArgumentParser(
description="Adds spatial reference information to json sidecars." )
parser.add_argument('-d',
required=True, help='Directory to process JSON files in')
parser.add_argument('-r',
... |
c6fc931ac546d5d1f19bd2bf84679aa42be3245412b4d4c02e89bf2b16ba473a | Python | 3,317 | 96 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmseg.registry import MODELS
from .decode_head import BaseDecodeHead
@MODELS.register_module()
class FCNHead(BaseDecodeHead):
"""Fully Convolution Networks for Semantic Segmentation.
This ... |
28c0aaae989fffc4cf23d9b3b8bd0b711ef7f4c96b946274d4ce2f2e8ce09dd3 | Python | 3,321 | 79 | import inspect
from pprint import pprint
from CybORG import CybORG
from CybORG.Simulator.Scenarios.EnterpriseScenarioGenerator import EnterpriseScenarioGenerator
from CybORG.Agents.SimpleAgents.ConstantAgent import SleepAgent
from CybORG.Agents.SimpleAgents.KeyboardAgent import KeyboardAgent
import argparse
def print... |
186d88e0c37250a0dfc4c4f94fbdf188776bf4587e12bea3efc2219defbfe473 | Python | 3,324 | 97 | #!/usr/bin/python
import logging
import os
import sys
from isorefiner.common import get_version, run_command
logger = logging.getLogger(__name__)
def main(args):
try:
# Set variables
raw_reads_files = [os.path.abspath(_) for _ in args.reads]
raw_genome_file = os.path.abspath(args... |
c37be815d4c44bbb20a2f1745bc1ac362cea4926833fe820dcd028b9009c8729 | Python | 3,325 | 103 | #!/usr/bin/env python
import argparse
import torch
import time
from models.model_MCMG import transformer_RL
from MCMG_utils.data_structs_GM import Vocabulary
from MCMG_utils.utils import seq_to_smiles
import pandas as pd
import gc
def Transformer_generator(restore_prior_from='Prior.ckpt',
... |
6ce52ef96b6131831cbbb6556033209da57b0a12058a75b93f2b582843e57001 | Python | 3,330 | 99 | import glob
import os
import numpy as np
from utils import DSC_computation
import yaml
def coarse_metrics(preds_path, labels_path):
metrics_dict = {}
labels = list(glob.iglob(os.path.join(labels_path, "*.npy")))
labels.sort()
for plane in "XYZ":
metrics_dict[plane] = {}
DSC = np.zer... |
d7058a17e8b73521e0c56d28c73f703846d0b87391b952bbe6494ba6c5113ba7 | Python | 3,331 | 92 | import numpy as np
from scipy.stats import chi2
from statsmodels.stats.multitest import multipletests
def LRTest(adata, Xc, Xg=None, index=None, add_intercept=True, **kwargs):
"""likelihood ratio test
layer_keys: ['isoform1', 'isoform2', 'ambiguous']
target: marginLik, ELBO
"""
## Fit the full... |
1f40ca606315841f7d952e97eb45d08171fa377a0b6a00a570a28072037a8981 | Python | 3,334 | 83 | """Tests for Socket.IO scaling with AsyncRedisManager."""
import os
import httpx
import socketio as socketio_lib
from socketio import AsyncRedisManager
from zndraw_socketio import wrap
class TestSocketIOClientManager:
"""Tests for Socket.IO client manager configuration."""
def test_async_redis_manager_can_... |
3c1ff2188a565bde5017cf8de1ae2ecb31c140742dc702c4e6fc6dc2e150c804 | Python | 3,335 | 100 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmengine import ConfigDict
from mmengine.structures import PixelData
from mmseg.models import build_segmentor
from mmseg.structures import SegDataSample
from .utils import _segmentor_forward_train_test
def test_encoder_decoder():
# test 1 decode ... |
a86a950919371cd38d76b32b5841cb884dbb290e6cee329ff4e357b09acb11b6 | Python | 3,336 | 119 | from __future__ import annotations
import logging
import os
import subprocess
import sys
from typing import Optional
from nipype.utils.filemanip import which
lgr = logging.getLogger(__name__)
def queue_conversion(
queue: str, iterarg: str, iterables: int, queue_args: Optional[str] = None
) -> None:
"""
... |
69356e189d653ff30f693e46616b8c40e1656875f7474a0607564ec7d98d1900 | Python | 3,339 | 86 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmseg.models.builder import LOSSES
@LOSSES.register_module()
class TreeTripletLoss(nn.Module):
"""TreeTripletLoss. Modified from https://github.com/qhanghu/HSSN_pytorch/b
lob/main/mmseg/mod... |
6b3435a8d47c4a9327fb2f2186cd667bcfef8610f98f9d097f650f502880f911 | Python | 3,339 | 116 | # Authors: Pierre Ablin <pierre.ablin@inria.fr>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Jean-Francois Cardoso <cardoso@iap.fr>
#
# License: BSD (3-clause)
import numbers
import numpy as np
def permute(A, scale=True):
'''Get a permutation to diagonalize and scale a matrix
Param... |
e81cde1a199ce3a30d7abe0ab733c24a10a288f51d56c0fdc0d2999416f4b2a2 | Python | 3,340 | 108 | import os
import ray
from ray import tune
from ray.tune import CLIReporter
from ray.tune.schedulers import PopulationBasedTraining
from ocpmodels.common.flags import flags
from ocpmodels.common.registry import registry
from ocpmodels.common.utils import build_config, setup_imports
# this function is general and sho... |
c5ecfedd9c098b9369d31e3a83168e5623e2f17ca62f02ecf085627b595dc7e5 | Python | 3,342 | 106 |
import pandas as pd
from jaxkineticmodel.parameter_estimation.training import Trainer
from jaxkineticmodel.load_sbml.sbml_model import SBMLModel
import jax.numpy as jnp
import numpy as np
import jax
import matplotlib.pyplot as plt
optimized_params_jkm=pd.read_csv("results/"
"PyPESTO... |
f3db0978c452dbe275337e94d3addd52c2f9122867c4f051f9738ac64826f4ae | Python | 3,343 | 84 | import numpy as np
import pandas as pd
from pathlib import Path
from sklearn.metrics import mean_absolute_error
# from ScaffoldSpliter import column_clean
def duplicate_checker(df):
value_counts = {}
# Iterate through the column
for value in df['Structurally_Unique_ID']:
# Increment c... |
a764c282bf422d80b980b8f42a083b0ddc5bd267d8b69404aac2161adf386b87 | Python | 3,346 | 93 | import numpy as np
from ase.build import molecule
from ase.calculators.mixing import LinearCombinationCalculator
from airss_baseline.calculators import (
MopacCalculator,
RestorativeCalculator,
)
def test_mopac_calculator():
atoms = molecule("H2O")
calc = MopacCalculator()
atoms.calc = calc
e... |
2fb96444e81801bd77eace12915914a1fe1819cb38b4fd458bca123068b17fcc | Python | 3,347 | 120 | """################################################################################
> # **Introduction**
> The notebook is divided into 4 major parts :
* **Part I** : define the functions
* **Part II** : optimization using the search algorithm
######################################################################... |
6f69ff22ce7e5149a9193f42d52702d32b04bdb1edde2d7989008cdec8eb3c7a | Python | 3,347 | 72 | # 3D Convolutional Neural Network is adoped from atom3d package
# https://github.com/drorlab/atom3d/blob/master/atom3d/models/cnn.py
import torch
import torch.nn as nn
from collections import OrderedDict
class Atom3DNetwork(nn.Module):
"""Base 3D convolutional neural network architecture for molecular data, consist... |
16347bcb3d4671a02fe3d57c93919c291b789386c3b353e08926f50b8bae58ef | Python | 3,349 | 110 | """MLCube handler file"""
import os
import shutil
import typer
from utils import setup_ws
from admin import (
get_experiment_status,
add_collaborator,
remove_collaborator,
update_plan,
)
app = typer.Typer()
def _setup(temp_dir):
tmp_folder = os.path.join(temp_dir, ".tmp")
os.makedirs(tmp_fol... |
6431199130935f52bffd8c4ac21158b7334d22ae29579a77eaf0b44ef08f4d0d | Python | 3,349 | 82 | import unittest
import numpy as np
from PyQt5 import QtGui
from features.EventDetection import BurstDetection
from tests.TestData import processed, DataManager, Plot, source, noise_std
from util.conf import bd_params
app = QtGui.QApplication([])
class BurstDetectionTest(unittest.TestCase):
def setUp... |
e15bd0c2f04c1196f574cfe9453acb05ef8c4cee440f33b25665558a824d6d4f | Python | 3,353 | 100 | import yaml
import json
from typing import Union, Type
from medperf import config
from medperf.account_management import get_medperf_user_data
from medperf.entities.interface import Entity
from medperf.exceptions import InvalidArgumentError
class EntityView:
@staticmethod
def run(
entity_id: Union[in... |
e59a54e84e58d568a0634c9f2ec2eda87aebfeb60884a749c34234c8d4125763 | Python | 3,357 | 118 | """
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 io
import os
import pytest
import requests
import torch
from ase.io import read
from ocpmodels.common.registry import registry
from ... |
afe8a7c4446a41f89379e2b376211536cddb168d13ea9c6e5335c31748954553 | Python | 3,358 | 87 | """Strategies for updater tests."""
from typing import cast
import pytest
strategies = pytest.importorskip("hypothesis.strategies")
exact_parameter_strategy = strategies.fixed_dictionaries(
{
"nthread": strategies.integers(1, 4),
"max_depth": strategies.integers(1, 11),
"min_child_weigh... |
b8e54adf95ed1f969728edb7542499d81a4d3abf46bc63a3fc824e191b713193 | Python | 3,360 | 84 | ##############################################################################
# Obsolete import
# Need to check if this script is still useful for the project
##############################################################################
import sys, time
import numpy as np
import pytraj as pt
from Nearl import uti... |
aa8851a13f1455b0edf34b5e2dd4dc9590aec37ce4cbeb2003a4cda4a9be6987 | Python | 3,361 | 89 | """Context-Aware Implicit Neural Representations to Compress Earth Systems Model Data
DEVELOPED AT:
Department of Chemical Engineering
University of Utah, Salt Lake City,
Utah 84112, USA
DIRECTOR: Prof. Salah A Faroughi
DEVELOPED BY:
... |
72fd19b68aada26b9bbc978803c70522a0407e80e20093c5c87547e855ec60b6 | Python | 3,362 | 87 | """Redis key patterns for ephemeral state.
All persistent room state (geometries, bookmarks, figures, selections, step)
is stored in SQL. Redis is used only for:
- Session cameras (frontend presence derived from camera hash)
- Ephemeral locks (TTL-based with metadata)
- Socket.IO pub/sub adapter
"""
class RedisKey:
... |
afe9160f71f342088f80c7ea8929d06f6226bfce22f1714a89dfd4586d2a7453 | Python | 3,363 | 143 | """
Creates LMDB files with extracted graph features from provided *.extxyz files
for the S2EF task.
"""
import argparse
import glob
import multiprocessing as mp
import os
import pickle
import ase.io
import lmdb
import numpy as np
import torch
from tqdm import tqdm
from ocpmodels.preprocessing import AtomsToGraphs
... |
bfb5d12ec3e0862adf400d771dc2662c3df6ab31192cc154ce43ab94a82069f0 | Python | 3,363 | 102 | # -*- coding: utf-8 -*-
import codecs
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from sphinx.util.nodes import set_source_info
class FileInputDirective(Directive):
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = Tr... |
abef2428b0ef2380c352ec470912d8e08472e119cca1d719b7485cd72f9ebef3 | Python | 3,365 | 92 | #%%
import subprocess
import numpy as np
import os
import argparse
# Setup argument parser
parser = argparse.ArgumentParser(description="Run script with custom iterations")
parser.add_argument('--N', type=int, default=5, help='Number of iterations')
# Parse arguments
args = parser.parse_args()
# Use the argument
num... |
bead7e4747ad2039be70793164f67a7f1115251b5bc28d228b42e9c8b7066cf8 | Python | 3,366 | 78 | import ast
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
def pd_to_pth(df, values, keys=['participant', 'task', 'trial']):
column_names_list = [keys + [value] for value in values]
wide_arrs = {}
for column_names in column_names_list:
arr = df[column_names].va... |
47f7b455539f75a4548da002cd6c1d6aee90bbd1d4374e437c075265689a89a9 | Python | 3,367 | 104 | # -*- coding: utf-8 -*-
from django.conf import settings
from typing import List
from catmaid.control.dvid import get_server_info
class DVIDDimension:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class DVIDColor:
def __init__(self, r, g, b, a):
self.r = r
... |
92ca0c9a0dbf87cb239cc32988a5819eed175cd0d357232c6d56f62cbe50c086 | Python | 3,370 | 99 | """Centroid mzML input for :mod:`masscube.raw_data_utils`."""
from __future__ import annotations
import numpy as np
from .core import MSData, Scan, finalize_scan_indexes
def read_mzml_into_msdata(data: MSData, *, preprocess: bool = True) -> None:
"""Read ``data.metadata.file_path`` and populate an existing ``M... |
f1186c0340c00d5c55a783550f0e613ce5b33c3ca23c59403bfd91361881851b | Python | 3,376 | 85 | from CybORG.Agents import BaseAgent
from CybORG.Shared.ActionSpace import ActionSpace
from CybORG.Simulator.Actions import Sleep, Action
from CybORG.Simulator.Actions.GreenActions import GreenAccessService, GreenLocalWork
from ipaddress import IPv4Address
from CybORG.Shared import Observation
class EnterpriseGreenAgen... |
0a8cec05bc7d2beefb461b2ce8566a8c43b809641cdeff9ffeff3ff2fe4598c0 | Python | 3,377 | 84 | """Pipeline-marked test for the source-impact report CLI.
Uses the existing ``emapa_pipeline_outputs`` fixture from ``tests/pipeline/conftest.py``
to ensure EMAPA's intermediate ids and concord files are populated, then drives
``src.tools.source_impact_report.cli.main`` in synthetic mode and asserts the rendered repor... |
273212cfd532c939faa3f65ac145f53354ef0b4addb0be0f7113f1cef232494b | Python | 3,377 | 93 | from glob import glob
from typing import List
import h5py
from torch.utils.data import ConcatDataset, Dataset
from mace.data.atomic_data import AtomicData
from mace.data.utils import Configuration
from mace.tools.utils import AtomicNumberTable
class HDF5Dataset(Dataset):
def __init__(self, file_path, r_max, z_t... |
3ae1d720440b50a60f2c17e657455516aa47a135e2f29c79865252852dec9d2b | Python | 3,377 | 79 | from medperf.entities.model import Model
from medperf.entities.benchmark import Benchmark
from medperf.entities.dataset import Dataset
from medperf.exceptions import MedperfException
from medperf.asset_management.asset_management import update_dataset_cc_policy
from medperf.asset_management.gcp_utils import CCWorkloadI... |
0b1bb07be0d48a5af35fd71141fdb0bfc6bbb6eaada4428bc4eb7ff1d26ec13b | Python | 3,378 | 112 | from Utils.dataloader_RSNA_BONE import *
from Utils. config import *
from Utils.models import *
from Utils.TrainModelRSNA import *
from multiprocessing import Process
from codecarbon import EmissionsTracker
def task(lr, data_partition:float=None, run_idx:int=None, backbone: str='eff3'):
_cuda = 'cuda:0'
if backbone ... |
5c297a16f6de656642236c1d2f745e8ad0079421aa22605d2f21f3aa05ca23ac | Python | 3,378 | 97 | """Centralized logging configuration for GuPPy.
This module provides a standardized logging setup that writes to platform-appropriate
log directories following OS conventions:
- Windows: C:/Users/<username>/AppData/Local/LernerLab/guppy/Logs/guppy.log
- macOS: /Users/<username>/Library/Logs/guppy/guppy.log
- Linux: /h... |
75fac22715570c49aae19ac053ea31fcc0b5199a59efe33254049c2041a3c1bc | Python | 3,378 | 100 | import numpy as np
import pandas as pd
from statsmodels.tsa.stattools import adfuller
import argparse
import pickle
import os
import glob
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--path', type=str, help='The folder of raw yahoo dataset', default='ydata-labeled-time-se... |
ac94513cb8e790902f7e73b1884dfca2cb377e1f833b74f935bc4ea4bc0b104f | Python | 3,379 | 96 | from gym.utils import seeding
from CybORG.Shared import Results
class BaseAgent:
"""The base inherited class for any agent used in CybORG.
This class acts as an abstract class that enforces the implementation of the agent choosing an actions.
It also provides placeholder functions for use when/if the age... |
f4b1b403ded83fec5eaf4b6cdd8aa9df69c34ca9664416a1ac5f2318b7c39e11 | Python | 3,379 | 69 | from setuptools import setup, find_packages
VERSION = '0.0.4'
DESCRIPTION = 'Adversarial-Observation: A package for adversarial generation and interpretation of PyTorch models'
LONG_DESCRIPTION = '''Adversarial-Observation is a Python package that provides a framework for improving the transparency, interpretability, ... |
b522291fda3056d5493222e39b02c8110fa9f4c5a184ec4bde673c15debc5cfe | Python | 3,380 | 90 | import torch
import torch.nn as nn
import pandas as pd
import numpy as np
class NT_Xent(nn.Module):
"""NT_Xent loss for SimCLR."""
def __init__(self, batch_size, temperature=1):
super(NT_Xent, self).__init__()
self.batch_size = batch_size
self.temperature = temperature
self.m... |
7e4a93c2a7b64638c04ff4d42170c626da409ac69814fea016877869d01ccbe5 | Python | 3,383 | 80 | from __future__ import print_function
import numpy as np
import pytest
from keras.preprocessing.image import ImageDataGenerator
from keras.utils.test_utils import get_test_data
from keras.models import Sequential
from keras import layers
from keras.utils.np_utils import to_categorical
def test_image_classification()... |
9ea9f25cfb5e02cdd2e42e74a96ab08a6d15161469647a94b3b9ef09a600d5cd | Python | 3,384 | 96 | # Copyright (c) OpenMMLab. All rights reserved.
from mmcv.cnn import build_conv_layer, build_norm_layer
from mmengine.model import Sequential
from torch import nn as nn
class ResLayer(Sequential):
"""ResLayer to build ResNet style backbone.
Args:
block (nn.Module): block used to build ResLayer.
... |
01e2beeb51c10854e0395ea617d4ec045586017821d3b117d165a4e3ee7f8856 | Python | 3,387 | 98 | from medperf.entities.ca import CA
from medperf.entities.cube import Cube
from medperf.entities.certificate import Certificate
from medperf import config
from medperf.exceptions import (
MedperfException,
InvalidCertificateError,
InvalidCertificateAuthorityError,
)
import logging
from medperf.enums import C... |
5eb6f492cf2e33a1f2843eb0f9129a63036cfecb2299b02c6b7bdfa3e75894cd | Python | 3,388 | 95 |
from CybORG.Shared import Observation
from CybORG.Simulator.Actions import Action
from CybORG.Simulator.Actions.ConcreteActions.StopService import StopService
from CybORG.Simulator.State import State
class DegradeServices(Action):
""" A Red action that attempts to degrade a service used by green in the mission. ... |
dd6e3242e4d0155e76167584c50735053d9d57e4b558e09d1d574034c4a654ad | Python | 3,388 | 98 | #!/usr/bin/env python
"""
interproscan_annotator.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Run interproscan for protein annotations
Copyright (c) 2019 Harvard School of Public Health
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"... |
a44594e6d65a2c3e7dc7e7494663351d1e884d516593ad86bd61de753bd45854 | Python | 3,390 | 117 | # tests/test_events.py
"""Tests for Socket.IO event models and Emission dedup."""
from datetime import UTC, datetime
from uuid import UUID
import pytest
from pydantic import ValidationError
from zndraw_joblib.events import (
Emission,
JobsInvalidate,
JoinJobRoom,
LeaveJobRoom,
TaskAvailable,
... |
3ee2078ff594429b813b2f3b5eb820962b5280929191d258dc5a68159c283174 | Python | 3,392 | 53 | from setuptools import setup, find_namespace_packages
setup(name='mednextv1',
packages=find_namespace_packages(include=["nnunet_mednext", "nnunet_mednext.*"]),
version='1.7.0',
description='nnU-Net. Framework for out-of-the box biomedical image segmentation.',
url='https://github.com/MIC-DKFZ/M... |
4ef8728ef6fdbbb1ea6795d06392fbda27dd53370e255cb603fd3520e3af70d8 | Python | 3,392 | 106 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 23 11:00:26 2023
@author: george
"""
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import pyqtSlot
from pyautogui import screenshot
import cv2
import glob
from threading import Thread
import shutil
impo... |
44546c5e701dbad254a5cde16f92e5b6fd9869d592c0d70cd0e7f2c0d3b42ac9 | Python | 3,394 | 96 | from jaxkineticmodel.parameter_estimation.training import Trainer, TrainingData
from jaxkineticmodel.load_sbml.sbml_model import SBMLModel
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import jax.numpy as jnp
import jax
import optax
# load model
model_name = "Smallbone2013_SerineBiosynthesis"
... |
3de2975e81da2a907056fa992b5e2df5ad59f1ece0f848e157c97e1a9667501b | Python | 3,396 | 82 | import pytest
import numpy as np
from keras.utils import conv_utils
from keras import backend as K
def test_normalize_tuple():
assert conv_utils.normalize_tuple(5, 2, 'kernel_size') == (5, 5)
assert conv_utils.normalize_tuple([7, 9], 2, 'kernel_size') == (7, 9)
with pytest.raises(ValueError):
con... |
4bd5e37a15b39f2d73338fe61899b89739ee6430241b1ca850b2d61829f23563 | Python | 3,396 | 85 | import torch
import torch.nn as nn
from nnunet_mednext.network_architecture.custom_modules.custom_networks.TransUnet import vit_seg_configs as configs
from nnunet_mednext.network_architecture.custom_modules.custom_networks.TransUnet.vit_seg_modeling import TransUNet as TransUNet_Orig
from nnunet_mednext.training.networ... |
e66a66145bc770131e3ea3b4599d123698a4f9a1eec69a9bbb521aa09ebbb240 | Python | 3,396 | 98 | # 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... |
c570cfd271c0327bece5ac9ad7e95399be101469c2abe4a621272496fb701356 | Python | 3,397 | 114 | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os.path as osp
from mmengine import Config
def parse_args():
parser = argparse.ArgumentParser(
description='Convert benchmark test model list to script')
parser.add_argument('config', help='test config file path')
parser.add_a... |
084d2c133c32259a10f93da126e46ffed29a5496b017798328b505aebea98337 | Python | 3,398 | 98 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def plot_top_down_histograms():
fig, axes = plt.subplots(1, 2, figsize=(16, 6), sharex=True)
all_preds_global = []
for label_idx, label in enumerate([0, 1]):
... |
d7cda4123b1cecdd7d550a883423868cf2296e3ce83062e118c96ae1b900c901 | Python | 3,398 | 88 | import os
import sys
import scanpy as sc
import numpy as np
from sklearn.cluster import KMeans
import metrics as M
#from .metrics import compute_metrics
def train(data_path, dataset_name, save_path):
"""
:param data_path: e.g. data/ including csv h5ad
:param dataset_name: "baron-human"
:param sa... |
32e3488eba92efc5ce1137266ef2d8eac9a99faebfc9ef25b1fba2ec85eba4d1 | Python | 3,399 | 83 | # -*- coding: utf-8 -*-
import numpy as np
import scipy.stats as stats
from django.db import connection
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from performancetests import PerformanceTest
from performancetests.models import TestView
class Command(BaseComm... |
7827d953b02f4f31b872a16727d6b600738197d2dbb5fa1e2008c3c371934977 | Python | 3,402 | 67 | # pytest unit tests to validate the results of the batch_single_subject.sh script
import csv
from pathlib import Path
import pytest
from spinalcordtoolbox.utils.sys import sct_dir_local_path
SCT_DIR = Path(sct_dir_local_path())
CACHE_DIR = SCT_DIR / "testing" / "batch_single_subject" / "cached_results"
OUTPUT_DIR =... |
8d90795d63001cb805354f452b87fdc760a079caa939e705d163b3e5d3f61c4e | Python | 3,403 | 147 | # src/zndraw_joblib/__init__.py
"""ZnDraw Job Management Library."""
from zndraw_joblib.client import Category, ClaimedTask, Extension, JobManager
from zndraw_joblib.dependencies import (
FrameRoomCleanup,
FrameRoomCleanupDep,
JobLibSettingsDep,
ResultBackend,
ResultBackendDep,
WritableRoomDep,... |
6c9a7f1ad55acbfd8f7490f5825d907d008eee20d40392f2a6562ea694620d20 | Python | 3,405 | 106 | import os
import shutil
def setup_ws(node_cert_folder, ca_cert_folder, plan_path, temp_dir):
workspace_folder = os.path.join(temp_dir, "workspace")
create_workspace(workspace_folder)
prepare_plan(plan_path, workspace_folder)
cn = get_admin_cn()
prepare_node_cert(node_cert_folder, "client", f"col_{... |
78109c57a8dac203cd1d02c7169a25a9d962329384f9b631216d09f3f76c76f6 | Python | 3,405 | 93 | from medperf.entities.training_exp import TrainingExp
from medperf.entities.event import TrainingEvent
from medperf.utils import (
approval_prompt,
dict_pretty_print,
get_participant_label,
sanitize_path,
)
from medperf.exceptions import CleanExit, InvalidArgumentError
import yaml
import os
class Star... |
703d0132a47bd16b3f353efebcc2aa78b814e356086d8c62e226232020459aa7 | Python | 3,406 | 103 | import random
import numpy as np
import argparse
import yaml
import os
def set_seed(seed: int, tensorflow: bool = True, pytorch: bool = True):
"""
Set the random seed for reproducibility across NumPy, TensorFlow, PyTorch, and Python's random module.
Parameters:
- seed (int): The random seed value.
... |
f4b360add0b671d6442acee99f451ff4e3170cb11cb1fd9b59e9b76d4836275d | Python | 3,406 | 94 | # Copyright (c) OpenMMLab. All rights reserved.
from typing import List
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, build_conv_layer
from torch import Tensor
from mmseg.registry import MODELS
@MODELS.register_module()
class PPMobileSegHead(nn.Module):
"""t... |
1c69a6b41bad79181c98e1e171b3529824c4ae9474b1a687994ab2ed3ba62f4e | Python | 3,410 | 109 | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmseg.models.backbones import BiSeNetV1
from mmseg.models.backbones.bisenetv1 import (AttentionRefinementModule,
ContextPath, FeatureFusionModule,
... |
3dd3c8ef02a6510d3c965237033ceef676458c36aae8a2e7e6675613ed2cbb14 | Python | 3,410 | 134 | from torch.utils.data import Dataset
import numpy as np
import collections
import os
import pprint
import pandas as pd
from skimage.io import imread, imsave
import random
default_pathologies = [
"Atelectasis",
"Consolidation",
"Infiltration",
"Pneumothorax",
"Edema",
"Emphysema",
"Fibrosis"... |
92ea751928d82eeb147cfd676ad02ec39cd53f02e330cb588790cf4eeb72b5fb | Python | 3,412 | 109 | from typing import Optional
from medperf.exceptions import InvalidContainerSpec, MedperfException
from medperf import config
import os
import logging
def check_allowed_run_args(run_args):
logging.debug("Checking allowed run args")
allowed_keys = {"shm_size", "gpus", "command", "entrypoint", "environment"}
... |
aedf3124fb9dd8d040cae539c9492d3774dad72629c60ac7b8c5d1ad016ed0ef | Python | 3,414 | 143 | from .utils import is_string_like
import nibabel as nib
from pathlib import Path
import numpy as np
"""
Flexible data I/O - based on murraylab/brainsmash
"""
def dataio(x):
"""
Data I/O for core classes.
To facilitate flexible user inputs, this function loads data from:
- neuroimaging files
... |
6c38ac228a98074234745e2a7bc77d8d2ea78bdcc64cfed5d2cce6c84f4ca2d5 | Python | 3,415 | 89 | #!/usr/bin/env python
# coding=utf-8
# Copyright 2023 Statistics and Machine Learning Research Group at HKUST. All rights reserved.
# FIXME should merge with finetune.py
"""A one-line summary of the module or program, terminated by a period.
Leave one blank line. The rest of this docstring should contain an
overall d... |
3ed77fdd8e46ca3f5cb625ea1cb6f9501c3fc83a967fdd17fcbec2babf903e10 | Python | 3,416 | 121 | from __future__ import annotations
import json
from typing import Annotated
import typer
from zndraw_joblib.schemas import (
JobResponse,
JobSummary,
PaginatedResponse,
)
from .connection import (
PasswordOpt,
RoomOpt,
TokenOpt,
UrlOpt,
UserOpt,
cli_error_handler,
get_zndraw,... |
a93d9d3c36bb552b4639aaaddd4007f8b592195520ce4fc6f9dc555ffe799306 | Python | 3,416 | 114 | from Utils.dataloader_RSNA_BONE import *
from Utils. config import *
from Utils.models import *
from Utils.TrainModelRSNA import *
from multiprocessing import Process
from codecarbon import EmissionsTracker
def task(lr, data_partition:float=None, run_idx:int=None, backbone: str='eff3'):
_cuda = 'cuda:0'
if backbone ... |
ad15c85edf5b5f900544b48a401c2ade96041514b93fa7f8f80f009ee2059c5c | Python | 3,416 | 90 | import os
from pdb import set_trace as bp
import numpy as np
from nilearn.masking import apply_mask
from scipy.signal import find_peaks
PRJDIR = "/mnt/d/Experiments/Experiment2-Blink_Tic/SPFM/02_Statistics"
def _main():
# Read list_subject_run_ALL.txt into list
with open(os.path.join(PRJDIR, "list_subject_... |
f27a3349b7579203eb61fae2934a70333a7f56d2c58e1b7ecdd44ea8e7f146ed | Python | 3,416 | 97 | import os, torch
import numpy as np
import pandas as pd
from torch import nn
import torch.nn.functional as F
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
import argparse
from PROMINENT_methylation.train import *
def preprocessing1(path_fn, gene_fn, label_fn):
### pathway datasets
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.