sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
b6e2b23b181b825ddcb10471dcd56e28e1ebb95f24aad237af5a95f8f3f97787 | Python | 3,300 | 122 | """Kernel pairings."""
import importlib
import geomstats.backend as gs
from .base import Pairing
if gs.__name__.endswith("pytorch"):
import torch
_compile = torch.compile
else:
def _compile(fn):
return fn
def GaussianBinetPairing(sigma, backend="auto"):
r"""Instantiate a Gaussian-Binet ... |
2392b1694fc1e021ae00b1e86463a30d3060753a8e796c8ba157baebfe622004 | Python | 3,301 | 112 | import numpy as np
from sleepstage import class_dict
import logging
logger = logging.getLogger("default_log")
def save_seq_ids(fname, ids):
"""Save sequence of IDs into txt file."""
with open(fname, "w") as f:
for _id in ids:
f.write(str(_id) + "\n")
def load_seq_ids(fname):
"""Lo... |
31c2e4d6a2aeacb74d124de62360f3b6e050d701297a2f2c67a77819d594b9ee | Python | 3,301 | 89 | """Module providing an implementation of MatrixLieAlgebras.
There are two main forms of representation for elements of a MatrixLieAlgebra
implemented here. The first one is as a matrix, as elements of R^(n x n).
The second is by choosing a base and remembering the coefficients of an element
in that base. This base wil... |
4c371e5b75ce84ffc70444d69372900997dc2cad8f1aa0c31102cc9004e81fea | Python | 3,302 | 88 |
# -*- coding: utf-8 -*-
#
#
# PyRates software framework for flexible implementation of neural
# network models and simulations. See also:
# https://github.com/pyrates-neuroscience/PyRates
#
# Copyright (C) 2017-2018 the original authors (Richard Gast and
# Daniel Rose), the Max-Planck-Institute for Human Cognitiv... |
6fedadc15c418fb956f1e4a59b00ec23306a1e01cf3eb03681f56fc6461a6925 | Python | 3,303 | 105 | import pandas as pd
import pickle
from cclib.io import ccread
import lzma
from tqdm import tqdm
from multiprocessing import Pool
import os.path as osp
def extract_properties(log_file: str) -> tuple:
"""
return: (HOMO, LUMO, HOMOLUMOgap); None on error
"""
try:
with lzma.open(log_file, mode='rt... |
a8a6b08ec9c9f81054bdaa5eb960cffc42b101f40341afa7997e04a4ade46f86 | Python | 3,303 | 96 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
b01deacea814a8c2a391a0815162198921938648f2a237293631cc49b4d84a89 | Python | 3,303 | 95 | from chromadb.api.types import EmbeddingFunction, Embeddable, Embeddings
import numpy as np
from typing import cast, Any
from chromadb.utils.embedding_functions import (
register_embedding_function,
known_embedding_functions,
)
class LegacyCustomEmbeddingFunction(EmbeddingFunction[Embeddable]):
def __call... |
10e94147461598d016e7006cc192c299774e28f8f8a3c26397e2c20509fe6160 | Python | 3,306 | 97 | # 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... |
5f74931cf2f50cbbfac0516b2631567ac6659652a6c8f49b65793027226f623b | Python | 3,308 | 113 | import hashlib
import os
import pickle
import torch
from abc import abstractmethod, ABC
class AbstractPreprocessor(ABC):
# language=rst
"""
Abstract base class for Preprocessor.
"""
def process(
self,
csvfile: str,
use_cache: bool = True,
cachedfile: str = "./proc... |
c594b19bd065acf3185bf611c021e0a5bf42a23d17b76769e5431aacad6f9563 | Python | 3,313 | 120 | import os
import shutil
from pathlib import Path
from ... import logger
def get_file_list(path, fullpath=True, recursive=False):
"""
Get files with or without full path.
Parameters
----------
path : str
The directory containing the files
fullpath : bool
If True, returns the f... |
cbfc478a1043464c80677f93725bf4f3f8cc07a7c134e20c1e867b75f5ace385 | Python | 3,318 | 67 | #*----------------------------------------------------------------------------*
#* Copyright (C) 2024 ETH Zurich, Switzerland *
#* SPDX-License-Identifier: Apache-2.0 *
#* *
... |
662eafdeebceb987892ec8b84d7315a67b17c819b0f62652e56a6b1f91a3aea0 | Python | 3,319 | 75 | from .Graphair import graphair,aug_module,GCN,GCN_Body,Classifier
import time
class run():
r"""
This class instantiates Graphair model and implements method to train and evaluate.
"""
def __init__(self):
pass
def run(self,device,dataset,model='Graphair',epochs=10_000,test_epochs=1_000,
... |
15a52ed78babf7e2beb4f689ab521ceda2e789f1de1a2a74b0a16e944c26b49a | Python | 3,320 | 101 | """Write out a TensorBoard report"""
from __future__ import annotations
from typing import TYPE_CHECKING
import logging
import numpy as np
from reinvent.runmodes.utils import make_grid_image
if TYPE_CHECKING:
from reinvent.runmodes.RL.reports import RLReportData
logger = logging.getLogger(__name__)
ROWS = 5
C... |
c576f4a39fa0c4a3aaad4406406501f6281d11c04237c4d5d5558c5b6bb65dc8 | Python | 3,321 | 110 | import geomstats.backend as gs
from geomstats.test.data import TestData
from .fiber_bundle import FiberBundleTestData
from .manifold import ManifoldTestData
from .mixins import ProjectionMixinsTestData
from .quotient_metric import QuotientMetricTestData
class RankKPSDMatricesTestData(ProjectionMixinsTestData, Manifo... |
3463e5637266a387534059345667947b389d7057ae361e7dd35208723806ba39 | Python | 3,324 | 97 | from glob import glob
from typing import List
import h5py
from torch.utils.data import ConcatDataset, Dataset
from mace.data.atomic_data import AtomicData
from mace.data.utils import Configuration
from mace.tools.utils import AtomicNumberTable
class HDF5Dataset(Dataset):
def __init__(
self, file_path, r... |
dd26ddad8d486d268fe415cdf179cdbcd888b26a74aa0972aa1f56e16b080314 | Python | 3,324 | 122 | # -*- coding: utf-8 -*-
import os
import numpy as np
import logging, argparse
from data_functions import *
import h5py
import matplotlib.pyplot as plt
import pickle
def parse_args():
# Argument Parser
parser = argparse.ArgumentParser()
# my args
parser.add_argument("--verbose", action = "store_true"... |
6d74ada3e0373d9879760878f1abb9079bac369bab7c029ac784f921180aa6bf | Python | 3,325 | 96 | # Copyright (C) 2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openfl.federated.data.loader import DataLoader
import pandas as pd
import os
import subprocess
class SmokersHealthDataLoader(DataLoader):
"""Data Loader for Smokers Health Dataset."""
def __init__(self, batch_size, data_path, ... |
81870d336364bbec3150ee1dc23537de1edfd5c9101de453fb2b4c4553d4358e | Python | 3,330 | 80 | """
Extract the annotations of Neo objects and structure them in a DataFrame
to complement a wave characterization.
"""
import argparse
import numpy as np
import pandas as pd
import quantities as pq
import re
from utils.io_utils import load_neo, save_plot
from utils.parse import none_or_str
from utils.neo_utils import... |
f05519120c579cbe67c5996130cf4d61cbf2229e3fc6630ef1c136bd4ac33398 | Python | 3,330 | 122 | """Report drift between the plot list, analysis-result schema, and detection.
Run after spike detection on a real recording::
uv run scripts/audit_analysis_stats.py --path data/2021_07_20_0010.abf
"""
from __future__ import annotations
import argparse
from pathlib import Path
from typing import Iterable
import... |
684f33c74de47a0a20629c16e889e6066f2f93fb0de15c546e57137d54444fd5 | Python | 3,333 | 83 | import numpy as np
import matplotlib.pyplot as plt
from visualization_utilities import *
from itertools import combinations
# use Coloumb's law to compute the forces on the individual point charges
def compute_force_interactions(points):
number_of_points = len(points)
forces = np.zeros(points.shape)
for i, j in... |
6bb6ae72feb64c4612c693ffa8b164a6c029737f327f81dfe17c26114a17ace6 | Python | 3,335 | 72 | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain ... |
f4286ade3617377d72cd50c7fb48ebad561ac9c754f93918172ea641fec91ebb | Python | 3,336 | 67 | #*----------------------------------------------------------------------------*
#* Copyright (C) 2024 ETH Zurich, Switzerland *
#* SPDX-License-Identifier: Apache-2.0 *
#* *
... |
5c27a9cdf5592ba58245a4a67c7044522e84b148f2e4d1a4371258060f65f1ba | Python | 3,341 | 104 | import json
import click
from click_option_group import optgroup
from corgie.log import logger as corgie_logger
from corgie.layers import get_layer_types, str_to_layer_type, \
DEFAULT_LAYER_TYPE
from corgie.data_backends import get_data_backends, str_to_backend, \
DEFAULT_DATA_BACKEND
from corgie impo... |
d1799b68d9d08e38276d4b103c329a49172b9452b6cf204cac7f8bd6d49280d3 | Python | 3,345 | 90 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from dataclasses import dataclass
import torch.nn.functional as F
from fairseq import metrics, utils
from fairseq.criterions impo... |
d3fc47a9a8b844e18a4b477fd54eb78d61a09fd4e9dfffd93c3cdbc4fcc492e8 | Python | 3,345 | 70 | from common.evaluation.monitor import PerformanceMonitorVirtual, CustomSaverVirtual
from common.evaluation.measures import get_binary_classification_measures
from variational.activations import sigmoid_moments_np
class CustomSaver(CustomSaverVirtual):
def __init__(self,
output_folder,
... |
cd8ede6c6373189dfaefed258716cd57b47088027d4eb5abc4b056ab537cb62f | Python | 3,346 | 103 | import random
import pytest
import geomstats.backend as gs
from geomstats.learning.aac import AACGGPCA, AACFrechetMean, AACRegression
from geomstats.metric_geometry.graph_space import (
GraphSpace,
_GeodesicToPointAligner,
)
from geomstats.test.parametrizers import DataBasedParametrizer
from geomstats.test_ca... |
09451b59a1642f03cc51cdcff8742a16345a74f2d56ddf996cbbe42785978cba | Python | 3,347 | 95 | """
Various functions for dealing with image data.
Author: Tal Eisenberg, 2021
"""
import io
from PIL import Image
import numpy as np
import collections
def resize_image(img: Image, size=(None, None)):
"""
Resize an image to the desired size.
:param img: The image as a PIL Image object.
:param size:... |
52752ddfe5721cef37b466effc381e1078311e9e8f7f801b5c2e413fea69f9da | Python | 3,347 | 86 | from overrides import overrides
from chromadb.api.client import Client
from chromadb.config import System
import hypothesis.strategies as st
from hypothesis.stateful import (
rule,
run_state_machine_as_test,
initialize,
)
from chromadb.test.property.test_embeddings import (
EmbeddingStateMachineBase,
... |
ab184a17eb5b12cb65b8e9f879644b102d4a5f1f433997bb15e63eee465c9cd9 | Python | 3,350 | 71 | import logging
from collections import Counter
from typing import List
from reinvent.chemistry import tokens
logger = logging.getLogger(__name__)
def construct_amino_acids_fragments(fillers: List[str], masked_inputs: List[str],
add_O=True, remove_cyclization_numbers=True) -> List... |
2eaa8d9db6a9abb985b2893b1e2b20d9632adf01a6861568240a337742cad26b | Python | 3,351 | 76 |
from PymoNNto.Exploration.Network_UI.Basic_Tabs.sidebar_fast_forward_module import *
from PymoNNto.Exploration.Network_UI.Basic_Tabs.sidebar_save_load_module import *
from PymoNNto.Exploration.Network_UI.Basic_Tabs.multi_group_plot_tab import *
from PymoNNto.Exploration.Network_UI.Basic_Tabs.hist_tab import *
from Pym... |
7f05354817bfa54732c95cfe5261b0d710de8ae900b1b82dd6cdb93ad9254ee9 | Python | 3,351 | 80 | """
Extract the annotations of Neo objects and structure them in a DataFrame
to complement a wave characterization.
"""
import argparse
import numpy as np
import pandas as pd
import quantities as pq
import re
from utils.io_utils import load_neo, save_plot
from utils.parse import none_or_str
from utils.neo_utils import... |
e7deaca2d269253bba83fce9e92bef2776bc77b4cb6e71d2759f256145aed4a5 | Python | 3,351 | 135 | import numpy as np
from torch.utils.data import DataLoader
import os, sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/..")
print(os.path.dirname(os.path.realpath(__file__)))
from model import *
from train import *
from tasks.seqDS import *
import torch
import wandb
from utils import *
import matplo... |
8dad454cdca996c12aaf632f9f645a8d9866c21ffbac7b89ddb61b7575a69a2d | Python | 3,358 | 83 | # 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... |
1be2d27f5a67776ed56c813c23058bac05c903c245eed053206574e8738ba1a6 | Python | 3,359 | 118 | import numpy as np
import torch
import torch.nn as nn
import math
import torch.nn.functional as F
surrograte_type = 'MG'
print('gradient type: ', surrograte_type)
gamma = 0.5
lens = 0.5
R_m = 1
beta_value = 1.8
b_j0_value = 0.01
def gaussian(x, mu=0., sigma=.5):
return torch.exp(-((x - mu) ** 2) / (2 * sigm... |
5e43edea0905752f72e5617a24db5ab8f099d587e22bff12f1102e69d341febc | Python | 3,362 | 86 | """Chunk lint checks. These are the rules a submitter hits in CI, so they get real coverage."""
from __future__ import annotations
import pytest
from vdjdb.qc.lint import lint_file
from vdjdb.schema import ALL_COLUMNS, CHUNK_DEDUP_KEY, COMPLEX_COLUMNS, KEPT_CURATION_COLUMNS
HEADER = "\t".join(ALL_COLUMNS)
ROW = "\t"... |
cf948cb096d9c5aed54c762a862d8f382031b7b220dc123988a6e0409e35e510 | Python | 3,363 | 106 | """Tests for the default-off external user-code policy."""
import importlib
from pathlib import Path
import pytest
import sanpy
from sanpy.interface.bPlugins import bPlugins
def test_external_plugin_files_are_ignored(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Ignore Python plugins found... |
776075c31f1b9e6cca18377313374e35150c997095bce0a6c73a5f3161ec1d17 | Python | 3,365 | 123 | # Copyright 2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Base class for different types of data sources."""
import hashlib
from abc import ABC, abstractmethod
from enum import Enum, auto
from pathlib import Path
from typing import Any, Dict, Generator
class DataSourceType(Enum):
"""Enum for t... |
9a8039e76751ef1c35d44f93ed205cf727e300d5710853ec6c24a37946fe9c0b | Python | 3,367 | 154 |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# Modified by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
from... |
1f94e0248a07611aa3f77cf3cdd8c487c97bff5a8ab99e8ff9aa5dcaaf2c59ea | Python | 3,370 | 88 | import os
import sys
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
import pandas as pd
from rdkit import Chem
from rdkit.Chem import rdChemReactions
def trans(smiles):
# isomericSmiles, kekuleSmiles (F), canonical
return Chem.MolToSmiles(... |
8a80e564d5cddfce85e4b118ca96d4b141b22d7bf6638f38131afef094a17773 | Python | 3,370 | 112 | import os
import importlib
from utils import logger
import argparse
from .base_scheduler import BaseLRScheduler
SCHEDULER_REGISTRY = {}
def register_scheduler(name: str):
def register_scheduler_class(cls):
if name in SCHEDULER_REGISTRY:
raise ValueError("Cannot register duplicate scheduler (... |
4e7784122f255bed5e59de580bb9c6ae18aeb362d04134c982da441dc7d37570 | Python | 3,371 | 96 | import pytest
import geomstats.backend as gs
from geomstats.test.test_case import TestCase
from geomstats.test.vectorization import generate_vectorization_data
from geomstats.vectorization import get_batch_shape
class InformationManifoldMixinTestCase(TestCase):
@pytest.mark.shape
def test_sample_shape(self, ... |
2c55db19880e64dacd8fb4f5b31e768ad7ee2e6f3d256a2588525cc772a77f43 | Python | 3,373 | 108 | from typing import Optional, Iterable, Union, Tuple
import torch
import torch.nn.functional as F
from bindsnet.network import nodes, topology
class PermuteConnection(topology.AbstractConnection):
# language=rst
"""
Special-purpose connection for emulating the custom ``Permute`` module in
spiking neu... |
a4a072d9ee238bd502130ec29bcc5e5308fbbeed253c31ce817be265fd757414 | Python | 3,373 | 95 | # -*- coding: utf-8 -*-
"""Provides reconstructors performing regression."""
import os
import json
import numpy as np
from sklearn.linear_model import Ridge
from dival.util.odl_utility import uniform_discr_element
from dival import LearnedReconstructor
class LinRegReconstructor(LearnedReconstructor):
HYPER_PARAMS... |
2b4e746cf40cfe90b74dff11ada7a9b79b560c49ad785decef3373b2eaeb35b1 | Python | 3,376 | 78 |
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... |
7d4bc5ad8e757938c232bf85dd77aa0057aa49b2029986dcea4a591ce4f27958 | Python | 3,376 | 96 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from dataclasses import dataclass, field
import torch
import torch.nn.functional as F
from fairseq import metrics, utils
from fa... |
d9096a792629859553be279a6f758e560a95017034f980a2804b0245079a7942 | Python | 3,379 | 65 | # =====================================================================================
# RE-MEASURE T4 end-to-end latency for ALL YOLO nanos + RT-DETR, in ONE clean run.
# RUN ON A T4 GPU. Re-checks v8n alongside v10/v11/v12 so all come from one batch.
# Robust: 150-iter warmup per model + median over all 165 test ima... |
0ed132f0f18841615c9dd7e9115f27ea034f320085144fb934667fc442297a03 | Python | 3,385 | 81 | from PymoNNto.Exploration.Network_UI.TabBase import *
from PymoNNto.Exploration.Visualization.Visualization_Helper import *
from PymoNNto.Exploration.Network_UI.Network_UI import *
class classifier_bar_tab(TabBase):
def initialize(self, Network_UI):
self.cluster_bar_tab = Network_UI.add_tab(title='Cluste... |
814c90f48d4fbd2f879c93f46dc383a356daa455ab4e3a9ce7341cb81a05b1e1 | Python | 3,388 | 107 | import unittest
import numpy as np
from foldingdiff import utils
class TestModuloWithWrappedRange(unittest.TestCase):
"""Test the modulo with wrapped range"""
def test_simple(self):
"""Test a hand-engineered example"""
x = utils.modulo_with_wrapped_range(3, -2, 2)
self.assertEqual(-... |
f78abed39b2cc568d17819d63130e9f87ef7c5ac7277ef6aca44a9fa4383929c | Python | 3,388 | 85 | # Copyright 2020 Forschungszentrum Jülich GmbH and Aix-Marseille Université
# "Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; and to You under the Apache License, Version 2.0. "
import numpy as np
import pathlib
import re
import os
import time
def wait_transformat... |
c4ddf6386b0b9eb66e7765db98801bab200a4d4ae588969cdd6fcdd8bb4ef79c | Python | 3,391 | 97 | # This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it.
import torch
def _normalize_weight_index_slices(weight_index_slices):
normalized = []
for entry in weight_index_slices:
index_slice = getattr(entry, "slice_1D", None)
shape_2d ... |
0bb50f92457c5415e89f1d37c68347d86a8705fae3bc9f6a15f52c5c853e69b2 | Python | 3,395 | 90 | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
from torch import nn, Tensor
from typing import Optional
class MaxPool2d(nn.MaxPool2d):
"""
Applies a 2D max pooling over a 4D input tensor.
Args:
kernel_size (Optional[int]): the size of the ... |
6e0eaa45f87916a08648508ca60a37bc5ddc1a19acc515779183065cd10c710b | Python | 3,395 | 92 | import os
import pandas as pd
import sys
import numpy as np
#Read in the intersected narrowPeak file derived from liftover
#cutoff is the argument that determines the degree of overlap required between two peaks for them to be considered partners.
y = sys.argv[1]
cutoff = float(sys.argv[2])
m = pd.read_csv(sy... |
fe27d402a66b741b21f1ac50c8e373b4ec39903c81823032e826a4441a9e1350 | Python | 3,395 | 107 | import sys
import numpy as np
import pandas as pd
from scipy import sparse
import itertools
import os
import CoEmbedding
DATA_DIR = '/media/O_o/UB/research/dataset/20newsgroups/CoEmbedding/'
dwmatrix_pt = DATA_DIR+'dw_matrix.csv'
vocab_pt = DATA_DIR+'vocab.txt'
n_docs = 18827
n_words = 20678
def tfidf(D... |
71345eb79be7401b0cda439ee607ec1867ed3f90e2a065fbc26067508d1755b2 | Python | 3,398 | 109 | """
Export fif raw data to different format.
Supported:
- EEGLAB '.set'
"""
from pathlib import Path
import mne
from scipy.io import savemat
from numpy.core.records import fromarrays
from .io_file_dir import get_file_list, make_dirs
from ... import logger
# ----------------------------- EEG LAB ---------------... |
711575fdbfd39805d58cf0a2db6257a7dbe52e3a40c22ead68931cc3ec1915dd | Python | 3,399 | 91 | #import sys
import matplotlib.pyplot as plt
import seaborn as sns
import pandas
import numpy
sns.set()
from Bio import pairwise2
from Bio.pairwise2 import format_alignment
def getinfo(INFO,KEY,caster=float):
splitter=KEY+"="
if splitter in INFO:
value=INFO.split(splitter)[1].split(";")[0]
retu... |
a036d2e315e906485bccfa469b356e7f1adb86a7e068131cc3f17dea99dea2df | Python | 3,402 | 93 | # Copyright (C) 2020-2023 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Data Splitters tests module."""
import pytest
from openfl.utilities import change_tags
@pytest.mark.parametrize(
'tags,expected_result', [
((), ()),
(('abc',), ('abc',)),
(('abc', 'def'), ('abc', 'def')),... |
f2b7bb34b1f49a58f1c0619085e1ffb83bc25a4d6e13049b689ac773bd9e3a1d | Python | 3,402 | 98 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
import math
from omegaconf import II
import torch
from fairseq import metrics, modules, utils
from fairseq.... |
303ac249f7468ad0e877096e0bf2c8315128abfab6953be2023a1b5729122e7e | Python | 3,404 | 60 | """Matched binary/discrete/continuous score comparisons with explicit error denominators."""
from __future__ import annotations
import polars as pl
def metrics(predictions: pl.DataFrame) -> pl.DataFrame:
"""Summarize saved held-out forecasts; never fit, choose thresholds or drop unknown calls.
Input columns... |
894bfecef2554c510a3847730e7c88acb679ee09c31c7191e54c78ca10756fdd | Python | 3,406 | 65 | """The assessment covers reported observations without changing their identity."""
from __future__ import annotations
import os
from pathlib import Path
import polars as pl
import pytest
from vdjdb.assemble.assessment import KEY, PROVENANCE, specification
from vdjdb.emit.vdjdb3 import read_table
from vdjdb.schema im... |
99855c94e233e7c195b6692d4c04b3ac3934409038dbef82e9073e88789357e8 | Python | 3,407 | 108 | import os
import time
import warnings
import numpy as np
from pydfc import MultiAnalysis, data_loader
warnings.simplefilter("ignore")
os.environ["MKL_NUM_THREADS"] = "16"
os.environ["NUMEXPR_NUM_THREADS"] = "16"
os.environ["OMP_NUM_THREADS"] = "16"
################################# Parameters #####################... |
2e05fa477851a221419eb54df9fddc8d8609c8541e0edb84df5d6cc641ca7ea7 | Python | 3,408 | 83 | # Based on the code from: https://github.com/klicperajo/dimenet,
# https://github.com/rusty1s/pytorch_geometric/blob/master/torch_geometric/nn/models/dimenet.py
import torch
from torch_scatter import scatter
from torch_sparse import SparseTensor
from math import pi as PI
device = torch.device('cuda' if torch.... |
f43a43c772d03909eaf5afb5e2b3ecd9113ada2bc1f94dbb611b7292e731f41b | Python | 3,408 | 96 | from typing import Dict, List
from hypothesis import given
from chromadb.test.conftest import (
ClientFactories,
)
import hypothesis.strategies as st
from chromadb.test.conftest import MULTI_REGION_ENABLED
def test_list_databases(client_factories: ClientFactories) -> None:
client = client_factories.create_cli... |
4494efffadb02652b7f3cb9fa3f6eeff90a132001868791388277d088c35df02 | Python | 3,412 | 82 | """
Extract the annotations of Neo objects and structure them in a DataFrame
to complement a wave characterization.
"""
import argparse
from pathlib import Path
import numpy as np
import pandas as pd
import quantities as pq
import re
from utils.io_utils import load_neo, save_plot
from utils.parse import none_or_path, ... |
765177ea9931dcb7ba51c2dd66b74c424dfacc19e6d4db1fd511143eb00e0dae | Python | 3,412 | 149 | import pytest
import geomstats.backend as gs
from geomstats.numerics.optimization import (
NewtonMethod,
ScipyMinimize,
ScipyRoot,
)
from geomstats.test.parametrizers import DataBasedParametrizer
from geomstats.test_cases.numerics.optimization import (
OptimizerTestCase,
RootFinderTestCase,
)
from... |
4ac22bc6a61a3e990cb64a1a2288a9c4e69229bce899e5f90ebdeef730aadd93 | Python | 3,413 | 105 | # 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."""
from logging import getLogger
import numpy as np
import keras
logger = getLogger(__name__)
def one_hot(labels, classes):
"""
One Hot encode a vector.
... |
cf1b664e7edca5f43dc90cb4d5de27c4da428f79ae8dc00dbc347d7687c82617 | Python | 3,413 | 107 | import numpy as np
from sleeprnn.data import utils
from sleeprnn.detection.predicted_dataset import PredictedDataset
def generate_ensemble_from_probabilities(
dict_of_proba, reference_feeder_dataset, skip_setting_threshold=False
):
"""
dict_of_proba = {
subject_id_1: list of probabilities to ensem... |
97f99798fc44ece2297ad07e94f8bec6be0bffffb68939d20dff924c10c40e16 | Python | 3,414 | 134 | import random
import pytest
from geomstats.geometry.pre_shape import PreShapeSpace
from geomstats.geometry.quotient_metric import QuotientMetric
from geomstats.test.parametrizers import DataBasedParametrizer
from geomstats.test_cases.geometry.pre_shape import (
KendallShapeMetricTestCase,
PreShapeBundleTestCa... |
b1be7d3e998c3f882d61ce5afa806f5320021ce30b6fd33a90e20b70192621a6 | Python | 3,414 | 82 | """
Extract the annotations of Neo objects and structure them in a DataFrame
to complement a wave characterization.
"""
import argparse
from pathlib import Path
import numpy as np
import pandas as pd
import quantities as pq
import re
from utils.io_utils import load_neo, save_plot
from utils.parse import none_or_path, ... |
f4f8cae9e85312fea6794aae091ede326ef2bc3c2c80c5889fe1c7ed24cfb3fe | Python | 3,415 | 104 | """Tests for Summarize Results row selection and its detection-error report."""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
import sanpy
from sanpy.interface.plugins.sanpyPlugin import sanpyPlugin
from sanpy.interface.plugins.summarizeResult... |
fc16f8ccdb7dca915ac6748048f96f77a0d40587082b799dba74b5dec41fb705 | Python | 3,415 | 95 | import sys
import os
import shutil
from logging import getLogger
from urllib.request import urlretrieve
from hashlib import sha384
from os import path, makedirs
from tqdm import tqdm
import modin.pandas as pd
import gzip
from sklearn.model_selection import train_test_split
import numpy as np
logger = getLogger(__name_... |
69561c86f5b432e717595b11bd4c06bb14ed6d36d8a2c971fbf320d9b5b590a6 | Python | 3,416 | 94 | ## Scripts to run test of the 3D model. The code is similar to reproduce.ipynb.ß
import os
import torch
from tqdm import tqdm
import numpy as np
from ogb.lsc import PygPCQM4MDataset, PCQM4MEvaluator
from torch_geometric.data import DataLoader
from deeper_dagnn import DeeperDAGNN_node_Virtualnode
from conformer.dataset... |
fe39d2150146424395549d5c8030c7d1e467dc219f78f93ffdc8ab42410cc524 | Python | 3,416 | 65 | # -*- coding: utf-8 -*-
import functions.rate_coding
import numpy as np
import functions.Graphs
import matplotlib.pyplot as plt
import functions.statistics_test as st
import functions.glm_to_predict_speed_from_neuronal_activity as glm
#%% Load data
data = np.load('/datapath/dataset.npy', allow_pickle=True).it... |
64645d0cc4ff5c4c31933260498279ea8a0ceff07c62e523986ea93062c8228b | Python | 3,417 | 114 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 6 20:51:38 2023
@author: Dongdong Zhou
"""
import numpy as np
import pandas as pd
from sklearn import svm, metrics
from sklearn.metrics import confusion_matrix, roc_curve
from sklearn.preprocessing import Normalizer
from sklearn.model_selection import GridSe... |
53d47043d54ec80cd752410f76a50e12f475a81b941b48d217202d8543b1c67f | Python | 3,421 | 105 | # Copyright 2020-2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import subprocess
import json
import logging
import argparse
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
def get_l... |
81ab0b51368a9080d03ab3c90ed79a40a00396d3e19266d77ba7ea632a9eac12 | Python | 3,424 | 92 | """
This script runs the simulation and saves the average synaptic currents.
"""
from brian2 import *
import numpy as np
from tqdm import tqdm
import os
from pathos.multiprocessing import ProcessingPool as Pool
from scipy.ndimage import gaussian_filter1d
import pickle
from utils import connection_matrix, extract_mean_... |
067f2e522cefd777330607a5e10cb720b3329384c486096365cc31a329683569 | Python | 3,427 | 113 | # Copyright 2020-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""openfl.experimental.workflow.utilities.stream_redirect module."""
import io
import sys
from copy import deepcopy
class RedirectStdStreamBuffer:
"""Buffer object used to store stdout and stderr.
Attributes:
_stdoutbuff... |
4c174124298aac11f2fbd217a136f8cd13726784da22b6c8e3f8ce09f5c20ee6 | Python | 3,427 | 92 | from typing import Tuple
import torch
from torch import nn as tnn
from torch.nn.utils import rnn as tnnur
from reinvent.models.linkinvent.networks.attention_layer import AttentionLayer
from reinvent.models.model_parameter_enum import ModelParametersEnum
class Decoder(tnn.Module):
"""
Simple RNN decoder.
... |
842d593bf961436554e3a693e3d8e01ced548c76de44d53e44ff8d04a113ab0a | Python | 3,427 | 118 | """Fixture setup for pytest
IMPORTANT: NEVER import directly from conftest.py
also DO NOT mess with sys.path
"""
import os
import sys
import json
import pytest
import torch
from reinvent import models
# kludge to fix tests by-passing compatibility mode in the code
sys.modules["reinvent.models.mol2mol.mod... |
a1b4875123c818a0f8c3ef57b605b299dd8d39530fdcf7ff8163bfe43adeedf2 | Python | 3,427 | 125 | import os
import argparse
import torch
from torchvision import transforms
from time import time as t
from tqdm import tqdm
import bindsnet.datasets
from bindsnet.encoding import PoissonEncoder, NullEncoder
from bindsnet.network import Network
from bindsnet.learning import PostPre
from bindsnet.network.nodes import ... |
74ab45beb814a6c3e20ef676576fc10cc0efc6b8fc0beae0e5333c1b90e8a55c | Python | 3,432 | 108 | import os
import argparse
from tqdm import tqdm
import chromadb
from chromadb.utils import embedding_functions
import google.generativeai as genai
def main(
documents_directory: str = "documents",
collection_name: str = "documents_collection",
persist_directory: str = ".",
) -> None:
# Read all file... |
3eb7b67317f13dd2b29c1df19e2e921d9052fb11f095a3c8f370b8efa37180d8 | Python | 3,433 | 104 | from functools import wraps
from pathlib import Path
import numpy as np
import flammkuchen as fl
from joblib import Parallel, delayed
from split_dataset import SplitDataset, Blocks, EmptySplitDataset
def h5cache(func, output_dir: Path, filename=None):
@wraps(func)
def return_cached(*args, **kwargs):
... |
2ab331f17b450d530965908d52e60766b4f08d54eabd7e66811136514490200b | Python | 3,435 | 119 | import threading
import uuid
from typing import Any, Callable
from chromadb.types import Segment
from overrides import override
from typing import Dict, Optional
from abc import ABC, abstractmethod
class SegmentCache(ABC):
@abstractmethod
def get(self, key: uuid.UUID) -> Optional[Segment]:
pass
@... |
6132d0ffa26db5a13936083d499912e8e0eac4efb45c055d5bbff027c1627707 | Python | 3,435 | 74 | # Generated by Django 4.1.5 on 2023-01-30 09:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('celsus', '0052_kinaselibrarymodel'),
]
operations = [
migrations.AlterField(
model_name='collab... |
dae898d5e4f6b63439a6487d0bbacf1930f6ae10f567b1c016f21e9ba6bded81 | Python | 3,435 | 115 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
# add python path of PaddleDetection to sys.path
parent_path = os.path.abspath(os.path.join(__file__, *(['..'] * 2)))
sys.path.insert(0, parent_path)
# ignore warning log
import warnings
w... |
3920ca8ca25dd5f95bcb6de93538fa4ad86cb67996cd5130c935343d9a215a7e | Python | 3,437 | 88 | #!python
__doc__="""\n
the script is used to merge mutrate dataframe of each sample together
INPUT:
a directory contaning all mutrate dataframes
optional: the metasheet of samples
OUTPUT:
mutrate matrix
reactivity matrix
"""
import argparse
import glob
import re
import nu... |
cd25e62a89bfc2efcde833e1b146dfb944775655f272df218618588cbde15d1a | Python | 3,437 | 69 | """The committed record registry against the corpus it is supposed to describe (#672).
`registry/records.tsv.gz` is an input: `vdjdb build` reads it and only `vdjdb identity update` writes it.
So it can go stale, and a stale registry is worse than none - it reports amendments nobody made and,
where a key change is amb... |
dca47fe51af7d7801fd74bbea12527484e4c6a7296a7a6a6095c71a0d5373a45 | Python | 3,437 | 101 | import fastdeploy as fd
import cv2
import os
def parse_arguments():
import argparse
import ast
parser = argparse.ArgumentParser()
parser.add_argument(
"--tinypose_model_dir",
required=True,
help="path of paddletinypose model directory")
parser.add_argument(
"--det_m... |
66e6e1cd407f1c0d1c4388de80492c3b3fe7e49b2bd2a5ba54cb3e27818e01b8 | Python | 3,438 | 152 | import functools
import torch as _torch
from torch import complex64, complex128, float32, float64, get_default_dtype
from geomstats._backend._dtype_utils import (
_MAP_FLOAT_TO_COMPLEX,
_pre_add_default_dtype_by_casting,
_pre_allow_complex_dtype,
_pre_cast_out_to_input_dtype,
)
from ._common import c... |
769b41aabf26f585edcd3d29503c9cb817099c657128305701d8e942b6f31a2a | Python | 3,440 | 77 | import numpy as np
import odl
from dival.data import DataPairs
from dival.evaluation import TaskTable
from dival.measure import PSNR, SSIM
from dival.reconstructors.odl_reconstructors import (FBPReconstructor,
CGReconstructor,
... |
871a40c0bc26a7079ab2da9f03564c490563ab70ccb97c715f1e3725fa4360f8 | Python | 3,440 | 106 | import torch
import torch.nn as nn
import torch.nn.functional as F
class DoubleConv(nn.Module):
"""(convolution => [BN] => ReLU) * 2"""
def __init__(self, in_channels, out_channels, mid_channels=None):
super().__init__()
if not mid_channels:
mid_channels = out_channels
... |
38c5b016880019cafa59ea2be4b94e03a9a745ee1e3b212b1dcc1a0b17083315 | Python | 3,441 | 102 | from pathlib import Path
import mne
from .. import io
from ... import logger
def rename_channels(inst, new_channel_names, **kwargs):
"""
Change the channel names of the MNE instance.
Parameters
----------
inst : mne.io.Raw | mne.io.RawArray | mne.Epochs | mne.Evoked
MNE instance of Raw ... |
88e59bc131ad8ba80b0ee66fa986bb002144b79fcdca465bcc82719442bf66b7 | Python | 3,441 | 91 | import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
import numpy as np
from dival.reconstructors.networks.unet import get_unet_model
def get_iradonmap_model(ray_trafo, fully_learned, scales=5, skip=4,
channels=(32, 32, 64, 64, 128, 128), use_sigmoid=True,
... |
beb16f496afce565c843b9365a033f287065b9418679d405e18008b0a2a5eba4 | Python | 3,444 | 99 | from collections import namedtuple
import numpy as np
import torch
import torch.nn as nn
from model_angelo.utils.knn_graph import knn_graph
from model_angelo.models.common_modules import SinusoidalPositionalEncoding
from model_angelo.utils.affine_utils import get_affine_translation, vecs_to_local_affine
from model_an... |
f451d29cb924fb4e6a59e4bc32ecbc8df714b5db82f1c95d1f0a98a293d99d3d | Python | 3,445 | 113 | import os
import pandas as pd
from tqdm import tqdm
import logging
import json
from sqlalchemy import create_engine
from sqlalchemy import inspect
from sqlalchemy.sql import text
def get_dict_chembl2uni(PATHDICT):
logging.info('Retrieving dictionary chembl2uni from rest api')
# original: https://ftp.ebi.ac.u... |
fdb2e11ce345ca36b8130a7384af79d12c67900c623e6de5f13378ba955d8d31 | Python | 3,445 | 92 | import copy
import torch.nn as nn
from reinvent.models.transformer.core.network.encode_decode.decoder import Decoder
from reinvent.models.transformer.core.network.encode_decode.decoder_layer import DecoderLayer
from reinvent.models.transformer.core.network.encode_decode.encoder import Encoder
from reinvent.models.tra... |
436f68cd0c58e74cfe4420a60d893710ddaae82341d42fa3a098cee07a6fe005 | Python | 3,446 | 66 | # =====================================================================================
# RE-MEASURE A100 end-to-end latency for all 6 models (clean, robust).
# RUN ON AN A100 GPU (Colab Pro: Runtime > Change runtime type > A100).
# YOLO + RT-DETR via Ultralytics; D-Fine skipped here (needs its own env) -> see note.
# ... |
c1a36e15adf840edd4a68e36b0671224fa21955e4c1c8ec3ef4c1f5bf6b9c23b | Python | 3,446 | 101 | import numpy as np
import pyabf
from sanpy.fileloaders.fileLoader_base import fileLoader_base, recordingModes
from sanpy.sanpyLogger import get_logger
logger = get_logger(__name__)
class fileLoader_atf(fileLoader_base):
loadFileType = ".atf"
# def __init__(self, path):
# super().__init__(path)
... |
4318e1d8b17f4c471b72bbf5e6088b01f375d8ff75b2257043ea6dac071096b0 | Python | 3,447 | 71 | """The homogeneity--parsimony trade-off ``Q``, for comparing two clusterings on equal terms.
``Q = 2hp/(h+p)`` (Tiffeau-Mayer, `arXiv:2607.20799 <https://arxiv.org/abs/2607.20799>`_), the
score `~/vcs/manuscripts/2026-immrep25-audit` places its cohort ladder with. Homogeneity ``h`` asks
whether clusters predict the ep... |
3d058a5c1afea15bca975bf02b6c5f6b9efc1a4cb0dcee9c62b7902a403636a1 | Python | 3,449 | 100 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from argparse import Namespace
from typing import Union
from fairseq.dataclass import FairseqDataclass
from fairseq.dataclass.utils import me... |
72626c02125ca68bafe548aafb3cd562dde47a69fe8a6e2264e795636b15c5c6 | Python | 3,450 | 95 | import pytest
import geomstats.backend as gs
from geomstats.test.test_case import TestCase
from geomstats.test.vectorization import generate_vectorization_data
class PointToGeodesicAlignerTestCase(TestCase):
def test_align(self, geodesic, point, expected, atol):
res = self.aligner.align(geodesic, point)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.