sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
ec199184dc4874159c4f5ebc5bc73613dd47091b23a495288b01e3887ac30787
Python
280
6
def test_get_analysis_tasks(simple_data, simple_task): assert len(simple_data.get_analysis_tasks()) == 0 simple_task.save() assert len(simple_data.get_analysis_tasks()) == 1 assert simple_data.get_analysis_tasks()[0]\ == simple_task.get_analysis_name()
ed6c5f958d9d240cf1f18ebe8baaacb311ad0b1e7b32729a160e1f518d3e5059
Python
280
10
from cog import BaseRunner, ConcatenateIterator, Input class Runner(BaseRunner): def run( self, text: str = Input(description="Text to prefix with 'hello there, '") ) -> ConcatenateIterator[str]: yield "hello " yield "there, " yield text
0a5d0e9bf25c9bcd58f77cb4823c498d290df909ed4d17f0b1047952cf868457
Python
281
12
from typing import Sequence, Dict import anndata import numpy as np # An annotated data matrix. AnnData = anndata._core.anndata.AnnData Array = np.ndarray StrArray = Sequence[str] ArrayDict = Dict[str, np.ndarray] NumberDict = Dict[str, float] StrArrayDict = Dict[str, StrArray]
204fb045920bc8273f440fdb398cbb9215e15c26575c4a249e972e667f2f3019
Python
281
9
from wikibaseintegrator.datatypes.string import String class EDTF(String): """ Implements the Wikibase data type for Wikibase Extended Date/Time Format extension. More info at https://www.mediawiki.org/wiki/Extension:Wikibase_EDTF """ DTYPE = 'edtf'
327e9316380d9575764335a53afe52d986e1b9bb96d0e57c6de6a5514c2ea751
Python
281
8
from pkg_resources import get_distribution __version__ = get_distribution('lavaset').version from .lavaset import LAVASET from .rf import StochasticBosque from .lavaset_clifi import LAVASET_CLIFI from .gradient_boost import GradientBoost # from .best_cut_node import best_cut_node
4bf5e77afa31308fd03d5e681ba301a8cace857997b357ca2bfedd13533aeb34
Python
281
11
# flake8: noqa import os.path as osp from basicsr.train import train_pipeline import realesrgan.archs import realesrgan.data import realesrgan.models if __name__ == '__main__': root_path = osp.abspath(osp.join(__file__, osp.pardir, osp.pardir)) train_pipeline(root_path)
e4ca85eac50adf5fad482a4e796b44fcec5035e9697f92e824f26063ad631064
Python
283
13
import tensorflow as tf from . import utime as _utime custom_objs = { 'Conv1DBlock': _utime.Conv1DBlock, 'Encoder': _utime.Encoder, 'Upsampling1DBlock': _utime.Upsampling1DBlock, 'Decoder': _utime.Decoder } tf.keras.utils.get_custom_objects().update(custom_objs)
5460083df8884758e7b319bbd4dff49e13daee18b2f4a19b863482d9d60b4265
Python
284
14
# Settings for regularization of optimized parameters ################## # Regularization # ################## params = {} params["regularization_flag"] = 1 params["regularization_q"] = 2 params["regularization_lambda"] = 1e-3 params["regularization_param_types"] = ["strength"]
55ded585b3c077617564f780ae30a2d86b25ab4ca6d718d4e7951daa43ccc0ed
Python
286
10
class Predicate(object): def __init__(self, name, arguments): self.name = name self.arguments = arguments def __str__(self): return "%s(%s)" % (self.name, ", ".join(map(str, self.arguments))) def get_arity(self): return len(self.arguments)
9b27233e12cb89e8eb04e4a6e64d536b00a5ec0cd98ff227ff2c3f3a1c6d7d6e
Python
286
9
from wikibaseintegrator.datatypes.string import String class LocalMedia(String): """ Implements the Wikibase data type for Wikibase Local Media extension. More info at https://www.mediawiki.org/wiki/Extension:Wikibase_Local_Media """ DTYPE = 'localMedia'
a41dbd4e3cef5e6caa6ea8b7ccf3a52e86c52675566fa189f56b0b13eefb4c84
Python
286
10
class CogError(Exception): """Base class for all Cog errors.""" class ConfigDoesNotExist(CogError): """Exception raised when a cog.yaml does not exist.""" class PredictorNotSet(CogError): """Exception raised when 'predict' is not set in cog.yaml when it needs to be."""
eeb334b8f85a433a2434bb51a6fe3311268ad35f18a4ccae2b0bb6f5e5165c30
Python
286
14
from PyQt6.QtCore import pyqtRemoveInputHook import sys def set_trace(): pyqtRemoveInputHook() try: import pdb debugger = pdb.Pdb() debugger.reset() debugger.do_next(None) frame = sys._getframe().f_back debugger.interaction(frame, None) finally: pass
bb1439023d3c705a888410d1dc8a3eb1ebef14b7a3996b5e845761bda755c90e
Python
287
11
import seaborn as sns import matplotlib.pyplot as plt def cosine_plot(interactive=False, heatmap=True): """Plot """ # Interactive could use either plotly (see https://plotly.com/python/clustergram/) # or bokeh/holoviz # The latter has a nicer interface in my mind
e2e733d92cf63cacfa85aa2631f1c2c24785cf0d766d0ae75a51356030acc73e
Python
287
11
from wonambi.bids.structure import BIDSName from .paths import BIDS_IEEG_CHANNELS def test_bids_name(): b = BIDSName(BIDS_IEEG_CHANNELS) assert b.values['sub'] == 'som682' assert b.extension == '.tsv' assert b.format == 'channels' assert b.filename == b._filename
e95add40d858c0a08ec2c4cbb8328ddba127756ff3367cab321d21bc4286dc32
Python
287
13
from . import beta, chi2, gamma, norm, poisson, t # Try block needed in case the user has an # old version of scipy without multivariate normal. try: from . import multivariate_normal except AttributeError: pass try: from . import dirichlet except AttributeError: pass
c757dda219be58d10374c68c8b6e6e694bd08f920a9962449d174c1a6e79eeb3
Python
288
10
from .loss import * from config import criterion_list def get_criterion(args): # create model if args.criterion in criterion_list: return eval(args.criterion)(args) else: raise NotImplementedError("Unsupported Loss Criterion : {}".format(args.criterion))
9c626790ea308485ea340d062e3400cb6e77840e85e66f56e29d3018216d4199
Python
289
7
#! /usr/bin/env python # -*- coding: utf-8 -*- import common # We want to test both NOT specifying the -sas-file option AND specifying the default "output.sas" value. # The result should be the same in both cases common.generate_experiments(common.generate_configs((None, "output.sas")))
c37a7963b8c905e03af17cea73018690f114bb117f4b5550db20993886f11d32
Python
289
9
import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set(style="darkgrid") tips = sns.load_dataset("tips") g = sns.FacetGrid(tips, row="sex", col="time", margin_titles=True) bins = np.linspace(0, 60, 13) g.map(plt.hist, "total_bill", color="steelblue", bins=bins)
0991d44132f39916fef0bc91e901305aa867f7aecdae89f6ff1919f9edfee145
Python
290
10
import keras def get_submodules_from_kwargs(kwargs): backend = kwargs.get('backend', keras.backend) layers = kwargs.get('layers', keras.layers) models = kwargs.get('models', keras.models) utils = kwargs.get('utils', keras.utils) return backend, layers, models, utils
1d7f098259a66c083a49b3851d9c70eb6aef152aeb2fceab54a3066d14cb67af
Python
290
9
"""Shared numeric constants for Sella. Single source of truth for tolerances that were previously duplicated across modules. """ # rcond passed to np.linalg.lstsq throughout the optimizer (Jacobian # pseudo-inverse solves, constraint least-squares, projected steps). _LSTSQ_RCOND = 1e-10
4654ca7e8962d49597a2ce00bd1f04d5e8289c52255b5d16901c955e6a9b1018
Python
290
10
"""Convert all examples to python files""" from pathlib import Path import nbconvert file_dir = Path(__file__).parent for file in file_dir.glob("**/*.ipynb"): body, _ = nbconvert.PythonExporter().from_file(file) with open(file.with_suffix(".py"), "w") as f: f.write(body)
4cdcbfe56e59a233799894346c818e3fce55416ed07853fead4df0f2837cff82
Python
290
8
"""Validation of HED tags.""" from .char_util import CharValidator, CharRexValidator from .string_util import StringValidator from .class_util import UnitValueValidator from .tag_util import TagValidator from .group_util import GroupValidator from .placeholder_util import placeholder_tag
059c591b3c041972f9bf2bb4e6ea1ea815ab1ecf6a2498c2a9b41d8e080a65ac
Python
291
11
#!/usr/bin/python3 import os, sys sys.path.append(os.getcwd()) sys.path.append(os.path.join(os.getcwd(), 'pyclamp')) sys.path.append(os.path.join(os.getcwd(), '../probayes')) from pyclamp import pyclamp if __name__ == '__main__': self = pyclamp.main() sys.exit(self.App.Widget.exec())
e9b27c111799002ed62c65b34d104cad7d8b2216b2a5ceb569a52251d09985b1
Python
291
9
from genrl.agents import TD3 from genrl.environments import VectorEnv from genrl.trainers import OffPolicyTrainer env = VectorEnv("MountainCarContinuous-v0") agent = TD3("mlp", env) trainer = OffPolicyTrainer(agent, env, max_timesteps=40000,render=False) trainer.train() trainer.evaluate()
15bffd28d915ab1c57ad6bab61cd93b93e8b7f70a687452abc2c202296a443e9
Python
292
13
""" MorphoGlia input/output infrastructure. Import concrete functionality from its owning module: morphoglia.io.image morphoglia.io.masks morphoglia.io.overlays morphoglia.io.table morphoglia.io.html The package initializer intentionally performs no eager imports. """
fdf772f9c1ed5a3ae197c0e07716ad0d8b8c19e042fb73e0961b423131739d34
Python
292
7
# Copyright 2017 The Chiron Authors. All Rights Reserved. # #This Source Code Form is subject to the terms of the Mozilla Public #License, v. 2.0. If a copy of the MPL was not distributed with this #file, You can obtain one at http://mozilla.org/MPL/2.0/. """Initial file for the package"""
a9415e8394875ba76da9784124465660c12c03c93ce5d937423e654247b345f8
Python
293
8
"""Models for BIDS datasets and files.""" from .bids_dataset import BidsDataset from .bids_file import BidsFile from .bids_file_group import BidsFileGroup from .bids_sidecar_file import BidsSidecarFile from .bids_tabular_file import BidsTabularFile from .bids_util import parse_bids_filename
e83ef3869d1bb79266b4e2ddb1383edac18207bc9a517fb04ba9335d95b8bf73
Python
293
14
# -*- coding: utf-8 -*- from memory_profiler import profile f = open('/dev/null', 'w') @profile(stream=f) def test_unicode(txt): # test when unicode is present txt = txt.replace (u"ی", u"ي") #Arabic Yah = ي return txt if __name__ == '__main__': test_unicode (u"ایست")
0679262470f82e26081e7fba1bc1fac900a97a2774c7841ed6641a6116914b6e
Python
295
13
import os MIN_SYN_THRESHOLD = 5 MIN_NBLAST_SCORE_SIMILARITY = 4 MAX_NEURONS_FOR_DOWNLOAD = 100 MAX_NODES_FOR_PATHWAY_ANALYSIS = 10 APP_ENVIRONMENT = str(os.environ.get("APP_ENVIRONMENT", "DEV")) class RedirectHomeError(ValueError): def __init__(self, msg): super().__init__(msg)
1cc9ca85cf2a34222a5db4ad9e447c7042a89e703c33d64fe0c8787f78a239e5
Python
295
19
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 24 17:11:14 2019 @author: joana """ from pathlib import Path def mypaths(): homepath = str(Path.home()) modelpath = homepath + '/fitted_models/' datapath = '../data/' return modelpath,datapath
4f890c187655bdb3873dd29107ff479d67a997738901ab3bf893b8e1de4d4dc2
Python
296
9
from .multregconn import * from .pc_multregconn import * from .calcconn_parcelwise_noncircular import * from .calcactivity_parcelwise_noncircular import * from .corrcoefconn import * from .partial_corrconn import * from .combinedFC import * from .graphicalLassoCV import * from .lassoCV import *
dd5f5636dba7cf7c5cc391f3c7831777e1c4abdd6ae6d4bdd8e64a64e6868f5c
Python
296
12
import chemprop.data import chemprop.features import chemprop.models import chemprop.train import chemprop.args import chemprop.constants import chemprop.hyperparameter_optimization import chemprop.interpret import chemprop.nn_utils import chemprop.utils import chemprop.attention_visualization
a7b1b635c6eee1b332099c2c5b932a978e7671dc0f5fc96c11261a7d066e5910
Python
297
16
import numpy as np from scipy.optimize import linear_sum_assignment from topaz.algorithms import (match_coordinates, non_maximum_suppression, non_maximum_suppression_3d) def test_match_coordinates(): pass def test_nms(): pass def test_nms_3d(): pass
cb2ebb9699cb420a9636fd105db3bfe8f25768c9d80ce7ae22ba28959fdee753
Python
297
13
# -*- coding: utf-8 -*- from .classes import models from .classes import states from .classes import data_handle from .util.LibFwdBwd import FwdBwdAlg_cpp """Root directory for ChromA package.""" __author__ = "Mariano Gabitto" __email__ = "mgabitto@simonsfoundation.org" __version__ = '2.1.2'
fc80c69f1c91f7ca9b4a6eebfeecf53262625c643507661c690fc98a1a5e51c1
Python
297
12
from setuptools import setup, find_packages from HyDGL import __version__ setup( name='HyDGL', version=__version__, url='https://github.com/hkneiding/HyDGL', author='Hannes Kneiding', author_email='hannes.kneiding@outlook.com', packages=find_packages(exclude=['test']) )
80c2c31e367a89755add1e85481dfa8c9e6a29ca6f024d4ec260e238097173b6
Python
298
6
from pystripe.core import filter_streaks, batch_filter, \ gaussian_filter, hist_match, max_level, foreground_fraction, \ imread, imsave, \ waverec, wavedec, \ fft, ifft, fft2, ifft2, magnitude
86a62b08002e50d38a8fc7b228a474da63fb8e452a44beec2ea3684a1ed37e5d
Python
298
24
"""" Catalog example for testing analysis.catalog # Author: Vladan Lucic # $Id$ """ __version__ = "$Revision$" identifier = 'exp_1' results_file = 'results_1.dat' results_obj = 'results_1.pkl' cleft_columns_obj = 'cleft_columns_1.pkl' category = 'second' feature = 'good' pixel_size=3.1
404ac42264825edc3f687eadc0e261e837f6dee6b951c028a2d0c6550436c2de
Python
299
14
# Libraries import os import sys code_path = os.path.split(os.path.split(os.getcwd())[0])[0] sys.path.append(code_path) from setting import * from download_data import * # Download data_path = get_data_path("tcga") database = "legacy" cancer = "BRCA" download_dataset(data_path, database, cancer)
88fc62ab58c3d763d042c487d6aec577999fc5e940239ac03177d258d2c2ee4a
Python
299
13
def mode_and_purity(x): value_counts = x.value_counts(sort=False) largest = value_counts.nlargest(1) purity = largest[0] / value_counts.sum() return largest.index[0], purity def sparse_density(x): return x.sparse.density def np_density(x): return (x != 0).sum() / len(x)
2a5884eb0aa012221dd094330271a91133f1d5834bf6fd2bd339e072a526cafd
Python
300
14
"""Modules for processing tree-like morphology reconstructions.""" # ruff: noqa: F403 from importlib.metadata import PackageNotFoundError, version try: __version__ = version("treem") except PackageNotFoundError: __version__ = "unknown" from treem.morph import * from treem.tree import *
8947c3e927eeaf851e541485607492f085f37576d1d49d0e9c44f391f620d79e
Python
300
18
import asyncio from memory_profiler import profile @profile @asyncio.coroutine def foo(): a = [1] * (10 ** 6) b = [2] * (2 * 10 ** 7) yield from asyncio.sleep(1) del b return a if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(foo())
de426f8771cfc9d2170f0a8a08e61f84f340d086c957db497dc0696b50a6d91e
Python
300
10
from .math_operations import MathOperations as MathOperations from .padding_operations import ( get_padded_count as get_padded_count, ) from .padding_operations import ( get_padded_q_inputs as get_padded_q_inputs, ) from .padding_operations import ( get_padding_len as get_padding_len, )
048f91c54e42797646bc4f4e60c6edda89a84f501030cb26f151b9c051d028ea
Python
303
14
# Libraries import os import sys code_path = os.path.split(os.path.split(os.getcwd())[0])[0] sys.path.append(code_path) from setting import * from download_data import * # Download data_path = get_data_path('pancan') database = 'pancan' cancer = 'pancan' download_dataset(data_path, database, cancer)
3eeec699b7576997e65eeb6481e3a85313c26dceeffa1221665aa578453fb174
Python
303
15
import os """ Helper functions """ def save_plot(plt, dir, filename, dummy): if not os.path.exists(dir): os.makedirs(dir) plt.savefig(f'{dir}{filename}') plt.close() def save_image(img, dir, filename, dummy): if not os.path.exists(dir): os.makedirs(dir) img.save(f'{dir}{filename}')
758efd578119a375978f8a0dc920405d515a01e94f526d71de9dd52012f10cf0
Python
303
15
# Random seeds params = {} # Random seed for determining optimization params["seed_evo"] = 0 # Random seed for determining connectivity params["seed_con"] = 5 # Random seed for determining tms activation params["seed_tms"] = 318 # Random seed for determining input spiking params["seed_input"] = 0
86769decdf9479253b2a35fec0b48b3aee2b28190c6ab111c36cd73ab7bc42e5
Python
303
14
import unittest class TestSymmetryBreaking(unittest.TestCase): def test_imports(self): try: from bin.symmetryBreaking import main except Exception: self.fail('Unable to import from symmetryBreaking module') if __name__ == '__main__': unittest.main()
9317d266955bd4f9385620c4a876d5d3056e933dab4944f0d4d2cd03dc57f60d
Python
303
7
"""Implementation of the python API for the cell count of the flagser C++ library.""" import numpy as np from pyflagsercontain import compute_cell_count def flagser_count(adjacency_matrix): return compute_cell_count(adjacency_matrix.shape[0], np.transpose(np.array(np.nonzero(adjacency_matrix))))
bb0c57c132496fc7e104992d5d596c9e84d0634e2fd67da1aa4edd2ba50be112
Python
303
14
from enum import Enum, auto class NboType(Enum): '''Enum class for the different NBO types to be used.''' BOND = auto() ANTIBOND = auto() LONE_VACANCY = auto() LONE_PAIR = auto() THREE_CENTER_BOND = auto() THREE_CENTER_ANTIBOND = auto() THREE_CENTER_NONBOND = auto()
baf7fc1b1e63c0f2471d85ce31ee26362628c2f016baa1a6c730d6c5df36d9a1
Python
304
12
from src.utils.pylogger import get_pylogger from src.utils.rich_utils import enforce_tags, print_config_tree from src.utils.utils import ( close_loggers, extras, get_metric_value, instantiate_callbacks, instantiate_loggers, log_hyperparameters, save_file, task_wrapper, )
db571f00377ae23fabd411f8e598639afdfc574350c413f52ef690ebb1e65e95
Python
304
10
from .arjun_vit import ArjunViT from .simple_vit import SimpleViT from .vanilla_transformer import VanillaTransformer from .vit import ViT from .conformer import Conformer from .atcnet import ATCNet from .tcnet import TCNet from .labram import LaBraM from .darnet import DARNet from .mhanet import MHANet
5aca2f2458465b26413115034aeafe7087e81c04b2c3c336f44ae3f105c2546e
Python
305
4
from .setupFunctions import read_config_file from .edit_add_bids_templates import copy_templates_to_bids_root, add_participants_ids_to_tsv, change_dataset_name from .utility_functions import mkdir_if_not_exists, calculate_hash from .databaseFunctions import wipe_sqlite_database, generate_insert_statement
6de1bd66c7015eca1b115c4dd2b4b622ed984a0f4325d93e8841d6ef36c5e3f5
Python
305
8
"""Implementation of the python API for the cell count of the flagser C++ library.""" import numpy as np from .pyflagsercontain import compute_cell_count def flagser_count(adjacency_matrix): return compute_cell_count(adjacency_matrix.shape[0], np.transpose(np.array(np.nonzero(adjacency_matrix))))
82c2360026a077042e3f41e960c5125d8aee7037f88132d573f2fa2ca86e918f
Python
305
11
from enum import Enum, auto class HydrogenMode(Enum): '''Enum class for the different ways to handle hydrogens in the molecule graph.''' # hydrogens are explicitly included in the graph as nodes EXPLICIT = auto() # hydrogens are ignored and not included in the graph OMIT = auto()
0a633e7241fcec869bacc9fbb40257c45377b5933a9dae02998789d27731c1d0
Python
306
16
"""Module to visualize things in: - 1d (plot_1d.py), such as: - time-series - things in 2d (plot_2d.py), such as: - topoplot - time-frequency plots - mri images - things in 3d (plot_3d.py), such as: - surfaces (meshes) - channels """ from .plot_3d import Viz3
0624ba5be43bcea84a5bd482ad131b77e25a0bebe0f43ca543b57b08bdf8af2a
Python
307
14
import unittest class TestRecognition(unittest.TestCase): def test_imports(self): try: from dreamcoder.recognition import RecognitionModel except Exception: self.fail('Unable to import from recognition module') if __name__ == '__main__': unittest.main()
6489224abef9eae0c3671ebc60a81d536f8bdd00a21e1772ba06cecc46ab82e3
Python
307
9
from .ani import ANI from .miao import MiaoNet from .spinmiao import SpinMiaoNet from .socspinmiao import SOCSpinMiaoNet from .miaomiao import MiaoMiaoNet from .model_interface import LitAtomicModule from .base import MultiAtomicModule from .repulsion import TwoBody from .ground_energy import GroundEnergy
64b1b305b6623e9cda861302c8532365aae359c796e793812f7a09f98b2886a8
Python
308
7
#!/usr/bin/python # -*- coding:utf-8 -*- from models.CNN_1 import CNN as CNN_1d from models.cnn_1d import cnn_features as cnn_features_1d from models.AdversarialNet import AdversarialNet from models.resnet18_1d import resnet18_features as resnet_features_1d from models.Resnet1d import resnet18 as resnet_1d
dbf162083756e6fa7ba5e218a26d6434f87b9d04c262ad0c0b21dd0fa8e56b0b
Python
309
8
# Copyright 2017 The Xron(Chiron) Authors. All Rights Reserved. # #This Source Code Form is subject to the terms of the Mozilla Public #License, v. 2.0. If a copy of the MPL was not distributed with this #file, You can obtain one at http://mozilla.org/MPL/2.0/. #Store the version here __version__ = '1.0.7'
c8e471bace32c87e9b12e2ce5efd066cd9fc1608a11e8d1bcc3d134d48b510b3
Python
310
11
import argparse parser = argparse.ArgumentParser(description="simulate chemotaxis network") parser.add_argument("--config", help="watch which neuron") parser.add_argument("--randseed", type=int, default=0, help="random seed")
0e8d7b8dd41f915f241c0404b2a8d142782a74716b6680c070e244dbb666cb83
Python
311
12
""" DeepLabCut2.0 Toolbox (deeplabcut.org) copyright A. & M. Mathis Labs https://github.com/AlexEMG/DeepLabCut Please see AUTHORS for contributors. https://github.com/AlexEMG/DeepLabCut/blob/master/AUTHORS Licensed under GNU Lesser General Public License v3.0 """ __version__ = '2.1.7.1' VERSION = __version__
7f45624a4abf2a7aeb1df4b95e5fa0417c095407cf7ac22086f9d92435b0a01a
Python
311
8
from setuptools import setup, find_packages setup( name='syncopy', version='2023.05', packages=find_packages(), install_requires=[ "h5py>=2.9", "dask>2022.6", "dask-jobqueue>=0.8", "numpy >=1.10", "scipy>=1.5", "matplotlib>=3.5", "tqdm>=4.31", "natsort>=8.1.0", "psutil>=5.9", "fooof>=1.0" ], )
3c6bb3ee2beb4bb746f6d13838104e259c4d2417480f398686f08679067973f0
Python
312
13
import torch import torch.nn as nn import torch.nn.functional as F from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score import numpy as np def accuracy_TU(scores, targets): scores = scores.detach().argmax(dim=1) acc = (scores==targets).float().sum().item() return acc
d085d7ea8ff558e9c1ab65e5953bc874ed176446af610d142d1d1ce8e2b443c5
Python
312
15
from . import molecule from .density import Density from .ensemble import CellPack, Ensemble, StarFile from .molecule import OXDNA, Molecule, StreamingTrajectory __all__ = [ "molecule", "CellPack", "Ensemble", "StarFile", "Density", "Molecule", "OXDNA", "StreamingTrajectory", ]
4056dc35fff5322b836ead948700445dc92ead770effd595c21456a2a82a2210
Python
313
13
"""Testing module geom.""" import numpy as np from treem.utils.geom import rotation def test_tree_rotation(): """Tests 3D rotation.""" vec = [1, 0, 0] assert np.allclose(rotation(vec, vec)[0], np.array([0., 0.70710678, -0.70710678])) assert rotation(vec, vec)[1] == 0.0
f7a33d3a62d3f5f74b431808a88464101dc9338f612ebefd93448366a0309a2a
Python
313
15
import os import sys fastq_path = sys.argv[1] fasta_path = sys.argv[2] fastq_file = open(fastq_path) fasta_file = open(fasta_path, 'w') for idx, line in enumerate(fastq_file): if idx % 4 == 0 or idx % 4 == 1: line = line.strip() fasta_file.write(line + '\n') os.system("rm " + fastq_path)
2efed2b3af762e07aef4a16e57d0e2c972f534b278cf5236a4101d4c167fc091
Python
314
13
# make sure that memory profiler does not hang on exception from memory_profiler import memory_usage def foo(): raise NotImplementedError('Error') if __name__ == '__main__': try: out = memory_usage((foo, tuple(), {}), timeout=1) except NotImplementedError: pass print('Success')
76e3cbcef60f467bb3ddf1e59bdc67fd28a186db2a534005fda35d5f86fbac27
Python
314
23
from this import d from topaz.model.factory import (conv31, conv63, conv127, get_feature_extractor, load_model) def test_conv31(): pass def test_conv63(): pass def test_conv127(): pass def test_get_feature_extractor(): pass def test_load_model(): pass
0d9a31ab67ba09e642684ba08d5d6c74e69c7bd006e485324213ab5e8e27010a
Python
315
15
# MEGIT manual cross validation GUI caller import sys import os sys.path.append(os.getcwd()) from PySide6 import QtWidgets from megit.gui.app_chkres import MainLoader if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = MainLoader() window.show() app.exec()
52211987c6fc411ea596924f82a3fb2b578e378471a6cfe2535d86a9d2884392
Python
315
10
from unittest import TestCase from codex.data.faq_qa_kb import FAQ_QA_KB class FaqQaKbTest(TestCase): def test_faq_list(self): self.assertGreater(len(FAQ_QA_KB), 0) for qa in FAQ_QA_KB.values(): self.assertGreater(len(qa["q"]), 10) self.assertGreater(len(qa["a"]), 10)
5ddfede6c3d5bce9a41abeecfe1b9f3a18b66dbdcecfeb2f2c023735f5ec5f71
Python
315
11
"""Concordance metrics using one fixed prediction per subject and cause.""" from .concordance import concordance, concordance_cr, concordance_cr_per_event from .interval_concordance import concordance_ic __all__ = [ "concordance", "concordance_cr", "concordance_cr_per_event", "concordance_ic", ]
64b97136e644341c7464d27fda4e4af1a42a858d3c8f7b184e98dd9bd3324245
Python
315
8
from .base_dataset import BaseDataset from .emotion_recognition import * from .folder_dataset import FolderDataset from .mne_dataset import MNEDataset from .numpy_dataset import NumpyDataset from .personal_identification import * from .sspev import * from .base_dataset_perturbation import BaseDataset_perturbation
6a2d938306a9107b6e5e6ac8327fd8f1a543a414cbbabc99b87cc2c654ef54d4
Python
315
14
"""Testing module io.""" import json import numpy as np from treem.io import TreemEncoder def test_io_encoder(): """Tests JSON encoder.""" data = [[1, 2, 3], np.array(range(4, 7)), {7, 8, 9}, 0, "a"] assert json.dumps(data, cls=TreemEncoder) ==\ '[[1, 2, 3], [4, 5, 6], [8, 9, 7], 0, "a"]'
cd915388cde91225497e2ad81423275f17d40abc73f787479a0aaf21a03d9cf7
Python
315
21
import pysam import pandas as pd import time import itertools import io import numpy as np import sys import os from .VCFUtils import * from .Wrappers import * from .RawBCMatrix_Utils import * from .GenUtils import * sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
faa3b0bf31a5594a357af20687017d4b74d62d1064bca8bc62169cdfa7fb9022
Python
316
12
import numpy as np RANDOM_SEED = 42 def set_random_seed(seed: int = RANDOM_SEED): np.random.seed(seed) print(f'Random seed set to {seed}') def print_module_versions(module_list): """Print module versions""" for module in module_list: print(f'{module.__name__:<20s}: {module.__version__}')
337d7f060d092486a9ddca476b511849c62d21af8e6e748fc0505c7d6b1af012
Python
317
7
from .transform import NormalizeTarget, RemapAtomType, RandomBFSOrder, Shuffle, VirtualNode, \ VirtualAtom, TruncateProtein, ProteinView, Compose __all__ = [ "NormalizeTarget", "RemapAtomType", "RandomBFSOrder", "Shuffle", "VirtualNode", "VirtualAtom", "TruncateProtein", "ProteinView", "Compose", ]
3af77fa53d5572e8bc8e7d6d694bae28ffb7b625f2dde34224703d3094dc34c9
Python
317
16
# Exposes API for extending autograd from .core import ( JVPNode, SparseObject, VJPNode, VSpace, def_linear, defjvp, defjvp_argnum, defjvp_argnums, defvjp, defvjp_argnum, defvjp_argnums, vspace, ) from .tracer import Box, notrace_primitive, primitive, register_notrace
4f5d394eadc5b072d09a4cec94232f2ba36ec7e9e692269250aa4d1133becf0a
Python
317
15
# MEGIT zoomview preprocess GUI caller import sys import os sys.path.append(os.getcwd()) from PySide6 import QtWidgets from megit.gui.app_preproc_zoom import MainLoader if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = MainLoader() window.show() app.exec()
6353b0abf9d8a95f6634f8d6026b008de00c35663cfb4c23117348defec37e68
Python
317
15
# MEGIT overview preprocess GUI caller import sys import os sys.path.append(os.getcwd()) from PySide6 import QtWidgets from megit.gui.app_preproc_over import MainLoader if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = MainLoader() window.show() app.exec()
ea94b7529a7484fd5845a07f00479fd9808f9a02dd684272002f76e88ff61de3
Python
317
14
import unittest class TestCompression(unittest.TestCase): def test_imports(self): try: from dreamcoder.compression import induceGrammar, ocamlInduce except Exception: self.fail('Unable to import from compression module') if __name__ == '__main__': unittest.main()
b3fe0fda1f5b5e68b660eb3dd552c341fd8fc85d4936c7f43eeea5dc799b98ed
Python
318
14
import unittest class TestFragmentGrammar(unittest.TestCase): def test_imports(self): try: from dreamcoder.fragmentGrammar import FragmentGrammar except Exception: self.fail('Unable to import from fragmentGrammar module') if __name__ == '__main__': unittest.main()
801ce5a2cffaf9d0bb28c60d2d7654dbbd15921ab8d38b6f6f14cdcdb5b599ea
Python
319
18
import os import tensorflow import hdf5storage import h5py from scipy import io as sio base_dir = '/home/mayank/Dropbox (HHMI)/temp' data_file = os.path.join(base_dir, 'trnDataSH_Apr18.mat') info_file = os.path.join(base_dir, 'trnSplits_20180418T173507.mat') A = sio.loadmat(info_file) B = h5py.File(data_file)
25f6e1b996db2a54884c19bb738d51ab0a2f131ba60d4a69c3f9982638f0cec2
Python
320
9
from .core import _MetaContainer, Registry, Configurable, make_configurable from .engine import Engine from .meter import Meter from .logger import LoggerBase, LoggingLogger, WandbLogger __all__ = [ "_MetaContainer", "Registry", "Configurable", "Engine", "Meter", "LoggerBase", "LoggingLogger", "WandbLogger", ]
3084c774b9bd267c542acba5b2b739f4f30a6ea0530793ad301996a41ecd9bc7
Python
320
22
from __future__ import annotations from .config import ( PreprocessingConfig, ) from .processor import ( process_image, ) from .stage import ( PreprocessingResult, run_preprocessing, ) __all__ = [ "PreprocessingConfig", "PreprocessingResult", "process_image", "run_preprocessing", ]
fdcd5375418ca8abf666025674330860ad0baf449915c5a2410cc5d98b962df4
Python
320
13
import logging from utils.logger import setup_logging from pathlib import Path from utils import set_random_seed SEED = 1126 set_random_seed(SEED) if __name__ == '__main__': setup_logging(Path('./Logs/Tests')) loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict] print(loggers)
172171521954c0fd870ca7d77e43ec36c7caca929c8948e6b0bbd41538a3fd7f
Python
321
12
"""A tool to fit mechanistic models to deep mutational scanning data""" # Import classes users will interact with from importlib.metadata import PackageNotFoundError, version from pymochi.project import MochiProject try: __version__ = version("pymochi") except PackageNotFoundError: __version__ = "0+unknown"...
733e01cdbc1efa096a469d171f8f31c35d7e42a3c15126f36c26d9b471d9e61f
Python
321
12
AVAILABLE_LR_STRATEGIES = { } def get_lr_strategy(config:dict): if config["lr_strategy"] is None: return None elif config["lr_params"] is None: return AVAILABLE_LR_STRATEGIES[config["lr_strategy"]]() else: return AVAILABLE_LR_STRATEGIES[config["lr_strategy"]](**config["lr_params"]...
7640135f8fa3779b6d3ba41d05c3b9465617567468e3790afcf460a53b32b1df
Python
321
12
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from glob import glob # run analysis script to precompute certain plotted values such as power # spectra os.system('python analysis.py') # iterate over figure generating scripts to create figures for f in glob('figure_*.py'): os.system('python {}'.format(f))...
b3c52cdc6f6819811d12c45f0b0f91fa0d17cdffc2e6e29fd7997ade5f1371ac
Python
321
10
import os for old_filename in os.listdir("."): if old_filename[-4:] == ".csv": new_filename = old_filename.replace("mpro", "postera_sars_cov_2_mpro") new_filename = new_filename.replace("chi2", "filtered") new_filename = new_filename.replace("sorted", "sort_and_slice") os.replace(old_filename, new_filename)...
d3fb0e114313e02570f5da03defc91857f345f5f4fc2a168501b3b816b05304e
Python
321
13
from .core import * from .codec import * from typing import Any, Union def ToASCII(label: str) -> bytes: return encode(label) def ToUnicode(label: Union[bytes, bytearray]) -> str: return decode(label) def nameprep(s: Any) -> None: raise NotImplementedError('IDNA 2008 does not utilise nameprep protocol') ...
d4a3db2812ddaea4201db9450cbd0845f24419301c409f78978031ba11545c83
Python
321
8
"""Different methods for transforming E/MEG data to HMP ready data.""" from hmp.io.bids_raw import read_bids_raw from hmp.io.metadata import add_metadata from hmp.io.mne_epochs import read_mne_epochs from hmp.io.mne_raw import read_mne_raw __all__ = ["read_bids_raw", "read_mne_raw", "read_mne_epochs", "add_metadata"]...
05ed293b82f3bd2500c074520f4c46c355c2724a83756fe0d7d950d5192de531
Python
322
12
""" Adapted from DeeperCut by Eldar Insafutdinov: https://github.com/eldar/pose-tensorflow """ import os from deeplabcut.pose_estimation_tensorflow.util.logging import * # if os.environ.get('DLClight', default=False) == 'True': # pass # else: # from deeplabcut.pose_estimation_tensorflow.util.visualize import ...
2a2330ca7dd5bb86896ebe80d46ed0d590e891f09055b79663f45c7343ef9377
Python
322
11
""" Script for applying progressively neighbours filter to an slice and analyze the organization evolution Input: - List of paths to SynGraphMCF pickles - Slice definition - Neighbors filter setting Output: - Spatial analysis for the different configuration of neighbors filter "...
79cfad0c96774d9745b06acc6e48068245dca5db37fb1053d3a83d3cfec67caf
Python
322
10
#! /usr/bin/env python from lab.parser import Parser parser = Parser() parser.add_pattern('sg_construction_time', 'time for root successor generation creation: (.+)s', type=float) parser.add_pattern('sg_peak_mem_diff', 'peak memory difference for root successor generator creation: (\d+) KB', type=int) parser.parse(...
1f70e81fd7330cb4617bcac0ee06031441e70f7a84bed3468492ef5d63b7b360
Python
323
15
from cog import BaseModel, Input, Path class TrainingOutput(BaseModel): weights: Path def train( prefix: str = Input(description="data you wish to save"), ) -> TrainingOutput: weights = Path("output.txt") with open(weights, "w") as f: f.write(prefix) return TrainingOutput(weights=weight...
3867f7f10a32c05f256404b5777b02b9a3cb5918c7deb41882054c107fcc0c4e
Python
323
14
""" OXASL - Quantification using Vaby (Python based VB) Unlike the fabber method this does not yet support PVC Copyright (c) 2008 University of Nottingham """ from . import multistep_fit def run(wsp): # Basic non-PVC run multistep_fit.run(wsp.sub("basil"), impl="vaby") wsp.quantify_wsps.append("basil") ...
7ce9b7c026c768d7e2da3638db7f9fae82042125daecd91edde17dcb88769888
Python
323
12
### -- NAMING CONVENTIONS -- # names for excitatory and inhibitory masses EXC = "EXC" INH = "INH" # names for matrices NODE_CONNECTIVITY = "local_connectivity" NODE_DELAYS = "local_delays" NETWORK_CONNECTIVITY = "connectivity" NETWORK_DELAYS = "delays" # speed for dummy fixed-point-dynamical variable LAMBDA_SPEED = 10...
bf1881fc53b0d346090ace78be668ff3190640fe9b554eb531cebce9358e7ddf
Python
323
14
#!/usr/bin/env python3 '''Go through all the sdfs in the current directory and output duplicates (so they can be removed). Looks for exact duplicates.''' import sys,glob seen = set() for fname in glob.glob('*.sdf'): contents = open(fname).read() if contents in seen: print(fname) else: seen.add(content...
c7b9573a7afbab3d4f90674cf488015d905f7bc8e1cdcadf7f0f93820eba0d39
Python
323
11
from .clocked_combinatorial import clocked_combinatorial from .shift_register import shift_register from .sliding_window import sliding_window from .unclocked_combinatorial import unclocked_combinatorial __all__ = [ "clocked_combinatorial", "unclocked_combinatorial", "shift_register", "sliding_window",...
13c2c10b59a29ce19f5780d82dc313e7b5664512d557ef5b4919834ce1433bb4
Python
324
11
# Modules package import os def get_project_root() -> str: """Return the absolute path to the repository root directory. Uses the location of this ``regtools/__init__.py`` file - one ``dirname`` up is the project root. """ return os.path.dirname(os.path.dirname(os.path.abspath(__file__)...
ae2a31ce243f76c5bbd3b342bd53f030f59fbdded7f9ca791b4a8237215795f0
Python
324
15
from enum import Enum, auto class GraphFeature(Enum): '''Enum class for the different graph features to be used.''' # number of atoms in molecule N_ATOMS = auto() # number of electrons in molecule N_ELECTRONS = auto() # molecular mass MOLECULAR_MASS = auto() # charge CHARGE = aut...