sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
3316c26e4334fd8f005eeeff935f05fa7dd4e3300aba6a4f56a19ac2ba5d908b
Python
3,116
77
""" ===================================================================== Sample from the Riemannian Gaussian distribution in the SPD manifold ===================================================================== Spectral embedding of samples from the Riemannian Gaussian distribution with different centerings and disp...
45ba596c2a838578c1ba680da8e645c88de2686c12822dbbabccfb281c8b1642
Python
3,116
67
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path from ultralytics import SAM, YOLO def auto_annotate( data: str | Path, det_model: str = "yolo26x.pt", sam_model: str = "sam_b.pt", device: str = "", conf: float = 0.25...
60c6789c0d2b91d24f4e75b3db0959ded4dea46d36c6a54097d00a9896acb2a7
Python
3,116
99
# This example requires the following dependencies to be installed: # pip install lightly # Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import torch imp...
eb52883022e698baa15a9be4fce8f20abacfcc35b9a6a8068c53205eaaf46f40
Python
3,116
68
"""Consumer-case exit tests for Spec C: nested R=2 Ragged + string-under-axis. Three real-world use-case shapes drawn from the shape survey (genoray / GenVarLoader / genvarformer): 1. test_consumer_alleles_string_under_axis (ploidy=2 flattened, ~variants) opaque allele strings -> chars (R=2). 2. test_consumer_fla...
ca5145ed073fa9204805aa575e2e4ab94733c178f05554318cf4bf40cf07f942
Python
3,117
83
from __future__ import division import unittest import numpy as np from wyrm.types import Data from wyrm.processing import calculate_signed_r_square from wyrm.processing import swapaxes class TestSelectClasses(unittest.TestCase): def setUp(self): # create noisy data [40 epochs, 100 samples, 64 channel...
ec31d0f65282a043f3b0c37ecf85d613bb681180ec99b28fd384b86b28d6850f
Python
3,117
74
# Written by Seonwoo Min, Seoul National University (mswzeus@gmail.com) # Some parts of the code were referenced from or inspired by below # - Tristan Bepler's code (https://github.com/tbepler/protein-sequence-embedding-iclr2019) # PLUS """ SecStr FASTA file loading functions """ import numpy as np import torch impo...
47f4ed69f9b195783d0879c5869698b92f73a95ccd4cfb28a93e73f2bd67831c
Python
3,118
103
import numpy as np from numpy.random import default_rng import pathlib from mpi4py import MPI from causal_optoconnectics.tools import conditional_probability, joint_probability, roll_pad from causal_optoconnectics.generator import ( construct_connectivity_filters, construct_connectivity_matrix, simulate, ...
deb4811f80e7e03a3849af448e080e4f6fd238c98be1d12b88bd06df82514a6c
Python
3,118
96
# Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved from typing import Callable, Tuple, Union import numpy as np from PIL.Image import Image from torch import Tensor from lightly.transforms.torchvision_v2_compatibility import functional as F from lightly.transforms.torchvision_v2_compatibility...
98662ac4af54a2982e854de57423f012c5565d0955b46c4841180588fb09eda2
Python
3,119
90
from datetime import datetime from unittest import mock import dateutil.relativedelta from api.mocks import FakeAuthContext from carbonserver.api.infra.repositories.repository_runs import SqlAlchemyRepository from carbonserver.api.usecases.run.experiment_sum_by_run import ( ExperimentSumsByRunUsecase, ) EXPERIME...
1daf18117e4757b09c5e5c9c680427a64002b03dfd58b022464292b03a6c44e2
Python
3,120
92
# --- THIS FILE IS AUTO-GENERATED --- # Modifications will be overwitten the next time code generation run. from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Root(_BaseTraceHierarchyType): _parent_path_str = "treemap" _path_str = "...
415f7815fcd9b20e10b02b2360c0d17cd10593e2265b3211d4686ff5567c66f7
Python
3,120
101
""" Tests to make sure the dataload module isn't busted """ import os import pytest import numpy as np import eugene as eu from pathlib import Path HERE = Path(__file__).parent @pytest.fixture def sdata(): """ sdata """ sdata = eu.datasets.random1000() eu.pp.ohe_seqs_sdata(sdata) eu.pp.rever...
a24345099deff5d637e647ffc79f135bc61e2209fd8eb4bcbd9e975e2b58676a
Python
3,120
80
try: from pyscf import gto from pyscf.dft.numint import eval_ao except ImportError: raise ImportError("You need to install pyscf to use this module") import numpy as np import numpy.typing as npt from ase.data import chemical_symbols class OrthoCoeffMatrixToMolecularOrbitals: def __init__( s...
e26598645aabefaedebe8a56468088e56181472b923b23b698f40f7a5c2a46f4
Python
3,120
92
# Copyright 2022 Deepfold Team # # 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 applicable law or agreed to in writin...
40cae8f01fc96f977ee2cff3ce6f1fab4b4b497e5eab479c4217e18dc1f0a97b
Python
3,121
82
"""FLOORLEAK regression pins: test fixtures must not outlive the tests they serve. Two session-pollution leaks flipped later tests red in the W051 backstops: * ``tests/real_model/r0/conftest.py`` cached every realism-sweep model and its finished ``Trace`` in a SESSION-scoped dict, so the traces' saved activations ...
3906a22daa91d9a7686b7ba61097f333768e14527aed2353b72f3992f9c3a4c6
Python
3,122
104
import logging import yaml import copy import argparse import numpy as np from bson.objectid import ObjectId from pymatgen.core import Molecule from atomate.qchem.fireworks.core import SinglePointFW, ForceFW from atomate.common.powerups import add_tags from fireworks import LaunchPad, Workflow from instance_mongo...
5b9807f2ff08df4d8202025681c662fff575576567607ee77f602671723f7076
Python
3,122
141
# 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 complian...
24cf8e44499a12ab6bab41a7e123273ebb0b8809b21a85d6f5a5367606617727
Python
3,123
80
import pandas as pd import numpy as np import torch def atom_features(atom): return np.array(one_of_k_encoding_unk(atom.GetSymbol(),['C', 'N', 'O', 'S', 'F', 'Si', 'P', 'Cl', 'Br', 'Mg', 'Na','Ca', 'Fe', 'As', 'Al', 'I', 'B', 'V', 'K', 'Tl', 'Yb','Sb', 'Sn', 'Ag', 'Pd', 'Co', 'Se', 'Ti', 'Zn', 'H','Li', 'Ge', 'Cu'...
7c0ffb932f40ebdc40a4664c5b21271158553b427d9965d2825b7df9caf4947d
Python
3,123
111
"""Helper methods for handling units in PyJibe""" def si2hr(name, value, si_unit=None): """Convert an SI unit to a human readable unit Parameters ---------- name: str The parameter name string, see `human_units`. value: numbers.Number or array The value of the parameters that will...
9a142abb27c4e5a92de9a01d91c92545dfed5638633c9eb8deadb8e21c4837a1
Python
3,123
91
"""Regression coverage for capture-wrapper unwrapping's common fast path.""" from __future__ import annotations from collections.abc import Callable from typing import Any from unittest.mock import MagicMock import torch from pytest import MonkeyPatch from torchlens import _state from torchlens.utils import _callab...
b2fdf38bb7806c4094c482249582c967b86a5a338e2b32005c285f495f01e2a2
Python
3,123
86
import torch.nn as nn import torch.nn.functional as F from torch import Tensor from typing import Optional from external_src.group_free_3D.models.multi_head_attention import MultiheadAttention class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activati...
6276da9f9701c83fc9cc33dba8f87b1695a320da9c8bbee99e5db78284776c9d
Python
3,124
105
# -*- coding: utf-8 -*- # @Author : Yue Liu # @Email : yueliu19990731@163.com # @Time : 2022/9/21 0:38 import torch import numpy as np def numpy_to_torch(a, is_sparse=False): """ numpy array to torch tensor :param a: the numpy array :param is_sparse: is sparse tensor or not :return a: torch...
aad0993c9840299e2ce6a40dfd1d2d040b47016dddabc4be27b7db5d7cd7c5f5
Python
3,124
98
import pickle import cv2 import time from ethoscope.hardware.interfaces.interfaces import HardwareConnection from ethoscope.hardware.interfaces.sleep_depriver_interface import SleepDepriverInterface obj = HardwareConnection(SleepDepriverInterface) with open("/tmp/pickled.pkl", "w") as f: pickle.dump(obj, f) obj.s...
43b3af2f1002e4107f53ea3381f05e1e7f8671cb013d6c9445bfacd5064f47aa
Python
3,125
74
""" Reference structure validation module. author: gaojie01 """ import json from helixfold.data.templates_input import get_refer_structure_features from helixfold.data.templates import Error as TemplateError from infer_scripts.validation import ValidationException def ref_structure_check(all_entities: list, kalign_bi...
76eb8d829c47e590699d04fd78b0ab63a25c5c37a60892ecf7195aa31ab76127
Python
3,125
84
import os.path import numpy as np CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) GENERIC_KWARGS = dict([ ("write_images", False), ("export_images", True), ("image_export_format", "native"), ("image", os.path.join(CURRENT_DIR, "data", "ct_images_seg", "CRLM-CT-1004", "image")), ("mask", o...
926a7a49445efd4ef407970e84f8ebdf0266d1f96d8b794fef42b0bc04e94cf8
Python
3,125
82
from typing import Any, Optional, Union from pl_bolts.datamodules.emnist_datamodule import EMNISTDataModule from pl_bolts.datasets import BinaryEMNIST from pl_bolts.utils import _TORCHVISION_AVAILABLE class BinaryEMNISTDataModule(EMNISTDataModule): """ .. figure:: https://user-images.githubusercontent.com/46...
a5a0527fa5b0e5468aa5adaddb2eea21d33e1a6a92aa2f812861c7a75316fb4b
Python
3,125
92
# --- THIS FILE IS AUTO-GENERATED --- # Modifications will be overwitten the next time code generation run. from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Root(_BaseTraceHierarchyType): _parent_path_str = "sunburst" _path_str = ...
af750112361918c0186594545602e3d47cfec55ad8dcca33d0ae947194920587
Python
3,125
69
"""this script is used to prepare Otb2015 dataset for tracking, which is Single Object Tracking benchmark""" import argparse import tarfile import os import time import json import numpy as np from gluoncv.utils import download, makedirs otb50 = ['Basketball','Biker','Bird1','BlurBody','BlurCar2','BlurFace','BlurOwl'...
1003b01bb2d266bfe691bc8854ab3b379aef09066429aeccdbb437bb6ad6e991
Python
3,126
106
from cmath import nan import pickle from matplotlib import pyplot as plt from numpy.lib import math from scipy.sparse.construct import rand from ssm.plots import gradient_cmap, white_to_color_cmap import seaborn as sns import numpy as np import os import os from scipy.io import savemat,loadmat import os from os import ...
939317761b43d9df5a6d16085414f977b005f37cc49e892b398f346ce803dc13
Python
3,127
110
def getDigitizerName(digitizerNumber): digitizers = { 0: "Unknown", 1: "Demo", 2: "MiniDigi", 3: "DD132X", 4: "OPUS", 5: "PATCH", 6: "Digidata 1440", 7: "MINIDIGI2", 8: "Digidata 1550" } if (digitizerNumber in digitizers.keys()): ...
86090fcce973070edae67676cb7b55fd1e56dc18d1398872636eb23152f9404c
Python
3,128
86
import numpy as np import sympy as sp import markov_builder import pints from . MarkovModel import MarkovModel class ClosedOpenModel(MarkovModel): def get_default_parameters(self): return self.default_parameters def __init__(self, voltage=None, times=None, Erev: float = None, parame...
5741b2c2dd9e3063d0b891bdb272ef0713b7262e11f348f1b1f543b7085ee4d0
Python
3,129
82
"""r-b4 R27-6a: chained selector composition stays flat and stack-safe. ``&``/``|`` built one binary composite per application, so ``functools.reduce(operator.or_, [tl.func(n) for n in five_hundred])`` made a 500-deep binary tree and blew the interpreter stack at trace entry. Chained same-operator composition now accu...
22d36eddf56daa6742fea9fbbd32f76ce25ab512f322d4bbac3e8b4c561da986
Python
3,130
80
import pytest import numpy as np from causal_optoconnectics.core import Connectivity from causal_optoconnectics.tools import compute_trials def test_connectivity(): stimulus = np.arange(10, 510, 10).repeat(2).reshape((50, 2)).astype(float) stimulus[:,0] = 3 # event id A = stimulus + 1 A[:,0] = 0 # eve...
8568472b0b0516bea6d60a66eb2cf1a8f01367ff5bacd1050f63791e1320c05e
Python
3,130
64
# Copyright 2019 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...
02c1a4796887189b90e950d3a64a67c9372f497e3ba80364be27b1df3b91eeaf
Python
3,131
82
"""F16 B6: the diagnostic frontier query (treescope memo F-E). One injected NaN flags the whole downstream cone; the frontier is the clean-to-dirty transition -- exactly one first-dirty site with its last clean parent and first dirty child, in deterministic order. """ from __future__ import annotations import torch ...
b36929e4c52e9097d05a079e00c3a330a7cde2f5b484fdec18f5ce5412bb9b7a
Python
3,131
61
"""Wrapper that autoreset environments when `terminated=True` or `truncated=True`.""" import gym class AutoResetWrapper(gym.Wrapper): """A class for providing an automatic reset functionality for gym environments when calling :meth:`self.step`. When calling step causes :meth:`Env.step` to return `terminated=...
c5a657842a87883fbcaa4079fabc439549706d194d2eecf5c30df4b9c63baa6e
Python
3,132
107
from pathlib import Path from typing import Dict import torch from pytorch_lightning import LightningModule, Trainer from pytorch_lightning.callbacks import DeviceStatsMonitor from pytorch_lightning.loggers import TensorBoardLogger from torch.utils.data import DataLoader from lightly.data import LightlyDataset from l...
c7cf6d7316508a491bd846ded79bd58e3e967759ddc5968a7e41a0405a01925a
Python
3,132
91
# Copyright (c) 2022 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...
8bf35cff06ef85942be42fce0fde8e9332ed7964e449615352ccca9b67e19e22
Python
3,133
107
from pathlib import Path from typing import Dict import torch from pytorch_lightning import LightningModule, Trainer from pytorch_lightning.callbacks import DeviceStatsMonitor from pytorch_lightning.loggers import TensorBoardLogger from torch.utils.data import DataLoader from lightly.data import LightlyDataset from l...
dad858e6c580348e4a846aa7e18dbcd87198605ccfd3f9410c718b2d6f5c584c
Python
3,133
91
__author__ = 'quentin' from ethoscope.core.monitor import Monitor from ethoscope.trackers.adaptive_bg_tracker import AdaptiveBGModel, ObjectModel from ethoscope.utils.io import SQLiteResultWriter from ethoscope.hardware.input.cameras import MovieVirtualCamera from ethoscope.drawers.drawers import DefaultDrawer import ...
e2f8ae6d8fc37ce2bfee35b3eebe656bb988af753bd6b1336aad54c926371cb6
Python
3,133
74
"""Minimal reproducer: cp.async.bulk (raw address) triggers racecheck hazard. Warp 0 loads via cp.async.bulk, warp 1 reads from smem after mbarrier wait. Pipeline is correctly synchronized but racecheck reports 1 error. python AI/racecheck_repro_1d_bulk.py # correctness CUTE_DSL...
68795787f2d25cdb9b1e3d6cc496fa19c42f4b5a05d7638573a31ceb9ae4d192
Python
3,137
104
# This example requires the following dependencies to be installed: # pip install lightly import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.models import utils from lightly.models.modules import MaskedVisionTransformerTorchvision from lightly.transforms.mae_transform imp...
71a120264362ea5c056d124382b79b68fb024ab16d03f063929b09da9688ccda
Python
3,137
80
#!/usr/bin/python3 # Copyright (c) ByteDance, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import argparse import functools import os import socket import subprocess import sys from typing impo...
8975b71388b44f006ecdf76ae0dcd2383385ac2ab6c58a36cdf4e6ae65a42707
Python
3,137
91
import numpy as np from neurogym.core import TrialEnv from neurogym.utils import spaces class GoNogo(TrialEnv): """Go/No-go task. A stimulus is shown during the stimulus period. The stimulus period is followed by a delay period, and then a decision period. If the stimulus is a Go stimulus, then the ...
ada3395e2584077240e751f3b42eedfa8500cd37cb9e2a51e0434146f99a4b3c
Python
3,137
103
"""Utility to dump events to screen. This is a simple program that dumps events to the console as they happen. Think of it like a `tcpdump` for Celery events. """ import sys from datetime import datetime, timezone from celery.app import app_or_default from celery.utils.functional import LRUCache from celery.utils.ti...
c60ad3f10ad9ff0a1f8e154a20bc39d8f435795d09282e232160ba92e3b12116
Python
3,137
80
"""grind-r5 corroborated LOWs: belt sweep watermark + rescue warning routing. * The belt's sweep watermark was a ``len(sys.modules)`` EQUALITY test, so a same-length module-table mutation (del one key + insert another) skipped the sweep and left a protocol-invisible stale ``from_numpy``/``frombuffer``/``as_subcl...
08188058cc79810c0a8227f3b75b6d20adf4c52ceb54cf54ae309dbedb43d810
Python
3,138
88
import numpy as np import pandas as pd from anndata import AnnData from scipy.sparse import csr_matrix from stlearn.spatial.sme._weighting_matrix import ( _PLATFORM, _WEIGHTING_MATRIX, impute_neighbour, weight_matrix, ) def sme_impute0( adata: AnnData, use_data: str = "raw", weights: _WEI...
5465cabb70c66d1950d9e3c6b18830a31e1dc341a0330047a917ddd161b1caa2
Python
3,138
95
from __future__ import print_function # to filter some unnecessory warning messages import warnings warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.ufunc size changed") import os import numpy as np import pandas as pd import glob import keras from...
b3ddc14206dcb7ee215352beaf5e2a471190861a3c1d1f2eeec97124b4226c8b
Python
3,138
95
from __future__ import print_function # to filter some unnecessory warning messages import warnings warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.ufunc size changed") import os import numpy as np import pandas as pd import glob import keras from...
f6c39c2aa0a48ad3c2fdf92b851f57f1e6701701f1fb94ed66cf178a88c5f7de
Python
3,138
74
# 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...
9186624e79335378627ec6bb920030cc69e9d95b1c8090ff7a3890729b165747
Python
3,139
102
# This example requires the following dependencies to be installed: # pip install "lightly[timm]" # Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightn...
64bac4b6fb10830a395e3678a80994cb1d763a0c79fdf3cfc86386cb333b699d
Python
3,141
87
import torch from torch import nn import torch.nn.functional as F def make_model(args, parent=False): return IDN(args) class FBlock(nn.Module): def __init__(self, num_features): super(FBlock, self).__init__() self.module = nn.Sequential( nn.Conv2d(3, num_features, kernel_size=3, pa...
7a7b9fde5806ea791a5e13ebe6bd462c7fcdc207dd364dacd75d9e7989a80096
Python
3,141
114
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu> import numpy as np from eelbrain import datasets, plot, testnd, cwt_morlet from eelbrain.plot._figure import Figure from eelbrain.plot._utsnd import _ax_bfly_epoch from eelbrain.testing import requires_mne_sample_data from eelbrain.testing import hide_plots @h...
e3f8ddfae2fc8700d5aa78ebcefa81d319dd0698086df3f36dd151d1f3d928a8
Python
3,141
77
import numpy as np def calculate_chain_pair_pae_matrix(pae_matrix, token_chain_ids, mask_chain, mask_value=np.nan, metric_type='mean'): """ Compute a square matrix where each entry (i, j) is the minimum PAE between chains i and j. Args: pae_matrix (list or...
1f37ebd8c828f6644237db83b7977c071f9fa67aac85c4ce8f5ea93fbe1b8a11
Python
3,142
124
''' Feature selector class This file is a part of BdPy ''' class FeatureSelector(object): ''' Feature selector class Parameters ---------- expression : str Selection command Attributes ---------- expression : str Selection command token : tuple Tokens ...
34d169d3cdd2b56f817646a268b6fba9c7e59cd484e3d44ad9e7f1e8995d9eae
Python
3,142
90
from permacache import permacache, stable_hash import tqdm.auto as tqdm import numpy as np import matplotlib.pyplot as plt from modular_splicing.data_for_experiments.standardized_sample import ( standardized_sample, ) from modular_splicing.models.modules.lssi_in_model import LSSI_MODEL_THRESH from modular_splicin...
5c9bee936bc95495940de53b58202937524eb7b1a02d507f8576c10077c0b0ae
Python
3,142
76
import torch from collections import OrderedDict from torch import nn from torch.nn import Linear,Dropout,BatchNorm1d,Sequential,LayerNorm from torch.nn import Softplus,GELU,Tanh,SiLU from torch.nn.init import xavier_normal_,zeros_,constant_ import numpy as np class ResBlock(nn.Module): def __init__(self, nl, drop...
328f6a5ffa0487616f696807f83faebef1781c16a73893ac14ca9724f6b9aa3a
Python
3,143
84
# Backends based on https://github.com/chung-neuroai-lab/adversarial-manifolds # Removed Backends that are not used in Feather et al. 2022 import numpy as np import torch from torch import nn from collections import OrderedDict from .modules import FakeReLU, SequentialWithArgs, FakeReLUM # AlexNet Back-End architectu...
67349e5aab04c74be4dac80a045d4806028e5878178be35c3837a693ebb9af97
Python
3,143
109
from permacache import permacache, stable_hash import tqdm.auto as tqdm import numpy as np from modular_splicing.lssi.utils import second_half_of_spliceai_cached from modular_splicing.utils.run_batched import run_batched from modular_splicing.models.modules.lssi_in_model import LSSI_MODEL_THRESH from modular_splicing...
effb50dc04cad27939754116a5aac9bf830d79d9e9e06286d76d177df0f59152
Python
3,143
102
"""Settings for plots.""" from collections import OrderedDict import numpy as np from matplotlib.colors import to_hex from specparam.modutils.dependencies import safe_import plt = safe_import('.pyplot', 'matplotlib') ##################################################################################################...
2dc9f306647aae7886eef8aa87391eab1e8c4a245961ecf66b49ca0ee6156012
Python
3,145
82
"""An OpenAI-compatible chat completions endpoint served from the test process. Point Galaxy's AI base URLs at it and Galaxy uses the real OpenAI client against a scripted reply, so tests can assert on the request that actually reached the provider. """ import json from typing import Any from galaxy.util.unittest_ut...
7c35d365d294872e4eaed885d9a67fd611b39f2db19d4fe90f3b556dbe2d004a
Python
3,145
94
import numpy as np from mudcod.community_detection import MuDCoD, StaticSpectralCoD from mudcod.network_simulations import MuSDynamicDCBM from sklearn.metrics.cluster import adjusted_rand_score T = 4 S = 4 # Multi-subject Dynamic DCBM model_dcbm = MuSDynamicDCBM( n=100, # Total number of vertices model_order...
0404242698762bb8d41139f0b8cf4d6d83af2c296e3b661e8bbf69448af9cce7
Python
3,146
92
from typing import Optional, Tuple import numpy as np from numpy.fft import fftshift, ifftshift, fftn, ifftn class Noiser: def __init__(self, sigma: float = 0.01): """ Initializes the Noiser object with the given sigma value. Args: sigma (float, optional): The sigma value for...
23ed9503a24765c11c2b0ceb4a5152d1b1e931dee2b0b1da192f0fd0e5b230b4
Python
3,146
47
"""Prepare COCO datasets ============================== `COCO <http://cocodataset.org/#home>`_ is a large-scale object detection, segmentation, and captioning datasetself. This tutorial will walk through the steps of preparing this dataset for object tracking in GluonCV. .. image:: http://cocodataset.org/images/coco-...
5fae15bc63cbd806d444ac1846c5893975c60183a217fbf6aa2c5e4e40142ee5
Python
3,146
86
# This file originally from pip: # https://github.com/pypa/pip/blob/8f4f15a5a95d7d5b511ceaee9ed261176c181970/src/pip/_internal/utils/glibc.py from __future__ import absolute_import import ctypes import re import warnings def glibc_version_string(): "Returns glibc version string, or None if not using glibc." ...
ac338a1af6dab201ea3c745a1ffde0989905a6b375c7aa65076d52477d790e94
Python
3,146
108
import errno import socket from unittest.mock import Mock, patch import pytest import t.skip from celery.contrib.rdb import Rdb, debugger, set_trace from celery.utils.text import WhateverIO class SockErr(socket.error): errno = None class test_Rdb: @patch('celery.contrib.rdb.Rdb') def test_debugger(se...
ed965a8dcfbfb130fdf71cfda810a51a7d92a11c2b33d4401492416120fd49ab
Python
3,146
105
"""File I/O for specific file types.""" import io import json from json import JSONDecodeError from specparam.io.utils import create_file_path from specparam.utils.convert import dict_lst_to_array ################################################################################################### ####################...
0142a5ba618665710e55cc2f66e3c29e2cd74ef3e620f52e54087c13fa4192a2
Python
3,149
89
from io import StringIO from pathlib import Path import numpy as np import pandas as pd import pysam import pytest from anndata import AnnData from scipy.sparse import csr_array import muon.atac as ac @pytest.mark.parametrize("empty_distance", [True, False]) def test_add_peak_annotation(empty_distance: bool) -> Non...
a8cfc9454dd098f2d65bad6bd2fd3ae6d8e6bcf574eaa5da95cafda0e6af91ae
Python
3,149
95
import warnings import os import tempfile import unittest import arviz as az import logging from pmsurv.models.weibull_nn import WeibullModelNN import tests.syntheticdata from pathlib import Path warnings.simplefilter("ignore") logger = logging.getLogger(__name__) class TestWeibullNN(unittest.TestCase): def te...
299ccc292e482df0bf274163e4c16510e2fb67d9ce9e545fa384e719d5c43d66
Python
3,150
65
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """"tests for cycles.py""" import unittest import numpy as np from scipy import sparse from sknetwork.data import star_wars, house, cyclic_digraph, cyclic_graph, linear_digraph, linear_graph from sknetwork.topology import is_connected, is_acyclic, get_cycles, break_cycle...
15a013fc032cfaabbe8e5e7fd1f37fee965d5216a0d2493ce166865b4f296709
Python
3,151
78
import warnings import pytest from absl.testing import parameterized from keras.src import backend from keras.src import testing from keras.src.backend import config from keras.src.testing.test_utils import x64_mode_scope X64_SUPPORTED = backend.backend() in config._X64_BACKENDS class X64ModeTest(testing.TestCase)...
a68bff6480b4ae1a9c53fc6c9f881c74170c2562280ccd885f9d0d80984afacf
Python
3,151
90
import numpy as np import pandas as pd from anndata import AnnData from natsort import natsorted from sklearn.cluster import KMeans def kmeans( adata: AnnData, n_clusters: int = 20, use_data: str = "X_pca", init: str = "k-means++", n_init: int = 10, max_iter: int = 300, tol: float = 0.0001...
32edbbd29936299f7a0446efca8247ca5a589a92ff8130b89e7e80e320ddde23
Python
3,152
95
"""Position feed-forward network from "Attention is All You Need".""" import torch import torch.nn as nn class ComplexLinear(nn.Module): def __init__(self,n_blocks,d_per_block): super(ComplexLinear, self).__init__() self.weight = nn.Parameter(torch.randn(n_blocks,d_per_block,d_per_bl...
12d6ac058be9f287e9aee29ed356da5477372f07dbaf7815ec8084725c7e2049
Python
3,153
78
''' Note: reference frames in numpy and opencv2 [x,y] in numpy array: x = row; y = col *********************************** * [0,0] → increasing y → [0,ncol] * * ↓ * * increasing x * * ↓ * * [nrow,0] [nrow,ncol] * ****************...
5ebc4f6825923e38efcb202583e1b34326379ab6247c45c12b8ed6a68f2502af
Python
3,154
114
from __future__ import print_function, division, absolute_import import math import torch import torch.nn as nn import torchvision.transforms as transforms from PIL import Image from munch import munchify class ToSpaceBGR(object): def __init__(self, is_bgr): self.is_bgr = is_bgr def __call__(self, te...
63b45ab7753ce24f033f641db6eb97b8956d758a9b3b32bcac885852d664ee4c
Python
3,154
84
"""One-time recording sweep over the postprocess axes matrix. Runs every axis of ``tests/support/postprocess_axes.py`` with the combined read+write audit in RECORD mode and dumps the per-step observation unions as JSON. The output is EVIDENCE for seeding the declared ``reads`` sets and the four-category findings revie...
6e2bb9a20137b29718835a690b663e5c01eeb61b981e292deb5fd919f7f3e203
Python
3,154
90
import os from typing import ( Annotated, ) from fsspec.implementations.local import LocalFileSystem from pydantic import Field from galaxy.files.models import ( FilesSourceRuntimeContext, StrictModel, ) from galaxy.util.config_templates import TemplateExpansion from ._fsspec import ( CacheOptionsDict...
408a92e38714508747b1726ba4aaea901db222b10d0f2d862361607048a6a3b1
Python
3,155
87
"""Module for build dynamic fields.""" from collections import Counter, defaultdict import torch from bioseq2seq.utils.logging import logger from bioseq2seq.utils.misc import check_path from bioseq2seq.inputters.inputter import get_fields, _load_vocab, \ _build_fields_vocab def _get_dynamic_fields(opts): # NO...
9bc7cf46a1c75869f7116f6023b4c4b57ccd5c257ffd5d49f66965e38c0e9898
Python
3,157
111
import numpy as np import dgl import torch import torch.nn.functional as F import h5py import sys sys.path.append('../pkgs/graph-sc/') import train import models device = train.get_device() import warnings warnings.filterwarnings("ignore", category=FutureWarning) import scanpy as sc from scbig.utils import setup_seed i...
b8cf3b7fc78fcdfc7b520139115a8ec0945e594c1b18cc367f06b621e7db240c
Python
3,157
100
import subprocess import sys import textwrap from pathlib import Path import example_models import pytest import torch import torchlens as tl from torchlens import trace as trace_fn from torchlens.experimental import dagua def test_dagua_renderer_requires_experimental_opt_in() -> None: """Core renderer rejects ...
d4a6a64a8e6886157c4bedbfd89ad453a56f897a71869251c9f21b48cb541a7e
Python
3,157
96
import torch import torch.nn as nn from modular_splicing.models.entire_model.modular_predictor import ( ModularSplicePredictor, ) from modular_splicing.models.motif_models.types import motif_model_types from modular_splicing.models.modules.lssi_in_model import ( LSSI_MODEL_THRESH, load_individual_lssi_mode...
67af9dde601a34740d13b92ab212dbdb3b8584416b006dcc3c967591ec683a5b
Python
3,158
104
#!/usr/bin/env python3 """ Test script comparing CPU-only (package) vs CPU+DRAM power measurement. This shows how rapl_include_dram=True gets closer to powerstat's readings. """ import subprocess import time from codecarbon.core.cpu import IntelRAPL from codecarbon.core.units import Time print("=" * 80) print("Testi...
8a65f9eb1fcd399d23090f56ba01919f39b0a2e6bed946821cb04a1cb2407b53
Python
3,158
79
from ovseg.preprocessing.SegmentationPreprocessingV2 import SegmentationPreprocessingV2 from ovseg import OV_PREPROCESSED import os # name of your raw dataset data_name = 'MY_DATASET_NAME' # name after preprocessing preprocessed_name = 'MY_PREPROCESSED_NAME' # whether to apply resizing, pooling and windowing during p...
20796c7495de1ea3d4f3f4819b87885ee6b9661c91200507e1c02d54d351ecd8
Python
3,160
62
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on March 2019 @author: Thomas Bonald <bonald@enst.fr> """ import unittest from sknetwork.data.test_graphs import * from sknetwork.data import cyclic_graph from sknetwork.hierarchy import Paris, LouvainIteration, dasgupta_cost, dasgupta_score, tree_sampling_di...
86c4c25fe65c9a48c4b412f5e515058a1810ac4e18dd50bcca6b418c72d485b2
Python
3,160
103
"""Analyse the edge weights for gene to gene interactions""" from posixpath import split from pprint import pprint as pp def get_edge_per_TR(mapfile): from numpy import mean, median, std, percentile outfile = open(mapfile.replace('.', '-edge_weight_stats80th.'), 'w') open_map = open(mapfile) # again,...
de1c1157b62722c22d4e4c3f81db5e0d41175087e92111361482b29cda9f1a15
Python
3,160
81
"""Models that incorporate tacticity in one way or another""" # TODO document better import nfp import keras import tensorflow as tf from keras import layers # TODO switch order of model_summary def pm_model(preprocessor, model_summary, prediction_columns, params): # Define the keras model # Input layers ...
225af6a122ce7831b96ae56104a2fc28fed25a141bda8cff9ce3193a101b0832
Python
3,161
82
"""Provides a generic testing environment for use in tests with custom reset, step and render functions.""" import types from typing import Any, Dict, Optional, Tuple, Union import gym from gym import spaces from gym.core import ActType, ObsType from gym.envs.registration import EnvSpec def basic_reset_fn( self,...
8bad573b05a218aca686596c00ed7e75a10532a82ec58cd5fdbad37411297ff8
Python
3,161
94
# 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 agree...
d4249cd80154acb03e47d29e99795b480d8fe64350dd9f1e000e311314c8f0ce
Python
3,162
78
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from ultralytics.utils import LOGGER def onnx_calibration_reader(dataset, transform_fn, input_name: str = "images"): """Create an ONNX Runtime calibration data reader from an Ultralytics calibration dataloader. Args: dataset (Iterab...
4c21d605b3aab316586c39111d962969c68f1ff4deeac0549dfca29ccb64c2b0
Python
3,164
62
import numpy as np import torch from scipy.spatial.distance import cdist from scipy.spatial.transform import Rotation def apply_data_augmentation_to_object_pcs(object_points, config=None): if config is None: config = {'brightness': 0.1, 'colors': 0.05, 'x_rot': 20, 'y_rot': 45, 'z_rot': 20, 'shift': 0.15,...
10cabeada91e57120a8a16bde73578c0cdea24fc99341c1752a51d186bd56237
Python
3,165
100
#!/usr/bin/env python # ============================================================================= # MODULE DOCSTRING # ============================================================================= """ Provide utility functions to read output files generated by PLUMED. """ # ====================================...
508b0094bb4fc64c68e6fd714e1fb9cda5e0f2f36668a91dedb13ca69375c83b
Python
3,165
73
#!/usr/bin/env python3 import os from argparse import ArgumentParser def main(): """ This is a utility script created to work with the ThermoNet ddG prediction protocol. It takes a given list of variants and the path to the Rosetta binary. It runs the Rosetta binary to create a structural model for e...
6afd5cf0a2ab910789ff2b3b42d9dcda1498945f3e6cd0aad3305db1e3d8b860
Python
3,165
109
# This example requires the following dependencies to be installed: # pip install lightly import torch import torchvision from torch import nn from lightly.models import utils from lightly.models.modules.masked_vision_transformer_torchvision import ( MaskedVisionTransformerTorchvision, ) from lightly.transforms.m...
ff6aa130ada42f6c78afa6e77a559c98436484369e2f74b029275563b0752c80
Python
3,165
83
# --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.16.0 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Setup # ...
bc4c8ef6d14a86147a169ba9d6fdcbef2da37e668099348944279d572e0bde13
Python
3,166
96
# 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...
f04926cafc8bcceec7a8b7a2baeeb4ded62daa9f265c55351176b399c8bc91e3
Python
3,166
89
import os import warnings from math import sqrt import h5py import numpy as np import pandas as pd import scanpy as sc from scipy.stats import pearsonr,spearmanr from sklearn.metrics import mean_squared_error from scbig import run_scbig, preprocess, setup_seed warnings.filterwarnings('ignore') for sparity in ['0.8'...
2a92526ed147119883612aa26c4f7fae717d10dabfc03bb354c3ae1160549a16
Python
3,168
109
"""Collect together library of available built in metrics.""" from specparam.metrics.metrics import Metric from specparam.metrics.error import (compute_mean_abs_error, compute_mean_squared_error, compute_root_mean_squared_error, compute_median_abs_error) from specparam.metrics.gof ...
418512c2eb42b21c080164e14ea8798177cfb5333654a13fa1f662d283b963e4
Python
3,168
91
"""Admin CLI for the GTN search database. Run as ``python -m galaxy.gtn --refresh`` from within a Galaxy virtualenv to force-redownload the published database. The CLI resolves ``gtn_database_path`` from Galaxy configuration unless ``--path`` is supplied. """ import argparse import logging import os import sys from p...
55844414609f0770a2dd64ebc3b5b51248a10741fa8459eaed810f180a2e2f77
Python
3,168
99
"""SiamRPN network Code adapted from https://github.com/STVIR/pysot""" # coding:utf-8 # pylint: disable=arguments-differ,unused-argument from mxnet.gluon.block import HybridBlock from mxnet.context import cpu import mxnet as mx from gluoncv.model_zoo.siamrpn.siam_alexnet import alexnetlegacy from gluoncv.model_zoo.siam...
936e9492c33a60ee0dffca9b69ac3bbfb9f300d020e5d2e9d2053c5ae89863fc
Python
3,170
102
import importlib.util import json from pathlib import Path import pytest SCRIPT = ( Path(__file__).resolve().parents[1] / "codecarbon/data/private_infra/update_usa_emissions.py" ) DATA = ( Path(__file__).resolve().parents[1] / "codecarbon/data/private_infra/2023/usa_emissions.json" ) # The script is ...
cde69d4bf2a1e78de456f52ccf72197439dd84faa16761f9f2e5d74ab4101c52
Python
3,170
91
"""Prepare ADE20K dataset. ======================== `ADE20K <http://sceneparsing.csail.mit.edu/>`_ is a scene-centric containing 20 thousands images annotated with 150 object categories. This tutorial help you to download ADE20K and set it up for later experiments. .. image:: http://groups.csail.mit.edu/vision/datase...