sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
69799572fcf74c3233a813e501794fc88fa6c0661f0721cd27a2f83b8ab78d0b
Python
2,596
77
import torch.nn as nn from ..builder import ALGORITHMS, build_backbone, build_head, build_neck from .base import BaseModel @ALGORITHMS.register_module() class FPSiam(BaseModel): """FPSiam. Implementation of `Self-supervised representation learning using feature pyramid siamese networks for colorectal polyp ...
beaab7ec35196c0b9e267e73877948c60df2c5abd1963cd378f12d8a3f7e040a
Python
2,596
67
# pylint: disable=arguments-differ,line-too-long,missing-docstring,missing-module-docstring from functools import partial import mxnet as mx from mxnet.gluon.nn import HybridBlock __all__ = ['DropBlock', 'set_drop_prob', 'DropBlockScheduler'] class DropBlock(HybridBlock): def __init__(self, drop_prob, block_size,...
7107aa7eab118dc18e2af76b2d54a9eb5ddd828762ed983c1004bbcb04267cf1
Python
2,597
90
import os import torch from modular_splicing.legacy.remapping_pickle import load_with_remapping_pickle def load_model(folder, step=None, **kwargs): """ Load a model from the given path. Uses `load_with_remapping_pickle` to load the model to allow for backwards compatibility. Has different behav...
71dd46c5556f5df1dac63e3ff7af877f0f2a788506d4edd0aad51ff810461b97
Python
2,597
84
# 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. from typing import List import torch import torch.nn.functional as F from timm.models.resnet import ResNet # hack: injec...
a8626ca1ec6ba27de287170ca2c53e5a355e799893178ea5e74a92461c01218d
Python
2,597
67
from __future__ import division import unittest import numpy as np from wyrm.types import Data from wyrm.processing import append_epo from wyrm.processing import swapaxes class TestAppendEpo(unittest.TestCase): def setUp(self): ones = np.ones((10, 5)) # cnt with 1, 2, 3 cnt = np.append...
0d4d3483c0e8a4524f460e92d39943386035dd6c3f5aebebf2c9c295f6cfd3fb
Python
2,599
83
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: sphinx # format_version: '1.1' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- """ .. _exa-customizing-plots: Customizing plots ===...
15bb837c6a98402662e47d3db3fce3137d1b17134a6f44934eda0c352b054977
Python
2,599
75
import logging from .wdl_parser import WDLParser logger = logging.getLogger(__name__) class CaperWDLParser(WDLParser): """WDL parser for Caper.""" RE_WDL_COMMENT_DOCKER = r'^\s*\#\s*CAPER\s+docker\s(.+)' RE_WDL_COMMENT_SINGULARITY = r'^\s*\#\s*CAPER\s+singularity\s(.+)' WDL_WORKFLOW_META_DOCKER_KEY...
0f08e5fc346277fe65a4824fa2b90c0a48adb90b5ecda441d3e2991b199d5388
Python
2,600
82
# 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 pytorch_lightning as p...
2ebea623b3ea2b3bbdce86a0317d959c4bc53c98419648a477fdb0e62a20cf93
Python
2,600
71
import numpy as np import scanpy from anndata import AnnData def normalize_total( adata: AnnData, target_sum: float | None = None, exclude_highly_expressed: bool = False, max_fraction: float = 0.05, key_added: str | None = None, layer: str | None = None, inplace: bool = True, ) -> dict[str...
89fc97369df996c3f5139d2cc7cdc850c35374c3fb993d39cf7745f38d3e9449
Python
2,600
81
"""The modern-spelling quickstart gate: zero warnings, in a fresh process. Quickstart memo B1: the block a newcomer actually types (modern spellings only -- ``tl.trace`` + ``summary()`` + indexed reads, eval-mode torchvision resnet18) must emit ZERO warnings. Historically the only spellings that controlled render outp...
7da617c6811f10964ddcd2b71aff864d6f31c889367ce29774e98347e9e4e82f
Python
2,601
79
import os import re import sys import sysconfig try: from Cython.Distutils import build_ext except ImportError: from setuptools.command.build_ext import build_ext from setuptools.extension import Extension def is_pip_install(): if "_" in os.environ and os.environ["_"].endswith("pip"): return Tru...
ddc8def878c392ee0c1e62b130d91001b852f87a70f7cbc293a4f61014ee0e9a
Python
2,601
68
import json import os import numpy as np from matplotlib import pyplot as plt from angorapy.common.const import PATH_TO_EXPERIMENTS, QUALITATIVE_COLOR_PALETTE experiment_ids = ['1674074113967956', '1674074113731734', '1673350499432390'] names = ["1", "2", "3"] reward_developments = {} reward_bands = {} cosucc_devel...
caf188c101f44347798630c5e750e02d4df8910ebb12a523849e7f00d9203abf
Python
2,602
71
#!/usr/bin/env python import os import torch import argparse import numpy as np from models import InferSent if __name__ == '__main__': parser = argparse.ArgumentParser( prog='extract-features', description='Extract features from pretrained InferSent model') parser.add_argument('-g', '--w2v_...
2dcf2e0a54e75f0758fab86868fa98773c2dc0fe86cf9379f3e2760b4dd9a986
Python
2,604
93
import csv import time import math import numpy as np import warnings from rdkit import Chem from rdkit import DataStructs from sklearn.model_selection import KFold, StratifiedKFold import torch import torch.nn as nn import torch.nn.utils.rnn as rnn_utils def read_sequence_file(filename, unique=True, add_end_tokens=F...
5354890ca0ecadf8c289e0dc9ab05bb892f95181812e710c4c53f3a9d5759ce4
Python
2,604
80
""" This example demonstrates how to use the CodeCarbon library to track the carbon emissions of a transformer model. We will use the model from https://huggingface.co/HuggingFaceTB/SmolLM2-360M-Instruct It's a small language model that fit on small GPU. - 360M model took 1 GB on disk, less than 2 GB in VRAM. - 1.7B ...
fe25c9d3cd4db9052063da41cd86c1cb1f020f8069675c54f8b5e57a370d9e7d
Python
2,604
60
from __future__ import division import argparse, time, logging, os, math, tqdm, cv2 import numpy as np import mxnet as mx from mxnet import gluon, nd, image from mxnet.gluon.data.vision import transforms import gluoncv as gcv gcv.utils.check_version('0.6.0') from gluoncv import data from gluoncv.data import mscoco fr...
a80cd424e65aceb2d59072f4162376c36cffe43305d07b7eb88ee6fff15b7590
Python
2,606
93
import csv import time import math import numpy as np import warnings from rdkit import Chem from rdkit import DataStructs from sklearn.model_selection import KFold, StratifiedKFold import torch import torch.nn as nn import torch.nn.utils.rnn as rnn_utils def read_sequence_file(filename, unique=True, add_end_tokens=F...
ccbc8b838e1ab2671a90aacd918cfa5994f388426f786c485b23148138cb2f18
Python
2,606
87
""" The data splitting script for pretraining. """ import os from argparse import ArgumentParser import csv import shutil import numpy as np import grover.util.utils as fea_utils parser = ArgumentParser() parser.add_argument("--data_path", default="../drug_data/grover_data/delaneyfreesolvlipo.csv") parser.add_argum...
4bd07558e7399470a34e3fccf89f997f1d3c5b2017201e7e93d42e3e6de67670
Python
2,607
64
# -*- coding: utf-8 -*- # Copyright (c) 2016-2018 Braintech Sp. z o.o. [Ltd.] <http://www.braintech.pl> # All rights reserved. """Wii Read Manager.""" from __future__ import print_function, division from .. import read_manager import numpy as np from . import wii_utils class WBBReadManager(read_manager.ReadManager):...
7d5a7191044aaa84d814cedbd373c54ffbf37469ee64b425059a2c887e48b076
Python
2,607
78
import random import numpy as np import copy from scipy.spatial.transform import Rotation predefined_rotation_arrays = np.array([ [ # identity [1,0,0], [0,1,0], [0,0,1] ], [ # counterclockwise 90 [0,0,1], [0,1.,0], [-1,0,0] ], [ [0,0,-1], ...
f6132525954dfc5110dd462b4f6d8f34afb1bd6d92e6ae883b37ddd3e77df39e
Python
2,607
54
import os, pydicom import numpy as np from operator import itemgetter def load_stack(srcdir): # Debug for CHUSJ mice: # srcdir='/mnt/data/DATA_Micro-CT_CR_CHUSJ/SPINE/DICOM/2M/2M-25J-1' # Assuming that slices are taken along the anteroposterior axis. # Doubt may remain on whether rows/columns corresp...
2bd0d29683d1d30d99ebc88cc92e3c99adbf7759b9bfc55dc0abfa990648ff9f
Python
2,608
70
"""The ``celery purge`` program, used to delete messages from queues.""" import click from celery.bin.base import COMMA_SEPARATED_LIST, CeleryCommand, CeleryOption, handle_preload_options from celery.utils import text @click.command(cls=CeleryCommand, context_settings={ 'allow_extra_args': True }) @click.option(...
5b73fce2a29d8508620591756106c69deb19e54295e23a3dc2f4ecb0a9e7e2e6
Python
2,608
61
"""grind-r3 T-CACHES: the framework-filename verdict cache must be bounded. ``_FRAMEWORK_FILENAME_VERDICTS`` is a process-global keyed by ``co_filename``. Generated-code, notebook, plugin, and long-running service workloads mint fresh filenames without limit (grind-r2 b4-sol R39: 1,000 distinct compiled filenames grew...
b0e1e7fb4da044f4c6439b7ad1161ec4766fe2a52db6aaee8dc8a239ca48ce22
Python
2,608
81
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: sphinx # format_version: '1.1' # jupytext_version: 1.4.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- """ .. _exa-boxplot: Boxplot ======= Much of the fun...
c0327da6c04411b5fbe6c0dc2e5f3019754d5de4409744ad9ca25430f64f26a0
Python
2,608
84
import torch __all__ = ["batch_trace", "batch_norm", "batch_diag", "batch_div"] def batch_operation(operation, tensor_a, tensor_b=None): """ This function allows to extend tensor operations provided in pytorch to batch tensors. As an input, it takes the pytorch operation and the tensors on which th...
50e3619cbc9f20ba3f21fcf851f24bcd873e6e2303f39d367ca77fda8f02dcdf
Python
2,609
81
import tensorflow as tf # implementation from: https://github.com/sayakpaul/Adaptive-Gradient-Clipping/blob/main/agc.py # noqa def compute_norm(x, axis, keepdims): """ Computes the euclidean norm of a tensor :math:`x`. Args: x: input tensor. axis: which axis to compute norm across. ...
185a021840b204efa7d482c5a3dc29f1f7192c419e2749dc0a1b130da15549da
Python
2,612
48
import torch.nn as nn import torch.nn.functional as F class LSTM_CNN_3_layers(nn.Module): def __init__(self, seq_length, img_size,kernel_s_layer_1, kernel_s, max1, max2, max3,out_channels_1, out_channels_2, out_channels_final, LSTM_hidden, LSTM_layers, p=0.0): super(LSTM_CNN_3_layers, self).__init__()...
c5dfd8884a6f02579182e1a47689c1547a25ab743c8216350366bd4d23d2c3cf
Python
2,612
66
import pandas as pd from pandas.core.frame import DataFrame from sklearn.model_selection import train_test_split from typing import List, Tuple import utils import numpy as np def split_datasets(root_data_path: str, random_seed: int, train_fraction: float) -> None: """Performs random split of dataset and exports c...
abbd298bfdd1ebe97a4af953291437378af0c0743817ab3221734c46e104ae60
Python
2,613
83
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 4 18:44:27 2020 Find peaks and slopes from PSDs using fooof @author: ml """ import mne import numpy as np import os import sys from fooof_parametrization import fooof_inparcel BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)...
c2f93ffcf01f095cb8345ecb00e3a1ac53f8cfed4db4d0b6b8a40fd610f7cfe9
Python
2,614
84
import pytest import rpy2.robjects.packages_utils as p_u def test_default_symbol_r2python(): test_values = ( ('foo', 'foo'), ('foo.bar', 'foo_bar'), ('foo_bar', 'foo_bar') ) for provided, expected in test_values: assert expected == p_u.default_symbol_r2python(provided) @p...
2a660f01b10169a6c9bb258080bcec027df48d1ed9e69cff45ecc7fccc697267
Python
2,615
75
import os import numpy as np import cv2 from operator import itemgetter from sklearn.preprocessing import LabelEncoder folder = next(os.walk('.'))[1] for f in folder: # Declarations X = [] Y = [] folders = [] filenames = [] readMask = False readImage = False image = np.empty((1024, 102...
9f6164565c115ff852eb57d8b779d2021d9ed95e827199ff75f6cf21dd690101
Python
2,615
82
from __future__ import absolute_import import logging import os.path import tempfile from pip._internal.utils.misc import rmtree logger = logging.getLogger(__name__) class TempDirectory(object): """Helper class that owns and cleans up a temporary directory. This class can be used as a context manager or a...
ebd524da6253bdc5d73cd22410bc186161ac9f058e135ae9db9c7514b1160553
Python
2,616
104
from sphinx_celery import conf globals().update(conf.build_config( 'celery', __file__, project='Celery', version_dev='6.0', version_stable='5.0', canonical_url='https://docs.celeryq.dev', webdomain='celeryproject.org', github_project='celery/celery', author='Ask Solem & contributors', ...
deb6c740ea5d80cf2a3fd166b1f2fd7651d2a19d785a39421350475651069c8a
Python
2,617
83
""".. _lightly-timm-backbone-tutorial-8: Tutorial 8: Using timm Models as Backbones =========================================== You can use LightlySSL to pre-train any timm model using self-supervised learning since most methods share a similar workflow. All methods have a base model (the backbone), which can be any ...
495b8ca2ed9cb542ef052a0770006e2f316d8666b0425111f7928233265281d2
Python
2,618
90
import matplotlib as mpl import numpy as np from numpy.typing import NDArray from scipy.optimize import curve_fit from scipy.special import erf from neurogym.utils.decorators import suppress_during_pytest def probit( x: NDArray[np.float64], beta: float, alpha: float, ) -> NDArray[np.float64]: """Cumu...
ff21c54218c0c991f78aea7ce5319d8541cb3e8cd43981df8628ecf09a09d57b
Python
2,619
91
import pytest from larvaworld.lib.reg.parDB import ParamRegistry _VALID_CATEGORIES = { "initial", "angular", "spatial", "chunks", "sim_pars", "deb_pars", } @pytest.fixture(scope="module") def pclass() -> ParamRegistry: return ParamRegistry() def test_build_populates_category_dict_for_a...
4dda9c413732cc9a9b45f38b52d9b2f484e36a5c20eb16288f9075996c86cc58
Python
2,620
86
#!/usr/bin/env python # Created on: October 8, 2013 __author__ = "Sven Kreiss, Kyle Cranmer" __version__ = "0.1" import optparse parser = optparse.OptionParser(version=__version__) parser.add_option("-i", "--input", dest="input", default="output/atlas_counting/comb.root", help="Input root model.") parser.add_optio...
83c843db878a864ccb5a84f1dcd5647834d029d72aaf6077f240903e8ffdf480
Python
2,620
72
"""Tests for specparam.algorthms.algorithm.""" from specparam.modes.modes import Modes from specparam.algorithms.settings import SettingsDefinition from specparam.algorithms.algorithm import * ################################################################################################### ########################...
a50354f4606ab739a6ed0f7d6c418f634211241d6aa1318468483c64cf23bcd2
Python
2,620
67
""" utility funcs to handle encapsulated objects """ import numpy as np def handle_encapsulated_contour(outer_cont, inner_cont) -> np.ndarray: """ given an outer contour (potentially) containing included inner contours this functions generates a contour representing the exact topology (outer contour w...
cb69e549aa393f2be74c9f376ac6d59368fcf4e6271a7d93ffbee49be081551d
Python
2,620
76
#!/usr/bin/env python """Convert GlimmerHMM GFF3 gene predictions into protein sequences. This works with the GlimmerHMM GFF3 output format: #gff-version 3 #sequence-region Contig5.15 1 47390 Contig5.15 GlimmerHMM mRNA 323 325 . + . ID=Contig5.15.path1.gene1;Name=Contig5.15.path...
cc9191aab6b8307c5d5114050aac03d03c4bfd426d0f7bf0ba295bb2bdfb3629
Python
2,620
82
from typing import Callable, Dict import numpy as np from hobj.types import ImageId # %% class RepresentationalModel: """ Class which maps images to feature vectors of shape (d,). """ def __init__( self, d: int, image_to_features_func: Callable[[ImageId], np.ndarray], ):...
30db1d769db7d9b9443bc220e68f5bd408193f0937114bc89798efc98abe9a6e
Python
2,622
99
import numpy as np import pandas as pd from tqdm.notebook import tqdm from constants import DATA_SUBSETS, RANDOM_SEED, LABEL_FEATURE, ROGUE_WAVE_THRESHOLD def read_files(infiles): """Read all parquet input files into a single pandas DataFrame.""" if isinstance(infiles, str): infiles = [infiles] ...
4e4137fc8a9fa14c289aed2c2b36f14d1c4ee41bc5cdf737d35f7fd3d143b617
Python
2,622
68
from unittest import TestCase, main from os.path import join, abspath, dirname from deblur.workflow import _system_call, create_otu_table from tempfile import mkdtemp from shutil import rmtree from biom import load_table class TestScript(TestCase): def setUp(self): self.data_dir = join(dirname(abspath(__...
a6f323561380a74d120c41d3cfc872e21ea9a38f25c69254c1271145f87dd1fd
Python
2,622
66
import time from pytest_celery import RESULT_TIMEOUT, CeleryTestSetup from t.smoke.tasks import add def _wait_until(predicate, timeout=RESULT_TIMEOUT, interval=0.5): deadline = time.monotonic() + timeout result = predicate() while not result and time.monotonic() < deadline: time.sleep(interval) ...
2f4221e412fdf0f738deaec050933736786d425c1fb057b6f26e775fd1134858
Python
2,623
77
import collections from cycler import cycler import matplotlib.pylab as plt from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import ( FigureCanvasQTAgg as FigureCanvas) import numpy as np from ..head import custom_widgets class MPLPreproc: def __init__(self): """Matplotli...
76bad5ec18ce64c4c19447635b1a19a8a6f596ac383ec218cf25b77445918dbf
Python
2,623
65
from ovseg.model.SegmentationModelV2 import SegmentationModelV2 from ovseg.preprocessing.SegmentationPreprocessingV2 import SegmentationPreprocessingV2 from ovseg.model.SegmentationEnsembleV2 import SegmentationEnsembleV2 from ovseg.model.model_parameters_segmentation import get_model_params_3d_UNet from ovseg.utils.io...
f2d1a51d6198848b3915d117b2953d25194e59f5c349e55515e840d5f16c5bab
Python
2,624
99
from mongoengine import * import datetime class TaskModel(DynamicDocument): id = SequenceField(primary_key=True) # Type of task: Importer, Exporter, Scanner, etc. group = StringField(required=True) name = StringField(required=True) desciption = StringField() status = StringField(default...
358198694a243a39afb7075d78a17b152d96e09331a753046f72568ef6110e0c
Python
2,625
76
import matplotlib.pyplot as plt import scipy as sp import sklearn.decomposition as skld from matplotlib import animation from mpl_toolkits.mplot3d import Axes3D def plot_results(self, results, action_data, fixed_point, title: str = "Results", dreiD: bool = False): """Plot results of analysis performed by chiefinve...
848cf47787b469b72be454b59ab0f393a1601485a0fa7e9036624a816e6cd3ad
Python
2,625
65
# Copyright 2017 The TensorFlow 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 applica...
8a5190ddc3a35fbd8a2d85ce40a2567a9e75b829d67cdebfd01073cf388a11b0
Python
2,625
85
import copy from typing import Any import numpy as np import pandas as pd from mirp._images.generic_image import GenericImage from mirp._imagefilters.generic import GenericFilter from mirp._images.transformed_image import TransformedImage from mirp.settings.generic import SettingsClass class SquareRootTransformedIm...
005bf0b5b93789fe1ed19d834882b0b8554706194c27b750642c7129896c94ac
Python
2,626
86
import sys import copy import argparse import logging import pathlib import numpy as np import joblib as jb import mudcod.sutils as sutils import mudcod.community_detection as community_detection logging.captureWarnings(True) parser = argparse.ArgumentParser( description="Cell-type-specific subject split experime...
03e369f3210bc62efeddcb1b67179bbef7c375b958fbde84d4ebf75ab9f39cd9
Python
2,626
88
from .base import Renderer class FakeRenderer(Renderer): """ Fake Renderer This is a fake renderer which simply outputs a text tree representing the elements found in the plot(s). This is used in the unit tests for the package. Below are the methods your renderer must implement. You are fre...
af293ec22b22ef4e6388d9557947ca2b5b22305676b916e32829c69f6a11b556
Python
2,626
75
# from schnetpack.md import neighborlist_md, calculators from ase import io # from ase.build import bulk import time from mace.calculators import MACECalculator # import schnetpack as spk # import random # from ase.md.npt import NPT from ase.md.langevin import Langevin from ase.units import s from ase import units from...
5ecb55f96882e475bc8acdf0df21428aab779eb3c8b6492ce1771d55e03f17ed
Python
2,627
80
import argparse import numpy as np import sys def generate(): parser = argparse.ArgumentParser() parser.add_argument('--vocab_file', default='vocab.txt', type=str) parser.add_argument('--vectors_file', default='vectors.txt', type=str) args = parser.parse_args() with open(args.vocab_file, 'r') as f...
aaea563c40b9da52c5be555c33b528dcb6c7af09628835069828076cf06c76f1
Python
2,627
89
"""Comprehensive predicate API contract tests for fastlog.""" from __future__ import annotations from collections.abc import Generator from typing import Any import pytest import torch from torch import nn import torchlens as tl from torchlens.fastlog import CaptureSpec, PredicateError, RecordContext class Predic...
c09d936b483ceb25d39a91e300cab374dc6d85c3fbbc3861def64e4eab75d933
Python
2,627
69
from pathlib import Path import torch import torch.nn.functional as F from brainbox import trainer from brainbox.physiology.neural import cc from src import readout class Trainer(trainer.Trainer): def __init__(self, root, model, train_dataset, n_epochs, batch_size, lr, lam, shuffle=True, device="cuda", id=None...
d562a5f689b892679cdc190b0cf3629f1ab3c0119bc0dc1a0cdeb00886f0e24b
Python
2,627
108
""" Useful constants """ from pyproj import CRS UNIVERSAL_CRS = CRS.from_epsg(3857) DEFAULT_CRS = CRS.from_epsg(4326) UID = 'uid' TID = 'tid' LATITUDE = 'lat' LONGITUDE = 'lng' ORIGIN = 'origin' DESTINATION = 'destination' ORIGIN_LAT = 'origin_lat' ORIGIN_LNG = 'origin_lng' DESTINATION_LAT = 'destination_lat' DESTINA...
18fc1c5ac54d1e2386829c256fe03fe28035cd7029337697099737c7b2e51cd4
Python
2,629
97
# %% ''' Extracts regions based on Tian SC parc. Saves ROI masks and a list of centroids. Looks at con_0006 ('threat reversal') and con_0007 ('safety reversal') specifically. ''' from nilearn import plotting from nilearn.image import new_img_like from scipy.ndimage import center_of_mass import nibabel as nib import nu...
48fd8a54969e45699079a0f5ee218fe3fcb8e79bcd3e238f54402c44ae0f368a
Python
2,629
71
from pydantic import AliasChoices, Field, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict(env_prefix="", extra="ignore") db_url: str = Field( "postgresql://codecarbon-user:supersecret@localhost:5432/codecar...
eedc65eb40f6dd57d086cb66631846543a5be16d3991ce9fcdeb75d4494767b8
Python
2,629
66
import torch from typing import Dict def compute_gradient( data: Dict[str, torch.Tensor], chains: Dict[str, torch.Tensor], centered: bool = True, pseudocount: bool= False, ) -> Dict[str, torch.Tensor]: """Computes the gradient of the log-likelihood. By default implements the centered version of th...
02f5f818fa087a9a4aff0a5bcfb543abf7119dd847f9768f591dacd75b7771ec
Python
2,630
30
# Read in the file with open('index.html', 'r') as f: data = f.read() # data = data.replace('<h1>Index</h1>', # '<h1>Index 🔍</h1>') # data = data.replace('<a href="https://csinva.github.io/imodels/">Docs</a>', # '<a href="https://github.com/csinva/imodels">Github</a>') #...
13e81d33085d6a401e262acb0301337ae85a53498d85b2445855d970789c376f
Python
2,630
74
# 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 random import numpy as np import torch from torch.utils.data.sampler import Sampler def worker_init_fn(worker_id...
3f3f88313763a0ddc3d382935ec51fe4d08e8f8b160ba4bb57700c7ab3af7af9
Python
2,630
71
from numpy.testing import assert_array_equal import numpy as np import pytest from pytest import approx from pyriemann.utils.ajd import rjd, ajd_pham, uwedge @pytest.mark.parametrize("ajd", [rjd, ajd_pham, uwedge]) @pytest.mark.parametrize("init", [True, False]) def test_ajd(ajd, init, get_covmats_params): """Te...
52590085bb2c9c9ae477b62d15c44f431929b13decc28df2c0c5f3726b84383a
Python
2,630
99
"""Double DQN.""" import argparse from collections import OrderedDict from typing import Tuple from pytorch_lightning import Trainer from torch import Tensor from pl_bolts.losses.rl import double_dqn_loss from pl_bolts.models.rl.dqn_model import DQN class DoubleDQN(DQN): """Double Deep Q-network (DDQN) PyTorch ...
8de0711c217e44bd02e025db48102ce10c193f091ed05952a23f9227362c41b0
Python
2,630
77
#!/usr/bin/env python3 import argparse as ap import numpy as np import pandas as pd import pickle from tqdm import tqdm # Parse arguments parser = ap.ArgumentParser() parser.add_argument("files", nargs="+", type=str) parser.add_argument("-out", "--output", type=str) args = parser.parse_args() # Open first file to g...
9fb2eb5192c84d152d30a82f1e48028dd56b9466ccf173bc9604783e612fdb7f
Python
2,630
69
import os import json import shutil import glob from tools.hash_value.morphology import make_morphology_hash_key_dict ''' Code for transferring morphology files from BluePyOpt output to BasalGangliaData and Snudda format ''' def transfer_morphologies(source, destination, selected=False): """ :par...
faa0358fab579e8b4170686f06b32c81b6d653f7d38b92b3f5b43c1f662059a0
Python
2,631
72
import numpy as np import sympy as sp from scipy.integrate import odeint from . MarkovModel import MarkovModel from . MarkovChain import MarkovChain from . common import * from . settings import settings class M10Model(MarkovModel): """ A four state Hodgkin-Huxley model with k=e^{av+b} parameters """ ...
5ec91c846f710813fa22772fc555d5a04a82c8f093cfa045bd303d359e69609f
Python
2,632
82
from typing import Literal import numpy as np import scanpy from anndata import AnnData from numpy.random.mtrand import RandomState _InitPos = Literal["paga", "spectral", "random"] def run_umap( adata: AnnData, min_dist: float = 0.5, spread: float = 1.0, n_components: int = 2, maxiter: int | Non...
7cced387b943e03615803710d2030b1520f30f8d9640631dcff0311cfc631ea3
Python
2,632
93
from abc import ABC, abstractmethod import attr import torch class LocalSplicepointModelResidualPropagator(ABC): """ Represents a technique for propagating the LSSI residual through a model. """ @abstractmethod def propagate_residuals(self, output, splicepoint_results_residual): """ ...
91d34f84222b38eb586157d231efb3040fe522d4245e9762888730b7df50a457
Python
2,632
95
import pytest from pyrosm import get_data @pytest.fixture def test_pbf(): pbf_path = get_data("test_pbf") return pbf_path @pytest.fixture def helsinki_pbf(): pbf_path = get_data("helsinki_pbf") return pbf_path def test_parsing_natural_with_defaults(test_pbf): from pyrosm import OSM from py...
cefb01b9507f173510f5bcc1e633273e5c2dd35b850822d021b6c2a7d65ea373
Python
2,632
96
#!/usr/bin/env python3 """Resolve the next FA4 beta tag and optionally create + push it. Usage: python bump_beta_tag.py # dry-run by default python bump_beta_tag.py --push # create and push the tag """ from __future__ import annotations import argparse import os import re import subprocess...
3b1ac397632e2ae313bfc864e88f86ec6aebaa656a7098c0abf28986c630139b
Python
2,633
78
from collections import defaultdict import itertools import os import warnings import numpy as np import torch from permacache import permacache, stable_hash from more_itertools import chunked from modular_splicing.dataset.basic_dataset import basic_dataset @permacache( "analysis/extract_psams", key_functi...
5e4cca8f23980227b45508de66254d78f3d682a1813aecd4e41606df04867fc2
Python
2,633
79
""" Video Utilities Module This module provides utility functions for video file management including file listing, video file indexing operations, and migration utilities for directory structure updates. """ import glob import logging import os import subprocess def list_local_video_files(rootdir, createMD5=False)...
85c35e6114017b4a01f36365f6a723654b221ddbd528e0104666f0602af00bfe
Python
2,633
74
import numpy as np import os import cv2 import os.path as osp def compute_mean_std(dataset_dir): """ 计算给定数据集中所有图像的RGB通道的平均值和标准差 参数: dataset_dir (str): 数据集路径,包含所有图像文件的目录 返回: mean (np.ndarray): RGB通道的均值,形状为(3,) std (np.ndarray): RGB通道的标准差,形状为(3,) """ # 初始化变量 pixel_n...
30bdeb95b42600f1a17b01779c8a397565f16ebb27d4d211eeea4f767543f7a8
Python
2,634
74
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import json import argparse from os import walk from os import path as osp from zipfile import ZipFile from gluoncv.utils import download, makedirs def parse_args(): parser = argparse.ArgumentParser( description...
5028eeb2ede96c28107d2b6f2fd4d4e311312503dd128a1db257a14f42b764f0
Python
2,634
103
#!/usr/bin/env python3 # encoding: utf-8 import os, sys, re import logging import argparse import gzip from collections import defaultdict def main(): parser = argparse.ArgumentParser(description="validate fastqs", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--left_fq",...
6035dc15df258f33a793d99c751f53de18c8799d8e391df89ba310fa8461d1ec
Python
2,636
70
from datetime import datetime import warnings import sklearn import auggam.config as config from datasets import load_from_disk import auggam.linear import auggam.data import pandas as pd from copy import deepcopy from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModel, AutoModelForCausalL...
d29482fcd6b7b17e2286cddc30ca3cb64ab6afbda51bc97f80a62d4c6b4339a8
Python
2,636
69
from src.keras_tuner_cv import * from src.data_processing import * import keras_tuner as kt import pandas as pd import numpy as np import os import click import datetime @click.command() @click.option('--cuda_device', default='0', help='which GPU to use', show_default=True) @click.option('--input_train', default='../...
640bd6949735b4bdc6ccfdeb67d32be38d4f77aaa7652c8386bfa2ea03ba9736
Python
2,637
80
# 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 pytorch_lightning as p...
0865226feac5065a7fd4cbb5fd0d2a35f3cb8b87c9a389f506b66983a24030e2
Python
2,639
67
### Monte-Carlo routines for significance level estimation import numpy as np import sys from .random_proc import ar1 from .fnutils import take def mc_levels(transform_fn, size=(256,256),level=3, N = 1e3): """Return Monte-Carlo estimation of noise :math:`\\sigma` Parameters: - transform_fn: (`functio...
5fc1197620852e4ca7233b7082a03e076ba7bd10e093373107b845c1fdeadea9
Python
2,639
82
"""grind-r5 b7 R24: the roster contradiction guard must survive ``python -O``. The plain-callable branch of the ``get_ignored_functions`` vs ``get_testing_overrides`` contradiction check was a bare ``assert`` + ``continue``: under ``-O`` the assert stripped, and a (fault-injected) future torch listing an overridable f...
328c2d28d131f097c063bf22335a51a33ea0d68b52b3945892dbe6aa0d2ccd94
Python
2,640
73
import os import warnings import h5py import numpy as np import pandas as pd import scanpy as sc from scbig import run_scbig, preprocess, setup_seed warnings.filterwarnings('ignore') for dataset in ['fetal_liver_atlas', 'Trachea']: print('----------------real data: {} ----------------- '.format(dataset)) set...
b790a9d36c88fe3fa93e62ecf54bbc24dff5a2ac61214110189040ca3cca3c07
Python
2,640
82
"""Composite datatype for the HDF5SummarizedExperiment R data object. This datatype was created for use with the iSEE interactive tool. """ from galaxy.datatypes.data import Data from galaxy.datatypes.metadata import MetadataElement from galaxy.datatypes.protocols import ( HasExtraFilesAndMetadata, HasMetadat...
f9c1efa0205911f93a3d04d159e651f6adf63541505c42b54f16b97eb0e93886
Python
2,640
30
# Read in the file with open('index.html', 'r') as f: data = f.read() # data = data.replace('<h1>Index</h1>', # '<h1>Index 🔍</h1>') # data = data.replace('<a href="https://csinva.github.io/imodels/">Docs</a>', # '<a href="https://github.com/csinva/imodels">Github</a>') #...
ff4da05ddc4cc28dacaa2bd5e084fb6a52c35a0cceae7446eaf2e7f2cf465990
Python
2,640
92
# Author: Aqeel Anwar(ICSRL) # Created: 7/30/2020, 1:44 PM # Email: aqeel.anwar@gatech.edu # Code resued from https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url # Make sure you run this from parent folder and not from utils folder i.e. # python utils/fetch_dataset.py import...
2b65cb904dc166c38f27ad79b849f1ca88b3a98bf1e688341852bca4f5a58223
Python
2,641
88
"""Fuzzy Min-Max Neural Network, 1992, Patrick Simpson. Paper: Simpson 1992, "Fuzzy min-max neural networks. I. Classification." Hyperbox membership measures compare each feature to learned lower and upper corners, then aggregate boxes by class. """ from __future__ import annotations import torch from torch import T...
6fc912ec3aa977ea5d97317a4302a00877246ad53c90558435cf3bbc47999960
Python
2,641
68
# Copyright 2019 Novartis Institutes for BioMedical Research Inc. 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...
d4174305da79b02e076a0d857ad87fde31a414c0d9dda0a90826c62a9d4c9f2e
Python
2,641
73
import numpy as np import sympy as sp from scipy.integrate import odeint from markov_builder.example_models import construct_four_state_chain from . MarkovModel import MarkovModel from . import common class BeattieModel(MarkovModel): """ A four state Hodgkin-Huxley model with k=e^{av+b} parameters """ ...
6f2db9244d9c5f19f8e64e6c427b866464813d8f8f3f131b6f5ed704b07eb4ea
Python
2,642
67
from typing import Dict, Any from .atomistic import AtomicDimeNet from .atomistic_nn_model import AtomisticNNModel from bioconfpred.data.split import DataSplit from bioconfpred.params import (LOG_DIRPATH, DIMENET_CONFIG, DIMENET_MODEL_NAME) class DimeNetModel(AtomisticNNModel):...
599facb857e88437879d22e588e38d2b8585b6553e48f78c4f9538941b93bf3a
Python
2,643
43
#==============================================================================# # Author: Dominik Müller # # Copyright: 2024 IT-Infrastructure for Translational Medical Research, # # University of Augsburg ...
5b68d2fa6bd72f5d799eab995348c03231b6206857c0250e5f5534fc19dbfd4a
Python
2,643
99
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 29 10:25:54 2018 @author: nfcontrol """ # import statements - all of these are packages within the rt environment import time from random import random as rand import sys import numpy as np import matplotlib import matplotlib.pyplot as plt im...
4e7796dc68e484e2e33effb8d6ea5ee263fad42656ffce91d3c0e8bce258c6f7
Python
2,644
77
# 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...
bd2d6d5ecd6943733d50bdad1a17c2bad9e7b0804fa664d97b6a7ec8ae55135a
Python
2,644
79
from __future__ import print_function, unicode_literals, absolute_import, division from six.moves import range, zip, map, reduce, filter from ..utils import _raise, backend_channels_last import numpy as np from ..utils.tf import keras_import, BACKEND as K def _mean_or_not(mean): # return (lambda x: K.mean(x,ax...
fd75229f1196972db82672234307c872cdaa815be06241f960f4d510b4a80b1c
Python
2,644
91
#!/usr/bin/env python """ Input: File with tab separated columns. One column contains the id's of a collection of molecules that should to be retrieved. Output: Retrieved compounds """ import argparse import sys import cheminfolib import psycopg2.extras cheminfolib.pybel_stop_logging(...
dd6dfae3ff10e1ad3a29e05ad635a2737f24cf3b4638339f569039da25ce784e
Python
2,645
91
import numpy as np import matplotlib.pyplot as plt from collections import defaultdict from modular_splicing.utils.statistics import bootstrap def plot_by_model_group( vals, names, title, ylabel, *, ax=None, colors, extra_zero_line=True, error_bars=True, ): """ Run a plot...
f349a7cac7eb8338fcd16eea927cb0e26e81034642f0d116711feae91a1166a0
Python
2,645
62
# 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...
5a6c7ee90db0dac8c1fd3736b70f599a77ba7551104f173b8263d6d7662a9241
Python
2,646
66
""" Framework constants — single source of truth across the paper series. Imported by: - paper5_5d/pipelines/reprocess_car_local.py - paper7_ad_cross_cohort/analyses/state_geometry.py - paper4_empirical/code_package/eeg_phi_analysis_v3.py - paper4_empirical/code_package/eeg_regional_analysis_v2.py - paper4_e...
08e155723e3d939543d8f6daf704c93d517c39720a6d81fa95e2c4e876f93234
Python
2,647
72
""" This module define the EncoderModel """ import math import torch.nn as nn import torch # Create pytorch Transformer model class model_ENCODER(nn.Module): # pylint: disable=invalid-name,abstract-method """ This class was created a long time ago but we CANNOT change the content because we load the pre...
6b601253e67524bf5ef958d29b8d2159669693031417dc09b2e3cdd20aaa7992
Python
2,647
95
import os import psutil import sys import traceback PROCESS = psutil.Process(os.getpid()) MEGA = 10 ** 6 MEGA_STR = ' ' * MEGA def main(): try: print_memory_usage() #alloc_max_str() alloc_max_array() except MemoryError as error: # Output expected MemoryErrors. log_exce...
2182c274bc8914dfa7760de72d5476d1bc9853666dde487899e00612a7a9ec87
Python
2,648
73
import os import pandas as pd import numpy as np from sklearn.ensemble import BaggingRegressor from sklearn.ensemble import BaggingClassifier from sklearn import linear_model import sklearn import pickle def load_model(in_model_fp=r"./models/model_clinical.pkl"): if not os.path.exists(in_model_fp): print("...