sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
4737257890d159720a0534bea18ad6e93a028b4693bb03347d7276792aeccd31
Python
2,316
61
import numpy as np from sklearn.decomposition import PCA class DynamicStatePCA(): """ This is the state function used per default. For better performance, replace with your own state function """ def __init__(self,state_dim,data_length=360,bin_size=18): """ You can give the object param...
38a0c2817673ad70e3b5ff74ca1ea7b43d13916398cd18b01445897db7cd652f
Python
2,317
68
import cedalion.typing as cdt from cedalion.dataclasses.geometry import PointType import matplotlib.pyplot as p def plot_montage3D( amp: cdt.NDTimeSeries, geo3d: cdt.LabeledPoints, landmarks: list[str] | None = None ): """Plots a 3D visualization of a montage. Args: amp: Time series dat...
f3a259e9f770b6153f359bac4ddc1d65a809dc9bd7b34840ceb0004b31987838
Python
2,318
66
import numpy as np import pandas as pd import pyBigWig import errno import os from pathlib import Path from typing import Tuple, Dict def assure_folders(folders): for folder in folders: Path(folder).mkdir(parents=True, exist_ok=True) print(f'Using folders at {[os.path.abspath(f) for f in folders]}') ...
a48f663e5ee003d71d28c1aae93303ab2febebaed24fa9469e9fc071a1b6af74
Python
2,319
72
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Scientific Reports reproducibility runner. Inputs (either option): A) Raw ADNI file: - ADNIMERGE.csv (place beside this folder or in data/raw/) -> enables reconstruction of the n=411 baseline cohort tables (Table 1; Supp Table S2) B) Analysis-ready file: - da...
8d18df31b2bae3c3ec0e272c9f7bc7a4067499ce7a5e034d8c0eeee20a85bf7b
Python
2,320
85
import numpy as np import tifffile as tf # import matplotlib.pyplot as plt import cv2 as cv import geopandas as gpd from utils.contourtools import * from utils.func import * from utils.img2df import img2df as img2df def get_program_parameters(): epilogue = """ create a dataframe of pixel sizes and z levels a...
96098449fe1eb24f9822a294a8680821514752a735f55457865aafedd232d472
Python
2,321
93
import itertools import numpy as np from lmfit import Parameters from dp5.nmr_processing.proton.pearson7 import p7sim, p7plot from dp5.nmr_processing.helper_functions import lorentzian def simulate_regions(params, peak_regions, grouped_peaks, y_data, xppm): sim_regions = np.empty(len(peak_regions), dtype=object...
124ffb03b72d9bf581fb7d8d78f6ce0db4392c3319040982bc380f29b21439c8
Python
2,322
75
import pytest import pandas as pd import pandas._testing as tm @pytest.mark.parametrize( "values, dtype", [ ([], "object"), ([1, 2, 3], "int64"), ([1.0, 2.0, 3.0], "float64"), (["a", "b", "c"], "object"), (["a", "b", "c"], "string"), ([1, 2, 3], "datetime64[ns]...
89155c49f9beedab301cc479935826d09e305546f9cadfc6502cbd466f4d8caa
Python
2,322
72
""" Related Figures: """ import numpy as np import scipy import scipy.io from scipy.fftpack import fft def get_fft(sequence,sf,zeros_fill=None): ''' 频率图绘制 输入为一维numpy数组(时序), 采样频率(sampling frequency), 输出为原信号图和对应的信号频率图 ''' N=sequence.reshape(-1).shape[0] if zeros_fill==None: ...
09a49071de096461c1bee15bf64dc1463b1e17b01d3d31e5ae456c1bf7b10a41
Python
2,323
79
''' Related Figures:2a,4,s1 ''' import scipy import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Circle def zplane(z, p, fig=None, ax=None): if fig==None or ax==None: fig, ax = plt.subplots(figsize=(4, 4),dpi=300) circle = Circle(xy = (0.0, 0.0), radius = 1, alpha = 0.9, f...
16bda4173d09e248529f193c1b972635e2620ceb0afa784c26edfea2773a1f23
Python
2,323
68
import torch from torch import nn from braincog.base.encoder import encoder from braincog.base.node import LIFNode class CNNQnet(nn.Module): def __init__(self, input_dim, output_dim): super(CNNQnet, self).__init__() self.cnn = nn.Sequential( nn.Conv2d(in_channels=input_dim, o...
d1daee586bd83030cd31f3685b86919fae28a609ca4009a74b98c23034079181
Python
2,323
71
""" Binned dendritic events with respect to rhythmic bursts Author: Drew B. Headley """ import numpy as np import pandas as pd from .load_dendevt_csv import load_dendevt_csv from .load_spike_h5 import load_spike_h5 from .seg_dendevt import seg_dendevt from .ser_seg_dendevt import ser_seg_dendevt from .bin_rhym_dendevt...
fee73a8986bda46f013ccce6b795b6293cb72b53d4aaf34353126d2c57ad4ee3
Python
2,323
63
from __future__ import annotations from typing import TYPE_CHECKING from micromanager_gui import MicroManagerGUI from micromanager_gui._menubar._menubar import DOCKWIDGETS, WIDGETS from micromanager_gui._widgets._viewers import MDAViewer if TYPE_CHECKING: from pymmcore_plus import CMMCorePlus from pytestqt.q...
4de2d41335fea7183ec6819e58e3bae2f86638d02cc42a6b77bd2e522cdfff19
Python
2,325
81
from __future__ import annotations from typing import TYPE_CHECKING import numpy as np from matplotlib import pyplot as plt from .utils._checks import check_type from .utils._docs import fill_doc if TYPE_CHECKING: import numpy as np from numpy.typing import NDArray @fill_doc class Viewer: """Viewer of...
1e7b62bde1bc7899b007cfc3de8e5c05746e18a9c2d1cbd6c60f743168758547
Python
2,327
85
# # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. import errno import os import tempfile class Pidfile: """\ Manage a PID file. If a specific name is provided it and '"%s.oldpid" % name' will be used. Otherwise we create a temp file using os.mkst...
591e62060648e92a18d517fc5fc3786bd53c46d3f5e2e167224c0bd7f0eb6db7
Python
2,327
43
#This code contrains portions originating from neka-nat and is licensed under the MIT License. See: https://github.com/neka-nat/distributed_rl #Code, Functions and structures were adopted from the original repository. Modified code is marked with [+]. import argparse import gym import torch import visdom from distri...
9c47b6af31dc66992b354039836b86dde86d0a96da1c5a4372095777146f392c
Python
2,327
77
""" Script to run a short training session of reversal learning task from O'Doherty lab Imports from config.py, initPract.py, runBandit.py Adapted for IBC by: Himanshu Aggarwal himanshu.aggarwal@inria.fr January 2021 """ import os import sys from psychopy import visual, gui, data, core, event, logging, info from psyc...
c517fb1308339e61eeb1c90141c70cbc4c71a1d9c5d700b1cc17ab1c134f34a9
Python
2,328
82
# This code is written for readability rather than efficiency. # # - It is aimed to give a set of logical steps explaining how to run the analysis # in the manner we ran it for this study. # import pandas as pd import numpy as np from scipy.spatial.distance import cdist # Load data df = pd.read_csv("your_file.c...
30a44b145ce04da6ac0eec5e4ae94616c169205ee980eaf9dc6368b850e374c5
Python
2,329
74
"""contains code for the generation of legacy class bins and calculating distances between all records in a given bin""" # TODO: duplicate code with a lot of other edge generation # from python import logging # from dependencies import tqdm # from other modules import big_scape.data as bs_data import big_scape.gen...
90961f24ff7ce32dcc305035b74b5f07d668d1f6d6b81b096abb0379dad5868b
Python
2,330
63
from fenics import * import numpy as np from biotbiot.utils import load_data, load_mesh, meshFunction_to_DG, update_material_params import sys from biotbiot.utils import von_mises_projector import yaml if __name__ == '__main__': sim_name = sys.argv[1] mesh_name = sys.argv[2] with open(f"config_files/{mes...
c890552626b5f0bfdf2db34c3fe2e2ff7671af44f9c44d0f224101c2c1695dda
Python
2,330
98
#!/usr/bin/env python3 import pandas as pd import numpy as np import os.path as osp import re import datetime from scipy.io import mmread import argparse as arp tag = str(datetime.datetime.now()) tag = re.sub('-| |:|\\.','',tag) prs = arp.ArgumentParser() prs.add_argument('-cp','--count_paths', t...
641ee7aea3d91f18c14b80e96db9fd1f4828a61d8de3200f4a7dce1f5e9da05b
Python
2,331
67
import matplotlib.pyplot as plt import os import random import numpy as np import torch def seed_all(seed_val): random.seed(seed_val) os.environ["PYTHONHASHSEED"] = str(seed_val) np.random.default_rng(seed_val) torch.manual_seed(seed_val) if torch.cuda.is_available(): ...
eae9c5b85f52ea11b91432438e2a9b2a0deb2fc22dcc9407c18f6f31d8eee3ed
Python
2,331
75
""" Tests for subclasses of NDArrayBackedExtensionArray """ import numpy as np from pandas import ( CategoricalIndex, date_range, ) from pandas.core.arrays import ( Categorical, DatetimeArray, NumpyExtensionArray, TimedeltaArray, ) class TestEmpty: def test_empty_categorical(self): ...
bb985285dbe35dc69469a676c0f8f7875bc23858593a4ae7b495f046e49781b7
Python
2,334
59
# 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. """ The classification section of the smCOG module. Categorises gene function according to a curated set of HMM profiles. """ from typing import Dict, List from anti...
53b0528e5b149e33fb98d81e1bcd5833300e417c6960df0e957f6270f7ddfc69
Python
2,336
64
import csv from pathlib import Path from typing import Tuple import numpy as np from app.dataflow.qqueue import QQueue from app.process.queue_process import QueueProcess import logging from util.trace import Trace logger = logging.getLogger("grimace_box."+__name__) class GrimaceResultWriter(QueueProcess): @T...
5e69e673904dc9a14595c30784f2335dfd7a1135c57d6f06e2122e957d8bb131
Python
2,336
76
import glob import os import hydra import lightning as L import torch_geometric.loader as geom_loader from lightning.pytorch.callbacks import ModelCheckpoint from models import AMRNodeDualGNN from utils import create_graph_dataset @hydra.main(version_base=None, config_path="../conf", config_name="config") def main(...
d2a7301bc62675c70fdf1a3a1a3ce14c554f0fc7a563529de8bf97a8c2b6cee2
Python
2,336
92
import pandas as pd import pytest from arcos4py.tools import estimate_eps @pytest.fixture def test_data(): data = {'t': [1, 1, 2, 2, 3, 3], 'x': [0, 1, 2, 3, 4, 5], 'y': [1, 2, 3, 4, 5, 6]} return pd.DataFrame(data) def test_estimate_eps(test_data): # Test kneepoint method eps = estimate_eps( ...
6a6b189812601640416caf67d0a8485fd0719d9e7f9b85d4c54fd1beae464a9f
Python
2,337
58
import os import shutil from collections import defaultdict from tqdm import tqdm def organize_and_check_dataset(source_dir): # 获取所有文件 files = os.listdir(source_dir) # 用字典存储每个受试者的模态文件 subject_files = defaultdict(dict) # 解析文件名并按受试者分组 print("正在分析文件...") for file in fil...
922979379d648614227d5f5acfec768a332bdf01ad75d2ab539a006ebd1bd61b
Python
2,339
81
""" Tests that work on both the Python and C engines but do not have a specific classification into the other test modules. """ from io import StringIO import pytest import pandas._testing as tm depr_msg = "The 'verbose' keyword in pd.read_csv is deprecated" def test_verbose_read(all_parsers, capsys): parser =...
ff5a2acfe18ffdf161ae100539692ca0a7ed0cfc8e667e49d1cac1ba6169eb38
Python
2,339
67
import numpy as np import torch from ase.units import Bohr, Hartree, mol, kcal from torch_geometric.data import Data, InMemoryDataset from tqdm import trange from torch_geometric.data import DataLoader class Chignolin(InMemoryDataset): self_energies = { 1: -0.496665677271, 6: -37.8289474402, ...
26dffdf1e4bb0718f4ed942950813d3f78c42918eb7ad8621794c1896c73e01a
Python
2,340
73
from snakemake.script import snakemake import pandas as pd import numpy as np from sklearn.metrics import mean_squared_error, mean_absolute_error ap_templates = pd.read_pickle(snakemake.input.ap_templates) track_of_interest = snakemake.params.track_of_interest # compute similarity between spike templates: # compares...
cda150dc68c36af36552c5117f4689c30cee737aa0994ca872c6ca5d2a5aa438
Python
2,342
82
""" Vectorizing function execution, a lot of functions in YASS need to be executed on different inputs over and over again, to simplify that workflow, some utility functions are provided. Implementation is naive now (for loop) but parallel execution will be implemented soon """ from copy import copy from functools impo...
f90fe8ece926893d729656fcc5f648c9623bf0cc5f87a451ffd705850c2654e4
Python
2,342
66
#!/usr/bin/env python3 """Fast ROCm/RCCL pre-flight health check for distributed CI shards. Some gfx950 runner pods come up with a container that cannot read part of the KFD/HSA topology -- RCCL fails every collective init with "ncclUnhandledCudaError: Call to CUDA function failed / Could not read node #N" (N is a fix...
94a2c30ea652754eece8fc876ebcb091a0899cc2784ca4a9851aa69e8ec171b5
Python
2,344
67
import numpy as np import pytest from pandas.core.dtypes.dtypes import PeriodDtype import pandas as pd import pandas._testing as tm from pandas.core.arrays import period_array @pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"]) def test_astype_int(dtype): # We choose to ignore the s...
1cea96495bbcd0f63ecda72b80c7f33c5d173ea102db804d4b0e8b9afc37d958
Python
2,346
76
""" Tests which scan for certain occurrences in the code, they may not find all of these occurrences but should catch almost all. """ import pytest from pathlib import Path import ast import tokenize import numpy class ParseCall(ast.NodeVisitor): def __init__(self): self.ls = [] def visit_Attribute(s...
8976fe49b7a3e0c05f07ffdc4777fddcb1993e45ee812e93012d27a9dadfcb53
Python
2,346
56
from stimulus_generation import stimulus_generator, multiband_generator data_path = 'Path/to/your/data' # update this to the path where your speech signals are books = ['Polarnacht_female', 'Polarnacht_male', 'Darum_female', 'Darum_male'] # folder names that contain .wav files harms_male = [[6, 15], [8, 18]] # [n1, n2...
ca0e8476035ace56797315893538409f5051092b0b6e21ab395cc3c742446280
Python
2,346
55
from pathlib import Path import numpy as np import torch import argus from src.indexes import IndexesGenerator from src.inputs import get_inputs_processor from src.argus_models import MouseModel from src import constants def get_blend_weights(name: str, size: int): if name == "ones": return np.ones(siz...
80838bcbca2b6ad7f96bc71a230120f81aba6debd31edf2a5b772f7b536878c1
Python
2,348
82
import pandas class FeatureDataset(object): """ Dataset of protein mutations and associated structural- and chemical-features for simple machine learning. Args: dataframe (pandas.DataFrame) protein (str, optional): protein name gene (str, optional): gene name species (str,...
578b53dae336ff5b42b337758ca4b2f18da5f62047360e0c40906716c95ccbb1
Python
2,349
72
""" Challenge Suite Problem 12: variational circuit to MPS overlap optimization. The solution contracts a DMRG-MPS target bra directly with a trainable circuit ket and differentiates the scalar overlap loss with respect to circuit angles. """ import numpy as np import optax import tensorcircuit as tc K = tc.set_bac...
eb19f39984a29bfca680ec30b5f24200191dacaf6180f4890f5351cabd3691d2
Python
2,350
74
import unittest from kernprof import ContextualProfile def f(x): """ A function. """ y = x + 10 return y def g(x): """ A generator. """ y = yield x + 10 yield y + 20 class TestKernprof(unittest.TestCase): def test_enable_disable(self): profile = ContextualProfile() se...
4e61cdb02c71be9f8a0cb0f949a4e6784b96243cd44b9d44834e2e4967adf4f8
Python
2,351
69
import numpy as np import pytest import pandas as pd import pandas._testing as tm @pytest.mark.parametrize( "to_concat_dtypes, result_dtype", [ (["Int64", "Int64"], "Int64"), (["UInt64", "UInt64"], "UInt64"), (["Int8", "Int8"], "Int8"), (["Int8", "Int16"], "Int16"), ([...
629e976f62f462db5b862a6238cdd17012711cbd0e4e601c5022bcee5e5ff3f5
Python
2,351
70
import os import numpy as np import pandas as pd import torch from torch.utils.data import Dataset, DataLoader from sklearn.preprocessing import StandardScaler import warnings warnings.filterwarnings('ignore') class Dataset_PEMS(Dataset): def __init__(self, root_path, flag='train', size=None, scale=True): ...
4fd07f56b75c16a28b1f6eb8265af15f0f8f5c25089a6dd5eade2f501d41673a
Python
2,352
77
"""Frequency-related signal processing methods.""" import numpy as np import scipy.signal import xarray as xr import cedalion.typing as cdt from cedalion import Quantity, units from cedalion.validators import check_dimensionality import cedalion.dataclasses as cdc @cdc.validate_schemas def sampling_rate(timeseries: ...
5f8a75a584f0f9d8fa3ad17ae05d4fcd13a4f9eed541fc09d65b7a94aea14aeb
Python
2,352
53
import logging import torch def init_edge_rot_mat(edge_distance_vec): edge_vec_0 = edge_distance_vec edge_vec_0_distance = torch.sqrt(torch.sum(edge_vec_0**2, dim=1)) # Make sure the atoms are far enough apart # assert torch.min(edge_vec_0_distance) < 0.0001 if torch.min(edge_vec_0_di...
3128e8e54eca2eeaae82712d5110bcce7a65748dfe70b21f5d094884dbd02c8e
Python
2,354
73
import pytest from pandas import ( Interval, Timedelta, Timestamp, ) class TestContains: def test_contains(self): interval = Interval(0, 1) assert 0.5 in interval assert 1 in interval assert 0 not in interval interval_both = Interval(0, 1, "both") asse...
67afa178adf1d395169294ae5680b2ce38dc5b3203d8a137e6a97ed495a56cac
Python
2,357
51
from pathlib import Path from typing import Optional, List import typer from rich.console import Console from .align_tilt_series import align_single_tilt_series from .._cli import cli from .._job_utils import write_global_output from ..._metadata_models.relion.tilt_series_set import RlnTiltSeriesSet from ..._utils.re...
161da3e8e6cf85b29963b3bab3d748be22fe58477170b9299728b32aafcebfa6
Python
2,358
86
import torch from torch_geometric.data import Batch, Data from torch_geometric.loader import DataLoader from graphs import graph2dataset from utils import set_seed def collate_graphs(samples): samples = [s for s in samples if s is not None and hasattr(s, 'y')] if len(samples) == 0: ...
37b793e58181ef2b41507029e1056460536573078f83096930136fe5bfd7044c
Python
2,358
72
# -*- coding: utf-8 -*- """ Created on Thu Apr 17 15:12:02 2025 @author: 24233 """ import numpy as np import scipy.signal as signal from scipy.io import savemat from array import array def ESA(raw_signal): b, a = signal.butter(1, 300, btype='highpass',fs=30000) filted_signal_1 = signal.lfilter(b, a, raw_si...
01d805154c998f0f0ce275ef8750f5ddcc5463c2264b94adf6338b86f57da188
Python
2,359
79
""" helper functions for conversions """ from typing import Any, Tuple, List import numpy as np from .. import gates Tensor = Any def get_ps(qo: Any, n: int) -> Tuple[Tensor, Tensor]: """ Get Pauli string array and weights array for a qubit Hamiltonian as a sum of Pauli strings defined in openfermion ...
88c000ed68a56f5a1f83562ea0b05e831a8f30f0cb359bc3af18916b0514baea
Python
2,359
80
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ utils/initialization """ import contextlib import platform import threading def emojis(str=''): # Return platform-dependent emoji-safe version of string return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str cl...
cda060a5f3cd466c551b776850895b6488b207df7432c5e2c0369bad28fd1e74
Python
2,360
62
""" ISO_C_BINDING maps for f2py2e. Only required declarations/macros/functions will be used. Copyright 1999 -- 2011 Pearu Peterson all rights reserved. Copyright 2011 -- present NumPy Developers. Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPR...
d194de3084c7acb5c62cee4129f6671e16353f70c5090877e78fb1f7dffaa15f
Python
2,360
87
""" A simple script to benchmark the approximation power of the MPS simulator. """ import tensorcircuit as tc tc.set_backend("tensorflow") tc.set_dtype("complex128") def tfi_energy(c, n, j=1.0, h=-1.0): e = 0.0 for i in range(n): e += h * c.expectation((tc.gates.x(), [i])) for i in range(n - 1):...
5c757472a254923aea151e22e962a3a333b16ab83107858d1fbe92a6f29688da
Python
2,362
37
r""" This module is a collection of builder functions used during training and inference for building Python object from configuration files """ import pkg_resources from itertools import product import numpy as np DEFAULT_PRETRAINED_MODELS = ['HCT116_RNA002', 'arabidopsis_RNA002', 'HEK293T_RNA004'] DEFAULT_PRETRAINE...
94799c114cbd891c1e52ece51b56d6f4fb5e53e09db7a17d64b7cc8ac3671e7b
Python
2,365
63
import numpy as np import torch from ase.units import C, _eps0, kJ, mol, nm, pi from torch_scatter import scatter_add from AIMD.protein import Protein class MMNonBondedCalculator: r""" MMNonBondedCalculator is a non-bonded calculator based on MM calculations. """ def __init__(self, device="cpu") -> ...
59de1b42e6d9752cbaf8fcab45036e307b67d959258caf6e3d93d596ed9c9b1d
Python
2,367
91
import sys from typing import TYPE_CHECKING, Optional, Union, Literal from .jupyter import JupyterMixin from .segment import Segment from .style import Style from ._emoji_codes import EMOJI from ._emoji_replace import _emoji_replace if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderResult E...
b06bb95ccfbf54236987225c639542a100a6cb9320b4bebf8439eca9fda3feba
Python
2,367
74
import sys import subprocess import textwrap from importlib import reload import pickle import pytest import numpy.exceptions as ex from numpy.testing import ( assert_raises, assert_warns, assert_, assert_equal, IS_WASM, ) def test_numpy_reloading(): # gh-7844. Also check that relevant globa...
7d37646d969c2baaaeb5293ac2dac55499d95db13cb7c33246e40f239cb9ba12
Python
2,368
58
import pandas as pd import numpy as np import pytest import os import shutil from m6anet.utils.dataprep_utils import parallel_index, parallel_preprocess_tx def test_parallel_index(dataprep_args, tmp_path, eventalign_index): eventalign_filepath = dataprep_args['eventalign'] chunk_size = dataprep_args['chunk_si...
7ff6e06f22ac41cf8129dac84e90db5e172c0385fbf2984962213e17210f8ad1
Python
2,372
77
import ctypes import os import sys from pathlib import Path def get_gomp_thread(): """ Retrieves the maximum number of OpenMP threads after loading the `libgomp.so.1` library and the `libtorch_cpu.so` library. It then queries the maximum number of threads available for OpenMP parallel regions using th...
cf383040621dd8ff115208a64ac9bbb8c0986fad713de9eb3ff37491c654f31e
Python
2,374
80
import pytest import numpy as np from numpy.testing import assert_raises_regex import numpy.lib._utils_impl as _utils_impl from io import StringIO def test_assert_raises_regex_context_manager(): with assert_raises_regex(ValueError, 'no deprecation warning'): raise ValueError('no deprecation warning') ...
b15d1b1296fe668b3d77c0b56c34114fdb835172b83df62bf8c4518064c3238c
Python
2,375
79
import numpy as np from rdkit import Chem import os import sys import tempfile import shutil from torch_geometric.data import Batch, Data, Dataset # , InMemoryDataset from torch.utils.data import DataLoader import logging import warnings import pickle from ase.db import connect import torch from tqdm import tqdm impor...
d4c81712d7ef20ffa1a679edb32e22c2909630a3eced1b670ff2125f518e371c
Python
2,375
80
""" process.run tests, checking that the pipeline finishes without errors for some configurations """ import os import yass from yass import preprocess from yass import detect from yass import cluster def test_cluster_nnet(path_to_config, make_tmp_folder): yass.set_config(path_to_config, make_tmp_folder) (s...
934b9f743a1305814be2512c42c2037175f5a2dcfcaa4df26f41e65e28518c90
Python
2,377
79
""" Script to run IBC implementation of reversal learning task from O'Doherty lab. Imports from config.py, initTask.py, runBandit.py Adapted for IBC by: Himanshu Aggarwal himanshu.aggarwal@inria.fr January 2021 """ import os from psychopy import visual, gui, data, core, event, logging, info from psychopy.constants im...
c34f10325cc79135da83daad98afbb7f205716663db9455c6c128ad3cee96ce9
Python
2,377
69
# Copyright (c) 2023 ETH Zurich. # All rights reserved. # # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # main author: Nils Blach from __future__ import annotations from typing import List from escargot.operations.operations import Operation...
f2c33758c4ee6e2d5c05bd9cfe53e45a937427c74c02aae029160b2e2d5d0952
Python
2,377
79
from __future__ import annotations import logging import sys import typing as t from werkzeug.local import LocalProxy from .globals import request if t.TYPE_CHECKING: # pragma: no cover from .sansio.app import App @LocalProxy def wsgi_errors_stream() -> t.TextIO: """Find the most appropriate error stream...
cf3ed47002069ccdef050ad326cc9bdd52903eb3ee3e17ff3ccf72bff46c01cc
Python
2,379
80
from math import comb import pandas as pd import sys import numpy as np sys.path.append("../") language = None # pd.read_csv("somePath/LANGUAGE_run1_TAB.txt", sep='\t') procedures = language["Procedure[Block]"].to_numpy() responseOnsets = language["ResponsePeriod.OnsetTime"].to_numpy() presentMathStart = language["P...
9dae20aa18463a87ddf210b7c36111289336e53abd3b7b7f7de20546fa782088
Python
2,381
73
# -*- coding: utf-8 -*- """ Wrapper functions for directly calling R functions in Python. This is kept seperate from stats_utils because it requires an R installtion to even load; without it, Python will crash. To install R: download it from https://cran.r-project.org. After installation, make sure R is in you...
4dec75e2205047b5fffd06c64bfb039aeaedff230c5b45c4b80ccce635da81dc
Python
2,382
87
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 17 16:54:12 2019 @author: wanxiang.shen@u.nus.edu @usecase: calculate varies distances """ from molmap.utils.distances import named_distances from molmap.utils.multiproc import MultiProcessUnorderedBarRun import numpy as np from tqdm import tqdm ...
34a1f1a37bddd79b5ea3c9214c303aed66834beeef5a1894e6fd7c6a64cb88b6
Python
2,383
75
"""contains code for the generation of antiSMASH class bins and calculating distances between all records in a given bin""" # TODO: duplicate code with a lot of other edge generation # from python import logging # from dependencies import tqdm # from other modules import big_scape.data as bs_data import big_scape....
c6278c4dbb40439808a75b888f206cd112418af2155b154b73f08a2f2002fce2
Python
2,383
51
def remove_quotes(s): if s and s[0] in ("'", '"') and s[0] == s[-1]: return s[1:-1] return s def process_knowledge_ids(knowledge_ids): knowledge_ids = knowledge_ids[knowledge_ids.find("(")+1:knowledge_ids.find(")")] knowledge_ids = [remove_quotes(elem.strip()) for elem in knowledge_ids.split(",...
c9a774121664a0f51a3aae79f092b82c61c129ca63d949893c29f06c4e682d97
Python
2,383
92
import os import sys thisfile = os.path.abspath(__file__) modulepath = os.path.dirname(os.path.dirname(thisfile)) sys.path.insert(0, modulepath) import numpy as np import tensornetwork as tn from tensorcircuit import simplify def test_infer_shape(): a = tn.Node(np.ones([2, 3, 5])) b = tn.Node(np.ones([3, 5,...
92b4f9c6acf886674392c21f29578608663b8ec88e5da47fb0c51910b550c1d0
Python
2,384
66
from __future__ import annotations from typing import cast from pymmcore_plus import CMMCorePlus, DeviceType from pymmcore_widgets import ShuttersWidget from qtpy.QtCore import Qt from qtpy.QtWidgets import QToolBar, QWidget, QWidgetAction class _ShuttersToolbar(QToolBar): """A QToolBar for the loased Shutters....
ab1a3f8bfb45a7c0558005ad06d12593fe250bb51b77bd83376c7aa2ac2f2d6f
Python
2,384
65
import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid import sys import numpy as np import k3d from matplotlib.colors import LinearSegmentedColormap import yaml if __name__ == "__main__": sim_name = sys.argv[1] mesh_name = sys.argv[2] plot_name = sys.argv[3] if len(sys.argv) ==5...
c21278c6a3deb753df7d539c47a5bfd8d17cc91e0b2c3877a592eb2a4974461e
Python
2,384
75
from ._backend import Backend from numpy.distutils.core import setup, Extension from numpy.distutils.system_info import get_info from numpy.distutils.misc_util import dict_append from numpy.exceptions import VisibleDeprecationWarning import os import sys import shutil import warnings class DistutilsBackend(Backend):...
675896359e9d7727236cbe721ce2520155566b21135e173f477c992276ef7771
Python
2,387
50
# An old version of OpenAI Gym's multi_discrete.py. (Was getting affected by Gym updates) # (https://github.com/openai/gym/blob/1fb81d4e3fb780ccf77fec731287ba07da35eb84/gym/spaces/multi_discrete.py) import numpy as np import gym class MultiDiscrete(gym.Space): """ - The multi-discrete action space consists ...
87f314678e466d990ff2deeeaa4b84da95fe3094fb8ddc3f9b1b97f6ba2e3fbb
Python
2,388
80
import torch.nn as nn from .interaction_block import * from .residual_stack import * """ Basic building block of the neural network which refines atomic features in an iterative way """ class ModularBlock(nn.Module): def __init__( self, order, num_features, num_basis_functions, ...
2aedb42d8596d61af2707f20b2517ca0dc1732ff3c4666890bbc746b918f6d8c
Python
2,389
81
""" Tests for DataFrame cumulative operations See also -------- tests.series.test_cumulative """ import numpy as np import pytest from pandas import ( DataFrame, Series, ) import pandas._testing as tm class TestDataFrameCumulativeOps: # ------------------------------------------------------------------...
24dc8bb085a2a06d2c330f52760c6f0c68038f22c51306fc328644bbf921bd98
Python
2,390
87
from typing import TYPE_CHECKING, Any, List, Optional, Sequence from .base import IMCFileTreeItem, ModelBase if TYPE_CHECKING: from .channel import ChannelModel from .imc_file import IMCFileModel class IMCFileAcquisitionModel(ModelBase, IMCFileTreeItem): imc_file_tree_is_checkable = True def __init...
09c00a0ec02841196b974775731c44c48c9eef0f0c6c238a09909f4703c40cec
Python
2,391
78
# coding: utf-8 from collections import defaultdict import torch from torch.optim import Optimizer class Lookahead(Optimizer): def __init__(self, optimizer, k=5, alpha=0.5): self.optimizer = optimizer self.k = k self.alpha = alpha self.param_groups = self.optimizer.param_groups ...
322a98cc2207bcd6cc1fe2dd4582effb84f410803b8432ade462d1d084532dd2
Python
2,392
75
import logging import os import tempfile import shutil import json from subprocess import check_call, check_output from tarfile import TarFile from dateutil.zoneinfo import METADATA_FN, ZONEFILENAME def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None): """Rebuild the internal timezone info ...
7e6faa36f586b66cacf63fa19d9af803abe46b7b407231b42e6df2c7cdaeb9cc
Python
2,392
80
"""Measure entrainment of dendritic events by rhythmic signal Author: Drew B. Headley """ import numpy as np from .bin_serser import bin_serser from .ppc import ppc2 def ent_rhym_dendevt(seg_df, rhym_ser): """ For each segment's dendritic event time series measure it entrainment with PPC to a rhythmic seri...
136a88f8860ed87209cacfee89a6400846888c435783ddfa4bdd99d4d5bbafce
Python
2,396
81
""" Creates binary time series of dendritic event occurrences Author: Drew B. Headley """ import numpy as np import sys sys.path.append(".") # have to do this for relative imports to work consistently from .ser_ss import ser_ss from .ser_pt import ser_pt def ser_seg_dendevt(seg_df, **kwargs): """ Takes a d...
91baa83d067fada9868376a6ce0a02664eedf5d7d7e4ba15fe3787042429ce18
Python
2,396
64
# 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. """Map Pfam domains to Gene Ontology terms""" from typing import Any, Dict, List, Optional from antismash.common import path from antismash.common.secmet import Record f...
fb9b988435020f9e73bf923767c6951440737428525ad6cf3523f4e67a941220
Python
2,398
71
from pandas import ( TimedeltaIndex, timedelta_range, ) import pandas._testing as tm class TestTimedeltaIndexDelete: def test_delete(self): idx = timedelta_range(start="1 Days", periods=5, freq="D", name="idx") # preserve freq expected_0 = timedelta_range(start="2 Days", periods=4...
088889583719f11ccb3e6055237c5aaa79f2f783eb87ee412cfe8b386aba77bf
Python
2,399
55
import torch from torch import nn from braincog.base.node.node import IFNode from braincog.base.learningrule.STDP import STDP,MutliInputSTDP from braincog.base.connection.CustomLinear import CustomLinear from collections import deque from random import randint class RSNN(nn.Module): def __init__(s...
5972e8ae29ab0be385c7b6d9a24724580919105b1dcd26331a1192a4a3ebc390
Python
2,400
73
import numpy as np import os import parmap import scipy.signal def duplicate_l2(fname_templates, fname_spike_train, neigh_channels, save_dir, n_spikes_big=100, min_ptp=2, units_in=None): # output folder if not os.path.exists(save_dir): os.makedirs(save_dir) templates = np.load(fn...
fb45bf6bfba0269befa53bcaac1b84554df00d43176bf3728ffe1888a28b36c1
Python
2,401
48
#!/usr/bin/env python3 """R0 scaffold — selective access to Zenodo 17726565 (77 GB single archive). Status: SCAFFOLD. R0 has NOT been run; nothing here produces citable output yet. Strategy: the archive is one zip; we read its END-OF-CENTRAL-DIRECTORY via HTTP range requests to enumerate members WITHOUT downloading 77...
8e7a103b79ebc592d0dbc71621e1f2eab015319271e966fe2b08aa7cfcf4c33c
Python
2,402
71
from asv_runner.benchmarks.mark import skip_benchmark_if from xgboost import XGBClassifier from shap import Explanation from shap.datasets import adult, imagenet50 from shap.explainers import PartitionExplainer from shap.maskers import Image try: from tensorflow.keras.applications.resnet50 import ResNet50, prepro...
cf14b8214fb22230c05301463101ba368e88b8529b380d99553b24697b538989
Python
2,402
73
# %% import pandas as pd import numpy as np from utils import index_structure from plot_utils import divergent_green_orange from surfplot import Plot from brainspace.datasets import load_parcellation from neuromaps.datasets import fetch_fslr # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%...
aeb24ef82e476a034a268e78da1df6781e53396543c62ac9bf5bb93d726487f2
Python
2,404
84
import numpy as np import pytest from pandas import ( DataFrame, MultiIndex, Series, concat, ) import pandas._testing as tm @pytest.mark.parametrize( "args, kwargs, increment", [((), {}, 0), ((), {"a": 1}, 1), ((2, 3), {}, 32), ((1,), {"c": 2}, 201)], ) def test_agg_args(args, kwargs, increme...
f57a5eae4edae3205340aa3c7e09378026b64b026bdf4987d896183185a0b966
Python
2,405
96
from copy import ( copy, deepcopy, ) import pytest from pandas import MultiIndex import pandas._testing as tm def assert_multiindex_copied(copy, original): # Levels should be (at least, shallow copied) tm.assert_copy(copy.levels, original.levels) tm.assert_almost_equal(copy.codes, original.codes...
c15c3e120daa6f2b4dec7ec3da791633302e46ac5bf8dfda5589a84f1107463a
Python
2,406
48
#!/usr/bin/env python import os import argparse import warnings from tqdm import tqdm parser = argparse.ArgumentParser(description='Process data from openmx output.') parser.add_argument('--input_dir', type=str, default='/home/lihe/hdd/materials_data/MoS2/md_openmx/configuration/', help='Every folder under input_dir ...
93ae904ccb627461544f37a5239bc9d283e7c12a9468c11088e22d09e2d28098
Python
2,408
81
import scipy import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import scanpy as sc import decoupler as dc import statsmodels.api as sm from statsmodels.stats.multitest import multipletests from patsy import dmatrices cell_type = snakemake.params.cell_type sample_key = snakema...
db3012520c41ee5f2db46d9f2a30a9223b6dfd343b8f8349d8bf7117373250f5
Python
2,408
79
import numpy as np from pandas.core.dtypes.cast import can_hold_element def test_can_hold_element_range(any_int_numpy_dtype): # GH#44261 dtype = np.dtype(any_int_numpy_dtype) arr = np.array([], dtype=dtype) rng = range(2, 127) assert can_hold_element(arr, rng) # negatives -> can't be held b...
c452a341406c5ebb29888b833d71d4cba0492ec5131c1c4c7055f9ea6d607eaf
Python
2,412
55
# Tests for FreeSASA class in ExternalCode.py import pandas import numpy import pytest import sbmlcore def test_freesasa_rnap(): # b = {'segid': ['A', 'A', 'A'], 'mutation': ['M1D','R2K', 'A3V']} b = {'segid': ['A', 'A', 'A', 'B', 'C', 'C'], 'mutation': ['I3D','S4K', 'Q5V', 'R6D', 'S450F', 'D435F']} df = pa...
cc1f9242f272764b3bb50d32230acfe860f77d035249a3e2abbcf0e321794f8d
Python
2,412
68
import contextlib import os import re import ssl import typing # candidates based on https://github.com/tiran/certifi-system-store by Christian Heimes _CA_FILE_CANDIDATES = [ # Alpine, Arch, Fedora 34-42, OpenWRT, RHEL 9-10, BSD "/etc/ssl/cert.pem", # Fedora 43+, RHEL 11+ "/etc/pki/ca-trust/extracted/p...
efda860fc7b5f12adeda91225dffe4d5978b22effca5eae1506332a7cc911672
Python
2,414
78
import os, sys, re import argparse from torch import nn, tensor from .utils_ML import LayerNorm from model.XMolNet import XMolNet def FindModel(directory): # Regular expression to match model files model_pattern = re.compile(r'model_(\d+)\.chk') # List files in the directory and filter those that matc...
e2fb69218a80659adb2988b77e73fb97f667e3662705b3f097cf9e35f64e1c7a
Python
2,415
66
import pytest from numpy import array from . import util @pytest.mark.slow class TestReturnComplex(util.F2PyTest): def check_function(self, t, tname): if tname in ["t0", "t8", "s0", "s8"]: err = 1e-5 else: err = 0.0 assert abs(t(234j) - 234.0j) <= err asser...
ec5527db2323cf92eba243c70d4fabc21fc0543407d12472ced5917fa981d77d
Python
2,415
64
# 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. """ The general clusterblast, comparing clusters to other antismash-predicted clusters. """ import os from typing import Dict from antismash.config import ConfigType...
7ded0a8cb0caad9415216964a879f996a05f0cd0a69680fcdf22a95f96c4c384
Python
2,416
80
# -*- coding: utf-8 -*- """ Created on Tue Jul 19 10:44:19 2022 @author: lindseyb """ import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint import pandas as pd from scipy import stats import matplotlib matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 ma...
ab459e5b4973c6290f4d9cc460722a494024c909776763a5d0083e41187f193f
Python
2,416
55
import multiprocessing import jax import jax.numpy as jnp import jax.scipy.stats as stats import blackjax import jax.random as random import pickle from MCMC.HMC_utils import inference_loop, inference_loop_multiple_chains from utils.utils import PyTree def get_MCMC(step_size,num_integration_steps, MCMC = 'HMC'): ...
6e46b5a0e0f6514813e3d625b667adf21e8bed6c1524498771069c83df68dc66
Python
2,419
72
#!/usr/bin/env python # Relatively generic setup.py that should be easily tailorable to # other python modules. It gets most of the parameters from the # packaged module itself, so this file shouldn't have to be changed # much. import os,sys,distutils from distutils.core import setup # patch distutils if it can't c...