sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
257777e88c74e8ec0ed3e2960504963cdaef96b1820b9d9688c347b0f62a9d21
Python
1,200
38
import pytest import numpy as np from deepface.modules import verification as target @pytest.mark.parametrize("dim", [2, 7, 8, 128]) @pytest.mark.parametrize("sign", [1, -1]) def test_single_parallel_vectors(dim, sign): a = np.ones(dim, dtype=np.float32) with np.errstate(invalid="raise"): actual = tar...
3dbb73c064f151a3c029c25074c7db556677e436c601eb548663df100856616c
Python
1,200
30
# built-in dependencies from typing import Optional # project dependencies from deepface import DeepFace from deepface.commons.logger import Logger logger = Logger() # pylint: disable=too-few-public-methods class ModelService: def __init__( self, face_recognition_models: Optional[str] = None, ...
48f97c83792618255b9accf50e5db489a6fd99681e3269a652519605716e181a
Python
1,200
31
import logging from agent.data.sql.sql_mgmt import get_connection, update_text_field logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) TABLE = "annotate_sentence" def do_preliminary_fc_classification(external=False): ...
94bb408bedf55f09996f3b26e6a49bb4b382ba936b8162fb516ec4bf87681cd5
Python
1,200
46
# __serve_example_begin__ import json import tempfile from ray import serve from ray.serve.config import AutoscalingConfig, AutoscalingPolicy # Create a JSON file with the initial target replica count. # In production this file would be written by an external system. scaling_file = tempfile.NamedTemporaryFile( mo...
eeb2b3c254d122fd1c56d7e6fc67fa9ef0c7c509742f1db4b3624c3140096f21
Python
1,200
41
#!/usr/bin/env python # Copyright 2023 The HuggingFace Team. 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...
bb3a1d30ffbdaf96642c940b9465d2e52fd52ab24db900f125e083d2014dc054
Python
1,201
43
"""Main module of ydata-profiling. .. include:: ../../README.md """ # ignore numba warnings import warnings # isort:skip # noqa import importlib.util # isort:skip # noqa from warnings import warn from data_profiling.compare_reports import compare # isort:skip # noqa from data_profiling.controller import pandas_de...
86b438650280eb64e469530cf077a59a881402197a5eb8056b77957b0e8a8f06
Python
1,203
43
import json import os import subprocess import numpy as np import torch def get_sample_weights(target, class_weight): return torch.Tensor([class_weight[t.int()] for t in target]) def correct_negative_edges(target): return target - 1, [i for i, t in enumerate(target) if t.item() != 0] def ...
f946e6b91a084c72fb44bde99c8cb6ec69e29f070e3148739a2e38d769bcc2d4
Python
1,203
42
from Prediction import ddpred from Para import parameter import numpy as np import torch import os trainday = 30 target = 'pHVAC_estimation' zones = 'Single' par = parameter() par.get_para(tar=target, zone=zones) ddp = ddpred() adj = np.array([[1]]).astype('float32') ddp.data_ready(num_zone=1, ...
aaf7fbd2e676f9d08836b8c3420bfb1929eeae74ad1ae1af81aab698c7c83c44
Python
1,204
24
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
101525e3b6019b23300a4ca4e4c5deb49213df6fc879967c80c4f0ed26de9aa7
Python
1,205
35
"""High level manager for refining and summarizing project scope.""" from __future__ import annotations from typing import List from .brief import BriefGenerator, ProjectBrief from .clarifier import Clarifier class ScopeManager: """Coordinate clarification and brief generation steps.""" def __init__(self,...
d4ab2bab983657a8b6eb762b29d57d1d83d5788911f6a01bd05477daa8cb0f6d
Python
1,206
43
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import argparse from fairchem.core.models.equiformer_v2.eqv2_to_eqv2_hydra import ( convert_checkp...
fef72a096937b255941705a624d6894845f8099f860e109e9efddbfe685d9325
Python
1,206
22
import sys sys.path.insert(1,'../src_simulation/') from sim_helper import sim_helper if __name__ == '__main__': sim_ = sim_helper(n_sim = 200, heritability_l = [0.8, 0.5, 0.25], percent_causal_l = [0.1,0.3], beta_var_l = [0.1], image_modality = None, random_seed ...
2cdffa53c276906deffd6e96d773249877a364e3d9162201408d4bf53b0cb0e2
Python
1,207
34
"""Test AIR internal utilities (under ray.air._internal).""" import os import pytest import ray from ray.air._internal.filelock import RAY_LOCKFILE_DIR, TempFileLock def test_temp_file_lock(tmp_path, monkeypatch): """Test that the directory where temp file locks are saved can be configured via the env vari...
88916221514a6c901488c4b89f30c5f4d3f5ea4327cc8eedf64cb789ca44e9ae
Python
1,207
25
from projectmetis.python.models.model_dataset import ModelDataset class LearnerTrainer(object): def __init__(self, model_ops_fn, model_pb): """ The initial state of the model for every other trainer instance is unique. Therefore, we initialize the model once during the trainer object cons...
5bd5e096b876c999a998cf42d11acbeec27687d1ebcdc7443879df5c24baf055
Python
1,208
51
"""This is the script for `ray clusterbenchmark`.""" import time import numpy as np import ray from ray.cluster_utils import Cluster def main(): cluster = Cluster( initialize_head=True, connect=True, head_node_args={"object_store_memory": 20 * 1024 * 1024 * 1024, "num_cpus": 16}, ) ...
5e6671411aa80811935e7e7b9acb20b7309c34d842fa2fec5b1187e765eccc19
Python
1,208
42
# -*- coding: utf-8 -*- """ Created on Mon Jun 3 14:00:28 2024 @author: jpv88 """ from setuptools import setup setup( name='DCISIv', version='0.1', description='Decoding Cross-contamination using Inter-Spike-Interval violations', url='https://github.com/economolab/DCISIv', author='Jack Vince...
c5da2565983adf3494344560b43c493dbb011301ac0192dddab71d07e41b20a4
Python
1,209
37
"""Find the number of volumes we acquired for long vs short ITI sessions""" import nibabel as nb import glob DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti/derivatives' SUBS = ['sub-05', 'sub-06', 'sub-07', 'sub-08', 'sub-09'] for sub in SUBS: print('') # =========================...
f134fed15cb6ef0f02484b70110a53e6f1c609d21b77876c856742d023ee446d
Python
1,210
37
with open("/tmp/eLife_Metrics.tsv") as in_file: in_file.readline() image_dict = {} for line in in_file: line_items = line.split("\t") path_parts = line_items[1].split("-") image_unique_key = f"{path_parts[1]}____{path_parts[2]}" image_version = path_parts[3] if im...
12e47c2f1d178b7fd63f16b42959a9567b0d40e468f340bb74a3d2e496e60649
Python
1,211
25
import argparse import torch def parse_args(): parser = argparse.ArgumentParser() device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') parser.add_argument('--device', type=str, default=device) parser.add_argument('--path', type=str, default='C:\\Users\...
d9063ca210f44b6bfe4e8510a56f851665dca2fd030b80f7d5536985244b0f01
Python
1,211
51
# -*- coding: utf-8 -*- """ Created on Sat Jan 23 15:15:47 2016 @author: matt """ # show movement of a particular trajectory, time color coded tra = traj[0,:,:] x = plt.scatter(tra[:,1],tra[:,0],c = xs) cbar = plt.colorbar(x) cbar.set_label('Time (d)', rotation=90) plt.show() # zoom out to the entire image x = plt.s...
e037c192e692bf5e3bfea6786b5329fecf46ff73a6c9274cdd4a80a3adb43a88
Python
1,211
55
from abc import ABCMeta, abstractmethod class Env(object, metaclass=ABCMeta): """RL learning environment. This serves a minimal interface for RL agents. """ @abstractmethod def step(self, action): raise NotImplementedError() @abstractmethod def reset(self): raise NotImpl...
451b090d80602150b64120702461579139c6e78d0f98fd57a456033db73c8d4e
Python
1,212
27
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
6bda1a09422605d1eaac3f7681fa418342e37a16a25b5227839d1ad6bddccba1
Python
1,212
24
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
6bdaae809c217351c9fce47158d0aca35027978ef5daa3816d5ac026bbd12b4f
Python
1,212
36
import unittest import torch from rising.transforms.functional.channel import one_hot_batch class TestChannel(unittest.TestCase): def test_one_hot_batch_1dim(self): inp = torch.tensor([0, 1, 2]).long() outp = one_hot_batch(inp) exp = torch.eye(3) self.assertTrue((outp == exp).all...
2bb0d2fc9b2d5065c41824b28924ac0f3ee654061a15c0efcee87c42a34351f6
Python
1,213
46
""" test for the 'i_offset' parameter of the LIF neuron """ from spinnaker2 import snn, hardware, brian2_sim def test_lif_curr_exp_i_offset(): params = { "threshold":1., "alpha_decay":1., "i_offset":0.123, "v_reset":0.0, "reset":"reset_by_subtraction", ...
8f78c12022d5d9dc9c7a827701bca36ec272225c1848006614217cd31b67c8f5
Python
1,213
22
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This library is fre...
199ca5f62b865e707fc23b4ab10f04ba96216bb96afacda64abd92ab12adcede
Python
1,214
52
import os import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt sns.set_theme(style='whitegrid') filename = os.path.splitext(os.path.basename(__file__))[0] df = pd.read_csv('../data/paperdiff.csv', index_col=1, parse_dates=True, ) df['Environment'] = df['Environment'].str.ca...
d4a8ac0e2f9bf18648897017fb3fa4f22148e5981b9c9beecddd4c032eed60be
Python
1,214
25
import pandas as pd file = "MetS_GWAS_MetS.csv" df_ukb = pd.read_csv(file, sep=",", index_col=False) df_ukb = df_ukb[['SNP', 'CHR', 'BP', 'A1', 'A2', 'MAF', 'est', 'SE', 'Pval_Estimate']] n_init = len(df_ukb) df_ukb = df_ukb[df_ukb['MAF'] > 0.01] print("Number of SNPs dropped by MAF filter (> 0.01): {:,}".format(n_ini...
0086b5ede44bc1a572e89a4363150bdbc5fb943b84c4eef965ff7628280875cb
Python
1,215
40
#!/usr/bin/env python3 import argparse import nbformat def convert_notebook(input_path: str, output_path: str) -> None: """ Read a Jupyter notebook and write a Python script. Cells that load or autoreload extensions are ignored. """ nb = nbformat.read(input_path, as_version=4) with open(output...
5a2f46f0430645d5adc23dfe9752f7283431c1c8c694142728d7787b63cce572
Python
1,215
36
import unittest from spinnaker2.mla.mla_config import Conv2DConfig class TestStride(unittest.TestCase): def test_base(self): c = Conv2DConfig() # stride_x for n in range(4): c.set_stride_x(2**n) self.assertEqual(c.stride_x_2_power_n, n) self.assertEqua...
236bb4e21ebe5769718852045aae4b2880c5b635b45507e70bc15e3b7c86738b
Python
1,216
51
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """Custom Exceptions for aihwkit.""" class AihwkitException(Exception): """Base class for exceptions related to aihwkit.""" class ModuleError(AihwkitExce...
483e4d8e1217ae88b44a2767468337a284b0d45ec48c5d6e1cd69a02073a834e
Python
1,216
34
import pandas as pd from sklearn.datasets import make_classification from siapy.features import AutoSpectralIndicesClassification from siapy.features.helpers import FeatureSelectorConfig from siapy.features.spectral_indices import get_spectral_indices # Create spectral-like data X, y = make_classification(n_samples=3...
ad8a1c17d60dcd043b7601e4d56100a453b083b2a5d4c8294bbefbea8185152e
Python
1,216
49
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ """ import argparse import pandas as pd def explode(df, idx_cols, list_col): """ Explode a column of lists into one row per list element """ df = df.set_index(idx_cols) df[list_col] = df[list_col].str.split(',') df = df[list_col].apply(pd...
dfe7aac15ab044bb325f025b6b1ca2f7c43de59af4f64d419c7cc47b67f20b5b
Python
1,217
38
from pathlib import Path from siapy.entities import SpectralImageSet # Set the path to the directory containing the data # !! ADJUST THIS PATH TO YOUR DATA DIRECTORY !! data_dir = "./docs/examples/data" # Find all header and image files in the data directory header_paths = sorted(Path(data_dir).rglob("*.hdr")) image...
6fee65398bc2bcc71dc3fd9c6145c36279b60cafa092130b01aac1750e6d83ec
Python
1,218
42
import numpy as np import pandas as pd from data_profiling.config import Settings from data_profiling.visualisation.missing import ( plot_missing_bar, plot_missing_heatmap, plot_missing_matrix, ) def missing_bar(config: Settings, df: pd.DataFrame) -> str: notnull_counts = len(df) - df.isnull().sum() ...
c26476933f7021f1d2abdac4d542fdf1947a000a994b6e6938f04887954f97a5
Python
1,220
34
import unittest import numpy as np from neuron_morphology.features.layer.reference_layer_depths import \ ReferenceLayerDepths class TestReferenceLayerDepths(unittest.TestCase): def test_thickness(self): depths = ReferenceLayerDepths(1, 2) self.assertEqual(depths.thickness, 1) def test_...
31a3abbd72b5dd01d228bea772c346066fec5c79cb3ceef702f60b12f825e076
Python
1,221
38
import torch from torch.nn import Embedding, Linear, LeakyReLU, PReLU, Parameter class NTD(torch.nn.Module): def __init__(self, n_x, n_y, n_g, rank, random_state=1234567): super().__init__() torch.manual_seed(random_state) # Define embedding layer along x, y, g modes self.e...
80a72b37379a65d85d11a9539c5a1bcab91a233886420497f76d00f969b2354d
Python
1,221
41
""" Flavours registry information """ from data_profiling.report.presentation.core import Root from data_profiling.report.presentation.core.renderable import Renderable _FLAVOUR_REGISTRY: dict = {} def register_flavour(name: str, mapping: dict) -> None: _FLAVOUR_REGISTRY[name] = mapping def get_flavour_map...
c9885254a4ac6bedd25b186991703f851b080cdddeec5c8bd5ccd15d23534982
Python
1,221
41
import argparse import numpy as np from spiking_readout.dataset import SpikingDataset from spiking_readout.readout import Readout def predict(dataset_path, model_path, output_file=None): # Load data dataset = SpikingDataset.from_file(dataset_path) # Assert data is not empty empty_dataset = np.any([sa...
4a3fb448ae613a19d621143fa44ba2762d69c73ac4da521abf05048b839fc5bb
Python
1,222
45
from Load_prediction import ddpred from Para import parameter import numpy as np trainday = 30+30 zones = 'Single' modes='Cooling' par = parameter() par.para_load(zone=zones) ddp = ddpred() adj = np.array([[1]]).astype('float32') ddp.data_ready(num_zone=1, enLen=par.paradic["encoLen"], ...
07346088e696bb6bc87ec8ceb99a661fa1fa3265500f0b3dc0ca12b906191289
Python
1,223
38
import inspect import yaml def pprint_dict(d): """ Pretty print a dictionary. """ print(yaml.dump(d, default_flow_style=False)) def print_help_for_function_arguments(func, arg_names=None, print_only_required=False): """ Prints the help text of arguments of the DeepDeWedge commmands. """...
80366f9fc290fe950ad4e6b2ff16b92432a22463a7911f4931c0bc6c7eddc7da
Python
1,223
43
# 3rd parth dependencies try: from flask import Flask from flask_cors import CORS from dotenv import load_dotenv except ImportError as import_err: raise ImportError( f"{import_err.name} is required to run the deepface api. " 'Please run `pip install "deepface[api]"` to install it.' )...
a13caa9a4beadc232e3c547b908ef357e434150fc485f7f5dbbc6d9568075aac
Python
1,223
34
import torch.nn as nn from optuna import Trial, Study from .base import BaseModelConfig from argparse import Namespace, ArgumentParser from nyumets.networks.nets.sttunet import STTUNet class STTUNetConfig(BaseModelConfig): model_name = "unet_stt" def setup_search_space(self, trial: Trial, args: Namespace)...
bb5617bb2515273f529b6c19274ef1c07ef11f3c00c63f973fe649e55bdf720b
Python
1,223
26
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
f46cb6320ec492ec0ea4d521eda61dad8b6bd7089199c23bb12bc9f0a813aaf4
Python
1,223
66
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import tempfile import pytest import yaml from fairchem.core.common.utils import UniqueKeyLoader @p...
756f8cf35da3ebe7a1f4c5d5448341b222bab977f75400d1eb3dc0e9fdb70d77
Python
1,224
46
import sys import pytest from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from ml4h.arguments import parse_args from ml4h.test_utils import TMAPS as MOCK_TMAPS from ml4h.test_utils import build_hdf5s def pytest_configure(config): pytest.N_TENSORS = 100 config.addinivalu...
369d66bb8d85432ff331b6511aeb174649bb710267875482efaf15be7480fee4
Python
1,225
23
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
67681e4637546d6694141885b33d77ecee69bbfa075d56f6f1fa0f0608acd9e9
Python
1,225
37
import logging from ray._private.ray_constants import DEBUG_AUTOSCALING_STATUS_LEGACY from ray.experimental.internal_kv import _internal_kv_initialized, _internal_kv_put """This file provides legacy support for the old info string in order to ensure the dashboard's `api/cluster_status` does not break backwards compat...
dc6c7755974a7a7dc1ada103efbcbd133475da0e260331cdbbad1f8e676db321
Python
1,225
42
import os import click from ci.ray_ci.tester_container import TesterContainer from ci.ray_ci.utils import ci_init, logger from ray_release.configs.global_config import get_global_config @click.command() @click.argument("team", required=True, type=str) @click.argument("bazel_log_dir", required=True, type=str) def m...
2e33cd9e15b2b8be969d4af39870219b4abe1bb535e44c8884af5db3c3a6fc1c
Python
1,226
39
import os try: print('SlURM_JOB_ID',os.environ["SLURM_JOB_ID"]) except: print("no slurm id") import matplotlib matplotlib.use('agg') import numpy as np import matplotlib.pyplot as plt import pandas as pd import tensorflow as tf import tensorflow.keras as K import tables import gc import argparse import scipy t...
4033e3169f7aadc0eb0a058d9352c0f8ed260495b3df2220715df8353217c4e6
Python
1,226
49
import sys import click from ci.ray_ci.automation.docker_tags_lib import list_image_tags from ci.ray_ci.docker_container import ( ARCHITECTURES_RAY, ARCHITECTURES_RAY_LLM, ARCHITECTURES_RAY_ML, PLATFORMS_RAY, PLATFORMS_RAY_LLM, PLATFORMS_RAY_ML, PYTHON_VERSIONS_RAY, PYTHON_VERSIONS_RAY...
2ee85b50d128bbc62b8c31087930a75a75d1993f90f014e4f9d26058d0a243db
Python
1,227
47
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations from numbers import Number from typing import TYPE_CHECKING, Protocol, overload, runtime_checkable if ...
effc8b91eddc9a957b2e870efd484b9ded06b270cfb078ccc2511136e91a0c8f
Python
1,227
32
from .performance import F1_score, d_prime, performance_curve, calculate_performance from .statistics import test_responsiveness from .convergence import test_convergence from .responsiveness import calculate_responsiveness from .weights import analyze_weights, import_W_signed, import_W_force, import_W_force_embedded ...
5c508602274d58a404cf3f37b2fd9a9c479f8121ce616b873f5603c5d78d3249
Python
1,228
46
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
a5ea285c3932a3f27132b59023ed393ae0c230272c6735b84418fe6b392a5214
Python
1,228
34
import torch.nn as nn from optuna import Trial from argparse import Namespace, ArgumentParser from .base import BaseModelConfig from monai.networks.nets import SwinUNETR class SwinUNETRConfig(BaseModelConfig): model_name = "swinunetr" def setup_search_space(self, trial: Trial, args: Namespace) -> Namespace...
ea537fe3169ec6091428a7f00a5d151461b74594eb39fea43f842fc3f6f7d448
Python
1,229
36
import sys import pandas as pd def Pair_mr(): d1 = pd.read_csv(qtl1, sep='\t', header=None, usecols=[0,1], names=['Phenotype', 'SNP']).groupby('Phenotype') d2 = pd.read_csv(qtl2, sep='\t', header=None, usecols=[0,1], names=['Phenotype', 'SNP']).groupby('Phenotype') dict1, dict2 = {}, {} for Phe1, s1 in...
32a9d6bfb06b932e57426f20a4ec2dc258f96e9ab74122a4b63d423c731e78f8
Python
1,231
41
import pytest import torch.nn as nn import sinabs.layers as sl @pytest.mark.parametrize( ("pooling", "layer_type", "expected_pooling", "expected_scaling"), [ (2, sl.SumPool2d, [2, 2], 1), ((2, 2), sl.SumPool2d, [2, 2], 1), (3, sl.SumPool2d, [3, 3], 1), ((4, 4), sl.SumPool2d, [...
51bd6544e8b43d5526be8d149618981a5d7577ba52827808dd978afe807e6725
Python
1,231
47
from pathlib import Path from siapy.entities import SpectralImage from siapy.transformations.image import ( add_gaussian_noise, area_normalization, random_crop, random_mirror, random_rotation, rescale, ) # Set the path to the directory containing the data # !! ADJUST THIS PATH TO YOUR DATA DIR...
e4922c6d4fe73ce715c5d32a257a416342d0b3540a162bb68d2c9d9ae190f8ec
Python
1,232
24
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. #...
7f9aa4a992916f88a00684bdd9faf862360d51bb652a4b0b64dc8cbec3f3a7a9
Python
1,234
44
""" Test for issue 437: https://github.com/Data-Centric-AI-Community/data-profiling/issues/437 """ import numpy as np import pandas as pd from data_profiling import ProfileReport def test_issue437(): try: # pd.NA does not exist in some pandas versions _ = pd.NA except: # noqa: E722 p...
c768874927c83a6e3dc2c67532dcd13f7e5030f11dbbbc78a8eb1c499583ff71
Python
1,234
36
from typing import Any, Callable, Dict, Optional import pyarrow from ray.data.block import BlockAccessor from ray.data.datasource.file_based_datasource import _resolve_kwargs from ray.data.datasource.file_datasink import BlockBasedFileDatasink class CSVDatasink(BlockBasedFileDatasink): def __init__( sel...
ee43dab1dcc9e476fa4734fa4d7a818f50c72325e77749279e3eab83228bd3f0
Python
1,234
36
from typing import Any, Callable, Sequence import torch from torch.utils.data._utils.collate import default_collate def _to_recursive(batched: Any, device: torch.device) -> Any: if isinstance(batched, torch.Tensor): return batched.to(device) elif isinstance(batched, list): return [x.to(device...
12d04875b1dbce106aa207219d6a1f0e3c2996fbda3e267500b920ed6b46b13e
Python
1,235
38
import pathlib path = pathlib.Path.cwd() if path.stem == 'tmb_survival': cwd = path else: cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')] import sys sys.path.append(str(cwd)) from matplotlib import pyplot as plt from lifelines import KaplanMeierFitter from figures.sim_tools import * from lifeli...
dc0f1a1360576123ff8ec21be19f67e8009b2bc26da1338714fc67cba20f4cf4
Python
1,235
36
import torch.nn as nn import torch.nn.functional as F from pfrl.initializers import init_chainer_default, init_lecun_normal class MLP(nn.Module): """Multi-Layer Perceptron""" def __init__( self, in_size, out_size, hidden_sizes, nonlinearity=F.relu, last_wscale=1 ): self.in_size = in_size...
3bd67eaa26f2e2fcacc660090e3e395169184b4c852c2b32a28764547fd30953
Python
1,236
44
# flake8: noqa # fmt: off # __actor_creator_failure_begin__ import ray import os import signal ray.init() @ray.remote(max_restarts=-1) class Actor: def ping(self): return "hello" @ray.remote class Parent: def generate_actors(self): self.child = Actor.remote() self.detached_actor = Act...
3e7fd1239714fff4411a8cc8a8896b96b9868789b7cd246ac460da0628232d0a
Python
1,236
46
#%% import timeit import numpy as np import os import caiman.external.houghvst.estimation as est from caiman.external.houghvst.gat import compute_gat, compute_inverse_gat import caiman as cm from caiman.paths import caiman_datadir #%% def main(): fnames = [os.path.join(caiman_datadir(), 'example_movies', 'demoMov...
8634e945c393238d3f7b5e657b76dfbf41ce547b6fc96552dfe3c765de577c70
Python
1,237
42
# -*- coding: utf-8 -*- """ This is implementation of model of corresponding to the article `Large scale model of cat primary visual cortex`. Antolík, J., Cagnol, R., Rózsa, T., Monier, C., Frégnac, Y., & Davison, A. P. (2024). PLOS Computational Biolology. https://pmc.ncbi.nlm.nih.gov/articles/PMC11371232 """ import m...
05c5c6cbd3682d611c52fcae8296cf1254bf13d33b8d1e2a05dbfe4145019dfd
Python
1,238
41
from typing import Union, List from torch.nn import Module from torch.nn.modules.loss import _Loss from src.losses.adversarial.utils import AdversarialLosses from src.losses.adversarial.adversarial import AdversarialLoss def get_discriminator_loss(config: dict) -> Union[_Loss, Module]: d_losses = [d_loss.value ...
2e81c1125040571344ca6eb31b2728eebdac822b33c4a144721c48806981d032
Python
1,238
26
from monai.losses import ( DiceLoss, DiceFocalLoss, FocalLoss, GeneralizedDiceLoss, GeneralizedDiceFocalLoss, DiceCELoss, TverskyLoss ) def get_loss_function(loss_function: str = 'dice'): if loss_function.lower() == 'dice': loss_function = DiceLoss(include_background=False, to_o...
91ff2b11934e5ae896b1bcff09fedaf691116a5343c92fa690b1b626254c33c0
Python
1,238
48
""" script to test spike routing in lif_neuron apps. """ import os from spinnaker2 import hardware, snn def test_routing_with_lif(): neuron_params = { "threshold": 1.0, "alpha_decay": 0.9, } n_stim = 1 stim = snn.Population(1, "spike_list", params={0: [1, 2, 3]}, name="stim") pop...
3966488c8f7e6ea49bb789f3d6cc7554dbbaae1e064c6ff4945c060789348ad2
Python
1,239
29
import torch import os import esm def load_model_and_alphabet(device): """Load the ESM model and alphabet.""" model, alphabet = esm.pretrained.esm2_t30_150M_UR50D() model.to(device) return model, alphabet def get_protein_embeddings(model, alphabet, sequence, device): """Get protein embeddings from...
52c98f64ac17bcbc6411845a3f78f7990f8a0545958824cd4c4d00c27c7dfc1c
Python
1,240
36
import os import matplotlib.pyplot as plt def main(): LOG_DIR = "./MODEL/SPLAM_v11/LOG/" OUT_DIR = LOG_DIR + "IMG/" os.makedirs(OUT_DIR, exist_ok=True) ########################################## # Plotting train & test separately ########################################## for target in ["T...
dd5ba01cef47429427e9d8c6b87417fc269ce5b05787dbd4dea3ea7b49c98a83
Python
1,240
45
import marshmallow as mm from argschema.schemas import ArgSchema, DefaultSchema from argschema.fields import ( InputFile, List, Float, Int, Nested ) from neuron_morphology.transforms.affine_transformer._schemas import ( AffineDictSchema ) class InputParameters(ArgSchema): swc_path = InputFile( des...
7a9dba6e06b9ac2293fa5bffee65aaf17c4986b911fb0fabd331073828902a95
Python
1,241
34
import torch.nn as nn from optuna import Trial, Study from .base import BaseModelConfig from argparse import Namespace, ArgumentParser from monai.networks.nets import BasicUnet class STTUNetBackboneConfig(BaseModelConfig): model_name = "unet_sttbackbone" def setup_search_space(self, trial: Trial, args: Na...
b232ed3d846dc020eab073362f2f19d06725e267e076dd85906cdfa306f03b91
Python
1,241
60
# 3rd party dependencies import cv2 import matplotlib.pyplot as plt # project dependencies from deepface.modules import streaming from deepface import DeepFace img_path = "dataset/img1.jpg" img = cv2.imread(img_path) overlay_img_path = "dataset/img6.jpg" face_objs = DeepFace.extract_faces(overlay_img_path) overlay_i...
bcc792853b8dfeb2d40736be08f2a75eda489dc11df9c7aec140ba52e6e9df77
Python
1,241
40
import torch import soft_rank_pytorch from metrics import _rank_data def spearman_loss(pred, true, regularization_strength, regularization): assert pred.device == true.device assert pred.shape == true.shape assert pred.shape[0] == 1 assert pred.ndim == 2 device = pred.device soft_pred = sof...
b0ef91c0bf679b51f7bcb275af6bec0ead066f01d9b68f32b75f9f8e0f30a72f
Python
1,243
29
import numpy as np from ray.data._internal.datasource_v2.interfaces.file_manifest import FileManifest from ray.data._internal.datasource_v2.interfaces.in_memory_size_estimator import ( InMemorySizeEstimator, ) from ray.util.annotations import DeveloperAPI # Default Parquet encoding ratio: in-memory is ~5x on-disk...
00321f29dd7ad9d989c693f38971dba56deb386f51ea4b61d96888e5fa0e0167
Python
1,244
25
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
176de0141be3b6554286510823c9da65754b99c585da5dd9483093f054abb551
Python
1,244
40
import os import warnings warnings.filterwarnings("ignore") # load in directories from language.constants import DATA_DIR from language.preprocess import Task, Prescreen def run(data_type='task'): """preprocess task or prescreen data Args: data_type (str): default is 'task'. other option is 'prescr...
455556842a2851284e594b648f9aa8a213d4bcbc4429e5f30fba8ffa9f0c3086
Python
1,245
38
from ._version import get_versions __version__ = get_versions()["version"] del get_versions __author__ = "Justus Schock, Michael Baumgartner" __author_email__ = "justus.schock@rwth-aachen.de" __license__ = "MIT" __copyright__ = "Copyright (c) 2019-2020, %s." % __author__ __homepage__ = "https://github.com/PhoenixDL/r...
a5cf65927a4516bf3a637818224fbdcc04ede2d8ac7de3c26b17133d67d0285d
Python
1,245
41
import pathlib import urllib.request import numpy as np import pytest from cebra.integrations.sklearn.cebra import CEBRA MODEL_VARIANTS = [ "cebra-0.4.0-scikit-learn-1.4", "cebra-0.4.0-scikit-learn-1.6", "cebra-rc-scikit-learn-1.4", "cebra-rc-scikit-learn-1.6" ] @pytest.mark.parametrize("model_variant", MO...
ab9817f22d2b2352d89d60289cc932572cae93ebdada8722fbafea58b7e6426f
Python
1,245
42
# -*- coding: utf-8 -*- """ This is the implementation of the model corresponding to the pre-print `Iso-orientation bias of layer 2/3 connections: the unifying mechanism of spontaneous, visually and optogenetically driven V1 dynamics` Rózsa, T., Cagnol, R., Antolík, J. (2024). https://www.biorxiv.org/ TODO: Update """ ...
1d1ace2113e55e3b1089df182dcda8026213c6cf677b1e712d4bdccb566f52ff
Python
1,246
31
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. #...
386a60bde844c48732ed517019f144693f6309d833a419aa766e06a6adf0b029
Python
1,246
34
import os import sys import copy from datetime import datetime import argparse import numpy as np from aptnn.io.xyz import Trajectory, write_frame, write_conf parser = argparse.ArgumentParser(description='Takes a trajectory XYZ file and displaces the respective atom identified with "atom_id" in the comment line') p...
5a6f937a74075074dc451e1ba7ce1f444926ea3386f247dc210850f39f9b1748
Python
1,246
31
# ------------------------------------------------------------------------------------------------------------------------------------- # Following code curated for Bio-Diffusion (https://github.com/BioinfoMachineLearning/bio-diffusion): # --------------------------------------------------------------------------------...
615c71f0ca013e36739e0678094c5d1cb8cc5c2deac7df592909cc4d2503e0be
Python
1,246
40
# Luis del Peso # Modified by A. Mathelier # Vancouver, Jan 2012 from Bio.SeqRecord import SeqRecord from Bio.Seq import Seq from Bio.Alphabet import generic_dna from Bio import SeqIO from altschulEriksonDinuclShuffle import dinuclShuffle from utils import * def shuffle_window(ss, wl, step): bs = ss[:] for i in r...
baf91c8b087c053da7b81319de0c7f516100bd04ccd87a4af74d42f65516d89b
Python
1,246
41
from pfrl.agents import dqn from pfrl.utils import evaluating from pfrl.utils.recurrent import pack_and_forward class DoubleDQN(dqn.DQN): """Double DQN. See: http://arxiv.org/abs/1509.06461. """ def _compute_target_values(self, exp_batch): batch_next_state = exp_batch["next_state"] ...
1f840de6f4c1e2885fbb8078a4a51f360251080abfad68fd37641f6002ed0351
Python
1,247
40
from typing import Any, Callable, Optional from data_profiling.report.presentation.core.item_renderer import ItemRenderer from data_profiling.report.presentation.core.renderable import Renderable class Variable(ItemRenderer): def __init__( self, top: Renderable, bottom: Optional[Renderabl...
b025138a9a6342942c8a1c6993ef03c2d853333e480da30802deb968bd469447
Python
1,248
44
import numpy as np from sklearn.decomposition import PCA from umap import UMAP def reduce_dim( x, n_components, method='pca', pre_normalize=False, post_normalize=False): if n_components >= 1: n_components = int(n_components) isfin = np.isfinite(x).all(-1) if pre_normalize: ...
312e790efe1b748d54012f448132db19731c2f3fe6c8fbe6559bade161086852
Python
1,249
41
import pathlib path = pathlib.Path.cwd() if path.stem == 'tmb_survival': cwd = path else: cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')] import sys sys.path.append(str(cwd)) from model import utils from matplotlib import pyplot as plt from lifelines import KaplanMeierFitter from figures.sim_to...
b0876d38f57adef620b1ddcc115c2e6d3dbee892a348256e2c01c56aeeb81e49
Python
1,249
47
# -*- coding: utf-8 -*- """ """ from setuptools import setup, find_packages import runpy from os.path import dirname, join HERE = dirname(__file__) with open(join(HERE, 'README.md'), "rb") as f: long_description = f.read().decode("utf-8") setup( name='vtkplotlib', version=runpy.run_path(join(HERE, "vtkp...
f0328ade9844d3a81acd4a6af337bc87cc003aa105d9f538af01c87094118367
Python
1,249
38
import numpy as np import torch def clip_l2_grad_norm_(parameters, max_norm): """Clip gradient L2 norm. This function works in the same way as `torch.nn.utils.clip_grad_norm_` with `norm_type=2`, but more efficiently on CPU as of PyTorch 1.4.0. Args: parameters (torch.Tensor or Iterable[torc...
32caceae449cd0fc6067e56ceb157cc02683bdda80d1585acfee4d5c31fe8ab8
Python
1,250
22
"""Vendored Bonsai-scout tree layout (upstream v1.0.0), CC BY-NC 4.0. Only ``my_tree_layout`` is carried, not the Dash application around it. The file is self-contained upstream (stdlib + numpy/pandas, no Bonsai imports); :func:`omicverse.external.bonsai.scout_layout` builds its ``Layout_Tree`` straight from an edge l...
647f40e3f72a81428f00d87e190e91e6df9d5375e9f4eee99dc253c2b5e348d0
Python
1,251
35
from typing import Callable, Iterable from ray.data._internal.datasource.sql_datasource import Connection, _connect from ray.data._internal.execution.interfaces import TaskContext from ray.data.block import Block, BlockAccessor from ray.data.datasource.datasink import Datasink class SQLDatasink(Datasink[None]): ...
bf18cfac88c517d319b97e93a65167ebff87acd3c0c6403b8496c0ba8d3015f6
Python
1,251
44
from typing import Tuple, Union class CellInteraction: def __init__(self, type1: str, type2: str): self.type1 = type1 self.type2 = type2 self.interactions = tuple(sorted([type1, type2])) def torch_str_key(self): return self.interactions.__str__() def interaction_types(...
77cba10b644e0e91b0579ce9748f2bc814f4089c8e028ae1fee6b9d35558d417
Python
1,253
42
# Copyright 2023 Google LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, sof...
fdee022eff9ecd39dae0eb5a3ec9695d25a2cd49ed8fbcdf8ee5309b01cbe276
Python
1,253
59
import numpy as np import matplotlib.pyplot as plt from spinnaker2 import snn, hardware neuron_params = { "threshold": 60., "alpha_decay": 0.9, "i_offset": 0.0, } stim = snn.Population( size=2, neuron_model="spike_list", params={0: [1, 5, 10, 15, 20, 26], 1: [2,...
1b2cb4fce41a693abbea3ba9143962d34e7aa7ea00d7b385e075b7cfca98ac83
Python
1,255
48
"""skorch base imports""" import sys import warnings import importlib.metadata from .history import History from .net import NeuralNet from .classifier import NeuralNetClassifier from .classifier import NeuralNetBinaryClassifier from .regressor import NeuralNetRegressor from . import callbacks from ._version import ...
1e6bc4bebdd41b542fe05e54f25482d8a5698ae9069a3a4f4d4cb90f9210f67e
Python
1,255
38
enhance_model = dict( _scope_='lqit', type='BaseEditModel', destruct_gt=True, data_preprocessor=dict( type='EditDataPreprocessor', mean=[0.0, 0.0, 0.0], std=[255.0, 255.0, 255.0], bgr_to_rgb=False, gt_name='img'), generator=dict( type='TIENetGenerator'...
d2647b9479117b77dae9d0f6c826438479e5c02a3c9a88245bb4142aa51a2728
Python
1,255
41
import os import argparse import cv2 import numpy as np def getImageRepetitive(fp): repetitiveMask = cv2.imread(fp,0) repetitiveMask = (repetitiveMask!=0) return repetitiveMask if __name__=="__main__": print "check" row_folders = ['row001_auto_out','row002_auto_out','row002_auto_out'] parser...