sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
342af4fb0b401f8de47ec45273fa37634bdd6529934c7c85e221c7a328d0b04b
Python
1,316
51
""" Invent a better (truly unique) GUID system """ import glob import os import sys import matplotlib.pyplot as plt import uuid import datetime import time import hashlib try: PATH_HERE = os.path.abspath(os.path.dirname(__file__)) PATH_DATA = os.path.abspath(PATH_HERE+"../../../data/abfs/") PATH_SRC = os....
42dde0be297b279948cf50a1496b4ca1f3e22052a2792d81fe081a36f0388998
Python
1,316
36
import torch import torch.nn as nn import numpy as np import torch.distributed as dist # define the strategy of weight decay class Save_Scheduler(): def __init__(self,init_weight,final_weight,start_lr,end_lr,scheduler,optim,Prop_class,PES_Normal,PES_Lammps): self.init_weight = init_weight self.fina...
b90ac608f1c41844f1fb46ab239b98a9b38ddf9ccc969d897af59e51db175253
Python
1,316
36
import pytest from rpy2 import rinterface from rpy2.rinterface import embedded from rpy2.rinterface_lib import sexp @pytest.mark.skipif(embedded.rpy2_embeddedR_isinitialized, reason='Can only be tested before R is initialized.') def test_set_initoptions(): options = ('--foo', '--bar') defa...
ce11e1895781362960a0cc52882da84bfd30f1d583d7029b19b8a17da88a5f36
Python
1,316
49
#!/usr/bin/env python import sys from pathlib import Path def get_column_names(file_path, indices): """ Get column names based on multiple indices from a tabular file. """ file_ext = Path(file_path).suffix.lower() sep = "," if file_ext == ".csv" else "\t" with open(file_path) as fh: ...
db8ad01bba1cffec3ab8a28b73ca6db41e45374a83251cf4347677d7298418c0
Python
1,316
42
import json import statistics import numpy as np from matplotlib import pyplot as plt from angorapy.common.const import PATH_TO_EXPERIMENTS ids = ['1667916362968118', '1667916362368835', '1667916362351224', '1667916362238643', '1667830229410560', '1667829693813697', '1667829690921903', '1667829690849747', '16...
700f9d0a455bf79c9bf6de4f2784f13b96256faea19c15ddee71fb7957e14c31
Python
1,317
56
import sqlite3 from datetime import datetime import click from flask import current_app from flask import g def get_db(): """Connect to the application's configured database. The connection is unique for each request and will be reused if this is called again. """ if "db" not in g: g.db =...
bb3fc5fd6b07479c2b6aaba4774c9de32064ee2bf100728d9dfac0d8df2a7d7c
Python
1,317
41
class defaultdict(dict): """Back compatible defaultdict: http://code.activestate.com/recipes/523034/""" def __init__(self, default_factory=None, *a, **kw): if default_factory is not None and not hasattr(default_factory, "__call__"): raise TypeError("first argument must be callable") ...
6a8558afe47e95977a431deef275e3b596b6be17c5b472e373f3748995d5b84f
Python
1,318
41
#!/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://...
cf261e11b79d2adb9040e54c62c67460a4d8edc20b2314d1f3f298e3b2667fc0
Python
1,318
45
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) fraction_of_standard_epoch = 5509 / 162706 msp.decay_per_epoch = 0.9 ** fraction_of_standard_epoch msp.architecture["num_motifs"] = 82 msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels") msp.arc...
d2549f870665b8e9ea2f1ea4b74e3b1eb1f45b1ec2e2f52e33787e988a76d785
Python
1,318
59
""" Interactive canvas widgets for the portal. Exposes the arena canvas, the objects placed on it and the state model that keeps the two in step. """ from __future__ import annotations from .environment_mapping import env_params_to_canvas_state from .environment_models import ( CanvasArena, CanvasRingOverlay...
f954c7f9b555210318e27bcc595e4ea6a1623e8b8d01f03b22eb71661c592174
Python
1,318
41
#!/usr/bin/env python from distutils.core import setup, Extension from distutils.command.build_ext import build_ext import numpy import git class CustomBuildExtCommand(build_ext): """build_ext command for use when numpy headers are needed.""" def run(self): # Import numpy here, only when headers are...
27adef73fd128ec2cbfab23b3af3a40f2df12e8866171d9433c871de86cd2bae
Python
1,319
57
# import libraries import pandas as pd from sklearn.utils import shuffle import sklearn import sklearn.model_selection from fastai import * from fastai.vision import * base_path = '/content/FBCG Dataset/Training Set' # get image file path path = Path(base_path) file_path=get_files(path, recurse=True) print(len(file...
6b340da0c9dee5899408909ee4d249f5b19cfb340580d89029b8b0d64b0003ba
Python
1,319
45
""" CREaTor Copyright (C) 2023 Microsoft Research This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed...
839a66747a0d9aa8959f7809ea0a71d85da944480a60ea86466581cf96689545
Python
1,319
68
import pytest # noqa from pytest import fixture, parametrize_with_cases from seqdata import read_vcf @fixture def vcf(): raise NotImplementedError @fixture def reference(): raise NotImplementedError def consensus(sample): raise NotImplementedError def bed_no_variants(): raise NotImplementedErr...
9beb9e52a873980958fcdc7611a15a82b587a33e3692116c4f9e388e3e23cccd
Python
1,319
43
import torch from nitorch import io from nitorch.spatial import resize, voxel_size from nitorch.core.py import fileparts from glob import glob root = '.' odir = f'{root}/lsfm/slide_center_oct/' device = 'cuda' for i in range(8, 24): foct = io.map(f'{root}/oct/slices/unstack/oct.{i:02d}.nii.gz') centero...
db3db77da9e2042cb623aa3341ebfceaabe96963e00409edae734cdfd9063eea
Python
1,319
40
""" Fix unite clustering from L1: - loss of barcode information under summary picklefile """ import os import pickle import snapatac2 as sa2 def update_pkl(cid, cll:str = "L1", from_dir: str = "L2_dlt2_encoder", prefix = "sa2_clustering", snap_prefix: str = "nfeat-top_nc50...
4a3b27e3e494aa7fb22eca952aa6e2773c1de920da52d78fa5bd0e00a72fe6ae
Python
1,320
42
import unittest import numpy as np from torch import nn import torch from parameterized import parameterized from modular_splicing.utils.sequence_utils import ( decode_packed_seq, map_to_all_seqs_idx, slice_packed_seq, ) class PackedSeqTest(unittest.TestCase): @parameterized.expand([(x,) for x in ...
74bb63931ab2125e11eb6dbe19695c60a572da7f72698ecaf354755dc54e708b
Python
1,320
43
""" point array class """ import numpy as np class DynamicPointArray: """ A point array that uses a numpy array to store points and resizes when its capacity is reached. It is used by algorithms that require the points as an numpy array and append points incrementally. """ def __init__(self, i...
a53e18839e2d7a67d8a4d2ffa2db4ce25325825729d3bf0198715761a6842dd1
Python
1,320
45
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) fraction_of_standard_epoch = 64764 / 162706 msp.decay_per_epoch = 0.9 ** fraction_of_standard_epoch msp.architecture["num_motifs"] = 82 msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels") msp.ar...
eb6d83056513964d83cdd855af902380e941a0f1535d07a6c76f3a3e7e2b839a
Python
1,320
41
# Copyright 2019 Novartis Institutes for BioMedical Research Inc. Licensed # under the Apache License, Version 2.0 (the "License"); you may not use # this file except in compliance with the License. You may obtain a copy # of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless # required by applicable law...
12dc31cab53cbf7f4b5d7005f09f1b2dd1955e092789b64262be83a8b4577d3d
Python
1,322
40
''' timothe.guyonnet@gmail.com & michael.reimann@epfl.ch ''' from setuptools import setup, find_packages setup( name='parcellation_project', version='0.2', install_requires=['rectangle-packer >= 2.0.0', 'numpy >= 1.18.5', 'voxcell >= 2.6.3', ...
3d1517fac1e2ba47cca4dff0e177208e9a46f5be369dd4440d1f3e3e66dd06a6
Python
1,322
67
from typing import List class NoComponentsAvailableError(Exception): def __init__( self, msg=( "No components were available. CarbonTracker supports Intel " "CPUs with the RAPL interface and NVIDIA GPUs." ), *args, **kwargs, ): super().__i...
b50b88ecc5af4535e4b0ba8180c215ecdec5e2cd463e0f09a53996135335b0c9
Python
1,322
36
#!/usr/bin/env python3 import argparse import tskit import msprime import numpy as np import pyslim def main(args): ts = pyslim.update(tskit.load(args.in_path)) ts_recap = pyslim.recapitate(ts, recombination_rate=args.rho, ancestral_Ne=args.Ne) sampN = np.random.choice(ts_recap.samples(), size=args.N, r...
fd8096f3b157b62a8f380a786d3f9602016b79e0c9db984027580522cd3676dc
Python
1,322
33
#! /usr/bin/env python import os import pandas as pd import sys from sqlalchemy import create_engine if __name__=='__main__': """Create table for meta info on Hi-C libraries. To be run after placing Hi-C libraries in '../lib/hic/<Enzyme>/hic_data/<Cell line>/<Replicate>.db' """ hic_fp = os.path....
471324896ee30159eec1b3b7d06c52920df5c639392736c969a82eed8dd3d272
Python
1,323
52
""" Tests to make sure preprocess functions work """ import eugene as eu import pytest from pathlib import Path HERE = Path(__file__).parent @pytest.fixture def sdata(): sdata = eu.datasets.random1000() eu.pp.ohe_seqs_sdata(sdata) return sdata @pytest.fixture def ohe_seqs(sdata): return sdata.ohe_...
ea6ba1ab4151444a0849bcab980cb45a059ab57a4a3f7a994e4d206f41b100ce
Python
1,323
52
#!/usr/bin/env python """Aggregate qc of all the subjects.""" import os from argparse import ArgumentParser, RawTextHelpFormatter from pathlib import Path import pandas as pd def get_parser(): """Build parser object.""" parser = ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter) ...
481493f064bc37593b69bb6329e6599e8c6d3bfea0fd063a9d557d381871699e
Python
1,324
45
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) fraction_of_standard_epoch = 9241 / 162706 msp.decay_per_epoch = 0.9 ** fraction_of_standard_epoch msp.architecture["num_motifs"] = 82 msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels") msp.arc...
4859e5fcbd8d933159bb68183e2a40835c89ca70e9d1f1c78a3984b22cf1abfa
Python
1,324
43
import numpy as np import cv2 as cv from F01 import Feature class F03(Feature): def get_map(self, img, img_f01, eroded_roi): map_float32 = self.get_map_float32(img, img_f01, eroded_roi, normalize=False) return np.uint8(map_float32) def get_map_float32(self, img, img_f01, eroded_roi, normaliz...
4a970d5642d74be64ff0ec8b2062528b49524bc2bc1f0de6cd26fbafbddf559b
Python
1,324
31
import gpytorch from gpytorch.models import ApproximateGP, ExactGP from gpytorch.variational import CholeskyVariationalDistribution, VariationalStrategy class Approx_GPModel(ApproximateGP): def __init__(self, inducing_points): variational_distribution = CholeskyVariationalDistribution(inducing_points.size...
55409432dc9efcf06f9a4e3769256d0b162670cf6d523dc0db82d183d0181239
Python
1,324
44
# 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...
c720ab53bd555eb5691d83e9a8a0de7106eb6755225d6d9cd7fb9824be61a246
Python
1,324
31
import torch from torch.utils.data import Dataset class AuxAttnDataset(Dataset): def __init__(self, size_A, size_B, device, init_method='one', mask_size=256, given_constant=1): super(AuxAttnDataset, self).__init__() self.A_size, self.B_size = size_A, size_B if init_method == 'one': ...
ef5d4fceef8231cd479e33423151e29fe18ae2a0883e34ead744a7b6d58392f0
Python
1,325
46
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["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels") msp.architecture["motif_model_spec"] = dict( type="AdjustedMotifModel", model_to_adjust_spec=dict( ...
081f21dfd10c061406d275aab2442302e00bdbe1fde5908bfa59695c8090782b
Python
1,326
47
#!/usr/bin/env python3 """ Barebones utility for changing the name of the package in `pyproject.toml`. """ import re from argparse import ArgumentParser from pathlib import Path import tomli import tomli_w def main(): parser = ArgumentParser( description="Script for changing the name of a project in a py...
98736779b035a316be5de7ba906bf63f8611fb2df84336b8ca5d00e61755f2ac
Python
1,326
44
import sys from typing import TYPE_CHECKING if TYPE_CHECKING: from ._connector import Connector from ._decreasing import Decreasing from ._hoverlabel import Hoverlabel from ._increasing import Increasing from ._insidetextfont import Insidetextfont from ._legendgrouptitle import Legendgrouptitle...
f59ca3761515bebb7ac4b74e30e5533cdee08f274b59018daf886f1683eba2e0
Python
1,326
40
"""Implementation for the app.events shortcuts.""" from contextlib import contextmanager from kombu.utils.objects import cached_property class Events: """Implements app.events.""" receiver_cls = 'celery.events.receiver:EventReceiver' dispatcher_cls = 'celery.events.dispatcher:EventDispatcher' state_...
3a96d9224f501f0392fd266f3064926d5f99e90f5b7a53e7b64a32e7eb62fa8a
Python
1,327
47
""" Ethoscope Node API Package This package contains modular API components for the Ethoscope Node Server. Each module handles a specific domain of functionality to improve maintainability and separation of concerns. Modules: - base: Common infrastructure and utilities - device_api: Device management and control - ba...
5fe41afe3ea350d0fc2aed102160db9836699fb7a9f4b9e5b70b04697778e9f7
Python
1,327
41
import tensorflow as tf from sklearn.model_selection import GridSearchCV from tensorflow.keras.wrappers.scikit_learn import KerasClassifier from codecarbon import EmissionsTracker def build_model(): model = tf.keras.models.Sequential( [ tf.keras.layers.Flatten(input_shape=(28, 28)), ...
c86335051bcdbde0c4efe65e1120926027c143a15df0e6a9cd3cbc7489fe730f
Python
1,327
47
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["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels") msp.architecture["motif_model_spec"] = dict( type="AdjustedMotifModel", model_to_adjust_spec=dict( ...
d49c1266ef86b374a7357a9b197178931f5e7b9604f1669e820db41734853d7f
Python
1,327
31
import argparse parser = argparse.ArgumentParser(description="") # parser.add_argument('--input_tsv', type=str, help="") parser.add_argument('--input_probs', nargs='+', help="") parser.add_argument('--output_csv', type=str, help="") parser.add_argument('--params', nargs='+', help="") args = parser.parse_args() #wit...
edb04254f5d24e12d26b71ba8367f18d248f46b02d75683cac2b34af1a63fc61
Python
1,327
45
import cv2 import os import numpy as np class Combine_Image(): def __init__(self, path_AB): self.path_AB = path_AB if not os.path.exists(path_AB): os.makedirs(path_AB) def combine_image(self, path_A, path_B): img_A = cv2.imread(path_A) img_B = cv2.imread(path_B) ...
5eb0313f0cd8b08373c9e60f75976f46a7e564947557eecbbd59db68fadd275f
Python
1,328
43
import urllib from pl_bolts.datasets.base_dataset import LightDataset from pl_bolts.datasets.cifar10_dataset import CIFAR10, TrialCIFAR10 from pl_bolts.datasets.concat_dataset import ConcatDataset from pl_bolts.datasets.dummy_dataset import ( DummyDataset, DummyDetectionDataset, RandomDataset, RandomDi...
f275e7b7c05b93f0c895231874b828bcfc7b96b7b46f5966d9f4048e829b6f40
Python
1,329
47
import numpy as np from sklearn.metrics import f1_score from sklearn.metrics.cluster import adjusted_mutual_info_score def cal_ami(a1, a2): labels1 = a1.astype(np.int16) labels2 = a2.astype(np.int16) ami = adjusted_mutual_info_score(labels1.flatten(), labels2.flatten()) return ami def ca...
37caf6d45adfd10b9c5688db936cfcdd659a34b48b26da96be7e01de39e87fdd
Python
1,330
33
from ovseg.preprocessing.SegmentationPreprocessing import SegmentationPreprocessing from ovseg import OV_PREPROCESSED import os import argparse parser = argparse.ArgumentParser() parser.add_argument("raw_data", default='OV04', nargs='+',) args = parser.parse_args() raw_data = args.raw_data data_name = '_'.join(sorted...
684d4a189d80c90c8b701547cbce31d37862be095c9101e9998164b53456af75
Python
1,330
40
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import json pages_db = "./pages_db.json" def get_total_number_of_epochs(f_name): with open(pages_db) as f: pages_data = json.load(f) try: number_of_epochs = pages_data[f_name] except IOError: "No key in json file!" return number_of_epoch...
d51d977f8fe0ebad6dbabd6b747266b264f46756b869b261de846228926a02b4
Python
1,330
42
import os import warnings from typing import Callable, Dict, Optional MISSING_PACKAGE_WARNINGS: Dict[str, int] = {} WARN_MISSING_PACKAGE = int(os.environ.get("WARN_MISSING_PACKAGE", False)) def warn_missing_pkg( pkg_name: str, pypi_name: Optional[str] = None, extra_text: Optional[str] = None, stdout...
08c3e180897a8c476a2c2157a338c246a890444c3bd58ed743e9f625e37431a8
Python
1,331
38
""" This module create TransformerClassifPerProt """ # pylint: disable=W0223 import logging import torch.nn as nn from torch.nn.modules.dropout import Dropout class TransformerClassifPerProtChangeDropout(nn.Module): """ This class define a Transformer model that classify an entire protein to ONE classe ""...
1773711391fc66c485d695a0c9beb563dc58ba80bfb9ac0203e9a782f6f7a5d4
Python
1,331
17
__doc__ = """ Copyright (C) 2014 Ingo Fruend This code reproduces the analyses in the paper Fruend, Wichmann, Macke (2014): Quantifying the effect of inter-trial dependence on perceptual decisions. J Vis, 14(7): 9. Permission is hereby granted, free of charge, to any person obtaining a copy of this softwar...
2ea81102f66b5c446ce37c13b36c029eb01e4f8043e88174554243d57f3ca9e9
Python
1,331
37
# %% Create a group level brain mask for SPM ''' Loops through every participant's brain mask generated by fmriprep and creates a group level mask that includes all voxels that had at least 2 participants brain mask ''' from nilearn import plotting import nibabel as nib import numpy as np from nilearn.image import new...
82b951307c2624504d8d4e093f445440c90491d493a21981b9fadeef0d3ca833
Python
1,331
38
import socket import os hostname = socket.gethostname() if 'vogel' in hostname: from .local_vogel import * elif 'zog' in hostname: from .local_zog import * elif 'magpi' in hostname: # Magpi Rev C and Rev D board revisions have different hardware # (solenoid vs servo hopper). To be sure we use the corr...
f25336058ed29285244ba8fddf81ac012ebc7c4b9f26e9137390c91820370912
Python
1,331
39
from __future__ import print_function import sys import unittest import SimpleITK as sitk class TransformixImageFilterTest(unittest.TestCase): """Test the deformation field api""" def setUp(self): pass def test_TransformixImageFilter_GetDeformationField(self): fixedImage = sitk.Image( ...
bfcdbfd99e97f01e3b10a8ad8f6f8e349bf311024ebced109894497e460b7065
Python
1,332
44
"""Wrapper for transforming the reward.""" from typing import Callable import gym from gym import RewardWrapper class TransformReward(RewardWrapper): """Transform the reward via an arbitrary function. Warning: If the base environment specifies a reward range which is not invariant under :attr:`f`, t...
67db8535668e486366d330a2d56525403b325fa56ecbf8f3a3daff5c4bdde022
Python
1,333
42
import sqlite3 from .db import DB class DistrictInformation(DB): def __init__(self): super().__init__() self.table_name = 'HR_district_info' self.table_desc = 'Haryana district-wise case information' self.cols = self.getcolumns() def getcolumns(self): cols = { ...
d7acadf13f25cd1bf6293adf810262466ae5f8975ce1362dc8af3297e13e4651
Python
1,333
40
import tensorflow as tf from tensorflow.python.client.device_lib import list_local_devices import os def is_multi_gpu_model(model): '''Checks if the model supports multi-GPU data parallelism.''' return hasattr(model, 'is_multi_gpu_model') and model.is_multi_gpu_model def get_gpu_count(): '''Returns the n...
15de739f4c433f9530d97d1e2eb6e6e5effc5af0de53d5d825dc2bad5c9a5c57
Python
1,334
37
import os from shutil import copy def check_dir_exists(path): if not os.path.exists(path): os.mkdir(path) def split_by_name(dir_path, real_save_path, fake_save_path): check_dir_exists(real_save_path) check_dir_exists(fake_save_path) if not os.path.exists(real_save_path): os.mkdir(real...
565173bd8b77b1920cb27aea4912277eac0b4deb63ad4a2338ab64bcc6cf5a5b
Python
1,334
46
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import ui from bs4 import BeautifulSoup import os, os.path import time driver = webdriver.Chrome("/opt/bin/chromedriver") import traceparts_parameters as tp tp.login(driver) time.sleep(5) # wait for page...
2155b8e5929a80104f2e4798fa1dbcad4d7ea7abf76427174a0fc34348a6171a
Python
1,335
40
import sys, os sys.path.insert(0, os.path.abspath('../../src')) from moxel import __version__ as version # Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Projec...
26e369291be8770cb609660cc81491aed94ac938cae19645a7f71ac6b318de5b
Python
1,335
43
#!/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://...
54ae07de208aaf6bf500b773eac833271c192bcdad51551647e7a65a74f8eeb7
Python
1,335
42
import numpy as np def test_distance_calculations(): from pyrosm.distance import Unit, haversine # Example line from Null Island to 10'10 --> should be ~1569 km lon1, lat1 = np.array(0.0, dtype=np.float), np.array(0.0, dtype=np.float) lon2, lat2 = np.array(10.0, dtype=np.float), np.array(10.0, dtype=...
8b0a603afbbc60286511047859b1687aa5a10492f478d0810ee4e7514235b56b
Python
1,335
33
# Written by Seonwoo Min, Seoul National University (mswzeus@gmail.com) # Some parts of the code were referenced from or inspired by below # - Tristan Bepler's code (https://github.com/tbepler/protein-sequence-embedding-iclr2019) # PLUS """ Solubility FASTA file loading functions """ import numpy as np import torch ...
bfb0d7a3858d41e1da9255f3eda813a2f467c9621cd52a8a9afbcfacaf602a31
Python
1,335
36
try: import pytabprops import unittest from os.path import join, abspath from numpy.testing import assert_allclose from tests.tabulation.turb_adiabatic_equilibrium.rebless import run from spitfire.chemistry.library import Library from spitfire.chemistry.ctversion import check as cantera_ve...
25f8937cf6bc76a60d4d29b2ecb43176f518cba94e82e3cf7fc86cb8e3aafea8
Python
1,336
35
from types import SimpleNamespace from ..data.pipeline import load_peaks from modular_splicing.motif_names import get_motif_names def peak_names(*, replicate_category): """ Get the names of the peaks for a given replicate category. """ return sorted(load_peaks(replicate_category=replicate_category)) ...
2fd893bdd40fa5bd3f0ff3b03effcb787c82d5a87f524b3f64984c5cb1108560
Python
1,336
33
import numpy as np import pandas as pd from pyreadr import pyreadr from utils.utils import plot_roc_curve, plot_pr if __name__ == '__main__': """ Script to plot roc curves and pr curves. """ task = 'mortality' population = pd.read_pickle(f'./data/{task}/population.pkl') outcomes = population[...
54ea737c69301db44e2d93121ff78b072e01adcec906283a3fd9857ea74f9fe4
Python
1,336
47
import os import utils import yaml import joblib from sklearn.feature_selection import SelectKBest from sklearn.pipeline import Pipeline from sksurv.datasets import get_x_y from sksurv.linear_model import CoxPHSurvivalAnalysis from skopt.space import Real, Categorical, Integer def preprocess_data(dataset, config): ...
9892086b5a43625cd8c8f5729756e0cdd844fd6b0060208e066dae7eb7d4099d
Python
1,336
47
import numpy as np import seaborn as sns import matplotlib.pyplot as plt from plot_params import get_plot_params get_plot_params() from ase import units def arhenius_rate(T, Ga): hbar = 6.582119569e-16 # eV s A = units.kB * T / hbar return A * np.exp(-Ga / (units.kB * T)) if __name__ == "__main__":...
8d7af50eb780ece26b55e656bb267be77a34fa82f7b37aa51120112a4396368b
Python
1,337
34
from __future__ import annotations import logging import warnings from bream4.device_interfaces.devices.base_device import BaseDeviceInterface from bream4.toolkit.procedure_components.voltage_operations import apply_voltages_for_durations class GlobalFlick(object): def __init__(self, config: dict, device: BaseD...
e206cd2c3d296a12d043d8656799bce282f4c771c3e55a84e72cc2b000fa853d
Python
1,337
42
#!/usr/bin/env python '''Given a results.dat file and password for db, put the contents into google sql as configurations that are being requested. Specify five of each.''' import sys, re, MySQLdb import pandas as pd import makemodel import numpy as np opts = makemodel.getoptions() def addrows(fname,host,db,passwo...
0186540087fc1ff480fb52a5eb88119ea68079c643a58994bc0de1fc70dff27a
Python
1,338
33
# Written by Seonwoo Min, Seoul National University (mswzeus@gmail.com) # Some parts of the code were referenced from or inspired by below # - Tristan Bepler's code (https://github.com/tbepler/protein-sequence-embedding-iclr2019) # PLUS """ Stability FASTA file loading functions """ import numpy as np import torch ...
2b654251872dc59dfc39a13ddeeed80ebc2e842ef832a3229e7901486f9bf13b
Python
1,338
53
#!/usr/bin/python import sys import os import re import pandas as pd import numpy as np import math import json import glob ##### return unique element in list ##### def unique(a): unique = [] [unique.append(s) for s in a if s not in unique] return unique def main(): ##### check argument ##### if len(sys.argv)<2...
4219c13d847bb0917c41f1ceebe2f85615fded8414347f0620baca855b1f0453
Python
1,338
50
#!/usr/bin/python import sys import os import re import numpy as np import pandas as pd import ConfigParser import json def main(): ##### check argument ##### if len(sys.argv)<3: sys.exit("ERROR: not enough arguments\nUSAGE ./celltype_perDatasetPlotData.py <filedir> <ds>") ##### get command line arguments ##### ...
5ff5785f5323671df9082f1c8c1c07122a14382a8ddd69ba50e4be5c5e2703dd
Python
1,338
52
from celery.app.annotations import MapAnnotation, prepare from celery.utils.imports import qualname class MyAnnotation: foo = 65 class AnnotationCase: def setup_method(self): @self.app.task(shared=False) def add(x, y): return x + y self.add = add @self.app.task(...
618e3cae5473e6beba8df37f848262df59ccf78f4ca56dafb461d0e813da9bb9
Python
1,338
51
import attr import scipy.stats @attr.s class Accuracy: """ Represents the accuracy of a prediction. The accuracy is represented as a mean value, and a confidence interval (95% by default). """ mean = attr.ib() low = attr.ib() hi = attr.ib() @staticmethod def of(matr, confidence...
da965208ebf404153769f034c8c78191c4c70a05d7107aad891b156c66902f19
Python
1,338
41
import pytest import glob import os import sys import pathlib PATH_HERE = os.path.abspath(os.path.dirname(__file__)) PATH_PROJECT = os.path.abspath(PATH_HERE+"/../") PATH_DATA = os.path.abspath(PATH_PROJECT+"/data/abfs/") PATH_HEADERS = os.path.abspath(PATH_PROJECT+"/data/headers/") try: # this ensures pyABF is im...
43e46a3772010988be06c3c8b3c530d681a941ef13319bcffaad7756be94fcf1
Python
1,339
42
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 7 15:05:52 2022 @author: psicobiologia """ import numpy as np from sklearn import metrics from statsmodels.stats.contingency_tables import mcnemar # define full path to target variable target_path = '/path_to_target/target.csv' # define full path...
2dd7acb6bd579fd88bb0d1092f8a2d93beae9535df29b51d0924fafe3f3e0070
Python
1,340
26
# Copyright 2019 Novartis Institutes for BioMedical Research Inc. Licensed # under the Apache License, Version 2.0 (the "License"); you may not use # this file except in compliance with the License. You may obtain a copy # of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless # required by applicable law...
5a0a5ce7017a69a9e5e273256cd31df29a7663bcd00afc8c0f4b8ccafa8a66db
Python
1,340
45
# -*- coding: utf-8 -*- # @Author: gviejo # @Date: 2022-01-17 23:01:05 # @Last Modified by: gviejo # @Last Modified time: 2022-02-07 18:01:14 import numpy as np import pandas as pd import pynapple as nap from matplotlib.pyplot import * import pynacollada as pyna from sklearn.manifold import Isomap from matplotlib....
49c85cf7dc307e01abba3ce69ee8712cc2090eaadcf5eb2fe83da90df27ed158
Python
1,341
39
"""These models have been pre-trained using self-supervised learning. The models can also be used without pre- training and overwritten for your own research. Here's an example for using these as pretrained models. .. code-block :: from pl_bolts.models.self_supervised import CPC_v2 images = get_imagenet_bat...
5add5050e86046e3dec2943f51849d3fd306472ebd8dd9a79202d5d296702c3b
Python
1,341
32
from unittest import mock from carbonserver.api.services.matomo_tracker import MatomoTracker def test_tracker_is_disabled_without_url_and_site_id(): assert not MatomoTracker().enabled assert not MatomoTracker(url="https://matomo.example.com").enabled assert not MatomoTracker(site_id="3").enabled def te...
6e0fce4bb828770cdf4352be74dd4994e77983ea17a780d6b2ee9baf9833f758
Python
1,341
35
"""Test functions for specparam.metrics.error.""" from specparam.metrics.error import * ################################################################################################### ################################################################################################### def test_compute_mean_abs_err...
755bb972e6b0b6f090d08468eb7bec46c985416f5b48387465fbefaa9ff51526
Python
1,341
49
import torch import torch.nn as nn import torch.nn.functional as F class no_z_InstNorm(nn.Module): def __init__(self, n_channels, **kwargs): super().__init__() self.norm = nn.InstanceNorm2d(n_channels, **kwargs) def forward(self, xb): nb, nc, nz, nx, ny = xb.shape ...
adbaf6559de104cc8822b8e0e9c7cf93620e57af5a3d1ed9f5362e1460e3456c
Python
1,341
38
import numpy as np def test_distance_calculations(): from pyrosm.distance import Unit, haversine # Example line from Null Island to 10'10 --> should be ~1569 km lon1, lat1 = np.array(0.0, dtype=np.float64), np.array(0.0, dtype=np.float64) lon2, lat2 = np.array(10.0, dtype=np.float64), np.array(10.0, ...
4babf80720337205679e8fbee34a7abba29600f14aeb93b228ffd467042c1fea
Python
1,342
44
"""Checks kit: the torch.compile composition leg (heavy tier). The mount decider (memo D1): Recorder refuses compiled models behind a deliberate guard while the public optimizer/tensor hooks fire normally, so the step-check family must run under torch.compile. This is the small CPU leg; the AT-SCALE compiled leg stays...
c497eece0b26077333c60b1510ffc0f2527385ce0c430dabe217e6a90a5e6995
Python
1,342
45
from sys import argv from msp import MSP msp = MSP() msp.file = __file__ msp.seed = int(argv[1]) msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels") msp.architecture["motif_model_spec"]["motif_width"] = 13 msp.architecture["motif_model_spec"]["motif_feature_extractor_spec"] = dict( type="...
485fff5cd43665536715710ef2fbf2d6ebf836a2299bb847b8ce38b88bdd50da
Python
1,343
46
from collections import OrderedDict from xml.dom.minidom import parseString import numpy as np import tifffile def load_ometif(path): """Load .ome.tif files Please see :func:`impose.formats.load` for more information. """ with tifffile.TiffFile(path) as tif: if not tif.is_ome: ra...
da5e2a9f4c124b9d2b89d7fa24288c03768366b4a5e2c19959877edb8e316e4b
Python
1,343
40
from mirp._images.generic_image import GenericImage from mirp._masks.base_mask import BaseMask class Feature(object): def __init__(self, **kwargs): self.name: None | str = None self.abbr_name: None | str = None self.ibsi_id: None | str = None self.value: None | float = None ...
fae5fd8c5574819dc7b172bba149f364e870deba451bccc20969b64a79a7e7db
Python
1,343
31
import os import tempfile from zipfile import ZipFile from xyz2swcapi import NeuroMorphoAPI def test_convert(): api = NeuroMorphoAPI() api.convert(open('../../input/to_convert/neuron_Neurolucida_DAT.dat', 'rb')) assert api.foldername is not None, "Folder name should be set after conversion." def test_che...
01bc9f83bfb64b31ce7bd316a3ee86ca1c80183e1785360b1d9172a56e33f250
Python
1,344
37
import os import re import numpy as np import matplotlib.pyplot as plt import sys sys.path.insert(1,'/home/mila/l/lindongy/deeprl-timecells') from analysis import utils_linclab_plot utils_linclab_plot.linclab_plt_defaults(font="Arial", fontdir="analysis/fonts") # ====== extract behavioural data and plot performance =...
e1293f252aba7d3a2f0f40121fc63009674bb57ea7e4478ce073a4999179cb7d
Python
1,344
42
from pytorch_lightning.utilities import rank_zero_only @rank_zero_only def log_hyperparameters(object_dict: dict) -> None: """Controls which config parts are saved by lightning loggers. Additionally saves: - Number of model parameters """ hparams = {} cfg = object_dict["cfg"] model = obj...
12fe8ffd18ab636ce7973c2aa633db0989bdc537f0f76455c7277dc6c09c6c63
Python
1,346
47
from __future__ import annotations from enum import Enum, auto from pytest_celery import CeleryTestWorker from celery.app.control import Control class WorkerKill: """Kills a worker in different ways.""" class Method(Enum): DOCKER_KILL = auto() CONTROL_SHUTDOWN = auto() SIGTERM = au...
17912001f19d654d8b94e65a6efa1969ceb9ac1e9b9fe9fc485f26c0e498b9f9
Python
1,346
46
from ethoscope.hardware.interfaces.optomotor import OptoMotor from ethoscope.stimulators.sleep_depriver_stimulators import MiddleCrossingStimulator class OptoMidlineCrossStimulator(MiddleCrossingStimulator): """ Shine LED light when animals cross the midline. Uses MODULE 3 LED even-channel mapping (same a...
2d38fb139badfae76756a47920aa6036ccfd983a8c0afcd0dcde3980ee42669f
Python
1,346
44
import os import numpy as np import random import nibabel as nib import torch from torch.utils.data import Dataset class DatasetRDO(Dataset): def __init__(self, paths, mode='training'): self.mode = mode self.paths = paths lenghts = [len(k) for k in paths.values()] assert all(x == ...
872274bd31ae50c2c23e13e68016d036b6cce3dad822a09b20d8ce5c9bd1561d
Python
1,346
35
import numpy as np import copy import tns def tmd_scale(barcode, thickness): # only the two first points of each bar are modified # because they correspond to spatial dimensions scaling_factor = np.ones(len(barcode[0]), dtype=np.float) scaling_factor[:2] = thickness return np.multiply(barcode, scal...
c8181de378f37d15066e3a4c3e911fbeb6bb818ce4de75d49422b36fb0422c17
Python
1,346
42
# -*- coding: utf-8 -*- import os import setuptools def read_file(filename): return open(os.path.join(os.path.dirname(__file__), filename)).read() setuptools.setup( name = 'bleualign', version = '0.1.1', description = 'An MT-based sentence alignment tool', long_description = read_file('README.md'), author = 'Ri...
ffac61d5075ef894d6bfa22a773551ba48e33dcc99d19bd689b697a343889f41
Python
1,346
57
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on April 2022 @author: Thomas Bonald <bonald@enst.fr> """ from abc import ABC import numpy as np from sknetwork.base import Algorithm class BaseRegressor(Algorithm, ABC): r"""Base class for regression algorithms. Attributes ---------- value...
5c76522cd9f24c0193f3c418a070ddff38293068d0869fd8474757c36d1b7053
Python
1,347
33
# Written by Seonwoo Min, Seoul National University (mswzeus@gmail.com) # Some parts of the code were referenced from or inspired by below # - Tristan Bepler's code (https://github.com/tbepler/protein-sequence-embedding-iclr2019) # PLUS """ Fluorescence FASTA file loading functions """ import numpy as np import torc...
8da0c48764cb02bce6cab2391f2941b7c3fdd10fa6a139d00f9a2ba240cb20e4
Python
1,347
38
""" This file lists the size of every structure in the structures file. sectionSizes = {'HeaderV1': 1678, 'HeaderV2': 76, 'SectionMap': 216, 'ProtocolSection': 208, 'ADCSection': 82, 'DACSection': 132, 'EpochPerDACSection': 30, 'EpochSection': 4, 'TagSection': 64, 'St...
e902ed80303de4958cb43bf121b0eb688f83a09b80d6b658378e175b913313ae
Python
1,347
66
"""Array related utilities.""" import numpy as np ################################################################################################### ################################################################################################### def normalize(data): """Normalize an array of numerical data (t...
8e7b269e06d3d988f253c0c4a886bbc953d9e9c726808ac32e896c512ff51982
Python
1,349
43
# Copyright 2024 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
9d58f4ebbef73710887330ed809f44519ec2d747370619ad4ead0ae7407956a5
Python
1,349
51
import matplotlib import numpy as np import pytest from pyriemann.utils.viz import ( plot_embedding, plot_cospectra, plot_waveforms ) matplotlib.use("Agg") pytestmark = pytest.mark.numpy_only def test_embedding(get_mats): n_matrices, n_channels = 5, 3 X = get_mats(n_matrices, n_channels, "spd"...
3da350b2ce30e62075042bd7470fc46d6442c94b9a161b828a6d79c8f6c7578b
Python
1,350
51
# from .utils import get_img_from_fig, checkType import scanpy from anndata import AnnData def non_spatial_plot( adata: AnnData, use_label: str = "leiden", ) -> None: """\ A wrap function to plot all the non-spatial plot from scanpy. This function will produce 3 plots: PAGA graph, cluster plot in...
413cb856547e536063b57f9e37f69adb55868094107b307a6091a23ed56dbef2
Python
1,350
48
""" EDeN filetypes """ from galaxy.datatypes import data from galaxy.datatypes.tabular import Tabular class Gspan(Tabular): """Class describing an gSpan file""" file_ext = "gspan" def set_peek(self, dataset, is_multi_byte=False): if not dataset.dataset.purged: dataset.peek = "gS...