sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
2d2d64839b3dc9b51e782e45f864d8d2bcdb9a4ebd13d37d34e5439854a30a7d
Python
2,084
54
from __future__ import print_function, unicode_literals, absolute_import, division import numpy as np from scipy.ndimage import zoom from .care_standard import CARE from ..data import PercentileNormalizer, PadAndCropResizer from ..utils import _raise, axes_dict class UpsamplingCARE(CARE): """CARE network for co...
7da90b06fefcf70746ccc9748d5247cc03f3497218067cb42384e2eb04012029
Python
2,084
67
import torch EPS = 1e-12 def robust_zscore_tensor(x): x -= torch.median(x, dim=0, keepdim=True)[0] x /= torch.median(torch.abs(x), dim=0, keepdim=True)[0] * 1.4826 + EPS x.clamp_(-3, 3) x -= torch.mean(x, dim=0, keepdim=True) x /= torch.std(x, unbiased=False, dim=0, keepdim=True) + EPS return ...
8a5e14424964060cc75f6eb1e075f710aa1091bb5021b21555039710abe9e4e0
Python
2,084
71
"""Benchmarking the cfaidx module. Usage:: pytest benchmark/faidx_bench.py """ import os import pysam from TestUtils import BAM_DATADIR def iterate_over_fastx(fn, persist=True): return len(list(pysam.FastxFile(fn, persist=persist))) def iterate_over_fastx_as_file(fn): with open(fn) as inf: return...
d38cd44728ea8c321e2e9eae8bf23f1dd0b6e7d5b0e9454064b9808948d1def4
Python
2,084
49
"""Code related to handling annotations.""" import sys import types import typing from inspect import isclass def is_none_type(value: typing.Any) -> bool: """Check if the given value is a NoneType.""" if sys.version_info < (3, 10): # raise Exception('below 3.10', value, type(None)) return val...
d5fc152357f46c00c2ea5d245ab5f01609eae66b58ad8d053b4339f4278c96d9
Python
2,084
61
"""grind-p3 T11.10: validation-copy attr restoration refuses misaligned trees. ``_restore_simple_plain_attrs_on_copy`` zipped ``source.modules()`` against ``copied.modules()`` positionally with no arity check, so a deepcopy that adds or drops a submodule (a ``__deepcopy__`` hook, lazy child materialization) silently s...
f5ad3b253b960787b8ee78088745ccfdd8aee391e867b3382378122114fd428b
Python
2,084
63
import sys from robustness import datasets from robustness.attacker import AttackerModel from robustness.model_utils import make_and_restore_model from model_analysis_folders.all_model_info import IMAGENET_PATH, MODEL_BASE_PATH import os def build_net(ds_kwargs={}, return_metamer_layers=False): # We need to build...
a1153f56158996866c23ecea01a2c0f3d5e055de6d432f798d2312002a4b67f0
Python
2,085
64
"""drop view Revision ID: 3356bc2ecfc4 Revises: 460d0ecd1dd8 Create Date: 2023-04-10 15:06:01.037416 """ from alembic import op # revision identifiers, used by Alembic. revision = "3356bc2ecfc4" down_revision = "460d0ecd1dd8" branch_labels = None depends_on = None view_name = "collection_job_state_summary_view" a...
deeb254ea83604a1f3a398a74282c65993a8e1772f6c670da4ad47a4964dc99b
Python
2,085
83
<<<<<<< HEAD """ Linear model from github.com/clinicalml/omop-learn """ import numpy as np import scipy.sparse from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline from sklearn.preprocessing import FunctionTransformer ======= from sklearn.linear_model import LogisticRegression from...
6f8a846beb3af8cb49a734b46cdcf4dea9c1472dcb9bddc97dea6c438e147632
Python
2,086
61
"""R10-15: sparse-runnable ``tensor_slots`` slot_id uniqueness was enforced nowhere, while every sibling namespace (call ids, witness families, registry ids, boundary positions) dup-checks. A duplicated slot_id parsed clean, then last-wins slot indexes disagreed with list-iterating consumers and the binder dropped one ...
a84dd6df8a4f327234e50d58b1eb9fa86d4c25e9dec0f9e5058193da3c32acfb
Python
2,086
64
import sys from robustness import datasets from robustness.attacker import AttackerModel from robustness.model_utils import make_and_restore_model from model_analysis_folders.all_model_info import IMAGENET_PATH, MODEL_BASE_PATH import os def build_net(ds_kwargs={}, return_metamer_layers=False): # We need to build...
e76921a865faf2ff4665d58658dc111e87860b3b4d2fbde75f88f2e555a45395
Python
2,086
53
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Written by Bin Xiao (leoxiaobin@gmail.com) # ------------------------------------------------------------------------------ from .build import make_dataloader from .build impor...
f68866a2a0a5a0570e8b35a80a5d6baebde6b102794d38889ba30b2a56c0f1c8
Python
2,086
57
# -*- coding: utf-8 -*- """ Created on Tue Feb 28 16:28:17 2023 @author: cbri3325 """ import SimpleITK as sitk import pandas as pd import os from ImageAnalysisFunctions import getMaxRoi,getMeanRoi data_supradir = 'Path to data directory' subjs_path = [ f.path for f in os.scandir(data_supradir) if f.is...
0dfaae463801c593f1cfb85e6c87dfae775993bb353781b6c05676639363262e
Python
2,087
59
from __future__ import annotations from collections.abc import Generator from functools import reduce from typing import Any, Optional def find_path(path: str, dictionary: dict) -> Optional[Any]: """Lookup a path e.g. 'a.b' in dict: {'a': {'b': 2}} will return 2. If the path doesn't exist, None is returned ...
21f5c2f17d7f1a701abcf4193d02380be20eb55edc5957042d2afd4538239442
Python
2,087
64
import sys from robustness import datasets from robustness.attacker import AttackerModel from robustness.model_utils import make_and_restore_model from model_analysis_folders.all_model_info import IMAGENET_PATH, MODEL_BASE_PATH import os def build_net(ds_kwargs={}, return_metamer_layers=False): # We need to build...
147d40391c89579d044bf1fc48ad01db4ad35ec5ec516fe1fab8ee0102e85ec8
Python
2,088
77
import os import sys import math import pickle from typing import Dict, List from dataclasses import dataclass, field import numpy as np import pyprojroot code_root_dir = str(pyprojroot.here()) pack_dir = f"{code_root_dir}/package/python" sys.path.insert(0, pack_dir) from leiden import LeidenSum, ScatterPlot from leid...
6505413c925b33cc6d723f07937e9f804507c30c37a7401a14f4443774fbaf40
Python
2,088
70
# 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...
c7155883101aa3accbee78fbf1e71cd29a6e2ba2265b5ec1cae26302e6df6ad2
Python
2,088
64
import sys from robustness import datasets from robustness.attacker import AttackerModel from robustness.model_utils import make_and_restore_model from model_analysis_folders.all_model_info import IMAGENET_PATH, MODEL_BASE_PATH import os def build_net(ds_kwargs={}, return_metamer_layers=False): # We need to build...
f51eb9f4249c9d895560af2ab936aa8435acd5fe21c123d062b5d7d4b7efee12
Python
2,088
64
""" core.cohort_pool — Cohort-pool composition helpers. The paper uses a 6-cohort pool (ds004504, BrainLat, ds003775, LEMON, figshare 5450293, ds006036) split into three roles: - Selection cohorts: ds004504, BrainLat, ds003775 — used for in-pool LOCO and pipeline development. - Held-out: figshare 5450293 — ne...
084eb75c1f90871a50542ed7768c6b0ef77667e57f54a77d84f007d0b997b83b
Python
2,089
69
# 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.loss import NTXentLoss from lightly.models.modules import SimCLRProjectionHead from lightly.transforms.simclr_transform import SimC...
3557180eff32c4c005320cff99e0144cd1d90d9e3dc669f86109d39b7654622b
Python
2,089
55
"""Liveness killers for the streamed-bundle finalization step (executor step 18). r7 R74 executor-family survivor, found by the family's own first sample campaign: forcing ``_should_run_step_18`` to ``False`` (the streamed bundle never finalizes) survived the ENTIRE 472-test arming suite -- no suite file captured with...
3ea4ad1acb6b5ba8aa91e5338a2439ec5760d9c2fe559cb350c8e1cf37e7b1f5
Python
2,089
60
#!/usr/bin/env python import argparse import os from Bio import SeqIO parser = argparse.ArgumentParser() parser.add_argument("--records", type=int, default=None) parser.add_argument("--limit", type=int, default=None) parser.add_argument("--num-chunks", type=int, default=0) parser.add_argument("input_file") args = pa...
90c18d7f4cc439332eaf38cfc4b7e4e5254ba0306b27797b566ef14162890113
Python
2,089
82
from pathlib import Path import typer def main( store: Path, batch_size: int = 128, max_batches: int = 100, load: bool = False, ): import gc import logging import sys from time import perf_counter import numpy as np import seqdata as sd import seqpro as sp import torc...
c0bfa5eaf0cf9e3f6fe298bc6581138b8f8896735caee0f19a69fb653647742b
Python
2,089
53
"""Regression tests for two capture-robustness fixes surfaced by real models. 1. Integer/bool-dtype ``nn.Parameter`` (e.g. a fixed lookup buffer declared as ``nn.Parameter(torch.arange(n), requires_grad=False)``) is legal PyTorch and never gradient-capable. Capture prep used to force ``requires_grad = True`` on ...
5f0f7fd4ca12dacf12f2988133f4472dec3b2c7b2b78fc83b7f4688e6cb8278d
Python
2,090
64
from bioseq2seq.bin.transforms import CodonTable import math from Bio.SeqUtils.CodonUsage import CodonAdaptationIndex from CAI import CAI as external_CAI class CAI: def __init__(self): self.table = CodonTable() self.rscu = None def parse_entry(self,entry): if any([c == ' ' for c ...
e3204e33bfd5028a967774c9cc8c63812e2e360391632bd78335ed82cc0452e8
Python
2,090
58
import pytest import gym from gym.wrappers import RecordEpisodeStatistics, VectorListInfo ENV_ID = "CartPole-v1" NUM_ENVS = 3 ENV_STEPS = 50 SEED = 42 def test_usage_in_vector_env(): env = gym.make(ENV_ID, disable_env_checker=True) vector_env = gym.vector.make(ENV_ID, num_envs=NUM_ENVS, disable_env_checker=...
ed73fdf29d0ee92df208410f1cba86036a917c27c798b6b2e961c206a3fede82
Python
2,090
57
__author__ = 'cenwan' # The Python implementation of Classifier Two-Sample Tests (CTST) for selecting the optimal synthetic protein feature samples. import numpy as np from sklearn.model_selection import LeaveOneOut from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score GOTermI...
058d0872608191b1a58243675c367132cd3e09a9ae2d19e6e7e41fdca8c01401
Python
2,093
52
""" Apply bandpass filters to the data. """ import sys sys.path.append('..') import argparse import mne from config import fname, n_jobs # Be verbose mne.set_log_level('INFO') # Handle command line arguments parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('subject', type=int, metavar='sub###...
061d67ed6dd67b637cbb544858fc84e5040613b7ac9cda1438b2d108bf19c9ee
Python
2,093
50
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for d-iteration""" import unittest import numpy as np from sknetwork.data import house, karate_club from sknetwork.data.parse import from_edge_list from sknetwork.data.test_graphs import * from sknetwork.linalg.operators import Regularizer from sknetwork.linalg....
2673595af29442ea80c0787ae0b083df3a6bcd62154045c2853a365061f356aa
Python
2,093
69
from __future__ import absolute_import import logging from .req_install import InstallRequirement from .req_set import RequirementSet from .req_file import parse_requirements from pip._internal.utils.logging import indent_log __all__ = [ "RequirementSet", "InstallRequirement", "parse_requirements", "install...
1a85c90edb8065458e3c62693d8e09cebdc0d088211626431c2ce2738fede511
Python
2,094
59
""" Integration tests for registry bootstrap and configuration behaviour. These tests rely on the ensure_datasets_ready fixture (auto-applied for the integration suite) so that the Schleyer processed datasets exist before the registry is exercised. """ from __future__ import annotations from pathlib import Path imp...
8e81eabe72b00b5a5fe83c189e3273e35530c5e936c290f132941d6a40dad929
Python
2,095
57
import os import warnings import h5py import numpy as np import scanpy as sc from scbig import run_scbig, preprocess, read_data, setup_seed warnings.filterwarnings('ignore') for dataset in ['10X_PBMC','mouse_bladder_cell','mouse_ES_cell','human_kidney_counts','Adam','Human_pancreatic_islets','Macosko_mouse_retina']...
38c2f9f03adce57f95063ec477bfbb184cdbeec1794437893d73f96e7a76c5f1
Python
2,096
61
import os import numpy as np import sys sys.path.append('..') from pyAudioAnalysis import audioBasicIO as aIO from pyAudioAnalysis import MidTermFeatures as aF from pyAudioAnalysis import ShortTermFeatures as sF def feature_extractor(dirs: str, num_of_classes: int, mid_win...
78a9d14c07d30129a8408ec09ead14d20b805ad6f0c16e4ffe64d7ad7b119733
Python
2,096
63
"""Phase 5(b): _tag_untagged_buffers ordering relative to stack push.""" from __future__ import annotations import torch import torchlens as tl class BufferConsumer(torch.nn.Module): """Child module that consumes a dynamically registered parent buffer.""" def forward(self, x: torch.Tensor, scale: torch.Te...
3749bf04e67b3b2acc289da93d0e0f26706c35e257a7c16b933a18fa0b0a7486
Python
2,097
68
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
47435dbcf4509f7d8976f2b86277c269ab03c51072bb46c4ef7ad24dc763fc38
Python
2,097
77
# --- 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 Marker(_BaseTraceHierarchyType): _parent_path_str = "histogram2d" _path_s...
a146b167e212ca6108e52fb8784d45f4262c7b33e1bca1707afbe43ac0512308
Python
2,097
76
import os import numpy as np import pandas as pd def load_annotations(path): D_dicts = {} for root, dirs, files, in os.walk(path): for file in files: #print(file) if file.endswith(".txt"): open_f = open(path + '/' + file, 'r') list_of_lists = [] for line in open...
88abaca9ac5e076567edd3b49be44904fd037c80abe2a451a0fb405933d440da
Python
2,099
70
#!/usr/bin/env python3 import os import dendropy import numpy as np import tskit def encode(nwk_str, no_taxa, der_ls=None): dpy_tr = dendropy.Tree.get(data=nwk_str, schema="newick", rooting="default-rooted") dpy_tr.calc_node_ages(ultrametricity_precision=1e-01) # assuming branch length in generations ...
b81776bb3dcc562e86bcae634c3a4735f77589dca5cbb6af74565ccd0a9df900
Python
2,099
67
from ovseg.augmentation.myRandAugment import torch_myRandAugment from ovseg.augmentation.MaskAugmentation import MaskAugmentation from ovseg.augmentation.GridAugmentation import torch_inplane_grid_augmentations from ovseg.augmentation.GrayValueAugmentation import torch_gray_value_augmentation import torch.nn as nn # ...
cbd6cfda54b404bbfa0ca96c7a20f7abf7c40c409cb2382129e55466749ab46c
Python
2,099
81
#!/bin/python3 import torch import numpy as np import matplotlib.pyplot as plt from torch.utils.data import DataLoader from torch import nn from torch import optim from NNucleate.dataset import GNNDataset from NNucleate.models import initialise_weights, GNNCV from NNucleate.training import train_gnn_unified, evaluate...
5287f0694af44c5a6d004f0b80935c0dc87d4ebdf6d5eb509826b5e70bf7e6b0
Python
2,102
68
from __future__ import absolute_import from setuptools import setup, find_packages from os import path _dir = path.abspath(path.dirname(__file__)) with open(path.join(_dir,'csbdeep','version.py')) as f: exec(f.read()) with open(path.join(_dir,'README.md')) as f: long_description = f.read() setup(name='csbd...
7f9648bee3f618e5115603d111b95a8dfe826c076a88fb9a943fdaac30182786
Python
2,102
81
"""Generate the image lists for data loaders.""" import os import sys from os import path as osp from ..common.logger import logger def gen_list( data_root: str, data_dir: str, list_dir: str, phase: str, list_type: str, suffix: str = ".jpg", ) -> None: """Generate the list.""" phase_...
abd2a1017139b60c9a353caac36e0362d0ce600d7b967c72a0d11bc728ffcb21
Python
2,102
62
# import pandas as pd # import numpy as np # import osmnx as ox # from ..utils import constants, gislib # # distance = gislib.getDistance # # # def route(tdf, G=None, index_origin=0, index_destin=-1): # """Routing. # # Create a route on Google Maps between two locations. # # Parameters # ---------- # ...
2b8c08a7ee126782f56c322b3c2d04063d2f0955aa9ec45a30dac223413ec296
Python
2,103
59
from typing import Union, Optional, Tuple, Collection, Sequence, Iterable from anndata import AnnData import numpy as np from scipy.sparse import issparse, isspmatrix_csr, csr_matrix, spmatrix import scanpy def filter_genes( adata: AnnData, min_counts: Optional[int] = None, min_cells: Optional[int] = None...
beebbe4e3493650879e107b3ba50c5ac6058c3933049e23822133001ff0714ac
Python
2,103
62
""" Author: Derek van Tilborg -- TU/e -- 24-05-2022 Basic 1-D Convolutional Neural Network based on the architecture of [1] [1] Kimber et al. (2021). Maxsmi: Maximizing molecular property prediction performance with confidence estimation using SMILES augmentation and deep learning """ import torch import torch....
f15546d83c4b1090e68a8ed3ac715d8059a21605efbaf91878f327018be5318f
Python
2,103
62
"""Add pg_notify to history audit triggers Revision ID: b8d5e2f9a1c7 Revises: f5e9e4bca542 Create Date: 2026-04-17 14:30:00.000000 The SSE-based history update pipeline (see `managers/history_audit_monitor.py`) depends on a PostgreSQL LISTEN on the `galaxy_history_update` channel. For existing installations, trigger ...
0ae9656ab286c02915159f6378eb6317e8d538aa6802d97ca37beb123b1b3e86
Python
2,104
69
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["num_motifs"] = 82 msp.architecture["motif_model_spec"]["motif_width"] = 13 msp.architecture["motif_model_spec"]["motif_feature_extractor_spec"] = dict( type="ResidualStack", depth=3, ) msp.arch...
9323dede5c6d7890aae49e24802b2216dde25b35f437aa1274790478d7eee1c9
Python
2,104
66
import os import threading import time import logging from src import sba_api from src.utils import * import src.api_server from src.api_server import run_server from src import config # Setup logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger...
5b3252a1e6ac16db6403d2e438e72d50c72afc582ebed00f09f0f7e725813a27
Python
2,105
62
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """Multiprocessing helpers.""" import torch def run( local_rank, num_proc, func, init_method, shard_id, num_shards, backend, cfg, output_queue=None, ): """ Runs a function from ...
c5d944266817d769710ecc2caf7a1c1a9c0ed4eb15f77541c2c70e7d3ac35a35
Python
2,105
66
import sys from robustness import datasets from robustness.attacker import AttackerModel from robustness.model_utils import make_and_restore_model from model_analysis_folders.all_model_info import IMAGENET_PATH, MODEL_BASE_PATH def build_net(ds_kwargs={}, return_metamer_layers=False): # We need to build the datase...
e5a997d0a63d72e3460b72a04f271ab2441a3771327ede719280a29cef3e6575
Python
2,105
60
from matplotlib import gridspec import matplotlib.pyplot as plt from pycobi import ODESystem # preparations ############## # plot settings plt.rc('text', usetex=True) plt.rcParams['figure.constrained_layout.use'] = True plt.rcParams['figure.dpi'] = 400 plt.rcParams['figure.figsize'] = (12, 5) plt.rcParams['font.size'...
24ef1e42f5cf0bcaa140dc6de72e200fb688bb77eee5c02b04f3694f69af2657
Python
2,106
71
#!/usr/bin/env python #========================================================================= # # Copyright NumFOCUS # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://...
3e5c11022aa2e5732e745760eb8961c85a34bd1e8478740d928c4d43d465bba8
Python
2,107
49
import unittest import numpy as np from Metrics.src.image_quality_estimation import IQS class TestIQS(unittest.TestCase): def setUp(self): # Create a reference image for testing self.ref_image = np.ones((10, 10)) # Create an instance of the IQS class self.iqs = IQS(pixel_max=255, ...
b1357f774441f4ceb3b1722f2d9ed553ab5e51f5f720ad484f29c3a71312dbdf
Python
2,107
61
"""Heartbeat service. This is the internal thread responsible for sending heartbeat events at regular intervals (may not be an actual thread). """ from celery.signals import heartbeat_sent from celery.utils.sysinfo import load_average from .state import SOFTWARE_INFO, active_requests, all_total_count __all__ = ('Hea...
b41c72d1a8366fcdd726aac2cb090f4eec539275f5eb9e5ba1e85cf2fa4f6126
Python
2,107
75
'''========================================================================= ' ' 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/licen...
b3e9422e4d9b151d8614307cfa1a9af2f52187fa492dd6e66ff6449e32c117b6
Python
2,108
63
"""The ``celery migrate`` command, used to filter and move messages.""" import click from kombu import Connection from celery.bin.base import CeleryCommand, CeleryOption, handle_preload_options from celery.contrib.migrate import migrate_tasks @click.command(cls=CeleryCommand) @click.argument('source') @click.argumen...
cec395c3164f9b134198239abff44bb06e66234c20c0f26212ccb3bb1b879332
Python
2,108
56
from ptic import pmi_tfidf_classifier as ptah import numpy as np import pandas as pd from sklearn import metrics import torch from ptic import neuro_ptic np.random.seed(42) path = "doc/datasets/" # Data is taken from here # https://www.kaggle.com/lakshmi25npathi/imdb-dataset-of-50k-movie-reviews data_raw = pd.read_cs...
e835bb04ce957a81bb27f17e13370613c95aff67cc40c8ecd1735937762870ec
Python
2,108
67
#!/usr/bin/env python import sys, csv, gzip import json import numpy as np class MatFlipper(object): infile = "" genesfile = "" outfile = "" botstrand = [] _coords = [] _matrix = [] def parseArgs(self, args): self.genesfile = args[0] self.infile = args[1] self....
f55a24416fdcc34b97b6ae42077c0c6df4ff0f485939ac1e283fa274be8e1960
Python
2,108
73
"""Plot History from Training""" import os class TrainingHistory(object): r"""Training History Record and Plot Parameters ---------- labels : list of str List of names of the labels in the history. """ def __init__(self, labels): self.l = len(labels) self.history = {} ...
0a1a817b577e457cd0efdb5ed34186f0ff4d6c0564541260fbac7ff087d31149
Python
2,109
60
import pathlib import os import logging import time import numpy as np def setup_savedir(exp_name, code_backup=True): save_dir = '../experiment/%s' % exp_name pathlib.Path(save_dir).mkdir(parents=True, exist_ok=True) if code_backup: pathlib.Path(f'{save_dir}/code').mkdir...
ad3d078b07d25a56a14b8d89a8eb5ce071ffd9cb2bd692a8e40800acbd9573cf
Python
2,109
63
# Demonstrates interoperability of the nfp preprocessing methods with the spektral GNN # library (https://graphneural.network/). Specifically follows the `DisjointLoader` # example for QM9 prediction shown here, https://github.com/danielegrattarola/spektral/ # blob/master/examples/graph_prediction/qm9_ecc.py import pa...
e85ec558323bacd8774279c8553872b48866af74f5ffb9c16e96068e2ce14d42
Python
2,109
62
"""2. Test with PSPNet Pre-trained Models ====================================== This is a quick demo of using GluonCV PSPNet model on ADE20K dataset. Please follow the `installation guide <../../index.html#installation>`__ to install MXNet and GluonCV if not yet. """ import mxnet as mx from mxnet import image from mx...
487187ab5e28010c82a02a038c15e95178c4770b5222dc38dc761c75112b6095
Python
2,110
48
import numpy as np import pandas as pd # 因为原始数据association只包含有关联的circRNA-disease对,所以要加上随机抽一些数据作为没关联的circRNA-disease对,这里已经在excel处理过 trainset = pd.read_csv('data/trainset.csv', header=0, encoding='gb18030').values meshdisname = pd.read_csv('data/Mesh_disease.csv', header=0, encoding='gb18030') targetdisease = pd.read...
6892f402337b587f03da5be09764ce3f5cdfda67f7ce28e0b9c6a7ae709b60fd
Python
2,110
75
from functools import lru_cache import os import pickle import tqdm.auto as tqdm import numpy as np def read_fasta_strings(fasta_path): with open(fasta_path) as f: lines = [] for line in f: assert line[-1] == "\n" lines.append(line[:-1]) lines.append(">") resu...
9c2046b6fe54fd092266a935538feaf0aaab3552b50d58d02d7318c544894f6b
Python
2,111
63
import pandas as pd from .gtex_data_table import gene_expr_data, transcript_data def produce_splice_table(limit=None): """ Produces the hg38 splice table, filtered for genes with transcripts. Has paralog information added to the table. Parameters ---------- limit : int, optional If n...
9ce1e220b64b05615d483b7df6e1b1d56812a839b1d574baa8f795a2e17bb8a5
Python
2,111
52
from typing import List, Optional from carbonserver.api.errors import NotAllowedError, NotAllowedErrorEnum, UserException from carbonserver.api.infra.repositories.repository_experiments import ( SqlAlchemyRepository as ExperimentSqlRepository, ) from carbonserver.api.schemas import Experiment, ExperimentCreate, Us...
b889e19792509e9a37529c92b7b4e352c07390a6f14aad14bcd17accf09308cb
Python
2,111
66
# 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...
57d24f0f0275e946cf8394655c574503ae9f232ff638d5d4251877c6391dfb31
Python
2,112
72
import itertools import os from pathlib import Path import nibabel as nib import numpy as np def load_nii(file: Path) -> np.ndarray: """ Loads the data from a NIfTI file. Parameters: file (Path): The path to the NIfTI file. Returns: np.ndarray: The data from the NIfTI file. """ ...
9a0ed27bd245b29ad42e6416b316ecbd7292b87809b95636e16509e48b702725
Python
2,112
67
import json import re import numpy as np from matplotlib import pyplot as plt import matplotlib font = {'family' : 'Times', 'weight' : 'normal', 'size' : 12} partial_results = [] for filename in ["./storage/predictability_repeated_august19d.json", "./storage/predictability_repeated_august19e.json"]:...
62de00064d069c2280b4156df7baf3bd5a42cf07d734637e889671b78f629c00
Python
2,113
81
""" Tests to make sure the dataload module isn't busted """ import os import numpy as np import eugene as eu from pathlib import Path from eugene.dataload import SeqData from pathlib import Path HERE = Path(__file__).parent dataset_dir = f"{HERE}/../eugene/datasets/janggu_resources" ref_file = "sample_genome.fa" roi...
4df0877c892cc1ae5509cfffe0d380cd62326a9ec94a25d84ea33ddb68e87ff8
Python
2,114
64
""" # > Script for measuring quantitative performances in terms of # - Structural Similarity Metric (SSIM) # - Peak Signal to Noise Ratio (PSNR) # > Maintainer: https://github.com/xahidbuffon """ ## python libs import numpy as np from PIL import Image from glob import glob from os.path import join from ntpath imp...
c347988f2d00498ac26393da2be7ec47815e0cb4e237f81b727885b19b72ad25
Python
2,114
56
###################################################### # This file prepares the NN269 data set for use in # # CMKN experiments. The script assumes that positive # # and negative sequences are provided in different # # files. # # # Author: Jonas Ditz ...
c57b3647de2dc4796b5b3e817e1c1adc1894980971094903546263a059e77f42
Python
2,114
47
import numpy as np import lifelines import lifelines.statistics from lifelines import KaplanMeierFitter, plotting import seaborn as sns import matplotlib.pyplot as plt from matplotlib.offsetbox import AnchoredText def plot_survival_function(surv_prob_median, surv_prob_lower=None, surv_prob_upper=None, label='', max_t...
f32dc9c175220a07db4a8c390c91a561c1461cef32579a04f3dcbb06f9799a12
Python
2,114
77
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["num_motifs"] = 82 msp.architecture["motif_model_spec"]["motif_width"] = 13 msp.architecture["motif_model_spec"]["motif_feature_extractor_spec"] = dict( type="ResidualStack", depth=3, ) msp.archi...
118cb4fd294a719b7460ec1299552a43de2a1dddabb28c6d5b21f7a51c33e6e4
Python
2,115
63
"""Provides functionality to identify corrupt images in a directory. This module helps users identify corrupt or unreadable image files within a specified directory. It uses parallel processing to efficiently scan through large collections of images. """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Righ...
2670c9046aace874cdb6e746b9085e90efe9ef38a51208ecd3c52bd6c3a238d9
Python
2,115
53
# 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...
708c117ff3fd57c0ff935aa92e3976761317ea848e1214541a89606668f34359
Python
2,117
58
import os import argparse import logging import autogluon.core as ag from gluoncv.auto.tasks import ObjectDetection from gluoncv.auto.estimators import FasterRCNNEstimator from d8.object_detection import Dataset os.environ['MXNET_ENABLE_GPU_P2P'] = '0' if __name__ == '__main__': # user defined arguments par...
968af95558bd1766dab322997905820c7b44c8f1df22a7b19f451d1116fb8d4b
Python
2,117
79
#!/usr/bin/env python import tempfile import xml.sax as sax import readfile class DictHandler(sax.handler.ContentHandler): """ Parse XML files with AID/CID/SID as key and mappings to several other IDs """ def __init__(self, key, value): self.ergebnis = {} self.schluessel = "" ...
3431156741f30f4c2fb37da649f0f3cd2d89afaee6a653de9b98ac71102f72e0
Python
2,118
42
#==============================================================================# # Author: Dominik Müller # # Copyright: 2024 IT-Infrastructure for Translational Medical Research, # # University of Augsburg ...
7c7c374cf6102fc26fa215e68ab4c4b72efa4b50c91aee7ff884a44298155b4f
Python
2,118
63
# generated by eelbrain/scripts/make_example_tests.py import importlib.util import logging import os from pathlib import Path import re import mne import pytest from eelbrain import configure from eelbrain.testing import hide_plots, working_directory DATASETS = { 'mne_sample': bool(mne.datasets.sample.data_path...
3bc091dad45466c25250c1a5a4e2b984f58dd231ab23f40275a315b25de6667b
Python
2,120
63
"""3. Test with DeepLabV3 Pre-trained Models ====================================== This is a quick demo of using GluonCV DeepLabV3 model on ADE20K dataset. Please follow the `installation guide <../../index.html#installation>`__ to install MXNet and GluonCV if not yet. """ import mxnet as mx from mxnet import image f...
416cd9dbda34fa3a4c88300bd4284d80b419314ef3a3e66f659c04bc5ca48b78
Python
2,121
58
import torch import torch.nn as nn from modular_splicing.motif_names import get_motif_names from modular_splicing.utils.io import load_model class NeuralFixedMotif(nn.Module): """ Uses a folder full of Neural fixed motifs as a fixed motif model. The folder should contain a file for each motif, named by ...
205a62be5b843896b25c0502d74d968b171a3870157a5ec844ac18ba1f6a7bb5
Python
2,123
66
from collections import defaultdict import json from modular_splicing.utils.construct import construct from .sources import ( read_rbns_motifs, read_rbns_v2p1_motifs, read_rbns_functional_motifs, read_rbns_v2p1_functional_motifs, rbns_rnacompete_motifs_deduplicated, rna_compete_motifs_for, ) ...
c1aebc6f587e4da355a4224d2f4e322e2e3bc86808ae5fd2cecb0bea65f1baf0
Python
2,123
68
from hydra import compose, initialize from torch.utils.data import DataLoader from torchvision.datasets.samplers import DistributedSampler from data.dataset_3d import Dataset3D, KFoldDataset3D def get_dataloader3d(cfg, finetune, *modes): res = list() for mode in modes: dataset = Dataset3D(cfg.dataset...
14f8c18611890659234f52b99bd7262ddd4e980094ef5bc589c3774ce9aadab3
Python
2,124
61
from __future__ import division import unittest import numpy as np from wyrm.types import Data from wyrm.processing import remove_epochs from wyrm.processing import swapaxes class TestRemoveEpochs(unittest.TestCase): def setUp(self): ones = np.ones((10, 5)) channels = ['ca1', 'ca2', 'cb1', 'cb...
7ccd3d7e2efc2cf269b920430dc9d3545b44ac148ccc6f19811aad69b6dbe493
Python
2,125
65
import argparse import glob import os from mp_dip.obci_readmanager.signal_processing.tags import tags_file_writer as tags_writer import mne from tqdm import tqdm import pandas as pd from mp_dip.utils.utils import TAG_DEFS tag_convert_dict = {'spindle': 'Spindle (wrzeciono)', 'segmentViewed': 'se...
ae00bc451e4f26352290147831e3dfb5f35fbafcac3d8f4b7e3812966ffba3eb
Python
2,125
45
""" Diffusion weighted MRI: calculate metrics for global cyst seg""" import pandas as pd from statsmodels.stats.multitest import multipletests from scripts.utils.io_utils import get_orig_imgs, get_masks from scripts.utils.constants import DWMRI_SEQUENCES, CSV_GLOBAL_CYST_ANNOT from scripts.utils.metrics import calcula...
f7b77d18e9a4c6586067ececae9d32ef4b8646e0404e60090ffc9e914a4f871f
Python
2,125
69
import numpy as np from gym import utils from gym.envs.mujoco import MuJocoPyEnv from gym.spaces import Box class InvertedDoublePendulumEnv(MuJocoPyEnv, utils.EzPickle): metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps"...
fdd3fd36effa5c2574f9611027b1399c6ea9c5958cb5b8fe2d112ed2fb717969
Python
2,125
76
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created in April 2020 @author: Nathan de Lara <nathan.delara@polytechnique.org> """ from typing import Union import numpy as np from scipy import sparse from scipy.sparse.linalg import LinearOperator from sknetwork.utils.check import check_format, check_square cla...
2784e7c5200495f75928e381841ddea41018c85b4c4421b428282b8dd0b2eb7e
Python
2,126
71
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["num_motifs"] = 82 msp.architecture["motif_model_spec"]["motif_width"] = 13 msp.architecture["motif_model_spec"]["motif_feature_extractor_spec"] = dict( type="ResidualStack", depth=3, ) msp.arch...
a97fb8af8d334fe0bb82f19027e3756a38fe032c63acd821dd2e2540eec57e63
Python
2,126
68
""" This module define a specific dataset """ import logging import torch from datasets_pre_processing.generic_dataset import GenericDataset class ClassificationPerAminoAcidDataset(GenericDataset): """ This class is a dataset where we have one label per protein/example """ def __init__( self,...
016f4c9f12e70606f4a86f6c3fcfea50b205587de8736e213b58af8ce971166f
Python
2,128
53
import torch from models.basic import DeepLearningRelayModel from strategies.basic import MultiSiteLearningStrategy class Relay(MultiSiteLearningStrategy): name = 'relay' model: DeepLearningRelayModel def __init__(self, model: DeepLearningRelayModel, config: dict, **kwargs): super().__init__(mod...
08bf3fd84c8d5a0a9b5907f0c2788a39ec6c7af4e380efc70a31fbc04d6148a6
Python
2,128
61
# Copyright 2023 DeepMind Technologies Limited # # 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 agree...
1f727271d3a679aa86d2da987b6a23eac303d5c0349058c0dd0e0b28de4ff361
Python
2,128
63
"""Tests for bdpy.task.core.""" from __future__ import annotations import unittest from bdpy.task import core as core_module class MockCallback(core_module.BaseCallback): """Mock callback for testing.""" def __init__(self): self._storage = [] def on_some_event(self, input_): sel...
932c893a8319fdd485993d006022d082e6c0ce3112b3abeadbb67429a62c9079
Python
2,129
78
#!/usr/bin/env python """ Standalone script to facilitate caching of required TemplateFlow templates. """ import argparse import os import templateflow.api as tf def fetch_MNI2009(): template = 'MNI152NLin2009cAsym' tf.get(template, resolution=1, desc=None, suffix='T1w') tf.get(template, resolution=1, d...
db731b4d12a9466493d16b6542c219d4d0706baf6815c2700f220c388b7e79cd
Python
2,130
81
import datetime import marisa import sys time_begin = datetime.datetime.now() keys = [] for line in sys.stdin: keys.append(line.rstrip()) time_end = datetime.datetime.now() print "input:", time_end - time_begin time_begin = datetime.datetime.now() dic = dict() for i in range(len(keys)): dic[keys[i]] = i time_end ...
477ac5b95219e075eb9fd409e708708988e217120bb4aa41a62100ddb3a1c8d5
Python
2,131
63
"""Convert BDD100K to Scalabel format.""" from typing import Dict, List, Optional from scalabel.label.typing import Frame, Label from scalabel.label.utils import get_leaf_categories from tqdm import tqdm from ..common.typing import BDD100KConfig IGNORED = "ignored" def deal_bdd100k_category( label: Label, bdd...
7d48e18f2c105d1669edc241e56bca9c7af7e2dfb03914f7efb59433337a60e0
Python
2,132
77
# --- 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 Marker(_BaseTraceHierarchyType): _parent_path_str = "histogram2dcontour" ...
b090c4c15247928e0a9d35098e7c381098038aec58666e462ac1ec55ddce6069
Python
2,132
68
#!/usr/bin/env python # ============================================================================= # MODULE DOCSTRING # ============================================================================= """ Normalizing flow concatenating multiple normalizing flows. """ # =============================================...
bb00c4d6ac2d389e6dfaed4f3eaf9245187f5f64dcda8a4160a3a00daa54180c
Python
2,132
64
""" # > Script for measuring quantitative performances in terms of # - Structural Similarity Metric (SSIM) # - Peak Signal to Noise Ratio (PSNR) # > Maintainer: https://github.com/xahidbuffon """ ## python libs import numpy as np from PIL import Image from glob import glob from os.path import join from ntpath imp...
600b81fe8e49d14b4775b0f2fadea2a59607e167f4e5ecdec53b3d45d4e841ee
Python
2,133
42
# Copyright (c) 2025, Tri Dao. """Storage order of the fp32 accumulate tiles the SM100 backward hands to its postprocess. dQ, and dK / dV for GQA, are accumulated with bulk reduce-adds into flat fp32 buffers of rows * hdim values per tile, in whatever order the epilogue streams them out of TMEM, and FlashAttentionBack...