sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
e6cf098cef6e626d9053f69e011d15668bbfa97268762ac18bb11511032d10c3
Python
5,171
98
#==============================================================================# # Author: Dominik Müller # # Copyright: 2024 IT-Infrastructure for Translational Medical Research, # # University of Augsburg ...
09326e7369ab787f8622bb49b88d0b87b1c8384b9533a6f46764fa50f5d867cc
Python
5,172
166
import networkx as nx import numpy as np from numpy import linalg as LA from scipy.integrate import quad from scipy.linalg import eigh from scipy.sparse import csgraph from scipy.spatial import distance from sklearn.metrics.cluster import adjusted_rand_score _eps = 10 ** (-5) def _assert_before_distance(adj1, adj2):...
77dec6f7f462be772a9443fd5d7ae0eea26fce54acf84113847789c5754ee23f
Python
5,172
153
import numpy as np import torch import torch.nn.functional as F from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from torch_geometric.data import DataLoader, Batch from torch.optim.lr_scheduler import ReduceLROnPlateau from pathlib import Path import copy from matplotlib...
9bd05b2771b3832bd32fc1aea7da4670599bc89df5700d93a6636257c544f71e
Python
5,173
165
import os import random as python_random import numpy as np import tensorflow as tf import tensorflow_datasets as tfds from tensorflow.keras.models import load_model from gradient_accumulator import GradientAccumulateModel from gradient_accumulator import GradientAccumulateOptimizer # get current tf minor version tf...
85f21c766cfbf14cb56b2f3f05265e1c26e0b7a539bf186ae8ee0611a92473b7
Python
5,175
161
from torch.nn.parameter import Parameter import torch import torch.nn.functional as F from .dense_layers import LinearLayer, Residual_block from torch_geometric.nn import MessagePassing from torch_geometric.utils import softmax #import torch_scatter from torch_geometric.utils import scatter class GATLayerCus(Message...
3e1ad1482c78a510a022c5e080a02cc51809a1f79e88c987a4c1711aa4251af1
Python
5,176
111
#========================================================================= # # Copyright NumFOCUS # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/license...
7d1f444d99d9303ff787552ab82a75f3c0dc916d6fd805cf4d86030f699950aa
Python
5,178
130
import numpy as np from ._perturb import embed_pattern_seqs, tile_pattern_seqs def embed_deepstarr_distance_cooperativity( null_sequences, motif_a, motif_b, step=1, allow_overlap=False ): """ Generates sequences for a motif cooperativity analysis similar to that performed in the DeepSTARR p...
40ee9ae6586b00abf13b002b7addc3d846bdaf7cc045965e6a796baeb77b3db0
Python
5,179
174
import pandas as pd import fiona import json import os import fnmatch from ..core.trajectorydataframe import TrajDataFrame from ..core.flowdataframe import FlowDataFrame from ..preprocessing import filtering, compression from tqdm import tqdm def write(skmob_df, file): """ Write a TrajDataFrame to a json file....
8a1dd84ccff1a96182a8a657be92b64f585ae7306ee64c14665e8a408d92d72d
Python
5,180
155
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # For a full list of documentation options, see: # https://www.sphinx-doc.org/en/master/usage/configuration.html # ---------------------------------------------------------------------------- import os from os.path import dirname ...
dcefe16d700aaca1c438b05b4a2bb7757bbb3219f8a1e424b5d209f30fa04e31
Python
5,180
120
#!/usr/bin/env python3 """ check_dois.py — verify every DOI in the JNE reference list resolves and that the returned title matches what the manuscript claims. Run: venv/bin/python check_dois.py IOP treats references to non-existent sources as strong evidence of irresponsible AI use: rejection at submission, retracti...
ffac5c289979a505e7b8c30dcc1efa4565be342f19d64231eda066e7cb9a63e0
Python
5,183
143
import numpy as np import pytest from keras.src import backend from keras.src import layers from keras.src import models from keras.src import testing from keras.src.backend.common import global_state from keras.src.backend.common.remat import RematScope from keras.src.backend.common.remat import get_current_remat_mod...
c754ad5b2f9dfa31bf5ae5b1958219dd50eb8cc9848e3db80e47fafa21f79df9
Python
5,184
119
# pylint: disable=unused-import,too-many-function-args """Anchor box generator for SSD detector.""" from __future__ import absolute_import import numpy as np from mxnet import gluon class SSDAnchorGenerator(gluon.HybridBlock): """Bounding box anchor generator for Single-shot Object Detection. Parameters ...
f04d1d75495cedfc8ded0318ee55a2abfccf38103783db0742e3a2e65f7b715e
Python
5,184
157
"""CenterNet training target generator.""" from __future__ import absolute_import import numpy as np from mxnet import nd from mxnet import gluon class CenterNetTargetGenerator(gluon.Block): """Target generator for CenterNet. Parameters ---------- num_class : int Number of categories. o...
a5b08181562d0dde48ae6df426aedae2e993d4af9c898dea9b6afa58076059ad
Python
5,185
166
"""Fastlog backward gradient recording tests.""" from __future__ import annotations import warnings from pathlib import Path import pytest import torch from torch import nn import torchlens as tl from torchlens.fastlog import CaptureSpec, GradRecordContext, InvalidStorageError class TinyRelu(nn.Module): """Ti...
b3fa38fb3c59b4afe0d08ea644c5035ede497addda2cd35b3e96349b4227788e
Python
5,185
148
#!/usr/bin/env python3 """ File: calc_avg_gene_expression.py Created: 2022/02/17 Last Changed: Author: M.Vochteloo Copyright (C) 2020 University Medical Center Groningen. A copy of the BSD 3-Clause "New" or "Revised" License can be found in the LICENSE file in the root directory of this source tre...
d69dd26422ef4d6092ba3d9fb1bd74cb4433277b3504fc7b773c286d475c738f
Python
5,185
154
"""Preview backends must match torch's exact relation-label convention. Torch (``postprocess/labeling.py``) relabels ``parents``/``children`` (and the lineage sets ``input_ancestors``/``output_descendants``/``root_ancestors``) through a CONDITIONAL mapping: a referenced op's bare ``layer_label`` when its layer has a s...
60affd771030392879f0f29c378c2648191b276153e31b88d9883f0c351abac1
Python
5,188
141
#!/usr/bin/env python3 # import required modules from keras import layers from keras import models from keras import optimizers from keras import callbacks import numpy as np from argparse import ArgumentParser def parse_cmd_args(): """ """ parser = ArgumentParser() parser.add_argument('-d', '--direc...
79d28a645c285f8379cb5797de37e079005f79a38beb29ef17dce310b66422fa
Python
5,188
121
import itertools import json import os import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt import matplotlib import statsmodels.stats.api as sms from angorapy.common.const import PATH_TO_EXPERIMENTS, QUALITATIVE_COLOR_PALETTE font = {'family' : 'Times', 'weight...
808a349513dd72b31494f06edcdd8589b6b2175b288ccd14b787025dece5173a
Python
5,188
129
""" Author: Bruno De Santi, PhD Affiliation: Multi-modality Medical Imaging Lab (M3I Lab), University of Twente, Enschede, The Netherlands Date: 20/09/2023 Description: Collection of metrics to evaluate registration performance MSE: mean square error PSNR: peak signal-to-noise ratio SSIM: structural similarity index N...
ad5a2d0de5c35a2ea870bbedce44fd3ce9a21247b33ed89556e169748aa09fd0
Python
5,188
148
from typing import List import torch.nn as nn import torch.nn.functional as F from torch import Tensor from models.basic import DeepLearningBackbone try: from torch.hub import load_state_dict_from_url except ImportError: from torch.utils.model_zoo import load_url as load_state_dict_from_url __all__ = ['ResN...
23f9c2ff4af24643d9db32e5618dd9214906db641ec284d9695cfc18fdaa6f0c
Python
5,189
133
# -*- coding: utf-8 -*- import os import numpy as np from numba import set_num_threads import pandas as pd from scipy.sparse.construct import random from scipy.sparse.sputils import matrix import sklearn from sklearn.preprocessing import StandardScaler import umap import matplotlib matplotlib.use("Agg") #サーバーでプロットする...
dbabfe308f59662cfc0227754128b94451349f7cd488c8780a522c7ceb5f857c
Python
5,189
152
import numpy as np import torch import torch.nn.functional as F from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from torch_geometric.data import DataLoader, Batch from torch.optim.lr_scheduler import ReduceLROnPlateau from pathlib import Path import copy from matplotlib...
a4b96a8c6f39c4339dcdff4bb5923d38ce2375eea60e6f23e182284bee80f1e2
Python
5,190
123
#!/usr/bin/env python3 import os import sys from utils import pdb_utils import time from argparse import ArgumentParser import numpy as np def parse_cmd(): """Parse command-line arguments. Returns ------- Command-line arguments. """ parser = ArgumentParser() parser.add_argument('-i', '--...
2756f3fa82a97186de424c7f08d992fe3a9d78670828b5e6e35e3d23cf050d22
Python
5,191
122
import torch import math import torch.nn as nn def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=True, ): output_attentions = True mixed_query_layer = self.query...
57c5267605736ae7118b89c4f39b276ea098142d7dcc703151734960568df5a6
Python
5,192
162
import torch import torch.nn as nn from modular_splicing.models.modules.positional_encoding import PositionalEncoding from modular_splicing.models.modules.sparsity_propagation import ( sparsity_propagation_types, ) from modular_splicing.utils.construct import construct from .tanh_attention.tanh_convolved_attn im...
7ba48b6291ba7f434d544e2d4fdc83446cd2b556a21bf1ecd514672029623a9f
Python
5,196
142
""" Dataproviders that iterate over lines from their sources. """ import logging from galaxy.util import ( Element, etree, ) from . import line _TODO = """ """ log = logging.getLogger(__name__) # ----------------------------------------------------------------------------- hierarchal/tree data providers c...
5964e50e70a1a82f5f738d344789bb2c85a517153148385a44b1f43cc05a42c3
Python
5,197
140
# 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: fewer clusters, a shal...
14e1a239eb3103b2b4bb676e0acf59710690f21cc3584d81ee751b36f69ab294
Python
5,198
128
# ----------------------------------------------------------------------------- # Copyright (c) 2015, The Deblur Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # -------------------------------------------------...
76c14f003674af59c2615d55608ce3438a99b993479c123dc8812a59a9a829d8
Python
5,198
136
"""Netron export x existing-feature composition rows (F14, netron memo s7). Every row names a composition of this exporter with an EXISTING feature: C2 export x interventions (marks visible in the artifact), C3 export x halted capture (the honesty marker is the composition most likely to rot silently -- the exporters ...
bb9b7670dae00c56fce71c63346300758c03d4cc521bfe438fb6c46d8dabd684
Python
5,198
150
"""Tier T3: the installed netron wheel's parser executes on the artifact. The harness (tests/test_netron_export_harness.mjs) imports netron's real ``onnx.js`` ModelFactory -- no transcription -- and reports what netron WOULD draw: matched reader, node/function populations, painted edge labels, sidebar strings, drill-d...
76043814af366b1813a4bc27da0e1e4d6ad5ad553cc5994c49ac8b059fbb9a73
Python
5,199
139
"""Tests for the xcp_d.interfaces.concatenation module.""" import os from nipype.interfaces.base import Undefined, isdefined from xcp_d.interfaces import concatenation def test_cleannamesource(datasets): """Test xcp_d.interfaces.concatenation.CleanNameSource.""" nifti_file = os.path.join( datasets[...
931d30cb0342975c904788d10b1121a1cca557d287eeb9a3060c6a221b93b506
Python
5,199
158
from __future__ import annotations from pathlib import Path import zipfile import numpy as np import pandas as pd import pytest from larvaworld.lib.process.import_aux import ( DLCImportError, DLCScaleValidationError, read_deeplabcut_tracks, ) from larvaworld.lib.process import discover_deeplabcut_source_...
44bdaae35ee2a7fe9fdd73f93aee554f03a9a6fa4ec84453cf251337843c1f1c
Python
5,200
124
"""12. Run an object detection model on NVIDIA Jetson module ========================================================== This tutorial shows how to install MXNet v1.6 (with Jetson support) and GluonCV on a Jetson module and deploy a pre-trained GluonCV model for object detection. What's in this tutorial? -------------...
fe0b3c7197084305faa719ff8fe75ff4b255b33b82ce5c3beb4f3f25b075e275
Python
5,200
128
import numpy as np import torch as th from .gaussian_diffusion import GaussianDiffusion def space_timesteps(num_timesteps, section_counts): """ Create a list of timesteps to use from an original diffusion process, given the number of timesteps we want to take from equally-sized portions of the origin...
351cd28034d68bbc88caced694f95bbf5af1d4bc38a991b2e25ca11a5c1eb271
Python
5,201
154
from typing import Tuple import numpy as np import torch import torch.nn as nn dev = torch.device('cuda:0') class MultipleOptimizer: def __init__(self, *op): self.optimizers = op def zero_grad(self): for op in self.optimizers: op.zero_grad() def step(self): for op in ...
cff918480307870c576797773228c6dd16494651ec0b082ca5434db940bc93f0
Python
5,201
255
""" Force choice 16 category imagenet, choosing the maximum of a cateogry that falls into the class. """ import csv import json import os FILE_DIRECTORY = os.path.realpath(os.path.dirname(__file__)) knife = ['n03041632'] keyboard = ['n03085013', 'n04505470'] elephant = ['n02504013', 'n02504458'] bicycle = ['n...
47de77f46556f8c03b759e930e2feaa7c8b6be006b68f9771c6687bba1023125
Python
5,205
210
# 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...
bc89a2cfa693985a8ef1719aa52c4ceded6f1771b815095e60fe6db0b9ce0434
Python
5,206
129
import os import nibabel as nib import numpy as np import imageio import scipy.ndimage as ndimage def resample(image, spacing, new_spacing=[1, 1], mode='constant'): """ Resample an image to a new spacing. """ new_shape = np.round(image.shape * (np.array(spacing) / np.array(new_spacing))) resize_factor...
e871bf43ef30f5a90acd947a58e8b7c1a8195b46c7df635d51388369249dfd7c
Python
5,208
287
#!/usr/bin/env python '''Generate models for affinity predictions''' # variables: # BALANCED(true) # POSEPREDICT # RECEPTOR(false) # AFFMIN(0) # AFFMAX(0) # AFFSTEP(0) basemodel = '''layer { name: "data" type: "MolGridData" top: "data" top: "label" top: "affinity" include { phase: TEST } molgrid_...
fe93524bb1c0900a2fdf6df026aade6205daec4b3b26b5af47de3256fa8ddbd4
Python
5,208
166
# %% ''' Runs PPI within GLM regions of interest Note that this only runs on the cluster because it needs AFNI ''' import platform import h5py import sys import os import numpy as np import pandas as pd from time import time from nilearn.signal import clean from ppi_afni import perform_ppi sys.path.insert(0, '..') fro...
51e8dfa6227125df0bbbec2072cba8feeff4d71866bf0e9df2c4a45cc764f849
Python
5,209
184
"""Terminals and colors.""" from __future__ import annotations import base64 import os import platform import sys from functools import reduce __all__ = ('colored',) from typing import Any BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) OP_SEQ = '\033[%dm' RESET_SEQ = '\033[0m' COLOR_SEQ = '\033[1;...
e2cdf172a8f2a45b3f5c555b38794bef6e2dd897c95ac42481b9e156be32108e
Python
5,209
197
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
0431c0870e1948751ed97c4d50dfd38b621664bfa2d0b30cb1a004ed18aefbb3
Python
5,211
103
# General imports import os import sys import numpy as np import pandas as pd import seaborn as sns from tqdm.auto import tqdm import matplotlib.pyplot as plt # EUGENe imports and settings import eugene as eu from eugene import settings settings.dataset_dir = "/cellar/users/aklie/data/eugene/revision/ray13" settings.o...
7d250b538907698f23bc5fe109bd94bb66c07a8b2a188cc6bdeb6de657d5c1ae
Python
5,211
82
"""General-purpose training script for image-to-image translation. This script works for various models (with option '--model': e.g., pix2pix, cyclegan, colorization) and different datasets (with option '--dataset_mode': e.g., aligned, unaligned, single, colorization). You need to specify the dataset ('--dataroot'), e...
3a9eec00bef1e2f76d84293fce5c5c014d7dadee847f356dd961895ba707b492
Python
5,212
155
import h5py import os from modular_splicing.dataset.generic_dataset import GenericDataset from modular_splicing.utils.multi_h5_file import MultiH5File class H5Dataset(GenericDataset): """ Represents a dataset that is stored in an HDF5 file. Data in this file must be stored under keys C# where C is a cha...
736a7d78625b0cc6aa1f3d819220e37a060ebc0230972677bbbd44c87fd404d7
Python
5,214
86
import pandas as pd import logging from utils_stats import output_summary_of_ensemble_strategy from utils.json_loader import load_json_into_pandas_dataframe """ dict_all_ensembles = { "My_network_with_label_smoothing": [ "old_before_may_2021/label_smoothing_EC_pred/fine_tune_for_EC_prediction_with_label_sm...
acc178bc90d5d648e0304f1f258adc8e308c5a5ebd9850d0bd60573e5ae6964b
Python
5,214
154
import random from typing import Tuple import numpy as np import torch import torchvision.transforms as transforms from PIL import ImageFilter from pytorch_lightning import LightningDataModule from torch.utils.data import DataLoader, Dataset from moco_data_set import MoCoDataset class MoCoDataModule(LightningDataMo...
f3e099b546ea828126a2cbe9a0b5a7bf5cb7501ac4e35150346da8d96c3ce68e
Python
5,215
216
""" Created on Thu Dec 16 23:56:35 2021 @author: apeyra4 """ import pynapple as nap import numpy as np from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler def assemblyPCA(spike_counts, epochRef, epochTest = None, method = 'marcenko', numComp = None): ''' Parameters ----...
04b93916bb8a1a833c891e6c19d44789940274307c48c5247c53ca18523056a5
Python
5,216
138
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Written by Bin Xiao (leoxiaobin@gmail.com) # Modified by Bowen Cheng (bcheng9@illinois.edu) # ------------------------------------------------------------------------------ fro...
202029199b3f86eec896ef2117112e8366373f928c93fd046006851abc8160cb
Python
5,216
159
# SOURCE: vendored from locuslab/TCN @ master # https://raw.githubusercontent.com/locuslab/TCN/master/TCN/tcn.py # # "TCN-based ECG-Denoising" (queue candidate: TCN architecture applicable to # ECG denoising/regression, e.g. the ECG-TCN paper arxiv:2103.13740, which uses # the same causal dilated Temporal Convolutional...
79b0fd11a93fd3e9038a8d64d347e6f5e0d6c482a8b9474dd000129d516c9329
Python
5,216
125
import numpy as np import sklearn.model_selection import tqdm from angorapy.analysis.investigators import base_investigator import tensorflow as tf from angorapy.analysis.sindy.autoencoder import SindyAutoencoder from angorapy.analysis.util.sindy import compute_z_derivatives, sindy_library_tf from angorapy.common.po...
2373f2d27a40699ee2f6c97eeab9da8003f18fd866905febdd8b80070fda1dcd
Python
5,217
179
'''bdpy.evals.metrics''' import warnings import numpy as np from scipy.spatial.distance import cdist def profile_correlation(x, y): '''Profile correlation.''' sample_axis = 0 orig_shape = x.shape n_sample = orig_shape[sample_axis] _x = x.reshape(n_sample, -1) _y = y.reshape(n_sample, -1) ...
e1165108d36c76b38071fac61b056682078e4b25da77649d893c95bfb54a264a
Python
5,219
147
from __future__ import print_function from __future__ import division import os.path as osp import mxnet as mx import numpy as np import gluoncv as gcv from mxnet import autograd, gluon from math import pi, cos from gluoncv.utils import LRScheduler, LRSequential def compare(obj, niter, expect, **kwargs): np.test...
10bdc2b2a86849f21ce2c9c624ad6177ebc8db5590af414d829e02910e4093df
Python
5,220
142
import os import sys import argparse import mne import numpy as np import pandas import pylab as pb from mne.datasets import fetch_fsaverage from mp_dip.utils.visualise_atoms import reconstruct, interpolate_feature_for_visualisation from mp_dip.research.parcellation_search import get_label_from_head_position_atlasre...
3b2cd33efe2b17d9725646d06c915ae9c2e8cf8bf4edb8f77dc4d39bcbc116f1
Python
5,224
180
import functools import attr # import tqdm import os import numpy as np import torch from utils import batched # from permacache import permacache, stable_hash MOTIFS_DIRECTORY = os.path.join( os.path.dirname(__file__), "data_motifs", "motifs" ) SPLICE_MOTIFS_DIRECTORY = os.path.join( os.path.dirname(__fil...
2b01a2b0710b02140ce6646a051e90641bad6acf19584784689898eaba45517a
Python
5,225
130
from os import PathLike from warnings import warn import numpy as np import pandas as pd import scanpy as sc from anndata import AnnData def read_10x_h5(filename: PathLike, atac_only: bool = True, *args, **kwargs) -> AnnData: """Read a 10x Genomics ``.h5`` file, keeping only the ATAC (peak) features by default. ...
ca5dc07b5e5202891d5dd45ef283955bdb692ba2bfb9e8c0ed81c59b15d04c55
Python
5,225
143
# SVHN model specification import torch import torch.distributions as dist import torch.nn as nn import torch.nn.functional as F from numpy import sqrt from torch.utils.data import DataLoader from torchvision import transforms, datasets from torchvision.utils import save_image, make_grid from src.utils import Constan...
f18a9eed1f7865f7b2123a935dc9fb06f0e2030ed58ed3261214cbed0775553e
Python
5,225
154
import warnings import torchinfo import torch import torch.nn as nn from tqdm import tqdm as tqdm_dataloader # tqdm(dataloader) causes an error if tqdm.auto.tqdm is used from .data import read_batch def get_model_summary(model, input_size=None, verbose=0, **kwargs): device = next(model.parameters()).device ...
15fe16c9052f8a88da713d8bb72419a5f110f86cff4acd5d2ec390404f2b4009
Python
5,226
134
"""Agent service layer for AI agent management.""" import logging from functools import partial from typing import ( Any, ) import anyio from galaxy.agents import GalaxyAgentDependencies from galaxy.agents.registry import AgentRegistry from galaxy.agents.router import QueryRouterAgent from galaxy.config import G...
2c1a998a62b08d9241f4d5efc766be561f31b2bb9f81bf06f4845befad86e976
Python
5,226
195
""" Test configuration and fixtures for ethoscope_node tests. This module provides common pytest fixtures and configuration for all tests in the ethoscope_node package. """ import os import shutil import tempfile from pathlib import Path from unittest.mock import Mock, patch import pytest # Test data directory TEST...
4fb052e2d6015b7171b8b9b1ac57a28ee7bfac97086a449f708c83f2fd5c5235
Python
5,226
109
#==============================================================================# # Author: Dominik Müller # # Copyright: 2024 IT-Infrastructure for Translational Medical Research, # # University of Augsburg ...
6e5b3fd287c18a0bf93dc3e00ac27c6319f9437b66e7d2ae7b6b54b4ce96edd6
Python
5,226
157
import sys import unittest from unittest.mock import patch, MagicMock import pynvml from carbontracker import exceptions from carbontracker.components.gpu.nvidia import NvidiaGPU class PynvmlStub: @staticmethod def nvmlInit(): pass @staticmethod def nvmlShutdown(): # NvidiaGPU._handle...
24f420db901cbcfb5ff8ca6b302c92236ca0535808c9d135618c75a1597702d3
Python
5,227
159
import matplotlib.pyplot as plt import torch from torch import nn from rectipy import Network import numpy as np device = "cpu" dtype = torch.float64 # model parameters node = "neuron_model_templates.spiking_neurons.lif.lif" N = 100 k = 2.0 tau = np.random.uniform(10.0, 15.0, size=(N,)) tau_s = 5.0 eta = 10.0 v_thr =...
148076b9a32e86aa76927cb050f4fd05ccddbecf2217fa1985d790dba4c66f53
Python
5,229
145
import torch.nn as nn import torchvision.models as models import torch from config import * import torch # Supported CNN models cnn_dict = { "resnet18": models.resnet18, "resnet34": models.resnet34, "resnet50": models.resnet50, "resnet101": models.resnet101, "resnet152": models.resnet152, } # Supp...
c0e4cc6182906fa78985f683234f9556f63ea1de69e20a6f7a60fa85006b9fae
Python
5,229
135
"""F29: the determinism contract, enforced as a test (agent memo 3.9). Same artifact bytes + torchlens version + normalized arguments -> byte-identical output, across fresh processes, PYTHONHASHSEED values, working directories, TZ, and locale. Golden files live in tests/agent_surface_goldens next to the COMMITTED arti...
1d145e1bb7ab2e3f29b36e6ad51c2b2f33a8920d31cff677dc7dfe7e2b431be2
Python
5,230
171
import fnmatch import os import stat import sys import zipfile from shutil import copyfile HERE = os.path.abspath(os.path.dirname(__file__)) CONDA_PREFIX = os.environ.get("CONDA_PREFIX", False) if sys.platform.startswith("darwin"): PLATFORM = "darwin" elif sys.platform.startswith("win32"): PLATFORM = "win32" ...
f3dbe0cfbd92519cb8d7029a2fb32b20b76cf2482bead1cef67e1d03d381ec95
Python
5,231
147
# MNIST model specification import torch import torch.distributions as dist import torch.nn as nn import torch.nn.functional as F from numpy import prod, sqrt from torch.utils.data import DataLoader from torchvision import datasets, transforms from torchvision.utils import save_image, make_grid from src.utils import ...
f82687311cd57935038eb461c9f654cd8352ca461e0fc1384da6bfc4a2f41471
Python
5,231
153
"""Test Dataset for supervised learning.""" from __future__ import annotations import warnings from typing import TYPE_CHECKING, Any import numpy as np from neurogym.core import TrialEnv from neurogym.envs.registration import all_envs, make from neurogym.utils import spaces from neurogym.utils.data import Dataset f...
05c7ec4dd4ab49f61552399fb3b75475d96995c4358ae1b01cdd8ea1e4e66082
Python
5,233
147
import prob2020.python.utils as utils import prob2020.python.indel as indel import pandas as pd def count_frameshift_total(mut_df, bed_path, use_unmapped=False, to_zero_based=False): """Count frameshifts for each gene. Parameter...
e4e3afde806cdef383cb15a45683786c1aa1448dd4b833807459d565d7422db2
Python
5,234
193
import inspect import os import pathlib import pytest import re from typing import TYPE_CHECKING import pysam import pysam.samtools import pysam.bcftools from TestUtils import BAM_DATADIR, CBCF_DATADIR, make_data_files try: import mypy.api except ImportError: pytest.skip('mypy API not available', allow_modul...
50aa62fb0681403ad912fbb5fae65c3ec563a2bff768b6d31c100ba1253374ed
Python
5,235
135
from __future__ import annotations import numpy as np from scipy.optimize import linear_sum_assignment from ..utils import get_overlap def init_stats(gt: dict, categories: dict) -> dict: """ Initializes statistics for each category based on ground truth annotations. Parameters: - gt (dict): Ground ...
f3bf3b35593f1754e07c734ad01def3e665f9294a1ab1f8092360a15afc49a8e
Python
5,235
168
""" abfinfo.exe was used to create a few text documents of header information. These tests compare header values from pyABF vs those in the text documents. """ import sys import pytest import glob import os import datetime try: # this ensures pyABF is imported from this specific path sys.path.insert(0, "src")...
43db9afe3790adecc0d4d27e7148a456e06010a7f3a371f5f677a0d01e97872c
Python
5,236
138
"""Profiler join against a REAL ``torch.profiler`` Chrome trace. Each op event is assigned to exactly one layer: the k-th ``aten::conv2d`` event to the k-th conv layer, so per-layer rows sum to the profiler's own event total with one event per row (the old name-substring join gave every conv layer every conv event and...
46d2f0e3f6548fabde15d96b9ff2c3ebf499fc3b3d5006777de96d03341bb1d0
Python
5,236
146
"""grind-r8 cluster 4.0.5: capture admission ordering (R54 + R57). The typed concurrent-capture refusal used to fire only AFTER the loser had already run process-global side effects: ``tl.trace`` orchestration reset and overwrote the admitted winner's capture runtime context (clearing its replay-template flag and inte...
f15a42b244186602f6dfe4d448c34f510a0098e2ba319601bcc296c98fc1eb6d
Python
5,236
152
"""grind-p3 T5.3/T5.4: a bundle that SAVES always LOADS (foreign container types). Two save-ok/load-fail traps in the portable scrub: * A USER tuple subclass (e.g. a namedtuple from the caller's module) in KEEP metadata was preserved by TYPE into ``metadata.pkl``. The default-deny safe unpickler then refused the ...
1b9ec29a20ee5c7fedbae4e13a62bc4f0e69ec06e194c191c0570aa6e09b2697
Python
5,237
154
import json import rclpy from rclpy.node import Node from rclpy.parameter import Parameter from std_msgs.msg import Bool, Int32, Float32MultiArray, MultiArrayDimension import numpy as np from saliency_code import Saliency class SaliencyROS2Node(Node): def __init__(self): ''' Initialize the Salienc...
96994f4f4750443a3ff4b1ac1549571e116bbe4086249025d7f145e52aefc325
Python
5,237
145
from __future__ import annotations import os import unittest import warnings from unittest import mock from coco_froc_analysis.froc import froc_point from coco_froc_analysis.froc import generate_froc_curve # remove tqdm logging while testing def notqdm(iterable, *args, **kwargs): return iterable class TestFr...
76b2b61b817faeca737e173257df367d599453666f1fe78a434aeb6e29c94e22
Python
5,238
90
#==============================================================================# # Author: Dominik Müller # # Copyright: 2024 IT-Infrastructure for Translational Medical Research, # # University of Augsburg ...
d8552e56088f6fe7410967e78aa097517124bb7a9866bb267ac2fd11bc2593a7
Python
5,238
133
''' Code for downloading and processing KITTI data (Geiger et al. 2013, http://www.cvlibs.net/datasets/kitti/) ''' import os,sys import requests from bs4 import BeautifulSoup import urllib import numpy as np from imageio import imread import hickle as hkl import scipy import scipy.misc from PIL import Image # Where KI...
53f281de8f8df4e8c72a1b2253082277b175fe84fce05ad3bcfb4bd37f91b071
Python
5,240
186
"""An offline label visualizer for BDD100K file. Works for 2D / 3D bounding box, segmentation masks, etc. """ import argparse import concurrent.futures from typing import Dict import numpy as np from scalabel.common.parallel import NPROC from scalabel.common.typing import NDArrayF64 from scalabel.label.typing import...
6b781f9528c4e5bc2129574ba43a9b7d75501e81bd893a26e88aaef025a5a61f
Python
5,241
97
from pyabf.abf2.section import Section class DACSection(Section): """ Information about the DAC (what gets clamped). There is 1 item per DAC. """ def __init__(self, fb): Section.__init__(self, fb, 108) self.nDACNum = [None]*self._entryCount self.nTelegraphDACScaleFactorEn...
ae9af0facbc8104b4decacab57eee540fabdc8f14fd40b92d16f720277f8584a
Python
5,241
131
import os from abc import abstractmethod from typing import Any, Callable, List, Optional, Union import torch from pytorch_lightning import LightningDataModule from torch.utils.data import DataLoader, Dataset, random_split class VisionDataModule(LightningDataModule): EXTRA_ARGS: dict = {} name: str = "" ...
a5313b1d24723f770cedd2038ef94096dc51e35d434b6db7319b5725fd4e98d4
Python
5,242
157
import os import gc from tqdm import tqdm from joblib import Parallel, delayed from irnlm.utils import save_pickle, write, check_folder from irnlm.data.text_tokenizer import tokenize from irnlm.data.utils import get_possible_morphs, get_possible_pos def extract_syntax(doc, morphs, pos): """Extract number of clos...
03b5983084126920ab66c6b08afe1e2c02bb824d726c204f575af7a4e0c3cdbf
Python
5,243
44
etas = { 'generic20_learning': { 'alpha_ATLAS_LUMI_2012': { 'muT__hat': 1.45680382599, 'muT__muT__down': 0.0403344500821, 'muT__muT__up': 0.0295059948201, 'muT__muW__down': -0.00170117606185, 'muT__muW__up': 0.00615134457977, 'muT__phi__down': -0.00520694457924, 'muT__phi__up': -0.00486484949081, 'muW__hat': 1.85214...
2037ba1c67092885652765eca689814acc30e5aaa751209cb8e3f61d38cad8ce
Python
5,244
156
# --- 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 Project(_BaseTraceHierarchyType): _parent_path_str = "surface.contours.y" ...
565c6ac6bc4e35199833352b9d6c29b995040a4baf2252a680ac269a21d679a1
Python
5,244
137
import tensorflow as tf import tensorflow.keras.backend as K from tensorflow.keras.losses import binary_crossentropy beta = 0.25 alpha = 0.25 gamma = 2 epsilon = 1e-5 smooth = 1 class Semantic_loss_functions(object): def __init__(self): print ("semantic loss functions initialized") def dice_coef(sel...
8c38bb4b4e3621c1462c75f6fc25bf4beeaefa1abf520cdada6055b3cfe664c0
Python
5,244
156
# --- 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 Project(_BaseTraceHierarchyType): _parent_path_str = "surface.contours.x" ...
ec4052d26bf477135c8a07b05291703309318b7029e0808a6c49769656c161e7
Python
5,244
156
# --- 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 Project(_BaseTraceHierarchyType): _parent_path_str = "surface.contours.z" ...
ac2ec03df331628faaa3a1be7fa00e8edfa1921b916bb27a2e729e5de595dcde
Python
5,245
147
"""Intervention honesty: a depth-2 store key cannot reach the three depth-1 splice sites without refusing (edits memo row 0d). The v1 splice sites substitute at ``arg_path[0]`` directly; a nested key reaching one of them would silently replace the WHOLE top-level argument at the wrong address -- well-formed, audited, ...
adf4edcb0464b7d00e138a18f05f9b924c11b37caee70125879e7dcac8f44b57
Python
5,245
154
""" Activation Factory Hacked together by / Copyright 2020 Ross Wightman """ from typing import Union, Callable, Type from .activations import * from .activations_jit import * from .activations_me import * from .config import is_exportable, is_scriptable, is_no_jit # PyTorch has an optimized, native 'silu' (aka 'swis...
bf99bbb2e9ca8aa872e2cf2fad01e052e55e0c63072b406c75506a33cc277a3f
Python
5,245
131
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import numpy as np import slowfast.datasets.utils as data_utils import slowfast.utils.logging as logging import slowfast.visualization.tensorboard_vis as tb import torch from slowfast.utils.misc import get_class_names from s...
f1462bcd9a86657583793881bd9adb57909a729a5f88ca1186c917573767eea4
Python
5,246
153
"""Wrappers encapsulating envs to modulate n_steps, rewards, and control state initialization.""" import abc from typing import List, OrderedDict, Tuple, Dict, Any, SupportsFloat import gymnasium as gym import numpy try: from mpi4py import MPI except ImportError: MPI = None from angorapy.common.senses import...
c6be45d28f4159ed8b0059a793b55e689dc5d955080cf202d5d7137f393a3783
Python
5,247
153
import numpy as np from numpy.testing import assert_array_almost_equal import pytest from pyriemann.geometry.mean import gmean from pyriemann.spatialfilters import Whitening pytestmark = pytest.mark.numpy_only n_components = 3 expl_var = 0.9 max_cond = 10 dim_red = [ None, {"n_components": n_components}, ...
d0be5223ac5696549ccc33e5a05f915c14c45616c27a9e49d4a01f7e4bc01469
Python
5,247
180
import gzip import os import pysam from TestUtils import TABIX_DATADIR FN_COMPRESSED = "example.bed.gz" FN_UNCOMPRESSED = "example.bed" FN_LARGE_COMPRESSED = "example_large.bed.gz" FN_LARGE_UNCOMPRESSED = "example_large.bed" def read_python_compressed(fn): '''iterate through with python.''' with gzip.open(f...
e1992d87630cdd9076aa2dd0dec657a836d13623bb1266cb4db23eddea461991
Python
5,248
137
import SimpleITK as sitk import numpy as np from skimage.transform import resize import nibabel as nib def read_file(filename): img = nib.load(filename) data = img.get_data() aff = img.affine return data, aff def save_img(image, affine, filename): nifti_img = nib.Nifti1Image(image, affine) n...
1f69781711787164f500789635d7b4736d3b602e2507eda9bdfa80634242a480
Python
5,249
122
# from this import d import imp import os import math from re import L import torch from torch import nn import torchvision from torch.nn.functional import relu from torch.nn import MaxPool2d from electric_unit import ChannelRepeat, ComplexConv2d, ConvBlock, ChannelShuffle import torch.nn.functional as F import torchsu...
c7bf52b453c69c834e480fc58f3663ac9f96276eb18de21d75e8c1e62a8f6c48
Python
5,249
171
"""The bidirectional deprecation-door gate (oracles D6/D21, build item 5). Contract: a DeprecationWarning fires at CALL TIME if and only if the registry says the door is deprecated; a registered door's warning must NAME the registered replacement, and the replacement must RESOLVE. Both failure directions go red: - a ...
e6db23720c141e9ac7a4e4c07a17d3427865dd42ba976756033ae017fba8a9fd
Python
5,249
135
"""Generate OSMnx reference fixtures for the pyrosm <-> OSMnx parity tests. Downloads OSM data from the Overpass API at the same historical moment as the ``helsinki_region_pbf`` test extract (an Overpass "attic" query via the ``[date:...]`` setting) using OSMnx, and saves each layer to disk as a GeoParquet file. The p...
7d879f71d4f7059aea5112be510a53da15b4f4fc0561cb2e6448dc48dbd9d1a1
Python
5,250
185
import os import sys import pytest from larvaworld.lib import reg from larvaworld.lib.sim import ExpRun from larvaworld.lib.process import LarvaDataset from larvaworld.lib.reg.generators import ExpConf RUN_WINDOWS_HEAVY = os.environ.get("LW_ENABLE_WINDOWS_HEAVY") == "1" pytestmark = [ pytest.mark.integration, ...
246fdf320b0de353f0bd0c67beade07411572581e69bc51f2e9903ae04671f7a
Python
5,252
156
import random from pathlib import Path from typing import Tuple import numpy as np import torch import torchvision.transforms as transforms from PIL import ImageFilter from pytorch_lightning import LightningDataModule from torch.utils.data import DataLoader, Dataset from logo_data_set import LoGoDataset class LoGo...