sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
164d61674d29895c428ea5e413ea8890d4d3f32edfa61a8a8cb3aabfb4fd1a65
Python
1,819
60
# Copyright (c) 2020 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 appli...
8987da4161ba8c232065985e2029c25539a71f223a71bcf4f4cc2e0db1bc54de
Python
1,819
35
import torch import torch.nn as nn from torch_geometric.utils import softmax from torch_scatter import scatter class MH_ATT(nn.Module): def __init__(self, n_att_heads=4, q_dim=128, k_dim=128, v_dim=128, out_dim=128): super(MH_ATT, self).__init__() self.n_att_heads = n_att_heads self.d_k =...
bcfef4c69cccea1eeac0e447c0c7268f94f76a245d43dd2ce33fd6044ac44b58
Python
1,819
47
from dig.xgraph.evaluation import XCollector, ExplanationProcessor, control_sparsity from torch_geometric.nn.conv import GCNConv from torch_geometric.utils.random import barabasi_albert_graph from torch_geometric.data import Data import torch def test_metrics(): device = torch.device('cuda:0') if torch.cu...
29942a180dce20d5736f5e3b6184d9c2f02e8965d41f700044eacb9a35d264c9
Python
1,821
50
import experiment as exp import arena import schedule import video_system class HeatImagesExperiment(exp.Experiment): default_params = { "image_src_ids": ["top", "thermal"], "video_src_ids": ["thermal"], "on_time": 30 * 60, "off_time": 30 * 60, "lamp_idx": 4, } def...
170848e44e38189e033108ceceb3c3365888cfca0e2c314f8ae4255d825aa81d
Python
1,822
66
import os import importlib import argparse SUPPORTED_STATS = ["loss", "grad_norm"] def register_stats_fn(name): def register_fn(fn): if name in SUPPORTED_STATS: raise ValueError("Cannot register duplicate state ({})".format(name)) SUPPORTED_STATS.append(name) return fn re...
98f41ce45e7461f24699562bdcefd28c28ffb09c1efd836062a35b1380f35f33
Python
1,822
58
import subprocess # Define a list of sample names and corresponding SNP list file names sample_names = [ "CD16p_Mono_conditional_eQTL_FDR0.05", "CL_Mono_conditional_eQTL_FDR0.05", "CM_CD8_conditional_eQTL_FDR0.05", "DN_B_conditional_eQTL_FDR0.05", "EM_CD8_conditional_eQTL_FDR0.05", "Fr_I_nTreg_...
27009c14510fd138d23e3463943f93441349fb5b210d3b8d2e0d35ddd818251a
Python
1,823
46
import pytest import geomstats.backend as gs from geomstats.test.random import NFoldManifoldRandomDataGenerator, RandomDataGenerator from geomstats.test.test_case import TestCase from geomstats.test_cases.geometry.manifold import ManifoldTestCase from geomstats.test_cases.geometry.mixins import ProjectionTestCaseMixin...
fa918c3ee8e7c9b86258f13dc0a957f077ef6aba5224ca03d1a494dc9e045182
Python
1,823
59
# 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 appli...
b869958c13b3f6875798670fe636cdd80c591ede390bc3dfab50b3cfaf3afd20
Python
1,827
94
import os from Bio.PDB.PDBParser import PDBParser from Bio.PDB.ResidueDepth import ResidueDepth, get_surface, residue_depth from Bio.PDB.HSExposure import HSExposureCA import warnings from Bio import BiopythonWarning import tempfile with warnings.catch_warnings(): warnings.simplefilter('ignore', BiopythonWarning...
177b161afe60ff66999e31641afc6dfcd8b8d8304c0401b5f6b3710737047b68
Python
1,828
71
# Copyright 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Experimental CLI.""" from logging import getLogger from pathlib import Path from subprocess import check_call from sys import executable from click import echo, group, pass_context import openfl logger = getLogger(__name__) @group(...
1d8a2fb26feb982b9909c6b1db9f832c70e0ac3c193cc21f44b9d63ddc94882b
Python
1,829
54
# Copyright (C) 2020-2023 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Numpy optimizers test functions module.""" from typing import Dict import numpy as np def rosenbrock_func(point: Dict[str, np.ndarray]) -> float: """ Calculate Rosenbrock function. More details: https://en.wikipedia.org...
317a0611fe69a3fd7c8d3c6fc0773526fce426d21cf058e6b45052e9f293e11e
Python
1,830
65
#!/usr/bin/env python # Prints all non-indel positions in MAF file with coordinates and variants from each species / individual # Usage python callSNPsFromMAF.py mafFile outFile import sys mafFile, outFile = sys.argv[1:] outFile = open(outFile, 'w') def parseChrom(chrom): fields = chrom.split(".") newChr...
5fb90ebf8bc0f9439dffa99c39d189facea2725dd93758da1d53a9ebd678841e
Python
1,833
51
from sparse_ct.tool import plot_grid from sparse_ct.data import image_to_sparse_sinogram, ellipses_to_sparse_sinogram from sparse_ct.reconstructor_2d import ( IRadonReconstructor, SartReconstructor, SartTVReconstructor, Sar...
e204a2db8a9835683e78281eb01dd4fcdab1d2567d830c93255be6f519e0ba50
Python
1,833
49
import re from typing import Tuple from uuid import UUID from chromadb.db.base import SqlDB from chromadb.segment import SegmentManager, VectorReader topic_regex = r"persistent:\/\/(?P<tenant>.+)\/(?P<namespace>.+)\/(?P<topic>.+)" def parse_topic_name(topic_name: str) -> Tuple[str, str, str]: """Parse the topic...
e5e46c684f70ad912d29f200073a0105d1a66224fd38b864251d6f7b4e6153f0
Python
1,833
45
__author__ = 'palmer' def hdf5_centroids_IMS(input_filename, output_filename): # Convert hdf5 to imzML imsDataset = inMemoryIMS(input_filename,cache_spectra=False,do_summary=False) coords = imsDataset.coords coords -= np.amin(coords, axis=0) step = [] for i in range(3): u = list(np.dif...
488c4148c9cafae6ddb75526d625f04a88da8d1df012d7f2329b9413057af1ee
Python
1,835
50
import pytest from chromadb.utils.embedding_functions.ollama_embedding_function import ( OllamaEmbeddingFunction, ) def test_ollama_default_model() -> None: pytest.importorskip("ollama", reason="ollama not installed") ef = OllamaEmbeddingFunction() embeddings = ef(["Here is an article about llamas......
376c243a4cfd98ad356d8a4fb569438cbc957a26e6dcf69271a4944d793cf0d9
Python
1,836
58
"""Compute the RDKit molecule volume from a conformer and its grid-encoding The quality depends on the quality of the conformer. """ from typing import List, Optional import numpy as np from rdkit.Chem import AllChem as Chem from pydantic import Field from pydantic.dataclasses import dataclass from ..component_resu...
b9eca4e2bcea850002a9965ac91c61ded40036dacf4c18ff579b448052e1963e
Python
1,841
54
import torch import torch.nn as nn from loss_objectives import GCCA_loss class MlpNet(nn.Module): def __init__(self, layer_sizes, input_size): super(MlpNet, self).__init__() layers = [] layer_sizes = [input_size] + layer_sizes for l_id in range(len(layer_sizes) - 1): if...
e176f9d23907b58ff395d21c21425b6410db601c77f2a26a0159253759c42a9f
Python
1,841
47
import numpy as np import tensorflow as tf from tensorflow.python.ops import gradient_checker from tensorflow.python.framework import constant_op import high_dim_filter2d_grad custom_module = high_dim_filter2d_grad.custom_module class HighDimGradTest(tf.test.TestCase): def test_high_dim_filter_grad(self): ...
c36c1d5d71e76748246b4d6d35b976ca10dfd9c1d2ee71aa35ecbd3a96083687
Python
1,842
51
import matplotlib.pyplot as plt import seaborn as sns def plot_example_boxplot(df, is_human_col="is_human", score_cols=["top_heavy_score", "top_light_score", "top_paired_score"], fontsize=12): ''' Compare the top CNN scores for human and non-human sequences wi...
8aeb76bfc72bace04d38dbe4132c71ccacbf2c2c1a89244525b02b47ac7769f6
Python
1,843
57
import os import logging as py_logging _log_level = { None: py_logging.NOTSET, "debug": py_logging.DEBUG, "info": py_logging.INFO, "warning": py_logging.WARNING, "error": py_logging.ERROR, "critical": py_logging.CRITICAL } def get_logger( log_file_path=None, name="default_log", l...
401c2ab918b9bf872780ec2cdcaad6cca005fea6a3f5e0d74b9c6e284f0c2b8e
Python
1,845
71
import json from live2p.websockets import Live2pServer from live2p import Alert test_params = { 'fr': 6.36, 'p': 1, # deconv 0 is off, 1 is slow, 2 is fast 'nb': 2, # background compenents -> nb: 3 for complex 'decay_time': 1.0, # sensor tau 'gSig': (7, 7), # expected half size of neurons in pi...
4ba6f3f640e902c2619889399498698310006ef411e4f9112f5d875bfbc73d50
Python
1,847
61
from typing import Tuple import time import copy import torch from torch import Tensor from torch_sparse import SparseTensor from torch_geometric.data import Data partition_fn = torch.ops.torch_sparse.partition def metis(adj_t: SparseTensor, num_parts: int, recursive: bool = False, log: bool = True) -> T...
79b013813324ab7ae803e6cc285ceea9bf3dbd5efcbaafcd10ee22aa06aabe42
Python
1,847
61
from pathlib import Path import getpass import json import numpy as np import matplotlib.pylab as plt import MEArec as mr import MEAutility as mu import spikeinterface.full as si # if you are not Sam nor Pierre you should add some lines here. if getpass.getuser() == 'samuel.garcia': # sam working # base...
9eb1bc25dd3538fc4404f75131bf56ce3901655b38b2f7825a343f34e9cf2926
Python
1,849
58
# This file is used to generate Samples from a Trained StyleGAN_1 model import os import dnnlib import dnnlib.tflib as tflib import numpy as np import PIL.Image import pickle # Generate and save images with different random seeds num_images = 100000 print ("Generating Samples") # Path to pre-trained StyleGAN1 .pkl ...
ce68f4a6c41e475786c39cdb31a1598200b807ef044a5330e659704ea7b7ad68
Python
1,849
50
"""Train Proj2Proj from image files with simulated noisy projections.""" import argparse from pathlib import Path import numpy as np from torch.utils.data import DataLoader from sparse_ct.reconstructor_2d import Proj2ProjReconstructor from sparse_ct.reconstructor_2d.dataset import DeepLesionDataset def main(): ...
097ac69317743e5bfd05951700914f97269abccb3ac043772e214df8f6907282
Python
1,850
49
from typing import List, Optional, Tuple from chromadb.base_types import SparseVector def normalize_sparse_vector( indices: List[int], values: List[float], labels: Optional[List[str]] = None ) -> SparseVector: """Normalize and create a SparseVector by sorting indices and values together. This fu...
43679f1d8d530715c0bf13996d3693631fb13d065190fb67bbb2d19fe2b6f109
Python
1,850
66
from PymoNNto.NetworkCore.Neuron_Group import * class NeuronGroup_read_write_event(NeuronGroup): ref = None wef = None current_dict = None def set_read_event_function(self, ref): self.current_dict = copy.copy(dir(self)) self.ref = ref def set_write_event_function(self, wef): ...
5d783ffc9117686bfa4241509ce550525110b67e6f6aafcc7d2067873ec83031
Python
1,850
59
from bindsnet.network import Network from bindsnet.pipeline import EnvironmentPipeline from bindsnet.encoding import bernoulli from bindsnet.network.topology import Connection from bindsnet.environment import GymEnvironment from bindsnet.network.nodes import Input, IzhikevichNodes from bindsnet.pipeline.action import s...
7f3453fda7aaf6fcf90698568b4c37f55705c5046108b5b40016e2b85fd12554
Python
1,850
54
"""The two tiny checkpoints every other golden is measured against.""" from __future__ import annotations from typing import Dict from tests.golden.paths import REPO_ROOT ORDER = 20 HELP = "the tiny anchor checkpoints and their build sidecars" #: anchor name -> (checkpoint, reference file, what the anchor is for) ...
8afb0420162b9d3e682ffb6d395b970b640117e9b0b36eec467ac8cf4ee84541
Python
1,851
51
import torch class RotaryPositionalEmbedding(torch.nn.Module): def __init__(self, dim, base=10000, precision=torch.half): """Rotary positional embedding Reference : https://blog.eleuther.ai/rotary-embeddings/ Paper: https://arxiv.org/pdf/2104.09864.pdf Args: dim: Dimens...
48fdbbb0e81a58eb42638fd26d87cf950b8ab196206c01e0a0fce31084caffa1
Python
1,852
54
import numpy as np from scipy.ndimage.interpolation import shift from fimpy.alignment.volume import sobel_stack from skimage.registration import phase_cross_correlation def align_single_planes_sobel( stack, fft_ref=None, prefilter_sigma=3.3, upsample_factor=10, maxshift=15, offset=[0, 0], ): ...
02315a9ced83145e32d21882d2245ab330bf6c4092105a18b52461cdf4b80243
Python
1,854
63
import os import sys import platform import subprocess import pandas as pd from tqdm import tqdm def get_simulation_time(byte_out): str_out = byte_out.decode("utf-8") result = [ line for line in str_out.split("\n") if line.startswith("simulation time:") ] return result def get_number(line, s...
6d94d17057882c7ddeb84dba12389d2ff7ec73e5bae27b58eadedf7f500de68d
Python
1,854
60
# # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # from torch import Tensor import random from typing import List, Optional, Tuple from utils.math_utils import bound_fn from .base_layer import BaseLayer class RandomApply(BaseLayer): """ This layer random...
7957d2b26d1c1198d501ce2b83daa47019be632ebd43cae4c6016ebb6d9e2a94
Python
1,855
53
import math import torch import torch.nn as nn import torch.nn.functional as F from reinvent.models.transformer.core.network.encode_decode.clones import clones def attention(query, key, value, mask=None, dropout=None): "Compute 'Scaled Dot Product Attention'" d_k = query.size(-1) scores = torch.matmul(q...
08c7765ebec58ca62660be79b9b475273dfed87261a3f507ce9265cf34aea194
Python
1,858
83
from __future__ import print_function import os import copy import pprint import torch import numpy as np import matplotlib.pyplot as plt import utils import utils as u import analysis_utils import analysis_utils as au from dataset_learning_trainable import DatasetLearningTrainable import torch.nn as nn import torc...
57c728bd5b5a62f6e668fb24435a47741574fac3c60e937c3627ee6adc36b6a7
Python
1,858
75
from numba import njit, jit, objmode from numba.experimental import jitclass from numba import int32, int64, float32, float64, boolean from numba import typed, types from numba.types import pyobject import numpy as np from scipy.io import loadmat, savemat from .Tree import Tree from itertools import chain def flatten(...
7fe086ce1313f655a2a897dc10c61c2ec0a9f819b5e62ca065f74508f17b53ce
Python
1,859
62
# Copyright 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Framework Adapter plugin interface.""" class FrameworkAdapterPluginInterface: """Framework adapter plugin class.""" def __init__(self) -> None: """Initialize framework adapter.""" pass @staticmethod de...
7bbd19c4c0bd573a8743331889baaaa07733c735b67d36bec6a6f42ea5a11a4f
Python
1,860
47
# Copyright (C) 2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Histogram module.""" import numpy as np from openfl.interface.aggregation_functions.core import AggregationFunction class AggregateHistogram(AggregationFunction): """Histogram aggregation.""" def call(self, local_tensors, *_)...
54af8207e6f391aaeb30fde481f3c46f68ca19dd65dad87932340558d0b416a6
Python
1,863
78
"""Logging setup for single- and multi-processing""" __all__ = ["setup_sp_logger", "logging_listener"] import sys import logging import logging.handlers from typing import TextIO FORMATTER = logging.Formatter( fmt="%(asctime)s <%(levelname)-4.4s> %(message)s", datefmt="%H:%M:%S", ) def setup_sp_logger( ...
edc9d7918c086d5df7204812e8aee976d15f930a83f2a88f7d21163acca3356e
Python
1,863
47
"""One training step per anchor, reduced to a per-parameter gradient digest.""" from __future__ import annotations from pathlib import Path from tests.golden import harness, targets from tests.golden.paths import REPO_ROOT ORDER = 35 HELP = "the one-training-step gradient digests" def run() -> None: # Late im...
13cfdb8afc742b8b185b51a7862b761aff32ea0096f4b22a938beaae96b3aa98
Python
1,865
52
# # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # from torch import nn, Tensor from typing import Optional, Tuple from . import register_norm_fn @register_norm_fn(name="sync_batch_norm") class SyncBatchNorm(nn.SyncBatchNorm): """ Applies a `Syncronized B...
30bd7d3ba64b95bc1a23bca9d344e97960c14d1ad07db2404e49a73e2ce8c157
Python
1,865
50
""" Combine the AnalogSignal and Event objects from different wave analysis blocks into the same Neo Block. """ import argparse from pathlib import Path from utils.io_utils import load_neo, write_neo CLI = argparse.ArgumentParser() CLI.add_argument("--data", nargs='?', type=Path, required=True, help=...
38d41a2268e33a5b68b3a99adb420ad4bc175d01b9071f8bbf0070056794fe82
Python
1,866
65
#!/usr/bin/env python # Prints all non-indel positions in MAF file with coordinates and variants from each species / individual # Usage python callSNPsFromMAF.py mafFile outFile import sys mafFile, outFile = sys.argv[1:] outFile = open(outFile, 'w') def parseChrom(chrom): fields = chrom.split(".") newChr...
afecc96de49b0feece23c2cd03c53345947fa6c2931ec9bb93e53b82d88e8b6c
Python
1,869
57
import math import numpy as np import tensorflow as tf import multiprocessing as mp from Humatch.utils import seq_to_2D_kidera class CustomDataGenerator(tf.keras.utils.Sequence): ''' Custom generator for batch training/eval with Kidera encoded sequences tf.keras.utils.Sequence allows multiprocessing in sa...
10b0a2c1e26837cf2eb014447a5dc57372b809ac2e116dc3d0c26e6b79bebae6
Python
1,870
57
import logging import multiprocessing from importlib import metadata import torch from torch.backends import mps from idtrackerai import IdtrackeraiError, conf def _get_device(user_device: str) -> torch.device: """Returns the current available device for PyTorch""" try: # when mocking torch, metadat...
14669466c6a5b2322ac2bd4fbfd034f29fab9ac9821fbca5770aa20aa04a79ee
Python
1,870
58
#!/bin/env python3 # # This is an example how to use the ExternalProcess scoring component using # RASCore. The scripts expects a list of SMILES from stdin and will # write a JSON string to stdout. # # Retrosynthetic Accessibility Score (https://doi.org/10.1039/D0SC05401A) # with code from https://github.com/reymond-g...
d832b625d87fc1a00eb0d8dd9c780afa00b40bc553e2c7c7d6195f3831207aa8
Python
1,870
62
from pyscf import gto, dft from rdkit import Chem from scipy.constants import physical_constants EH2EV = physical_constants['Hartree energy in eV'][0] def geom2gap(geom): mol = gto.Mole() mol.atom = geom mol.basis = '6-31G(2df,p)' #QM9 mol.nelectron += mol.nelectron % 2 # Make it full shell? Otherwise...
08521aebd5150e1ae7fc9945641045b24910027afc8f57a6889c3667f93e72d5
Python
1,872
66
from setuptools import setup, find_packages meta = {} with open("smithers/meta.py") as fp: exec(fp.read(), meta) # Package meta-data. NAME = meta['__title__'] DESCRIPTION = ( "Smithers' a Mathematical Interdisciplinary Toolbox for Helping Engineers " "Researchers and Scientist" ) URL = 'https://github.com...
2850e6d3441e67f7701d28a088b131bcc17ef09061061a974f108d8fa2a66f38
Python
1,873
49
""" Combine the AnalogSignal and Event objects from different wave analysis blocks into the same Neo Block. """ import argparse from pathlib import Path from utils.io_utils import load_neo, write_neo CLI = argparse.ArgumentParser() CLI.add_argument("--data", nargs='?', type=Path, required=True, he...
a4e940db01a7596cd038fd6ec57b78f9dd864f63629b61adacd2dd78c70c44f8
Python
1,874
61
#!/usr/bin/env python3 import argparse import numpy as np import odil from odil.runtime import mod def test(method, ndim, loc): cshapeh = 3 + np.array(range(ndim)) cshape = cshapeh * 2 dimnames = ["x", "y", "z", "w"][:ndim] domain = odil.Domain(cshape=cshape, dimnames=dimnames) domainh = odil....
60d6908dc6aedb4f0cad434abaecd213d50bc3ff3f138abd9f887ebdf9e50ce1
Python
1,876
52
"""Tests for snakemake_io""" from __future__ import absolute_import import collections from snakebids.utils import snakemake_io def test_glob_wildcards(): """Test glob_wildcards() with various patterns""" file_path = ( "snakebids/tests/data/bids_t1w/sub-001/anat/" "sub-001_acq-mprage_T1w.nii.gz" ...
620e56b1b50cc3257d2da92ad2f240eca79b7967a163bb7cc3290cc908ced49e
Python
1,878
57
""" Check whether the input data representation adheres to the stage's requirements. Additionally prints a short summary of the data attributes. """ import numpy as np import argparse import quantities as pq import warnings import re from utils.io_utils import load_neo from utils.parse import none_or_str CLI = argpa...
285b264993a7ab20726bc63190bc11b1b3bd6b89816cfe4eabc07a7c0b0deaa4
Python
1,879
60
import logging import unittest from typing import Tuple from unittest.mock import patch, mock_open from sniffles.config import SnifflesConfig from sniffles.region import Region class TestRegions(unittest.TestCase): """ Tests --regions parameter """ @staticmethod def _get_common_args() -> Tuple: ...
cfe2d3ef4d4e78dca890dfcc22587adeeb7ff744efa3b6f7ae2d3ed73008aacc
Python
1,879
54
import sys import time from PyQt5.QtWidgets import QApplication from ._scope import _ScopeEEG from ._scope_controller import _ScopeControllerUI from .. import logger from ..stream_receiver import StreamReceiver, StreamEEG from ..utils.lsl import search_lsl class StreamViewer: """ StreamViewer instance. The s...
eb2b8bca3733f9ebb2a9c118bca1510f94b9184ff937701acea707ca5f950fae
Python
1,879
48
# Copyright 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from openfl.callbacks.callback import Callback class LambdaCallback(Callback): """Custom on-the-fly callbacks. This callback can be constructed with functions that will be called at the appropriate time during the life-cycle of...
71db6449e249a8a174f8966b6192b0b4d1e5c42f0461ec152402f9e9bea0e5ae
Python
1,884
53
from types import SimpleNamespace import pytest import chromadb.test.utils.wait_for_version_increase as wait_module class _FakeClient: def __init__(self, collection_id: str = "test-collection-id") -> None: self._collection = SimpleNamespace(id=collection_id) def get_collection(self, collection_name...
a5f9cbffadcb68be0c16a9bb4b5ca3b9f3fc0589cc9ebde2962e5eb7aebd6f81
Python
1,886
32
import datasets import image_experiment import experiment img_basepath = 'saved-data/plots/' cifar10_experiment = image_experiment.ImageExperiment(datasets.ImageDataset.CIFAR10) # cifar10_experiment.train_models(10,epochs=10,batch_size=64) cifar10_experiment.load_models(10) cifar10_experiment.run_experiment(experimen...
f4b640434d33b2ad3aa36a518d84b8b6d1b7ef8d18fb1299062d5be015057027
Python
1,886
38
"""Splitting parallel corpora according to specified sentence lengths - lengths""" # en_file: Source language corpus address; de_file: Target language corpus address def split_sentences_by_length(en_file, de_file): lengths = [(0, 10), (10, 15), (15, 21), (21, 32), (32, float('inf'))] # Create a list for stor...
6fcdb5c6b0eb85f7c22c50461195ee4bed553f2cd2eb1d7ba6c1381686777ab4
Python
1,887
57
""" Check whether the input data representation adheres to the stage's requirements. Additionally prints a short summary of the data attributes. """ import numpy as np import argparse import quantities as pq import warnings import re from utils.io_utils import load_neo from utils.parse import none_or_str CLI = argpa...
49456bc084e1b13843e9a751ba986abc62cbfffdbfb3ad329cb2060e9197603c
Python
1,888
59
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*- import os import argparse import logging import itertools import pickle # use this format to tell the parsers # where to insert certain parts of the script # ${imports} def parse_args(): # Argument Parser parser = argparse.ArgumentParser() # my args pa...
e3f007e35f3758458b2ba974b46041e54caa051e085240ee458541bc24477a56
Python
1,889
45
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Script for using model and detecting defects. Input data files should be saved in a folder called 'CellFiles' (or 'data_filepath' should appropriately changed), with each file being a as a comma separated text file where each line contains the x and y coordinates, as...
e715c0fe31a27b81a229465fcb268c40a34c6ebe37eb01821da863a3a5ed9c1a
Python
1,889
60
from PymoNNto.Exploration.Network_UI.TabBase import * #from Testing.Common.Classifier_Helper import * class sidebar_drumbeat_module(TabBase): def add_recorder_variables(self, neuron_group, Network_UI): if hasattr(neuron_group, 'pattern_index'): Network_UI.add_recording_variable(neuron_group, ...
e8d1c343d4edfd07c16c845fdd531ff1a79995802bc2320fa99630f58a5541bd
Python
1,890
66
import pytest from pathlib import Path import torch from reinvent.runmodes.TL.run_transfer_learning import run_transfer_learning from reinvent.runmodes.utils.helpers import set_torch_device from reinvent.models.meta_data import check_valid_hash @pytest.fixture def setup(tmp_path, json_config, pytestconfig): dev...
572be9896c0e9418f54f2fda596ec3f4af2cb9dbd00f2e9a8821c401b8d0adaf
Python
1,891
70
import os import sys from pprint import pprint import numpy as np import pandas as pd project_root = ".." sys.path.append(project_root) DATASETS_PATH = os.path.join(project_root, "resources", "datasets", "nsrr") if __name__ == "__main__": dataset_name_list = [ "chat1", ] # Keys in dataset: ...
ca441da11e60b42dad4447279322af2b959af5a542c11feccdc37705a47eb807
Python
1,892
68
"""Benchmark metric inner product.""" from importlib import import_module import pandas as pd import pytest def read_benchmark_inner_product_data(): """Read benchmark parameters from file benchmark_params.pkl.""" data = [] ids = [] df = pd.read_pickle("benchmark_params.pkl") params = list(df.ite...
46f725b6ce4e4658f74f7929ce45118438dcf39ad2c262cfa17f610dfcc4ffe8
Python
1,895
67
from pymonntorch.NetworkCore.Behavior import Behavior from pymonntorch.NetworkBehavior.EulerEquationModules.Helper import ( eq_split, remove_units, ) class Variable(Behavior): def __init__(self, *args, eq=None, **kwargs): super().__init__(*args, eq=eq, **kwargs) def initialize(self, neurons):...
3d17c26e9a77ebce00ab423b469879441b53e6854f724cf83fbb057b475208a2
Python
1,896
71
# NIBR substructure filter # # adapted from RDKit commit 4a69bc3493dd3e9bb9f7a519e306fbcb545f1452 which # includes the CSV file SubstructureFilter_HitTriaging_wPubChemExamples.csv # # build the filter from a CSV filer and write it out in pickle format from collections import namedtuple import pandas as pd from rdkit...
3c49adf05561dcf471e0cbff05a67de45d25c4858ad6015af10982233e6baa4b
Python
1,899
57
import geomstats.backend as gs from geomstats.geometry.general_linear import GeneralLinear from geomstats.geometry.matrices import Matrices from geomstats.test.data import TestData from .base import LevelSetTestData from .riemannian_metric import RiemannianMetricTestData class StiefelTestData(LevelSetTestData): ...
aeec181d32393cc8cbbb2d174257435f98f7f5b79241e19e09bdb6f529322bab
Python
1,903
61
import os import numpy as np import pickle import pandas def import_data(patient): print('\nLoading data...') directory=f'../../Data/pat_{patient}' #import information about seizures with open(os.path.join(directory,'all_seizure_information.pkl'), 'rb') as seiz_info: ...
3451c2eca01151f378438ec65c40f31fd4a4173c7709336b9529f0acb98986d7
Python
1,904
66
import geomstats.backend as gs from geomstats.test.data import TestData from ._base import BaseEstimatorTestData class RiemannianEMTestData(BaseEstimatorTestData): fail_for_autodiff_exceptions = False MIN_RANDOM = 5 MAX_RANDOM = 8 def estimate_belongs_test_data(self): return self.generate_r...
87829e68c0a7c611231f2d34556bf6a0b775ba9326ca25e875ab2ccb07f253c5
Python
1,904
68
# Path to save data DATA_PATH = r'' # classifier type DECODER_FILE = r'' # fake decoder? FAKE_CLS = None DIRECTIONS = [ ('L', 'LEFT_GO'), ('R', 'RIGHT_GO') ] ADAPTIVE = {'selected':'False', 'False':False, 'True':[3]} # Retrain classifier every 2 x TRIALS_EACH, 3= nb_runs, ...
e4bfab72398886c3fc07b1a4c9254034b803445a7dcb0be36316fae1419db246
Python
1,904
58
""" Check whether the input data representation adheres to the stage's requirements. Additionally prints a short summary of the data attributes. """ import numpy as np import argparse from pathlib import Path import quantities as pq import warnings import re from utils.io_utils import load_neo from utils.parse import...
3c292900127642a2ae375c5c245fbf2ad30b71d8274cf0679360139db264bcbc
Python
1,906
81
from collections import Counter from pathlib import Path import matplotlib.pyplot as plt from rich import print import neurodesign output_dir = Path(__file__).parent / "output" output_dir.mkdir(parents=True, exist_ok=True) exp = neurodesign.Experiment( TR=1.2, n_trials=20, P=[0.3, 0.3, 0.4], C=[[1, ...
b3351aee5a166eecfa9d4d928908e94eaff6badece81649aefbbe45fac05ade0
Python
1,906
67
''' Example showing software-timed analog input using nidaqmx-python pynidaqmxegs.ai.softwareTimedVoltage Purpose Describes how to do software-timed analog input using using nidaqmx-python This is unbuffered or "on demand" acquisition. Demonstrated steps: 1. Create a task. 2. Create an An...
eb206cf140176ce800aefa620594e98fb8278254231179ed97797f0907d613d5
Python
1,906
62
import numpy as np import torch # class modules # In this file we collect all the modules so we don't need to re-write them # at every file class _ResidueModule(torch.nn.Module): '''One-dimensional convolutional residual we only provide the channel count the stride and the filter width are fixed to zero. ...
54a6d6eca3268267f836e6df1fc0f7e68939bf30c55469cf29db891f1f890edc
Python
1,909
46
from utils.visualization_utils import plot_cam, concat_images import sys def cam_dataset_model(sel_dataset, sel_model, n_classes, size=None): sys.argv.append('--common.config-file') sys.argv.append('config/classification/food_image/ehfr_net_food101.yaml'.format(sel_dataset)) sys.argv.append('--mo...
c57984984e424060d206e7ff3969594ea3154bef6c11bfd2d6589b0fc5d80c9a
Python
1,909
47
# -*- coding: utf-8 -*- """Implements datasets for training and evaluating learned reconstructors. .. autosummary:: get_standard_dataset Dataset GroundTruthDataset ObservationGroundTruthPairDataset EllipsesDataset LoDoPaBDataset The function :func:`.get_standard_dataset` returns fixed "standar...
a8bb763ab1510b090a2dfcca7b7709549e5b9e07c8d19bbbe6d2bcae7df5fd5f
Python
1,911
49
import os # Define a list of file names file_names = [ "CD16p_Mono_conditional_eQTL_FDR0.05.vcf", "CL_Mono_conditional_eQTL_FDR0.05.vcf", "CM_CD8_conditional_eQTL_FDR0.05.vcf", "DN_B_conditional_eQTL_FDR0.05.vcf", "EM_CD8_conditional_eQTL_FDR0.05.vcf", "Fr_I_nTreg_conditional_eQTL_FDR0.05.vcf",...
4e92700fb08ed27fdd23f6cadad48cba7c7b5be104cfb4c872d282291e7a7e52
Python
1,913
43
""" Reproduce the metrics from Figure 5 in https://doi.org/10.1038/s41597-021-00893-z """ import numpy as np from dival import get_standard_dataset from dival.measure import PSNR, SSIM from dival.reconstructors.odl_reconstructors import FBPReconstructor from dival.reference_reconstructors import get_reference_reconstru...
8e14e13e1ea375d13354f2cb83d7b6d164c367c3b1f487e529eaadc0ab7a031d
Python
1,915
64
import pytest from reinvent_plugins.components.RDKit.comp_matching_substructure import ( Parameters, MatchingSubstructure, ) def test_comp_matching_substructure(): smarts = ["ClccccF"] smiles = ["c1cc(F)ccc1Cl"] params = Parameters(smarts, [False]) ms = MatchingSubstructure(params) result...
4489bc0a009feadcba23852f67b86ebee40cba4d1cb6ed2e8c43cbbb2c02b02d
Python
1,917
71
"""Fixture setup for pytest IMPORTANT: NEVER import directly from conftest.py also DO NOT mess with sys.path """ import os import json import pytest def pytest_addoption(parser): """Command line parsing for pytest Use e.g. like $ pytest [pytest parameters and options] --device cpu """ ...
54d0bd0e4fd2fe8592a6e848f9d26249da384cce5af5100fb73324eabf809166
Python
1,917
69
from typing import Optional, Tuple, List, Iterable, Dict import torch import numpy as np from PIL import Image from ..encoding import Encoder, NullEncoder import sys sys.path.append("C:/Users/cstei/Dropbox/work/projects/hebb/code/") import libstein.hebb.image_data as image_data class NatImages(torch.utils.data.Datas...
1e8849ae622d20a3c8f7543c9f8bbc2bbdc2db3483af7473750a282a2e427b8a
Python
1,919
58
""" Divide the signal in each channel by their max/mean/median value. """ import numpy as np import argparse import neo import quantities as pq import os import sys from utils.io_utils import write_neo, load_neo CLI = argparse.ArgumentParser() CLI.add_argument("--data", nargs='?', type=str, required=True, ...
feb850f7ca51c691707a42b0d364cbf98cbb3fb8992ba4aa7efecba2b1327e5e
Python
1,919
60
# This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it. import torch import lightning from lightning.pytorch.callbacks import Callback from nequip.data import AtomicDataDict from nequip.train import NequIPLightningModule class LossCoefficientMonitor(Callba...
58192fb433642af3b85cf5e7730eba6a12fd5a62d11b00fdf30cde0b3a9181b5
Python
1,921
68
"""Compute the PMI score in RDKit""" from typing import List import numpy as np from rdkit.Chem import AllChem as Chem from pydantic.dataclasses import dataclass from ..component_results import ComponentResults from ..add_tag import add_tag from reinvent_plugins.mol_cache import molcache @add_tag("__parameters") @...
7b07f8cf602ff86c4466563a4da001f38861d08f40ea72f46e757e70e2f2a1cb
Python
1,922
52
from PymoNNto.Exploration.UI_Base import * from PymoNNto.Exploration.StorageManager.StorageManager import * from PymoNNto.Exploration.Evolution.EvolutionPlots import * class Single_Evolution_UI(UI_Base): def __init__(self, evolution): super().__init__(title='Evolution Monitor', create_sidebar=False, cre...
7cbf3c91012951d048134be3232e297bfb5d84dd8b24884675a67c3eec1e8da2
Python
1,922
53
# Copyright 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Adagrad adaptive aggregation module.""" from typing import Dict, Optional import numpy as np from openfl.interface.aggregation_functions.core import AdaptiveAggregation, AggregationFunction from openfl.interface.aggregation_functions....
37df6414ca52010af400dc3e84ccd0a7f414c895c54123592618fdb1e4b443ff
Python
1,924
59
# -*- coding: utf-8 -*- import os import argparse import logging # use this format to tell the parsers # where to insert certain parts of the script # ${imports} def parse_args(): # Argument Parser parser = argparse.ArgumentParser() # my args parser.add_argument("--verbose", action = "store_true", hel...
d494e260288261d7584e37bb1921ee120eef613e3afe03f562fb1f5ea60f0fbd
Python
1,924
64
from nltools.simulator import Simulator, SimulateGrid import numpy as np def test_simulator(tmpdir): sim = Simulator() r = 10 sigma = 1 y = [0, 1] n_reps = 3 output_dir = str(tmpdir) shape = (91, 109, 91) dat = sim.create_data(y, sigma, reps=n_reps, output_dir=None) assert len(dat)...
da2875c9218f23cb8aca4ea44db2878c359e5d800edaa22bc8c648b6c466b96b
Python
1,925
52
# -*- coding: utf-8 -*- """ Created on Mon Aug 31 15:05:59 2020 @author: Tom """ import tensorflow as tf import numpy as np class NegativeLogLikelihood(): def __init__(self, followup, event): self.followup = tf.constant(followup, dtype='float32') self.event = tf.constant(event, dtype='fl...
ce4b56134e619982ad5f03d77772554729b600257352ab9a07b45cd0a7fe57f6
Python
1,928
67
from .meta_arch import BaseArch from ppdet.core.workspace import register, create from paddle import in_dynamic_mode __all__ = ['CLRNet'] @register class CLRNet(BaseArch): __category__ = 'architecture' def __init__(self, backbone="CLRResNet", neck="CLRFPN", ...
8dfa317c08a396c79e74e0d745e135463769a769195d6f489edcd3e02b09ae09
Python
1,929
56
import os import shutil import pytest import unittest import torch from reinvent.runmodes.create_model.create_libinvent import create_model @pytest.mark.integration @pytest.mark.usefixtures("json_config") class TestCreateModel(unittest.TestCase): def setUp(self): self.workdir = self.json_config["MAIN_TE...
b0b5dabddb7acff3534ff89b5903cbe734a5210e06688f7f47b5b21ee65c2669
Python
1,930
60
# Copyright 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Base abstract optimizer class module.""" import abc from importlib import import_module from os.path import splitext from typing import Dict from numpy import ndarray from openfl.plugins.frameworks_adapters.framework_adapter_interface...
beaafef0f69940d8aa09b0733a941f75a841f9c833e883711e4e9fdb7f11034c
Python
1,933
58
import numpy as np import mrestimator as mre def h_offset(exp_fit: mre.FitResult, expoffset_fit: mre.FitResult) -> bool: """ Test the H_offset hypothesis as described in (Wilting&Priesemann 2018; Supplemental Note 5) :return: if True, then the data set should be rejected for m estimation """ retur...
db9c83f67b1e69c51625bb4b5863ca6971b05912501682f77996a26d1f04cf45
Python
1,933
61
"""Tests for ScaffoldSimilarity._find_similar_scaffold.""" import pytest from reinvent.runmodes.RL.memories.scaffold_similarity import ScaffoldSimilarity # Benzene and toluene — atom-pair Tanimoto similarity is moderate BENZENE = "c1ccccc1" TOLUENE = "Cc1ccccc1" CYCLOHEXANE = "C1CCCCC1" # very different from benzen...
9452b6e0748067a8c0050a1ef30afada9099028c85a2eea962044e4ff90f04f4
Python
1,939
75
import random import pytest import geomstats.backend as gs from geomstats.geometry.hypersphere import Hypersphere from geomstats.geometry.poincare_ball import PoincareBall from geomstats.learning.expectation_maximization import ( GaussianMixtureModel, RiemannianEM, ) from geomstats.test.parametrizers import D...
2e00b0148f2a31732ed41200c13b1e1ca9a80697053c76dc6e6f05bdb331da32
Python
1,941
51
"""Load a folder-backed collection of SanPy recordings and analyses.""" from pathlib import Path import sanpy def main() -> None: """Summarize an analysis directory and load one saved analysis. Raises: RuntimeError: If the example recording or its analysis cannot be found. """ # Locate the ...
8db823588ca1933ab8acacac538a40f64e909b67727c6d0e6adff171d8d081f7
Python
1,941
51
"""Tests for RL distance penalty in reinvent/runmodes/RL/distance_penalty.py.""" import pytest import numpy as np import torch from reinvent.runmodes.RL.distance_penalty import get_distance_to_prior # ── torch.Tensor branch ────────────────────────────────────────────────────── def test_distance_penalty_tensor_abo...
fe08ff7e7613765be8bf9b5c944e6f2e8eabb1f30d2fd2c552f4420699769d3f
Python
1,941
58
"""Differentiable Radon operators with filters for current PyTorch versions. Filter formulas adapted from pytorch_radon, Copyright (c) 2019 phernst, licensed under MIT: https://github.com/mozanunal/pytorch_radon. """ import torch from pytorch_radon import IRadon as _IRadon from pytorch_radon import Radon from torch i...