sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
7d9869931fc82fd3869cf27d23d94a76e3cfff46d32e2497de3004cebb45b40c
Python
1,714
57
from time import sleep from codecarbon import EmissionsTracker def load_dataset(dataset, split): print(f"Loading dataset {dataset} {split}") sleep(5) return dataset def build_model(): model = "huge_model" sleep(5) return model def inference(model, data, inference_task_name): print(f"R...
c795bc3bad1b934593b77a6b07beb12a7f926484ae284e2ac9fab7fd2f0f4c1e
Python
1,717
60
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["motif_model_spec"]["motif_width"] = 13 msp.architecture["motif_model_spec"]["motif_feature_extractor_spec"] = dict( type="ResidualStack", depth=3, ) msp.arch...
703636bf2b432cb66b501ec48303fe76039f47a6ad5afae35aa6a9bea210b632
Python
1,718
72
"""Lightly is a computer vision framework for self-supervised learning. With Lightly you can train deep learning models using self-supervision. This means, that you don't require any labels to train a model. Lightly has been built to help you understand and work with large unlabeled datasets. It is built on top of PyT...
e39569d88ad8df3eea8e8ddd69181147cb97e707d12d9f7a807320b424d5c1db
Python
1,718
50
from typing import Optional, Union from anndata import AnnData from pathlib import Path import os import pandas as pd def lr( adata: AnnData, db_filepath: str = None, sep: str = "\t", source: str = "connectomedb", copy: bool = False, ) -> Optional[AnnData]: """Add significant Ligand-Receptor p...
e4c355cb008cbebc273a81d9c118f2ce7695dc2a7a652275e5e63e67b93cfc95
Python
1,718
75
import pandas as pd import pytest import larvaworld import larvaworld.lib.process.dataset import larvaworld.lib.reg as reg pytestmark = [ pytest.mark.integration, pytest.mark.heavy, pytest.mark.skip(reason="legacy integration tests kept for manual execution"), ] def test_import_Schleyer(): g = reg....
176be4cd3fb5761ddeb46c977aefbc6844b79dfce555b4eefc05767243d4b9c0
Python
1,719
44
import scanpy from anndata import AnnData def run_diffmap(adata: AnnData, n_comps: int = 15, copy: bool = False): """\ Diffusion Maps [Coifman05]_ [Haghverdi15]_ [Wolf18]_. Diffusion maps [Coifman05]_ has been proposed for visualizing single-cell data by [Haghverdi15]_. The tool uses the adapted Gauss...
25a79f4d3cb5d94a999c1d89ba7753bb3e08ce827fe65ddfaa235b7de69d6b72
Python
1,719
44
import torch from pytorch_lightning import LightningModule, Trainer from torch.utils.data import DataLoader from torchvision.datasets import FakeData from lightly.transforms.torchvision_v2_compatibility import torchvision_transforms as T from lightly.utils.benchmarking import MetricCallback class TestMetricCallback:...
57d2ed1784b19da5caf70538dc49eceadb14c23127600b3ac6792aa533b33565
Python
1,719
50
#!/usr/bin/env python # fix problems with pythons terrible import system import sys import os file_dir = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os.path.join(file_dir, '../')) from prob2020.python.bed_line import BedLine import pandas as pd import argparse import IPython def parse_arguments(): ...
68154a44d42b7cd59fe81eca3991750683adff2eda761dc2bbea5a5d471461d9
Python
1,719
50
from functools import partial from typing import Tuple import jax import jax.numpy as jnp @partial(jax.jit, static_argnames=['vec']) def hebb_update(w: jnp.ndarray, X: jnp.ndarray, y_hat: jnp.ndarray, eps: float, lam: float, vec = False) -> jnp.ndarray: """ Performs one Hebbian update step. :param w: Weigh...
da1b9e60b5fac4b2e763167f30801812220ab5b3a906b4a3491ed04635c521c0
Python
1,719
58
import sys import os.path as op from setuptools import setup, find_packages # get the version (don't import mne here, so dependencies are not needed) version = None with open(op.join("pyriemann", "_version.py"), "r") as fid: for line in (line.strip() for line in fid): if line.startswith("__version__"): ...
a13175b65399f41c65b2edd8740ff679cbba481d95ef049bf87d1086112e7cbb
Python
1,720
51
# coding=utf-8 # Copyright 2025 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...
bf1dbb6ead03f8ce0d1a4702947f762bd26024b6e935e17b21cc7dff770a09d0
Python
1,720
61
"""Append-aware backward validator regression tests.""" from __future__ import annotations import pytest import torch from torch import nn import torchlens as tl from torchlens.intervention.errors import AppendStateValidationWarning from torchlens.options import CaptureOptions, ReplayOptions from torchlens.validatio...
c5e83960644f06a82ba3345c92a2b722f139417e281ffaa984526d0e44a76156
Python
1,720
60
""" opto.py Contains modules for opto stimulation tag generation and analysis using Pulse Pal. For more information regarding stimulation setup see: https://sites.google.com/site/pulsepalwiki/parameter-guide """ import numpy as np ####################################################################################...
b9ea14b29a04270155dcfa602d736cbed0b8edcc7c350fe8cf1c5d566cb9d90f
Python
1,722
64
from __future__ import absolute_import from mxnet.gluon import nn, HybridBlock from mxnet import init from mxnet.gluon.model_zoo import vision class ResNet(HybridBlock): __factory = { 18: vision.resnet18_v1, 34: vision.resnet34_v1, 50: vision.resnet50_v1, 101: vision.resnet101_v1,...
36cefcb4b866914cf68374981d65a2261f43e98f8243fe37fb112218c7e3b928
Python
1,723
80
# Optimization utilities import numpy as np from scipy import optimize fmin = optimize.fmin leastsq = optimize.leastsq exp = np.exp def gaussian(x, params): (a, b, c,f) = params return a * np.exp(-(x-b)**2/(2*c**2))+f def fwhm(c): return np.sqrt(2*np.log(2))*c def score_gauss(p, x, v): return sum((...
d3d3538e36e102f90dd5dbdb1759b1831a3cbbcc56e16693e2c7df2bba194834
Python
1,724
48
import numpy as np class MultiTermLossFunction(object): def __init__(self, loss_fn, weight) -> None: self.terms = list(weight.keys()) if type(loss_fn) is not dict: self.loss_fn = {term:loss_fn for term in self.terms} else: self.loss_fn = loss_fn sel...
fa3f5ee7cafb12f2d05e57ac0ed948084fb6155c473bc10dc5b08939515a3a18
Python
1,724
45
""" This is an example script showing how to process your own data. You need to provide SMILES and their bioactivity. """ from MoleculeACE.models import RF, SVM, GBM, KNN, MLP, GCN, MPNN, AFP, GAT, CNN, LSTM, Transformer from MoleculeACE.benchmark.const import Descriptors from MoleculeACE.benchmark.data_prep import pr...
0c28efff0017e54ade3b3969ded6cce2b41b81ebb673a25f05ad6fa4d6cb8fff
Python
1,725
60
"""Test configuration script.""" import numpy as np import pytest import pynapple as nap def skip_if_backend(backend_name): """Skip test if the backend matches `backend_name`.""" return pytest.mark.skipif( nap.nap_config.backend == backend_name, reason=f"Test skipped because backend is {back...
58a50ec90f56885054ad72b354fd267472b886d7fdfeb163f0ce7ff9cce8575e
Python
1,725
52
"""Adapted from: https://github.com/https-deeplearning-ai/GANs-Public.""" from typing import Any, Tuple import torch from pl_bolts.utils import _PIL_AVAILABLE, _TORCHVISION_AVAILABLE from pl_bolts.utils.warnings import warn_missing_pkg if _PIL_AVAILABLE: from PIL import Image else: # pragma: no cover warn_m...
aca1cbd0999f11173f3082320948a5d37b92a6b0e94b51d24eea5d16565483f0
Python
1,725
39
from unittest import TestCase from drug_interactions.reader.dal import Drug, DrugBank from drug_interactions.reader.preprocessor import DrugPreprocessor class DrugPreprocessorTestCase(TestCase): def setUp(self): self.drug1 = Drug(**{'id_': '1', 'interactions': {('3', 'bar')}}) self.drug2 = Drug(*...
af02b7d49f565fa49cf74deca4f322312314c85906d5b0caa83c1636277c5c65
Python
1,725
38
import unittest from config_manager import base_configuration from config_manager import config_field class TestBaseConfiguration(unittest.TestCase): """Test class for base_configuration.BaseConfiguration unit tests.""" def test_validate_field(self): valid_test_fields = [ ({"hello": "worl...
8c3de6705a22d587e8204ae21f185e9f40f2d5df2aa3ea30b5945a3c30befc37
Python
1,726
62
import numpy as np import itertools as itt def _sorted_memberships(membs): return np.array(sorted(list(range(int(np.max(membs)+1))), key=lambda i:np.sum(membs==i))) def sort_clusters_by_size(membs): """ Sort cluster indices such that cluster with smallest index has most members. """ sorted_id...
d6fa9b446206bb20c3a2fcaf8d72ffde11a92878266eefa91ab50e51e0415887
Python
1,726
55
""" Tools for matplotlib plot exporting """ def ipynb_vega_init(): """Initialize the IPython notebook display elements This function borrows heavily from the excellent vincent package: http://github.com/wrobstory/vincent """ try: from IPython.core.display import display, HTML except I...
574ea8cd214f24eb29de46e57a9cba434b1de29d6101993f692e42f6f0005d7c
Python
1,727
67
#!/usr/bin/env python3 '''convert gninatypes file to xyz file''' import struct, sys, argparse from functools import partial import molgrid names = molgrid.GninaIndexTyper().get_type_names() def elem(t): '''convert type index into element string''' name = names[t] if 'Hydrogen' in name: return 'H'...
c0f5967cb27def29acb5c9ec9df82e8c9fa02e95699ba8895fe8224d830cdc99
Python
1,727
61
__author__ = 'quentin' import cv2 from ethoscope.hardware.input.cameras import MovieVirtualCamera import numpy as np from math import log10 import os import random class NegativeMaker(object): _path = open("/tmp/fly_snapshots/negative.csv","w") def run(self, camera): for j, (t,f) in enumerate(cam...
2a8dd4367d9d238de92829e0ecfb00fee2643a58d44c10dc0de3f4d249227a74
Python
1,728
44
import sys # setting path sys.path.append('../TM2_segmentation') import os import numpy as np import nibabel as nib import itk import pandas as pd import tarfile from scripts.preprocess_utils import find_file_in_path, register_to_template # load metadata file input_annotation_file = '/media/sda/Anna/28andme/ds002...
6fd8ae989d81617c83f5e86564179853eb6f396db31e3cd29103e9349176b3c8
Python
1,729
66
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["motif_model_spec"] = dict( type="AdjustedMotifModel", model_to_adjust_spec=dict( type="PSAMMotifModel", motif_spec=dict(type="rbns"), e...
e2b55c8efe70e8212eb3e28b77f0198aab7635afe1052b10399d221711f704a7
Python
1,729
48
from imodelsx import submit_utils from os.path import dirname, join import os.path repo_dir = dirname(dirname(os.path.abspath(__file__))) params_shared_dict = { 'seed': [1], 'save_dir': [join(repo_dir, 'results')], 'use_cache': [1], 'batch_size': [64, 16, 4], 'renormalize_embs_strategy': ['Standard...
0075c69137e2ab68aaa3402afda80e97c84c10a74a4dd3c4294e100a4be7c50c
Python
1,730
60
# Copyright 2024 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
0c938493ab7a20b7c5bf3cc296b52542e610245a2aefd569264d29f9442ea02c
Python
1,730
55
import sys from ij import IJ from ij.plugin import Duplicator # Fiji Jython interpreter implements Python 2.5 which does not # provide support for argparse. input_file = sys.argv[-13] xleft = int(sys.argv[-12]) width = int(sys.argv[-11]) ytop = int(sys.argv[-10]) height = int(sys.argv[-9]) first_channel = int(sys.arg...
2e3a55301e238560bba354fb2d6d1f61747330bad5763653dba1a41ab93f7255
Python
1,731
52
import torchinfo import numpy as np import torch.nn as nn def get_conv1dblock_output_len(modules, input_len): """ Get the dimension of the flattened output of a convolutional modules with only Conv1d and Maxpool1d layers. This will be deprecated in the future. Parameters ---------- modules : ...
91aafeb2379f482991f7ffe152f9d8b10dbbc91579a8788e5cdc3ba405f34987
Python
1,731
65
import copy import warnings from typing import Optional, Type, Union class bcolors: """ANSI escape sequences for colored terminal output.""" HEADER = "\033[95m" OKBLUE = "\033[94m" OKGREEN = "\033[92m" WARNING = "\033[93m" FAIL = "\033[91m" ENDC = "\033[0m" BOLD = "\033[1m" UNDERL...
414dd7ceeb5a1ca40d38d83994416457f75d46e4c5cb1318fe2af061ad064d12
Python
1,732
58
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from numpy import array import numpy as np #import array_tools from dcCustom.metrics import swapped import sys import pdb def cindex_singletask(Y, P): #Y = np.array(...
6260d87540ed6388c8c153157a77a040bf0154712ab3a6c8e0af4d357a15276f
Python
1,732
38
from __future__ import print_function import os from bleualign.align import Aligner if __name__ == '__main__': current_path = os.path.dirname(os.path.abspath(__file__)) options = { # source and target files needed by Aligner # they can be filenames, arrays of strings or io objects. 'srcfile':os.path.join(curre...
71170779a308e19342834c6f6cc886a29966c54486f2926373b8396eaec64a12
Python
1,732
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...
6ad51f1a5796838abde0edc046363c4e63281492dc9bf47c69e84cca45d1aec9
Python
1,733
49
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # Written by Yuichiro Yada #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ################################################ # A code for Fig. 2f. Before running this code, please run "prediction_realdata.py" # with and without gradient_term, and set the resulting amyl...
6e018ac5cd5c4575ace7e4c6038b36ca4aabb5a2d0cf45e968047c3c8377cc12
Python
1,733
51
"""Module for dynamic data transfrom.""" import os import importlib from .transform import make_transforms, get_specials,\ save_transforms, load_transforms, TransformPipe,\ Transform AVAILABLE_TRANSFORMS = {} def get_transforms_cls(transform_names): """Return valid transform class indicated in `transfo...
8d5cd6e1bce54513dfc7cef8f85a501aa3b1a25a2f32753939df5aaa6852c2e5
Python
1,733
62
_author__ = "quentin" # flake8: noqa: E402 import time from ethoscope.hardware.interfaces.lynx_motion import LynxMotionInterface class OdourDelivererInterface(LynxMotionInterface): _positions_to_angles = {1: -25, 2: 20, 3: 0} _dt = 250 def __init__(self, *args, **kwargs): self._current_pos = [3...
a726ba2dfb66e96e19e86644122b884c1efb5ad5f5d0ef8dd4d18343f67d7da3
Python
1,733
56
from torch_geometric.data import Data from torch_geometric.data import InMemoryDataset, download_url import torch import pandas as pd from featurizer import MolecularGraphData, SMILESToECFP4 from sklearn.model_selection import train_test_split class MolecularDataset(InMemoryDataset): def __init__(self, root, csv_...
33a28cef04acaedb680044152119a13442ab61cfbe51e51486f65e1b961495c1
Python
1,735
46
import os from data import common from data import srdata import numpy as np import torch import torch.utils.data as data class Runtime(srdata.SRData): def __init__(self, args, name='', train=True, benchmark=True): super(Runtime, self).__init__( args, name=name, train=train, benchmark=True ...
5c69ebf460c354dc8037730e2e336fb70035b234f89808966e2ea869e3cbe626
Python
1,735
58
from __future__ import print_function, division, absolute_import from .fbresnet import fbresnet152 from .cafferesnet import cafferesnet101 from .bninception import bninception from .resnext import resnext101_32x4d from .resnext import resnext101_64x4d from .inceptionv4 import inceptionv4 from .inceptionresnetv2 im...
95edc142174cde5ac5b45634ca9f69548302bb50eaa56086d9644d8985fecc22
Python
1,735
58
from anndata import AnnData from typing import Optional, Union import numpy as np from stlearn.spatials.trajectory.utils import _correlation_test_helper def set_root(adata: AnnData, use_label: str, cluster: str, use_raw: bool = False): """\ Automatically set the root index. Parameters ---------- ...
94d644a3e905504d399261e3e92d15a1f297d54123e51c54af55f39bdfb5b43b
Python
1,736
58
# %% [markdown] # # Write HCS Plates # (tutorials:write_hcs_plate)= # # This tutorial shows how to write a high-content screening (HCS) dataset to OME-NGFF format. # HCS datasets represent culture plates with multiple wells, where each well can contain multiple fields of view. # # ## Create sample data # # First, let's...
c4e8668aa1bf8eaada32eb5b5b0fe16627001193edabeae54090af216c92e50e
Python
1,736
49
#!/usr/bin/env python """Tests for `stringdb` package.""" import pytest import stringdb @pytest.fixture() def mapped_ddr_ids(): """Example string ids""" string_ids = stringdb.get_string_ids(['TP53', 'BRCA1', 'FANCD1', 'FANCL']) return string_ids def test_string_mapping(mapped_ddr_ids): assert (m...
53339ef22afe0c7c47e9fb9a67c1a87ae018a0a8805a8693c9a62f858203687c
Python
1,737
54
"""Benchmarking module for AlignmentFile functionality""" import os import pytest from VariantFileFetchTestUtils import * GENOMES_URL = "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr{chrom}.phase3_shapeit2_mvncall_integrated_v5a.20130502.genotypes.vcf.gz" CHROM = 22 @pytest.fixture def genomes...
7ca225e72fe471b009e8760f71f7425d7eee9c8bd9bd302e07a91037865fb84c
Python
1,737
56
import os import random import numpy as np from skimage import io, color import cv2 images_path = './GT' # series of graound truth hypothalamus masks masks_path = './pred' # series of predicted masks img_overlay_path = './overlay' img_overlay_GT_path = './overlay_GT' images = [] masks = [] images_name = [] for im i...
84ca4dc0b1747fdc3b6436d15b7cfd4b3893c2c53771b849d68ca6b3b618079c
Python
1,737
57
import pyvista as pv import numpy as np def vtk2swc(inputfile, outputfile): """ Function to convert a .vtk file into a .swc file. Required arguments: inputfile: [string] Path of the reconstruction format to convert. outputfile: [string] Path of converted SWC file. ...
8a05119e6c16449cdae3f7bee2ef1355aa36d688ba7cd9d18a4b0baf05eb9246
Python
1,738
58
"""Test functions in xcp_d.utils.execsummary.""" import os import matplotlib.pyplot as plt from xcp_d.data import load as load_data from xcp_d.tests.utils import chdir from xcp_d.utils import execsummary def test_make_mosaic(tmp_path_factory): """Test make_mosaic.""" tmpdir = tmp_path_factory.mktemp('test_...
264b8c63056c87ca5dbde51740774178cdb7e997630a689cbace4a9c62cf8c67
Python
1,739
65
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["motif_model_spec"] = dict( type="AdjustedMotifModel", model_to_adjust_spec=dict( type="PSAMMotifModel", motif_spec=dict(type="rbns"), e...
c3b5307e22a76134f87a8d29810e12387fc096b9ff6f08423d5436cfa5eb69b0
Python
1,739
68
from unittest.mock import patch import pytest from celery.utils import deprecated class test_deprecated_property: @patch('celery.utils.deprecated.warn') def test_deprecated(self, warn): class X: _foo = None @deprecated.Property(deprecation='1.2') def foo(self):...
6411388dea93ac1f88605de75506e8e32ae87eaca5d265794620eb64c65d5d9f
Python
1,740
49
import subprocess import sys import textwrap import pytest @pytest.mark.parametrize('multi,template,expected', [ (False, '%%n-%n.log', '%n-worker.log'), (False, '%%x.log', '%x.log'), (True, '%%%%n-%n.log', '%n-worker.log'), (True, '50%%%%d.log', '50%d.log'), (True, '%%%%x.log', '%x.log'), (Tr...
8560942a164e0efc38efe051e05c3ae3c46d38b8dfb0b40e1d06fca64a1fa2ba
Python
1,742
60
""" Interface between a larvaworld simulation and a remote model """ from __future__ import annotations from typing import Any __displayname__ = "Client-Server" __all__: list[str] = ["Client", "Server", "BrianInterfaceMessage"] from .ipc import Client, Server, Message class BrianInterfaceMessage(Message): ""...
3c1853ef6d980db9cf1ab197403d7fb1ba53f8ae02fd512f0ff24f07f1c59d93
Python
1,744
67
import numpy as np import matplotlib.pyplot as plt # define lotka-volterra operator ################################ from pyrates import OperatorTemplate op = OperatorTemplate( name="lv", equations="x' = x*(alpha + x_in)", variables={"x": "output(0.5)", "alpha": 0.5, "x_in": "input(0.0)"} ...
6c9e64f961ad8507670d8fc4f1931d48f99312c6ff1535ed744eefe97cb76faf
Python
1,744
65
import pandas as pd import numpy as np import random np.random.seed(1000) random.seed(1000) def make_synthetic_data(tgi_path, OS_path, ptnm_path): tgi_df = pd.read_csv(tgi_path) OS_df = pd.read_csv(OS_path) ptnm_df = pd.read_csv(ptnm_path) # randomize NMID unique_nmid = pd.unique(tgi_df.NMID) ...
731e2d297569ce5465e8ee2de940113db1fb196977199e0aad5ba21cfc79db5c
Python
1,744
66
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import seaborn as sns dt = 10e-3 # sampling interval baserate = 5.0 amplitude = 4.0 basename = "rates" np.random.seed(42) def get_random_signal(period=10.0, alpha=1.5, nb_repeats=11, cutoff=128): theta = np.random.rand(cutoff,2) durati...
f69f23edc68347b476e79c4e35612a8673227aaa6f4b1783712275ecebfd2382
Python
1,744
48
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ @author: Pramod Bharadwaj Chandrashekar, Li Liu @email: pchandrashe3@wisc.edu, liliu@asu.edu """ import numpy as np from sklearn.cluster import KMeans import scipy.stats as stats def get_cdf_pval(data): """ Function for guassian mixture of dat and computing pval...
110495e4fda8c685017d44526078beb9602d54135fdfc83a802b1d35ca331e5f
Python
1,746
63
"""Trace a toy transformer block that builds its mask with ``torch.vmap``.""" import torch from torch import nn import torchlens as tl class VmapMaskedToyTransformer(nn.Module): """Tiny attention-style block with a vmapped mask builder.""" def __init__(self, width: int) -> None: """Initialize the t...
d1946b83a94b6516323c1554b4dd7849f63c7859129696c2d0b39c87253d7be7
Python
1,746
65
'''Definition of bifurcation functionality''' import numpy as np import tns.morphmath.rotation as rt from tns.morphmath.utils import get_random_point def random(): ''' Get 3-d coordinates of a new random point. The distance between the produced point and (0,0,0) is given by the value D. ''' d...
e93d0658ea52e5b84fb25c1003324886fee4b0660eef55590e2b67ac1a05bf40
Python
1,746
54
import json import unittest from types import SimpleNamespace from cellxgene_gateway.gateway import do_GET_status_json, app, cache from cellxgene_gateway.cache_entry import CacheEntry, CacheEntryStatus class TestGatewayStatusJson(unittest.TestCase): def test_do_GET_status_json_returns_expected_structure(self): ...
489859dc4ce5bb24ebc653e70fadfc32ac8098b9edddaf79d381611b0ffe053b
Python
1,747
57
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # 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 app...
6bf52dd2c94f37db2562989dc96e04e88e82dacf4925def6ac65d50302146786
Python
1,747
55
"""Fuse Many image of CT and RMI using a json file """ from os.path import dirname, abspath, join, exists from os import makedirs from SEEGFusion import ImageFusion import SimpleITK as sitk import json import sys def main(argv): output_path = join( dirname( dirname( dirname(abs...
98b31acaa70a6a1b907453c0f53ced9397dbdab048dd327853a228f3d621f60a
Python
1,747
55
""" Get snap2 file with all the samples. """ import os import sys import logging from pathlib import Path from typing import Dict, List import numpy as np import snapatac2 as sa2 import pyprojroot proj_dir = str(pyprojroot.here()) pack_dir = f"{proj_dir}/package/python" sys.path.insert(0, pack_dir) from mylog impor...
c44e8659c392c583e43e0fa906916d5c3f7c372c4d1b9049178f1d664e0cadca
Python
1,747
70
import os import pytest from hobj.data.behavior import load_highvar_behavior, load_oneshot_behavior from hobj.data.images import ( load_image, load_imageset_meta_catch, load_imageset_meta_highvar, load_imageset_meta_oneshot, load_imageset_meta_warmup, ) pytestmark = pytest.mark.skipif( os.env...
4ab67ea4feef2c9263157639da7121fbff29bda2ee057e2105e08c1b9bafe0ce
Python
1,748
66
from scipy import misc import os, cv2, torch import numpy as np def load_test_data(image_path, size=256): img = misc.imread(image_path, mode='RGB') img = misc.imresize(img, [size, size]) img = np.expand_dims(img, axis=0) img = preprocessing(img) return img def preprocessing(x): x = x/127.5 - ...
706390b1dc0ab6b6518be9e231a29a9feb5e2e61d76479beef71bb5c16809cc8
Python
1,748
66
""" Check whether the start codon is present """ import os.path import logging from Bio import SeqIO from .utils import find_gapped_pos # pylint: disable=C0103 # Invalid constant name logger = logging.getLogger('pipe.gag_codon') def gag_codon(configs, seqs): """Primer check. Check whether any of the prim...
8ee21f536e385ca123899adf0c5f7bb5fc2aea62b3bbe8b632ce7857c41d87ab
Python
1,748
58
""" This code demonstrates how to perform measurements on small ranges of sweeps. """ # import the pyabf module from this development folder import os import sys PATH_HERE = os.path.abspath(os.path.dirname(__file__)) PATH_SRC = os.path.abspath(PATH_HERE+"/../src/") PATH_DATA = os.path.abspath(PATH_HERE+"/../data/abfs/...
1a2edc72042d6f9bd52fe007c381a85592b5575ceaebc87e00f9556f7a8095c8
Python
1,749
43
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu> """Accessible tool for statistical analysis of MEG and EEG data. For the full documentation see <http://eelbrain.readthedocs.io>. "The human brain is like an enormous fish. It's flat and slimy, and has gills through which it can see." ...
8a28c8c6f7301e0471703c717204c245f2782c0a3e5802086bfc1a64068ce9b5
Python
1,749
44
from __future__ import division import argparse import numpy as np import mxnet as mx from mxnet import gluon, nd, image import matplotlib.pyplot as plt import gluoncv as gcv gcv.utils.check_version('0.6.0') from gluoncv import data from gluoncv.model_zoo import get_model from gluoncv.data.transforms.pose import det...
cc37232161065ebf0a51e69d2094913e929c87b6b669b2c2f7150929e4a6950c
Python
1,749
61
import os import time import h5py import numpy as np import scanpy as sc from ica import ica1 from memory_profiler import profile from scbig.utils import setup_seed def preprocess(adata, scale=True): sc.pp.filter_genes(adata, min_cells=3) sc.pp.filter_cells(adata, min_genes=200) sc.pp.normalize_total(ad...
d90b57da26216723a1dd0a78efb5e5998a995c0c4421a23304c8a85b3ee116b4
Python
1,749
50
import cv2 import os import numpy as np class Combine_Image(): def __init__(self, path_AB): self.path_AB = path_AB if not os.path.exists(path_AB): os.makedirs(path_AB) def combine_image(self, path_A, path_B): img_A = cv2.imread(path_A) img_B = cv2.imread(path_B) ...
26222a4e6fe27fb3a2c461f0fd13022593375e42159a63976b4a5d100da0ba50
Python
1,750
63
"""Creating events, and event exchange definition.""" import time from copy import copy from kombu import Exchange __all__ = ( 'Event', 'event_exchange', 'get_exchange', 'group_from', ) EVENT_EXCHANGE_NAME = 'celeryev' #: Exchange used to send events on. #: Note: Use :func:`get_exchange` instead, as the type of ...
53bfbfe32ed1f9c15f435b5f0da2635dd73c2e5057cbe5d8dfd55f8e5f908df4
Python
1,750
49
"""A custom nms module for tvm with static shape""" # pylint: disable=unused-argument from tvm import relay from tvm.relay.frontend.pytorch import _op, AttrCvt, get_relay_op def nms(inputs, input_types): """A static NMS hack for torchvision.nms, it requires the nms to be the last layer of the network""" boxes ...
753b6c966f5913ce6d490d5e0d96170226cb31f1b04c88a89861412a9a288d97
Python
1,751
42
from typing import Any, Dict, Iterable, Optional, Tuple import argparse import torch import torch.nn as nn import transformers from imodelsx.iprompt.utils import PrefixLoss, PrefixModel class PromptTunedModel(PrefixModel): args: argparse.Namespace loss_func: PrefixLoss model: transformers.PreTrainedMod...
7e250a4f4da7f3994d64c90cdcdacbb6c5c5a83046b65c623776d06116324f56
Python
1,751
46
"""add_indexes_for_workflow_comment_foreign_keys Revision ID: 2dc3386d091f Revises: 8a19186a6ee7 Create Date: 2024-03-13 15:25:52.587488 """ from galaxy.model.database_object_names import build_index_name from galaxy.model.migrations.util import ( create_index, drop_index, index_exists, ) # revision ide...
8849bbfec8e2534c54b4484f4f751ff3e05732acec6df0330ce7057d71da668e
Python
1,751
49
""" Integration tests for calibration.py using REAL LarvaDataset. Uses real dataset from registry (exploration.30controls) with full preprocessing. Requires ensure_datasets_ready fixture. """ import pytest pytestmark = [pytest.mark.integration, pytest.mark.heavy] @pytest.mark.usefixtures("ensure_datasets_ready") d...
fe7cd5f008f154a147c5a0e47ca1fbe31e79bd9146b421e85fcc41b1c4e554cc
Python
1,752
47
import time import torch import torch.utils.benchmark as benchmark from triton.testing import do_bench if torch.version.cuda: backendBLAS = "cuBLAS" elif torch.version.hip: backendBLAS = "hipBLAS" def benchmark_forward(fn, *inputs, repeats=10, desc='', verbose=True, **kwinputs): """Use Pytorch Benchmark ...
a0f795d37f3a6474b9202669495ba0d77a96bb562daad64c9561e21fa78aa28d
Python
1,753
52
from __future__ import division import unittest import random import numpy as np from wyrm.types import Data from wyrm.processing import sort_channels, swapaxes, CHANNEL_10_20 class TestSortChannels(unittest.TestCase): def setUp(self): self.sorted_channels = np.array([name for name, pos in CHANNEL_10_...
4e33fcc9ba117ae56ee724d613b888a357c5552a856a642671480686347f8ac5
Python
1,755
61
import json from textwrap import dedent from caper.singularity import find_bindpath UBUNTU_18_04_3 = ( 'ubuntu@sha256:d1d454df0f579c6be4d8161d227462d69e163a8ff9d20a847533989cf0c94d90' ) UBUNTU_18_04_3_LAST_HASH_TAR_GZ = ( 'sha256:6001e1789921cf851f6fb2e5fe05be70f482fe9c2286f66892fe5a3bc404569c.tar.gz' ) def...
5b197dfaec03f7c10fd3d0b799ff6a4e31669ed5195b8911f4f7852a7fa48397
Python
1,755
52
#!/usr/bin/env python """ Convert a GFF and the associated sequence (FASTA) into GenBank, embl or FASTA format. https://raw.github.com/chapmanb/bcbb/master/gff/Scripts/gff/gff_to_genbank.py Usage: gff_to_gb_or_embl.py <GFF annotation file> <FASTA sequence file> <Output file> <Output format genbank or ...
f6589e3a73506e48dfed8b3e0c831b30145e0318175f7ee7af952b9f9c567e44
Python
1,755
45
"""Building blocks for world models. A world model predicts how an environment evolves. A latent world model does it in embedding space: it predicts the embedding of the next frame from the embeddings of the past frames, optionally conditioned on the action that was taken. The modules here are parts that latent world...
f791f7ddb91bfe44881c7f161fad196d06e89535eb41e3a98315f955a2c02dcd
Python
1,755
51
from mirp._images.generic_image import GenericImage class MRDCEImage(GenericImage): # Diffusion contrast-enhanced MR consists of multiple types of (semi-)quantitative parametric maps. These maps all # quantify different characteristics, some of which may contain negative numbers. def __init__(self, **kwa...
a2f797b6aa562a93f47de4cd78a0e982660074324d14d7570bb56a355feaffa9
Python
1,756
43
from imodelsx import submit_utils from os.path import dirname import os.path repo_dir = dirname(dirname(os.path.abspath(__file__))) # python /home/chansingh/llm-tree/experiments/01_train_model.py --use_cache 0 --subsample_frac 1 --model_name llm_tree --max_depth 3 --use_llm_refine 1 # python /home/chansingh/llm-tree/...
420b3d21b7012c88c75cdabfd94b16e82111839b0417ee24867d29a129fccada
Python
1,757
78
import array import pytest import rpy2.rinterface as ri ri.initr() def test_init_from_seqr(): seq = [True, False, False] v = ri.BoolSexpVector(seq) assert len(v) == 3 for x, y in zip(seq, v): assert x == y def test_from_int_memoryview(): a = array.array('i', (True, False, True)) mv ...
1bdedd2b858c86adf5d89ee1bc212d6f94304959a0a8a1e4d523354b8c746d74
Python
1,758
69
#!/usr/bin/env python # -*- coding: utf-8 -*- import os # download model weights import gdown import shutil from zipfile import ZipFile # constant values from .constants import RESET_COLOR_CODE from .constants import GREEN_COLOR_CODE from .constants import RED_COLOR_CODE __author__ = ['Nico Curti'] __email__ = ['ni...
5fed2ef36166046159ccd64950e025a3ac80a1f71795c17ec90f70cdc8c42c99
Python
1,758
57
#!/usr/bin/env python # ============================================================================= # MODULE DOCSTRING # ============================================================================= """ Test objects and function in the module ``tfep.loss``. """ # =================================================...
30a15748069ebadc706472ac219439f39d556d150adca72244d1bb3e7f5ac5ef
Python
1,759
55
""" This module define the class StructurePredictionDataset """ import torch import numpy as np from scipy.spatial.distance import pdist, squareform from datasets_pre_processing.generic_dataset import GenericDataset class StructurePredictionDataset(GenericDataset): """ FINE TUNNING ON Structure """ d...
7cf0576416789a3ec6602ac7dd9ff20d5be3c81c62effb5ae4b26c6170b82bfb
Python
1,760
43
""" Gregory Way 2016 PanCancer Classifier scripts/process_copynumber.py Usage: Run by initialize.sh to initialize repository or in command line Output: Two sample by gene matrices that indicate if the gene has 1) copy number gains or 2) copy number losses in each sample """ import os import pandas as pd copy_input_...
cb88d77b87936fae0f6aca585da3a74540d075388078f7d5b32f4fcd6201b088
Python
1,760
52
# -*- coding: utf-8 -*- from mne.gui._coreg_gui import CoregModel import os import sys import glob def calc_trans(subj, meg_file, subjects_dir, output_dir, task='EO', i='full'): print(meg_file) cm = CoregModel() cm.mri.subject_source.trait_set(subjects_dir=subjects_dir) cm.hsp.trait_set(file=meg_file...
cdee3110cbdc530b026665635c06db999954b24b50c59bdf79ac3cf43c8ef72d
Python
1,760
53
import gzip import os import pandas as pd from typing import Dict, List def generate_bedpe_worker(meta: str, sample: str, infnm: str, outdir:str,) -> bool: """Partition barcodes from a sample bedpe to different goups. Outfile format...
31c60242132dc8b1d18466dd1e037cadca0d2462ee72ee9b7d2023d24f708714
Python
1,761
46
import sys sys.path.append('./src/') import os import pandas as pd import torch import torch.nn.functional as F import numpy as np import tqdm from sklearn import preprocessing import src.generator_transformer as Generator import argparse import json use_cuda = torch.cuda.is_available() tokens = ['/', 'a', 'b', 'c', ...
6edbfdc435bf53d4a781f4f2fe588445bad30e67d523191343a3a94137808e66
Python
1,761
62
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 CeleryLatestWorkerContainer(CeleryWorkerContainer): """Defines the configurations for a Celery worker container....
9b013633caea680ecb5a41ebfebf69e0fd62b1ed94ad26a36b2dc9b44c56c115
Python
1,761
50
"""Absence tests for the deleted capture/IR compatibility shims. The kernel/ledger/projector layer and the ``ModuleEvent``/``BufferEvent`` event kinds were deleted in the backend migration; the compatibility shims that kept their imports resolving were removed in the species-1 cleanup. Contract now: the historical spe...
abee3698d835e4b2f93d7b7adcaac3eae509f417377121a2bc273a658ae33c66
Python
1,761
57
import sys from ij import IJ, Prefs # Fiji Jython interpreter implements Python 2.5 which does not # provide support for argparse. input_file = sys.argv[-8] threshold_min = float(sys.argv[-7]) threshold_max = float(sys.argv[-6]) method = sys.argv[-5] display = sys.argv[-4] black_background = sys.argv[-3] == "yes" out...
fc3d40094698982fa5dde7213afd00c2f12a455efc5474b73d9dfdff50364854
Python
1,761
50
import numpy as np from .conf_ranker import ConfRanker from rdkit.Chem import Mol from typing import List, Any, Sequence class PropertyRanker(ConfRanker): def __init__(self, descriptor_name: str = 'E', ascending: bool = True) -> None: super().__init__(name=descriptor...
33426f47e4b0452b3df0d9095326eacb18176a1a696a0ab4c13167ae694bc8d7
Python
1,762
59
from pathlib import Path import pytest from larvaworld.lib import reg, util from larvaworld.lib.reg import config from larvaworld.lib.reg.generators import ExpConf def test_conf(): conftype = "Exp" id = "dish" id_new = "dish_test" C = reg.conf[conftype] ids = C.confIDs conf = C.getID(id) ...
70fd7df88dcd317327fc61321ec7486737f52d02a776de37702e9900a187e572
Python
1,762
52
"""Test built-in rater""" import pathlib import shutil import tempfile from unittest import mock import h5py from PyQt6 import QtCore import pyjibe.head data_path = pathlib.Path(__file__).parent / "data" def test_rater_basic(qtbot): mw = pyjibe.head.PyJibe() td = pathlib.Path(tempfile.mkdtemp(prefix="rate...
cff345ddfa8dd5cef0f20ad56b87ea3f0aed49b8ad9bc80f5b524b621d5ce670
Python
1,762
41
from ipywidgets import interact, IntSlider, RadioButtons import numpy as np import matplotlib.pyplot as plt class ImageSliceViewer3D: def __init__(self, image, pred, figsize=(15,15), cmap='Greys'): self.pred_orig = pred self.image_orig = image self.pred = pred self.image = image self.fi...
5e656a6eefe4cf75f813262afd70276cfd929d73f2e78a76173fb00575fbb7a1
Python
1,763
48
"""Utilities to create reports and useful print outs.""" from specparam.reports.text import gen_methods_text from specparam.reports.strings import (gen_version_str, gen_settings_str, gen_freq_range_str, gen_methods_report_str) ####################################################...
8d4c22cc046bb19cdd146c26ab69ae5e72cf6a728edef7c3072393367c4e29a5
Python
1,763
57
# --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.4.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Check alignments # Ch...
b5b0635c3109f928df439291d3e31c20f479d4ba27fe066d288dffd1ba52cc50
Python
1,763
48
from skmob.utils import gislib import math class TestClustering: def setup_method(self): self.point_1 = (43.8430139, 10.5079940) self.point_2 = (43.5442700, 10.3261500) self.decimal = 43.8430139 self.DMS = (43, 50, 34.85) def test_get_distance(self): output = gislib....