sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
59e876474c3fa70bd071857f460974bc730b7acff3aec8fb6d16bbaa41ee5ecc
Python
2,337
72
import argparse import os import os.path as op from fsub_extractor.utils.anat_utils import anat_to_gmwmi # Add input arguments def get_parser(): parser = argparse.ArgumentParser( description="CLI tool for converting anatomical file (FreeSurfer output or T1) to a GMWMI. Also produces the 5TT image as an in...
7005802b2ce65cd961b59ca7b6be404ff78bc62e598963a4375720255a251469
Python
2,337
60
import argparse import numpy as np from spiking_readout.utils import Logger from spiking_readout.dataset import SpikingDataset from spiking_readout.readout import ReadoutParameters, Readout def fit(input_dir, output_dir, config, seed=0, log_to_file=True, save_model=True, eval_test=False): # To control randomness ...
d5487e8eafb858fcc1b34051326ed4a79997369f3efe641aba21a6a01dd7f063
Python
2,337
80
import time from pybuildkite.buildkite import Buildkite from ci.ray_ci.bisect.validator import Validator from ci.ray_ci.utils import logger from ray_release.aws import get_secret_token from ray_release.configs.global_config import get_global_config from ray_release.test import Test BUILDKITE_POSTMERGE_PIPELINE = "p...
482989d79e215be31e99bce1df7423c04e7aa13466a5874b0a20388146c962f1
Python
2,338
75
#!/usr/bin/env python3 """Functions for module enrichments on dataFrames.""" import numpy as np import pandas as pd def calc_df_enrichment(df, col, genes, module_match): """ Calculate enrichment of modules in dataframe. Given a dataframe with genes (df.gene) and some split (df[col]), calculate the en...
b2016d0f217b89c84bed2b195c852868185c81626a20bf134aba30b3813c928e
Python
2,339
88
import asyncio import time import ray from ray import serve from ray.exceptions import RayActorError from ray.serve.config import DeploymentActorConfig # __begin_define_deployment_scoped_actor__ @ray.remote class SharedCounter: def __init__(self, start: int = 0): self._value = start def increment(se...
62a61617a5e107d12d60cfa8770dd5d0fee784d3bae22c4f39151751d6c06463
Python
2,340
55
import pytest import numpy as np from reval.internal_baselines import select_best, evaluate_best from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score, davies_bouldin_score import hdbscan @pytest.mark.parametrize( "data, clustering, internal_measure, clust_range, select, expected_type, e...
8bbd15ed5745a393535007f8cb9497a54e36c6983214e6251ad78b826dbeca5a
Python
2,340
75
r""" Input/Output utilities for OmicVerse datasets. Subpackages: general: Shared I/O helpers for tabular data and serialization. bulk: I/O helpers for bulk omics resources. single: I/O helpers for single-cell data. spatial: I/O helpers for spatial omics data. cytometry: I/O helpers for flow / mass ...
ba25391420bc202cb8919989b19fa9f05ff41a98c176138d134d4a8515908680
Python
2,340
67
import cupy as cp import numpy as np import matplotlib.pyplot as plt import time import torch from pyJoules.energy_meter import EnergyContext from pyJoules.device.rapl_device import RaplPackageDomain, RaplDramDomain from pyJoules.device.nvidia_device import NvidiaGPUDomain from pyJoules.handler.pandas_handler import ...
5c7e5e9f20fb39130906a3fa9685a9b95d603f44bca585dd78dd0ebe4a32d106
Python
2,342
72
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Merge duplicate records and counts files across multiple TSVs. """ from typing import List, Text, Optional from collections import defaultdict import argparse import sys import csv def merge_duplicates(record_files: List[str], count_files: List[str], fout: str): ...
579046b51990d406a1199a0125fab8b69e2a4244210da9f86540cd1eecd1ad55
Python
2,343
68
""" 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 random import ase import numpy as np from fairchem.data.oc.core import Adsorbate _test_db = { ...
62df3b6dc0d3c6c11080b461c762eaadd08c58a282c3c9336484ad33d58fd1b5
Python
2,343
65
#!/usr/bin/env python3 # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # Used to run Google Tests generated during build. Takes in a text file # containing a list of relative paths to text exectuables to run and path to # binary output directory of build. The paths are re...
7fb4d5b51b6c63feba50656b04df5c869ab47f6f9158fb60d0a635bf353e76f3
Python
2,344
60
import unittest from dataclasses import dataclass from typing import List, Union import numpy as np import PIL.Image from diffusers.utils.outputs import BaseOutput @dataclass class CustomOutput(BaseOutput): images: Union[List[PIL.Image.Image], np.ndarray] class ConfigTester(unittest.TestCase): def test_ou...
4f0963ea32164d848ea59b8fe863083077b03de590e26c4fa9136e1ccfef9339
Python
2,346
70
# __cgraph_overlap_start__ import ray import time import torch from ray.dag import InputNode, MultiOutputNode @ray.remote(num_cpus=0, num_gpus=1) class TorchTensorWorker: def send(self, shape, dtype, value: int, send_tensor=True): if not send_tensor: return 1 return torch.ones(shape, d...
f1bce9716dc53e9ff6b10e8859d7dd2e40c3b0cc5f9fe29ce5a194061208aed5
Python
2,346
70
#!/usr/bin/env python ####################### # unused functions # # These are not presently used in the Caiman codebase, but are # being kept for being potentially useful (and either not trivial to # reimplement, or themselves a nontrivial idea). # # Code in this file should: # 1) Not be considered for purposes of "d...
bae2ebf41234e6c0128f4094f13a0d2193b5fa114ad6555f18f446f3ab039905
Python
2,350
88
import collections import pytest from pfrl.collections.random_access_queue import RandomAccessQueue @pytest.mark.parametrize("maxlen", [1, 10, None]) @pytest.mark.parametrize("init_seq", [None, [], range(5)]) class TestRandomAccessQueue: @pytest.fixture(autouse=True) def setUp(self, maxlen, init_seq): ...
4aa2b22a22de43754ed694c308073b1bf6508008218303427162dd2937d922ad
Python
2,351
49
"""Binary hashing and sparse local histograms, without dense 2**L arrays.""" import torch def block_geometry(height, width, block_size, overlap): bh, bw = block_size sy, sx = (int((1 - overlap) * b + .5) for b in block_size) if height < bh or width < bw: raise ValueError(f"Histogram block {block_s...
627aba95b10b351572f941ad9369bae06d0ebd8030cd7ef9dc48f19a8f9e4c1d
Python
2,351
71
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ Convert RdTest de novo format to standard format """ import argparse import numpy as np import pandas as pd def reformat_dn_rdtest(dn_metrics): id_vars = 'chr Start End CNVID Type Family AffectedMember'.split() metrics = pd.melt(dn_metrics, id_vars=id_vars...
289b54d282cad35902289bbc0f4c477147f092baad975d06d585630936c8e213
Python
2,352
62
import torch def add_noise(x, noise, snr_db): """Add zero-mean noise scaled to a per-lead SNR (dB) relative to the signal power.""" signal = x.var(dim=-1, keepdim=True, unbiased=False) noise = noise - noise.mean(dim=-1, keepdim=True) power = noise.pow(2).mean(dim=-1, keepdim=True).clamp_min(1e-12) ...
63e25a38952fc264313ec441790ba74830c2954379fe4a06265c30c0fe16564d
Python
2,352
56
import logging from datetime import datetime logger = logging.getLogger(__name__) timezones = [ {"offset": "-12:00", "value": "Etc/+12"}, {"offset": "-11:00", "value": "Pacific/Pago_Pago"}, {"offset": "-10:00", "value": "Pacific/Honolulu"}, {"offset": "-09:00", "value": "America/Anchorage"}, {"off...
cec37b3340d383a899b373dd18ef226c1bd87cc12361da12bcd8bed1fc467f10
Python
2,352
58
import numpy as np def generate_example_timeseries(num_examples, length): """Generates a dataset of three-channel timeseries of desired size, meant to substitute (but not exactly approximate) wearable sensor data. First two channels represent heart rate and stepcount, modelled as cyclical trends with ...
44725d11fdbbb169364ba4e23d7715430e03a44efaf6b0bdb5b7c9781aafc12b
Python
2,354
61
#! /usr/bin/env python3 # ReScience yaml to bibtex converter # Released under the BSD two-clauses licence def generate_bibtex(filename, article): content = ( "@Article {{{_.authors[0].lastname}:{_.date_published.year},\n" " author = {{{_.authors_full}}},\n" " title = {{{{{_.t...
95e1ece1f370f0ae5675840e97ac245acb5c9ef643bd09fe8013368284ec73ed
Python
2,354
78
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """Base classes for the RPUConfig.""" from typing import Type, Union, Any, TYPE_CHECKING from dataclasses import dataclass, field from .runtime import RuntimeP...
e56763ae1e9a1ede7af3a1865f4a0ae7469963c96c10f61b46bdcf9e8ce1dc82
Python
2,354
69
from loguru import logger import os import sys import json from deltasplice.constant import CL, EL, Fapath from pyfasta import Fasta import pandas SavePath = "data/FAS" # hgfile["chr10"][90770509:90770572].upper() matches def main(File, species, SavePath): mutinfo = pandas.read_csv(File) fafile = Fasta(os.pa...
23ed1c50a7532c81aba7cd92d2bcd3f73bd37d1f2d2a318baa26c3c850cffeab
Python
2,355
58
import numpy import pandas def assert_indices_equal(i1: pandas.Index, i2: pandas.Index, context: str): assert numpy.array_equal(i1.isnull(), i2.isnull()), f"{context}: index null values not equal" assert numpy.array_equal(i1[~i1.isnull()], i2[~i2.isnull()]), f"{context}: index non-null values not equal" def...
74800fd8e617f837bf0d54139070bf3a1417a9d0d605370b4786d1bbc3c51bcb
Python
2,356
79
# flake8: noqa # fmt: off from typing import Iterator, Union, List import pyarrow from ray.data.block import Block # __datasource_constructor_start__ from ray.data.datasource import FileBasedDatasource class ImageDatasource(FileBasedDatasource): def __init__(self, paths: Union[str, List[str]], *, mode: str): ...
b9b117f0abd9d7cb59822958b06cb9a55b5a9a3a851a47d0e82e6b6c4da6d41f
Python
2,356
82
import os import torch import torch.nn as nn from sinabs.backend.dynapcnn import DynapcnnNetwork from sinabs.backend.dynapcnn.dynapcnn_visualizer import DynapcnnVisualizer from sinabs.from_torch import from_model weights_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "dvs_gesture_params.pt" ) ...
d9e32b08bba3d65635516ae02f9d1f5f5a993278c4f496ad9555a55140ea5bf9
Python
2,356
55
#---------------------------------------------------------------------------------------------------------- # Author: Brandon S Coventry # Date: 12/16/2023 # Purpose: Generate data to address asymptotics of Bayesian vs Frequentist inference on a DBS-LFP model #-----------------------------------------------------------...
d2f3315876545bf23adb092310eccceec5cbd31c73e2ee597f68a45d6dce72fd
Python
2,357
73
import torch import sinabs import sinabs.backend.dynapcnn as sdl def get_network(has_identity_weights=True, n_layers=9, has_bias=False): sequential = torch.nn.Sequential() for i in range(n_layers): layer = torch.nn.Conv2d(1, 1, (1, 1), bias=has_bias) if has_identity_weights: with ...
19938f6571dff47d61ba2295c437d925437d12a77e6e0444696d7fd7d8304684
Python
2,359
50
#################################################################################################### # 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...
9d4c34c0b7fe018f15211fb8081c3813e4fb81b211255f97f65fbe28b8b0c35e
Python
2,359
71
import os os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' import numpy as np import torch from solver import Solver from optimizer import Optimizer import matplotlib import plt_config import matplotlib.pyplot as plt matplotlib.use('Agg') # for running on server without GUI color = plt.rcParams['axes.prop_cycl...
1f66065eebe52c31278c53e313f7581adec3cfa0a7ec511fad1da15709cdb09a
Python
2,360
98
# flake8: noqa import requests # __echo_class_start__ # File name: echo.py from starlette.requests import Request from ray import serve @serve.deployment class EchoClass: def __init__(self, echo_str: str): self.echo_str = echo_str def __call__(self, request: Request) -> str: return self.ec...
8042cada215dc23dc4d2e45ffe461e46019da24b853e4b0fe99b7015c675ad59
Python
2,360
65
#!/usr/bin/env python3 from __future__ import print_function import argparse import os import subprocess def parse_args(): parser = argparse.ArgumentParser("Extracts FASTA/FASTQ segments from another fasta") parser.add_argument('--input', '-i', dest='input', required=True, type=str, he...
527eb499ad3111196c8ee8c306af39356afbd8e5080abf3d274a317d435313aa
Python
2,361
56
import importlib import json import argparse import torch from benchmark.utils import benchmark_forward def generate_data(batch_size, N, L, symmetric=True, device='cuda'): if not symmetric: v = torch.randn(batch_size, N, dtype=torch.complex64, device=device, requires_grad=True) w = torch.randn(b...
79c63edb8f9fef709a41d8e230157074c715e389f557a85fe5a030846a6aa182
Python
2,361
73
from abc import abstractmethod, ABC import sqlite3 from google.cloud.bigquery import Client class DatabaseClient(ABC): def __init__(self, client): self.client = client super(DatabaseClient, self).__init__() @abstractmethod def execute(self, query: str): pass class BigQueryDatab...
e1c80a40b7d9b4b4796a3dbab3883968d95fac1a7d968da146f4df0a2dd38aee
Python
2,361
77
import numpy as np import torch import random from .spaces import num_flat_space_elements from .spaces import nd_to_flat_space_index from .spaces import flat_to_nd_space_index from .set_values import set_value_by_function from .set_values import linear_value_adaptation from .similarity_search import inverse_distance_k...
17ee7ed4f5efde1228b3927c153ecefff67f85fccb1d0c3c27d681c78c9540f7
Python
2,362
81
#!/usr/bin/python #################################################################################################### # 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> # # ...
3908ada84ef52107ad6242cc9f1f1cd61aa491acb4826d4ab1dc78bf49b98ec1
Python
2,363
88
# __example_code_start__ from io import BytesIO from fastapi import FastAPI from fastapi.responses import Response import torch from ray import serve from ray.serve.handle import DeploymentHandle app = FastAPI() @serve.deployment(num_replicas=1) @serve.ingress(app) class APIIngress: def __init__(self, diffusi...
8967a4be6ae7f33e3a4fa4e82f3db42cc50799128bf154108d2de554169c58a9
Python
2,364
76
import unittest from neuron_morphology.feature_extractor.data import Data from neuron_morphology.feature_extractor.mark import Mark from neuron_morphology.feature_extractor.marked_feature import marked from neuron_morphology.feature_extractor.feature_extraction_run import \ FeatureExtractionRun from neuron_morphol...
ef1f780f56fb036988316f077308b6b6ab8504358e2d545b6d4b390688fe1df5
Python
2,364
65
import pickle import requests import pysam import subprocess import concurrent.futures file_path = 'files/' samples_to_file, regions = pickle.load(open(file_path + '/bams/queries.pkl', 'rb')) ##your token with open(file_path + '/bams/gdc-user-token.2021-12-13T20_06_44.138Z.txt') as f: token = f.read() def load_u...
727687058f00fa0857777a2e1a46f10d866d712ca78328bb2f22dc07e303832d
Python
2,365
100
from typing import Optional from jaxtyping import DTypeLike from functools import partial import numpy as np import jax import jax.numpy as jnp import jax.random as jr from jax.sharding import PositionalSharding jax.config.update("jax_enable_x64", True) jax.config.update("jax_default_matmul_precision", "float32") jax...
c07bb12bfe7850b48c41fc683a1510b9d76a335018fed2072cab3f73d35ef1f0
Python
2,366
63
from typing import Optional, Sequence import torch from rising.transforms import BaseTransform from rising.transforms.functional import one_hot_batch __all__ = ["OneHot", "ArgMax"] class OneHot(BaseTransform): """ Convert to one hot encoding. One hot encoding is applied in first dimension which results...
f9ab4bec567193a0fc27048ff42292cf1d8fb0b29456a1b64229dc6676892df9
Python
2,366
59
import logging import json from agent.data.entities.config import BACKUPS_PATH, ROOT_LOGGER_ID from agent.data.sql.sql_mgmt import execute_query, get_connection from agent.data.sql.sql_mgmt import select_fields_where logger = logging.getLogger(ROOT_LOGGER_ID) def insert_triple(connection, triple_dict): insert_t...
396f13bb586fe444475ac401b2cf456cf6310eba0dff23db1f053ff5e86063bc
Python
2,367
79
""" 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 random import numpy as np import pytest from fairchem.data.oc.core import Adsorbate, Bulk, Inte...
fed7e68ff6c9e905a31cbcebfe5b6dcbff550aea906ffd987adcce0f8be0ab12
Python
2,370
67
from typing import Dict, Optional from ray._common.observability.internal_event import InternalEventBuilder from ray.core.generated.events_base_event_pb2 import RayEvent as RayEventProto from ray.core.generated.platform_event_pb2 import PlatformEvent, Source from ray.util.annotations import DeveloperAPI @DeveloperAP...
957ca282d538f9ade166b1928a67ef32863a5debc137b4bd47bc2e7b026a98f3
Python
2,371
69
import torch import torch.nn as nn import pytorch_lightning as pl from torch.nn import functional as F import sinabs.layers as sl # import sinabs.exodus.layers as sel class SNN(pl.LightningModule): def __init__(self, batch_size, lr=1e-3): super().__init__() self.batch_size = batch_size sel...
a7707e37a261373f69bc4d5c18e37a3141c10f4e1f13c00a6802be43899f7fbc
Python
2,371
73
#!/bin/env python import argparse import pysam import sys from typing import List, Text, Optional def _parse_arguments(argv: List[Text]) -> argparse.Namespace: # noinspection PyTypeChecker parser = argparse.ArgumentParser( description="Prepare call set for evaluation against PacBio variants, includin...
d330e063d88e7a0c3ce12e6132df5ea41210f6f38a2ea390c0d6808237a7585f
Python
2,372
72
from typing import Literal from scvi.module.base import PyroBaseModuleClass from ...models.base._pyro_mixin import AutoGuideMixinModule, init_to_value class RegressionBaseModule(PyroBaseModuleClass, AutoGuideMixinModule): def __init__( self, model, amortised: bool = False, encode...
eb68eedbae9c21c247da73c78ffb8e53abbf710a475af47769d5036a4f4e41dc
Python
2,372
80
# TODO: [V2] Deprecated doc code to delete. import os os.environ["RAY_TRAIN_V2_ENABLED"] = "0" import tempfile import horovod.torch as hvd import ray from ray import train from ray.train import Checkpoint, ScalingConfig import ray.train.torch # Need this to use `train.torch.get_device()` from ray.train.horovod impo...
b8dbbd83b332f83c220e103afa32bfcdc579350c477953dac23f4dffdd8d4ddb
Python
2,373
92
import pandas as pd from lisa import FromGenes import requests import fire import argparse import numpy as np URL = 'http://lisa.cistrome.org/gallery/{id}_{dir}.txt' TEST = [ ('189', ['NFE2']), ('172',['PPARG']), ('187',['YY1']), ('220',['RUNX3']), ('135', ['HNF4A']), ('154',['MYOD1']), (...
2885edd9becdaf23424d15a7608843673585dd6c106ba3549496e99f6dd3ab74
Python
2,374
74
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """Noise model info in rpu_config to neural network model""" # pylint: disable=no-name-in-module,import-error from aihwkit.cloud.converter.definitions.i_input_f...
f07d0a08da3d429ade3d51b370969dc4c16a0da224bd1371baf3358fd5b19569
Python
2,374
83
from . import unittest import mock from ngs_mapper import runsample class TestPBSJob(unittest.TestCase): def setUp(self): self.runsample_args = self.rsa = [ 'readsdir', 'foo.fasta', 'prefix', '-trim_qual', '25', '-head_crop', '0', '-minth', '0', '--CN', 'bar', '-od', 'o...
468942bf0f5b8e244fc90c2b29144e3aa0ef7962add0c9811cabe0e46fc7b961
Python
2,375
98
""" scLLM: Single-cell Language Models ================================== A unified interface for single-cell language models including scGPT, scFoundation and others. Main classes: - SCLLMManager: High-level interface for model operations (RECOMMENDED) - ModelFactory: Factory for creating different model types - ScG...
78cc7815c65a2f8d7568fbaae5c529dd461a36cfd632841723d69cd500c5b7e1
Python
2,376
78
# -*- coding: utf-8 -*- """ The module is used for computing the composition of amino acids, dipetide and 3-mers (tri-peptide) for a given protein sequence. References ---------- .. [1] Reczko, M. and Bohr, H. (1994) The DEF data base of sequence based protein fold class predictions. Nucleic Acids Res, 22, ...
8616c5a9cc9b9470431b78447e95ead141503a33f79b1f888ec0cd88f53210c4
Python
2,376
56
# helper utils for reading in data import numpy as np import os # reads in a list def read_list(path, trans=None): collection = [] with open(path) as infile: for line in infile: newline = line.strip().split() if len(newline) == 1: newline = newline[0] ...
c806d36fbc876238248fd98b9ac039cb4edc84f958e9c34d96b3bd68e1e434f6
Python
2,376
65
import os import cv2 import numpy as np from utils.tool import get_type_max, read_img, save_img from omegaconf import OmegaConf import torch import json from einops import rearrange, repeat from utils.ssim import ssim as ssim_calc from utils.ssim import ms_ssim as ms_ssim_calc import copy def cal_iou_acc_pre(data_gt:n...
d6435b0798f40658f0e453ea0acde6847ab1852ad9d2e2a53c763238afc25c53
Python
2,376
58
from transformers import PreTrainedTokenizer class scMulanTokenizer(PreTrainedTokenizer): def encode(self, text, *args, **kwargs): # scMulan calls ``tokenizer.encode(list_of_token_strings)`` # treating the list as a pre-tokenized sequence — i.e. one id # per element. transformers <= 4.40 s...
0ce19cbeb3632e6c6b741701fd42099048a95ead96c638244e60a6bc945a1de8
Python
2,378
67
import numpy as np import pytest import torch from pfrl.functions.lower_triangular_matrix import lower_triangular_matrix @pytest.mark.parametrize("n", [1, 2, 3, 4, 5]) class TestLowerTriangularMatrix: @pytest.fixture(autouse=True) def setUp(self, n): self.n = n self.batch_size = 5 sel...
8b4ddf2e287d4bfefa3a0cdc2e48ce25e6545812f9da309d7d21be99241bbc3a
Python
2,378
81
import os import numpy as np import torch from tqdm import trange from solver import Solver from KS_equation import dynamics import matplotlib import matplotlib.pyplot as plt matplotlib.use('Agg') torch.set_default_tensor_type(torch.cuda.FloatTensor if torch.cuda.is_ava...
2d8109ca301aa5d52098823f8b35a4b521e9107c364eb6314ded26c7483543e6
Python
2,380
75
from __future__ import annotations import dataclasses import torch @dataclasses.dataclass class GraphAttentionData: """ Custom dataclass for storing graph data for Graph Attention Networks TODO: complete this """ # attributes atomic_numbers: torch.Tensor charge: torch.Tensor spin: t...
84da7c7064e89f26894de0228812cdcc1dac8b67d4df949fef30250d4c120bd6
Python
2,380
53
import pandas as pd import zipfile import os import logging from logging import handlers def HLA_Label_Length_Position_AA_peptides(data, hla, label, length, posi, aa): posi -= 1 peptides = [item for item in data[data.HLA == hla][data.label == label][data.length == length].peptide if item[...
0b12e5780dbfcf608fc584a9df90b1fc0991551596dff9c572107fb22ede390d
Python
2,381
75
# coding: utf-8 import os import sys import pytest import torch import ray import ray.cluster_utils from ray.dag import InputNode, MultiOutputNode from ray.tests.conftest import * # noqa if sys.platform != "linux" and sys.platform != "darwin": pytest.skip("Skipping, requires Linux or Mac.", allow_module_level=T...
2c117ef9d1070dd01439b506a79f24d6e9cab38ba0d98b4bb8bb8be01e463f18
Python
2,381
76
'''study mean/max pairwise corr as the number of random vector grows''' import numpy as np import seaborn as sns import matplotlib.pyplot as plt from utils.stats import compute_stats from scipy.stats import pearsonr sns.set(style='white', palette='colorblind', context='talk') n_sims = 30 more = 0 f, axes = plt.subpl...
cdba2abc868c89a9f4966a4fc2c8139e36f22ed6e8e8e60eadf19a9132763285
Python
2,382
78
import os import pdb import numpy as np from tqdm import tqdm import torch import matplotlib.pyplot as plt import yaml from latent_time_stepping.AE_models.VAE_encoder import VAEEncoder from latent_time_stepping.AE_models.autoencoder import Autoencoder from latent_time_stepping.AE_models.encoder_decoder import Decoder,...
fd05e000ccb00829fad1625a5ddfd0a838d89bfd055d8e78f36025bd470e8da6
Python
2,384
95
import os import sys import time import errno import time import timeit import warnings import numpy as np import numba from numba import jit warnings.simplefilter("ignore") @jit(nopython=False) def VEP2Dmodel(params, constants, init_conditions, SC, dt, ts): nt=ts.shape[0] nn=SC.shape[0] #parame...
51686991adb8c3409eb250a801b00dadf6e51b692070dd9d6cb06f32ed06d266
Python
2,385
58
#################################################################################################### # 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...
aa4e58abc218b813ef99a04d41b00298f9b08fe10607d819ec469ceb52ab0b9a
Python
2,385
73
# 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, ...
c99499bf2a5d36bb18daf286c6e780299502a83edf29bb3e27958117a805f02a
Python
2,385
63
"""Facenet prewhitening uses the original model's adjusted standard deviation.""" from types import SimpleNamespace import numpy as np import pytest from deepface import DeepFace from deepface.modules import modeling, preprocessing @pytest.mark.parametrize("dtype", [np.float32, np.float64]) @pytest.mark.parametriz...
d4e4e4bd626acf998c097161577f54bfe56d583616104779f2667838964dc196
Python
2,385
95
import os import sys import time import errno import time import timeit import warnings import numpy as np import numba from numba import jit warnings.simplefilter("ignore") @jit(nopython=False) def VEP2Dmodel(params, constants, init_conditions, SC, dt, ts): nt=ts.shape[0] nn=SC.shape[0] #parame...
939ef31646df9722fd2f6b66ab04719d7ee237854b93a9ca93243512248d1aa1
Python
2,386
97
import os import sys import time import errno import time import timeit import warnings import numpy as np import numba from numba import jit warnings.simplefilter("ignore") @jit(nopython=False) def VEP2Dmodel(params, constants, init_conditions, SC, dt, ts): nt=ts.shape[0] nn=SC.shape[0] #parame...
dd19bd5701568a824bb3603882dc22a98ac218f9a9e312b941db4bbe798166fa
Python
2,386
74
# built-in dependencies from typing import List, Any import warnings # 3rd party dependencies from numpy.typing import NDArray # project dependencies from deepface.models.Detector import Detector, FacialAreaRegion # mtcnn is an optional dependency requiring keras, it is imported within __init__ on # purpose - deepfa...
05c34a6ed02062fffd5a61564b2ff228b1fcd09b78c5b61c211790231fbecbb7
Python
2,387
97
import zipfile import pytest from stl import mesh _STL_FILE = b""" solid test.stl facet normal -0.014565 0.073223 -0.002897 outer loop vertex 0.399344 0.461940 1.044090 vertex 0.500000 0.500000 1.500000 vertex 0.576120 0.500000 1.117320 endloop endfacet endsolid test.stl """ def test_single_stl(tmp...
1e2cefc3cce29d9e9557d383e82bba8f1acbbe99d63416b033c12147f84fd6f4
Python
2,387
97
import os import sys import time import errno import time import timeit import warnings import numpy as np import numba from numba import jit warnings.simplefilter("ignore") @jit(nopython=False) def VEP2Dmodel(params, constants, init_conditions, SC, dt, ts): nt=ts.shape[0] nn=SC.shape[0] #parame...
e2bdb125079183db676d2b2c626b19413911cb63fd2efd8919a653204af0f357
Python
2,387
65
import numpy as np import matplotlib.pyplot as plt import time import torch from pyJoules.energy_meter import EnergyContext from pyJoules.device.rapl_device import RaplPackageDomain, RaplDramDomain from pyJoules.device.nvidia_device import NvidiaGPUDomain from pyJoules.handler.pandas_handler import PandasHandler de...
fde569be716ad07621b5275e7e405114cf37c800f9bec09983654c440eb1cb57
Python
2,387
48
#################################################################################################### # 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...
3f112732f9f0ddc4458262e1eba99e3a4e2904ac60e5ded6c1a365037ad3ff0b
Python
2,388
91
from itertools import product import pytest import torch import torch.nn as nn def test_init_defaults(): from sinabs.backend.dynapcnn.dvs_layer import DVSLayer dvs_layer = DVSLayer(input_shape=(128, 128)) print(dvs_layer.get_config_dict()) data = torch.rand((1, 2, 128, 128)) out = dvs_layer(d...
bced901cf4597533f002961cdf85c08fe9d80c9c8f203acf479864f0d6664d50
Python
2,389
99
import logging import pandas as pd from datetime import date, datetime from agent.data.entities.config import ROOT_LOGGER_ID from agent.data.sql.sql_mgmt import get_connection from agent.data.entities.item import insert_item, item_tuple_to_dict logging.basicConfig(format='%(levelname)s : %(message)s', level=logging...
a7dac532d156de068c7e10bc74c084d35c86ed1fed1a504fb0f51e6815316afc
Python
2,390
88
from typing import Any import pytest from ray.dag.py_obj_scanner import _instances, _PyObjScanner class Source: pass def test_simple_replace(): scanner = _PyObjScanner(source_type=Source) my_objs = [Source(), [Source(), {"key": Source()}]] found = scanner.find_nodes(my_objs) assert len(found)...
c88146159bbcb9acb45f142eaa9db2b9e796c519de98af47d9a8b11792a91bd0
Python
2,390
67
import torch from networks.attention_gan import Generator, Discriminator from modules.module_unet import GAN as UnetGan # Define the custom GAN class inheriting from UnetGan class GAN(UnetGan): def __init__(self, config): super().__init__(config) # Initialize the superclass with the given configuration ...
8c2a676ddc3ed0ced3fcab8f708f90db759f02a2c8e87950ebcf73aa03d0d5ef
Python
2,391
62
"""Automative patch flattening of all participants""" import subprocess import os import glob subs = ['sub-06'] for sub in subs: subFolder = f'/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti/derivatives/{sub}' anatFolder = f'{subFolder}/ses-01/anat/upsample' # Make output directory out...
b02229e54a9d9863380022409de7245f1fd83e9e7e7c300340291ce51053091a
Python
2,391
65
from skimage import color import numpy as np def overimpose_shade(img, mask, alpha=0.6, col=(1, 0, 0)): # Construct RGB version of grey-level image img_color = np.dstack((img, )*3) img_mask = (np.dstack((mask, )*3)*col).astype(img_color.dtype) # Convert the input image and color mask to Hue Saturatio...
45bd28dfeab7dc7dbd08e575855af17297a63ca846ecd7cbfd5867e4d77e1a01
Python
2,396
83
# flake8: noqa # __start_translation_model__ # File name: model.py from transformers import AutoModelForSeq2SeqLM, AutoTokenizer class Translator: def __init__(self): # Load model self.tokenizer = AutoTokenizer.from_pretrained("t5-small") self.model = AutoModelForSeq2SeqLM.from_pretrained...
0a2b67f09334076203713f068ecb5cb40fe24a18f37a53a9627e704109029bc1
Python
2,397
87
""" Test for issue 51: https://github.com/Data-Centric-AI-Community/data-profiling/issues/51 """ import numpy as np import pandas as pd from data_profiling import ProfileReport def test_issue51(get_data_file): # Categorical has empty ('') value file_name = get_data_file( "buggy1.pkl", "https:...
45dbb071b95a8740b52d2bd5035f2844faf5d137b3d9a6d63f8702ec6671dd27
Python
2,397
76
import numpy as np import matplotlib.pyplot as plt from lib5c.util.plotting import plotter try: from sklearn.metrics import auc sklearn_avail = True except ImportError: sklearn_avail = False auc = None @plotter def plot_roc(eval_results, labels, colors=None, **kwargs): """ Plots an ROC curv...
701c5d317c80efc4851ba4fc85ced791e9d262a7f012b630bb7947c1236e9357
Python
2,397
71
__author__ = "Simon Andermatt" __copyright__ = "Copyright (C) 2017 Simon Andermatt" import logging from copy import deepcopy import numpy as np import torch as th from mdgru.helper import argget, compile_arguments, generate_defaults_info class CRNNCell(th.nn.Module): """Base convolutional RNN method, implement...
8afbe6e4622264c9603bfe8bfe26e31fec046546f1cab23de40cc23b7e43237c
Python
2,397
90
# __starting_ray_start__ import ray import math import time import random ray.init() # __starting_ray_end__ # fmt: off # __defining_actor_start__ @ray.remote class ProgressActor: def __init__(self, total_num_samples: int): self.total_num_samples = total_num_samples self.num_samples_completed_per_...
e6ebe89629b166bef98aa111b4a3b80f188f6f6f83d708ebbc21cc00dcdfeb14
Python
2,398
83
""" 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 numpy as np import pytest from ase import Atoms from ase.constraints import FixAtoms from fairc...
a68f593241e796c068ae8085c314b68a43b55f603a4fa3fc593615c4e8008cfd
Python
2,399
67
from typing import List, Optional, Union, Any import torch from torch_geometric.nn.conv import MessagePassing from torch_geometric.utils import add_remaining_self_loops def sym_norm(edge_index:torch.Tensor, num_nodes:int, edge_weight:Optional[Union[Any,torch.Tensor]]=None, impro...
e302e6f018f9f7873048ed88c76e42a4b32f6ad456936b26ac0c5737ad1f0109
Python
2,399
73
# 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, ...
18d8ac12d3831dca919b3e944c69f8dfbe4c2a00534111493bdeaff1fc8b1c53
Python
2,400
33
from importlib import resources from typing import Dict, List predefined_signatures = dict( cell_cycle_human=resources.files("omicverse.datasets").joinpath("data_files/cell_cycle_human.gmt").__fspath__(), cell_cycle_mouse=resources.files("omicverse.datasets").joinpath("data_files/cell_cycle_mouse.gmt").__fspa...
2c26ad3f9a5e6272fcb2c54c842fe01e153021836be626de28dbc120f6423b9a
Python
2,400
63
r"""Real Doench-2016 CFD (Cutting Frequency Determination) off-target scoring. The CFD score (Doench *et al.* 2016, Nat Biotechnol) is the field-standard CRISPR off-target metric: a product of empirically-measured per-position, per-mismatch-type retention factors times a PAM factor. The scoring tables (``mismatch_scor...
4bdb38e00ced8883927638380cce2d9929bf84ded9410e70e27309b815e74911
Python
2,400
77
import numpy as np from math import sqrt import matplotlib.pyplot as plt def generate_online_performance_plot( performances=None, colors=None, xticks=[], xticks_labels=None, yticks=[], yticks_labels=None, m=20000, xlabel='', ylabel='', la...
2f753dccfcf281b2c22725c3e3fb0122475250e04c1a91ed52c3c9c6a8e02c1a
Python
2,401
60
#################################################################################################### # 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...
d6d7bddea358ad1776271c58d3fc970cceb26a562b8a188a4ca203e148b827be
Python
2,401
95
# built-in dependencies import os from unittest.mock import patch # 3rd party dependencies import pytest import psycopg from deepface import DeepFace from tqdm import tqdm import pandas as pd # project dependencies from deepface.commons.logger import Logger logger = Logger() connection_details_dict = { "host": ...
22f536d537ac6e72c0039b6e7fdaf335599e5623e354e1ae2eb46dcada519a5b
Python
2,402
69
import numpy as np import pytest from stl import mesh from .test_mesh_mass_subdivision import _boundary def moderate_appendage(): bounds = np.array( [[[0, 0, 0], [2, 2, 2]], [[-1000, 0, 0], [0, 1e-4, 1e-4]]], dtype=np.float32, ).astype(float) axes = [np.unique(bounds[:, :, i]) for i in r...
ee3cbd3a0d02816266b8808673690298a5cbe20b55ee715e1d0869fc8635b14b
Python
2,403
72
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ pandas version: 1.5.0 numpy version: 1.23.3 """ #%% Import Modules import pandas as pd import numpy as np import glob import json from pathlib import Path #%% Functions def calculate_deviation_angle(row): # Extract row and column direction cosines x_direction...
621f857e750215e9a5ab78e921494384e700e1eb3fe7451637fbd260a7520deb
Python
2,404
66
# -*- 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. #...
8c75c37a9b54758183c60a782ae97d8e99978dc9ae9e7dbf67485f4708dbc575
Python
2,404
70
# Modified from https://github.com/open-mmlab/mmediting/blob/main/mmedit/utils/logger.py # noqa: E501 # Modified from https://github.com/open-mmlab/mmdetection/blob/main/mmdet/utils/logger.py # noqa: E501 import inspect import logging from mmengine.logging import print_log from termcolor import colored def print_c...
3135539939cb60c883419a337e01fb5213026103e93ada34bc36b490c8c00e20
Python
2,406
74
from typing import Tuple def conv_output_size(image_length: int, kernel_length: int, stride: int) -> int: """Computes output dimension given input dimension, kernel size and stride, assumign no padding, *per* dimension given. :param image_length: int image size on one dimension :param kernel_length: ...
68a50fef0c7a4c640e8cd25102c7ca65c89036c1f853fc7fdf933d4da1a31703
Python
2,406
78
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html import setuptools # -- Project information ----------------------------------------------------- # https://www.sphinx...
180eac0ecc6a1313d9144ecdb6c8d466723887280af9d614bd77d774a971b176
Python
2,408
70
from typing import List from data_profiling.config import Settings from data_profiling.report.presentation.core import Container, FrequencyTable from data_profiling.report.presentation.core.renderable import Renderable from data_profiling.report.presentation.frequency_table_utils import freq_table from data_prof...