sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
8cf68d5f2ce9a240681f1484546fede06f4740f4d8f6cf2f68b865a81daedea9 | Python | 1,525 | 46 | import numpy as np
class StaticStateDownsampled():
"""
This is the state function used per default. For better performance, replace with your own state function
"""
def __init__(self,state_dim,bin_size=18):
"""
You can give the object parameters here.
state_dim (int) numb... |
caa6bbe3ed1b3d6e73c55e4af01d553102e4f621ae41f75ad86dc501e1177b62 | Python | 1,525 | 50 | from rna3db.cluster import InfernalGraph
import unittest
class TestInfernalGraph(unittest.TestCase):
def setUp(self):
self.graph = InfernalGraph()
def test_add_family(self):
self.graph.add_family("A")
self.assertTrue("A" in self.graph.graph)
self.assertEqual(self.graph.graph["... |
eb2a01547a7751481ce8ae88e321fe06f1308aef0248fca0e5d94b79f1101cf4 | Python | 1,525 | 57 | #!/usr/bin/env python3
"""
Example script demonstrating how to run the machine unlearning experiments.
"""
from models import *
from datar import *
from poison_unlearn import *
def run_mnist_example():
"""
Example of running MNIST experiments.
"""
print("Loading MNIST data...")
xs0, ys0, xs_val, ... |
adcb3c3786e64abf55a6a6ebdd9fbef75af376337dad30e94920ff5630059bbe | Python | 1,526 | 45 | from pydacefit.regr import regr_constant
from pydacefit.dace import DACE, regr_linear, regr_quadratic
from pydacefit.corr import corr_gauss, corr_cubic, corr_exp, corr_expg, corr_spline, corr_spherical
class GP:
""" Gaussian Process (Kriging) """
def __init__(self, regr='linear', corr='gauss'):
self.r... |
da8d1444b16b115ceca9bc69704e0835d4d1d12fce868dcd4febdc3b5e3067d8 | Python | 1,527 | 34 | from snakemake.script import snakemake
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
feature_name = snakemake.wildcards.feature
features_background_all = pd.read_pickle(snakemake.input.features_background_all)
ap_track_window_tracked = pd.re... |
edcf44ebdad400c949a9a8a1ed9cd727a0efb4b444b950d35f7efd58255c37c9 | Python | 1,527 | 46 | """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
import torch
### Methods for sample points on a sphere
def CalcSpherePoints(num_points: int, device: str = "cpu") -> torch.Ten... |
28ae1c877de664128d2e9cf5f1eaa22c455b4ca6a1ef1fd4b5619fc39b4ecf63 | Python | 1,528 | 37 | """
Related Figures:
"""
from feature_extracting import*
import numyp as np
import colorednoise as cn
if __name__=="__main__":
neural_signal=np.load('')
esa=ESA(neural_signal)
emand=eMAND(neural_signal)
mua=MUA(neural_signal)
sbp=SBP(neural_signal)
cc=np.corrcoef(emand,sbp)[0,1]
white_nois... |
7cd6432648c5b0de9e2723ffb62ea7dd07d9afe1b87e4ea78a1ab0c5a10c2682 | Python | 1,528 | 62 | # This code shows how to use JOINT to perform soft clustering and do DEG
import numpy as np
from joint import joint
from joint import deg
# generate mixture of zero inflated negative binomial random variables
np.random.seed(12345)
K = 2 # number of cell types
G = 2 # number of genes
L = 2 # number of negative binom... |
586c636a1c50930f869380e59cb5b4ac3b1e8b4766ba80ae66eb0d31ea70b72d | Python | 1,531 | 56 | import gc
import numpy as np
import pytest
from pandas import (
DataFrame,
to_datetime,
)
@pytest.fixture(autouse=True)
def mpl_cleanup():
# matplotlib/testing/decorators.py#L24
# 1) Resets units registry
# 2) Resets rc_context
# 3) Closes all figures
mpl = pytest.importorskip("matplotli... |
1cbb48aa12c45ac7d3c5a5fd788c9e015872ac7f843d775f24c40e32ac1fbf32 | Python | 1,534 | 47 | import torch
from config import AdaLiConfig
def heaviside(x: torch.Tensor):
return (x >= AdaLiConfig['Vth']).to(x)
def cal_firing_rate(s_seq: torch.Tensor):
# s_seq.shape = [T, N, *]
fr = s_seq.flatten(0).mean(0)
return fr
def percentage_in_range(tensor, lower_bound, upper_bound):
# 统... |
4a6600f18556878159c80c3baf717de5b7fc0a48a4af197c5ad3992c2ccb34d8 | Python | 1,535 | 42 | from pathlib import Path
import nablaDFT
import pytest
from hydra import compose, initialize_config_dir
@pytest.fixture(
params=[
"dimenetplusplus.yaml",
"equiformer_v2_oc20.yaml",
"escn-oc.yaml",
"gemnet-oc.yaml",
"graphormer3d-small.yaml",
]
)
def pyg_optim_config(re... |
818fbf8f63ab325adbe8a6ae4935df4f7f33d3cd253d82e65e7fa6f4500a24e4 | Python | 1,536 | 49 | import asap
# The below code is a complete script that sets up the training of a model using the ASAP library.
# It includes data paths, model parameters, training parameters, and the creation of training and validation datasets.
# The script then trains the model using the specified parameters.
def main():
# ... |
141a92f79506c953ac9bb926682acafdcaaf08b4a2cea9c41bcef9a174772638 | Python | 1,537 | 48 | #----------------------------------------------------------------
# load images for regression
# ImageFolder works well for classification, not for regression
#----------------------------------------------------------------
import torch.utils.data as data
from PIL import Image
import os
import os.path
def default_lo... |
4b8879a548c0d2e96e709efdc2414fef628d8e1e3166c6dbf54cb1e0033908a6 | Python | 1,538 | 40 | import tensorflow.keras as keras
class LossHistory(keras.callbacks.Callback):
"""
Callbacks to store train, validation loss at the the end of every batch and the end of every epoch.
You can also track the counts loss and profile loss seperatley using the callbacks provided.
"""
def __init__(se... |
e97a8a11eaee9abfcdced6b896394556b71f045c05f6fadd94e1fe168b816dcd | Python | 1,538 | 56 | """Tests for FOOOF core.utils."""
from fooof.core.utils import *
from py.test import raises
###################################################################################################
###################################################################################################
def test_group_three():
... |
8dd948fa0e900ff9207d921a6cb186347aa283fc251b78f2fe46d78eb56dc67e | Python | 1,540 | 26 | import numpy as np
import pandas as pd
def single_img_stats(pred, gt, print_results=False):
'''Takes in a single image's prediction and ground truth and returns the overall accuracy, precision, recall, IoU, and F1 score as a mean over all classes in the image.'''
df_list = []
for class_val in np.unique(gt)... |
35f538bdb5d50625791541baf4d41c88eeb54fe7453c1e8dd19774cc3f1de1e6 | Python | 1,541 | 53 | from numpy.distutils.fcompiler import FCompiler
compilers = ['NVHPCFCompiler']
class NVHPCFCompiler(FCompiler):
""" NVIDIA High Performance Computing (HPC) SDK Fortran Compiler
https://developer.nvidia.com/hpc-sdk
Since august 2020 the NVIDIA HPC SDK includes the compilers formerly known as The Po... |
b22ceafb6a0d5e71252ce7f21bc5b3f579b5a7fcfa2597fe2590762f87e898e6 | Python | 1,542 | 48 | """Utility functions for network analysis"""
# from dependencies
import numpy as np
def edge_list_to_sim_matrix(
edge_list: list[tuple[int, int, float, float, float, float, int]],
) -> tuple[np.ndarray, list[int]]:
"""Return a similarity matrix and id list from an edge list
This function returns an adja... |
08d7903e7a40b9d63bee79b33a438d4a6020465cc87f4e97f97f66bd160e0e6b | Python | 1,543 | 47 | from __future__ import annotations
import collections
from typing import TYPE_CHECKING, Any, Generic, Iterable, NamedTuple
from ..structs import CT, KT, RT, DirectedGraph
if TYPE_CHECKING:
from ..providers import AbstractProvider
from ..reporters import BaseReporter
from .criterion import Criterion
... |
a225b4483faad41f0bfbdca3f58a5bdf58b9c1a0c195699432320ef16960be24 | Python | 1,550 | 40 | import numpy as np
from sklearn.preprocessing import RobustScaler
from scipy import sparse
from sklearn.utils import check_array
from sklearn.utils.validation import FLOAT_DTYPES
from sklearn.preprocessing._data import _handle_zeros_in_scale
class RobustNanScaler(RobustScaler):
def _check_array(self, X, copy... |
9ea960164f8e71f81cd7c83e6f87e9ad8b2c7dca517a2caf81b58fcec344a052 | Python | 1,552 | 45 | from numpy._core._multiarray_umath import (
__cpu_features__, __cpu_baseline__, __cpu_dispatch__
)
from numpy._core import _umath_tests
from numpy.testing import assert_equal
def test_dispatcher():
"""
Testing the utilities of the CPU dispatcher
"""
targets = (
"SSE2", "SSE41", "AVX2",
... |
389f798536af11649b44fef46adbae4ef4db03d6fa56ebf697b5124443f01a7f | Python | 1,553 | 55 | import pytest
import cedalion.data
import cedalion.geometry.utils as geoutils
from cedalion.dataclasses.geometry import affine_transform_from_numpy
from cedalion.errors import CRSMismatchError
@pytest.fixture
def geo3d():
recordings = cedalion.data.get_snirf_test_data()
geo3d = recordings[0].geo3d
geo3d = ... |
15374ace2caef4735343a012083dd9a76fe2c42c81523a900c098b51b8e2bed8 | Python | 1,554 | 36 | import os
import torch
# Borrowed from e3nn @ 0.4.0:
# https://github.com/e3nn/e3nn/blob/0.4.0/e3nn/o3/_wigner.py#L10
# _Jd is a list of tensors of shape (2l+1, 2l+1)
_Jd = torch.load(os.path.join(os.path.dirname(__file__), "Jd.pt"))
# Borrowed from e3nn @ 0.4.0:
# https://github.com/e3nn/e3nn/blob/0.4.0... |
8dccb5035ee4618e38116fa9293b9ad52da682a6f701f53acf6a81737a8c16b6 | Python | 1,554 | 49 | # -*- coding: utf-8 -*-
# jvparidon@gmail.com
import time
import functools
import logging
logging.basicConfig(format='[{levelname}] {message}', style='{', level=logging.INFO)
def timer(func):
"""Decorator to add timing wrapper to other functions.
Use by prepending `@timer` to the target function definition.
... |
b7f3411b4d5e80be29bed4e859d5137af2e5c4278a5ab4bdcbaef772efa01361 | Python | 1,554 | 47 | # tests/test_cli.py
import io
import sys
import unittest
from contextlib import redirect_stderr, redirect_stdout
from unittest.mock import patch
from cli.run import main
class TestArgparseCLI(unittest.TestCase):
@patch("cli.build_cli.register_build.VllmBuildRunner.run", return_value=None)
@patch("cli.build_c... |
045ea2e995215f1e5a5ae55eb027cc58a3b76c7e7aae268b4fc40d93076d4198 | Python | 1,555 | 73 |
# import pandas as pd
# from tqdm import tqdm
# tqdm.pandas(ascii=True)
# total = 138857329
# data_path = './data/CID-SMILES'
# df = pd.read_csv(data_path, header=None, sep = '\t',index_col=0)
# df = df.drop_duplicates(1)
# df.index.name = 'cid'
# df = df.rename(columns={1:'smiles'})
# df = df.reset_index()
# prin... |
4de8ced4ac6fa0f113b0df9975e7c678f87027eb336a861a9cff404171e0635f | Python | 1,555 | 68 | import numpy as np
import pytest
import pandas as pd
from pandas.core.arrays.integer import (
Int8Dtype,
Int16Dtype,
Int32Dtype,
Int64Dtype,
UInt8Dtype,
UInt16Dtype,
UInt32Dtype,
UInt64Dtype,
)
@pytest.fixture(
params=[
Int8Dtype,
Int16Dtype,
Int32Dtype,
... |
961b70b2850f48e49d82749dc6faef4b8ae88a277ce9e5b34ab1a376b2a41fb8 | Python | 1,555 | 43 | import os
import subprocess
import sysconfig
import pytest
import numpy as np
from numpy.testing import IS_WASM
is_editable = not bool(np.__path__)
numpy_in_sitepackages = sysconfig.get_path('platlib') in np.__file__
# We only expect to have a `numpy-config` available if NumPy was installed via
# a build frontend (... |
b78466f397979bbd538b4f8f3b580040c44add5ecd377c75b5c6dcc34fb11922 | Python | 1,555 | 40 | """setuptools.errors
Provides exceptions used by setuptools modules.
"""
from distutils import errors as _distutils_errors
from distutils.errors import DistutilsError
class RemovedCommandError(DistutilsError, RuntimeError):
"""Error used for commands that have been removed in setuptools.
Since ``setuptools... |
3de5087831daf6b1a082b6846d5251b4b8b619c9cd71792b5dbd28b65b61382e | Python | 1,556 | 41 | import pytest
from pandas import Index
import pandas._testing as tm
def test_add_prefix_suffix(string_series):
with_prefix = string_series.add_prefix("foo#")
expected = Index([f"foo#{c}" for c in string_series.index])
tm.assert_index_equal(with_prefix.index, expected)
with_suffix = string_series.add... |
a969ff5207d14ce01df3dbb5fa080f580d8fd0b3126432dd5130c79f95607b47 | Python | 1,556 | 69 | import numpy as np
def BenjaminiHochberg(p : np.ndarray):
"""Apply Benjamini-Hochberg FDR correction for multiple comparisons.
See http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3530395/
Args:
p: Array of uncorrected p-values, arbitrary shape.
Returns:
Array of FDR-corrected q-values, ... |
d93a3f7849f6c6b50dd624824fe4a24966089526bc0dde89d116437a1437bfff | Python | 1,557 | 46 | import abc
from typing import Type
import numpy as np
import torch
class InputsProcessor(metaclass=abc.ABCMeta):
@abc.abstractmethod
def __call__(self, frames: np.ndarray, behavior: np.ndarray, pupil_center: np.ndarray) -> torch.Tensor:
pass
class StackInputsProcessor(InputsProcessor):
def __i... |
ebde73b47bd4973047fcec7da6fadbe22b579428564dd1d840c298378ef81eaa | Python | 1,557 | 56 | import dataclasses
from dataclasses import dataclass
from typing import List
import numpy as np
import torch
from ultralytics import YOLO
@dataclass(slots=True)
class Point:
conf: float
x: float
y: float
@dataclass(slots=True)
class PoseInstance:
conf: float
box: np.ndarray
pose: List[Point... |
a824361e96f25fd1d960a0ec48566ab772976eb0ea3865fdabb3550537bbbd82 | Python | 1,558 | 55 | import sys, os
import numpy as np
import matplotlib.pyplot as plt
import yaml
if __name__ == '__main__':
sim_name1 = sys.argv[1]
mesh_name1 = sys.argv[2]
sim_name2 = sys.argv[3]
mesh_name2 = sys.argv[4]
variables = ["d", "pP_i","pP_e","phi_i", "phi_e"]
name1 = f"{mesh_name1}_{sim_name1}"
n... |
4cc227c98a546be28bec2ce627d22d43fc6d88478eb6708248fb1b5d1458a4c9 | Python | 1,559 | 37 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
# for test files, silence irrelevant and noisy pylint warnings
# pylint: disable=no-self-use,protected-access,missing-docstring
import os
from unittest import TestCase
f... |
9a368102714ac2b23a0110103f40c4d0a493793356f67ac2d698ff54d569ebfe | Python | 1,559 | 51 | """Module containing code to handle logging"""
# from python
from contextlib import AbstractContextManager
import logging
import sys
def init_logger(run) -> None: # pragma: no cover
"""Initialize the logger"""
# logger
# this tells the logger what the messages should look like
# asctime = YYYY-MM-D... |
ac0925ae88f9831ac65c08e2ac15bb0361fb23843968f5070f745a91b9128ec6 | Python | 1,559 | 48 | import numpy as np
from shap.datasets import adult
from shap.maskers import Independent, Partition
from shap.utils import MaskedModel
class TabularMaskerSuite:
# Adapted from tests/maskers/test_tabular.py and monitoring/permutation_explainer.py
max_samples = 100
def setup(self):
X, _ = adult()
... |
628703408a2f5e7ae95c4cf3dc073ede5d8f7466837f6fec17c50f70b545d59f | Python | 1,561 | 51 | # Arithmetic tests for TimedeltaIndex are generally about the result's `freq` attribute.
# Other cases can be shared in tests.arithmetic.test_timedelta64
import numpy as np
from pandas import (
NaT,
Timedelta,
timedelta_range,
)
import pandas._testing as tm
class TestTimedeltaIndexArithmetic:
def tes... |
0c32a843960739608b1167b27d1eb36a7a25b4ee666a5ffa9025d849a933ae8f | Python | 1,563 | 39 | from __future__ import annotations
from pathlib import Path
import pandas as pd
from src.plotting import plot_fig10
# Replace with your final numerical summary if needed.
TABLE = [
["IGSA-MLPNN", 0.0531, 0.00309, 0.0556, 0.9652, 0.0117, 5.6, 0.0514, 0.0548, 0.9608, 0.9696],
["GSA-MLPNN", 0.0592, 0.00383, 0... |
fc58ff4468ad541e4ec72bb4f6a0e2c275b4b86f527243a46244d214ff2b9846 | Python | 1,563 | 45 | '''
Created on 2015.5.27
@author: Liang Qian
'''
from data import globaldata as Global
from .layer import Layer
from .synapse import Synapse
class Cortex():
'''
This class defines properties and funtions of cortex
'''
def __init__(self,neuronnumscale):
'''
Constructor
'''
... |
59375eed140bbf21490da9021f31a58c5465c606e3a6319c58e2b996a6b6c8a8 | Python | 1,564 | 53 | import glob
import os
import hydra
import lightning as L
import torch_geometric.loader as geom_loader
from models import AMRNodeDualGNN
from utils import create_graph_dataset
@hydra.main(version_base=None, config_path="../conf", config_name="config")
def main(cfg):
L.seed_everything(cfg.trainer.seed * cfg.data.... |
945b7a616116def2cdecbf1cf8ec44f6077b32d4e666d46fe8dbf02b575bce93 | Python | 1,565 | 69 | from abc import abstractmethod
from typing import Any, List, Optional
class IMCFileTreeItem:
imc_file_tree_is_checkable = False
def __init__(self) -> None:
self._deleted = False
@property
@abstractmethod
def _imc_file_tree_data(self) -> List[Any]:
pass
@property
@abstrac... |
b958e035f49a006c86d4c9c8ef741f5411cb1da48022e27fff664b6ef9ad5e2f | Python | 1,566 | 57 | """ Aggregates dendritic events within segments
Author: Drew B. Headley
"""
def seg_dendevt(dspk_df, agg_colname="Elec_distanceQ"):
"""
Takes a dendritic events dataframe and aggregates event times by segment.
Parameters
----------
dspk_df : dataframe
dendritic spike events and their cor... |
7d46393041b0d98c42b05c9895d92450adedab64455f4f4bdaccfb7d694d7598 | Python | 1,567 | 52 | import os
from pathlib import Path
from urllib.request import urlretrieve
import numpy as np
import pandas as pd
def load(filename, backup_url=None, header="infer", index_col="infer", **kwargs):
"""Load a csv, txt, tsv or npy file."""
numpy_ext = {"npy", "npz"}
pandas_ext = {"csv", "txt", "tsv"}
if ... |
9007f6bdfe4c642d42a05c2dc9469d0ccb9a49f285990c73ba9667535d825cc3 | Python | 1,568 | 48 | import util
from os import path
import yass
from yass import preprocess
from yass import detect
from util import ReferenceTesting
def test_threshold_detector_returns_expected_results(path_to_config_threshold,
path_to_output_reference,
... |
735be4058201f20ee47c8e83b743a7c84d8613a23c011eab8fe1655427a2e6ca | Python | 1,570 | 51 | # Copyright (C) 2020 Bernd Feige
# This file is part of avg_q and released under the GPL v3 (see avg_q/COPYING).
"""
Basic reading of sleep stages from a CSV file.
"""
__author__ = "Dr. Bernd Feige <Bernd.Feige@gmx.net>"
from . import slfile as parent_slfile
stages={
'W': 0,
'?': 0,
'N1': 1,
'N2': 2,
'N3': 3,
... |
8459f7cecee99777954de220f35308806f7eca0b2d20ec5670b006db2e310e8b | Python | 1,576 | 51 | import time
import logging
from util.trace import Trace
logger = logging.getLogger("grimace_box."+__name__)
class RecordingContext:
@Trace.trace(logger)
def __init__(self, recording_duration: float = None):
super(RecordingContext, self).__init__()
self.recording_duration = recording_durati... |
a3014bd5fcacdcb3d35a9025b234be2335b8b12bbdf27729d819ec21eb4b4ab0 | Python | 1,576 | 149 | import numpy as np
f8 = np.float64(1)
i8 = np.int64(1)
u8 = np.uint64(1)
f4 = np.float32(1)
i4 = np.int32(1)
u4 = np.uint32(1)
td = np.timedelta64(1, "D")
b_ = np.bool(1)
b = bool(1)
f = float(1)
i = int(1)
AR = np.array([1], dtype=np.bool)
AR.setflags(write=False)
AR2 = np.array([1], dtype=np.timedelta64)
AR2.se... |
e92cb69f413e047d5a130b2e06a8c9e728fb8983d6343bfd3e463507d80d3df6 | Python | 1,576 | 50 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
"""Configuration handling for antiSMASH
"""
import configparser
import os
from argparse import Namespace
from antismash.common import path
_DEFAULT_NAME = 'default.cfg... |
99f4b74538fdb984fa2bd224a7c4639ac10f21602d513ccc857f6c1a313217a2 | Python | 1,577 | 51 | from numpy.distutils.ccompiler import simple_version_match
from numpy.distutils.fcompiler import FCompiler
compilers = ['SunFCompiler']
class SunFCompiler(FCompiler):
compiler_type = 'sun'
description = 'Sun or Forte Fortran 95 Compiler'
# ex:
# f90: Sun WorkShop 6 update 2 Fortran 95 6.2 Patch 11169... |
db36cbba7364c7530a08aba451e27866899dce2a68e139e714464458c9216e53 | Python | 1,577 | 54 | """
Adapter to represent stfio recordings as neo objects
Based on exampleio.py and axonio.py from neo.io
08 Feb 2014, C. Schmidt-Hieber, University College London
"""
# needed for python 3 compatibility
from __future__ import absolute_import
import sys
import numpy as np
import stfio
def neo2stfio(neo_obj):
... |
0db1b970534c492e64a854fff31aa43f9220f75b09f176b9a2ffb84dbda1289a | Python | 1,578 | 57 | import os
import nilearn as nil
import nilearn.datasets
import nilearn.image
from glob import glob
import pandas
import torch
from tqdm import tqdm
from .prep_atlas import prep_atlas
from nilearn.input_data import NiftiLabelsMasker
datadir = "./Dataset/Data"
def prep_abide(atlas):
bulkDataDir = "{}/Bulk/ABID... |
d92d8007adaad6d16097d560b452b562b557e8094c2cdb4b246f773bf62d943b | Python | 1,578 | 41 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
""" Classes representing complex qualifiers for features.
"""
from typing import Dict, List
class GOQualifier:
"""A qualifier for tracking Gene Ontology terms for a... |
1be8f3cf01ab2f685c6a787c0e9c48820c4efee040f3f2a55fe3c28942936ffb | Python | 1,580 | 49 | # Copyright 2024 RADar-AZDelta
# SPDX-License-Identifier: gpl3+
from typing import Any, cast
import google.cloud.bigquery as bq
import polars as pl
from ..data_quality_dashboard import DataQualityDashboard
from .etl_base import BigQueryEtlBase
class BigQueryDataQualityDashboard(DataQualityDashboard, BigQueryEtlBas... |
5a1543e8e24a3501c5bbe1861b24102f72d4bfe5200c3e523947bf5e5236bef7 | Python | 1,582 | 41 | import pandas as pd
import numpy as np
import os, sys, shutil, importlib, glob
from tqdm.notebook import tqdm
import celloracle as co
from celloracle import motif_analysis as ma
from genomepy import Genome
import scanpy as sc
from anndata import AnnData
from scipy.io import mmread
from scipy.sparse import csr_matrix
im... |
fbeebc6e13830ee63762abd1cc88f0070abb48b4d721dbc498a6ab697c4b6f6d | Python | 1,585 | 70 | import sys
sys.path.append('/Users/midani/OneDrive/proj/leap/manuscript')
import pandas as pd
import repo_code.lib_excel as lib_excel
set_screen_size = lib_excel.set_workbook_to_screen_size
dict_dfs = {}
## SPECIES INPUT
order_cols = [
'Variable',
'Subcategory',
'Overall',
'High',
'Typical',
... |
7e7860f2b583d115db48e764d3ed2f37b1cacd01534df0dad1d8118aeacb0041 | Python | 1,586 | 48 | import numpy as np
import yaml
from pathlib import Path
import matplotlib.pyplot as plt
from skimage.io import imsave
from skimage.util import img_as_ubyte
import nrrd
from skimage.measure import regionprops
from CrystalTracer3D.io import CrystalReader
from CrystalTracer3D.segment import segment_filled_crystal
from Cr... |
1b6475165f067af3be0745c43036f93c2d84dd584fabd66646e48891f0971bc2 | Python | 1,587 | 43 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
# Create output directory
os.makedirs('paper_graphs/Control_Deletion_Plots', exist_ok=True)
# Read the data
deletion_distances = pd.read_csv('CT2_log/euclidean/high_variation_genes/deletion_distance.csv')
control_distances = pd.read_csv(... |
40d5049f1cba18db92396bd446936cda59273ed8b0ae6ec773dfe754fad2ac9e | Python | 1,587 | 55 | """
Convert a TensorCircuit U(1) circuit to TenCirPauli execution.
This is a short integration preview for fixed-particle-number circuits. For
the complete 60-qubit comparison and benchmark study, see:
https://github.com/tensorcircuit/TenCirPauli/tree/main/examples/research/u1_vqe_60q
"""
from __future__ import annot... |
88432d67a8024125feaa3bec0ada4a1d48edc2bf81a4f0b681347d7b66136c41 | Python | 1,587 | 57 | """
Analog circuit simulation for Rydberg array
"""
import numpy as np
import tensorcircuit as tc
K = tc.set_backend("jax")
tc.set_dtype("complex128")
# Define simulation parameters
# a compatible set of units: mus, mum, MHz
nqubits = 12
omega = 2.0 * np.pi
delta = 0.0
c6 = 8e8
evolution_time = 2.0
# Define the 1D ... |
a4f1e39872aae3d64e75db5269bc6d7261699ea56fd7f386430a8991256b9894 | Python | 1,587 | 55 | import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
from scipy.ndimage import gaussian_filter
from main_functions import mark_voisins#, fast_multi_periodogram_window_3d, fast_multi_periodogram_prewindow_3d
sns.set_theme()
group_name = ["Hemisphere 1", "Hemisphere 2"]
if... |
06ff87f69eed7b9fb0ccd837e5f90575f71b9052156fd19c6e2a717ca967b7b1 | Python | 1,590 | 53 | """Test functions for FOOOF analysis."""
import numpy as np
from fooof.analysis import *
###################################################################################################
###################################################################################################
def test_get_band_peak_grou... |
628791784494871ef882ba9bd264926fd960861cac5a6147621b1b3154235cef | Python | 1,591 | 54 | from typing import Optional, TYPE_CHECKING
from .segment import Segment
from .style import StyleType
from ._loop import loop_last
if TYPE_CHECKING:
from .console import (
Console,
ConsoleOptions,
RenderResult,
RenderableType,
Group,
)
class Screen:
"""A renderabl... |
d8fb0c81cf85354172d558dac9b63f1496ff8041e92ff0a63aabf134b7aa5a08 | Python | 1,591 | 38 | import json
import argparse
import os
import pandas as pd
def get_parsers():
parser = argparse.ArgumentParser()
parser.add_argument("-op", "--output_prefix", type=str, required=True, help="Path prefix to store the fold information (appended with .json)")
parser.add_argument("-c", "--chrom-sizes", type=str,... |
3a7e50c53ebb9b3d62a4fc151840d99e39b4dd763e48561774950feff49f1976 | Python | 1,592 | 55 | #!/usr/bin/env python3.7
"""Generate a plot of fiber coordinates overlaid with a plot of the sample.
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub repository: https://github... |
87c590c50479faf902881e917b59255cb36c09b5810b2f16115b79b1dd893d49 | Python | 1,592 | 48 | import torch
import numpy as np
class HEBatchGenerator(object):
def __init__(self, hyperedges, labels, batch_size, device):
self.batch_size = batch_size
self.hyperedges = hyperedges
self.labels = labels
self._cursor = 0
self.device = device
self.shuffle()
def __... |
43a1ec3aeb768aafa5fb4e97e30ca1cdb87fce172b2a32ab9718e1d6dba75130 | Python | 1,598 | 39 | import numpy as np
from scipy.stats import fisher_exact
import pandas as pd
# Load the data
candidates = pd.read_csv('CT2_log/euclidean/final_candidate/candidate_genes.csv')
pws_genes = pd.read_csv('consistency/pws_region_genes.csv')
overlap = pd.read_csv('CT2_log/euclidean/final_candidate/consistency/pws_region_overl... |
0c8e6244aa08839d6523ff85cac290cb26899f0addf02a8b8e4edbee2a85229d | Python | 1,599 | 51 | import pytest
from pandas import (
Interval,
Period,
Timestamp,
)
class TestIntervalConstructors:
@pytest.mark.parametrize(
"left, right",
[
("a", "z"),
(("a", "b"), ("c", "d")),
(list("AB"), list("ab")),
(Interval(0, 1), Interval(1, 2))... |
685fde83dba5e5df1b302c5f4924b141c7ecf8ea4975b4ad62a647a32d8ad511 | Python | 1,601 | 55 | import os
import string
import urllib.parse
import urllib.request
from .compat import WINDOWS
def path_to_url(path: str) -> str:
"""
Convert a path to a file: URL. The path will be made absolute and have
quoted path parts.
"""
path = os.path.normpath(os.path.abspath(path))
url = urllib.parse... |
b39b6952616e9b05741fd2524f3af2ac863827040cf29686b7b4a6ede370b766 | Python | 1,601 | 44 | from __future__ import annotations
import functools
import logging
from pip._vendor.packaging import specifiers, version
from pip._vendor.packaging.requirements import Requirement
logger = logging.getLogger(__name__)
@functools.lru_cache(maxsize=32)
def check_requires_python(
requires_python: str | None, versi... |
464e953d3593b058abed61e2223c82cf2b5f3b913a0241891d471b1c143e3b52 | Python | 1,602 | 44 | import warnings
from functools import wraps
from typing import Mapping
# Modified from https://github.com/scverse/scanpy/blob/master/scanpy/_utils/__init__.py
def deprecated_arg_names(arg_mapping: Mapping[str, str]):
"""Marks a functions keyword arguments as deprecated.
This decorator marks a functions keywo... |
93ad112d0f7135b20de53e8dcc3c14e3b0df8ec12fc282307df9f50e776d0465 | Python | 1,602 | 55 | from protgps.utils.registry import register_object
from pytorch_lightning.callbacks import StochasticWeightAveraging
from protgps.utils.classes import ProtGPS
@register_object("swa", "callback")
class SWA(StochasticWeightAveraging, ProtGPS):
def __init__(self, args) -> None:
if "." in args.swa_epoch:
... |
ac79cefee7f327a60c80d0ae2378d015f0f46f36b80466a4418fa6f5cd0a17b1 | Python | 1,602 | 60 | import numpy as np
import pandas as pd
from pycisTopic.iterative_peak_calling import get_consensus_peaks
from pycisTopic.pseudobulk_peak_calling import peak_calling
import scanpy as sc
import pickle
import os
# Load in the locations of the bed files, per cell type
bed_paths = {}
with open(snakemake.input.bed_paths) a... |
08877728a9464e460edfafa31b6c040494f8b70e73c8de2eb3d7fe024f97da33 | Python | 1,603 | 60 | # Tests for DSSP secondary structure code
import pathlib
import shutil
import subprocess
def test_stride_ok(tmp_path):
if pathlib.Path("./stride").exists():
stride = pathlib.Path("./stride").resolve()
# or if there is one in the $PATH use that one
elif shutil.which('stride') is not None:
... |
6ecc06a2c0880dbff005f746685a87a298316e627aae05576255612435992887 | Python | 1,604 | 53 | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import time
import platform
import tempfile
from gunicorn import util
PLATFORM = platform.system()
IS_CYGWIN = PLATFORM.startswith('CYGWIN')
class WorkerTmp:
def __init__(self, cfg):
old_... |
caab4fca69f19286b5c830bfdd40666d93967c0a97286b0fb4f4dd17933aa20d | Python | 1,604 | 46 | # coding: utf-8
import torch
class ExponentialMovingAverage:
def __init__(self, model, decay=0.999, start_epoch=10):
# save arguments
self.model = model
self.decay = decay
self.start_epoch = start_epoch
# register exponential moving averages of parameters
self.ema... |
0fecfc41806f2c5560fced5f46f5af04b6e1b7d93809c1b0610e338cccbaf2dc | Python | 1,605 | 57 | import torch
import torch.nn as nn
from .layers.unmap_predictor import UnmapPredictor
class VanillaCNN(nn.Module):
def __init__(self, window_size=2048, bin_size=4, nr_tracks=1, use_map=False):
super().__init__()
assert window_size % bin_size == 0
nr_bins = window_size // bin_size
se... |
cd4bcf3c226ba7a74e17437818055b39c97aa3ee2e5ca4ab1a24e492be6f512e | Python | 1,605 | 57 | from .ssl_ import create_urllib3_context, resolve_cert_reqs, resolve_ssl_version
def connection_requires_http_tunnel(
proxy_url=None, proxy_config=None, destination_scheme=None
):
"""
Returns True if the connection requires an HTTP CONNECT through the proxy.
:param URL proxy_url:
URL of the p... |
13b2277ebce875ea5c20244fff3172835d4232cfb64a636bc456377fc6e1aa30 | Python | 1,608 | 54 | from io import StringIO
import numpy as np
import pytest
from pandas import (
DataFrame,
concat,
read_csv,
)
import pandas._testing as tm
class TestInvalidConcat:
@pytest.mark.parametrize("obj", [1, {}, [1, 2], (1, 2)])
def test_concat_invalid(self, obj):
# trying to concat a ndframe wit... |
bba24b61acc82c8765b5b7b5b9913788102a13f8b15f0c74a2ac12e93f8ca678 | Python | 1,608 | 45 | import numpy as np
from pandas import (
Index,
Timestamp,
date_range,
)
import pandas._testing as tm
class TestDateTimeIndexToJulianDate:
def test_1700(self):
dr = date_range(start=Timestamp("1710-10-01"), periods=5, freq="D")
r1 = Index([x.to_julian_date() for x in dr])
r2 = ... |
e7c8bf1578821e1a9aa7da7ed521e1f042fc86b6089735a6597f3e97e077cd3e | Python | 1,608 | 43 | import os
from argparse import ArgumentParser
from argparse import ArgumentDefaultsHelpFormatter
import pandas as pd
import joblib
from ..utils.norm_utils import annotate_kmer_information, create_kmer_mapping_df, \
create_norm_dict
def argparser():
parser = ArgumentParser(
formatter_class=Argument... |
244a5c47be94b0dd07af4eca682cefbb246781e778eb8686b9d963a92ee820fe | Python | 1,609 | 46 | import random
from scipy.spatial import KDTree
class Individual(object):
def __init__(self):
self.rank = None
self.crowding_distance = None
self.domination_count = None
self.dominated_solutions = None
self.features = None
self.objectives = None
def... |
acc0bcf88c813a2b9955f02892557f2a70fda95781fe1155bdbe5d4adc5f934f | Python | 1,609 | 42 | import shutil
import subprocess
import sys
import pytest
from numpy.distutils import mingw32ccompiler
@pytest.mark.skipif(sys.platform != 'win32', reason='win32 only test')
def test_build_import():
'''Test the mingw32ccompiler.build_import_library, which builds a
`python.a` from the MSVC `python.lib`
'''... |
29cda5996870fc6d892aad68a8fdcbe8a9a0a9b677dd00afd5efe65769c9b437 | Python | 1,610 | 55 | import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join("..", "..")))
# 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
# -- Project information --------... |
8e6775da0b22161545c7df6ae09f77260afb93b2079157251c1535c48b8e403d | Python | 1,610 | 62 | """
The main script. Replaces PyDP4.py, orchestrates the high-level workflow.
Molecules is the container class to contain all the data. MM and DFT methods no longer modify it directly to improve maintainability.
"""
import logging
from dp5.run.data_structures import Molecules
from dp5.nmr_processing import NMRData
... |
3c529a8614a639c472eb1f4529f7928473ad8a334ab29c6f6a8a52a1278ed3d3 | Python | 1,611 | 64 | """
VQE on 2D square lattice Heisenberg model with size n*m
"""
import tensorflow as tf
import tensorcircuit as tc
# import cotengra as ctg
# optr = ctg.ReusableHyperOptimizer(
# methods=["greedy", "kahypar"],
# parallel=True,
# minimize="flops",
# max_time=120,
# max_repeats=4096,
# progbar=... |
b8a6e5d851ecb38cdbf22fd1c32366b0cc7832a82f880811250bf81cbbc857ca | Python | 1,613 | 34 | import os
from src.asap.config import CONFIG
def get_checkpoint_for_fold(checkpoint_dir: str, exp: str, model_name: str, cell_line: str, fold: int):
all_files = os.listdir(checkpoint_dir)
should_contain = [exp, f'_{model_name}_', cell_line, f'fold{fold}']
matches = list(filter(lambda f: all(s in f for s ... |
d00115c3c94d3631e899daa0a50ed96026ae51bdb7407bf163734f0deeef210c | Python | 1,614 | 53 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
def test_astype():
# with missing values
arr = pd.array([True, False, None], dtype="boolean")
with pytest.raises(ValueError, match="cannot convert NA to integer"):
arr.astype("int64")
with pytest.raises(ValueE... |
e7a95a858a3488f41ce179dce42896f97da82f34615f36889bb538d2fbf7f869 | Python | 1,614 | 56 | from __future__ import annotations
from ..utils._typed_cache import typed_cache
from ..counts._count_words import count_words
from ..counts._count_difficult_words import count_difficult_words
from ._words_per_sentence import words_per_sentence
@typed_cache
def dale_chall_readability_score(text: str, lang: str) -> fl... |
2e3247fe0bdf34ed7028b64d06fe361715651807043f1ca652878063c60b0930 | Python | 1,615 | 57 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .grn import GRN1d
class ConvNeXtV2Block(nn.Module):
"""Adapted from ConvNeXt"""
def __init__(
self,
channels_in,
channels_out,
kernel_size,
groups=False,
inv_bottleneckscale=4,
grn=Tr... |
635d8fe9aa63412a4e1be9a1cd071e10876150be9f7fa83a4716d67c247e8d22 | Python | 1,615 | 37 | import pandas as pd
import numpy as np
from nilearn.maskers import NiftiLabelsMasker
from nilearn.regions import connected_regions
from nilearn.image import math_img
def extract_roi_values(group_stat_map, subject_maps, p_threshold=0.05, min_size=1500):
"""
Extracts subject-wise values from significant group-le... |
aff61f4566c3cb3b519954490cd74d5da44104f36c51c45f9779ad07f8fb7e0b | Python | 1,617 | 47 | # Tests for the '.AminoAcidHydropathyChange' defs for different hydropathy scales
import pandas
import numpy
import pytest
import sbmlcore
def test_amino_acid_hydropathy_KD_change_value():
a = {'mutation': ['A1D', 'E2K']}
df = pandas.DataFrame(a)
a = sbmlcore.AminoAcidHydropathyChangeKyteDoolittle()
... |
f7104f88c806383570119d830b784645429848736589ae330e4281d40f5d4d5c | Python | 1,617 | 51 |
import os
import sys
from pprint import pprint
import numpy as np
import scipy.io
# Usage: python "C:\\Code\\campy\\utils\\view_metadata.py" folder_name file_name numCams
# python "C:\\Code\\campy\\utils\\view_metadata.py" "D:\\20200401\\test\\videos" "metadata.npy" 6
folder_name = str(sys.argv[1])
file_name = str(s... |
b9fb52cd67387faef5197fd4fb4a1565d582f3526269e764acee4d91177999b2 | Python | 1,619 | 67 | import pandas as pd
import sys
import numpy as np
sys.path.append("../")
gambling = None # pd.read_csv("somePath/GAMBLING_run1_TAB.txt", sep='\t')
procedures = gambling["Procedure[Trial]"]
trialTypes = gambling["TrialType"]
trialOnsetTimes = gambling["ExperimenterWindow.OnsetTime"]
initialOnsets = gambling["SyncSlide... |
090eed401f903d4c43e999db4b64b31558e3bc20fbf9c8a095ec6475b6e7ef2f | Python | 1,620 | 93 | """
Arithmetic operations for PandasObjects
This is not a public API.
"""
from __future__ import annotations
from pandas.core.ops.array_ops import (
arithmetic_op,
comp_method_OBJECT_ARRAY,
comparison_op,
fill_binop,
get_array_op,
logical_op,
maybe_prepare_scalar_for_op,
)
from pandas.core... |
850334f71b08e618e5a5fb11fd1c368ee6d6084ec9cbf4a9d88dd3288c9b7ea2 | Python | 1,620 | 59 | from scvelo.core import (
clean_obs_names,
cleanup,
get_initial_size,
merge,
set_initial_size,
show_proportions,
)
from scvelo.plotting.simulation import compute_dynamics
from scvelo.plotting.utils import (
clip,
interpret_colorkey,
is_categorical,
rgb_custom_colormap,
)
from scv... |
95ab81877f576b4dc72f70e7b1ac3d27f9e891435330c416247f2137fb5a8628 | Python | 1,621 | 38 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 5 10:04:33 2018
MathLangage experiment adaptation for the IBC project.
@author: am985309, Juan Jesus Torre Tresols
"""
import os
import argparse
# IMPORTANT: adapt TOTAL_EXPE_DURATION in file mathlang.py if necessary
# Higher onset for last white cross : 56... |
0128da38ee27ab91b78458809f9c50d188d7377b60cc73d3ee777bca8029425d | Python | 1,622 | 46 | # Modified from OpenAI's diffusion repos
# GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py
# ADM: https://github.com/openai/guided-diffusion/blob/main/guided_diffusion
# IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_d... |
9e8aa1b05f044cf9d0a182833ba5d0c4ea02f5db655f69252e9295eec927f0df | Python | 1,622 | 55 | #!/usr/bin/env python3
"""Repair (delocate) macOS arm64 wheels so they are self-contained.
Usage: repair_wheel.py <input_dir> <output_dir>
Mirrors the .ci/wheel/linux/repair_wheel.py contract (read raw wheels from
input_dir, write finished wheels to output_dir) but uses delocate -- the macOS
analog of auditwheel/patc... |
4531f32994137bb4c6c20880e2ce39945451e68596d46ce4c5136197567eabbd | Python | 1,625 | 22 | from pathlib import Path
from cli import VesselCrystalCLI
if __name__ == '__main__':
vs = VesselCrystalCLI()
imgs = [
r"Y:\All Data\Lab Members\Jiaxi Lu\01_Raw Data\Tickertape\2025-26\Cancer_GEAR\InVivo\20250324_NudeMice26-33_LPSDoseDependency_Snap_LSM780\Nude32_CD31-IHC\10x_Scan\Z3\Nude32_Z3_2025_05_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.