sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
66e57a8c759d0445f3b9ee43be2db1197001e269fb27005b7c9e9fe2a1f3c46f
Python
2,133
54
import tensorflow as tf import numpy as np from pdb import set_trace BATCH_SIZE = 10 def get_dataset(): fashion_mnist = tf.keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() return (train_images, train_labels), (test_images, test_labels) de...
434fec59d185b53f6d911d6115a7bf602a39993884f9265323f181b18d92ae68
Python
2,134
69
OVERALL_SIZE_CANO_TEST_SET = 16505 def get_tissue_groups(name): import sys sys.path.insert(0, ".") from modular_splicing.gtex_data.experiments import tissue_groups return getattr(tissue_groups, name) def get_path(name): import sys sys.path.insert(0, ".") from modular_splicing.gtex_data...
b94963082ef4bc2173ec887375f390048c9db604e43e199500726d4da9a99967
Python
2,134
61
import functools @functools.lru_cache(maxsize=1) def torchvision_vit_available() -> bool: """Checks if Vision Transformer (ViT) models are available in torchvision. This function checks if the `vision_transformer` module is available in torchvision, which requires torchvision version >= 0.12. It also han...
ce6c2f8816b27b236ba54e2b93fe7eb016218ae50ebbae239fef82d5238c3226
Python
2,134
72
"""Functional performance-regression smoke tests.""" from __future__ import annotations from types import FrameType import torch from torch import nn import torchlens as tl import torchlens.utils.introspection as introspection class TenLayerMlp(nn.Module): """Ten-layer MLP for stack-introspection smoke tests....
50583a634c3136dcbbb565466fed9ce0f90dee1f14823d305c19f66c72240228
Python
2,135
68
import sys, os from collections import defaultdict from functools import wraps import brian2.numpy_ as np from brian2.units.fundamentalunits import ( Quantity, fail_for_dimension_mismatch, is_dimensionless, DIMENSIONLESS) from brian2.core.variables import VariableView @wraps(np.concatenate) def concatenate(arrays...
6245ab5c4eddbb0a9c2cffbfbd305b4786719c07f8bea1c649df2ad60428ec44
Python
2,135
77
from pathlib import Path import pandas as pd from anndata import AnnData def positions( adata: AnnData, position_filepath: Path | str, scale_filepath: Path | str, quality: str = "low", copy: bool = False, ) -> AnnData | None: """\ Adding spatial information into the Anndata object Pa...
e1f4cf286661be7730f9505db3b2912108e989364d4fe082cae586f4f1f914bb
Python
2,135
86
''' http://pymolwiki.org/index.php/cgo_arrow (c) 2013 Thomas Holder, Schrodinger Inc. License: BSD-2-Clause ''' from pymol import cmd, cgo, CmdException def cgo_arrow(atom1='pk1', atom2='pk2', radius=0.5, gap=0.0, hlength=-1, hradius=-1, color='blue red', name='', state=0): ''' DESCRIPTION C...
1f9f0280c13fa9238f4d92ce1b4f30160ad04b58f7e29bcdc0c3eb9138f7124e
Python
2,136
67
# We use the same API as https://github.com/rwightman/pytorch-image-models/blob/v0.6.11/timm/models/layers/patch_embed.py # But we use nn.Linear instead of Conv2d and it's about 8x faster. from functools import partial import torch.nn as nn from einops import rearrange from torch import _assert from torch.nn.modules....
b66942ea6bf3328606ba47b7e1530b06e60adf8f56c1dbf2faec32523675f342
Python
2,136
61
# fix problems with pythons terrible import system import os import sys file_dir = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os.path.join(file_dir, '..')) import prob2020.console.randomization_test as rt import numpy as np def test_ctnnb1_hotmaps_main(): opts = {'input': os.path.join(file_dir, '...
ff7862e347683241855bf2e8eb4cc610a16365b68754f23c23072c92180d0648
Python
2,136
92
#!/usr/bin/env python3 from __future__ import annotations import re import ghapi.all from rich import print from rich.syntax import Syntax ENTRY = re.compile( r""" Suggested \s changelog \s entry: .* ```rst \s* (.*?) \s* ``` """, re.DOTALL | re.VERBOSE, ) print() api = ghapi.al...
658c538c62a32d2770425488e2f1e25af60e68df9128a23612c3cd164e958a14
Python
2,137
86
from typing import Optional, Union from anndata import AnnData import pandas as pd def stack_3d_plot( adata: AnnData, slides, cmap="viridis", slide_col="sample_id", use_label=None, gene_symbol=None, ) -> Optional[AnnData]: """\ Clustering plot for sptial transcriptomics data. Also it ...
75c7a509b9904a71d0beda0b27a058836f79ce9aab0ad13e311606812a51507c
Python
2,139
32
etas = { 'generic14_learning': { 'alpha_sys': { 'muT__hat': 1.0, 'muT__muT': 0.0896875702392, 'muT__muW': 0.00786798398002, 'muT__phi': 0.0, 'muW__hat': 1.0, 'muW__muT': 0.00803419913052, 'muW__muW': 0.214994532712, 'muW__phi': 0.0 }, }, 'generic20_learning': { 'alpha_sys': { 'muT__hat': 1.0, 'muT__muT__down': 0...
ccc35e2e5f018104bf6d4ab3340e55577d97c5c2a94df58745aadbdaa2da02f0
Python
2,139
54
from ptic import pmi_tfidf_classifier as ptah import numpy as np import pandas as pd from sklearn import metrics import torch from ptic import neuro_ptic device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') np.random.seed(42) path = "doc/datasets/" data_raw = pd.read_csv(path + 'DILI_data.csv') indi...
191b5001f2eea758bce69416a049fcb5752015c246f892301cfe9a53ea64112f
Python
2,141
59
from bioconfpred.data.split import DataSplit from typing import Dict, Any from .atomistic.comenet import AtomicComENet from .atomistic_nn_model import AtomisticNNModel from bioconfpred.params import (LOG_DIRPATH, COMENET_CONFIG, COMENET_MODEL_NAME) class ComENetModel(AtomisticN...
53240a65c389ba2ae439e3e3aba514d30f385177a95404df2a0b4f86deb81e22
Python
2,141
56
import os import glob import shutil #print [name for name in os.listdir(".") if os.path.isdir(name)] raw_dir = "" mask_dir = "" # Change rootdir as you want: counter = 0 #List all files in raw_dir for raw_file in os.listdir(raw_dir): raw_filename = os.path.join(raw_dir, raw_file) mask_filename ...
ad87bb4b199bacc00e915ba1c5a4cd2eeecb5e03b0c451194800448568507b1c
Python
2,141
61
from __future__ import division import unittest import numpy as np from wyrm.types import Data from wyrm.processing import remove_classes from wyrm.processing import swapaxes class TestRemoveClasses(unittest.TestCase): def setUp(self): ones = np.ones((10, 5)) channels = ['ca1', 'ca2', 'cb1', '...
b4ffbb7bcf89a5fbd50b25e304477c31f5d3baec981ebd6fe1388ae3a38345a0
Python
2,141
32
etas = { 'generic14_learning': { 'alpha_sys': { 'muT__hat': 1.0, 'muT__muT': -0.0160994540422, 'muT__muW': 0.000696975533569, 'muT__phi': 0.0, 'muW__hat': 1.0, 'muW__muT': 0.139179311976, 'muW__muW': 0.0039681776849, 'muW__phi': 0.0 }, }, 'generic20_learning': { 'alpha_sys': { 'muT__hat': 1.0, 'muT__muT__down': ...
544f2ebbd7becaf52e430e61836be893da3073a99c76d6262e9cc5a609ade1f1
Python
2,142
65
import json import re import numpy as np from matplotlib import pyplot as plt import matplotlib from angorapy.common.const import QUALITATIVE_COLOR_PALETTE as COLORS font = {'family' : 'Times', 'weight' : 'normal', 'size' : 12} matplotlib.rc('font', **font) with open("storage/predictability_repe...
7057fe09cb0934d424ad677644925f131a03405d77963dd8b4185a1c8f45d7ab
Python
2,142
61
import json from typing import Optional, Union import requests from codecarbon.core.telemetry_schemas import TelemetryCreate from codecarbon.external.logger import logger class TelemetryClient: """ Client dedicated to sending CodeCarbon telemetry payloads. """ def __init__( self, en...
7c48e7aa3d468d3b475732255bf14ddec73d06a69e5fa09346ba730c935d474a
Python
2,142
50
#!/usr/bin/env python """Update the featurenames json file that contains the expected names""" """ Copyright (c) 2015, Blue Brain Project/EPFL All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Red...
8ce94dc7be79521d21002d8d8587ae37d30a9bf3429e0c1917bcc3688a71913b
Python
2,142
45
"""Pre init checks""" import sys def _require_mxnet_version(mx_version, max_mx_version='2.0.0'): try: import mxnet as mx from distutils.version import LooseVersion if LooseVersion(mx.__version__) < LooseVersion(mx_version) or \ LooseVersion(mx.__version__) >= LooseVersion(max_mx...
ac64c2fdbefcb2b421125d012bcf720094c4883dffdd40d9ed6b6dc11bcf218e
Python
2,143
62
import logging import colorlog import re import os from cvnn.utils import create_folder from tensorflow.keras.utils import get_custom_objects from cvnn.activations import act_dispatcher from cvnn.initializers import init_dispatcher get_custom_objects().update(act_dispatcher) # Makes my activation functions usable ...
920fd85dc8f288e1b74334f710a10b9524a44a90b6be4efa221b80c80df29a40
Python
2,144
67
from __future__ import annotations from larvaworld.portal.landing_registry import ITEMS from larvaworld.portal.registry_logic import validate_registry from larvaworld.portal.serve import APP_ID_TO_FACTORY_PATH, SERVED_APP_IDS def test_validate_registry_strict_passes() -> None: validate_registry(strict=True) de...
811afa47d03353a96ff2ad9d3750a3f8601afe0497adb5de044030c907ac41a5
Python
2,145
63
import numpy as np import math import statistics import pdb # ------------------------------------------------------ # 3d distance def distance3d(a, b): d = math.sqrt(math.pow(a[0] - b[0], 2) + math.pow(a[1] - b[1], 2) + math.pow(a[2] - b[2], 2) * 1.0) # print("Distance is...
b9571d8cbda4f3b96f83676ca187e29a3086ddfb1cfbadee14eff9f563fec003
Python
2,145
62
"""Distributions used in some continuous RL algorithms.""" import torch class TanhMultivariateNormal(torch.distributions.MultivariateNormal): """The distribution of X is an affine of tanh applied on a normal distribution. X = action_scale * tanh(Z) + action_bias Z ~ Normal(mean, variance) """ de...
2a20dedee260c1483deb9ebefefb950b934bdd6179038b1a54a2eafd87a17250
Python
2,146
64
import cv2 import time import logging import os import numpy as np from ethoscope.utils.debug import EthoscopeException import multiprocessing from scipy.misc import toimage, imread, imsave from io import BytesIO import io from ethoscope.hardware.input.cameras import PiFrameGrabber, OurPiCameraAsync class PiFrameGrab...
a47c557744c77faa8b8dce69546531a8f04c0eb4e0b0014e31ad71223aca66c7
Python
2,146
64
from __future__ import annotations import os os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") from PySide6.QtWidgets import QApplication from larvaworld.gui_v2.apps.models_environments.env_builder_widget import ( EnvBuilderWidget, build_environment_builder_widget, ) def _app() -> QApplication: re...
cb92b0baf6092bfaa0472339f30fa8b5e3713cf399a4c8769cf6c04553845209
Python
2,146
81
import logging import yaml import copy import argparse from bson.objectid import ObjectId import numpy as np from pymatgen.core import Molecule from atomate.qchem.fireworks.core import ( FrequencyFW, FrequencyFlatteningTransitionStateFW, ) from atomate.common.powerups import add_tags from fireworks import ...
d0c85e677601a978ef16171104bbb4b44d2cba322dd5b1f128c0456bc2534f95
Python
2,146
32
etas = { 'generic14_learning': { 'alpha_sys': { 'muT__hat': 1.0, 'muT__muT': 0.203084255229, 'muT__muW': -0.000905716822652, 'muT__phi': 0.0, 'muW__hat': 1.0, 'muW__muT': -0.000110063688614, 'muW__muW': 0.201823621185, 'muW__phi': 0.0 }, }, 'generic20_learning': { 'alpha_sys': { 'muT__hat': 1.0, 'muT__muT__down'...
0ff48543448e66488a3fc5e3daedffbae40e63a14411acd5f74af5283ae0b7fa
Python
2,147
71
import sys import pathlib import matplotlib.pyplot as plt import numpy as np from typing import Tuple try: PATH_HERE = pathlib.Path(__file__).parent PATH_ABFS = PATH_HERE.joinpath("../../data/abfs/").resolve() PATH_SRC = PATH_HERE.joinpath("../../src/").resolve() print(PATH_SRC) sys.path.insert(0, ...
c0d60d9e477c9fff979046488e40d6eb01ecc1fd116be249650b4bcc2a9e7bd6
Python
2,147
70
""" need FreeCAD daily after Nov 2020 convert off mesh format to some other format and also calc properties like bbox, volume """ import sys import os try: sys.path.append("/usr/lib/freecad-daily-python3/lib") # /usr/lib/freecad-daily/Mod import FreeCAD as App import Mesh except: pass # it is fine...
2f67fa9977c38c01e6c93c0f0ee9dda3b803ac390ccd87616197902e13f33fd3
Python
2,148
69
import numpy as np from .conf_ranker import ConfRanker from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem.rdchem import Mol from typing import List, Any class EnergyRanker(ConfRanker): """Can rank conformers based on MMFF94s energy :param name: Name of the ranker :type name: str :...
4faa2984a3997a03c2ed2701baec23bbe25b84642d1c58587b513d680bb2cc0b
Python
2,148
52
# Copyright 2019 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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://w...
bcd99dedc0327db50e256beb0a108b07bd66555ae09e66038b29429e3fbc9a8e
Python
2,148
66
"""Image preprocessing. """ from typing import Optional, Union import cv2 import matplotlib.pyplot as plt from anndata import AnnData from ..io.image_utils import add_image_layer def remove_background( adata: AnnData, threshold: Union[float, str] = "auto", slice: Optional[str] = None, used_img_layer...
7c13b3d7321235a5a610cc5dbfcaa3abcefc9c0859d648f5df41c395630c00fb
Python
2,149
49
from angorapy import make_task from angorapy.common.policies import BetaPolicyDistribution, MultiCategoricalPolicyDistribution, \ CategoricalPolicyDistribution from angorapy.utilities.model_utils import is_recurrent_model from angorapy.utilities.core import flatten from angorapy.models import get_model_builder d...
8709c567a1a9508b587ad2f3878e9645f7fa7aa17701ea7fe9d42d8f3dbd4be6
Python
2,149
65
""" # > Script for measuring quantitative performances in terms of # - Structural Similarity Metric (SSIM) # - Peak Signal to Noise Ratio (PSNR) # > Maintainer: https://github.com/xahidbuffon """ ## python libs import numpy as np from PIL import Image from glob import glob from os.path import join from ntpath imp...
b648679bd278fbc4d708d836f595b8b7e503035d4682fcaa71af4c3eb4581c22
Python
2,149
59
"""AUD-CODE 3.10 regression: the README gate's volatile normalizer. The README first screen prints ``log.summary()``, whose Memory line carries the host-RSS forward peak (a runtime measurement documented as never portable). Two cold runs printed ``78.9 MB`` and ``80 MB`` and the gate went red non-deterministically. Th...
d82b35a554c52e90d259fe0ff248ce1c8d52ea6977f6147722cee88e82892ddf
Python
2,149
53
import numpy as np import math import pdb # ----------------------------------------------------- def checkConsecutive(index_list): return (sorted(index_list) == list(range(min(index_list), max(index_list) + 1))) and (sorted(index_list) == index_list) # ------------------------------------------------------ # I...
4903b28311e2947021ce8f2878e89d93b0a8b2c3d69d16eef153a096fd2143d8
Python
2,150
53
from model import * from utils import * import numpy as np import torch import os,sys from sklearn.metrics import roc_auc_score, precision_score, recall_score,precision_recall_curve, auc,accuracy_score,f1_score TEST_BATCH_SIZE =256 model_name = 'ratio_0.9bach32LR_1e-4random_0_onehot.pt' dataset = ['toy_cls','BindingD...
db7cdb86cde552dda1832513e538d3c80cb0de33b42d90877d5a4e4c50820b56
Python
2,150
24
# Reorganize the data in folders as expected by the code # developed by Diamant et al. import os import shutil ids = ['HN1004','HN1006','HN1022','HN1026','HN1029','HN1046','HN1047','HN1054','HN1057','HN1060','HN1062','HN1067','HN1074','HN1077','HN1079','HN1080','HN1081','HN1083','HN1088','HN1092','HN1095','HN1096','H...
343e12b624c5a92b5d5a494177f6492578c997883a07932906ff80dfe73cd035
Python
2,151
64
import pytest import torch from lightly.loss import FroSSLLoss class TestFroSSLLoss: def test_forward(self) -> None: loss_fn = FroSSLLoss() for bsz in range(2, 4): z0 = torch.randn((bsz, 32)) z1 = torch.randn((bsz, 32)) loss = loss_fn([z0, z1]) asse...
9956c82775041c244a63ac942a2533974149534502f300d1a9b4e23797ede086
Python
2,152
65
import os, argparse, shutil import gluoncv as gcv gcv.utils.check_version('0.6.0') from gluoncv.utils import makedirs def parse_opts(): parser = argparse.ArgumentParser(description='Preparing MINC 2500 Dataset', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser...
35afcc2209a38247180f5b7ff98fa97ccebd62e66ffa58f4b70a63e4f63e4aad
Python
2,153
57
"""Executable gate over ``docs/reference/checks_kit.md`` (memo item 11). Every Python fence on the checks-kit page executes top to bottom, statement by statement, in ONE shared namespace with ZERO ambient injections: the page must define everything it references, so a recipe that drifts from the real surface fails thi...
84d81fe6fbea88f2340e3357753253992a99259970b3a9bb0669817f644053b5
Python
2,153
74
"""Neural Logic Machine, 2019, Dong et al., "Neural Logic Machines". Paper: Dong 2019, "Neural Logic Machines." Binary predicate tensors are transformed by existential and universal reductions, pairwise predicate composition, and an MLP-style logic layer. """ from __future__ import annotations import torch from torc...
d38a6ac8a51f528357d12183dc3c078a37ac3c1de4643fc9ecd925494491b423
Python
2,153
60
import os from .parcellation_level import ParcellationLevel class BinarySplitLevel(ParcellationLevel): def __init__(self, root, config, hierarchy, structures, region_volume, overwrite=False): super().__init__(root, config, hierarchy, region_volume, overwrite) self._structures = structures @p...
61691a03cf08d82429c17a427d082566da95c4e2885b4cbad48747b473eb0bf6
Python
2,155
54
''' Copyright 2021 Twente Medical Systems international B.V., Oldenzaal The Netherlands 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...
a206571e4143c1c3bd566c540eff107f356ada3d918ccc50f1ec8de736279a22
Python
2,155
46
''' Regularized LNP model for neural system identification Author: Santiago Cadena Last update: April 2019 ''' import numpy as np import os from scipy import stats import tensorflow as tf import hashlib import inspect import random from tensorflow.contrib import layers from tensorflow import losses from cnn_sys_ident...
c05eec79c9948cc33507755b1eee7c22ba293b12eb228beb7c006e2c46a997e4
Python
2,155
57
from pkgutil import ImpImporter import pgl import paddle import math import numpy as np class DualDataLoader(object): def __init__(self, data_2d, data_3d, batch_size, shuffle=False): ''' Load data ''' self.data_2d = data_2d self.data_3d = data_3d self.batch_size = batch_size...
070d0228a9be722f69a041cc70030ec12054f2d9fe44b8756d36e57263536265
Python
2,156
64
# Demonstrates interoperability of the nfp preprocessing methods with the spektral GNN # library (https://graphneural.network/). Specifically follows the `BatchLoader` example # for QM9 prediction shown here, https://github.com/danielegrattarola/spektral/blob/ # master/examples/graph_prediction/qm9_ecc_batch.py import...
2401674f845b3ed1761348365f8fd955c4e620d3a5e436e80c3ff32a4ac7f83e
Python
2,156
49
import unittest from carbontracker.components.cpu.sim_cpu import SimulatedCPUHandler class TestSimulatedCPU(unittest.TestCase): def test_simulated_cpu_initialization(self): handler = SimulatedCPUHandler("Intel Xeon", 150.0) self.assertEqual(handler.cpu_brand, "Intel Xeon") self.assertEqual(...
6c6eff9bc7e1ac34261f273c6dbbb0cfcd8f3adbc592d20f5e911b4fbcc8c85d
Python
2,156
57
# skip test: data unavailable """Compute DSS on Alex's Toolbox demo data""" from eelbrain import * # If the raw file is already filtered, the events can be loaded directly with # the filename ds = load.fiff.events('DATA/R2290_HAYO_P3H_1-8-raw.fif') # select the desired events ds = ds.sub("trigger == 167") # add MEG t...
d46341be8438b49e852ba45911d5e45ba88c87af9f91ff9ebda22be9585a11ae
Python
2,156
80
""" Entry point for the UI software SimplyFire - Customizable analysis of electrophysiology data Copyright (C) 2022 Megumi Mori This program comes with ABSOLUTELY NO WARRANTY 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 F...
0f5fb4052668f44c2a2d5cdaa3205d1dba6028f3af604780ecd2c30d7935c7c9
Python
2,157
62
from __future__ import division import unittest import numpy as np from wyrm.types import Data from wyrm.processing import spectrum from wyrm.processing import swapaxes class TestSpectrum(unittest.TestCase): def setUp(self): # create some data fs = 100 dt = 5 self.freqs = [2, 7...
47ae3f513c966abc6ed55a005de09f6cb7ba2afe366b97d77e3c921fae15008b
Python
2,157
65
import os import json import ssl from urllib import request from urllib.error import HTTPError from time import sleep class PFamConnector(): def __init__(self) -> None: self.base_url = 'https://www.ebi.ac.uk:443/interpro/api/entry/pfam/structure/PDB/' def from_pdb(self, ...
58b0207f6441cbaa1aa8928f6d90409971cd8116d73a602a39bd949744aad13a
Python
2,157
74
import cv2 import numpy as np class Camera: def __init__(self): ''' Initialize the camera ''' self.snapshot_size = (1024, 1024) self.scene_size = (2048, 4096) self.degrees_per_pixel = 0.087890625 self.eye_pos = np.array([0.0, 0.0]) self.target_locatio...
80c9f7cdf148bc5408893be9b16339464a68e6c647cf268dee9cd29b02a1add0
Python
2,157
69
""" """ import os class Dataset(object): """Base class for dataset fetching and formatting.""" def __init__(self, task_name, dataset_dir=None, url=None): self.task = task_name self.dataset_dir = dataset_dir self.url = url self.train = None self.test = None se...
d17a360e382ef7047cf6cba1402c94ed3681bf0e363aed13fbde32bfdfd0ad2d
Python
2,157
70
# ----------------------------------------------------------------------------- # Copyright (c) 2013, The Deblur Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # -------------------------------------------------...
04c2de3fe03294c1f07976cb36348dc8d5248a6621379aac2e0327bc65ba9069
Python
2,158
76
# This example requires the following dependencies to be installed: # pip install lightly # Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import torch import torchvisi...
55fabc558dd1d8c634a8bd21ea0d3de112e9867953b77646c8a765f42f51106f
Python
2,158
81
""" Tests for the ethoscope-light CLI. """ import io import json from unittest.mock import patch import pytest from ethoscope.hardware.interfaces import light_cli from ethoscope.hardware.interfaces.light_daemon import LightDaemonUnavailable class _FakeClient: def __init__(self, *_, **__): self.calls = ...
9574d440a6bf310a40490cc1e17ffeffd65029ec454a4533e3d26a0dcf9b3330
Python
2,158
65
# Mossy layer at 0 deg from os.path import join import numpy as np import os import pandas as pd from library.comput_utils import cal_hd_np from library.params import ParamsHolder from library.shared_vars import sim_results_dir from library.utils import save_pickle from library.simulation import simulate_SNN analysis...
c6c2db6920ef95050881919ff873ab4088db51901f16787e7c8944a954f89911
Python
2,158
88
import sys import collections from scipy import stats import math import os #factor = 1 def cal_RT_value(mutations, factor): dict_file = collections.defaultdict(lambda :0) with open(mutations) as f: for line in f: line = line.strip('\n').split('\t') if len(line) == 1: continue else: chrID = line...
cf856c8d0b41d2b0756eccf4cfede54049889f32fa0246505943ddbf720165af
Python
2,158
64
# Custom RESNET based on RCAN and SRGAN Code import keras import model_builder # === ResNet === def _get_spatial_ndim(x): return keras.backend.ndim(x) - 2 def _get_num_channels(x): return keras.backend.int_shape(x)[-1] def _conv(x, num_filters, kernel_size, padding='same', **kwargs): n = _get_spatial_ndi...
d887b1b8b76040617f7d860235f480c46bfafee6a8fd7f40d8b8cfbccf2abf7e
Python
2,158
56
"""Wrapper to enforce the proper ordering of environment operations.""" import gym from gym.error import ResetNeeded class OrderEnforcing(gym.Wrapper): """A wrapper that will produce an error if :meth:`step` is called before an initial :meth:`reset`. Example: >>> from gym.envs.classic_control import ...
df13add661c278b710257b61bbcf0c3bb6f114a7b2e182709cf41452d09485d9
Python
2,158
80
import numpy as np import scipy import scipy.spatial # calculate dihedral angles defined by 4 sets of points def get_dihedrals(a, b, c, d): b0 = -1.0*(b - a) b1 = c - b b2 = d - c b1 /= np.linalg.norm(b1, axis=-1)[:,None] v = b0 - np.sum(b0*b1, axis=-1)[:,None]*b1 w = b2 - np.sum(b2*b1, axis...
2ed6051d2d5c862abcee6b8d188cca71653b1664d0062e5437ebebe2f7688a11
Python
2,160
60
import time import pandas as pd from keras import models, layers, optimizers, backend as K from keras.callbacks import EarlyStopping import numpy as np import tensorflow as tf import optuna # Load datasets def load_data(path, skip_cols=5, drop_pattern='EEE', target_cols=(3,5)): data = pd.read_csv(path, d...
c75f4bee6522413af2cd24e3161f26adbe85781ee3cc3948bd761e978ca00631
Python
2,160
75
import numpy as np import sympy as sp from scipy.integrate import odeint from . MarkovModel import MarkovModel from . import common from numba import njit class LinearModel(): """ A simple linear model which mocks some of the functions in MarkovModel. Used for testing and debugging. """ n_par...
746db12535848d1731c8a4ece40ec31723613b9d3eed42a904869615f9b21ff3
Python
2,162
82
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created in July 2019 @author: Nathan de Lara <nathan.delara@polytechnique.org> @author: Thomas Bonald <bonald@enst.fr> """ from typing import Optional import numpy as np from scipy import sparse from sknetwork.utils.neighbors import get_degrees def get_membership(l...
be27be2f6f9d0105daa181f5257b16e5426afe26963bfceb243bc3eebab7f4eb
Python
2,162
54
"""Every olfactor states how it reaches locomotion, rather than inheriting it. `brute_force` selects between the two couplings of the olfactory sensor: False feeds the turner, so the animal steers up the gradient; True suppresses that output and only interrupts locomotion when concentration falls. `ModuleDB.module_co...
4747362afcfaf1e7a2986c41b6c36ac237ef3df8c9971d4fa242407fa6ba215b
Python
2,163
53
import sys from OscopeBootstrap import qvalue from OscopeBootstrap.create_edge_network_represention import create_edge_network_representation from OscopeBootstrap.SyntheticDataset import GetSimISyntheticData, true_adj_matrix from OscopeBootstrap.oscope_tf import bootstrap_hypothesis_test, get_accuracy, get_metrics_for_...
602a0a3268acf01b600925bcb318ef81ce1be04a61514e48c267f5b79620efea
Python
2,163
71
# This example requires the following dependencies to be installed: # pip install lightly # Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as p...
e823a6750a3071c9363d012d58ab656ee33a30b5e56592c036d882e800a8c2fc
Python
2,163
65
# -*- coding:utf-8 -*- import os import random import math import copy from tqdm import trange import numpy as np import predict_model import torch import torch.nn as nn import torch.optim as optim import re class PolicyGradient(object): """ policy gradient""" def __init__(self, gen_loader, beta=0, score_up=...
2cc4f198737685ae6230edb965d04e18b03adcc687e9835d36a91a1e3ffc1ba3
Python
2,164
70
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Written by Bin Xiao (leoxiaobin@gmail.com) # ------------------------------------------------------------------------------ from __future__ import absolute_import from __future...
98dc972716b3a3b0dfbbc4b442d30c6c5fefefb95d6325d5254e488e3b2d82d6
Python
2,164
77
from typing import Optional, Union from anndata import AnnData import pandas as pd from pathlib import Path import os def positions( adata: AnnData, position_filepath: Union[Path, str] = None, scale_filepath: Union[Path, str] = None, quality: str = "low", copy: bool = False, ) -> Optional[AnnData]...
b3ebc93ec295e7cc46d8fb12f1b588b18455253a3d356b517c4f1971f020005a
Python
2,164
77
""" Helpful dataloaders. """ import glob import os import numpy as np from skimage.io import imread def load_data( channel_1_dirpath=None, channel_2_dirpath=None, seg_channel=0, # load_seg_outlines=False, img_glob="*.tif", seg_glob="*.npy", img_reader_plugin="tifffile", merge_cha...
297c5925b66a479c4d329e8a981669df9556840b73ed133eeebe731ee025b6b0
Python
2,165
58
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created in March 2020 @author: Nathan de Lara <nathan.delara@polytechnique.org> """ from typing import Optional import numpy as np from sknetwork.classification.base_rank import RankClassifier from sknetwork.ranking.pagerank import PageRank class PageRankClassifier...
ddaeb2890b9c3ea6a04f0b016daad1a42779dea3b3237433d61b98899b49ea37
Python
2,165
81
import pandas as pd from . import utils def concat_TDs(frames, re_index=True): """ Concatenate trial_data structures. Supports if structs don't have the same fields, missing values are filled with nan. Parameters ---------- frames: sequence of trial_data structs ex: frames=[td1, td2, ...
4404c7047da152b40f3d5344ed76a4e71cdae7584fc05a1986672a6ae6744f15
Python
2,166
67
""" This module define the class ContactDataset_per_amino_acid to predict contact """ import torch import numpy as np from scipy.spatial.distance import pdist, squareform from datasets_pre_processing.generic_dataset import GenericDataset class ContactDataset_per_amino_acid(GenericDataset): """ FINE TUNNING ON...
65b31da5627e1fe335a02a562487d277e8b83644d345cf721ecead517e1ecbad
Python
2,167
65
from imodelsx import submit_utils from os.path import dirname, join import os.path repo_dir = dirname(dirname(dirname(os.path.abspath(__file__)))) CUSTOM_CHECKPOINTS = { "financial_phrasebank": ["ahmedrachid/FinancialBERT-Sentiment-Analysis"], "sst2": ["textattack/bert-base-uncased-SST-2"], "emotion": ["...
f49cb3fdf9d5ae5d61d1ead7cc7bc8504ff35c2f61b8ee5834d2d78a8b6633f4
Python
2,167
65
# -*- coding:utf-8 -*- import os import random import math import copy from tqdm import trange import numpy as np import predict_model import torch import torch.nn as nn import torch.optim as optim import re class PolicyGradient(object): """ policy gradient""" def __init__(self, gen_loader, beta=0, score_up ...
6083b24b93cc91a23e28b4e357e7a74f99cea81c7e40f9a6eef3271e46110c27
Python
2,168
73
import re import numpy as np from imfun.external.physics import Q from imfun.core import units from imfun.core.units import QS def parse_property(line): l = line.strip().replace('"','') name, value = l.split('\t') values = value.split(',') return name, list(map(str.strip, values)) def from_brackets(s...
84f3db18a0f1362be3001cdfe96394f9ebfef69e6824fb90b9009489bfbb7c51
Python
2,168
69
from keras.src import backend from keras.src.api_export import keras_export from keras.src.layers.merging.base_merge import Merge @keras_export("keras.layers.Add") class Add(Merge): """Performs elementwise addition operation. It takes as input a list of tensors, all of the same shape, and returns a singl...
4f35d0895635946fc22bd67bf86fecd85257feaefd01f58ddcf29516d3bfd7c8
Python
2,169
74
"""Phase 5(c): exception safety -- pop on exception.""" from __future__ import annotations import pytest import torch import torchlens as tl from torchlens import _state class RaisingChild(torch.nn.Module): """Child that raises after entering a nested module.""" def __init__(self) -> None: """Init...
25c7f3ec97579c5d2f83034e4377c11d703f8fa06f5fd1d9323743758e34ee12
Python
2,170
73
"""Tests for the curated Explore scenario catalog.""" from __future__ import annotations import pytest from larvaworld.portal.explore.scenarios import ( CATEGORY_ORDER, CATEGORY_TITLES, SCENARIOS, scenario_by_id, scenarios_by_category, validate_scenarios, ) def test_catalog_is_valid_standal...
30df94eb38402c7de667bd2c421bd0f418102da8c828017ed9553708a1abf7f1
Python
2,170
61
"""The module describes the ``meminfo`` job metrics plugin.""" import re from typing import Any from galaxy import util from . import InstrumentPlugin from .. import formatting from ..safety import Safety MEMINFO_LINE = re.compile(r"(\w+)\s*\:\s*(\d+) kB") # Important (non-verbose) meminfo property titles. MEMINFO_...
bd5661821f538e77a847c7a748c9e9f1007007864333b34cc3aed88579e75cbc
Python
2,170
49
import torch import torch.nn as nn class MMD_loss(nn.Module): def __init__(self, kernel_type='linear', kernel_mul=2.0, kernel_num=5): super(MMD_loss, self).__init__() self.kernel_num = kernel_num self.kernel_mul = kernel_mul self.fix_sigma = None self.kernel_type = kernel_ty...
100cf2ab39922cff76b42b491c7bb9299bbfd29e178206a7d25b31073a2381ca
Python
2,171
77
# --- THIS FILE IS AUTO-GENERATED --- # Modifications will be overwitten the next time code generation run. from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Line(_BaseTraceHierarchyType): _parent_path_str = "quiver.selected.marker" ...
3f18e8aa8997b0a32420773c455c5defd3c7b36a61b607826ed2442286f32d1b
Python
2,171
69
"""Smoke tests for train-mode capture APIs.""" from __future__ import annotations import pytest import torch import torchlens as tl from torchlens.options import CaptureOptions from .conftest import TwoLayerMlp def test_trace_train_mode_basic(two_layer_mlp: TwoLayerMlp) -> None: """trace backward_ready keeps ...
59d0364ea3025103f98e82b0909f01f7c6eac504431d77c564c4d4d0b1f77ba9
Python
2,171
55
import os import glob import argparse from tqdm import tqdm import multiprocessing from pathlib import Path from subprocess import check_call, CalledProcessError # Arguments parser = argparse.ArgumentParser(description='Build up complete dataset.') parser.add_argument('--wsj_root', default=None, type=str, ...
18ad5d083d7d3223ea7de072541178d885850011310bacae8d445b3fac2fa322
Python
2,172
70
"""test linking against pysam. """ import os import pytest import subprocess import pysam from TestUtils import LINKDIR if not os.environ.get("PYSAM_LINKING_TESTS"): pytest.skip("enable linking tests by setting PYSAM_LINKING_TESTS environment variable", allow_module_level=True) def check_import(statement): ...
3762f3db4fff1d2aab5eed4ea353a047cf627c9d29615df949232397efb02c89
Python
2,172
77
import logging import yaml import copy import argparse from bson.objectid import ObjectId from pymatgen.core import Molecule from atomate.qchem.fireworks.core import FrequencyFW from atomate.common.powerups import add_tags from fireworks import LaunchPad, Workflow from instance_mongodb import instance_mongodb_sei ...
bf5307837419e45c95f57e858756d460789bf0243dab947851efdd1533a4bc2d
Python
2,174
81
"""Run DTox with different seeds""" import logging import os from sys import argv import pandas as pd import dtox import dtox_interpret import targettox logging.basicConfig(format="%(levelname)s [%(asctime)s] %(message)s", level=logging.INFO) # constants AO_COL = 'assay_outcome' START_DIR = os.g...
40724a37b8538b7331a3cb2e884af2906b155fcb2a01e239c2e787aa8c02393e
Python
2,176
60
"""Microbench: O(64) linear scan vs O(1) LUT in ``AminoAlphabet.translate``. Not collected by pytest (filename is not ``test_*``). Run explicitly to measure the speedup on your hardware:: python tests/bench_translate_lut.py Speedups are data- and hardware-dependent; this script reports measured numbers rather th...
ac9d27b68833547a731851fd865a6f22986acdf4984e97da1b4b3937344b9551
Python
2,176
69
# 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...
c45a12c3824a9fa3440e55f97917bf4a0709dc8ba200691d2ddecdaabb0ca59e
Python
2,176
56
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras from utils import DataGenerator tf.config.experimental.enable_tensor_float_32_execution(False) inputKeys = ["rho"] outputKeys = ["c1"] # Read simulation data from the prepared files simData = np.load("data/HS.np...
1f43e23163bcc0a135d3cd7ddf4acbf95f7cbb93c1b64cde0f47cd92dca5c2eb
Python
2,177
65
"""Tests for xcp_d.utils.plotting module.""" import os import numpy as np import pandas as pd from xcp_d.utils import plotting def test_plot_fmri_es(ds001419_data, tmp_path_factory): """Run smoke test on xcp_d.utils.plotting.plot_fmri_es.""" tmpdir = tmp_path_factory.mktemp('test_plot_fmri_es') prepro...
2600e0ba433c694fbe0734b910be21c304e60f358b739beabd99542cbfee1a18
Python
2,177
49
import unittest from carbontracker.components.gpu.sim_gpu import SimulatedGPUHandler class TestSimulatedGPU(unittest.TestCase): def test_simulated_gpu_initialization(self): handler = SimulatedGPUHandler("NVIDIA A100", 400.0) self.assertEqual(handler.gpu_brand, "NVIDIA A100") self.assertEqua...
19883b2f5a4a25780ad004bbabe45240469d0fca91ebb69076411a09583a99de
Python
2,178
73
""" File: logger.py Created: 2020/10/16 Last Changed: 2021/09/22 Author(s): M.Vochteloo Copyright (C) 2020 University Medical Center Groningen. A copy of the BSD 3-Clause "New" or "Revised" License can be found in the LICENSE file in the root directory of this source tree. """ # Standard imports. impo...
3bc60eaa47ef7c38c3eca837f6cbc1b02a6cdc8ac256de8a64a033c5de89a496
Python
2,179
47
from ovseg.data.DataBase import DataBase from ovseg.data.SegmentationDataloader import SegmentationDataloader from ovseg.data.SegmentationDoubleBiasDataloader import SegmentationDoubleBiasDataloader from os import listdir from os.path import join class SegmentationData(DataBase): def __init__(self, augmentation=...
507b675ab8142cfd34b3a4b3bd36bd9acab074a3ab9676da3fe6c3cf106fc08a
Python
2,179
57
#!/usr/bin/env python '''Grab all the "Sucess" examples from the database, look if any of the directories exist. If they do, reval them and update the database''' import sys, re, MySQLdb, os, argparse, subprocess from MySQLdb.cursors import DictCursor parser = argparse.ArgumentParser(description='Fix evaluation of ...
913287d7fe0bb782d3732b9b793fe1fcdc36c5b90ccfb97e78fd80f53b834454
Python
2,179
65
"""7. Test with ICNet Pre-trained Models for Multi-Human Parsing ====================================== This is a quick demo of using GluonCV ICNet model for multi-human parsing on real-world images. Please follow the `installation guide <../../index.html#installation>`__ to install MXNet and GluonCV if not yet. """ i...