sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
2e9f1327f4e66b6dc8e6e9575af86496146a12f09a87dd8544adf8e3e1be32cd
Python
4,816
121
#!/usr/bin/env python3 from BeattieModel import BeattieModel import argparse import os import common import numpy as np import logging import matplotlib.pyplot as plt import regex as re import pandas as pd import common import myokit as mk import cProfile from BeattieModel import BeattieModel def main(): mean_par...
a2b89f656c88389946f78c4b3130520bdcfb7623d8409174dc853c2bf525e0a8
Python
4,817
135
import logging from dataclasses import dataclass from typing import Optional import jwt from dependency_injector.wiring import Provide from fastapi import Depends, HTTPException from fastapi.security import APIKeyCookie, HTTPBearer from carbonserver.api.errors import AuthenticationError from carbonserver.api.services...
ae6de04b915514d83dc93bebf726493db766e9c8e2d2d0fafc909a8f968c9ea5
Python
4,819
125
import numpy as np from neurogym.core import TrialEnv from neurogym.utils import spaces # TODO: are trials counted correctly in this task? # TODO: No longer maintained, use existing task to build this task class IBL(TrialEnv): metadata = { # noqa: RUF012 "paper_link": "https://www.sciencedirect.com/sc...
d74edf89f5a61c4b28e86c8d873bc706584c1dae19aeb40b55ee7c4d137d1d77
Python
4,820
119
import yaml import torch import torch.nn as nn from argparse import Namespace from collections import defaultdict, Counter from bioseq2seq.inputters.inputter import _load_vocab, _build_fields_vocab, get_fields, IterOnDevice from bioseq2seq.inputters.corpus import ParallelFastaCorpus, ParallelTextCorpus from bioseq2seq....
1c88430511b577456ccfecf9e9826958da2257979fc935e1172eb788120a306a
Python
4,822
158
from collections import Counter import functools import itertools import tqdm import torch import numpy as np from permacache import permacache, drop_if_equal from modular_splicing.dataset.basic_dataset import basic_dataset from modular_splicing.evaluation.run_evaluation import evaluate_model_on_data from modular_spl...
eee62161b3676aea386f2b758b2ac5ec9ef13802d760a53a90949f618e1b586d
Python
4,822
130
""" 1D diffusion simulations with NEURON 8.2.6: 1D cuboid Last updated: .2026 Author: Saana Seppälä   ### Description   This script performs one-dimensional calcium diffusion simulations using the NEURON reaction-diffusion (RxD) framework. A cylinder morphology is represented as a single NEURON section discretized into...
d7307f1b0e35e8dfc398243639922e10a7ba85bb98a01dae784eee9c2fb17d9b
Python
4,823
130
"""Manifest <-> metadata integrity anchors (AUD-CODE 3.0b). ``manifest.json`` and ``metadata.pkl`` are written together by one writer, so the facts both carry must agree at load or the artifact has been edited, truncated, or spliced from two sources. The loader compares: * the ``tlspec_version`` stamp -- the manifest...
18cdfc8a96f479c56929f78e07d9db552c351455aecabfcf5fe5cb2a1d5bd3ba
Python
4,824
134
import copy from typing import List, Tuple import torch from pytorch_lightning import LightningModule from torch import Tensor from torch.nn import Identity from torchvision.models import resnet50 from lightly.loss.tico_loss import TiCoLoss from lightly.models.modules.heads import TiCoProjectionHead from lightly.mode...
2e5d6029a7e6ec06ea43f487e13133cabffb494c7b319c7b9875f8a67ebefe80
Python
4,824
174
import pytest import rpy2.rinterface as rinterface import rpy2.robjects as robjects import array # TODO: move to common module for testing def almost_equal(x, y, epsilon = 0.00001): return abs(y - x) <= epsilon def test_init_invalid(): with pytest.raises(TypeError): robjects.vectors.IntArray(3) de...
4c0985871aa8bb40b4c1a7cc04c6dee9725dc81053846272fbc6479f1bd6fc1d
Python
4,826
140
import threading import time import gc # garbage collection from Utilities.common_packages import np from Configurations import config as cfg from Configurations import CNN from tensorflow.keras.utils import Sequence # define indexes idxSimChaNum = cfg.EnumSimParams.chanum.value class DataGeneratorFD1T(Sequence): ...
9796f9e2268862ae833ece6467d2571e74d6ffcbee7470e8a3d5c819da469313
Python
4,827
99
import torch from torch import nn from torch import Tensor from collections import OrderedDict import numpy as np class GetDensity(torch.nn.Module): def __init__(self,rs,inta,cutoff,nipsin,norbit,ocmod_list): super(GetDensity,self).__init__() ''' rs: tensor[ntype,nwave] float inta:...
82255dab12b9ab35bf3e24f1b61b4ebcd8e4b14e2e168351209eb8731f2573e4
Python
4,828
144
"""Pins for the trace inventory surfaces: ``sites_table`` and ``bill_of_materials``. Both are read-only rollups of already-captured facts (DOCUMENTED-UNSTABLE spellings). ``sites_table`` follows the L1 consumer matrix: a legacy keyless artifact refuses ``site_key_unavailable``, never a silently empty table. """ from ...
9bf51c2ff172b62cc1bb5d11caa0816a0e7123eafc49e1f4fc60267303054655
Python
4,828
126
import os import numpy as np import math from tensorflow.keras.utils import Sequence from tensorflow.keras.preprocessing.image import ImageDataGenerator from imageio import imread from scipy.special import expit from skimage.transform import resize class SegmentationSequence(Sequence): def __init__(self, imag...
b28d18c077d7861de7204f0d56b5ad21323773ae944b0f91cf1e1a32e84c5c29
Python
4,828
131
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu> import numpy as np from numpy.testing import assert_array_equal import pytest from eelbrain.testing import assert_dataobj_equal from eelbrain import Categorial, Factor, NDVar, Scalar, UTS, Var, datasets, table, combine def test_cast_to_ndvar(): "Test table...
1161cd535acc2e8df68258028e7690a4aba3481a638e51d372ba0ac38be19ba0
Python
4,829
144
import glob import numpy as np import argparse import yasa import matplotlib.pyplot as plt from mp_dip.utils.utils import read_raw from mp_dip.obci_readmanager.signal_processing.tags import tags_file_writer as tags_writer TAG_CONVERT_DICT = {'N1': "1", 'N2': "2", 'N3': "3", ...
4cfacbb34b1406ec86e92cd9fcde531ffbc4dc733daa555e9883c56de24bd0c9
Python
4,829
152
""" Unit tests for utils/img_proc.py and utils/video.py. Tests merge_blobs contour merging and video file listing. """ import os import shutil import tempfile import unittest import cv2 import numpy as np from ethoscope.utils.img_proc import merge_blobs from ethoscope.utils.video import ( ensure_video_directory...
d0ab4971d7d635f071807d6a291cefb75966b50674d5645e3470d454f93e945f
Python
4,831
126
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import absl.app import argparse import numpy as np import wave import csv import os import sys from deepspeech import Model from deepspeech_training.util.evaluate_tools import calculate_and_print_report from...
8bd409b922ae68c41c4475c103212f849f22632ea07c411fa0360987012ab173
Python
4,833
151
"""Policy-level tests for MLX preview option honesty.""" from __future__ import annotations from pathlib import Path from typing import Any import pytest from torchlens.backends import BackendUnsupportedError from torchlens.backends._options import ( MLX_EXTRA_KWARG_POLICY, MLX_PREVIEW_TRACE_OPTION_POLICY, ...
c29f2c9ceb45361ce4bbf4ae2a89b4557b8fa732bcd9c7642a9fded7ec6e6c19
Python
4,833
122
import numpy as np import pytest import gym from gym import envs from gym.envs.registration import EnvSpec from tests.envs.utils import mujoco_testing_env_specs EPS = 1e-6 def verify_environments_match( old_env_id: str, new_env_id: str, seed: int = 1, num_actions: int = 1000 ): """Verifies with two environm...
a54917620e4c3360794bec2ee1d87528445f4322f2fd65cea24535e747e52541
Python
4,835
165
import os import glob import seaborn as sns from os import PathLike from typing import Optional, Union, Sequence, Mapping import matplotlib.pyplot as plt from ._utils import ( _plot_seaborn, many_logs2pandas, _save_fig, ) from .. import settings def metric_curve( log_path, metric, hue: Optiona...
a7785be5044463a497d0c9617eb7983b3eab35cc6a3ec8acfc0912af3def5bf8
Python
4,836
153
import argparse import json import warnings import pandas as pd from mlxtend.frequent_patterns import association_rules, fpgrowth from mlxtend.preprocessing import TransactionEncoder def main( inputs, infile, outfile, min_support=0.5, min_confidence=0.5, min_lift=1.0, min_conviction=1.0, ...
e585610c83d861bc35c3eeba95a2a56a2c7cc97f96da56a9ff42a838f082e0dd
Python
4,836
150
"""Adapted from: https://github.com/https-deeplearning-ai/GANs-Public.""" import torch import torch.nn as nn from pl_bolts.utils import _TORCHVISION_AVAILABLE from pl_bolts.utils.warnings import warn_missing_pkg if _TORCHVISION_AVAILABLE: from torchvision.models import vgg19 else: # pragma: no cover warn_mis...
18431315395660c49282c4f05d2c739f913fd35f1b727928995ab83950dba975
Python
4,838
181
#pomocni fajl za evaluaciju LSTM modela # pomocne funkcije za evaluaciju modela i za metrike #osnovne biblioteke import numpy as np import pandas as pd import math #LSTM: import tensorflow as tf from tensorflow import keras from keras import layers #Early stopping from keras.callbacks import EarlyS...
0f83a2c3d944c85fb11c9ddf279fd77248002c3aec0d3625b32713d69e35e7a1
Python
4,839
173
"""The ``celery shell`` program, used to start a REPL.""" import os import sys from importlib import import_module import click from celery.bin.base import CeleryCommand, CeleryOption, handle_preload_options def _invoke_fallback_shell(locals): import code try: import readline except ImportError...
175fde0508accf650e2b4bfb06a8b2be6bcfe6bbba55f0efa1e8e52539419293
Python
4,839
151
__author__ = "diana" import cv2 try: CV_VERSION = int(cv2.__version__.split(".")[0]) except Exception: CV_VERSION = 2 import logging import numpy as np from ethoscope.core.roi import ROI from ethoscope.roi_builders.roi_builders import BaseROIBuilder class ArenaMaskROIBuilder(BaseROIBuilder): def __i...
5f32d713e7bedd09cf39f8e49a6fd2b808809f49cb9cd6d95fcf6682201cef19
Python
4,839
138
"""F29: the tiered CLI -- tier-0 torch purity, exit codes, CI gates. Tier-0 verbs must leave torch out of ``sys.modules`` (the memo's purity test); exit codes are a closed set CI can branch on; ``--fail-on`` gates READ existing result records, never recompute. """ from __future__ import annotations import json impor...
8ab28e8e241d2f268dc5495503171a85ea19c27c7e804075ffbeb95df1bb06e6
Python
4,839
161
import dataclasses import os from prometheus_client import ( CollectorRegistry, Counter, Gauge, delete_from_gateway, push_to_gateway, ) from prometheus_client.exposition import basic_auth_handler from codecarbon.external.logger import logger from codecarbon.output_methods.base_output import BaseOu...
b362eaa61764eecfb2b5a7487ddfd6d95b83474de853bb496d12f63506baceb5
Python
4,840
136
"""THE summary pin-derivation script (F08; summary memo section 4, binding). Numbers discipline: every count and total in the summary memo's tables is RE-DERIVED at build time by this ONE committed script against pinned versions -- the panel's tables establish structure, never byte-final constants. The derivation basi...
b51c535e4b41acd4679f6dffd021dbf432e636a467aee66f73beac7a965c9375
Python
4,840
64
from argparse import Namespace,ArgumentParser def meta_train_parse_args() -> Namespace: parser = ArgumentParser() parser.add_argument("--meta_batchsz",type=int,default=15,help='the meta-learning batch size in meta-training') parser.add_argument("--meta_lr",type=float,default=1e-3,help='the meta-learning ...
9195f793f6ef24f943cd91f03fd0fb1b97440e00d1efd9d5df08552ecf348e3b
Python
4,841
129
## here I used dbscan_.py from sklearn as a reference import numpy as np from . import metrics from .Cluster_ import Cluster def dbscan(points, eps, min_pts, distances=None,dist_fn='euclidean',verbose=True): """ Implementation of DBSCAN density-based clustering algorithm Parameters: - `points`: input ...
12a5f298063a76f706fccdf7004d9571cc99f9f1402fe9e7dd3d051c9f8f1dac
Python
4,842
119
from typing import ClassVar import numpy as np import torch import torch.nn as nn from torchvision import models, transforms class Model: _WEIGHTS: ClassVar[dict] = { ("resnet50", "v1"): models.ResNet50_Weights.IMAGENET1K_V1, ("resnet50", "v2"): models.ResNet50_Weights.IMAGENET1K_V2, ("vg...
3909eacb7c714920bdd15c949bcce0ace81d05816b6431813a723ee2d31b83cf
Python
4,842
100
from unittest import TestCase, mock import numpy as np import spateo.segmentation.label as label from ..mixins import TestMixin, create_random_adata class TestLabel(TestMixin, TestCase): def test_watershed(self): X = np.zeros((10, 10)) X[:3, :3] = 1 X[7:, 7:] = 1 mask = X > 0 ...
7903735173fd74228b4f7bb5de18721441dd4734e6c278c33abbb63fe053a04e
Python
4,842
147
from math import sqrt from model import common import torch from torch import nn import torch.nn.functional as F def make_model(args, parent=False): return DFSRCNNPS(args) class DFSRCNNPS(nn.Module): """ Args: upscale_factor (int): Image magnification factor. """ # def __init__(self, ups...
839190f26da2d45afac57a1e0c569fa715a0ab6552edae0ccecc6ccbab010b2f
Python
4,842
115
""" The pyrho fused-LASSO objective function. Classes: RhomapObjective: The objective function for a given dataset. """ from __future__ import division import numpy as np from scipy.sparse import dok_matrix class RhomapObjective(object): """ The fused-LASSO objective function for a given dataset. A...
6c923217aaf218b20279e5d0bea61c7b4580ce069e68f982e6184f08c683b6fa
Python
4,843
99
# pytest unit tests for sct_extract_metric import csv import numpy as np import pytest import logging from spinalcordtoolbox.scripts import sct_extract_metric from spinalcordtoolbox.utils.sys import sct_test_path logger = logging.getLogger(__name__) @pytest.mark.sct_testing def test_sct_extract_metric_against_gro...
187938728a3231e20c1c1a9663831e1e75d1b25e8e2fdd910f43f2b70b68daf3
Python
4,846
191
"""GCNN-P4: group-equivariant CNN over translations and 90-degree rotations. Paper: Group Equivariant Convolutional Networks, Cohen and Welling, ICML 2016. The defining primitive is group convolution on P4, the group generated by image translations and rotations by 0, 90, 180, and 270 degrees. This compact model lif...
514f19369f55f146e3df3840fdcbf8ee7860169882b38e9c8097cfe39c96dcd3
Python
4,846
123
"""DeviceRef vocabulary conformance (R17-2). ``ir/refs.py`` documents ``DeviceRef.backend`` as the HARDWARE device class (``"cpu"``, ``"cuda"``), never the framework namespace ``DtypeRef.backend`` carries. tf and paddle used to write ``DeviceRef(backend="tf"/"paddle", ...)`` directly; every backend must now route thro...
f673c9741a6d304840cbb7e1ef98bf36ca391fa31f6ebf554ac0893bb1053305
Python
4,846
139
import zipfile from pathlib import Path import numpy as np import pytest import zarr from zarr.storage import LocalStore, MemoryStore, StorePath, ZipStore from ome_zarr import OMEZarrImage, OMEZarrMultiscale from ome_zarr.data import create_zarr from ome_zarr.io import ZarrLocation, parse_url from ome_zarr.reader imp...
64fdda931c0dfe6dfb3016d8d4b563aa05fba109c2eea9d155abbe8bf396f4a9
Python
4,848
156
#!/usr/bin/env python # Created on: October 8, 2013 __author__ = "Sven Kreiss, Kyle Cranmer" __version__ = "0.1" import ROOT def getNll( pdf, data, minStrategy=0, enableOffset=True, globObs=None ): """ Generic functions to use with minimize() from BatchProfileLikelihood. """ # config minimizer ROOT.RooAbsRea...
739971d2d281bc685a3b318a9bfe2685ac27902e2f50833ce1cc2ad5a4379007
Python
4,848
192
"""Functions to compute measures of spiking activity.""" import numpy as np from spiketools.utils.extract import get_range from spiketools.measures.conversions import convert_times_to_counts ################################################################################################### ##########################...
0b4c5735b0a52aef504766470d69a58e431f70c0edeb3341670cca24db4006fb
Python
4,849
170
import itertools from mock import Mock, patch import numpy as np from numpy import testing as npt from scipy import stats from tns.astrocyte.section import SectionSpatialGrower from tns.generate.tree import SectionParameters POINT_CLOUD_POINTS = np.array([ [0.0, 0.0, 0.0], [0.1, 0.1, 0.1], [0.2, 0.2, 0....
15185a8fa0afb0029f021d8b545b24fd6b58cd40191a4074a58d69dd05c953e1
Python
4,850
127
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
7672b3bd57f9a35599e2b73352e7b94b28f7e88c7765071041f2a82e06f089c3
Python
4,852
132
""" Author: Bruno De Santi, PhD Affiliation: Multi-modality Medical Imaging Lab (M3I Lab), University of Twente, Enschede, The Netherlands Date: 20/09/2023 Description: Deformation field regularization functions Acknowledge: The code was adapted from J. M. Wolterink, J. C. Zwienenberg, and C. Brune, “Implicit Neural...
cdbb626ded8211e12bca26ccd5e1a5dc2ed85b51176167acc7e49982f0956b31
Python
4,852
138
# coding=utf-8 # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
0083f2debc915e9d49f54d6d3e175bcab2507736663d2e8f7a9cf6bb29a260f3
Python
4,853
129
#Autor: Carlos Alberto Hernández Nava #ASVspoof2017 spectrograms 100 x 100 color import cv2, sys, os, gc import numpy as np import pandas as pd import seaborn as sns import openpyxl as pxl import tensorflow as tf from tensorflow import keras from numpy.random import randn from pandas import ExcelWriter import matplotl...
163803314568bb5399abaf1753dbc4c2ef56fbb397b2db7f34de2b5d405a702f
Python
4,853
175
import matplotlib from matplotlib import pyplot as plt from typing import Optional, Union from anndata import AnnData def plot_mask( adata: AnnData, library_id: str = None, show_spot: bool = True, spot_alpha: float = 1.0, cmap: str = "vega_20_scanpy", tissue_alpha: float = 1.0, mask_alpha...
d09470227686de4836ff2ea6f7f14b727d3687183d68f5c0936abc9f0f4e7caf
Python
4,854
138
# coding=utf-8 # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
232414214d27f32310d6a8b46ef9fc047ba17ca338e9b22352627f9ddf76575c
Python
4,855
117
#!/usr/bin/env python # -*- coding: utf-8 -*- # # In case you've sequenced the same sample multiple times, use this script to # merge those samples together and then rmdup the pooled data. # WARNING: This assumes you've used the pipeline up to this point, and have pre-sorted & fixmated .bams. # Why use this script, wh...
361993053dcd50812541bb6e518e1a1b59897f22ade003a6081eb6d1a2e9681d
Python
4,858
111
""" Author: Derek van Tilborg -- TU/e -- 09-06-2022 Script to replicate the benchmark results """ import tensorflow as tf physical_devices = tf.config.list_physical_devices('GPU') tf.config.experimental.set_memory_growth(physical_devices[0], enable=True) from MoleculeACE.models import RF, SVM, GBM, KNN, MLP, GCN, ...
e38758cead2f4f4905cb86d427eaca14f3062d67a687b0790f8fea3030c70997
Python
4,858
266
#!/usr/bin/env python '''Generate models for affinity predictions''' # variables: # kernel size: 3 or 7 # width: [32,32,32] [64,32,32] [64,32,16] [32,16,16] # pool or not # stride 1,2,3 (>1 if no pool) modelstart = '''layer { name: "data" type: "MolGridData" top: "data" top: "label" top: "affinity" incl...
00acb0c937330600cbba5c1de903f167da5d5c5e8a9b5e315767978d462567dc
Python
4,860
147
import matplotlib.pyplot as plt import torch from torch import nn from rectipy import Network import numpy as np device = "cpu" dtype = torch.float64 # model parameters node = "neuron_model_templates.spiking_neurons.lif.lif" N = 10 k = 2.0 tau = np.random.uniform(10.0, 20.0, size=(N,)) tau_s = 5.0 eta = 10.0 v_thr = ...
7c6aeed289f43a188f3a0cdb58507bdd8fa7e01e722bd2e028044bb65290a827
Python
4,860
147
""" Statistics calculation utility """ import time import math import sys from bioseq2seq.utils.logging import logger class Statistics(object): """ Accumulator for loss statistics. Currently calculates: * accuracy * perplexity * elapsed time """ def __init__(self, loss=0, n_words=0,...
914186a69b038175777598d46861dda61bdf2728d8a600b76c43ae36428ff53d
Python
4,860
147
import matplotlib.pyplot as plt import torch from torch import nn from rectipy import Network import numpy as np device = "cpu" dtype = torch.float64 # model parameters node = "neuron_model_templates.spiking_neurons.lif.lif" N = 10 k = 2.0 tau = np.random.uniform(10.0, 20.0, size=(N,)) tau_s = 5.0 eta = 10.0 v_thr = ...
34fba8111fc237842821df02678b38055d35587346642b7a7c4b4976ff9554cd
Python
4,861
176
import matplotlib from anndata import AnnData from matplotlib import pyplot as plt def plot_mask( adata: AnnData, library_id: str | None = None, show_spot: bool = True, spot_alpha: float = 1.0, cmap_name: str = "vega_20_scanpy", tissue_alpha: float = 1.0, mask_alpha: float = 0.5, spot_...
90822f9eac208548b7914ef0c3f745d2c93e0b5f5a6877a5a4e1a562623bcd14
Python
4,861
157
import tensorflow as tf import tensorflow_datasets as tfds from IPython.display import clear_output import matplotlib.pyplot as plt from time import gmtime, strftime from unet2 import create_model_UNet2 # network model parameters OUTPUT_CLASSES = 3 INPUT_SIZE = 128 # training parameters EPOCHS = 20 BATCH_SIZE = 64...
df7d5cd2cf378a33401906d60249a2d26d18b62bce248674b7f9bb2b65966569
Python
4,861
171
import pytest import rpy2.robjects as robjects rinterface = robjects.rinterface import rpy2.rlike.container as rlc import array import csv import os import tempfile def test_init_from_taggedlist(): letters = robjects.r.letters numbers = robjects.r('1:26') df = robjects.DataFrame(rlc.NamedList((le...
1650e9603a817d02c9c6547659f9f9fb55d06988935cd18cf8477162e168c596
Python
4,862
134
from ..utils import gislib, utils, constants from ..core.trajectorydataframe import * import numpy as np import inspect def compress(tdf, spatial_radius_km=0.2): """Trajectory compression. Reduce the number of points in a trajectory for each individual in a TrajDataFrame. All points within a radius of `sp...
41389cedced3cb4a9d6f7d74c582f3a795db194c770be5d399b13de4fbb29ead
Python
4,862
114
"""Intervention honesty: the ``resample_ablate`` -> ``scramble_elements`` honest rename (edits memo row 1, decision D19; alias posture: hard rename, no alias, artifact-load compatibility KEPT). The helper is an elementwise iid scramble -- a false friend of the field's "resampling ablation" (coherent donor patching). S...
eaa27de84a44ad1f1b0baa883ec7b76793ee0973362646a7f93ebb7d5e3b2abe
Python
4,864
181
import flask def test_template_rendered(app, client): @app.route("/") def index(): return flask.render_template("simple_template.html", whiskey=42) recorded = [] def record(sender, template, context): recorded.append((template, context)) flask.template_rendered.connect(record, a...
17afd73d13382889a20a8b1007674320411ad5f405cee0e818c93644e520926e
Python
4,868
131
from conftest import get_metrics import numpy as np import pytest from pytest import approx from pyriemann.utils.distance import distance_riemann from pyriemann.utils.tangentspace import ( exp_map_euclid, exp_map_logeuclid, exp_map_riemann, log_map_euclid, log_map_logeuclid, log_map_riemann, upper, unupper...
d38dda287489a4a98bee1a60918bb73e0bd5adb85bcd0ca785ea0385258101b8
Python
4,869
124
"""grind-p3 T5.5: ``tl.fastlog.recover`` is bounded and total over hostile indexes. ``recover.py`` parsed the JSONL index and metadata with raw ``json.loads`` / ``json.load`` plus an unbounded ``read_text``: a depth-bomb line escaped the ``JSONDecodeError`` handler as a raw ``RecursionError`` out of the public ``tl.fa...
b661fe1a2e049675c9ef68d4036a474c974c02626872c8177b60552647069241
Python
4,870
131
from typing import Any, Optional import torch from pytorch_lightning import LightningModule from pl_bolts.models.detection.retinanet import create_retinanet_backbone from pl_bolts.utils import _TORCHVISION_AVAILABLE from pl_bolts.utils.warnings import warn_missing_pkg if _TORCHVISION_AVAILABLE: from torchvision....
d60381ea09bfb784bfeec8cbfe71e6415577631187278bdf87f3742519875dc6
Python
4,870
143
"""Stateful live-model ``Trace.run`` diagnostics.""" from __future__ import annotations import warnings import pytest import torch from torch import nn import torchlens as tl def test_training_mode_stateless_model_does_not_warn() -> None: """Training mode alone should not trigger the live-state warning.""" ...
ed3398074ff2b6e48096d57855f7d2eec9279ae62df2ae2b4c5a37bea3929d9b
Python
4,870
147
from pyoperant import hwio, components, panels, utils from pyoperant.interfaces import comedi_, pyaudio_ import socket _VOGEL_MAP = { 1: ('/dev/comedi0', 2, 0, 2, 8), # box_id:(subdevice,in_dev,in_chan,out_dev,out_chan) 2: ('/dev/comedi0', 2, 4, 2, 16), 3: ('/dev/comedi0', 2, 24, 2, 32), 4: ('/dev/come...
27c87c721ef335c60d015975f9d306f22fd44c2f75b4d7faf178ff4523ecafc6
Python
4,871
152
from types import SimpleNamespace import numpy as np import matplotlib import matplotlib.pyplot as plt import tqdm.auto as tqdm from permacache import permacache, stable_hash, drop_if_equal from .compute_psi import all_psi_values def directional_strand_histogram(all_table): plt.figure(dpi=200) bins = np.ar...
47d188dc8ca69702461c3e68c0e2594ab609e69269f56751587db19cd3b6402f
Python
4,871
135
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for Louvain""" import unittest from sknetwork.clustering import Louvain from sknetwork.data import karate_club, star_wars from sknetwork.data.test_graphs import * from sknetwork.utils import bipartite2undirected class TestLouvainClustering(unittest.TestCase): ...
a96c1708be2a78834543e1ea3a10a9a540f84f0b8656152b0adbdcc83ed60e1e
Python
4,871
80
#==============================================================================# # Author: Dominik Müller # # Copyright: 2024 IT-Infrastructure for Translational Medical Research, # # University of Augsburg ...
d1817c90ea94ce65639ff9c82ee9f597b264ceb6dfbd3f9cbbcd3ff892dd0780
Python
4,872
122
"""YOLO default config""" # pylint: disable=unused-variable,missing-function-docstring,bad-whitespace,missing-class-docstring from typing import Union, Tuple from autocfg import dataclass, field @dataclass class YOLOv3: # Base network name which serves as feature extraction base. base_network : str = 'darknet...
a0afc03d8a86c29b8a64918c69cd144938f7989b01f40fe6c1034e54b16c80e5
Python
4,873
100
import torch from torch import nn from torch import Tensor from collections import OrderedDict import numpy as np class GetDensity(torch.nn.Module): def __init__(self,rs,inta,cutoff,nipsin,norbit,ocmod_list): super(GetDensity,self).__init__() ''' rs: tensor[ntype,nwave] float inta:...
db95e89e1b97cf68908c30e6dafa1f2499a1a9a1a3e46005fc595e54634db1f6
Python
4,873
152
import logging import time import serial from ethoscope.hardware.interfaces.interfaces import SimpleSerialInterface class WrongSerialPortError(Exception): pass class NoValidPortError(Exception): pass class OptoMotor(SimpleSerialInterface): _baud = 115200 _n_channels = 20 def __init__(self, ...
2a852d210dd05bed01e981f303346e417e62b0724ef6227202dce6e6a98fa74b
Python
4,875
176
""" The core functionalities of the larvaworld platform """ __displayname__ = "Core library" __all__ = [ # Global registry object "funcs", # Subpackages "param", "reg", "plot", "model", "process", "screen", "sim", # Re-exported from process.dataset "ParamLarvaDataset", ...
368fff22893dd1f71b7411c4563fef231f5a89b9bb0332bf10f33c945bcaf311
Python
4,876
107
import os import re import pandas as pd import appdirs from score_behavior.score_session_manager import SessionManager from score_behavior import appauthor, appname from score_behavior.score_config import get_config_section import logging logger = logging.getLogger(__name__) class ObjectSpaceSessionManager(Session...
d9abae090fc5c8ba5fad73747b9315e137d5b7797fd46e1898ddf918cbbbf69b
Python
4,876
148
import os import numpy as np from mirp import extract_images from mirp._images.ct_image import CTImage CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) def test_median_denoiser_method(): # 3D variant data = extract_images( write_images=False, export_images=True, image_export_...
ec0a2b0354e103f3a143c954275746e2504ea089cbefe5e9a0b1c86996a6df46
Python
4,877
131
"""Structural non-tensor input-tree honesty: empty containers + key types (r29-C2). The H1 non-tensor leaf-path SET witness records only LEAF paths, so it was blind to two structural changes that steer unobserved Python control flow: * An EXTRA/removed EMPTY container (codex-F1): ``{'flag': {}}`` adds no leaf path, s...
c2034b297496f53e304744bbcaa72cbd156d38f91e0bc7937d19c4cc300afb31
Python
4,879
121
#!/home/ubuntu/miniconda2/bin/python from __future__ import print_function import glob, os, gc, sys import os.path import csv import numpy as np np.random.seed(1337) # for reproducibility from time import time from subprocess import (call, Popen, PIPE) from itertools import product from IPython.display import display...
66424d65e0a96007228b27558d0527a05cc75ee6580549708a54f09f5872f15b
Python
4,880
97
# Contains arguments for generating input audio representations # These can be used either as part of the transformation or as # part of the preprocessing (which will be included in the graph # for gradient computation) # Feather et al. 2022 used cochleagram representations, however parameters # for a mel-spectrogram...
c072ea9e548104606c6f2ffebd84eef6e70caa591d15e0e912e692a21023f230
Python
4,880
188
"""Phase 13 discoverability tests.""" from __future__ import annotations from pathlib import Path import torch from torch import nn import torchlens as tl from torchlens.intervention.resolver import SiteTable class M(nn.Module): """Small model with a stable relu site. Kept inline deliberately (NOT migrat...
8d93a2ce41b334d333756091ed91ebe82f2d5a2877f611311207ad20ca424407
Python
4,881
160
from __future__ import annotations import time from typing import Optional # Temporary store for which channels passed/failed calibration # TODO: Will be replaced by CORE-32 CALIB_PASS_CHANNELS: dict[int, bool] = {} # TODO: Remove for [CORE-906] to tell how long a channel has been in each well CHANNEL_TIME_IN_WELL: ...
a6e8c42399cc78d1c659fc9f44ff2549444f74d6e6fb28814680eed97247cfa1
Python
4,881
112
#!/usr/bin/env python """Convert plain tabular or quoted TSV to Parquet with explicit header handling.""" import argparse import csv import math import re import sys from collections.abc import Iterable from decimal import ( Decimal, InvalidOperation, ) try: import pyarrow as pa import pyarrow.parquet...
d3eca0d78e6d3c08441924362600d27cd9548493f451b93df81c415555b9f5a4
Python
4,881
166
""" FUNCTIONS for similarity network fusion, diffusion map embedding and domain adapted ML Author: Dominik Kraft """ from brainspace.gradient import embedding from adapt.instance_based import TrAdaBoostR2 from scipy.stats import pearsonr from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score fro...
5a1dfe5bbdc0db2324ad0ae631ddcd50aa9cc657147d3b06c92d6a8d2dac3d8a
Python
4,882
149
#!/usr/bin/env python3 # Setup script for PyPI; use CMakeFile.txt to build extension modules from __future__ import annotations import contextlib import os import re import shutil import string import subprocess import sys from collections.abc import Generator from pathlib import Path from tempfile import TemporaryDi...
b41f1d549792f78c5fd55df1fd2a0f78dec282b6e59d353a4251333f54d30c18
Python
4,883
103
"""Калибровка прибора. Прежде чем измерять неизвестное, детектор прогоняют по известному источнику. Здесь два таких источника — политики, для которых мы ЗАРАНЕЕ знаем ответ: threshold — поведение полностью определяется внутренним состоянием. I(энергия; действие) обязана быть большой. Если метрика этог...
f496b9b1987d740f25ddace6dd85d1667c448c0b20b850b3931100eaa86fd935
Python
4,883
125
# SOURCE: vendored from https://github.com/abdulsalam-bande/KDeep @ main # (pytorch/model.py, `CNNScore` class). Community PyTorch reimplementation of # the KDeep 3D-CNN binding-affinity scorer (Jimenez et al., JCIM 2018), a # SqueezeNet-style network of "fire" squeeze/expand Conv3d blocks operating # on 16-channel vox...
36381d80def5a3a210415c7711abffcfc635817fbf921b13816ddfbfb8174ca4
Python
4,884
111
import os from angorapy.agent.utils import extract_discrete_action_probabilities os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import gymnasium as gym import numpy as np import tensorflow as tf from scipy.stats import norm, entropy, beta from angorapy.common.policies import GaussianPolicyDistribution, CategoricalPolicyD...
ab5855643dbfc92d8b8ce769d7b1ec3f1adcde2a5ceeb684ed6c5822a82521bd
Python
4,884
132
import pandas as pd import nibabel as nib from os.path import join as pjoin from magicbox.io.io import CiftiReader from cxy_visual_dev.lib.predefine import mmp_map_file, LR_count_32k,\ L_offset_32k, L_count_32k, R_offset_32k, R_count_32k,\ s1200_1096_myelin, s1200_1096_thickness, s1200_avg_myelin,\ s1200_av...
631e816a8ad9384cecdf397d9172dd93a20bfa3699a285a4a54286b4a5838492
Python
4,888
192
""" Main Script containing the following steps: - perform similarity network fusion and diffusion map embedding in PNC - split ABCD data into baseline (only T1), baseline, follow up - train ML model on PNC embeddings with supervised Domain Adaptation - ABCD *baseline only* data enhances prediction of embedding in unsee...
b333bcf17d116c7afbd8f142e61b4cef19ce0b0dd6c83b847ad5ff777c957b11
Python
4,889
141
# Copyright 2021 Google Inc. All Rights Reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the foll...
6dd865ec3519d73edeba464b92da0ed6f8648bdb02e7bea005670581e978ebce
Python
4,890
114
""" pip._vendor is for vendoring dependencies of pip to prevent needing pip to depend on something external. Files inside of pip._vendor should be considered immutable and should only be updated to versions from upstream. """ from __future__ import absolute_import import glob import os.path import sys # Downstream r...
ecd83c5f1f812b063d9dd53ce403c96f0101c7a8246d3a73e2b958d568123508
Python
4,890
121
"""Deployment envelope (lane F37): bitsandbytes 4/8-bit capture on CPU. Quantized capture is DISCLOSED-DEGRADED, never silently wrong: outputs match the bare forward bit-for-bit at fp32 tolerance, the quantized-module warning fires at entry, the compat row reads pass/warning, and the validation tripwires keep their ho...
5c57cc92a753367b14cab037de04983f9634b2cd79e4a3710b86a1c5404d14fe
Python
4,891
149
""" densratio.core ~~~~~~~~~~~~~~ Estimate Density Ratio p(x)/q(y) """ from numpy import array, linspace from .KLIEP import KLIEP as _KLIEP from .RuLSIF import RuLSIF as _RuLSIF from .helpers import is_numeric, to_ndarray _METHODS = ("uLSIF", "RuLSIF", "KLIEP") def densratio(x, y, method="uLSIF", sigma="auto", la...
7931f9fc7c390c2c26400a4d01a610186f4283bb29302d0e949c1955b2cf7971
Python
4,892
142
################################################################################################################################################################# ####################### Testing MulitRBP #####################################################################################################################...
67e167050a45c43caeffca953d6a2f6aa4bc68fc29075de9ff1e0aeca1ee8393
Python
4,893
86
import torch #import opt_einsum as oe class Neigh_List(torch.nn.Module): def __init__(self,cutoff:float,nlinked:int): # nliked used for the periodic boundary condition in cell linked list super(Neigh_List,self).__init__() self.cutoff=cutoff self.cell_list=self.cutoff/nlinked ...
726a9e723026200556940be54f63f9f7ea816cae27f9c95ca5156aab1d7354e2
Python
4,893
130
#!/usr/bin/env python3 """Суточный автономный прогон протокола B: «Когда выгодно учиться». Шесть условий на ОДНИХ И ТЕХ ЖЕ seed'ах (см. sim/protocol_b.py), 100 000 тиков каждое, единый предок на seed. Копится в runs/daily/protocol_b.jsonl, по строке на прогон, с датой, хешем коммита и версией протокола. Объявленные ч...
8ae1d66869db50edc5736486f6e7a5dbfd5e8406a533059b13c3756e29fda5f7
Python
4,893
130
#!/usr/bin/env python3 """Суточный автономный прогон протокола B: «Когда выгодно учиться». Шесть условий на ОДНИХ И ТЕХ ЖЕ seed'ах (см. sim/protocol_b.py), 100 000 тиков каждое, единый предок на seed. Копится в runs/daily/protocol_b.jsonl, по строке на прогон, с датой, хешем коммита и версией протокола. Объявленные ч...
1d15dd2f495a16aa0694cb34bb971349a25e0ae2310f627e2d4eadfc9a2bf8ea
Python
4,895
144
import numpy as np import scipy import matplotlib as mpl import matplotlib.pyplot as plt import brian2.only as br from contextlib import contextmanager from functools import partial def starstar(mapfn, f, kwargs_list): """Maps `f` to `kwargs_list` using `mapfn`.""" return mapfn(partial(apply_kwar...
c81d6013519a79a1d70b31b246b03c3f0b1398e295939d8579857fa842bde0c4
Python
4,898
123
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Written by Bin Xiao (leoxiaobin@gmail.com) # Modified by Bowen Cheng (bcheng9@illinois.edu) # ------------------------------------------------------------------------------ fro...
d54b132dc0052799fcd4090f15a2374f60f8bd8b35c8f321bec8f452c73bd34f
Python
4,899
136
"""Armed distributed state never steers a capture that has no process group. Arming is process-lifetime by design: it survives ``destroy_process_group`` so the group-lifecycle ledger outlives every group (a disarm-and-rearm after teardown would read the emptied group registry as "no history" and reuse lifetime ordinal...
6eba260eb21ea92161feece33994d7ca226f3c9ec5f08b65ee43f07a3d63abcc
Python
4,901
156
# coding=utf-8 # Copyright 2023 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...
82e9a39ce7473e151e5d5c930d1aa982d3344ee9d1c9a333c660100f007cb926
Python
4,902
138
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from external_src.group_free_3D.pointnet2.pointnet2_modules import PointnetSAModuleVotes, PointnetFPModul...
033f3e6a2ea707d9943328e7f85914285770f344dce79fe9596bfa2e8e2b285b
Python
4,903
126
import os import numpy as np import math from tensorflow.keras.utils import Sequence from tensorflow.keras.preprocessing.image import ImageDataGenerator from imageio import imread from scipy.special import expit from skimage.transform import resize # This is a custom Keras Sequence class that is used to load and pr...