sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
cd568c32d27e7a4e41cc6e1a815eb3cd41283713444dda41b8751c451897b167 | Python | 1,468 | 58 | import pytest
from rpy2.rinterface import NA_Character
from rpy2 import robjects
def test_init():
vec = robjects.FactorVector(robjects.StrVector('abaabc'))
assert len(vec) == 6
def test_factor_repr():
vec = robjects.vectors.FactorVector(('abc', 'def', 'ghi'))
s = repr(vec)
assert s.endswith('[ab... |
329762b8e21156d81154d0a0ddaebdfc4cff29eb487a3e387761c837f64bf6b3 | Python | 1,469 | 44 | import numpy as np
import torch.nn as nn
from modular_splicing.utils.io import load_model
class MotifModelForRobustDownstream(nn.Module):
motif_model_dict = True
def __init__(
self, input_size, channels, num_motifs, models_for_motifs, trainable=False
):
super().__init__()
models ... |
5ec7f89cee7938a139ab47f3f0eb4599bcb9b6bcc78805927481d7ac61d35aea | Python | 1,469 | 52 | import numpy as np
import pytest
from Transform.src.noise import Noiser
def test_noiser_init():
# Test if the Noiser object is initialized with the correct sigma value
noiser = Noiser(sigma=0.1)
assert noiser.sigma == 0.1
noiser = Noiser()
assert noiser.sigma == 0.01
def test_noiser_set_sigma(... |
735224d2d6070879b046bb1006e51c7f721cf7a9b0f1857ffaed42303556dd84 | Python | 1,470 | 45 | """Tests for spiketools.plts.spikes"""
import numpy as np
from spiketools.tests.tutils import plot_test
from spiketools.tests.tsettings import TEST_PLOTS_PATH
from spiketools.plts.spikes import *
###################################################################################################
####################... |
84729670cd869626648898a491102ebdb49e8fb315300f4e38670cf88ac06e27 | Python | 1,470 | 39 | """ Conv2d w/ Same Padding
Hacked together by Ross Wightman
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Tuple, Optional
from .padding import pad_same, get_padding_value
def conv2d_same(
x, weight: torch.Tensor, bias: Optional[torch.Tensor] = None, stride: Tuple[i... |
ba34269d696d78b81630b13dcc8d032868fdc4f7b3334497a9bfd9882bc38937 | Python | 1,470 | 41 | import nway.image_processing_utils as imu
import pytest
from pathlib import Path
import numpy as np
import PIL.Image
TEST_FILE_DIR = Path.resolve(Path(__file__)).parent / "test_files"
@pytest.fixture
def fixed_image_fixture():
# grab one specific file because failing large translation
# cases vary image-by-i... |
6f19550b9d4820f969ee8cd3f37cbde449295ca6ae0c3cd2984a0106c109e181 | Python | 1,471 | 39 | from setuptools import find_packages, setup
import pathlib
here = pathlib.Path(__file__).parent.resolve()
long_description = (here / "README.md").read_text(encoding="utf-8")
setup(
name='pyfiber',
packages=find_packages(where='src'),
version='0.2.15',
description='Fiber photometry and behavioral data ... |
71e3eb1d46d62b78dfb06c51482958e5cc34d765f568d536aecf375e16c2a776 | Python | 1,471 | 43 | from Bio import SeqIO
import sys
from random import sample, shuffle
def parse(fname,outname,only_verified=True,n=None):
if 'RNA' in fname:
prot_file = fname.replace('RNA','PROTEIN')
rna_file = fname
elif 'PROTEIN' in fname:
rna_file = fname.replace('PROTEIN','RNA')
prot_file = ... |
7343376768a83909be1abf6f2914633eedb8608f3a79c06563fcab88b0ef9576 | Python | 1,471 | 42 | """
This pipeline computes baseline-shift indices for sensor space.
"""
import os
import numpy as np
from scipy.signal import welch
from tools_general import load_json, save_pickle, list_from_many
from tools_lifedataset import read_rest
from tools_signal import peak_in_spectrum, bsi
dir_save = load_json('settings/dirs... |
26f9f31c0a31976811325be433c9d8b6c2036eca856e248f35d87f13ddf0b0f5 | Python | 1,472 | 38 | """
Author: Bruno De Santi, PhD
Affiliation: Multi-modality Medical Imaging Lab (M3I Lab), University of Twente, Enschede, The Netherlands
Date: 20/09/2023
Description: Normalized cross correlation for network optimization
Acknowledge: The code was adapted from
1) https://github.com/BDdeVos/TorchIR
2) J. M. Wolterink... |
8dfb042cd1d7911253739ba93da395c2539dca048fffec36cd3e7c2b9d79d6fb | Python | 1,472 | 50 | from sys import argv
from msp import MSP
msp = MSP()
msp.file = __file__
msp.seed = int(argv[1])
msp.architecture["splicepoint_model_spec"] = dict(
type="BothLSSIModels",
acceptor="model/splicepoint-model-acceptor-1",
donor="model/splicepoint-model-donor-1",
)
msp.architecture["motif_model_spec"]["motif_... |
96c8ebc83483953634b81746126b3e73eb288cf4d6c13fd661fd85b529c03436 | Python | 1,472 | 39 | import unittest
from os.path import join, abspath
from numpy.testing import assert_allclose
from tests.tabulation.nonadiabatic_defect_steady_slfm.rebless import run
from spitfire.chemistry.library import Library
from spitfire.chemistry.ctversion import check as cantera_version_check
if cantera_version_check('atleas... |
af03588d980acadfb526c30438f4ec5dab972979b242acd32a139c126f408f8a | Python | 1,472 | 46 | """Shared holder for stale pre-wrap torch references in rescue tests."""
from __future__ import annotations
from collections.abc import Callable
from typing import Any
from torch import nn
class OpaqueCallable:
"""A custom callable object: a holder the per-capture rebind never scans.
Capture preparation r... |
842a496323715bc58ec508ae4faa9273b66f5192dae1d266ce733085d6602b27 | Python | 1,473 | 48 | #!/usr/bin/env python
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = ['pandas', 'requests', ]
setup_requirements = ['pytest-runner... |
a23e154b24611c1c6a40af429196b7109a6f262b962cac50425fbb4ae67a509f | Python | 1,473 | 42 | from __future__ import annotations
import pytest
from kombu import Exchange, Producer, Queue
from pytest_celery import CeleryBrokerCluster, RabbitMQTestBroker
from celery import Celery, uuid
from celery.app.amqp import Queues
@pytest.fixture
def celery_broker_cluster(celery_rabbitmq_broker: RabbitMQTestBroker) -> C... |
e4658c6de2ae5cb12c4b6e01ea4badbf39389feafdd2d67823df18aee97b0d8e | Python | 1,473 | 38 | import pathlib
from PyQt5 import QtCore, QtWidgets
class DirectoryDialogMultiSelect(QtWidgets.QFileDialog):
def __init__(self, *args):
"""A dialog that lets the user select multiple directories"""
QtWidgets.QFileDialog.__init__(self, *args)
self.setOption(self.DontUseNativeDialog, True)
... |
2dafabc2a89a9881a5dbfc52742ce4a71629fc4f925aa539040b28fcbff07c4e | Python | 1,474 | 28 | from .base_options import BaseOptions
class TestOptions(BaseOptions):
"""This class includes test options.
It also includes shared options defined in BaseOptions.
"""
def initialize(self, parser):
parser = BaseOptions.initialize(self, parser) # define shared options
parser.add_argum... |
8613bee3ac7d1fd19bc74b3a067b0aa0bbdcbbceff467632207d87be1140784d | Python | 1,474 | 44 | import pytest
from larvaworld.lib import reg
from larvaworld.lib.reg.graph import GraphRegistry
from larvaworld.lib.sim import ExpRun
from larvaworld.lib.process import LarvaDataset
pytestmark = [pytest.mark.integration, pytest.mark.heavy]
expIDs = ["dispersion", "chemorbit"]
@pytest.mark.usefixtures("ensure_datase... |
f213a2d2932605ffd1c5266bc1675f0bc1ebf38bfe59350d3c46b6b0d32d88c2 | Python | 1,474 | 42 | """Tests for specparam.plts.aperiodic."""
import numpy as np
from specparam.tests.tutils import plot_test
from specparam.tests.tsettings import TEST_PLOTS_PATH
from specparam.plts.aperiodic import *
###################################################################################################
#################... |
c80e89f9343c831c2cdaff5ae3ea9bb051d2b9a459ce36cd8bc9e3e8160d9cb4 | Python | 1,475 | 54 | import logging
import sys
import time
from codecarbon import OfflineEmissionsTracker
def train_model():
"""
This function will do nothing during (occurrence * delay) seconds.
The Code Carbon API will be called every (measure_power_secs * api_call_interval) seconds.
"""
occurrence = 60 * 24 * 365 ... |
d37276af2e706e5db2beb55603992f2c08e964b37730312820e7197a2d6bb1aa | Python | 1,475 | 59 | import pytest
import torch
from lightly.loss.mmcr_loss import MMCRLoss
class TestMMCRLoss:
def test_forward(self) -> None:
bs = 3
dim = 128
k = 32
loss_fn = MMCRLoss()
online = torch.randn(bs, k, dim)
momentum = torch.randn(bs, k, dim)
loss_fn(online, mom... |
170dc1d6f127e939651ca205b895f985c08ad242ab0b5e7ca4c125e2b4af478f | Python | 1,476 | 53 | import torch.nn as nn
from modular_splicing.models.motif_models.types import motif_model_types
from .short_range_motif_reprocessor import srmp_types
from modular_splicing.utils.construct import construct
class ReprocessedMotifModel(nn.Module):
"""
Motif model that uses a reprocessor to reprocess the motifs b... |
55e92d0c0e4f5e99bf48ea21d52bba2588201a61f7e9bf84f54bc0ae58752fc9 | Python | 1,476 | 52 | from sys import argv
from msp import MSP
msp = MSP()
msp.file = __file__
msp.seed = int(argv[1])
msp.architecture["splicepoint_model_spec"] = dict(
type="BothLSSIModels",
acceptor="model/splicepoint-model-acceptor-1",
donor="model/splicepoint-model-donor-1",
)
msp.architecture["num_motifs"] = 82
msp.arch... |
68572b612c035088071f4bc87cb9539f52d3029556f771740dd0aa53df72d26b | Python | 1,476 | 52 | from sys import argv
from msp import MSP
msp = MSP()
msp.file = __file__
msp.seed = int(argv[1])
msp.architecture["splicepoint_model_spec"] = dict(
type="BothLSSIModels",
acceptor="model/splicepoint-model-acceptor-1",
donor="model/splicepoint-model-donor-1",
)
msp.architecture["num_motifs"] = 82
msp.arch... |
8700089d0c9c8da8c3ef5e88efce300761623aff35ea44a50dbe04bfcc820552 | Python | 1,477 | 37 | from prodict import Prodict
import numpy as np
import sys
import pandas as pd
sys.path.append("src")
import utils
from predict import evaluate_model
from model import *
def get_pt_encodings(cfg: Prodict) -> None:
"""Generates the initial condition and parameter encodings for each patient.
Parameters
---... |
eff64a0b3c7f68300dd4b7e0648c164f91f2f061b7d60e8eeb81d3a0b49cd4fe | Python | 1,477 | 55 | from collections.abc import Callable
from dataclasses import dataclass
import numpy as np
import torch
from torch import nn
from neurogym.wrappers.components.modules.base import LayerProbeBase
@dataclass
class AFLayerProbe(LayerProbeBase):
@staticmethod
def layer_types() -> set[type[nn.Module]]:
"""... |
98a1e2da65d67716711b6587063f369d56d8e16d388d22a051b60bb97c318f78 | Python | 1,478 | 43 | import torch
from torch import nn
from torch._C import dtype
from .gru_model import GRUModel
from torch.nn import functional as F
from .activations import get_activation
class Discriminator(nn.Module):
def __init__(self, hidden_size, activation='gelu'):
super().__init__()
self.dense = nn.Linear(hi... |
c0dcd4ba437d7e1ab9b91e483bcc4060b8599695f5ecff970b6be2087b24ae0c | Python | 1,478 | 39 | """ Conv2d w/ Same Padding
Hacked together by Ross Wightman
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Tuple, Optional
from .padding import pad_same, get_padding_value, pad_same1d
def conv1d_same(
x, weight: torch.Tensor, bias: Optional[torch.Tensor] = None, str... |
cc28c88790502193bd7f1adc50eea2a940268090abb4f84a2af9b9508f0858e1 | Python | 1,478 | 65 |
def collapse_to_mean(select_collapse):
from numpy import mean
select_open = open(select_collapse)
select_dic = {}
outfile = open(select_collapse.replace('.', '_ctm.'), 'w')
# again there isnt a header so set to false - OC
first_line = False
for line in select_open:
if first_l... |
0949557ce33d90e6ccb2245eafac0baec07bd971707c094d26da52c4c6c47369 | Python | 1,479 | 32 | from ToMoDL.models.models_system import MoDLReconstructor
import matplotlib.pyplot as plt
from pathlib import Path
import ToMoDL.utilities.dataloading_utilities as dlutils
from config import model_system_dict, trainer_system_dict, dataloader_system_dict
from torch.utils.data import DataLoader
import torch
import wandb
... |
7b7a8762fc316f00ec40e22e134d2e7880b6491a8da317c2525aa5af541c6c82 | Python | 1,479 | 42 | import os.path
import unittest
from os import path
from codecarbon.core.rapl import RAPLFile
from codecarbon.core.units import Energy, Time
class TestEnergy(unittest.TestCase):
def setUp(self):
self.mock_energy_data_filename = "mock_rapl_data.txt"
self.path = path.join(
path.dirname(o... |
a0a5234950487ee25c7a185b22218fabca566555ddc6b238cb116d9e281f1749 | Python | 1,479 | 49 | """Tests for bdpy.util."""
import unittest
import numpy as np
import bdpy.mri as bmr
class TestMri(unittest.TestCase):
"""Tests for 'mri' module."""
def test_get_roiflag_pass0001(self) -> None:
"""Test for get_roiflag (pass case 0001)."""
roi_xyz = [np.array([[1, 2, 3],
... |
bd2777fcab5ab17242f41819b18f40fab23f1821d7bdddcdf7a9d16a4ad1a6a1 | Python | 1,480 | 42 | # Example how to use the xyz2swc API:
# 1 ) upload and convert two files to the server
# 2 ) download the swc files as a zip to folder output/converted.zip
# 3 ) download the log files as a zip to folder output/logs.zip
import requests
import os
# set the cipher list to avoid SSL errors, needed temporarily
requests.p... |
0454ee79572bb21e55558553bfcbbf1d9077d9e7fcfd5d05e5dc2ee7e00e8f24 | Python | 1,481 | 43 | from collections.abc import Mapping
RAW_VALUE_BY_DEFAULT = False
def env_to_statement(env: Mapping[str, object]) -> str:
"""Return the abstraction description of an environment variable definition
into a statement for shell script.
>>> env_to_statement(dict(name='X', value='Y'))
'X="Y"; export X'
... |
0b6228b17d098daf13d7ebe6fc14da54a16d78fd8f8630554fd99a43de9631aa | Python | 1,481 | 41 | """Widget containing force-distance plot"""
from PyQt5 import QtWidgets
from .mpl_indent import MPLIndentation
class WidgetPlotFD(QtWidgets.QWidget):
def __init__(self, *args, **kwargs):
"""Display force-indentation graph with navigation"""
super(WidgetPlotFD, self).__init__(*args, **kwargs)
... |
3b992ed1e26338f1ace407812d708239e8a1b4c21fcf6c3dcaedc879d44ea044 | Python | 1,481 | 34 | import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
cudnn.deterministic = True
cudnn.benchmark = True
import torch.nn.functional as F
from .gat_conv import GATConv
class STAGATE(torch.nn.Module):
def __init__(self, hidden_dims):
super(STAGATE, self).__init__()
... |
66db7c1ee4ac6670434ff000e47ff3ec1c3c426fe965e8e98d6f035b55afbe04 | Python | 1,481 | 39 | import unittest
from os.path import join, abspath
from numpy.testing import assert_allclose
from tests.tabulation.nonadiabatic_defect_transient_slfm.rebless import run
from spitfire.chemistry.library import Library
from spitfire.chemistry.ctversion import check as cantera_version_check
if cantera_version_check('atl... |
b09f51d95cf01b5239ef00730b1301be918a1ed40448bba362ff82eb96176979 | Python | 1,481 | 63 | # Specipy work details
work_name = 'Large-screening_TUWGEX-' # Work name for save
run_mode = 'Training' # {Training, Predict, Explain, Hyperopt}
data_mode = 'Crystal' # {Crystal, Molecule}
model_name = 'MEGNet' # {MEGNet, GCN, CGCNN, SchNet}
train_size = 6000 #8457
fingerprint = 'Avalon'
random_state = 2
model_path = N... |
bd9245e7e681e32c7923afc4d5313f5c47c7067a719b1700afc6012ed02f9670 | Python | 1,482 | 60 | """select_top.
This file is a part of BdPy.
"""
__all__ = ['select_top']
from typing import Tuple, Optional
import numpy as np
from .util import print_start_msg, print_finish_msg
def select_top(data: np.ndarray, value: np.ndarray, num: int, axis: Optional[int] = 0, verbose: Optional[bool] = True) -> Tuple[np.nda... |
d1b0fc1975375ae18bf7d0b79387803dbf31a8f45263d696ac883a3301eacae0 | Python | 1,482 | 47 | from imodelsx import submit_utils
from os.path import dirname
import os.path
repo_dir = dirname(dirname(os.path.abspath(__file__)))
# List of values to sweep over (sweeps over all combinations of these)
params_shared_dict = {
'seed': [1],
# 'save_dir': [os.path.join(repo_dir, 'results', 'fmri_feb24')],
's... |
f478a914e42f942b8c9008d3803f75f2bf26d35764b05414580b033de2304680 | Python | 1,482 | 41 | import tempfile
import unittest
import nibabel as nib
from Loader.src.loader import *
class TestLoader(unittest.TestCase):
def setUp(self):
# Create a temporary directory for the test data
self.temp_dir = tempfile.TemporaryDirectory()
# Create a dummy image file for testing
self.... |
ffaa87f8cd7dd7b7c69392e117aba4a3ea37d51204b4ddab6145cce96d7800e1 | Python | 1,482 | 33 | import unittest
from svim.SVSignature import SignatureDeletion,SignatureInsertion
class TestSVSignature(unittest.TestCase):
def test_accessors(self):
deletion = SignatureDeletion("chr1", 100, 300, "cigar", "read1")
self.assertEqual(deletion.get_source(), ("chr1", 100, 300))
self.assertEq... |
4ad66bea49d09e86aa612402633ef17f5b3e68e6074164b0d24d0ba5bda22750 | Python | 1,483 | 63 | """
Lightweight records describing workspace datasets.
These carry only what a listing needs, so the catalog views never open the
stored HDF5 files.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Literal
@dataclass(frozen=True)
class... |
451c39026293906354b25cd5d09d051eb6e65267d345c4a44eb3c1a08c349426 | Python | 1,484 | 53 | """
I got an email that this ABF1 is messing up.
This script investigates the issue.
"""
import os
import sys
PATH_HERE = os.path.abspath(os.path.dirname(__file__))
PATH_DATA = os.path.abspath(PATH_HERE+"../../../data/abfs/")
PATH_SRC = os.path.abspath(PATH_HERE+"../../../src/")
sys.path.insert(0, PATH_SRC)
import ma... |
e011885c8cc64f454f33e0abc7265b3be4046ac8013f53b608d25eb9155926ad | Python | 1,484 | 43 | #!/usr/bin/env python
import os
from setuptools import setup
VERSION = '2.0.0'
# read the contents of README.md
this_directory = os.path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
LONG_DESCRIPTION = f.read()
if os.path.exists('MANIFEST'):
os.rem... |
eb767763de8d0692234de0883095f2fe79486d33ef994335d08f49b8fd20f631 | Python | 1,484 | 50 | from sys import argv
from msp import MSP
msp = MSP()
msp.file = __file__
msp.seed = int(argv[1])
msp.architecture["num_motifs"] = 82
msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels")
msp.architecture["motif_model_spec"] = dict(
type="AdjustedMotifModel",
model_to_adjust_spec=dict(
... |
0d0f3f0f2f6493bc1b0a77c82940b8c0be85e731f0164f13437cc7b52dfb7c5f | Python | 1,485 | 40 | import os,csv,re
import pandas as pd
import numpy as np
def Moran_I(genes_exp, XYdistances, XYindices):
W = np.zeros((genes_exp.shape[0],genes_exp.shape[0]))
for i in range(0,genes_exp.shape[0]):
W[i,XYindices[i,:]]=1
for i in range(0,genes_exp.shape[0]):
W[i,i]=0
I = pd.Seri... |
a569ea004fda6b6f82108675a3a5da456e7f678e0c06673d405517cf54a2f272 | Python | 1,485 | 47 | #!/usr/bin/env python
"""
Input: DNA Fasta File
Output: Tabular
Return Tabular File with predicted ORF's
Bjoern Gruening
"""
import sys
from kegg import KEGGDB
from sqlalchemy.orm import sessionmaker
KEGGDBEngine, KEGGDBBase = KEGGDB.init("postgres://bag:bag@10.4.56.8:5432/phabidb")
KEGGSession = sessionmaker(bind=KE... |
c97a29b2c679a5c660bbe531b72d93e6a28dac5d267e60d7cb1a11e3bdbe8208 | Python | 1,485 | 36 | """Smoke check: the Rust _core.Ragged exposes the API surface consumers use.
Surface derived from grepping genoray/GenVarLoader/genvarformer source.
"""
import numpy as np
import pytest
from seqpro.rag._core import Ragged
CONSTRUCTORS = ["from_offsets", "from_lengths", "from_fields", "empty"]
METHODS = ["to_packed",... |
7170c4492d0956c293623b810029720e1139356d9c814930c8d4b1a4855d587b | Python | 1,486 | 51 | """
test_mua.py
Unit tests for mua spike extractions.
"""
import unittest
import pathlib
from fused_org_ephys import FusedOrgSpikes
################################
class TestMUASpikes(unittest.TestCase):
def setUp(self):
# default dir to tc metadata
metadata_path = pathlib.PurePath('tests'... |
b69fb0fab9ab00cb7edf0d3c92e77764a8092e8f15901aa7fa6cf62e3f6d7151 | Python | 1,486 | 57 | import marisa
keyset = marisa.Keyset()
keyset.push_back("cake")
keyset.push_back("cookie")
keyset.push_back("ice")
keyset.push_back("ice-cream")
trie = marisa.Trie()
trie.build(keyset)
print("no. keys: %d" % trie.num_keys())
print("no. tries: %d" % trie.num_tries())
print("no. nodes: %d" % trie.num_nodes())
print("si... |
51b9b0b9a49e5542787c4299c98d0365442197dca5cd021616436afa37e17a27 | Python | 1,487 | 37 | import pickle
from os.path import abspath, join
def run():
from spitfire.chemistry.mechanism import ChemicalMechanismSpec
from spitfire.chemistry.reactors import HomogeneousReactor
import numpy as np
xml = abspath(join('tests', 'test_mechanisms', 'h2-burke.yaml'))
mechanism = ChemicalMechanismSpe... |
9b391a754396e4ed4b942c571d704d829ade745d8ac2445d51de2666eafa446e | Python | 1,487 | 36 | from mock import Mock
import numpy as np
from numpy import testing as npt
from tns.astrocyte.context import SpaceColonizationContext
from tns.astrocyte.section import SectionSpatialGrower
from tns.astrocyte.tree import TreeGrowerSpaceColonization
from test_grower import _parameters, _distributions, _context
def tes... |
53a46ed5d2a41b716c7ebce821bfdcb135f238d0815172225a7d2b8c0f174f80 | Python | 1,488 | 55 | """add dispatched column to notifications
Revision ID: 303a5583a030
Revises: 55f02fd8ab6c
Create Date: 2024-04-04 11:45:54.018829
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy import (
Boolean,
Column,
)
from galaxy.model.database_object_names import build_index_name
from galaxy.model.m... |
618e7bd472dda667707e5ed426fd47c5d5ee82ac62cf8e66b998784c46de46b4 | Python | 1,488 | 56 | """seed_dfg_team_data
Revision ID: 73a394753d3a
Revises: 5abae4eb2079
Create Date: 2021-05-20 11:34:59.174223
"""
from alembic import op
DFG_ORG_ID = "e52fe339-164d-4c2b-a8c0-f562dfce066d"
DFG_TEAM_ID = "8edb03e1-9a28-452a-9c93-a3b6560136d7"
DFG_TEAM_API_KEY = "default"
DFG_PROJECT_ID = "e60afa92-17b7-4720-91a0-1... |
4d3b56587a232a409f6b4aa60668486ff63249f1b13152eff005497f2a53c355 | Python | 1,489 | 51 | import torch
import torch.nn as nn
class ConvolutionalBottleneck(nn.Module):
def __init__(self, *, num_motifs, num_output_motifs=2, width):
super().__init__()
assert width % 2 == 1
self.num_motifs = num_motifs
self.conv = nn.Conv1d(num_motifs, num_output_motifs, width, padding=widt... |
d0191f5e0400160ae12d018c7096f22d083c7b7aa4bd488b68636796b9dba754 | Python | 1,489 | 51 | from modular_splicing.evaluation import standard_e2e_eval
from modular_splicing.lssi.maxent_tables import three_prime, five_prime
from modular_splicing.lssi.analyze import maxent_accuracies, lssi_accuracies
from modular_splicing.models_for_testing.list import (
AM,
spliceai_10k,
LSSI,
LSSI_EXTRAS,
)
fr... |
d9cd0ef12d2ed21176de2caced02c72493b3d96efdac731e10ed8e30341b8259 | Python | 1,489 | 49 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""tests for embeddings"""
import unittest
from sknetwork.data.test_graphs import *
from sknetwork.embedding import Spectral, SVD, GSVD, Spring
class TestEmbeddings(unittest.TestCase):
def setUp(self):
"""Algorithms by input types."""
self.methods ... |
dfc1c6cefa00c0e8a139fb203deea978ad8a0924e559af034a5bb3fc45f181a4 | Python | 1,490 | 31 | """Handles the SelectionWindow Class"""
# License: GNU General Public License v3.0
import ipywidgets as widgets
from ipywidgets import Widget
from gui import DropdownSelectionWidget, DataUploadWidgets
class SelectionWindow(Widget):
"""Handles the Selection functionality"""
def __init__(self, data_path, tests,... |
bacc3527192709a92bf3539d58ab82e74889a002ab0c4052a0ac1b0ac22b9ad2 | Python | 1,491 | 57 | from typing import Any
import pytest
from pytest_celery import CeleryTestWorker, CeleryWorkerContainer, defaults
from pytest_docker_tools import build, container, fxtr
from celery import Celery
class LegacyWorkerContainer(CeleryWorkerContainer):
@property
def client(self) -> Any:
return self
@c... |
cf36ced218e0306853490f3df5150968ae44a6bb3785f53ae0e9a6f920a8a0a5 | Python | 1,491 | 54 | """
Widget for editing a whole environment configuration.
"""
from __future__ import annotations
import panel as pn
import param
from .arena_widget import build_area_widget
from .border_widget import build_border_widget
from .food_widget import build_food_conf_widget
from .odorscape_widget import build_odorscape_wid... |
db3c8c4252240451c974a90989b804be99e23fa5654f38da42a6aaeeaa0a8d44 | Python | 1,491 | 39 | # -------------------------------------------------------------------------------------
# Code with saving functions
# -------------------------------------------------------------------------------------
import os
import pickle
import joblib
def save_variable(variable, name, folder_path):
with open(os.path.join(fo... |
7458f7e15e4ccc18c4d0ceffccae9c0b3db2445b6ba5ca37dac8376389285d03 | Python | 1,492 | 47 | # LICENSE
#
# _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._
#
# BioImage Suite Web is licensed under the Apache License, Version 2.0 (the "License");
#
# - you may not use this software except in compl... |
bcde5e1aeec321b83c411ab853a87230935f2b92cc3d5f7aa1afc571a0b561fc | Python | 1,492 | 48 | import os
from datetime import datetime
def get_project_root() -> str:
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def get_time_stamp() -> str:
current_time = datetime.now()
return current_time.strftime('%m%d%H%M%S')
def generate_descriptor(train_with_supervision, use_negative_sa... |
d2df2c42f804d6ab9e34e2d8dc0d42416d7145de5c42b9a172ead345174f7675 | Python | 1,492 | 45 | import random
import time
import datetime
import sys
from torch.autograd import Variable
import torch
import numpy as np
from torchvision.utils import save_image
class ReplayBuffer:
def __init__(self, max_size=50):
assert max_size > 0, "Empty buffer or trying to create a black hole. Be careful."
... |
f49d3dd3b6c1eeea5434656c776eb84315f78b9dcedb0dd6b823521a259a57d6 | Python | 1,492 | 49 | import os, json
import pandas as pd
lsdat = pd.read_table('annot_tab.tsv')
df = lsdat[['image_name','image_width','image_height']].drop_duplicates().reset_index(drop=True)
df.columns = ['file','iwidth','iheight']
df['imgid'] = list(range(1, len(df['file'])+1))
lsdat = lsdat[['image_name', 'bbox_x', 'bbox_y', 'bbox_w... |
3f94b247cd26db0aa814aedff815c2388edfd42d13a7efbbecefb06369f8c0d8 | Python | 1,493 | 25 | from nose import tools as nt
from tns.morphmath import bifurcation as _bf
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
def test_get_bif_directional():
assert_array_almost_equal(_bf.directional([0., 1., 0.], [0., 0., 0., np.pi/2]),
(np.arra... |
ae9fed3646be5ea4e0cc1ec26df1b055a7e1760d6d0532a709f6ebeea9926061 | Python | 1,493 | 45 | """
This module create ProtBertProjectGOPoincareBall
"""
# pylint: disable=W0223
from curses import nonl
import logging
import torch.nn as nn
import torch
import geoopt
import numpy as np
from goatools.obo_parser import GODag
from goatools.gosubdag.gosubdag import GoSubDag
from tqdm import tqdm
import time
import torch... |
ce37715abaa80387ce1f6ec88f2243a1d10e983c08401c377981ddf389ab7784 | Python | 1,493 | 51 | #!/usr/bin/env python
#=========================================================================
#
# Copyright NumFOCUS
#
# 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://... |
3bae8fe6b0cca6b3ed4ebbd60d82145946134b74cc1d7812491f069504891c34 | Python | 1,494 | 49 | import pytest
from nfp.preprocessing import features
from nfp.preprocessing.tokenizer import Tokenizer
from rdkit import Chem
@pytest.fixture()
def mol():
return Chem.MolFromSmiles("CO")
def test_atom_features(mol):
assert features.atom_features_v1(mol.GetAtomWithIdx(0)) == "('C', 1, 3, 3, False)"
asser... |
a07f4630abda01821c0193054a0fda41aa2cfb80df6123ffa40e96e735a9b5df | Python | 1,494 | 45 | """
This script loads every ABF in the data folder and generates a summary of its
header (in both HTML and markdown format).
"""
import pytest
import glob
import os
import sys
import warnings
import pathlib
PATH_HERE = os.path.abspath(os.path.dirname(__file__))
PATH_PROJECT = os.path.abspath(PATH_HERE+"/../")
PATH_D... |
93e7c4d3aef329e257dbc36ac94a6b7884715423ace8a8fdb306ffb98e1a40ee | Python | 1,495 | 58 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
af4e9fb0bcd27684c77e9368402c47d718a453d2da9952f698ac52899708aeb1 | Python | 1,495 | 31 | import os
import slicer
from slicer.ScriptedLoadableModule import *
# Source: https://github.com/lassoan/SlicerSegmentEditorExtraEffects
class SegmentEditorBiomedisaTraining(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/main/Base/Python/... |
48b3d9806e89b06d6c54a925511307b506bdcba9f2e2f90ad5dc5bb38bfe21bc | Python | 1,496 | 51 | from torch.utils.data import Dataset
import torch
import numpy as np
from functools import partial
class PreprocessDataset(Dataset):
"""A base preprocessing dataset representing a preprocessing step of a Dataset preprocessed on the fly.
supporting integer indexing in range from 0 to len(self) exclusive.
"... |
58d8455b5be774a028f4441c9c3c52afe7ca10529932fbcf8578230e5efe0d58 | Python | 1,496 | 51 | import logging as log
from typing import Any
OPTIONS: dict[str, Any] = {}
_VALID_OPTIONS: dict[str, Any] = {}
class set_options:
"""Control muon options.
MuData options are passed to MuData's set_options.
Available options:
- ``display_style``: MuData object representation to use
in noteboo... |
9156a9486855f1bea50e3ee91407ac0156c208a025458957c044cdde934a2fcc | Python | 1,496 | 37 | import makemodel
modeldefaults = makemodel.getdefaults()
def cleanparams(p):
'''standardize params that do not matter'''
for i in range(1,6):
if p['conv%d_width'%i] == 0:
for suffix in ['func', 'init', 'norm', 'size', 'stride', 'width']:
name = 'conv%d_%s'%(i,suffix)
... |
ef9ea970291d370a1612a5ca01c2578d89ebb4bc53b44df82111f1deb5509f30 | Python | 1,496 | 49 | import sqlite3
from .db import Database
from .WB_tables import WB_case_info, WB_hospital, WB_testing, WB_district_cases, WB_testing_labs, \
WB_PPE, WB_vaccination, WB_counselling
class WestBengalDB(Database):
def __init__(self, datadir):
super().__init__(datadir)
self.init_tables()
s... |
1e7ef6df88f7297f118003e3c70f79b127e67698f71b95d119d4d36c1dc22ad0 | Python | 1,497 | 35 | __author__ = 'quentin'
from ethoscope.core.monitor import Monitor
from ethoscope.trackers.multi_fly_tracker import MultiFlyTracker
from ethoscope.utils.io import SQLiteResultWriter
from ethoscope.hardware.input.cameras import MovieVirtualCamera
from ethoscope.drawers.drawers import DefaultDrawer
# You can also load o... |
6b7f9aca9fdfcec1f21b5bdc45042db8e40db7d076a8ba35bfaa063ec2d7bcfb | Python | 1,497 | 31 | #! /usr/bin/env python
import os
import pandas as pd
import sys
from sqlalchemy import create_engine
if __name__ == '__main__':
'''
Create table for meta info on PCHi-C libraries.
To be run after placing PCHi-C libraries in
'../lib/pchic/<enzyme>/pchic_data/<tissue or cells>/<replicate>.db'
'''
... |
7340d8ca94336bd434515a2ac1026a71adb2061eb3749f5ae1df3378dc148be1 | Python | 1,498 | 42 | import csv
import logging
import os
from collections.abc import Iterator
from typing_extensions import TypedDict
log = logging.getLogger(__name__)
class CarbonIntensityEntry(TypedDict):
location_name: str
carbon_intensity: float
def get_carbon_intensity_entry(geographical_server_location_code: str) -> Car... |
7a13a9f48c73cfc4fc0922ba4884576ea5eea5a5f2f315797d53a85b8f4a072d | Python | 1,498 | 48 | # Generated by Django 3.2.6 on 2023-02-20 14:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('biomedisa_app', '0097_alter_upload_resnet'),
]
operations = [
migrations.RenameField(
model_name='specimen',
old_nam... |
93a61d145375db56bd14ad341dbe7a198fbe4c689063302e386544cc578b5084 | Python | 1,499 | 47 | import numpy as np
import pandas as pd
# 读取数据
disease_df = pd.read_csv('data/disease.csv', header=0, encoding='gb18030')
disease = disease_df['disease'].tolist()
rna_df = pd.read_csv('data/rna.csv', header=0, encoding='gb18030')
rna = rna_df['RNA'].tolist()
association_df = pd.read_csv('data/association.csv', heade... |
8291a551ac959d31e0085013e7e36f6200f2f7f0c54e4bdbd4d0b9c05d232380 | Python | 1,500 | 52 | import numpy as np
def compare_transitions(adata, trajectories):
"""\
Compare transition markers between two clades
Parameters
----------
adata
Annotated data matrix.
trajectories
List of clades names user want to compare.
Returns
-------
Anndata
"""
pos_1... |
dddf80e4e44ed2ca85e8c3a9bc7958669ce0b9b49eb0df20e1973f7c6621c3ac | Python | 1,500 | 44 | import glob, os, re, mne
STROKE_ROOT = "data/figshare_stroke/edf_extracted"
HEALTHY_ROOT = "data/physionet_eegmmidb"
RENAME_MAP = {'T3': 'T7', 'T4': 'T8', 'T5': 'P7', 'T6': 'P8'}
NON_EEG = {'HEOL', 'HEOR', 'VEOL', 'VEOR', 'EKG', 'ECG', ''}
CANONICAL_CHANS = [
'FP1', 'FP2', 'FZ', 'F3', 'F4', 'F7', 'F8',
'FCZ'... |
18d8551a791b024c5da99fbbbff82ac605f16d59c78ec269ff5669c0308ccdd5 | Python | 1,501 | 34 | from pyabf.abf2.section import Section
class EpochPerDACSection(Section):
"""
This section contains waveform protocol information. These are most of
the values set when using the epoch the waveform editor. Note that digital
output signals are not stored here, but are in EpochSection.
"""
def ... |
2503932e8c242c459642cc30f769da476f59d6312f3c59dbb8ee9d30cc8f4ce6 | Python | 1,501 | 48 | from __future__ import annotations
from typing import TYPE_CHECKING
from gymnasium import Wrapper
if TYPE_CHECKING:
from neurogym.core import TrialEnv
class Noise(Wrapper):
"""Add Gaussian noise to the observations.
Args:
env: The NeuroGym environment to wrap.
std_noise: Standard devia... |
7049ba099a3fa07b0b454c197d90d2f1539be9a35dfc3040f94d126800ba9111 | Python | 1,502 | 47 | import torch
import numpy as np
from src.datasets.transforms import ClipGrayscale, ClipNormalize
from torchvision.transforms import Resize, InterpolationMode
class BaseDataset(torch.utils.data.Dataset):
def __init__(self, normalise=True, scale=1, grayscale=True):
h, w = self._get_dimensions()
mea... |
974ab753fac8bb6b677932926d6505142da1068028b3393bb613b80ee24185d0 | Python | 1,502 | 45 | """Test to ensure that the telemetry schema used by the CarbonServer API does not drift from the core telemetry schema defined in CodeCarbon."""
import importlib.util
from copy import deepcopy
from pathlib import Path
from carbonserver.api.schemas_telemetry import TelemetryCreate as ServerTelemetryCreate
REPO_ROOT =... |
f405fb961134e8169417114ad1d9c033583fc31af9b118441029eea4a584d409 | Python | 1,502 | 49 | import os
import sys
import traceback
from pathlib import Path
from typing import Dict
import numpy as np
import snapatac2 as sa2
import pyprojroot
code_root_dir = str(pyprojroot.here())
pack_dir = f"{code_root_dir}/package/python"
sys.path.insert(0, pack_dir)
import utils #pyright: ignore # noqa: F401, E402
# * log... |
5830d76b4c82bf71ec21efcb0d52fc5c4fbd157a068aecc4198b0e7d5ede4b5f | Python | 1,503 | 29 | import mne, numpy as np, itertools
from mne.decoding import CSP
from sklearn.pipeline import Pipeline
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import cross_val_score, StratifiedKFold
BASE = "data/physionet_eegmmidb"
SUBJECTS = [f"S{i:03d}" for i in range(1, 21)]... |
263c533a57478d6627c24310201352e9ffc2308ed9ab91864b74a99c3b8948d5 | Python | 1,504 | 50 | """
Title: SpatialBasePlot for all spatial coordinates and image plot
Author: Duy Pham
Date: 20 Feb 2021
"""
from typing import Optional, Union, Mapping # Special
from typing import Sequence, Iterable # ABCs
from typing import Tuple # Classes
import numpy as np
from anndata import AnnData
from .utils import (
... |
6784d10aa1de00b37cde70b8f31e9b1d5bc504d490e4a1ee7b995fed7eaa8084 | Python | 1,504 | 57 | from pathlib import Path
import geopandas as gpd
import spatialdata.models as models
from stlearn._compat import get_adata, is_spatial_data
def polygon_annotations(
data,
annotations,
label_column="label",
obs_key="region",
spatial_key="spatial",
table_key="table",
copy=False,
):
"""... |
6803dbe3248e98866255b49630a76e073174e80f42562d1804b50f01994afcf6 | Python | 1,504 | 55 | import numpy as np
from mirp._masks.base_mask import BaseMask
def split_masks(
masks: None | BaseMask | list[BaseMask],
boundary_sizes: None | list[float] = None,
max_erosion: None | float = 0.8
):
if boundary_sizes is None or len(boundary_sizes) == 0 or \
all(boundary_size ==... |
954020a3851f5aeb921b90e14a4e52213ed3a0b0e03c6fb924282639efcced5c | Python | 1,504 | 44 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for eigenvalue solver."""
import unittest
import numpy as np
from sknetwork.data import miserables, karate_club
from sknetwork.linalg import LanczosEig, SparseLR
def eigenvector_err(matrix, eigenvectors, eigenvalues):
"""Approximation error for eigenvecto... |
c7c10a7fb8ec0f7f6427d72e564d86e3e31129ff52be218d7040932d0e1bbceb | Python | 1,504 | 53 | #!/usr/bin/env python
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sys
import scipy
import sklearn
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
i... |
2fc77acc2c7ce56dba32592d978d188d06b56ecc5e1dd53b1dabea05defedfae | Python | 1,505 | 50 | import numpy as np
import pandas as pd
import time
import random
import csv
import os
import copy as cp
import heapq
import pickle
import cmcrameri.cm as cmc
from scipy.stats import norm
from scipy.integrate import odeint
from scipy.interpolate import RBFInterpolator
from PCAfold import preprocess
from PCAfold import ... |
4f312b04c1a8ea50ebc903a0c01f0588285c88cbfc556bb07af95b86da79b24b | Python | 1,506 | 29 | basic = "/Users/talley/DropboxHMS/CBMF/lattice_sample_data/lls_basic_samp/"
mitosis = "/Users/talley/DropboxHMS/CBMF/lattice_sample_data/lls_mitosis_samp/"
bidirectional = "/Users/talley/DropboxHMS/CBMF/lattice_sample_data/lls_bidirectional/"
bleedthrough = (
"/Users/talley/DropboxHMS/CBMF/lattice_sample_data/lls_b... |
54fa0a4cf0f7d476fe31abb5f217273b9389c94d15ab64eecbc1d2ce62c63b99 | Python | 1,506 | 54 | # Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
# This script can be executed from the Terminal using $ pythonw
# dataset: mne_sample
from eelbrain import *
w = 3
# load sample data
ds = datasets.get_mne_sample(sub="modality=='A'", sns=True)
# interactive plot
plot.TopoButterfly('meg', ds=ds)
# plot top... |
4a6e70b8b41280a1c1953c1a0687ed5db23686c5c02bcd5f52046645c736ab0c | Python | 1,508 | 69 | import os
import signal
import subprocess
from platform import system
from time import sleep
try:
from psutil import (
NoSuchProcess,
Process,
)
except ImportError:
"""Don't make psutil a strict requirement, but use if available."""
Process = None
def kill_pid(pid: int, use_psutil: bo... |
7911c34f14ab03aab4db027c2d7c253a869fcf9cd9d92e7845c5964a02c104a8 | Python | 1,508 | 65 | import os
import pickle
from pathlib import Path
import cProfile, pstats, io
from time import time
'''
Read/write file in a pickle jar
'''
def read_pickle_file(filename):
try:
with open(filename, 'rb') as f:
return pickle.load(f)
except EOFError as e:
print('Corrupted pickle ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.