sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
65bb6102051d8e84a8b1c63d4d6e8540663576c1681aa9ea0080806869562e61
Python
1,789
60
"""Tests for `multimodal_ad.models.gradcam`.""" from __future__ import annotations from typing import TYPE_CHECKING import numpy as np import pytest pytest.importorskip("tensorflow") keras = pytest.importorskip("keras") from multimodal_ad.models.architecture import Cnn3DConfig, build_3d_cnn # noqa: E402 from mult...
af0243c0deb4dbc698db8ad8baa9b963dd3d0aeac59d29ef34640dec79e9923d
Python
1,792
63
"""NotebookManager protocol.""" from __future__ import annotations from dataclasses import dataclass from typing import Protocol class NotebookManagerError(RuntimeError): """Raised by any manager when a session lifecycle op fails.""" @dataclass class SessionDescriptor: """What a Manager returns after spaw...
c1f456bdd921417118c70347586d79d94f958446ac8840e12edbe66abd1c25ec
Python
1,793
44
import os # path to this repo BASE_DIR = os.path.dirname(__file__) # path to save download checkpoints CHECKPOINT_DIR = os.path.join(BASE_DIR, "checkpoints") # URLs to download checkpoints of different models SVORT_URL_DICT = { "v1": "https://zenodo.org/record/7486938/files/checkpoint.pt?download=1", "v2": "...
c6a20b0060242b82e26251c9890a0c1ea0f294c19954e65f973c0bbe40d77a28
Python
1,793
42
#!/usr/bin/env python3 from pathlib import Path import gzip, itertools, csv, sys import pheweb from pheweb.file_utils import VariantFileReader, read_maybe_gzip sites_filepath = Path(sys.argv[1]) vep_filepath = Path(sys.argv[2]) out_filepath = Path(sys.argv[3]) def sites_reader(): with VariantFileReader(sites_f...
0b3b330a5aab76fff0717d32959422e92d75b81c49c12a0ba113df573328468b
Python
1,794
55
import os import shutil class models_genesis_config: DATA_DIR = "/mnt/dataset/shared/zongwei/LUNA16/Self_Learning_Cubes" nb_epoch = 1000 patience = 20 lr = 1e-1 train_fold=[0,1,2,3,4] valid_fold=[5,6] test_fold=[7,8,9] hu_max = 1000.0 hu_min = -1000.0 def __init__(self, ...
12243d78f340cfa7a10ec112a79ca7ecdfa1cfc312683a9332b69b271b76f6cd
Python
1,794
51
# -*- coding: utf-8 -*- class Kmers(object): """ Class is primarily used to determine the error probabilities based on k-mers. """ @staticmethod def _default_error_function(kmer_amount): """ Default/Fallback function to calculate error probabilities based on k-mers. :param...
f464711e79d8de7c6303a4b016775e53802a52caf74711ac4cd7fa46e60165dc
Python
1,795
65
""" Stub file for a guaranteed safe import of duecredit constructs: if duecredit is not available. To use it, place it into your project codebase to be imported, e.g. copy as cp stub.py /path/tomodule/module/due.py Note that it might be better to avoid naming it duecredit.py to avoid shadowing installed duecredit....
e02d669c89ad232db875be9b7dc15320f986aba261894f9a11ef4943baaffd26
Python
1,798
57
# Copyright 2018-2023 Xanadu Quantum Technologies 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 or...
66c014d1f6f2c121b7f6e5cf5091b88ea9b7540fa8c46a655b1743376d1269c1
Python
1,799
62
""" Unopinionated display configuration. """ from __future__ import annotations import locale import sys import pandas._config.config as cf # ----------------------------------------------------------------------------- # Global formatting options _initial_defencoding: str | None = None def detect_console_encodin...
4d0bf3096b0d46db6cb67ef3cac759d53f8f98d44122215d7171ca76e56b3eab
Python
1,800
65
"""Screenshots for quick guide R-lme4""" import pathlib import sys from PyQt6 import QtCore from PyQt6.QtWidgets import QApplication from shapeout2.gui.main import ShapeOut2 from shapeout2.gui import compute test_data = pathlib.Path(__file__).parent / ".." / ".." / "tests" / "data" app = QApplication(sys.argv) QtC...
d312bf19ce47669980b5b7e39b67eab65a12dbf9610e26b1753ce1a4c1903df6
Python
1,801
34
import enum import pytest from pgen import models, esm_msa_sampler, utils from pgen import pgen_msa_revised from io import StringIO from pgen.esm_msa_sampler import ESM_MSA_ALLOWED_AMINO_ACIDS import tempfile def test_pgen_msa_revised_legacy_1(shared_datadir): with tempfile.TemporaryDirectory() as output_dir: ...
ec45a69d8906dd792d2ca95f35017f774af7a6d4645301a0939c6f763f60cb15
Python
1,801
65
""" Stub file for a guaranteed safe import of duecredit constructs: if duecredit is not available. To use it, place it into your project codebase to be imported, e.g. copy as cp stub.py /path/tomodule/module/due.py Note that it might be better to avoid naming it duecredit.py to avoid shadowing installed duecredit....
775b1ae794a03400720ccc91df9bf12226bf34a5bcafcf0e3ae62c04adb2319d
Python
1,803
63
"""Test simple key-based indexing of files""" import os import pickle import shutil import pytest from pheweb import weetabix FIXTURE = os.path.join(os.path.dirname(__file__), 'input_files/correlations/rg-pipeline-output.txt') # TODO: Add unit tests for the various indexing options (eg column number etc) @pytes...
e436c3a22896c6e711cc2a5a9af253f4388cefb11a8605427e69e1958653625d
Python
1,804
51
from Curves.curves import * from Common.kernelFunctions import * from Curves.curveMultiPhase import * from Common import loggingUtils def compute(): outputDir='/Users/younes/Development/Results/curves_Stitched_0' if __name__ == "__main__": loggingUtils.setup_default_logging(outputDir, fileName='info')...
a90bb0ac214c851e9c3f345ca3fb97f7653fdb5af79602849f27a1859f0fdea6
Python
1,806
55
# MOFTransformer version 2.0.0 import torch from torchmetrics import Metric class Accuracy(Metric): def __init__(self, dist_sync_on_step=False): super().__init__(dist_sync_on_step=dist_sync_on_step) self.add_state("correct", default=torch.tensor(0.0), dist_reduce_fx="sum") self.ad...
0fc8de52d17c54a44c1458426dbeb806b69db6f0cd7f2b5ce55d43b4162c2f3e
Python
1,809
42
''' This script creates generated-by-pheweb/best-of-pheno/<pheno> which contains the strongest 100k associations for the phenotype. ''' from ..file_utils import VariantFileReader, VariantFileWriter, get_pheno_filepath from ..utils import chrom_order from .load_utils import MaxPriorityQueue, parallelize_per_pheno, get_...
4b4c93be9cb0869fbb01dd9750d151dbe0d1892caa82b8a727748a4d329e20e6
Python
1,809
36
#!/usr/bin/env python3 #Convert the RepeatMasker output to a zero-based UCSC track #script provided by Gabby Hartley import sys with open(sys.argv[1],'r') as rpmsk: with open(sys.argv[2],'w') as bed: for line in rpmsk: line = line.replace("/","\t") spl=line.split() zer...
d458129dad36d8ed9affac50b0a1f69418434ecec27ab12d1b92f2226330495c
Python
1,809
70
__all__ = ["normalize_by_max", "dot_product"] from typing import Literal import numpy as np def normalize_by_max(x: np.ndarray) -> np.ndarray: x_max = np.nanmax(np.abs(x)) if x_max == 0.0: return x else: return np.divide(x, x_max) def dot_product(x: np.ndarray, y: np.ndarray): # avo...
30f250782a08b6798303de81c153c21816a535b341b6f74005c539875f20e591
Python
1,810
57
from setuptools import setup, Extension, find_packages from codecs import open from os import path import warnings package_name = 'qbiome' example_dir = 'examples/' example_data_dir = example_dir + 'example_data/' version = {} with open("version.py") as fp: exec(fp.read(), version) here = path.abspath(path.dirna...
57f1a26b05f5cda7a1a6f3e1d252e9702ca5370bde7c1a317704bcb34b1a7d03
Python
1,810
48
# Gudied BackPropagartion from ..utils.process import get_last_layer import numpy as np import tensorflow as tf from skimage.transform import resize # for N-dimensional images @tf.custom_gradient def guided_relu(x): def grad(dy): return tf.cast(dy>0,"float32") * tf.cast(x>0, "float32") * dy return tf....
92c94188cbede6423109600bbea6a5c1239ab56ab35073c6d3171c9a89f3dc86
Python
1,811
64
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import torch import torch.nn as nn import torch.nn.functional as F class SSIMLoss(nn.Module): """ SSIM loss module. """ de...
ff48c9c0f19daa4f1b09c4a5fcba22163e13c06c08b602386f9b0b3c068c64a4
Python
1,811
43
import io import requests import pandas as pd from typing import NamedTuple from ._preference import path_exists class Data(NamedTuple): data: pd.DataFrame meta: pd.DataFrame class SuematsuData: def __init__( self, data_path: str = "https://drive.google.com/file/d/1-CyJhEb3kkkcM...
23dffd510c9446ccc285a859a44e616d64d0296bf9faa1f350f1ad8ddd65e8ef
Python
1,813
35
from Environment import * from Data_preprocessing.utils import intensity_normalization, segmentation_quick_view, dot_2d_slice_by_slice_wrapper from Data_preprocessing.edge_dection import remove_edge from Parameter import * def spot_seg(train_image_path, save_seg_path, channel, scaling_param, wrapper_param): data_p...
3b6ad1335eba53e0097239dbcb57a1553711d16494423ed7c2223a39ca2d4f67
Python
1,814
59
import argparse import os import shutil import pandas as pd def get_args(): """ Get arguments from command line with argparse. """ parser = argparse.ArgumentParser( prog='Copy-Final-MAGs.py', description="""Copy MAGs passing filters to final directory.""") parser.add_argument("-i", ...
d7f91419969f9a15b1934ca73db61e022d4860b6ff354c94765ab7c3bbe2df88
Python
1,814
49
import torch import torch.nn.functional as F import torch.autograd as autograd # Typing from torch import Tensor from typing import List, Optional, Tuple # Adopted from https://github.com/ermongroup/sliced_score_matching def sliced_score_estimation(score_net, data): x = data.view(-1, *data.shape[1:]) x.requi...
520a2fdec895e1808a0d10978ecffb1f04e3836cb149d30a4c1c91a951d03f01
Python
1,815
53
import pytest from scripts.check_test_imports import main @pytest.mark.parametrize( "src, expected_out, expected_ret", [ ( "from pandas import Series\n", "t.py:1:0 use 'pd.Series' rather than importing 'Series' " "from the pandas namespace\n", 1, ...
ff96e308d3621b5e0484a4ab66c8ccb0c286cd1833a19f76e4389bef3180506f
Python
1,815
55
"""RayVecEnv call sites batch shipped asymmetric observations without Ray in CI.""" import sys import types import numpy as np import pytest from rl_games.common import env_configurations from rl_games.common.vecenv import RayVecEnv class _Remote: def __init__(self, fn): self._fn = fn def remote(se...
282dc54ab8cf1691703b7f54ac4493cdab019aa5821e781e6288b66aa160c25e
Python
1,816
61
# Copyright 2018-2025 Xanadu Quantum Technologies 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 or...
646af6e776c6998a05f2679cec4e514534ffec0aff8954cca48b1c4520d554e5
Python
1,817
70
import tensorflow as tf import subprocess import sys import numpy as np from halo import Halo from const import SIZE from dataset import load_all_datasets BATCH_SIZE = 1 def load_iterators(train_dataset, val_dataset): batch_size = BATCH_SIZE train_dataset = train_dataset.shuffle(batch_size) val_dataset...
e9881190eae7fe9ce0ca39ab3b89b7430cfb2470963ead491e7332fee95f3551
Python
1,817
69
import torch import torch.nn.functional as F from torch import Tensor from torch.nn import ( Sequential, Linear, ReLU, GRU, Embedding, BatchNorm1d, Dropout, LayerNorm, ) from torch_geometric.nn import ( Set2Set, global_mean_pool, global_add_pool, global_m...
0a1b9a10d8cb4b0dab9f424409dbb1ebfa4bfdbd31c1fc288bb6d29db0507e0f
Python
1,818
53
from torchvision.transforms import * from PIL import Image import random import math import numpy as np import torch class RandomErasing(object): ''' Class that performs Random Erasing in Random Erasing Data Augmentation by Zhong et al. --------------------------------------------------------------------...
cce0461d5b4e8395e4132fd9b0ebe5c14bdc051776a412a0ca689c337ed0450a
Python
1,818
59
import pytest from scripts.validate_exception_location import ( ERROR_MESSAGE, validate_exception_and_warning_placement, ) PATH = "t.py" # ERRORS_IN_TESTING_RST is the set returned when parsing testing.rst for all the # exceptions and warnings. CUSTOM_EXCEPTION_NOT_IN_TESTING_RST = "MyException" CUSTOM_EXCEP...
9a9e49b96ea39598a9d6daff67abc304797e6315ea1ddc4885b81f3bd965cb90
Python
1,819
60
"""Tests for scripts/inference-timing/plot_results.py. Exercises the pure data-shaping helpers plus a full main() run against synthetic CSVs, so a change to the CSV schema written by benchmark_single_config.py that plot_results.py doesn't know about gets caught without needing real benchmark data or a GPU. """ import ...
a5ec6001284a5642ccf44331a01e6ea1eb58a300c94aacdada9f97af950e11c5
Python
1,819
43
from . import kernelFunctions as kfun ## Parameter class for matching # timeStep: time discretization # KparDiff: object kernel: if not specified, use typeKernel with width sigmaKernel # KparDist: kernel in current/measure space: if not specified, use gauss kernel with width sigmaDist # sigmaError...
d1886460de0a854daac4c4526ceb8aec1886b799ea3d88d6df27422df8d3858a
Python
1,821
69
import pytest from pandas.util._validators import ( validate_bool_kwarg, validate_kwargs, ) @pytest.fixture def _fname(): return "func" def test_bad_kwarg(_fname): good_arg = "f" bad_arg = good_arg + "o" compat_args = {good_arg: "foo", bad_arg + "o": "bar"} kwargs = {good_arg: "foo", b...
4f2ffa9e491fb6af0e935aac51d698b3896d63e1870bcd785e1a6a4f764ac397
Python
1,822
51
import os import pysam def filter_survivor_by_supp(vcf_path, min_supp=10): print(vcf_path) out_vcf_path = vcf_path.replace(".vcf", ".s{}.vcf".format(min_supp)) vcf_file = pysam.VariantFile(vcf_path) with open(out_vcf_path, "w") as out_vcf_file: out_vcf_file.write(str(vcf_file.header)) ...
cd2b5f5a9b3dfc4f2dcae8c5c7238b5a67629dc8016448363b32ededb58c89fd
Python
1,822
57
from os.path import join from dredda.download import download_if_not_exist def get_remote_files_manifest(remote_prefix, local_prefix, fp_list): remote_prefix = remote_prefix.rstrip("/") local_prefix = local_prefix.rstrip("/") fp_list = [fp.rstrip("/") for fp in fp_list] remote_files_manifest = [] f...
049fd1d38c4616d4ab804a5099497a6123150f4d368b07aaf1d795191e53a432
Python
1,824
42
from ..file_utils import VariantFileReader, get_filepath, get_tmp_path import sqlite3 from pathlib import Path from typing import List,Iterator,Tuple,Optional def run(argv:List[str]) -> None: if '-h' in argv or '--help' in argv: print('Make sqlite3 db for converting between chr-pos-ref-alt and rsid') ...
f26ae3bdddad43c2d4b81bcc7c98b47e61b6c571f9bcfb11260b81d09a5016d8
Python
1,825
45
#MIT License # #Copyright (c) 2019 Inigo Prada Luengo # #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge,...
a3a2de071e4ebf89f8a51b21a37cc8769b72a1be05f7e2671e048ca4b382ecfc
Python
1,826
50
# -*- coding: utf-8 -*- import json import regex as re UNDESIRED_SEQUENCES_JSON = "../config/error_detection/undesired_sequences.json" class UndesiredSequences(object): def __init__(self, seq_file=UNDESIRED_SEQUENCES_JSON): """ Class is used for checking existing undesired subsequences. ...
66b6a35ecc55fcd931c8a44c679c89fb9d796f9d539e90c0f1652a70bf5fb694
Python
1,827
35
import numpy as np from PIL import Image from .corruptions import * corruption_tuple = (gaussian_noise, shot_noise, impulse_noise, defocus_blur, glass_blur, motion_blur, zoom_blur, snow, frost, fog, brightness, contrast, elastic_transform, pixelate, jpeg_compression, ...
9d9e6672dc2f37ea18203f9d8e2583835753f185451c469006fa7eb37f0e28b2
Python
1,827
59
import os import requests import hashlib from pathlib import Path from tqdm import tqdm def download_if_not_exist(fp, url, md5sum=None): """ Download file from the given URL to the given fp if it doesn't exist. :param url: The URL of the file to download. :param fp: The local fp to save the file as. ...
c85ba320541f9d65154122a3f43613383447371bde43c9ea97a57913ccb8533e
Python
1,827
75
import os import h5py import nibabel as nib import numpy as np DIR = os.path.dirname(os.path.realpath(__file__)) # %% b-values and vectors f = h5py.File(DIR + '/1shell_30dir_diff_encoding.h5', 'r') bvals = f['bvals'][:] bvecs = f['bvecs'][:] # bvals = bvals.reshape(-1, 1) # B = epi.get_B(bvals, bvecs) print(bvals....
252a7452da1733c4ec33a4026db5cbc6f043b6d6fb415ac5dac753ebacda5039
Python
1,828
50
from base.surfaces import Surface from base.kernelFunctions import Kernel #from surfaceMatching import SurfaceMatchingParam from base.surfaceTemplate import SurfaceTemplate, SurfaceTemplateParam from base import loggingUtils def main(): # [x,y,z] = np.mgrid[0:200, 0:200, 0:200]/100. # y = y-1 # z = z-1 ...
865f1ecbefad7c25db16ba7065a9a7066cd4b1450719cc5b1214598324d2651a
Python
1,829
53
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import csv from read_grd import read_grd x, y, Z = read_grd('../data/Bolund.grd') with open('../data/Measurements/Dir_270.dat', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=' ', skipini...
9747ebf4949abcb5bbf55a3edc359dc3dd371b680bb32946dbed0b5dfe35b3b6
Python
1,829
58
# !/usr/bin/env python # -*- coding: utf-8 -*- import time from onmt.utils.logging import init_logger from onmt.utils.misc import split_corpus from onmt.translate.translator import build_translator import onmt.opts as opts from onmt.utils.parse import ArgumentParser from collections import defaultdict def translate(o...
9803dcd3b23500e69eddd0f516f8c90850d763174482674c8b357c55339970dd
Python
1,829
66
"""Functions for tensor shaping, unit conversion, typing, etc.""" from mrpro.utils import slice_profiles from mrpro.utils import typing from mrpro.utils import unit_conversion from mrpro.utils.fill_range import fill_range_ from mrpro.utils.smap import smap from mrpro.utils.reduce_repeat import reduce_repeat from mrpro...
9eb6b96e66c820b31dd8a85c3354907e2cdeac356436bc25b893a5344c05bd91
Python
1,830
55
import numpy as np from PyQt6 import QtCore, QtGui, QtWidgets import pyqtgraph as pg from .simple_plot_widget import SimpleViewBox class SimpleImageView(pg.ImageView): """Custom class for data visualization in Shape-Out""" def __init__(self, *args, **kwargs): super(SimpleImageView, self).__init__(vi...
aabda795f96d8e07acb6991673b20f02ff9c8d7458b21ca66ab7093088929e6f
Python
1,830
46
from typing import Tuple from functools import cached_property import torch from torch import Tensor from torch.nn import Module class PoissonGaussianNoiseModel(Module): """Poisson-Gaussian noise model for CM2 sensor: https://ieeexplore.ieee.org/document/4623175""" def __init__(self, config: dict): s...
bed5ac19a80c125d3e57170ea0bc55429b311da8722ffbbe757eb760e8e97b20
Python
1,830
45
import os from unittest import TestCase, mock import dynast.preprocessing.bam as bam import dynast.preprocessing.coverage as coverage from .. import mixins class TestCoverage(mixins.TestMixin, TestCase): def test_read_coverage(self): coverage.read_coverage(self.control_coverage_path) def test_calc...
59f4675b55388cfdf1bd2fff65789dd704301487bc966b721370f94c8a166d39
Python
1,831
68
# JN 2015-05-11 """ small function to copy start of ncs file to folders """ from __future__ import print_function, division, absolute_import import os from argparse import ArgumentParser from combinato.basics.nlxio import NCS_RECSIZE, NLX_OFFSET def start_to_folder(ncsfname, destination=None): """ read the...
b47c479251d8eff96764e263b11e1aa5219cd513a6224ef9793dcc7e9bd92b54
Python
1,831
45
from botocore.client import Config import ibm_boto3 # import types import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) from app import create_app from utils import compare_dataset_bucket_d...
c33f4305301aabb5d1c8fcb6a5d498bf2e04a72daaf1d3d421ff943cabac68bb
Python
1,831
57
"""Test some private functions.""" from pathlib import Path from fmriprep_denoise.features import derivatives import pandas as pd import numpy as np import pytest fake_timeseries_template = ( "task-test_space-MNI152NLin6Asym_" "atlas-test_nroi-100_desc-test_timeseries.tsv" ) def _make_fake_timeseries_collection...
092f0fe5af99ff3a0b08f3e5a7bdb486ff002362bb8b02a90ba99b3f69c3a37e
Python
1,833
54
import pandas as pd import pandas._testing as tm class TestToFrame: def test_to_frame_respects_name_none(self): # GH#44212 if we explicitly pass name=None, then that should be respected, # not changed to 0 # GH-45448 this is first deprecated & enforced in 2.0 ser = pd.Series(range...
86b448a5e755e03b795e2490476ede6783245426a5f9dc77af7bf9a8e11a9796
Python
1,835
55
from rl_games.common.algo_observer import AlgoObserver from isaacgymenvs.utils.utils import retry from isaacgymenvs.utils.reformat import omegaconf_to_dict class WandbAlgoObserver(AlgoObserver): """Need this to propagate the correct experiment name after initialization.""" def __init__(self, cfg): s...
28c914441cf6feb1e41ea0ba8d8a8356bb2a7a8a8752a9af6faf19813e487dbe
Python
1,836
58
'''' This extends the cloudsqlitedict module to support tuples of strings as keys. Currently, this comes at the cost, that '@' in keys is not allowed anymore. The class SqliteDict in this module does not inherit from cloudsqlitedict.SqliteDict, however it contains an instance of it. In case, some API is missing, simpl...
f6762b927d5671c4c018c71332e98325941a4e9f0c248ae5483913dccb40b2a5
Python
1,836
69
import pickle import tree import re import sys def readStrFromTree(f): strDic = {} for line in file(f): t = tree.Tree() t.read(line) s = re.sub(" +", " ",t.leaf()) strDic[s]=line return strDic dev = "genmodel/chccg.dev.linetrees" train = "genmodel/chccg.train.linetrees" #...
294b198e98528c509edbf2ef83eabdb4e2715ddd18ff9ce0b2a5b909bb117469
Python
1,837
52
from torch.optim.lr_scheduler import _LRScheduler class ConstantLR (_LRScheduler): def __init__(self, optimizer, last_epoch=-1): super (ConstantLR, self).__init__ (optimizer, last_epoch) def get_lr(self): return [base_lr for base_lr in self.base_lrs] class PolynomialLR (_LRSchedu...
3bf83a2ee7704982bb53848b64a1fe8a7e7313b91fd826770854eff430ec7c3b
Python
1,838
50
#----------------------------------------------------------------------------- # Combine Features #----------------------------------------------------------------------------- import pandas as pd import os def read_file(Vina58,SASA,dE,Water,Ion): combine = "pdb" f_V58 = pd.read_csv(Vina58,dtype={"pdb":str}) ...
bbc2241716864306930a02ef64e8cbe78bb9988654aa21826086eb1b4e7be2cf
Python
1,838
48
import os # import cloudpickle import compatibility '''Module implements a database concept, using two interfaces: (1) the dump function (2) the loader class To save an object, the dump method is called, e.g. > import myDumper > myDumper.dump(obj, savedir) This saves the object using a method specified in the res...
e109f7b4287cc5634b5069ae73ffba03c04700ee76ced35fb6ae41affa427d54
Python
1,838
55
#!/usr/bin/env python # Filename: clean_up_annotations.py # Author: Alessandro Gerada # Date: 2023-03-17 # Copyright: Alessandro Gerada 2023 # Email: alessandro.gerada@liverpool.ac.uk """Script that cleans up duplicate images in annotation folders. Use clean_up_annotations.py -h for help.""" import argparse impo...
aef064e2b8781bfe0b428acbe2a3913ee952afec080c6679d08b57e91fb9429c
Python
1,839
57
import numpy as np from pandas import ( DataFrame, Index, date_range, read_stata, ) from ..pandas_vb_common import BaseIO class Stata(BaseIO): params = ["tc", "td", "tm", "tw", "th", "tq", "ty"] param_names = ["convert_dates"] def setup(self, convert_dates): self.fname = "__test...
4e3a09656ce09247a95241c78e416d91869b70d82aae58529109e874fb595e05
Python
1,842
60
"""Index for splitting data.""" import torch def split_idx(idx: torch.Tensor, blocksize: int, overlap: int = 0, cyclic: bool = False) -> torch.Tensor: """Split a tensor of indices into different blocks. Parameters ---------- idx 1D indices to be split into different blocks. blocksize ...
a268363de303dcfc6b3b9d931e060d2edad70d7da6ad51e23326398c8fd24ce9
Python
1,842
53
#!/usr/bin/env python __author__ = 'etseng@pacb.com' """ Helper script for calculating expected accuracy from FASTQ sequences. ex: i0_LQ_sample32f89e|c32/f1p0/929 isoform=c32;full_length_coverage=1;non_full_length_coverage=0;isoform_length=929;expected_accuracy=1.0 """ import os, sys from Bio import SeqIO def phred...
1979394c24b032f6671881f18eddef83874ccc7fee1c59c97a5298cc4fbc6465
Python
1,843
62
from sys import path as sys_path sys_path.append('..') sys_path.append('../base') import os import matplotlib if 'DISPLAY' in os.environ: matplotlib.use('qt5Agg') else: matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np from scipy.linalg import expm from base import pointSets from base imp...
22f50dbae5425bafd74e8c1e56df069439a1318a26bbc80e64d7b6e624c9bd9b
Python
1,843
57
import math from numpy import random import math class viewContainer(): # container 应该包含所有刺激所需的要素 def __init__(self, config) -> None: # w 代表window,所有的刺激都要在win上显示 self.w = None # displayFrame是呈现最终结果的刺激帧 self.displayFrame = None # frameSet是ImageStim的集合,是刺激帧 ...
faf6e46f9ac78dea651be969ff09785627e946ac440412969bd8dd882a525f1b
Python
1,844
57
# ------------------------------------------------------------------------------------------------------------------------------------- # Following code curated for GCPNet (https://github.com/BioinfoMachineLearning/GCPNet): # ----------------------------------------------------------------------------------------------...
4589b62be5a08ae69d39cfca07fe9285732187b2d75c01322a06720a9adf0ba4
Python
1,845
57
"""Integrity check for the bundled AAL2 atlas asset (no TensorFlow needed). Guards the repository-root `atlas.nii.gz` + `AAL2_Atlas_Labels.csv` pair that `multimodal_ad.models.regions` depends on: wrong shape/voxel size or a label mismatch would silently break region ranking without failing loudly elsewhere. """ from...
1c066e2809ba8095c108ab43eb550a930307602d5c8fa9b9ed5787afa4e00adc
Python
1,846
44
from csv import DictReader, DictWriter import gzip import os, sys def main(bc_info_csv, input_csv, output_csv): bc_info = {} # BC --> cell type reader = DictReader(open(bc_info_csv), delimiter=',') if 'BCrev' not in reader.fieldnames or 'Celltype' not in reader.fieldnames: print(f"ERROR: Expected ...
440e053e42acfc3d55627289eb48da5b4ae2089881e2906e1038352b37b4c3aa
Python
1,846
75
from textwrap import dedent import pytest from pandas.util._decorators import deprecate import pandas._testing as tm def new_func(): """ This is the summary. The deprecate directive goes next. This is the extended summary. The deprecate directive goes before this. """ return "new_func called" ...
c3c60bbab38d7b004645f3e74f0b93eeda57028b9211566e759d5b6ca3a5c628
Python
1,848
51
import importlib.resources from PyQt6 import uic, QtGui, QtWidgets from ... import meta_tool class LME4Dataset(QtWidgets.QDialog): def __init__(self, parent, slot, *args, **kwargs): super(LME4Dataset, self).__init__(parent, *args, **kwargs) ref = importlib.resources.files( "shapeout2...
096ba81c1aaa3dd17d02a21843bfddb40f3b6b540e62541b69134a8bf58c1480
Python
1,849
59
import numpy as np import pytest import pandas as pd import pandas._testing as tm def test_astype(using_infer_string): # with missing values arr = pd.array([True, False, None], dtype="boolean") with pytest.raises(ValueError, match="cannot convert NA to integer"): arr.astype("int64") with py...
6b7e44febe608782d1c9cfb66cdda5ec973dfe6dc273c34487c11a17c7af2305
Python
1,849
53
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this wo...
1c3fbe3a58aa28363add3ea4e79048938ab70193c3aca4c40249cc29ea1bffa7
Python
1,850
65
# neural network for Hb import tensorflow as tf import numpy as np from keras.models import Sequential from keras.layers import Dense import matplotlib.pyplot as plt # load the dataset X = np.loadtxt('hb_all_for_mlp.csv', delimiter=',') y = np.loadtxt('raphe_all_for_mlp.csv', delimiter=',') # Plot original...
8c9b23d3425a61c62bf1fdf6e8a63fd62259e06da1d06f4de3d7c13c741a5105
Python
1,852
63
"""Random B0 map generation.""" import torch from scipy.special import sph_harm_y from mrpro.data.SpatialDimension import SpatialDimension from mrpro.utils.RandomGenerator import RandomGenerator def random_b0map( shape: SpatialDimension[int], fov: SpatialDimension[float], l_max: int = 3, sigma_ppm: ...
30709072cdec4b2afb2d938d99a34048e4ba95faadcb8c5acc7e26f398d0fdbd
Python
1,854
50
""" Supported Arguments for model variant: * For GPT-Neo and OPT family, everything before the slash shown in the get_llm_vec.py file (i.e., EleutherAI/ and facebook/) is not needed in any step after get_llm_vec.py GPT-2 family: "gpt2", "gpt2-medium", "gpt2-large", "gpt2-xl" GPT-Neo family: "gpt-neo-125M", "gpt-ne...
c907fcc73d788bda806c73e00577c115c09ecc0a28026b66c6fc9c5eb772da0e
Python
1,854
104
""" Arithmetic operations for PandasObjects This is not a public API. """ from __future__ import annotations from pandas.core.ops.array_ops import ( arithmetic_op, comp_method_OBJECT_ARRAY, comparison_op, fill_binop, get_array_op, logical_op, maybe_prepare_scalar_for_op, ) from pandas.cor...
dbadc2ccf73faaff7b58aa87c7a78fa2300d62cafa696d4dda3f4fd869d8a46a
Python
1,854
53
import numpy as np import pandas as pd import pandas._testing as tm class TestInferObjects: def test_copy(self, index_or_series): # GH#50096 # case where we don't need to do inference because it is already non-object obj = index_or_series(np.array([1, 2, 3], dtype="int64")) resul...
04c5804af7c78447720511929f54af70d880686d83ed5c1e44f4803a522ff2d2
Python
1,855
58
import sys import re rword = re.compile('^[^ ]*') #rlpar = re.compile('-LRB-') rlpar = re.compile('[(]') #rrpar = re.compile('-RRB-') rrpar = re.compile('[)]') renclitic = re.compile("([a-zA-Z]\'s)|([a-zA-Z]\'d)|([a-zA-Z]n\'t)|([a-zA-Z]\'ll)|([a-zA-Z]\'m)|([a-zA-Z]'re)|([a-zA-Z]'ve)") rproclitic = re.compile("([yY]'[k...
117e3fe49df03633f203e8068f785daba9e9666d642a442f2e8520fe02b8799f
Python
1,855
60
from __future__ import annotations from typing import TYPE_CHECKING import pandas as pd if TYPE_CHECKING: from pandas._typing import AxisInt def _check_mixed_float(df, dtype=None): # float16 are most likely to be upcasted to float32 dtypes = {"A": "float32", "B": "float32", "C": "float16", "D": "float6...
44045ba810209a4d3a68d0711991178d7a3bc2d6fdcb60168b2cb2d479e4a2a0
Python
1,856
58
#%% from src.trainer import Trainer from src.workflow import WorkflowBuilder, WorkFlowSpecs, WorkflowResults import numpy as np import pandas as pd from sklearn.model_selection import KFold from sklearn import set_config from src.test_config import pipe_config, model_config import yaml import tempfile import pytest se...
7645337d35ca35617a8ac26413a80c7bbfa9c5d3119646c0303e11225564535e
Python
1,856
64
#!/usr/bin/env python __version__ = '1.0' import os, sys import gzip import numpy as np from Bio import SeqIO def type_fa_or_fq(file): file = file.upper() if file.endswith('.FA') or file.endswith('.FASTA') or file.endswith('CLIPS'): return 'fasta' else: return 'fastq' def get_seq_stats(file, binwidth): ...
a1e301d5b81555ae2b958209873fbdfa612abac1ecf933c8df9265ad1457f148
Python
1,856
50
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) from app.models import Condition def get_adni_dx(visit_dx): condition = None if not isinstance(visit_dx, str): return N...
172cd3bdbe5e4952566a5612b8ced8fd5bf77f08b896fefe72be02f223ff3f77
Python
1,857
62
import os, sys, re, argparse sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts')) import model, tree argparser = argparse.ArgumentParser(''' Takes a linetrees file and headedness model and produces most probable dependency graphs. ''') argparser.add_argument('model', nargs=1,...
223cb2c0241bb19a8c2895be35e2fa09f0413f99a7ea08ea15365febc58013b9
Python
1,857
70
#! /usr/bin/env python # -*- coding: utf-8 # # Copyright (c) 2023 Kenneth Atz, Clemens Isert & Gisbert Schneider (ETH Zurich) import argparse import numpy as np import pandas as pd from rdkit import Chem from tqdm import tqdm from dragonfly_gen.ranking.qsar.cats2d import CATS2D cats2d = CATS2D() def get_cats_sim(s...
dfb2da3bab944dd9c7eca5b7ad316bc4ebda535eae0619864cd68510361ebe84
Python
1,859
57
import numpy as np import pytest import pandas as pd import pandas._testing as tm from pandas.arrays import BooleanArray from pandas.tests.arrays.masked_shared import ComparisonOps @pytest.fixture def data(): """Fixture returning boolean array with valid and missing data""" return pd.array( [True, Fa...
e2c8f1d086d63743a1127b8ad4e8af4bee6e7331cc8c42951152f721ef281a01
Python
1,860
60
#!/usr/bin/env python3 # # Copyright 2014 Google Inc. 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 requir...
5d261dc39fb7b1d13e4be705ce69eb710806fd407d3a03bc329d4aa395c4b1be
Python
1,862
59
# ------------------------------------------------------------------------------------------------------------------------------------- # Following code curated for GCPNet (https://github.com/BioinfoMachineLearning/GCPNet): # ----------------------------------------------------------------------------------------------...
0bbf242611fafdfe43f6609fef6e49753bc6ae2a83a856a5db05b3063cc41317
Python
1,864
56
# -*- coding: utf-8 -*- """ Created on Sat Sep 10 09:10:23 2022 @author: Anonymous Example code to quickly load data from tfrecords into data.Dataset. """ # %% imports from pathlib import Path import tensorflow as tf # %% prepare test dataset using stimuli directory tfrecord_dir = 'C:/Users/username/tfrecord_direct...
82b702a0a31c2aad6724591ee4eb9474f8b890fb225c3dc3dbe4e446cd66f91b
Python
1,864
71
import numpy as np import gzip def read_vcf(file,start_position=None,end_position=None): if file.endswith('.gz'): f = gzip.open(file, 'rt') else: f = open(file, 'rt') con = True head = [] while con: line = f.readline() if line.startswith('##'): ...
a79f1ace20f2933277a0fd755fb910c1c8a8952c1580e1b1aaf7bd8e99d4a7a7
Python
1,864
55
import pytest import pandas as pd import pandas._testing as tm class TestMap: def test_map(self): rng = pd.date_range("1/1/2000", periods=10) f = lambda x: x.strftime("%Y%m%d") result = rng.map(f) exp = pd.Index([f(x) for x in rng]) tm.assert_index_equal(result, exp) ...
bc95d3721923ce2a03062163296bc8c0c2f57f0ab9550052ff3e5f4147992817
Python
1,864
52
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
501149866fb540220b8081971e3d6ef740fae127e14e26dfe0f3f3816235283d
Python
1,865
57
import random import glob from cine import Cine import tube2 import align from skimage.io import imsave from numpy import int16 videonames = glob.glob("data2/*.cine") videonames2 = glob.glob("videos_surface_bug/*.cine") videonames.extend(videonames2) for i, name in enumerate(videonames): vid = Cine(name) m...
0d6be5a5e59c2e0a963f2c4e90bb13fc412f2868f7305b2b0a4cc927163a8098
Python
1,866
60
import pytest import pandas as pd from pandas.tests.plotting.common import ( _check_plot_works, _check_ticks_props, _gen_two_subplots, ) plt = pytest.importorskip("matplotlib.pyplot") class TestCommon: def test__check_ticks_props(self): # GH 34768 df = pd.DataFrame({"b": [0, 1, 0], "...
8b40eee2859dccbbec6d2c22e18fad8ffcd3d45f33f9b1c699b8557b60669cf4
Python
1,866
57
"""lightning-pose: pose estimation with supervised and semi-supervised losses.""" import importlib.metadata from pathlib import Path from typing import Any from omegaconf import OmegaConf LP_ROOT_PATH = (Path(__file__).parent.parent).absolute() OmegaConf.register_new_resolver("LP_ROOT_PATH", lambda: LP_ROOT_PATH) ...
5124a2237dac37ed06ea56584d826858bbf8d07bda2033d6e6c5635489d41711
Python
1,867
47
"""Serial mapping function.""" from collections.abc import Callable, Sequence import torch def smap( function: Callable[[torch.Tensor], torch.Tensor], tensor: torch.Tensor, passed_dimensions: Sequence[int] | int = (-1,), ) -> torch.Tensor: """Apply a function to a tensor serially along multiple dime...
a21e03c22d0c9234f60b88668ee6b6545a5527a3a18e8697f1bae83601f5b5e7
Python
1,867
54
import sys import os def nested(A, B, max_df=1): # Only checks nesting based on variable names and ablation configuration # Does not check for identity of data or formula a_vars = A.split('.')[-3].split('_')[2:-1] b_vars = B.split('.')[-3].split('_')[2:-1] if len(a_vars) != len(b_vars): ret...
e0ca3c3956118152f0601e100b64a59faae5926a93e779505b777851697b5145
Python
1,870
69
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 16 12:01:18 2023 @author: vman """ from nilearn.plotting import plot_markers, plot_roi from nilearn import datasets import numpy as np import pandas as pd import matplotlib from matplotlib import pyplot as plt # Define plot styling matplotlib.rcPa...
af0f2adf212cc35f939f0fc7a434d3574dc91e3d2d61c06b1aaa80015e5d9934
Python
1,872
69
""" Though Index.fillna and Series.fillna has separate impl, test here to confirm these works as the same """ import numpy as np import pytest import pandas as pd import pandas._testing as tm from pandas.tests.base.common import allow_na_ops def test_fillna(index_or_series_obj): # GH 11343 obj = index_or_se...
c603321694ac6ad4558aa10de053966414ebee3ec1404ff5c80c2d1530ea7cab
Python
1,872
49
# Integrated Gradient from ..utils.process import get_last_layer import numpy as np import tensorflow as tf def compute_grads(model, io_imgs, class_id, LAYER_NAME=None, MODALITY="FLAIR", XAI_MODE="classification"): modality_dict = {"FLAIR": 0, "T1": 1, "T1CE": 2, "T2": 3} io_imgs = tf.convert_to_tensor(i...