sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
fa72cb194c60492b1770d83f52a2402d5053014aa7055408feab533bb741919a
Python
1,942
54
import sys import numpy as np sys.path.append(' /home/kusch/Documents/project/co_simulation/TVB-NEST-proof/lib/soft/lib/python3.8/site-packages/') from neurolib.models.aln import ALNModel from neurolib.utils.loadData import Dataset import matplotlib.pyplot as plt print("start "); sys.stdout.flush() path_mpi_input = ...
29fd6df3f1e229625c8a8ddaf4fab30f88ba6555f9a031b62d7d2affcba88cab
Python
1,945
41
import json import pickle import argparse import torch from torch.utils.data import DataLoader from dig.ggraph3D.dataset import QM93DGEN, collate_fn from dig.ggraph3D.method import G_SphereNet from dig.ggraph3D.evaluation import RandGenEvaluator parser = argparse.ArgumentParser() parser.add_argument('--model_path', t...
0ed9c308096c1c0e02dd10bfc1aaa57052991bee61fa0f3496f7a1f760a269d4
Python
1,946
59
""" Divide the signal in each channel by their max/mean/median value. """ import numpy as np import argparse from pathlib import Path 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=Path, ...
7125a986656680d1c4a8b84866cf03e279ffa769257615ce1faa96cbba8a8a95
Python
1,947
48
from unittest import TestCase import torch import torch.nn as nn from smithers.ml.models.rednet import RedNet from smithers.ml.models.fnn import FNN if torch.cuda.is_available(): device = torch.device('cuda') else: device = torch.device('cpu') class Testrednet(TestCase): def test_constructor_0(self): ...
b5b234532a997d42a7d7d9b7a9c31f90f713e9e7e6a74cd1eabe7478e92843c9
Python
1,947
53
import argparse import numpy as np import pandas as pd import warnings from scipy.stats import ttest_1samp # Create an argument parser parser = argparse.ArgumentParser(description='Load data, make predictions, and save results.') parser.add_argument('file_name', type=str, help='Path to the data file') parser.add_argum...
3c97346c7024532440d5c6a357f4207a5d1945905b4f5be4ba90dbf7fb846dc3
Python
1,948
61
import os strA = "h" strB = "rs" # Process input lines and categorize them into output files based on conditions def process_file(input_file, output_prefix): with open(input_file, 'r') as infile: for line in infile: parts = line.strip().split('\t') if len(parts) >= 4: ...
e36ec51fa99e8de21011fa3aa9a7166e616d761b8ac5bdb8e979b72a0e7354c1
Python
1,948
48
from typing import List import pandas as pd from reinvent.chemistry.library_design.reaction_definitions.leaving_groups_dto import ( LeavingGroupsDTO, ) class StandardDefinitions: def __init__(self, definitions_path: str): # TODO: implement in config default path for reaction definitions self...
9cd9a8ffc8893d4abcb364be38a9346c433f99f7c19cfb616dae731e5969a233
Python
1,950
73
import seaborn as sns import matplotlib.pyplot as plt from scipy.cluster.hierarchy import leaves_list import numpy as np from scipy.stats import pearsonr def plot_hline_dend(position, text, c="gray", s=":", w=2): plt.axhline(y=position, color=c, ls=s, lw=w) plt.annotate( text, (0, position), ...
9df8447710025e94fee35670610f8930849748671243956f243aac8ba991f00e
Python
1,951
65
"""Visualization for Geometric Statistics.""" import logging import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # NOQA import geomstats.backend as gs from geomstats.geometry.special_euclidean import SpecialEuclidean SE2_GROUP = SpecialEuclidean(n=2, point_type="matrix") SE2_VECT = SpecialEucli...
74b4fa9ccdd1896247adad7b92b94eab730a0326a61d40ae1272b36b380e2960
Python
1,952
59
""" 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, ...
aee01b7b4802e96abc9913f87e1c895dbe87fd012359c0780b8a50bf6cc9867e
Python
1,952
47
import unittest from rdkit.Chem.rdmolfiles import MolToSmiles from reinvent.chemistry import conversions from reinvent.chemistry.library_design import bond_maker, attachment_points from reinvent.chemistry.library_design.fragment_reactions import FragmentReactions from tests.chemistry.fixtures.test_data import ( M...
5ffa0c3f2c75896aae2f347a9b6918fe986e241b4dceaa625be3df599d3a7a4c
Python
1,954
58
r"""Compute a geodesic in BHV space between two fully resolved trees with 5 leaves. In [BHV01], Figure 18, there are depicted the trees T and T', as well as the respective splits named e1, e2, f1, f1 at the axes. Furthermore, the geodesic between T and T' is depicted, and in this example, this scenario is reconstructe...
84a33c5c5b78cf68491ef54a97a493d6f073b49d0d32b969f2d130c366c8e1fa
Python
1,954
63
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
9074d2da98973d066f9a10dced7062a281560300b448dab67eee7f50b900d09c
Python
1,955
67
""" Does the Python binding give what the MATLAB toolbox gives? It must, and not approximately: both call the very same C. This is not a reimplementation of TFCE in Python, it is the same max-tree with a different caller, so anything other than bit-identical output means a binding bug -- a transposed volume, a face li...
e44265e99261fbf74d8a62575066e82e98e63b1461a62b2a5ab29fd9ebf69f74
Python
1,955
53
""" 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 from utils.io_utils import load_neo from utils.neo_utils import analogsignal_to_imagesequence, imagesequence_...
6f2892b86d10bac21f0ab666a4c0cdb753a948e3a4ae011d25cbf19a91778a41
Python
1,960
59
import argparse from torch.optim import Adam from . import register_optimizer from .base_optim import BaseOptim @register_optimizer("adam") class AdamOptimizer(BaseOptim, Adam): """ `Adam <https://arxiv.org/abs/1412.6980>`_ optimizer """ def __init__(self, opts, model_params) -> None: BaseOp...
c25f9b75429fc84fe50964a923b525d891111cdf0e3f619431c973136490dba3
Python
1,960
62
# Copyright (c) 2021 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...
efc2493fb8039fa5d40db6463735c0861500305181251abf7fadf578d1faf0a9
Python
1,961
45
import shutil from dig.sslgraph.evaluation import GraphUnsupervised from dig.sslgraph.utils import Encoder from dig.sslgraph.dataset import get_dataset from dig.sslgraph.method import GraphCL, InfoGraph, MVGRL def test_GraphUnsupervised(): root = './dataset' dataset = get_dataset('MUTAG', task='unsup...
a85ab02a16aa90159bc07278622dab2024466165181820dcd24caacc2e2e2a98
Python
1,962
69
import unittest from deeprank_gnn.NeuralNet import NeuralNet from deeprank_gnn.ginet import GINet import torch import os CWD = os.path.dirname(os.path.realpath(__file__)) def _model_base_test(database, model, task='reg', target='test_target', plot=False): device_name = 'cuda:0' if torch.cuda.is_available() else...
d1de99fcb4f940f1dcd5f0c8c4d069f99c4d37a1f5cdcd819d31587c51cd1c3b
Python
1,962
48
# Copyright (C) 2020-2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """You may copy this file as the starting point of your own model.""" import argparse import os import numpy as np from tqdm import tqdm def create_data(collaborators, dst, total_dataset_size_per_col): num_samples = 1 input_sha...
f288e0f3e2491ceca856e86dda4e32796e7b8923cf9f23fbbfc8914753368c6c
Python
1,962
55
import pytest import geomstats.backend as gs from geomstats.test.vectorization import generate_vectorization_data from geomstats.test_cases.geometry.base import VectorSpaceOpenSetTestCase from geomstats.test_cases.geometry.riemannian_metric import RiemannianMetricTestCase class PoincareBallTestCase(VectorSpaceOpenSe...
2ad95182903ea0130e2aa7ecd92efa95aad2b52fd13b2ff49ca14cb5b3d3ec63
Python
1,965
65
import sys import os import mdtraj as md from mdtraj import Trajectory from mdtraj.formats import DTRTrajectoryFile from mdtraj.utils import in_units_of sys.path.insert(1, "/project/dinner/scguo/ci-vsd/python") from util import zero_h_occupancy TOPFILE = "/project/dinner/scguo/ci-vsd/unbiased/000/civsd.prmtop" def ...
ef17f858db139b796aff538c560ec625036a4d6e32cb4e0da9f62678fac6afe7
Python
1,965
62
import os import shutil import pytest import unittest import torch from reinvent.runmodes.create_model.create_mol2mol import create_model @pytest.mark.integration @pytest.mark.usefixtures("json_config") class TestCreateModel(unittest.TestCase): def setUp(self): self.workdir = self.json_config["MAIN_TEST...
0cb2e724183842878808db2b997b4a1057940e78f6c43822bad810c234265e3d
Python
1,968
62
class Graph(): def __init__(self, V): self.V = V self.graph = [[0 for column in range(V)] \ for row in range(V)] ################################################ # This function returns true if graph G[V][V] # is Bipartite, else false d...
90a38efd0856ecf71ba16ee5ccbf574c2ef747ee8bf86ee7af3e6e38f5eba97f
Python
1,969
52
# 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...
a5c47334c6975d5ddfb2f785ea6a67bf4eebda73887af88556b017e3b8f0f5e3
Python
1,970
65
import geomstats.backend as gs from geomstats.test.data import TestData from .base import VectorSpaceOpenSetTestData from .riemannian_metric import RiemannianMetricTestData class PoincareBallTestData(VectorSpaceOpenSetTestData): xfails = ("projection_belongs",) class PoincareBallMetricTestData(RiemannianMetric...
020ef05ad759eeb47fbcf123c05c8a660a7d892733d3347652472782e688f9c6
Python
1,973
70
# 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 # # Unle...
ff1a39569757dce07f060b3a114605578ef39fe30b98b29650808d45b730c6f3
Python
1,974
64
import socket import torch import torch.distributed as dist from utils import logger def is_master(opts) -> bool: node_rank = getattr(opts, "ddp.rank", 0) return node_rank == 0 def dist_barrier(): dist.barrier() def is_start_rank_node(opts) -> bool: node_rank = getattr(opts, "ddp.rank", 0) def...
966d1f001e9a42dc7268473f298b5431c984b3df92e54b778eeb0c3a3857ff9f
Python
1,975
57
import torch def tv_2d_l2(img): assert len(img.shape) == 2 numel = img.shape[0] * img.shape[1] x_variance = torch.sum(torch.pow(img[:, :-1] - img[:, 1:], 2)) y_variance = torch.sum(torch.pow(img[:-1, :] - img[1:, :], 2)) return (x_variance + y_variance) / (numel) def tvd_2d_l2(img, direction='x...
d9cea65741b2657b2fd7ff71bec44b0842daa01d11e4dd103feb3310ffce31de
Python
1,975
59
import argparse from torch.optim import AdamW from . import register_optimizer from .base_optim import BaseOptim @register_optimizer("adamw") class AdamWOptimizer(BaseOptim, AdamW): """ `AdamW <https://arxiv.org/abs/1711.05101>`_ optimizer """ def __init__(self, opts, model_params) -> None: ...
605bd486a538cb1cdf5f1f654a1a06d40e7ae8ff88d1c0931e346b27660cbb91
Python
1,976
57
from ._tp_scatter_base import TensorProductScatter class OpenEquivarianceTensorProductScatter(TensorProductScatter): _nequip_custom_ops_libs = ("openequivariance",) def __init__( self, feature_irreps_in, irreps_edge_attr, irreps_mid, instructions, use_opaque: b...
fceb1f9aeaafd77a5a07128f3d2081016cc00256cd006a1cff31aaaef2611652
Python
1,976
58
from corgie.stack import Stack from corgie.log import logger as corgie_logger from corgie.argparsers import create_layer_from_dict, create_layer_from_spec import json def spec_to_stack(spec, prefix, layers): """Create Stack by filtering a dict of layers Args: spec (dict): job_specs including src_img, ...
acd438f113b860a35399940a7d5e5de2bc299b6e0de814daf85b8a295736c29e
Python
1,977
75
from __future__ import annotations import logging import os from pathlib import Path from typing import Union logger = logging.getLogger(__name__) _cache_root: Path = Path(".cache") def set_cache_root(root: Union[str, Path], create=False): global _cache_root _cache_root = Path(root) if create and not ...
887c7e8e9199381e9f19c8dec452ed49f895b454fb22501e08c6e3e62b476be0
Python
1,978
68
""" Functions for building dendrogram trees and manage their levels """ import numpy as np from scipy.cluster.hierarchy import linkage, fcluster import warnings def tree_modules(W, num_clust): Z = linkage(W, "weighted", "correlation") T = fcluster(Z, num_clust, criterion="maxclust") return T def level_...
8b39c4a0dbb10fc73d005c885ce5c63887c2eb7fad3524c2847cb3c41ee2ff1b
Python
1,978
65
#!/usr/bin/env python3 """ Stream a recorded fif file on LSL network. Command-line arguments: #1: Stream name #2: Raw FIF file to stream #3: Chunk size #4: Trigger file If no argument is supplied, prompts for the server name and for the path to the '-raw.fif' file to play. Example: python nd_strea...
ed29265e27a85280b80406ea31b26e6580d5f68fbb4bfb90110df766674335c1
Python
1,980
68
import os import neo import matplotlib.pyplot as plt import warnings from snakemake.logging import logger from pathlib import Path def load_neo(filename, object='block', lazy=False, *args, **kwargs): try: filename = Path(filename) if filename.suffix == '.nix': kwargs.update(mode='ro') ...
2fc8dda3301544b20c1f948e51eefd0a5c4a76f29acfa99bd46f3180afd44311
Python
1,981
68
import os import neo import matplotlib.pyplot as plt import warnings from snakemake.logging import logger from pathlib import Path def load_neo(filename, object='block', lazy=False, *args, **kwargs): try: filename = Path(filename) if filename.suffix == '.nix': kwargs.update(mode='ro') ...
23287f54b269fa46e19a1f772b0282d15355f500f4ca75d269f4e9b8fe23363a
Python
1,982
67
""" See: """ from typing import Union from pprint import pprint import pyabf path = 'data/20191009_0005.abf' path = '/Users/cudmore/data/theanne-griffith/07.20.21/2021_07_20_0013.abf' abf = pyabf.ABF(path) class epochTable(): def __init__(self, abf : pyabf.ABF): self._epochList = [] print('sweepX pnts:', len...
92a893b7323a086e267258f5355d422f1405c699709a59163a87e19d7f7ac72c
Python
1,984
80
import os import glob import random import fnmatch import re import sys class_id = {"nofight": 0, "fight": 1} def get_list(path, key_func=lambda x: x[-11:], rgb_prefix='img_', level=1): if level == 1: frame_folders = glob.glob(os.path.join(path, '*')) elif level == 2: frame_folders = glob.glo...
00a0774f9da34042a19cf7f8395a22796a201f421f747e8b9747072820d86794
Python
1,991
86
""" Pytest configuration and fixtures for stats module tests. Fixtures defined here are automatically available to all test files in this directory and subdirectories. """ import pytest import numpy as np import polars as pl @pytest.fixture def random_state(): """Provide a fixed random state for reproducibility...
9c1ea06b728efcef09a73067d3b5509eb782ba1d6e45f72d80169d1f55cee1ab
Python
1,991
75
# -*- coding: utf-8 -*- import os import argparse import logging import matplotlib.pyplot as plt import pandas as pd import numpy as np # use this format to tell the parsers # where to insert certain parts of the script # ${imports} def parse_args(): # Argument Parser parser = argparse.ArgumentParser() #...
a35358ad0fbecc3d95fb5d00831d2c4e06e32c0f0f68bea75db46ad1d1b37e1c
Python
1,992
49
# Copyright 2020-2024 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Median module.""" import numpy as np from openfl.interface.aggregation_functions.core import AggregationFunction class Median(AggregationFunction): """Median aggregation.""" def call(self, local_tensors, *_) -> np.ndarray: ...
6c779ba3fb7780385b4863c697b68d6621ed48d29dec45abb1a0c27272bde5b4
Python
1,993
67
# ============================================================================== # Copyright 2023 Technical University of Denmark # Author: Nikolas Borrel-Jensen # # All Rights Reserved. # # Licensed under the MIT License. # ============================================================================== from typing impo...
7b3284dd16035801e07214ad2b7cb5930258c9b2cb2a9af218ed085a14835186
Python
1,995
63
import random from torch_geometric.data import Batch class RandomView(): r"""Generate views by random transformation (augmentation) on given batched graphs, where each graph in the batch is treated independently. Class objects callable via method :meth:`views_fn`. Args: candidates (list...
f9db0bf14d246d9a34aa6782d1382bf7f98c3f2f5128a20f63f872b2e65df93b
Python
1,997
61
import torch from torch import sigmoid import torch.nn as nn import torch.nn.functional as F import numpy as np class bce_loss(nn.Module): def __init__(self, weights=None, use_gpu=False): super(bce_loss, self).__init__() self.weights = weights self.use_gpu = use_gpu def forward(self, ...
99c4511aa3e5730ce3671af63f5919046e44ec5926798bc0c402a07cca694060
Python
1,998
53
from setuptools import setup, find_packages PYRATES_TEAM = "Richard Gast, Daniel Rose" INSTALL_REQUIREMENTS = ['numpy', 'networkx', 'pandas', 'ruamel.yaml', 'sympy', 'scipy' ...
a8c88eebd4040162e2ec4139ece270ba9dd92cb2a358f48339d1dacdcb3bdc98
Python
1,998
53
import jax from jax import numpy as jnp import haiku as hk from typing import Dict, Optional from deeperwin.configuration import Configuration from deeperwin.loggers import LoggerCollection from deeperwin.utils.utils import getCodeVersion from deeperwin.checkpoints import delete_obsolete_checkpoints def initialize_t...
b30c2cea8a9d9012dbdd660dd47c6599b8a5cb20dd21a56197d5a08d3ac27e01
Python
1,998
78
import random import pytest from geomstats.geometry.lower_triangular_matrices import ( LowerTriangularMatrices, StrictlyLowerTriangularMatrices, ) from geomstats.test.parametrizers import DataBasedParametrizer from geomstats.test_cases.geometry.base import ( LevelSetTestCase, MatrixVectorSpaceTestCase...
275535983c5cde4b8be042acf9cffa7f1cf6828181fe5a4fe0f88de28a7869d7
Python
2,000
55
from nequip.data import AtomicDataDict from nequip.nn import ( GraphModel, SequentialGraphNetwork, AtomwiseLinear, AtomwiseReduce, ) from nequip.nn.compile import CompileGraphModel from nequip.nn.embedding import NodeTypeEmbed from nequip.utils import dtype_from_name, torch_default_dtype def test_grap...
40b6cb7ef50c067b9a5e5fa0969e4d1a01ba581c63ce8c721f8bce1fb9db885c
Python
2,000
76
"""Compute scores with Qptuna models""" from __future__ import annotations __all__ = ["Qptuna"] import pickle from typing import List import logging import json import numpy as np from pydantic.dataclasses import dataclass from .component_results import ComponentResults from .add_tag import add_tag from ..normalize...
0ee1d04bad4a2398a4486f5b7a036962e6c162b1f361b5fb7d19965691a9e72a
Python
2,002
58
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
415f07e14e002205579b467bc17ce9335b4814c81382b4049d703f1271631c0e
Python
2,002
65
import os import shutil import pytest import unittest import torch from reinvent.runmodes.create_model.create_reinvent import create_model @pytest.mark.integration @pytest.mark.usefixtures("json_config") class TestCreateModel(unittest.TestCase): def setUp(self): self.workdir = self.json_config["MAIN_TES...
7481a625a97b74681022597deabec3c73beaa318f2792638720d9b27c9382178
Python
2,006
49
from concurrent.futures import ThreadPoolExecutor from chromadb.config import DEFAULT_TENANT from chromadb.test.conftest import ClientFactories def test_multiple_clients_concurrently(client_factories: ClientFactories) -> None: """Tests running multiple clients, each against their own database, concurrently.""" ...
cace11f6d74497d1521ac4e290bee8aa928db82afc107ee56fcad481d010600a
Python
2,006
65
import argparse from pathlib import Path import os def _arg_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description='this is Single Sensillum Sort v.XX authors: Georg Raiser, XX', formatter_class=argparse.ArgumentDefaultsHelpFormatter, argument_default=argparse.SU...
cb83a9616b45e8a720e24eb31b03a820721e8e2ae40cda5f220f4df452c6facc
Python
2,006
73
import random import pytest from geomstats.geometry.poincare_half_space import ( PoincareHalfSpace, PoincareHalfSpaceMetric, ) from geomstats.test.parametrizers import DataBasedParametrizer from geomstats.test_cases.geometry.poincare_half_space import PoincareHalfSpaceTestCase from geomstats.test_cases.geomet...
e4586a871b92b79aafd4dffbef028f75ae18503464bcf7c4c176496ee4782df0
Python
2,007
64
"""Strict conversion of SanPy values to portable JSON values.""" from __future__ import annotations import enum import json import math from dataclasses import asdict, is_dataclass from datetime import date, datetime from pathlib import Path from typing import Any import numpy as np import pandas as pd def json_va...
7a384d1423a6258d7eb0bf9618d78175acc58ec480e8d8d40e12f7f938c50ce7
Python
2,008
56
"""Paths, resolved once from the repo root. Every legacy script in ``py_src/`` hard-codes ``../chunks`` and must be run from inside ``py_src/``. Nothing here uses a relative path; the root is found by walking up for a marker file, so the CLI works from any working directory. """ from __future__ import annotations fro...
5271c6667350aa38c26be90c1c079af2e4d6b8edec0a7878c1cac1eb2568d079
Python
2,009
44
# Check Pytorch installation import torch, torchvision from torch import nn print(torch.__version__, torch.cuda.is_available()) import cv2 import matplotlib.pyplot as plt import mmcv import numpy as np import pandas as pd import nibabel as nib import imageio import os from monai import metrics from monai.utils.enums i...
bde819ce22b236a3b88c51a247cb500137a60a9ff7af9b72de8799b7f8f69b16
Python
2,009
61
# ============================================================================== # Copyright 2023 Technical University of Denmark # Author: Nikolas Borrel-Jensen # # All Rights Reserved. # # Licensed under the MIT License. # ============================================================================== import io import...
03167b19d602f60d3964b9b32ca4f0d39d7f11bbc443c17d08862938d7180db2
Python
2,010
74
import threading from types import TracebackType from typing import Optional, Type class ReadWriteLock: """A lock object that allows many simultaneous "read locks", but only one "write lock." """ def __init__(self) -> None: self._read_ready = threading.Condition(threading.RLock()) self._r...
93d38e3ecde5cf5ce3f136060a5ecee0f9a5e90afd20780827c3a081eeb23be1
Python
2,010
65
"""Write the two row-oriented resources in requested representations.""" from __future__ import annotations from pathlib import Path from typing import Any import pandas as pd from .json_codec import canonical_json def prepare_table(table: pd.DataFrame) -> pd.DataFrame: """Copy a table and encode structured o...
e12821aece2ab028a247faad980a17a655035153c56305183e90b75d16cbd452
Python
2,013
41
import numpy as np import torch from torch.utils.data import DataLoader import argparse import sys import os from evaluate import Tester from data import * if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--testfile', type=str, help='path to the test file for pretrain') p...
1f073c6861621db964113210a55c2c1ccfcb2c191c69a4b8c1a3701fa7ecb27a
Python
2,014
74
from brian2.units import * from brian2 import defaultclock """ Fixed parameters required by the equations """ tau_Cl = 100.*ms # removal rate of chloride ions in excitatory cells; healthy 0.1s | epilepsy 0.5s or 1.0s, page 88, Aussel Ek = -100.*mV # resting potential of potassium chann...
5c91168f83ae895107969d3e4f4ecffb7dddc5cf01f70653a65c09bf1a64843f
Python
2,014
42
import json import argparse from rdkit import RDLogger from torch_geometric.loader import DenseDataLoader from dig.ggraph.method import GraphDF from dig.ggraph.evaluation import ConstPropOptEvaluator from dig.ggraph.dataset import ZINC800 RDLogger.DisableLog('rdApp.*') parser = argparse.ArgumentParser() parser.add_ar...
e55f8561ded08285e1b9772397be93ffd6b307f4c1755b051376599a8225f861
Python
2,014
71
from geomstats.test.data import TestData class DiffeoTestData(TestData): def diffeomorphism_vec_test_data(self): return self.generate_vec_data() def diffeomorphism_belongs_test_data(self): return self.generate_random_data() def inverse_vec_test_data(self): return self.generate_ve...
7b97b520cc90a467b52e80486b5497a5bb311a6219d1e0e99451817869c62e5f
Python
2,015
60
"""Plot a geodesic of SE(2). SE2 is equipped with the canonical Cartan-Shouten connection, whose geodesics are the group geodesics, i.e. one parameter subgroups and the left and right invariant canonical metric. In all cases the rotation part is the same: it has constant angular velocity. The translation parts differe...
2a814e3bd4a8d2b096ac32b2c9212dcfe439e38648e7dac49b37b2e2926ef6a0
Python
2,016
68
import math import geomstats.backend as gs from geomstats.test.data import TestData from .hermitian import HermitianMetricTestData CDTYPE = gs.get_default_cdtype() SQRT_2 = math.sqrt(2) MAT9_33 = gs.array([[4, 0, 1j], [0, 3, 0], [-1j, 0, 4]], dtype=CDTYPE) MAT10_33 = gs.array([[1, 1 + 1j, -3j], [1 - 1j, 0, 4], [3j...
356a7ab4de8e7a93217121b445c02f43afff70e17788e7f7cce9e9429f23748a
Python
2,018
51
import torch import torch.nn as nn import torch.distributed as dist from gather import GatherLayer class NT_Xent(nn.Module): def __init__(self, batch_size, temperature, world_size): super(NT_Xent, self).__init__() self.batch_size = batch_size self.temperature = temperature self.wor...
717156af9d3ccd18d15001aaae498516f5412d0f91f6c94e225eec01db29e467
Python
2,019
54
import glob import argparse from Bio.PDB import PDBParser from Bio.PDB.Polypeptide import is_aa import warnings from Bio import BiopythonWarning def three_to_one(code): """Convert three-letter amino acid code to one-letter code.""" aa_map = { 'ALA': 'A', 'ARG': 'R', 'ASN': 'N', 'ASP': 'D', 'CYS': 'C', ...
877497cfe7bdb63f21dcf52f9556c90272f5f9483a698ffe48451d0ca5a9bacd
Python
2,020
58
"""Tests for immutable application state used by the DANDI NiceGUI demo.""" from dataclasses import replace import pytest from gui.app_state import DandiAppState, DandiAppStateStore, OperationStatus def test_store_publishes_complete_state_transitions() -> None: """Notify subscribers with the previous and repla...
191a260fa3d97bcbd5c70b867f4b93d98dfc8bb5fcb3ae82f73caae0fdba23dc
Python
2,021
67
""" GPU_UTILS ==================== Nvidia-smi GPU memory parsing. Tested in nvidia-smi 370.23 The code is borrowed from Yaroslav Bulatov's post in Stack Overflow: https://stackoverflow.com/questions/41634674/tensorflow-on-shared-gpus-how-to-automatically-select-the-one-that-is-unused/41638727#41638727 We thank Den...
2d0614ffd8e3dde090562396c03e4d128487c821ee465ef792f3f35959843133
Python
2,021
60
from unittest import TestCase import torch import torch.nn as nn import numpy as np from smithers.ml.layers.pcemodel import PCEModel input_ = torch.rand(120, 50) mean = torch.mean(input_, 0) var = torch.var(input_, 0) class TestPECModel(TestCase): def test_constructor_pce_01(self): pce = PCEModel(mean, va...
e113071ee4ec41181f3ce49b1954697d6ab1a5521c322da36c46212aae8f29d4
Python
2,021
56
# 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...
129f7c9d2192e26136db5660c2c9ba044298c050aacef4a5b6d300dc37e956c1
Python
2,025
50
# Copyright 2020-2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import pytest import logging from tests.end_to_end.utils import federation_helper as fed_helper from tests.end_to_end.utils.tr_workspace import create_tr_workspace_gandlf log = logging.getLogger(__name__) def test_gandlf_segmentation(req...
b2d6cfc8f8813efaa72d26ffd42a2cc42dcb28dabc44da52e2b74cffdd7c8b38
Python
2,025
66
import logging import chromadb.test.property.strategies as strategies import hypothesis.strategies as st from chromadb.api import ClientAPI from chromadb.test.conftest import NOT_CLUSTER_ONLY, reset from chromadb.test.property import invariants from chromadb.test.utils.wait_for_version_increase import wait_for_version...
9bee7e7d67d193f98c66ed46ff715bfab4f8d429589f96308a30dc0ddfb1d0cb
Python
2,026
55
from skimage.color import gray2rgb from sparse_ct.tool import plot_grid from sparse_ct.data import image_to_sparse_sinogram from sparse_ct.reconstructor_2d import ( IRadonReconstructor, SartReconstructor, SartTVReconstructor) if __name__ == "_...
9e3506b45bc14be070be6664ce76b07a9edfce2fab8cccdc6633dc43d256cdaf
Python
2,026
61
# -*- coding: utf-8 -*- """ Created on Tue Jun 29 14:21:17 2021 @author: Tom """ import sys from tensorflow import keras as k # Dependency - change to corret path before use! randaugment_path = r'../../pathology-he-auto-augment/he-randaugment' sys.path.append(randaugment_path) # image variables IM_FORMAT = 'jp...
313058728732a4d3edd68b1993d0ff3686f934f07c9ec2316099572f4c5efe3e
Python
2,028
58
# Copyright 2020-2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import pytest import logging from tests.end_to_end.utils.tr_common_fixtures import ( fx_federation_tr, fx_federation_tr_dws, ) from tests.end_to_end.utils import federation_helper as fed_helper from tests.end_to_end.utils.exceptions...
518887d979653500c4b3dd5ec402bcfb4740704ed59da13650b90e012540b59b
Python
2,028
65
"""Placeholders with error messages. NumPy backend does not offer automatic differentiation. The following functions return error messages. """ from geomstats.exceptions import AutodiffNotImplementedError _USE_OTHER_BACKEND_MSG = ( "Automatic differentiation is not supported with numpy backend. " "Use autogr...
b5415d8d96bfa5a8d6ee25ca450dc1ffccf53ee8cc15865f88ec54b119549b08
Python
2,028
60
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html master_doc = 'index' # -- Path setup ---------------------------------------------------...
2b3ccfc4f34a71b30b61604565839d677875db384750d9e464ad89e2259be8bc
Python
2,030
76
import torch from torchvision import transforms def get_training_augmentation(): train_transform = [ albu.HorizontalFlip(p=0.5), albu.ShiftScaleRotate(scale_limit=0.5, rotate_limit=0, shift_limit=0.1, p=1, border_mode=0), albu.PadIfNeeded(min_height=320, min_width=320, always_apply=True...
79e1e09b3be927c125f7a0dc305c6e3f81b16d376a7d6d09967d96e4f52342d3
Python
2,031
69
import os import sys def renumber_res(pdb_input, output_dir, start_res=1): ##get all chainIDs from the pdb file chainIDs = [] with open(pdb_input, 'r') as f: for line in f: if line.startswith('ATOM'): chainID = line[21] if chainID not in chainIDs: ...
fd3b3f6c01a3accb866495c29145dbbdd2aa33c4708165a2e14407d538452d26
Python
2,031
52
from dcmrtstruct2nii import dcmrtstruct2nii, list_rt_structs from glob import glob import os import platform directory_split = "\\" if platform.system() == "Windows" else "/" def format_scan(dicom_path, rstruct_path, savepath): dcmrtstruct2nii(rstruct_path, dicom_path, savepath, mask_foreground_value=1, structure...
135fd2fbe3be1aebf97968ab34ca653ed7447ed117fea5cbdc1671f752eab4e5
Python
2,032
46
import json import argparse from rdkit import RDLogger from torch_geometric.loader import DenseDataLoader from dig.ggraph.dataset import QM9, ZINC250k, MOSES from dig.ggraph.method import GraphAF from dig.ggraph.evaluation import RandGenEvaluator RDLogger.DisableLog('rdApp.*') parser = argparse.ArgumentParser() pars...
d87791226c1f1ff1261036b03c17d2a7c24b3b7d7e29c13aaeb3e39e50620e72
Python
2,032
53
"""Tests for cross-cutting helpers in ``nltools.utils``.""" import warnings import numpy as np from nltools.utils import DesignMatrixWarning, _find_stack_level class TestAttemptToImport: """``_attempt_to_import`` returns the module or ``None`` — no side-registry.""" def test_returns_module_on_success(self...
9cbbd4d6d7053470fec92aae72d313e01321a6928963c271b4e129b73dee4b12
Python
2,033
65
"""Plot a geodesic in H2. Plot a geodesic on the hyperbolic space H2. With Poincare Disk visualization. """ import matplotlib.pyplot as plt import geomstats.backend as gs import geomstats.visualization as visualization from geomstats.geometry.hyperboloid import Hyperboloid def plot_geodesic_between_two_points( ...
08e7303a2e2246360f8902978d9e7393de68742dc51ab19669ba3a7d8885728f
Python
2,034
68
import torch.nn as nn from torch.utils.checkpoint import checkpoint as torch_checkpoint class Bottleneck(nn.Module): expansion = 4 def __init__( self, in_planes, planes, stride=1, groups=1, activation_class=nn.ReLU, conv_class=nn.Conv3d, affine=...
ed6b5c77e1dce6daaeee9fcaa620c4907abea58fefbdaee1de27612689fcd858
Python
2,034
48
import numpy as np from bone_segmentation.DataStructures import ImageToPatientTransformation from bone_segmentation.Viewer import ImageViewer import config from data.dataset import BratsTest dataset_prefix = 'test' dataset = BratsTest(None, None, None) experiment_name = 'UNet-20220221-Brats184-256-geoaug-imaug-valid-...
7f1a339ce62ddfbe97f232d5474b715a29fc6821afb62a86b94f52008960ae22
Python
2,035
65
""" Visualize the wave detection by means of clustering the detected trigger in (time,x,y) space. """ import numpy as np import quantities as pq import argparse import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import seaborn as sns import random import warnings from utils.io_utils import lo...
4b5f4d637e6739bfc9433a2bd440ef4f15dd5cec9b95f6a5646c8c1e61a9786a
Python
2,036
47
# flake8: noqa # pylint: skip-file pybids_inputs = { "bold": { "filters": {"suffix": "bold", "extension": ".nii.gz", "datatype": "func"}, "wildcards": ["subject", "session", "acquisition", "task", "run"], } } parse_args = { "bids_dir": { "help": "The directory with the input datase...
c68d5ce0509752122108f9fa8a273aa8b79492dd3363eef3960c443fe303df2c
Python
2,036
64
from __future__ import annotations from typing import Any import pytest from hypothesis import given from hypothesis import strategies as st from pytest_mock import MockerFixture from snakebids.plugins.version import Version from snakebids.tests.helpers import allow_function_scoped @given(version=st.text()) def te...
59ad84b0c6b3409c9ed9f08c5714db643554611ee6aaf530318194d1b7c2f550
Python
2,038
63
from . import register_scheduler from .base_scheduler import BaseLRScheduler import argparse import math @register_scheduler("fixed") class FixedLRScheduler(BaseLRScheduler): """ Fixed learning rate scheduler with optional linear warm-up strategy """ def __init__(self, opts, **kwargs) -> None: ...
7a7f2650f9c3d010f60cc8c7c32f79b6ca26141dbeb52d80e0747d88f5d6a183
Python
2,039
60
import numpy as np import pandas as pd from nltools.cross_validation import KFoldStratified def check_valid_split(train, test, n_samples=None): # Use python sets to get more informative assertion failure messages train, test = set(train), set(test) # Train and test split should not overlap assert tra...
06b834c5b51d07afda72ce02407c0a10e9e769c09c9d76fd7b60f6591c6dec9c
Python
2,040
59
import operator as op import re from typing import List, Tuple from hypothesis import given from hypothesis import strategies as st from snakebids.utils.utils import matches_any @given(st.text(), st.lists(st.text())) def test_matches_any_with_eq_operator(item: str, match_list: List[str]): if item not in match_l...
f807fd72d77be9122a2e2d5cd9a579346c1519d6629da391a71b2b635f7d3775
Python
2,042
84
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
1e8bcfae4da843170da2e10740e14d484ac94417214186d6fbb5798b70be9784
Python
2,043
77
#!/usr/bin/env python import os directory = "." # All files in directory allFiles = os.listdir(directory) # Only the files we care about files = [] for i in allFiles: if i.startswith("snpCounts") and "human" in i: files.append(i) print(files) snp_dict = {} counter = 1 total = str(len(files)) for i in ...
95d0d8a6c5ba13496d7ef95b2c53f6cbd19cc2927aaa6c4b3d1ecf222ce45f03
Python
2,044
64
import os from pathlib import Path import shutil import numpy as np from torch import nn, optim import torch def test_xyz_read_write(): from mlspm.utils import read_xyzs, write_to_xyz xyz_path = "./test.xyx" # fmt: off xyz = np.array([ [ 0.0, 0.1, 0.2, 0.3, 1], # (x, y, z, charge, eleme...
c73d59052c61c40555083639070d3a2a01d776bf794706248c457e76f3c1bef8
Python
2,044
75
# -*- coding: utf-8 -*- from __future__ import print_function, division from builtins import input """ Decoder speed test. Results on i7-8700K machine: 1000 Hz, 6 channels, 500-sample window: sklearn 0.17.1(pip) = 32.7 Hz, 0.19.1(conda) = 28.8 Hz with intel-mkl library: sklearn 0.17(pip) = 25.0 Hz, 0.19.1(conda)...
95ccc7cee41bbfd63dccb31c418d2e6b1e2033403f4d3ced5899bda6cb4a6ace
Python
2,045
52
from torch import nn class MLPHeader(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim): super().__init__() self.network = nn.Sequential( nn.Linear(input_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, output_dim) ) def forward(self...
3d6ed999cfdd32c67ae3418b0520e651aab7e4854da8f79f6830158f5c50dbab
Python
2,046
73
from PymoNNto import * class LIF_main(Behavior): def initialize(self, n): self.set_parameters_as_variables(n) n.v = n.vector('uniform')*n.v_rest n.fired = n.vector() > 0 n.dt = 0.1 def iteration(self, n): n.v += ((n.v_rest-n.v)+n.I)*n.dt n.fired = n.v > n.v_th...